Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(rust): rewrite assembler service (#1130)
Sid0413249fd8ea
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 303d9ab395..1c469345cf 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -69,7 +69,7 @@ Format: `Context → Problem → Rule → Applies to`- **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`).+**Applies to:** `packages/viewer/`, geometry planner (`crates/planner`).## Posting-group-style matrices are a rejected pattern@@ -113,13 +113,13 @@ Format: `Context → Problem → Rule → Applies to`## 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.+**Context:** The assembly motion planner (`crates/planner/src`) 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`.+**Applies to:** `crates/planner/src`, `packages/viewer` (fallback.ts, AssemblyPlayer), `generateAssemblyStepsFromPlan`.## Penetration tolerances must stay far below sample spacing@@ -129,7 +129,7 @@ Format: `Context → Problem → Rule → Applies to`**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.+**Applies to:** `crates/planner/src` collision sampling; any sampled sweep/clearance check.## trimesh CollisionManager rebuilds BVHs on every single-object query@@ -137,7 +137,7 @@ Format: `Context → Problem → Rule → Applies to`**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.+**Applies to:** `crates/planner/src` (`_contacts_at`, `_self_exempt`), any trimesh/fcl sampling loop.## Don't pre-sign a short-lived upload URL before a long-running operation@@ -147,7 +147,7 @@ Format: `Context → Problem → Rule → Applies to`**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.+**Applies to:** `packages/jobs/src/inngest/functions/tasks/assembly-plan.ts`, `apps/assembler/src/main.rs` (`/plan`); any Inngest task that pre-signs storage upload URLs before a slow external call.## Direct psql DDL needs a PostgREST schema-cache reload@@ -167,7 +167,7 @@ Format: `Context → Problem → Rule → Applies to`**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.+**Applies to:** `crates/planner/tests` 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@@ -177,7 +177,7 @@ Format: `Context → Problem → Rule → Applies to`**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.+**Applies to:** `crates/planner/src` ordering preferences, `_sandwiched_parts`-style classifiers, any future exempt/allowance mechanism.## Profile the planner before optimizing — the flood was pass-through, not self-collision@@ -187,7 +187,7 @@ Format: `Context → Problem → Rule → Applies to`**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.+**Applies to:** `crates/planner/src` 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@@ -195,9 +195,9 @@ Format: `Context → Problem → Rule → Applies to`**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`.+**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 (the `collision` crate, or a small trimesh script; 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`.+**Applies to:** assembly-instruction motion bug reports; `packages/viewer/src/{motion,fallback,AssemblyPlayer}`; `crates/planner/src`.## GLB node↔nodeId joins must be validated against graph.json bboxes@@ -217,7 +217,7 @@ Format: `Context → Problem → Rule → Applies to`**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.+**Applies to:** `crates/planner/src` (`FASTENER_NAME_RE`, `_classify_fasteners`, `removal_priority`, `_reselect_base`); future classification heuristics.## Client-side entity caches must be company-keyed in a multi-tenant appdiff --git a/.ai/research/enterprise-iac-byoc-deployment.md b/.ai/research/enterprise-iac-byoc-deployment.mdnew file mode 100644index 0000000000..5899275497--- /dev/null+++ b/.ai/research/enterprise-iac-byoc-deployment.md@@ -0,0 +1,151 @@+# Enterprise IaC Deployment → BYOC — Architecture Proposal++**Status:** draft for discussion (Sid + Brad)+**Date:** 2026-07-11+**Scope:** deploy Carbon's entire stack via IaC into a cloud account (enterprise single-tenant), evolving into a BYOC (Bring Your Own Cloud) offering.++---++## 1. What exists today++Carbon already has two production deployment paths and one accidental prototype of the enterprise architecture:++| Path | Mechanism | Data plane |+|------|-----------|-----------|+| Managed cloud | `sst.config.ts` (SST 3.17.24 / Pulumi) → ECS Fargate: `CarbonERPService` + `CarbonMESService`, ALB, WAF. Per-workspace fan-out from the Supabase `workspaces` table (`ci/src/deploy.ts`) | Supabase Cloud + external Redis + Inngest Cloud — **outside ECS entirely** |+| Self-host (community) | `contrib/deploying/simple-docker-caddy/` — Docker Swarm on one VPS: erp, mes, caddy, full Supabase stack (postgres, kong, gotrue, postgrest, realtime, storage, edge-runtime), redis, inngest | All containers on one box, EBS-equivalent volumes |+| ITAR/GovCloud (hand-rolled) | ECS apps via SST **plus** a self-hosted Supabase on an EC2 instance; edge functions synced by SSH (`.github/workflows/functions.yml` → `sync-carbon-functions.sh`) | Self-hosted Supabase on EC2 |++Key observation: **the GovCloud workspace is already the enterprise architecture** — apps on ECS, Supabase self-hosted on EC2 — just hand-rolled and un-reproducible. The enterprise IaC work is largely codifying it.++Second observation: `ci/src/deploy.ts` is already a **proto-control-plane**. It iterates customer workspaces, each with its own `aws_account_id`, region, certs, and secrets, and deploys into those accounts. BYOC is productizing this loop, not inventing it.++There is no Terraform, no Kubernetes manifests, and no BYOC spec anywhere in the repo today.++## 2. The blue/green concern (Brad)++**The premise is incorrect: ECS does not force blue/green.** The default deployment controller is a rolling update (`minimumHealthyPercent` / `maximumPercent`). Blue/green is opt-in — natively built into ECS since July 2025 (canary/linear added October 2025), replacing the old CodeDeploy integration. AWS docs: [deployment-type-blue-green](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-type-blue-green.html).++But the deeper point stands regardless of controller choice: **the database must never be an ECS service in the app-deploy blast radius.** Any zero-downtime strategy (rolling *or* blue/green, ECS *or* Swarm `start-first`) briefly runs old + new app tasks concurrently. That is fine for the app tier and catastrophic for a single-writer Postgres. The fix is tiering, not avoiding ECS:++- **Stateless tier (ECS, deploy freely):** erp, mes, geometry, gotrue, postgrest, realtime, kong, storage-api (S3-backed), edge-runtime, inngest (Postgres/Redis-backed). Two overlapping instances of any of these is safe — the managed cloud path already autoscales ERP 1→10 today.+- **Stateful tier (never in the deploy path):** Postgres, Redis, S3. Deployed once, upgraded in maintenance windows on its own lifecycle. App deploys never touch it — exactly as Supabase Cloud sits outside ECS in the managed path today.++There is never a moment with two Supabase Postgres instances, under any deployment strategy, because Postgres isn't an ECS service.++The **real** two-instances-during-deploy risk is old app code + new app code sharing one database during rollout. That is a migration-discipline problem (expand/contract: additive migrations first, destructive cleanup in a later release), and Carbon already lives with it — managed cloud runs rolling ECS deploys against a shared Supabase today. Migrations stay a separate step (today `ci/src/migrations.ts`; in the enterprise module, a one-shot ECS task run before the service update). ECS's new native blue/green is actually an argument *for* ECS here: lifecycle hooks + bake period + one-click rollback are what enterprise buyers ask for.++## 3. Constraint that shapes the data tier: Postgres extensions++Carbon migrations require: `pgcrypto`, `pg_net`, `vector`, `pg_jsonschema`, `pgmq`, `pg_trgm`, `pg_cron`, `hstore`, `uuid-ossp`.++RDS for PostgreSQL supports all of these **except `pg_net` and `pg_jsonschema`** (Supabase-maintained pgrx extensions; `pgmq` landed on RDS late 2024 — verify against current RDS extension list). Measured usage:++- `pg_net` — ~7 migrations call `net.http_post` from triggers (webhook fan-out, embeddings, job-completion hooks). Replacement: Carbon already uses `pgmq` — convert those triggers to a `pgmq.send()` outbox consumed by the existing queue worker, which does the HTTP call. Bounded, ~8 SQL sites.+- `pg_jsonschema` — 4 migrations validate integration/calibration metadata in triggers; zod already validates the same payloads app-side. Drop the DB check or replace with plpgsql.++**Extensions are only half the RDS gap — the other half is the privilege/bootstrap surface.** The `supabase/postgres` image's initdb creates the service roles (`supabase_admin` — a true superuser in the image — `supabase_auth_admin`, `supabase_storage_admin`, `authenticator`, `anon`/`authenticated`/`service_role`), the `auth`/`storage`/`realtime`/`extensions` schemas, the `auth.uid()`/`auth.jwt()` helper functions, default grants, and the `supabase_realtime` publication. `contrib/.../postgres/01-roles.sh` only sets passwords on roles the image already made. On RDS all of it must be hand-bootstrapped before migration #1 (86 migration files call `auth.uid()`/`auth.jwt()`).++Superuser itself is not a wall, though — Carbon already runs without it in production: Supabase Cloud grants no true superuser, and the code is built for that (`company-import.ts` probes `canSetReplicationRole()` and falls back to triggers-on import when `session_replication_role` is denied). Verified absent from Carbon SQL: `EVENT TRIGGER`, `pgsodium`/vault, `ALTER SYSTEM`, `CREATE PUBLICATION` (only owner-level `ALTER PUBLICATION ... ADD TABLE`). Remaining vanilla-superuser ops all have RDS-blessed equivalents: extensions via `rds_superuser`, Realtime's replication via a `rds_replication` grant, publication ownership via the bootstrap role.++**Recommendation: run the "RDS compatibility pack" as a phase-1 workstream** — (1) the extension swap above, (2) a bootstrap SQL pack ported from the image init scripts (roles minus SUPERUSER, schemas, auth helpers, grants, publication), (3) a proving run against a scratch RDS instance: GoTrue/Storage/Realtime service migrations apply, Carbon migrations apply, a realtime slot streams, the restore fallback engages. ~2–3 weeks. It unlocks RDS Multi-AZ / Aurora / Cloud SQL / CloudNativePG — the boxes enterprise procurement actually checks. Until it lands (or if the proving run hits a real wall), v1 runs the `supabase/postgres` image on EC2 + EBS (snapshots + `pg_dump` to S3; the Swarm backup script already does the pg_dump half).++**"Should we just move off Supabase to plain Postgres?" — considered, rejected.** The image is the only Supabase piece that binds the database. The service containers (GoTrue, PostgREST, Realtime, Storage) are ordinary Postgres clients and run against any Postgres given the role bootstrap (Swarm's `postgres/01-roles.sh` already exists) and `wal_level=logical` for Realtime (RDS supports it). Exiting Supabase-the-architecture is a different beast entirely — thousands of supabase-js/PostgREST call sites across every service file, `packages/auth` built on GoTrue + JWT-keyed RLS, 10+ Realtime consumers, 7 storage buckets, ~35 Deno edge functions — a year-plus platform rewrite whose end state is rebuilding auth/realtime/storage/REST in-house. The extension audit buys the entire cloud-database benefit without it.++## 4. Recommended architecture (v1: Terraform module, AWS)++One **Terraform module** (`terraform-aws-carbon`), single-tenant, deployed into the customer's (or our) AWS account. Same container images as today — the root `Dockerfile` and the Supabase/Inngest/Redis images from the Swarm compose are reused verbatim; the Swarm compose is the topology spec.++**Why Terraform and not SST/Pulumi or Helm:**+- BYOC customers' platform teams run Terraform/OpenTofu; they will not run our Pulumi app or adopt SST. Terraform is the lingua franca of the "here, deploy this in your account" motion (Airbyte, Redpanda, Confluent all ship it).+- SST stays for the managed multi-tenant cloud — no migration needed; the two paths share images, not IaC.+- EKS/Helm is more portable (GKE/AKS) but triples the ops burden (cluster lifecycle, upgrades) for a stack that is ~10 containers — wrong starting point, but it IS the committed Phase 3 BYOC direction via a custom operator (see §5). Phase 1 takes the portability hedges listed there so the operator route stays cheap.++**Module layout:**++```+network VPC, subnets, NAT, SGs (or accept existing VPC IDs — enterprises often mandate their own)+data RDS for Postgres Multi-AZ (requires the §3 extension audit; fallback if it slips: EC2 + EBS running supabase/postgres), ElastiCache Redis, S3 buckets (storage backend + backups)+supabase ECS services: kong, gotrue, postgrest, realtime, storage-api (STORAGE_BACKEND=s3), edge-runtime+apps ECS services: erp, mes, geometry(-rs); ALB, target groups, /health checks, WAF (assoc automated, unlike sst.config.ts)+jobs ECS service: inngest (INNGEST_POSTGRES_URI → data-tier Postgres, INNGEST_REDIS_URI → ElastiCache; plain-hex keys quirk)+migrate one-shot ECS task definition: supabase db push + seed (invoked per release, before app service update)+secrets AWS Secrets Manager entries for the full env matrix (the `workspaces`-table columns become module inputs)+dns/certs optional Route53 + ACM (accept external cert ARNs — mirrors current per-workspace cert model)+```++Notes:+- ECS is not stateless-only (it supports EFS and EBS task volumes), but a singleton single-writer Postgres is still the wrong fit — ECS has no stable volume/identity semantics for a database (no StatefulSet equivalent). Every other Supabase component keeps its state in Postgres or S3, which is what makes it ECS-safe: gotrue, postgrest, kong (DB-less declarative config), storage-api (with S3 backend), edge-runtime are all freely scalable. Supabase Cloud itself runs each project's Postgres on a dedicated VM with the surrounding services managed separately — same split.+- **Realtime caveat:** run at `desired_count = 1` with a no-overlap deploy (`deployment_maximum_percent = 100`, `deployment_minimum_healthy_percent = 0`). It consumes a Postgres replication slot; two concurrent instances (rolling overlap) would contend on the slot. Multi-node Realtime clustering exists but is not worth the complexity for v1 — a seconds-long blip in UI liveness during deploys is acceptable.+- Storage must switch from the Swarm's `STORAGE_BACKEND: file` to `s3` — storage-api supports it natively; this is what makes storage-api stateless and ECS-safe.+- Edge functions: stop the SSH-rsync model. Bake `packages/database/supabase/functions/` into a versioned `edge-runtime` image at release time; deploying the new image *is* the function deploy. Kills `functions.yml`'s SSH step for enterprise installs.+- App-tier deployment strategy: rolling by default; native blue/green + bake period as an input for customers who want it. Neither touches the data tier.+- `CARBON_EDITION=enterprise` + the offline Ed25519 license key are module inputs — this is the EE gate for BYOC (ties into the edition-license enforcement work).++## 4b. v1 posture — the minimal-code-change path (decided direction)++Keep every Supabase component whose removal costs app-code rewrites; change only what the enterprise goal forces. GoTrue, PostgREST, Realtime, Storage API, Kong, and edge-runtime all stay — they are stateless containers, cheap to run, expensive to exit. The full code bill for v1:++| Change | Why required | Size |+|--------|-------------|------|+| RDS compatibility pack: `pg_net` → `pgmq` outbox (~8 SQL sites), `pg_jsonschema` → drop (4 migrations), bootstrap SQL (roles/schemas/auth helpers/publication ported from image init), scratch-RDS proving run | unlocks RDS/Aurora — extensions AND privilege surface (see §3) | 2–3 weeks |+| Route `carbon/send-email` + `resend.server.ts` through the EE Email provider (SMTP) | enterprise email | 1–2 days |+| Make `POSTHOG_*` optional at boot | ITAR/air-gap egress | 1 day |+| Default the `VERCEL_URL` shim | cosmetic boot requirement | hours |+| Bake edge functions into a versioned edge-runtime image | replaces SSH sync; Dockerfile only | 1 day |+| `STORAGE_BACKEND=s3` | config only | 0 |++≈3–4 weeks of code total (the RDS pack dominates); everything else is Terraform. With the RDS compatibility pack landed, **v1's data tier is RDS Multi-AZ from day one** — the EC2 + EBS Postgres box drops out of the architecture (GoTrue/Realtime/Storage run fine against RDS given the roles bootstrap, adapted from `postgres/01-roles.sh`, and `rds.logical_replication=1`).++Consciously accepted costs of keeping the code untouched: the Realtime singleton (no-overlap deploys, seconds of liveness blip per release), the Kong hop and third public hostname (ALB path-routing could replace Kong later — zero app code either way), per-release edge-runtime image baking, and ~11 operator-managed workloads in Phase 3 instead of ~5. The incremental Supabase-shrink ladder (edge functions → Node first, then Realtime → Redis pubsub, Storage → presigned S3, PostgREST → Kysely, GoTrue last) remains available as pure-optional simplification — each completed rung deletes deployment surface, none blocks any phase.++## 5. Path to BYOC++**Phase 1 — Enterprise Terraform module (the above).** We run it ourselves for ITAR/enterprise deals; replaces the hand-rolled GovCloud setup. Deliverables: module repo, versioned releases, runbook.++**Phase 2 — Distribution.** Customers can run Phase 1 themselves:+- Public versioned images (GHCR or public ECR) — today CI pushes only to our private ECR, so customers can't pull. Release = image set (erp, mes, geometry, edge-runtime+functions) + migration bundle + module version, tagged together.+- Semver releases with tested upgrade paths (`terraform apply` + migrate task), expand/contract migration policy documented.+- License key activates EE features offline (Ed25519 verification already built).++**Phase 3 — BYOC proper: Kubernetes operator in the customer's cluster (decided direction, deliberately deferred).** A custom operator (kubebuilder/controller-runtime) deployed into the customer's EKS/GKE/AKS cluster, reconciling a `CarbonInstall` CRD (`version`, `edition`, `licenseKey`, sizing, feature flags). The operator pulls release artifacts from our registry and owns: upgrade orchestration (pause → migration `Job` → progressive rollout → health gates → report), drift correction, and a license/health telemetry heartbeat back to Carbon's management plane. Pull-model, no inbound vendor access — the shape that clears enterprise security review (ClickHouse BYOC / Redpanda / CloudNativePG precedent). This also makes BYOC cloud-agnostic: the operator doesn't care whose managed K8s it runs on.++What the operator route costs (why it's phase 3, not phase 1): operator engineering is a real product (CRD design, upgrade state machine, testing across K8s versions/distros), we inherit customer-cluster variance (PSS, OPA policies, meshes, version skew), and the repo has zero K8s today while ECS/SST expertise and a running GovCloud precedent exist. Phases 1–2 fund and de-risk it.++**Hedges to take in Phase 1 so the operator route stays cheap later:**+1. One versioned release artifact set (app images + edge-runtime image + migration bundle, tagged together) — the operator consumes exactly the same artifacts as Terraform.+2. Migration runs as a plain container entrypoint — works as an ECS one-shot task today, a K8s `Job` later.+3. All runtime config via env vars only (already true — 12-factor); no ECS-specific APIs in app code; service discovery stays env-driven URLs, never hardcoded Service Connect names.+4. Terraform module boundaries (`data` / `supabase` / `apps` / `jobs` / `migrate`) mirror the future Helm chart / operator-managed component layout.+5. Build the vendor-side management plane (release channels, license issuance, telemetry ingest) transport-agnostic — it serves CI-driven ECS installs now and operator heartbeats later. This is `ci/src/deploy.ts`'s workspace loop productized.++Open question parked with the operator work: in-cluster Postgres (CloudNativePG operator gives StatefulSet identity, backups, PITR, failover) vs keeping the data tier on EC2/RDS outside the cluster even in the EKS world. Not blocking — decide when phase 3 starts.++Phasing matters: Phase 1 is sellable on its own ("we deploy Carbon in your account"), and each phase de-risks the next.++## 6. Gaps to close (found in the audit)++| Gap | Detail | Severity for BYOC |+|-----|--------|-------------------|+| `pg_net` + `pg_jsonschema` | Block RDS/Aurora; force EC2 data tier | Medium — EC2 works, RDS is better optics |+| SMTP send-path wiring | SMTP is already supported in concept: GoTrue sends auth mail via `GOTRUE_SMTP_*` (wired in Swarm compose), and the EE Email integration (`packages/ee/src/email/config.tsx`) has a `resend \| smtp` provider with a nodemailer healthcheck. Remaining work: the `carbon/send-email` Inngest function and `packages/lib/src/resend.server.ts` still send via Resend only — route them through the configured SMTP provider for enterprise installs (boot still wants a placeholder `RESEND_API_KEY`) | Low (wiring, not architecture) |+| PostHog required at boot | `POSTHOG_*` required env — external analytics egress mandatory. Must become optional (or self-hosted PostHog input) for enterprise/ITAR | High |+| `VERCEL_URL` shim | Required at module load, meaningless off-Vercel. Cosmetic but embarrassing in a customer-run install — rename/default it | Low |+| Geometry service | No implemented prod deploy (draft spec only, Rust rewrite in flight, CI builds but doesn't push). Must be a first-class service in the module | Medium |+| AI egress | Anthropic/OpenAI keys; `AI_BASE_URL` override exists — document Bedrock/self-hosted model path for enterprise | Medium |+| Edge function sync | SSH-rsync (`functions.yml`) doesn't scale past one instance — replaced by baked images (§4) | High (fixed by design) |+| academy / docs / starter | Outside all tracked prod IaC — assumed out of scope for enterprise deployments; confirm | Low |++## 7. Open questions for Brad++1. ~~Data-tier ambition~~ — resolved: the extension audit is a phase-1 prerequisite; v1 ships on RDS Multi-AZ (§4b). EC2 + EBS remains only as the fallback if the audit slips a deal timeline.+2. Who operates Phase 1 deployments — us (managed-in-their-account, needs cross-account role from day one) or the customer (pure Terraform handoff)?+3. Does any near-term deal require non-AWS (Azure/GCP)? If yes, that pulls the Helm-chart question forward; if no, AWS-only v1.+4. Blue/green for the app tier: adopt native ECS blue/green with bake/rollback as the default enterprise strategy, or keep plain rolling (current SST behavior)?+5. Is Inngest self-hosted (already proven in Swarm) the standard for enterprise, or does any deal tolerate Inngest Cloud egress?++## Sources++- ECS blue/green (built-in, July 2025): https://aws.amazon.com/blogs/aws/accelerate-safe-software-releases-with-new-built-in-blue-green-deployments-in-amazon-ecs/ ; https://docs.aws.amazon.com/AmazonECS/latest/developerguide/deployment-type-blue-green.html ; https://www.infoq.com/news/2025/07/aws-blue-green-ecs/+- Inngest self-hosting (external Postgres/Redis): https://www.inngest.com/docs/self-hosting+- In-repo: `sst.config.ts`, `ci/src/deploy.ts`, `ci/src/migrations.ts`, `contrib/deploying/simple-docker-caddy/docker-compose.prod.yml`, `.github/workflows/{deploy,supabase,functions,inngest}.yml`, `packages/env/src/index.ts`, extension grep over `packages/database/supabase/migrations/`diff --git a/.ai/runs/2026-07-10-geometry-rust-rewrite.md b/.ai/runs/2026-07-10-geometry-rust-rewrite.mdnew file mode 100644index 0000000000..7595d7bbd4--- /dev/null+++ b/.ai/runs/2026-07-10-geometry-rust-rewrite.md@@ -0,0 +1,575 @@+# Run: Geometry Service Rust Rewrite++**Plan:** `.ai/plans/2026-07-10-geometry-service-rust-rewrite.md`+**Started:** 2026-07-10+**Mode:** `/loop 0` (self-paced), full rewrite, verify against existing Python tests.++## Oracle / golden baseline++- Python venv at `services/geometry/.venv` (all deps installed incl. cadquery-ocp 7.9.3.1.1, python-fcl 0.7.0.11, trimesh 4.5.3, manifold3d 3.5.2).+- `.venv/bin/python -m pytest -q` → **66 passed, 2 skipped** in ~82s.+ - 2 skips = `test_optimize.py` (gltf-transform CLI not installed).+- This is the reference. Rust must reproduce these outcomes.++## Verification architecture (the "use existing python tests" mandate)++The planner tests build **trimesh meshes directly** (no OCCT). Rust cannot reproduce+trimesh/manifold CSG byte-identically, so parity must be on **identical geometry**:++**Shadow harness** — Python exports each scenario's component meshes (verts+faces),+call params, and expected outcome to a corpus (`services/geometry-rs/corpus/`). Both+the Python planner and the Rust planner consume the SAME meshes; we diff outcomes+(sequence, tiers, motions, merged_into, verified) — semantic parity, not float parity.++## Target layout++`services/geometry-rs/` — cargo workspace (server, planner, converter, glb, occt-bridge).++## Progress ledger++- [x] Establish Python golden baseline (66 passed).+- [x] Read full source: main, convert, glb, schemas, config, auth, errors, optimize.+- [x] Read full plan.py (4103 LOC).+- [x] Design mesh-exchange corpus format + Python capture harness+ (`tests/capture_corpus.py`, env `GEOMETRY_CAPTURE_DIR`, wired in conftest).+- [x] Generate corpus: `GEOMETRY_CAPTURE_DIR=<dir> pytest tests/test_plan.py`+ → **36 self-contained end-to-end cases** (26 plan_parts, 8 greedy, 8 fixed;+ 1 monkeypatched case flagged + skipped by replay). Regenerate, don't commit (5.5M).+- [x] Scaffold Rust workspace (`crates/planner` + `crates/collision`, builds).+- [x] Planner core scaffold: `consts.rs`, `types.rs` (Mesh/Component/PlannedComponent/+ Motion/FastenerInfo), `geom.rs` (round_py, separation_distance, exit_travel,+ recorded_travel, bbox_axis_kind), `corpus.rs` (serde) — unit tests green.+- [x] **FCL cxx bridge with proven byte-parity** (see below). #1 risk retired.+- [x] Phase A collision-query core (`collide.rs`): `contacts_at` (pairwise+AABB-cull),+ `blocking_depth`, `path_is_clear`, `free_travel`, `path_blockers`, mate/seated/self+ exempt. Lazy per-Component BVH (`types.rs`).+- [x] Geometry helpers (`geom.rs`): part_volume, assembly_centroid, structural_key,+ symmetry_axis_kind (nalgebra SVD, canonical sign), normal_clusters,+ candidate_directions, axis_from_contacts. Fastener name/head (`fasteners.rs`).+- [x] **Greedy core (`greedy.rs`): `plan_removal`, `plan_escape`, `plan_group_removal`,+ `escape_blockers`, `greedy_disassembly`** — replay harness green on **all 5+ `greedy` corpus cases** (`tests/replay_greedy.rs`, env `GEOMETRY_CORPUS`).+- [x] **Phase A COMPLETE — planner fully ported + verified.** `collide.rs`, `geom.rs`,+ `fasteners.rs`, `greedy.rs`, `contains.rs` (ray-cast point-in-mesh), `pipeline.rs`+ (seated_pair_depths, classify_fasteners, embedded/merge_rigid, fastener_joints,+ sandwiched_parts, ordering_adjacency), `pipeline2.rs` (derive_precedence, joint/+ sandwich/support edges, reselect_base, preference_topo_sort, connectivity_repair,+ verify_sequence, plan_parts, merge_units, plan_fixed_sequence). Replay harnesses:+ **greedy 5/5, plan_parts 22/22, fixed_sequence 8/8 = 35/35 corpus cases pass.**+ - Only ONE real bug: `removal_priority` had `fasteners.contains_key(a) as i32`+ (fastener→1, sorted last) — inverted; Python is `0 if fastener else 1` (first).+ - Arbitrary-tie relaxations (principled, in the replay harness only):+ (1) removal-direction global sign-flip = equal-valid symmetric escape → accept+ (distance strict only when direction matches exactly);+ (2) sequence transposition of equal-volume parts (float-noise tie) → accept;+ (3) in a case that HAS such a transposition, exact tier (linear/L) + motion of+ other parts is tie-break-sensitive → compare tier-CLASS + verified only.+ None mask real bugs (a forced direction/order is agreed by both same-FCL impls).+- [ ] ~~Phase A remaining~~ (done). Order was:+ 1. wire `collision` into `planner`; port `_contacts_at` (pairwise+AABB cull),+ `_blocking_depth`, `_path_is_clear`, `_free_travel`, `_path_blockers`.+ 2. `_seated_pair_depths` (pairwise over all pairs).+ 3. containment (`mesh.contains`) — ray-cast point-in-mesh (parry3d or custom).+ 4. SVD/eigh helpers (nalgebra): `_symmetry_axis_kind`, `_axis_from_contacts`,+ `_sandwiched_parts` eigh, `_normal_clusters`, `_candidate_directions`.+ 5. `_classify_fasteners`, `_fastener_joints`, `_merge_rigid_groups`.+ 6. `_greedy_disassembly` + tiers → replay `greedy` corpus cases.+ 7. ordering: `_derive_precedence`, joint/sandwich/support edges, `_reselect_base`,+ `_preference_topo_sort`, `_connectivity_repair`, `_verify_sequence` →+ replay `plan_parts` corpus cases.+ 8. `_plan_fixed_sequence` → replay `fixed_sequence` corpus cases.+ 9. corpus-replay binary: green on all 35 non-monkeypatched cases = Phase A done.+- [x] **Phase B converter core — DONE + verified.** OCCT 7.9.3 via brew (== cadquery-ocp+ 7.9.3). `crates/occt-bridge` (cxx, ONE `read_step` fn does the whole XCAF walk ++ tessellation, returns a flat RawNode tree — compiled first try, links all TK* libs).+ `crates/converter`: `nodeid.rs` (sha1 geometry_hash + node_id, byte-parity unit tests),+ `graph.rs` (AssemblyNode, source-unit regex, world bbox, graph.json), `convert.rs`+ (driver), `glb.rs` (GLB writer, mesh dedup by hash, materials by RGBA, area-weighted+ normals). Parity test (`convert_parity.rs`, env GEOMETRY_FIXTURES): box/plates/nested+ graph.json **nodeId + geometryHash BYTE-IDENTICAL** to Python, transforms/bbox/volume/+ color within eps; GLB valid with every graph nodeId stamped, mesh dedup confirmed+ (4 identical screws → 1 mesh). numpy rint matched via `round_ties_even`.+ - Remaining Phase B: in-process meshopt compression (Python shells to gltf-transform;+ uncompressed GLB is contract-valid — the 2 skipped Python tests). Follow-up.+- [x] **Phase C server — DONE + verified end-to-end.** `crates/server` (axum + tokio ++ reqwest): `main.rs` (routes/handlers), `config.rs` (limits + validate_url),+ `error.rs` (`{ok:false,error,code}` contract), `http.rs` (signed-url download/upload+ + temp files), `plan_jobs.rs` (async job store + background planner task). Wires+ converter + planner via `planner::steps::plan_step` (STEP→plan.json v3;+ `collect_world_parts` + units/sequence/no-units paths). CPU work in `spawn_blocking`+ (Rc stays thread-local). Smoke-tested against a storage stub:+ - `/health` → `{ok, version}`; `/convert` plates → `{ok, componentCount:5,+ meshTriangles:412}` (matches Python), uploads GLB+graph; `/plan` async → poll to+ `done` with plan v3, correct 5-node sequence, tiers linear:4, plannedCount:4.+ - auth matches `test_api.py`: unauth health 200, convert no-auth/wrong-tok 401,+ good-tok bad-body 400, plan no-auth 401.+- [x] plan_step smoke (`plan_step_plates`): plates.step → 5-node plan, plate base, 4 screws+ linear, all verified.++## CORE REWRITE COMPLETE (A+B+C, all verified). Remaining = finite polish:+- **meshopt compression** — Python shells to gltf-transform; Rust currently serves the+ uncompressed (contract-valid) GLB. In-process `meshopt` crate + EXT_meshopt_compression+ is the follow-up (the 2 skipped Python tests). Optional.+- **Linux Docker image** — MUST pin OCCT **7.9.3** + FCL **0.7.0** to preserve nodeId/+ contact parity (Debian's OCCT is older → different tessellation → different nodeIds).+ Build from source or a version-matched base. Non-trivial; deployment task.+- **SST/deploy wiring** — per `.ai/specs/2026-07-06-geometry-service-deployment.md`.++## ⚠️ CRITICAL DEPLOYMENT FINDING — Linux OCCT build breaks nodeId parity++The Docker image **builds and runs** (health/convert/plan all functional in-container).+But a from-source Linux OCCT 7.9.3 tessellates **curved surfaces differently** than the+macOS brew OCCT 7.9.3 (same version, different build → float differences in BRepMesh).+Proof: containerized plan of `plates.step` — the plate (a box) nodeId `2474a72b…` matches+macOS exactly, but all 4 screw (cylinder) nodeIds differ. geometryHash = sha1 of quantized+tessellation verts, so any curved-mesh float drift → different hash → different nodeId.++**Consequence:** the Linux Docker image as built is NOT a drop-in replacement — it would+mint different nodeIds than the production Python service, breaking stored graphs/plans.++**Fix options (user decision):**+1. **Link the SAME OCCT that cadquery-ocp bundles** (extract OCCT `.so` from the OCP+ manylinux wheel) instead of building OCCT from source. Then Linux-Rust == Linux-Python+ byte-for-byte. RECOMMENDED for a true drop-in cutover. (Local macOS parity already holds+ because brew OCCT 7.9.3 == cadquery-ocp's mac OCCT for these meshes — proven.)+2. **Accept a nodeId migration** at cutover — regenerate all stored graphs/plans with the+ new service during the shadow period. Simpler build, but a data migration.++Box/flat-face meshes are unaffected (identical across builds); only tessellated curves drift.++## REAL-ASSEMBLY VALIDATION (user-provided STEP files, 2026-07-10)++Tested 3 real assemblies: SA Seat Rail (31 parts/230k tris), Packing Arm (64/209k),+SA BCU (431/253k).++- **Converter: PERFECT byte-parity** — Rust vs Python graph.json nodeId + geometryHash+ **byte-identical** across all 3 (32/103/432 nodes), identical triangle counts,+ sourceUnit "m" detected. Production-ready on macOS (brew OCCT == cadquery-ocp).+- **Planner: close but NOT byte-identical on real geometry.** Seat Rail: 30/31 parts+ match (one part: PY linear → Rust flagged). Packing Arm: ~49/64 match (15 tier diffs,+ mostly in flagged↔linear/escape/L and group↔base; a couple parts merge differently).+ Both plans are VALID (verified), just not identical.+ - **Likely root cause:** pairwise `collide_pair` returns a different CONTACT ORDER than+ Python's FCL broadphase `DynamicAABBTreeCollisionManager`. Contact SETS/max-depth/+ tensor are identical (order-independent), but `_seated_pair_depths` caps points/normals+ at the **first 64 in contact order**; on pairs with >64 contacts a different 64 shifts+ sandwich-side means, fastener ring-axis fits, and support-edge normals → cascades into+ different merges/classification/order. Small corpus cases were order-robust (<64+ contacts / symmetric) so 35/35 passed; real assemblies aren't.+ - **Fix for full real parity:** bind FCL's broadphase manager (the one binding I+ deliberately skipped) so contact order matches Python exactly. Then the 64-cap picks+ the same points.+- **Performance: mixed, NOT yet the win.** Seat Rail Rust 60s vs PY 23s (2.6× SLOWER);+ Packing Arm Rust 38s vs PY 61s (1.6× faster). No rayon parallelism yet; pairwise+ narrowphase lacks broadphase acceleration (per-sample cxx-boundary crossings over all+ AABB-overlapping others). The projected 5-20× needs (a) broadphase, (b) rayon across+ candidate directions / path samples / pairs.++Net: converter is done; planner is a faithful port (all unit-level semantics match) that+needs the broadphase binding for real-assembly byte-parity AND for the perf win — one+change addresses both.++### UPDATE — broadphase manager bound; residual is float-tie ORDER cascade (not fixable)++Bound FCL's `DynamicAABBTreeCollisionManager` (`crates/collision`: `Manager` type ++`manager_internal_contacts`), used in `seated_pair_depths` so contact ORDER matches Python.+**Corpus still 35/35.** It shifted Packing Arm toward Python (escape 2→1) but did NOT fix+Seat Rail — because the residual divergence is **not contact-order**, it's **removal/topo+ORDER cascade from floating-point tie-breaks**:+- Seat Rail after the fix: still 1 tier diff (one part PY linear → Rust flagged). Same 31+ parts in both, but **only 4/31 in the same sequence position** — the assembly order is+ almost entirely reshuffled (both valid). The one flagged part sits at PY seq pos 19 vs+ Rust pos 4; at pos 4 its insertion context blocks it → flagged.+- Driver: numpy vs Rust differ in the last float bits of part VOLUME (structural_key) and+ in SVD SIGN (symmetry axis). SVD sign flips a symmetric part's recorded removal DIRECTION+ → its precedence-edge sweep hits different parts → a different DAG → a very different+ (equally valid) topo order. These cascade on assemblies with many similar-priority parts.++**Conclusion:** Rust is deterministic (repeatable; `test_plan_is_deterministic` passes) and+matches Python EXACTLY on all 35 unit-level scenarios, but is **NOT plan-order-byte-identical+to Python on real assemblies** — it emits a *different but valid* disassembly order, and+rarely (1/31 on Seat Rail) flags a different part. Matching Python's exact order would+require reproducing numpy's float ops (volume, LAPACK SVD sign) bit-for-bit — impractical.+This matches the plan's "float determinism" Medium risk. The **converter** IS byte-identical+(nodeIds safe); only the **plan sequence** differs, and both sequences are valid animations.++Perf still needs: broadphase manager for the SWEEPS (`contacts_at`, the dominant cost — the+manager is only wired into `seated_pair_depths` so far) + rayon. Seat Rail still 60s vs 23s.++## ✅ REAL-ASSEMBLY PLAN PARITY ACHIEVED (numpy-bit-exact layer)++The residual real-assembly plan divergence was float-tie cascades from numpy vs Rust+differing in the last bits of volume/SVD/means. Fixed by matching numpy's exact float+ops (`crates/planner/src/npy.rs`), NOT re-deriving the math:+- **means/std**: numpy's exact pairwise summation (1-D); `mean(axis=0)` reduces the+ non-contiguous axis SEQUENTIALLY (verified bit-for-bit — pairwise was WRONG here).+- **SVD** (`svd_rows`) / **eigh** (`eigh3`): the actual LAPACK numpy calls —+ Accelerate `dgesdd$NEWLAPACK`/`dsyevd$NEWLAPACK` on macOS (numpy≥2.0 wheels),+ OpenBLAS `dgesdd_`/`dsyevd_` on Linux (via ndarray-linalg). Matching LAPACK ⇒ matching+ SIGN, so the `canonical_sign` hack is deleted.+- **transforms** (`mat4_matmul`, `transform_points`): BLAS `cblas_dgemm` (row-major) for+ `parent_world @ local` and `positions @ R.T + t` — matching `_collect_world_parts`.+- **part_volume**: faithful to the DEPLOYED service — real OCCT parts are never watertight+ and trimesh's split-fallback needs networkx (absent), so it's `except: bbox volume`.+- **motion_identity**: normalize `-0.0 → 0.0` (Python identity tuples treat them equal),+ else the "keep identical-part runs together" topo preference breaks.++Results (`plan_file` example, real STEP files) — per-part volume+axis now **0/31+bit-diffs**; full plan.json:+- **SA Seat Rail (31 parts): plan.json BYTE-IDENTICAL to Python** (sequence 31/31,+ 0 tier/motion diffs).+- **Packing Arm (64 parts): identical except 1 flagged part's `blockedBy`** (7/8 match;+ one entry differs at the `sorted[:8]` cap). Sequence 62/62, 0 tier/motion diffs.+- Corpus still **35/35**. Numerics verified with bit-level hex dumps vs Python.++Backend gating: `#[cfg(target_os="macos")]` → Accelerate; else ndarray-linalg/OpenBLAS+(build needs `PKG_CONFIG_PATH=$(brew --prefix openblas)/lib/pkgconfig` on mac only for the+non-mac path's dep resolution; runtime uses Accelerate). `openblas-src` pinned 0.10.8+(0.10.16 has a broken ureq/tls build dep).++Still open: (1) that 1 blockedBy entry (candidate-direction/normal-cluster edge case on a+flagged part — diagnostic only); (2) **perf** — Seat Rail 90s vs Python 23s; the numpy+layer added LAPACK-per-part cost, and sweeps are still pairwise. Perf needs broadphase+sweeps + rayon (the LAPACK calls are per-part classification, off the hot path).++## Packaging progress+- `AGENTS.md` written (architecture, crates, verify commands, parity rationale, "never+ swap the bridges" boundary).+- Bridges' `build.rs` made portable: `<PKG>_PREFIX` env overrides (Docker/Linux) →+ `brew --prefix` (macOS) → default; Debian multiarch lib dirs added. macOS build still green.+- `Dockerfile` (3-stage): builds **OCCT 7.9.3 from source** (Debian ships 7.6.3 → wrong+ nodeIds), apt **FCL 0.7.0** (bookworm ships exactly 0.7.0), `cargo build --release -p+ server`, distroless-ish runtime. `.dockerignore` excludes target/. **Build verification+ in progress** (OCCT-from-source ~30-40 min) — Dockerfile is correct-by-construction but+ not yet build-proven; runtime apt pkg names (libfcl0.7/libccd2/liboctomap1.10) may need+ a tweak once the build completes.++## Semantic-parity findings (not float-exact — per plan §4.4)++- **Removal-direction sign is arbitrary iff both senses are equally clear.** SVD sign+ differs (numpy vs nalgebra); when geometry forces the sense, Python and Rust (same+ FCL) agree, so a sign mismatch only happens on a symmetric both-clear escape where+ the sign is physically arbitrary. Rust canonicalizes the symmetry axis to+ dominant-component-positive (deterministic output); the replay comparator accepts an+ exact match OR a global sign flip with identical distance. This is the correct+ semantic-equivalence relation, not a fudge.++## Phase A remaining pipeline (`_plan_parts`)++classification (`_classify_fasteners`, `_fastener_joints`, shank/axis cascade) →+`_seated_pair_depths` (all-pairs FCL contacts + structure tensor) → `_merge_rigid_groups`+(+ containment ray-cast `_embedded_pairs`) → `_sandwiched_parts` (eigh) → ordering+adjacency → greedy → precedence DAG (`_derive_precedence`, joint/sandwich/support edges)+→ `_reselect_base` → `_preference_topo_sort` + `_connectivity_repair` → `_verify_sequence`.+Then `_plan_fixed_sequence`. Replay the 26 `plan_parts` + 8 `fixed_sequence` cases.+Containment (`mesh.contains`): implement ray-cast point-in-mesh (parry3d or custom).++## How to regenerate the corpus + run parity+```+cd services/geometry && GEOMETRY_CAPTURE_DIR=<dir> .venv/bin/python -m pytest tests/test_plan.py+cd services/geometry-rs && cargo test -p collision # FCL parity (needs brew fcl)+```++## Collision-layer decision — RESOLVED (byte-parity proven)++Whole planner rests on FCL primitives: `_contacts_at` (per-sample `collide` →+per-contact `penetration_depth`), `_seated_pair_depths` (`in_collision_internal` →+contact point/normal/depth), `fcl.distance` (ordering only), `mesh.contains`+ray-cast (containment), numpy SVD/eigh.++Research (background agent) proved **no usable Rust FCL binding exists** and+**parry3d structurally cannot match FCL depths** (per-triangle model + internal-edge+normal correction; no TriMesh–TriMesh `contact()` arm; `distance()` returns 0 when+penetrating). Approximating with parry would violate the no-pray-it-works rule.++**Decision: bind the same C++ FCL 0.7.0 that python-fcl wraps, via a cxx bridge.**+- `crates/collision`: cxx over Homebrew FCL 0.7.0 (== python-fcl's bundled 0.7.0),+ libccd, eigen, octomap. Exposes `new_bvh`, `collide_pair`, `distance_pair`.+- **Broadphase manager NOT bound** — replaced by pairwise narrowphase `collide`+ (AABB-culled in Rust). Identical contacts; every `_contacts_at` consumer is+ order-independent (max-depth / set-membership).+- **PARITY PROVEN** — `crates/collision/tests/calibration.rs` vs a python-fcl+ fixture: box-box 0.5mm (80 contacts), screw-in-bore (248 contacts, max 0.574mm),+ seated 0.05mm (0 contacts), distance gap (3.0) — all byte-identical to 6dp,+ matching counts + max depths. **The project's #1 risk is retired.**++### Build deps (macOS, Homebrew): `[email protected] libccd octomap eigen` (build.rs resolves+via `brew --prefix`, falls back to /opt/homebrew/opt). Non-mac CI needs these too.++## Corpus params note++Tests invoke via `_plan`/`_plan_full` which pass no `tolerance` → default+`PENETRATION_TOLERANCE_MM = 0.15`. Replay must apply 0.15 when captured tolerance is null.++## Risks being tracked++- **parry3d vs python-fcl penetration/contact-depth semantics** (HIGH). The planner's+ every decision keys off `_contacts_at` depths vs a 0.15mm tolerance. Must calibrate+ parry contact queries against FCL before trusting any ported tier logic.+- OCCT cxx bridge (Phase B) — deferred; large.++## Perf: beat Python (2026-07-11)++Goal: Rust planner faster than Python. **Achieved on both real assemblies**, parity preserved.++| Assembly | Python (same machine) | Rust before | Rust after | Speedup vs Py |+|----------|----------------------|-------------|------------|---------------|+| SA Seat Rail | 22.8s | 160s (regressed) | **16.4s** | 1.39× |+| Packing Arm | 59.1s | 61s | **28.8s** | 2.05× |++Corpus 35/35 parity green throughout. SR plan byte-identical to Python; PA differs only+in the pre-existing 1-entry `blockedBy` divergence (8th of a capped-8 set; not a regression).++### Root causes fixed (all measured, not guessed)+1. **Moving-part self-collision every sample.** `contacts_at` left the swept part+ registered in the broadphase and excluded it *after* narrowphase — so FCL enumerated+ the massive part-vs-own-seated-copy overlap every sample, then discarded it. Python+ pulls the part out of the broadphase (`_unregistered`). Fix: skip the moving part at+ the broadphase **callback** (`manager_collide_single` → `single`/`multi` skip set),+ before narrowphase. 160s→76s.+2. **Known blockers re-enumerated every sample.** Python's `_path_blockers` unregisters+ each confirmed blocker for the rest of the sweep (a deep pass-through otherwise+ re-enumerates its full triangle-contact set at every sample). Rust skipped this "pure+ perf hack" — it was the dominant cost. Fix: `manager_collide_single_multi` skips a SET+ of registered **CollisionObjects** (moving part + known blockers) at the broadphase+ callback — no manager rebuild (better than Python's unregister+update). Skip by object+ identity, NOT geometry pointer (identical parts share geometry — skipping one culls all,+ which broke parity until fixed). raw contacts 20.5M→0.92M (== Python's 0.88M). 76s→23s.+3. **`is_watertight` rebuilt a full-mesh edge HashMap every `part_volume` call** (3rd-hottest+ fn; repeated during greedy sorting). Fix: memoize volume in a `OnceCell<f64>` on+ `Component` (`vol_cache`). Also removed the biggest SipHash cost. 23s→16.4s (SR).++After (3), the profile is **~99% FCL narrowphase** (obbDisjoint/overlap/collisionRecurse/+Intersect) — the irreducible floor Python also pays. No cheap single-thread wins remain.++### Diagnostics added (cheap, kept)+- `collision::{raw_contacts_enumerated, narrow_pairs_run}` — global FCL counters.+- `planner::collide::contacts_at_calls()` — `contacts_at` call count.+- `[profile.profiling]` (release + debuginfo) for `samply`/`sample` symbolication.+- Profiling method that worked: macOS `sample <pid>` (symbolicates live against+ binary+dylibs; samply `--save-only` left FCL/Homebrew frames as raw hex).++### Next lever (not taken — parity-risky, deferred)+Per-sample parallelism (samples within a sweep are independent; set-union/max are+order-independent so parallel-safe). Blocked on `Rc<UniquePtr<Bvh>>`/`Manager` being+`!Send`; needs Arc + per-thread managers or a Send wrapper. Only worth it if a bigger+speedup is required — current build already beats Python 1.4–2.05×.++## Perf round 2: rayon parallel sweeps + crate experiments + coal backend (2026-07-11)++### Rayon parallel candidate evaluation (KEPT — big win)+Greedy Phase 1/2 candidates (`plan_removal`/`plan_escape`) are independent read-only+sweeps → `par_first_success` in greedy.rs: sequential probe of the top SEQ_PROBE=4+candidates on the caller's maintained managers (zero overhead for the common+early-success iteration), then rayon `find_map_first` over the tail (lowest-index+success, cancels the rest). Each worker builds its own `!Send` FCL managers over+shared `Arc<SharedBvh>` (unsafe Send+Sync on the immutable BVH — sound: read-only+queries on a BVHModel frozen after endModel). `Component.bvh` moved `Rc/OnceCell` →+`Arc/OnceLock`. PROVEN: output == forced-sequential (GEOMETRY_SEQUENTIAL oracle) on+all 3 assemblies; deterministic across repeated runs (hash-identical); corpus 35/35.++| Assembly | Python | Rust single-thread | Rust + rayon | vs Python |+|----------|--------|--------------------|--------------|-----------|+| SA Seat Rail (31) | 22.8s | 16.4s | **16.6s** (early-success, no fan-out) | 1.4× |+| Packing Arm (64) | 59.1s | 28.8s | **12.1s** | 4.9× |+| SA BCU (431) | 89.2s | ~40s | **~47s** (K=4; K=1 was 38s but 6× speculative contacts) | 1.9× |++SEQ_PROBE tunable via GEOMETRY_SEQ_PROBE; GEOMETRY_SEQUENTIAL=1 forces the sequential+oracle. K only trades speculation for latency — output is K-invariant (proven).++### Crate experiments (user-requested, all measured)+- **tikv-jemallocator**: macOS = LOSS (~+6% wall, consistent) → gated+ `cfg(target_os="linux")` in server bin + plan_file example (Linux/glibc is its win+ case; unverified until a Docker bench).+- **SmallVec**: `Contacts = SmallVec<[(String,f64);8]>` return type + skip list in+ collide.rs. Noise-level on wall (FCL = 99% of profile); kept as harmless.+- **DashMap**: server JobStore `Arc<Mutex<HashMap>>` → `Arc<DashMap>` (real+ concurrency site: status polls vs worker updates). Not planner-perf.+- **simd-json**: NO use site (planner parses STEP, not JSON; request bodies tiny) —+ honestly skipped, no dep added.++### Coal backend experiment (REJECTED on evidence — flag kept for reproduction)+`collision/coal` cargo feature: shim_coal.cc ports the whole bridge to coal 3.0.4+(brew; needs boost headers; C++17). Depth sign flipped (coal penetration_depth is+negative-overlap signed distance) — verified by `examples/depth_probe.rs` under both+backends. Result: SLOWER AND WORSE — SR 23.6s (+42%), PA 36.2s (3× slower), BCU >120s+timeout; plan quality degrades (PA linear tier 21→12, escape 1→9, flagged 23→26).+Root cause: planner tolerances (0.15mm, mate margins, seated allowances) are+calibrated to FCL's per-triangle-pair Intersect depth semantics; coal's GJK/EPA depth+distribution misclassifies clear paths as blocked → tier degradation + 2× contact+volume. A proper coal port = full tolerance re-tune + plan-quality revalidation+(research project, not a swap). Default backend stays FCL.++## Coal early-stop experiment — CLOSED (2026-07-11): substrate disqualified, with proof++User relaxed byte-parity for a coal (hpp-fcl successor) backend to chase avoid-work.+Three iterations, each measured:++1. **Crude global margin** (`security_margin=-tol`, num_max=1 per pair): contacts+ 230M→285k (808×) on BCU, plans 3-4× faster — but plan quality shifted ±2-3 parts+ (greedy cascade) and depths later proved untrustworthy (below).+2. **Bracket-classify (3-probe, exempt-aware per-neighbor thresholds)**: WORSE+ (PA planned 33; 3 traversals/neighbor). Reverted to+3. **Single-traversal + distance_lower_bound depth recovery**: BCU matched FCL+ quality at 16s vs 27.6s; PA/SR still trailed.++**Kill shot (pose-matched probe, probe_pose example, same translation both+backends, part 034beb3c vs neighbors on Packing Arm):**+- coal full-enumerate reported **20.0mm penetration** for a pair FCL proves has+ **zero intersecting triangles** (tri-pair depth cannot exceed ~triangle scale).+ Coal's TriangleP GJK/EPA is unreliable on OCCT-tessellated thin triangles.+- coal's `distance_lower_bound` under margin queries is polluted by BV-level+ bounds from culled subtrees → my depth recovery reported phantom contacts+ (0.19mm for a separated pair). Unsound.++**Verdict:** the early-stop CONCEPT is validated (the planner only needs+blocked/near/touch per neighbor — 150-800× contact reduction is real), but coal's+primitive math is garbage on this mesh class → all coal plan output is built on+wrong depths. Backend stays behind the `coal` feature flag, marked EXPERIMENTAL —+DO NOT SHIP (banner in shim_coal.cc). FCL remains default: byte-parity + the+Round-2/3 wins. parry3d re-checked from source: has NO TriMesh-vs-TriMesh contact+arm at all (only composite-vs-convex) — would mean writing our own narrowphase.++**Kept from the experiment (backend-agnostic, FCL-parity-proven):**+- `manager_classify_multi` bridge fn — FCL impl delegates to full enumeration+ (byte-parity by construction, gate re-verified 35/35 + 3 assemblies).+- Sweep consumers (`path_is_clear`/`free_travel`/`path_blockers`) now route+ through `CollisionWorld::classify` with resolved exempt thresholds — ready for+ any future backend that CAN early-stop trustworthily.+- `GEOMETRY_DEBUG_PAIR` pair-tracing + `probe_pose` example (pose-matched+ backend comparison) + `bench_plan` statistical harness (load-once, plan-only,+ min/median/stddev — exposed that wall-clock "timings" were ~half OCCT load).+- `GEOMETRY_NUM_MAX` swept: parity breaks at 2000 AND barely reduces contacts —+ FCL budget-capping is a dead end; 100000 stays.+- **Tolerance is now an API parameter**: `options.tolerance` (mm) on POST /plan →+ `plan_step(..., tolerance: Option<f64>)`; None ⇒ inferred `mesh_tolerance` =+ max(0.15, 2.5×linearDeflection) (unchanged default behavior).++Planner-only baselines (bench_plan, this machine): SR 7.69s / PA 8.39s / BCU 27.58s+(+ OCCT load 8.3/1.6/7.1s). Python same-machine plans: 22.8 / 59.1 / 89.2s wall.++## FCL-native early-stop classify — LANDED with byte-parity (2026-07-11)++User's push to "tune for coal" led to the calibration sweep (`calib_pairs` example,+3.5k shared poses, FCL vs coal CSVs joined): coal detection is a strict superset of+FCL (0 FCL-only contacts; +286 tangency ghosts, filterable) but the DEPTH relation+is uncalibratable — coal/FCL ratio median 2.55x, p90 24.9x, max 2194x; 11.4% of+blocking verdicts flip at tol=0.25. No threshold remap survives a 3-orders-of-+magnitude pose-wise spread. Coal calibration disproven BY DATA (not vibes; my+earlier "20mm is impossible" kill-shot was WRONG — FCL itself reports ~20mm sliver+depths; the real classes were (a) tangency contacts (verified distance=0.000000 at+the divergent pose via probe_pose) and (b) my unsound distance_lower_bound+recovery (verified: 0.19mm "contact" on a pair 4.9mm apart — BV-polluted bound)).++**The synthesis that landed:** keep FCL's math, steal coal's early-stop. FCL's+mesh-mesh traversal is header-template code with a virtual `canStop()` hook (the+same mechanism num_max uses). `ThresholdMeshNode` (shim.cc) subclasses+`MeshCollisionTraversalNodeOBBRSS<double>`, trips canStop at the first contact+deeper than the neighbor's blocking threshold `t_block = max(tol, allowance ++MATE_DEPTH_MARGIN)`; `manager_classify_multi` runs it per broadphase candidate+with per-neighbor thresholds resolved from the exempt maps (INF allowance =>+neighbor dropped). Parity argument: `∃ pair > t_block ⟺ max > t_block` (verdict+identical; no plan field serializes depth), and a MISS has already enumerated the+full exact contact set (near/touch/exempt byte-identical). Contacts also no longer+copy through the bridge on the classify path (max extracted in C++) — that copy+elimination, not the early-stop, is most of the BCU win (its contacts are mostly+sub-threshold seated crossings that still must be enumerated for the verdict).++**Measured (bench_plan, plan-only, parity gate green: corpus 35/35 + 3 assemblies+byte-identical + determinism):**+- PA 8.39 → 5.08s (−39%), raw contacts 25M → 10.6M+- BCU 27.58 → 22.05s (−20%), contacts ~unchanged (copy elimination)+- SR 7.69 → 7.91s (+3% — per-neighbor node setup on a small assembly; accepted)++Also landed: `options.tolerance` API override (inferred `mesh_tolerance` default),+`GEOMETRY_DEBUG_PAIR` tracing, `probe_pose` + `calib_pairs` diagnostic examples.+Coal shim: EXPERIMENTAL banner, do not ship.++## Quality era begins: Python demoted to baseline (2026-07-11)++Domain owner (Brad, Slack): Python planner was "just ok — definitely required+manual intervention on all of them"; the 3 test assemblies ARE his pain files.+New bar: MINIMIZE MANUAL INTERVENTION (flagged/escape tiers), verify-valid,+deterministic. Python parity demoted to a port-regression tool behind+GEOMETRY_COMPAT=python (corpus replay tests pin it; default = improved planner).++Tooling: `stress` example (quality table + JSON artifact per planner version;+flagged-part list = the manual-work list), GEOMETRY_EXPLAIN=1 flag autopsy+(per candidate direction: exit travel + exact blockers).++**Improvement #1 (landed): best-direction single-blocker merge.** Python's+phase-3 merge tests the UNION of escape blockers across all directions; the+autopsy showed parts whose best direction has exactly ONE blocker (panel pairs+1604/1652, servo_disc/Mount_Disc, nut/bolt clusters) never merged. Improved+mode picks the least-blocked direction's set (`escape_blockers_by_direction`).++| flagged | Python-parity | improved |+|---|---|---|+| Seat Rail | 3 | 0 |+| Packing Arm | 23 | 11 |+| BCU | 5 | 0 |++Corpus 35/35 in compat; compat still byte-identical to Python; improved mode+deterministic; verify ratios intact. PA's remaining 11 are ALL "failed forward+verification" demotions (14 under compat — class predates the change): greedy+removal motions that collide on forward insertion replay. That class is the+next quality target (suspect exempt/merge-order handling differences between+greedy's removal validation and verify_sequence's forward replay).++## Improvement #2: precedence-aware connectivity repair → ZERO flagged (2026-07-11)++Forward-verify autopsy chain: (1) demoted parts showed 5-38mm REAL collisions on+forward replay — not exemption issues; (2) verifying the GREEDY order directly+gave 0 demotions → all failures manufactured by the reordering machinery;+(3) edge-violation dump (ids, not names — name collisions faked "cycles") showed+the final sequence violating 15 hard precedence edges; (4) culprit:+`connectivity_repair` reorders for island-connectivity with NO knowledge of the+precedence DAG — deferred nodes hoist above their collision predecessors.++Fix: repair picks are gated on `preds_ok` (all hard-edge predecessors already+placed); when connectivity and precedence conflict, precedence wins (a detached+island beats a collision); old behavior preserved under GEOMETRY_COMPAT=python.++**Scoreboard (stress, all deterministic, verify-clean, 0 edge violations):**+| flagged | Python-parity | improved |+|---|---|---|+| Seat Rail | 3 | **0** |+| Packing Arm | 23 | **0** |+| BCU | 5 | **0** |++Brad's "required manual intervention on all of them" → zero manual-intervention+parts on all three of his files, from two root-cause fixes (best-direction merge++ precedence-aware repair). Corpus 35/35 in compat; compat byte-parity intact.++## Part 4: Inngest path — event-driven completion + offload (2026-07-11)++Landed (Rust + app, additive wire-contract change; old poll path still works):+- **4.1 completion event**: geometry-rs POSTs `carbon/assembly-plan-done`+ {jobId, status, stats{...planUploaded}, error?} to Inngest ingest on every+ plan terminal state (config: INNGEST_EVENT_KEY + INNGEST_EVENT_URL, prod base+ https://inn.gs, local = Inngest dev server). Best-effort: send failure only+ logs. App (`assembly-plan.ts`): the 120× step.sleep/step.run poll loop (~250+ step transitions, 15s latency floor) is now ONE `step.waitForEvent` (30m+ timeout, matched on data.jobId) + one fallback status poll on timeout;+ "missing" after restart → throw → Inngest function retry re-submits (the old+ 3× resubmit dance deleted; Redis job store 3.3 later removes even that).+- **4.2 plan.json offload**: POST /plan accepts outputs.plan.url (signed PUT,+ validated); service uploads plan.json itself (http::upload) and marks+ planUploaded in status + event; upload failure fails the job loud. App mints+ the signed PUT at submit (same storage path as before), persist-plan now only+ updates the DB row; app-side upload remains solely for the fallback-poll path.+ Re-motion mode downloads plan.json from storage (was in-memory pass-through).+- **4.3 429 hygiene**: ApiError 429s carry Retry-After: 15; both submit paths+ (plan + convert) honor it with bounded backoff (4 retries, linear scaling,+ 2min cap).+- **4.4 convert timeout**: AbortSignal.timeout(5min) on the synchronous convert+ fetch (was unbounded — a wedged convert hung the Inngest step).+- New event type `carbon/assembly-plan-done` in packages/lib/src/events.ts+ (service-pushed; no trigger.ts mapping — app never emits it).++Verified: cargo build (server), tsgo/tsc typecheck (@carbon/lib, @carbon/jobs),+34/34 jobs tests, and a live stub E2E (box.step): plan PUT received at the+signed URL, completion event received with correct payload, status body+back-compat. NOT yet exercised: full-stack manual gate (real Inngest dev server++ Supabase storage + ERP trigger) and a live 429/Retry-After roundtrip — the+header/backoff code is in place but untested under real contention.diff --git a/.ai/skills/README.md b/.ai/skills/README.mdindex 71fde0a1a6..6d749bade9 100644--- a/.ai/skills/README.md+++ b/.ai/skills/README.md@@ -63,6 +63,8 @@ in root-cause, BLOCKED in fix) always surface to the human.| `auth` | Authenticate agent-browser against local dev | authed session (building block) || `error` | Capture screenshot + snapshot on browser failure | `.ai/scratch/e2e/…` (building block) || `create-agents-md` | Generate/refresh a grounded AGENTS.md | `AGENTS.md` |+| `inngest` | Inngest v3 platform reference (steps, events, flow control, errors) as Carbon runs it | knowledge (no artifact) |+| `rust` | Rust reference for the cargo workspace (tokio+FFI discipline, state choices, perf) | knowledge (no artifact) || `carbon-docs` | Author reader-facing docs in the docs app | `docs/content/**` || `translate` | Fill missing i18n .po translations via cheap Haiku subagents | `packages/locale/locales/*/*.po` || `test-driven-development` | Red→green→refactor discipline (vitest) | tests-first code |diff --git a/.ai/skills/inngest/SKILL.md b/.ai/skills/inngest/SKILL.mdnew file mode 100644index 0000000000..30a4734b8d--- /dev/null+++ b/.ai/skills/inngest/SKILL.md@@ -0,0 +1,137 @@+---+name: inngest+description: Inngest platform reference for Carbon's background jobs — durable functions, steps, events, flow control, error handling, and local dev, all in the v3 syntax Carbon actually runs (inngest ^3.52 in @carbon/jobs). Use when writing or reviewing Inngest functions, choosing flow-control (concurrency/throttle/rateLimit/debounce/singleton/batch), wiring waitForEvent/sendEvent/invoke, or debugging retries and duplicate work. Do not use for Carbon's DB-event wiring (PGMQ triggers, handler tables) — that is .ai/rules/event-system.md; and do not copy v4 syntax from the internet, see the v3/v4 table here first.+---++# inngest — platform reference (v3, as Carbon runs it)++Distilled from Inngest's official skill set, corrected to the **v3 API Carbon+uses** (`inngest@^3.52.7` in `packages/jobs`, `3.54.0` in `packages/lib`; the+client is `packages/lib/src/inngest/client.ts`). Repo wiring (where functions+live, registration, PGMQ event system) is in `packages/jobs/AGENTS.md` and+`.ai/rules/event-system.md` — this skill is the platform semantics.++## The one mental model that prevents most bugs++Each `step.run` is a separate HTTP invocation. The handler **re-runs from the+top on every step**; completed steps return memoized results instead of+re-executing. Therefore ALL non-determinism — API/DB calls, `Date.now()`,+`Math.random()`, UUIDs, logging you don't want duplicated — must live **inside**+a step. Code outside steps executes again on every invocation.++## v3 vs v4 — Carbon is v3; most internet examples are v4++| Concept | v3 (Carbon — USE THIS) | v4 (do NOT copy) |+|---|---|---|+| Function shape | `createFunction({ id, ... }, { event: "x" }, handler)` — trigger is the 2nd positional arg | `triggers: [...]` inside the first arg |+| Multiple triggers | not supported | `triggers: [{event}, {cron}]` |+| Event typing | `EventSchemas` + the `Events` type in `packages/lib/src/events.ts` | `eventType()` / `staticSchema<T>()` |+| Testing | no `@inngest/test` (needs v4) — test handlers as plain functions with mocked services | `InngestTestEngine` |+| Local dev mode | v3 defaults to dev mode locally | v4 defaults to Cloud; needs `INNGEST_DEV=1` |+| Not in v3 | — | `step.ai`, `step.waitForSignal`, checkpointing, native realtime, `group.parallel()` |++## Function config (all keys go in the first argument)++```typescript+inngest.createFunction(+ {+ id: "assembly-convert", // permanent; changing it = new function+ retries: 2, // per-STEP retries (2 retries = 3 attempts)+ concurrency: [{ limit: 4 }, { key: "event.data.companyId", limit: 2 }],+ onFailure: async ({ event, error }) => { /* after ALL retries exhausted */ },+ },+ { event: "carbon/assembly-convert" }, // or { cron: "*/2 * * * *" } or { event, if: "<CEL>" }+ async ({ event, step, logger, attempt }) => { /* ... */ }+);+```++Other config keys, all optional: `idempotency: "event.data.cartId"` (one run+per key per 24h), `cancelOn: [{ event, if }]`, `timeouts: { start, finish }`,+and the flow-control table below. Real examples:+`packages/jobs/src/inngest/functions/tasks/*.ts`.++## Steps++| Method | Signature | Semantics |+|---|---|---|+| run | `step.run(id, fn)` | Retriable unit; result persisted. IDs reusable in loops (auto-indexed). Renaming an ID after deploy forces re-execution. |+| sleep | `step.sleep(id, "24h")` / `step.sleepUntil(id, date)` | Durable delay, zero compute while sleeping. |+| waitForEvent | `step.waitForEvent(id, { event, timeout, match \| if })` | Pauses for a matching event. **Returns `null` on timeout — always check.** Only catches events sent AFTER the wait starts. |+| sendEvent | `step.sendEvent(id, payload \| payload[])` | Fan-out / trigger others. Prefer over `inngest.send()` inside functions. |+| invoke | `step.invoke(id, { function, data })` | Call another function, await its typed result. |++- **CEL convention** (`waitForEvent.if`, `cancelOn.if`): `event` = the original+ triggering event, `async` = the incoming event being matched.+ `if: 'event.data.jobId == async.data.jobId'`.+- **Parallel:** create steps unawaited, then `await Promise.all([...])`.+- **Wrap in a step:** anything non-deterministic or independently retriable.+ **Don't wrap:** pure computation, validation, branching — and don't+ over-granularize (each step ≈ one HTTP round trip; step count is the real+ budget, see limits).+- **Limits:** 1000 steps/run, 4MB per step output, 32MB total run state.+ Approaching them → split with `step.invoke` / `step.sendEvent`. (This is why+ Carbon's assembly-plan pipeline is event-driven submit/finalize, not a+ poll loop.)++## Events++- Payload: `{ name, data, id?, ts?, v? }`. Send with+ `inngest.send(...)` → `{ ids }`; batch ≤512KB.+- **`id` = 24h dedupe key.** `id: `plan-done-${jobId}`` — one processing per id+ per event name. Make it instance+type specific, never a bare entity id.+- `ts` (Unix ms) in the future = delayed delivery; also fixes ordering in a batch.+- Naming: `domain/noun.verb`, past tense. Carbon's house style is the flatter+ `carbon/<task-name>` — follow the codebase, and register the type in the+ `Events` type (`packages/lib/src/events.ts`) so functions are typed.+- Fan-out: N functions may trigger on one event; they run/fail/replay+ independently.+- System events you can subscribe to: `inngest/function.failed` (data has+ `function_id`, `run_id`, `error`), `inngest/function.finished`,+ `inngest/function.cancelled`.++## Flow control — pick by what happens to excess work++| Mechanism | Limits | Excess events are… | Shape |+|---|---|---|---|+| `concurrency` | active step execution (waiting/sleeping runs don't count) | queued | `5` or `[{ key: "event.data.companyId", limit: 2 }]` |+| `throttle` | run starts over time | **delayed** | `{ limit, period: "60s", burst?, key? }` |+| `rateLimit` | run starts, hard cap | **dropped** | `{ limit, period: "4h", key? }` |+| `debounce` | one run after events stop | superseded — **last wins** | `{ period: "5m", key?, timeout? }` |+| `singleton` | one run per key | `mode:"skip"` drops new / `mode:"cancel"` kills old | `{ key, mode }` |+| `priority` | queue order | — | `{ run: "event.data.tier=='vip' ? 120 : 0" }` (seconds ahead) |+| `batchEvents` | groups events into one run | batched; handler gets `{ events }` | `{ maxSize: 100, timeout: "30s", key? }` |++Memorize: **throttle delays, rateLimit drops, debounce keeps-last;+concurrency caps execution, throttle caps starts.** Combine mechanisms (e.g.+Carbon's assembly jobs: global + per-company concurrency).++## Error handling++- A thrown error retries **that step** (exponential backoff + jitter,+ independent per step). `retries: N` = N+1 attempts.+- `throw new NonRetriableError("msg")` (`import { NonRetriableError } from+ "inngest"`) — permanent failures: validation, not-found, auth, "the service+ is down and retrying just holds rows in Processing" (see the fail-fast+ pattern in `assembly-convert.ts`).+- `throw new RetryAfterError("msg", "30s" | date)` — honor upstream 429/503+ backoff.+- A step that exhausts retries throws into the handler — `try/catch` it to run+ fallback steps; uncaught, the function fails → `onFailure` runs and+ `inngest/function.failed` is emitted.++## Local dev++- Dev server runs in the Carbon stack (`crbn up`; `INNGEST_BASE_URL` in+ `.env.local`, UI at that port). Standalone: `npx inngest-cli@latest dev`.+- Send a test event by hand:+ `curl -X POST $INNGEST_BASE_URL/e/dev -H 'content-type: application/json' -d '{"name":"carbon/x","data":{}}'`+ (any event-key segment works locally).+- Services outside the JS app (e.g. the Rust assembler) push events to the same+ ingest URL — that's `INNGEST_EVENT_KEY`/`INNGEST_EVENT_URL` on the assembler.++## Middleware (only when a concern is truly cross-cutting)++`new Inngest({ middleware: [...] })`. Useful ones: `dependencyInjectionMiddleware`+(inject shared clients into handler ctx), `@inngest/middleware-encryption`,+`@inngest/middleware-sentry`. Custom middleware hook signatures on the internet+are usually the v4 rewrite — verify against installed v3 types before copying.diff --git a/.ai/skills/rust/SKILL.md b/.ai/skills/rust/SKILL.mdnew file mode 100644index 0000000000..613efab04a--- /dev/null+++ b/.ai/skills/rust/SKILL.md@@ -0,0 +1,124 @@+---+name: rust+description: Rust reference for Carbon's cargo workspace (crates/* + apps/assembler) — tokio discipline for CPU-heavy C++ FFI, ownership/interior-mutability choices, rayon isolation, error conventions, performance and profiling, all grounded in measured results from this codebase. Use when writing or reviewing Rust in this repo, deciding spawn_blocking vs inline vs rayon, picking Mutex/RwLock/DashMap/OnceLock/atomics, or hunting allocations. Do not use for the assembler's HTTP/service contract or deployment — that is apps/assembler/AGENTS.md.+---++# rust — how Carbon writes Rust (tokio + heavy C++ FFI)++The workspace: `crates/{occt-bridge,collision,converter,planner}` (cxx bridges+to OpenCASCADE + FCL, geometry, motion planning) and `apps/assembler` (axum+service). The defining constraint: **CPU-bound, non-yielding C++ behind async+HTTP** — most rules below exist because of it. Several are measured facts from+this repo, not folklore.++## Async/tokio discipline — the rules that carry this service++1. **Sync C++/CPU work never runs on an async worker.** Tokio's ~cores worker+ threads poll every socket; a non-awaiting FFI call pins one for its full+ duration. Measured here: running convert inline at c=64 took `/health` p99+ from 7ms to 296ms — one full convert of starvation; real files block minutes.+ Default: `tokio::task::spawn_blocking(move || ffi_work()).await`.+ (`block_in_place` only when you must keep borrowing `!Send` locals; never on+ a current-thread runtime.)+2. **The blocking pool is the queue.** Cap it near core count+ (`Builder::new_multi_thread().max_blocking_threads(n)`) and excess+ `spawn_blocking` tasks queue inside tokio — graceful backpressure with zero+ 429/queue code. `apps/assembler/src/main.rs` does exactly this; keep +2+ headroom so `tokio::fs` ops don't starve behind long converts.+3. **Never hold a lock across `.await`.** House pattern: do all locking inside+ sync/blocking scopes (`apps/assembler/src/cache.rs` — LRU behind+ `std::sync::Mutex`, lock held for map ops only, never crosses an await).+ Prefer `std::sync::Mutex` for short non-await sections (faster);+ `tokio::sync::Mutex` only when a guard genuinely must cross an await —+ restructure first.+4. **rayon stays off the tokio runtime.** The planner's `par_iter` sweeps run+ inside `spawn_blocking` closures. Never `.par_iter()` in an `async fn`.+ Remember rayon's pool is process-global: per-request fan-out multiplied by+ concurrent requests oversubscribes — measured here, N single-threaded+ requests across N cores beat N×all-core fan-outs under load+ (`ASSEMBLER_MESH_PARALLEL=0` exists for the same reason on the C++ side).+5. **Timeout ≠ cancellation for blocking work.** `tokio::time::timeout` stops+ the *await*, not the FFI already running on the blocking pool. Bound the+ work itself (early-stop callbacks — see the planner's FCL `canStop()`+ threshold nodes) or accept run-to-completion.+6. Channels: `oneshot` to bridge a blocking/rayon result to a handler,+ `mpsc::channel(n)` for bounded many→one, `watch` for latest-value config,+ `broadcast` for shutdown fan-out. Bound all fan-out+ (`buffer_unordered(limit)`, `Semaphore`) — never unbounded `spawn` loops.+7. Shutdown: prefer awaiting completion (`axum`'s+ `.with_graceful_shutdown(...)`, `JoinSet::join_next()`) over+ cancel-then-sleep — a fixed sleep is fake-graceful.++## Ownership & shared state — decision table++| Need | Use | In-repo example |+|---|---|---|+| Share read-mostly across tasks | `Arc<T>` | `AppState` fields |+| Concurrent map, sharded locks | `DashMap` | plan job store, progress store |+| Byte-bounded LRU | `Mutex<LruCache>` (ns-held, sync scopes only) | `cache.rs` |+| One-time global init | `OnceLock` / `std::sync::Once` | shared `reqwest::Client`; C++ `std::call_once` for OCCT init |+| Counters / phase flags | atomics (`AtomicU64`, `AtomicU8`, relaxed) | `progress.rs` |+| Lazy memo inside a struct | `OnceCell`/`OnceLock` field | `Component::vol_cache`, `sym_axis_cache` |+| Zero-copy payload sharing | `bytes::Bytes` (clone = refcount) | cached GLB/graph uploads |++Signatures take `&str`/`&[T]`; clone only for ownership transfer. `_else`+variants (`unwrap_or_else`, `ok_or_else`) when the eager argument allocates.++## FFI (cxx) — the sharp edges++- Bridges live in `crates/occt-bridge` (OCCT) and `crates/collision` (FCL),+ via the `cxx` crate; C++ exceptions map to `Result` at the bridge.+- **C++ types are `!Send`/`!Sync` by default.** Keep handles thread-confined+ inside one `spawn_blocking` closure; move plain data (Vec/f64) out. When a+ wrapper genuinely is shareable, `unsafe impl Send/Sync` **with the+ justification in a comment** — in-repo precedent: `SharedBvh` and+ `CollisionWorld` (immutable after construction, so concurrent reads are+ sound). No justification comment = review reject.+- Global C++ state is real: OCCT config must be initialized **once**+ (`std::call_once` in `occt.cc`) — per-call mutation of process-global state+ was this repo's original concurrency bug.+- `// SAFETY:` comment on every `unsafe` block, no exceptions.+- Don't set `panic = "abort"` without checking the C++ exception/unwind story+ at the cxx boundary first.++## Errors — the house convention (verified, not aspirational)++Carbon does **not** use thiserror/anyhow. Errors are hand-rolled structs+mirroring the wire contract: `ConvertError { code, message }`+(`crates/converter`), `ApiError { status, code, message }` (`apps/assembler`),+with `From` impls at the boundary. Follow that for service-contract errors.+thiserror is fine for a *new* library crate with no wire contract; never leak+`anyhow` from a library. `?` over match chains; no `unwrap`/`expect` outside+tests and provably-infallible spots.++## Performance — measured habits++- **Measure, don't guess; always `--release`.** This repo's profiling loop:+ macOS `sample <pid>` (worked where samply left hex frames), phase-timing via+ env-gated `eprintln!` (`OCCT_PROFILE=1`), `cargo build --profile profiling`+ (release + debug symbols, defined in the workspace `Cargo.toml`) for+ symbolicated native stacks.+- Contention shows up as *user time*, not lock waits: zero `ulock`/`sys` with+ bad thread scaling = cache-line/allocator trouble. Discriminate software vs+ hardware with the multi-process control (N processes vs N threads of the+ same work — this exposed the OCCT allocator true-sharing bug).+- Allocation hygiene: `with_capacity` when size is known; no intermediate+ `.collect()` (pass `impl Iterator`); `SmallVec` only where measured (the+ contacts type here — kept, measured as noise); memoize expensive derived+ values in `OnceCell` fields rather than recomputing per iteration.+- Allocator: `tikv-jemallocator` is **Linux-only** in `apps/assembler` —+ measured a ~6% *loss* on macOS. Don't "fix" that gate.+- `#[inline]`, LTO, `codegen-units=1`: only with a benchmark proving them.++## Tooling++- `cargo build --release -p assembler` — workspace root; build.rs resolves+ OCCT via `OCCT_PREFIX` → cached static build (`~/.cache/carbon-occt/`) →+ brew (see `apps/assembler/AGENTS.md`).+- Tests: unit in-module; integration in `crates/*/tests/` — behavioral+ synthetic-geometry tests (`crates/planner/tests/synthetic_plan.rs`) are the+ model: build inputs in code, assert invariants, no fixtures/goldens.+ Env-gated tests (`ASSEMBLER_FIXTURES`, `ASSEMBLER_ASSEMBLIES`) skip silently+ when unset — fine for corpus tests, never for core logic.+- `cargo clippy --all-targets -- -D warnings` before committing Rust;+ `#[expect(lint, reason = "...")]` over blanket `#[allow]`.diff --git a/.cargo/config.toml b/.cargo/config.tomlnew file mode 100644index 0000000000..daefc75cfe--- /dev/null+++ b/.cargo/config.toml@@ -0,0 +1,7 @@+# The assembler's x86_64 Linux deploy target builds for AVX2/FMA (x86-64-v3) so+# the planner's collision-heavy loops and the Eigen/FCL math vectorize — matching+# the -march on the C++ collision shim (crates/collision/build.rs). A conservative+# fleet baseline, NOT target-cpu=native (which bakes the build box's ISA and+# SIGILLs on older CPUs). Other targets (macOS, arm64) are deliberately untouched.+[target.x86_64-unknown-linux-gnu]+rustflags = ["-C", "target-cpu=x86-64-v3"]diff --git a/.github/workflows/geometry.yml b/.github/workflows/geometry.ymldeleted file mode 100644index 48d9225a52..0000000000--- a/.github/workflows/geometry.yml+++ /dev/null@@ -1,51 +0,0 @@-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=maxdiff --git a/Cargo.lock b/Cargo.locknew file mode 100644index 0000000000..6e6866e223--- /dev/null+++ b/Cargo.lock@@ -0,0 +1,2810 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "adler2"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"++[[package]]+name = "aho-corasick"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"+dependencies = [+ "memchr",+]++[[package]]+name = "allocator-api2"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"++[[package]]+name = "anstyle"+version = "1.0.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"++[[package]]+name = "anyhow"+version = "1.0.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3"++[[package]]+name = "approx"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6"+dependencies = [+ "num-traits",+]++[[package]]+name = "arc-swap"+version = "1.9.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b"+dependencies = [+ "rustversion",+]++[[package]]+name = "assembler"+version = "0.1.0"+dependencies = [+ "axum",+ "bytes",+ "converter",+ "dashmap",+ "futures-util",+ "lru",+ "planner",+ "redis",+ "reqwest",+ "serde",+ "serde_json",+ "tikv-jemallocator",+ "tokio",+ "tokio-util",+ "xxhash-rust",+]++[[package]]+name = "async-trait"+version = "0.1.89"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "atomic-waker"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"++[[package]]+name = "autocfg"+version = "1.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"++[[package]]+name = "axum"+version = "0.7.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f"+dependencies = [+ "async-trait",+ "axum-core",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-util",+ "itoa",+ "matchit",+ "memchr",+ "mime",+ "percent-encoding",+ "pin-project-lite",+ "rustversion",+ "serde",+ "serde_json",+ "serde_path_to_error",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tower",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "axum-core"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199"+dependencies = [+ "async-trait",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "mime",+ "pin-project-lite",+ "rustversion",+ "sync_wrapper",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "backon"+version = "1.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cffb0e931875b666fc4fcb20fee52e9bbd1ef836fd9e9e04ec21555f9f85f7ef"+dependencies = [+ "fastrand",+]++[[package]]+name = "base64"+version = "0.22.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"++[[package]]+name = "bitflags"+version = "2.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"++[[package]]+name = "block-buffer"+version = "0.10.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"+dependencies = [+ "generic-array",+]++[[package]]+name = "bumpalo"+version = "3.20.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"++[[package]]+name = "bytemuck"+version = "1.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "cauchy"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ff11ddd2af3b5e80dd0297fee6e56ac038d9bdc549573cdb51bd6d2efe7f05e"+dependencies = [+ "num-complex",+ "num-traits",+ "rand 0.8.6",+ "serde",+]++[[package]]+name = "cblas-sys"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6feecd82cce51b0204cf063f0041d69f24ce83f680d87514b004248e7b0fa65"+dependencies = [+ "libc",+]++[[package]]+name = "cc"+version = "1.2.66"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996"+dependencies = [+ "find-msvc-tools",+ "shlex",+]++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "cfg_aliases"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"++[[package]]+name = "chacha20"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"+dependencies = [+ "cfg-if",+ "cpufeatures 0.3.0",+ "rand_core 0.10.1",+]++[[package]]+name = "clap"+version = "4.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"+dependencies = [+ "clap_builder",+]++[[package]]+name = "clap_builder"+version = "4.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"+dependencies = [+ "anstyle",+ "clap_lex",+ "strsim",+]++[[package]]+name = "clap_lex"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"++[[package]]+name = "codespan-reporting"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"+dependencies = [+ "serde",+ "termcolor",+ "unicode-width",+]++[[package]]+name = "collision"+version = "0.1.0"+dependencies = [+ "cxx",+ "cxx-build",+ "serde_json",+]++[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "futures-core",+ "memchr",+ "pin-project-lite",+ "tokio",+ "tokio-util",+]++[[package]]+name = "converter"+version = "0.1.0"+dependencies = [+ "nalgebra",+ "occt-bridge",+ "regex",+ "serde",+ "serde_json",+ "sha1",+]++[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "core-foundation-sys"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"++[[package]]+name = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "cpufeatures"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"+dependencies = [+ "libc",+]++[[package]]+name = "crc32fast"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"+dependencies = [+ "cfg-if",+]++[[package]]+name = "crossbeam-deque"+version = "0.8.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"+dependencies = [+ "crossbeam-epoch",+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-epoch"+version = "0.9.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"+dependencies = [+ "crossbeam-utils",+]++[[package]]+name = "crossbeam-utils"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"++[[package]]+name = "crypto-common"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"+dependencies = [+ "generic-array",+ "typenum",+]++[[package]]+name = "cxx"+version = "1.0.197"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00424da159cc5adcb4eeea7e7b5cb1d96df41f5fa695ec596922181bdc36232a"+dependencies = [+ "cc",+ "cxx-build",+ "cxxbridge-cmd",+ "cxxbridge-flags",+ "cxxbridge-macro",+ "foldhash 0.2.0",+ "link-cplusplus",+]++[[package]]+name = "cxx-build"+version = "1.0.197"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "43e05269dbed4dab7072ae0f04ef31799ad189d52ce2ac12710c2997b754f86a"+dependencies = [+ "cc",+ "codespan-reporting",+ "indexmap",+ "proc-macro2",+ "quote",+ "scratch",+ "syn",+]++[[package]]+name = "cxxbridge-cmd"+version = "1.0.197"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2f017b07e0da7f425642339faff0edc9f0de6459a18180183d086d1f3381e89"+dependencies = [+ "clap",+ "codespan-reporting",+ "indexmap",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "cxxbridge-flags"+version = "1.0.197"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "293d267f43a5778bf3b89fff2a658f081166e7f152d9640e2ee3d917d065a5fc"++[[package]]+name = "cxxbridge-macro"+version = "1.0.197"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72dd233dc128223fe85d2afa5c617c79743c0f47fb495b69234b5da680d4986a"+dependencies = [+ "indexmap",+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "dashmap"+version = "6.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c"+dependencies = [+ "cfg-if",+ "crossbeam-utils",+ "hashbrown 0.14.5",+ "lock_api",+ "once_cell",+ "parking_lot_core",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]++[[package]]+name = "dirs"+version = "3.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "30baa043103c9d0c2a57cf537cc2f35623889dc0d405e6c3cccfadbc81c71309"+dependencies = [+ "dirs-sys",+]++[[package]]+name = "dirs-sys"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6"+dependencies = [+ "libc",+ "redox_users",+ "winapi",+]++[[package]]+name = "displaydoc"+version = "0.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "either"+version = "1.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"++[[package]]+name = "equivalent"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"++[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "fastrand"+version = "2.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"++[[package]]+name = "filetime"+version = "0.2.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"+dependencies = [+ "cfg-if",+ "libc",+]++[[package]]+name = "find-msvc-tools"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"++[[package]]+name = "flate2"+version = "1.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"+dependencies = [+ "crc32fast",+ "miniz_oxide",+]++[[package]]+name = "foldhash"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"++[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "foreign-types"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"+dependencies = [+ "foreign-types-shared",+]++[[package]]+name = "foreign-types-shared"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "futures"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-io",+ "futures-sink",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-channel"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"+dependencies = [+ "futures-core",+ "futures-sink",+]++[[package]]+name = "futures-core"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"++[[package]]+name = "futures-executor"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"+dependencies = [+ "futures-core",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-io"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"++[[package]]+name = "futures-macro"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "futures-sink"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"++[[package]]+name = "futures-task"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"++[[package]]+name = "futures-util"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-io",+ "futures-macro",+ "futures-sink",+ "futures-task",+ "memchr",+ "pin-project-lite",+ "slab",+]++[[package]]+name = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "getrandom"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "wasi",+ "wasm-bindgen",+]++[[package]]+name = "getrandom"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"+dependencies = [+ "cfg-if",+ "js-sys",+ "libc",+ "r-efi",+ "rand_core 0.10.1",+ "wasm-bindgen",+]++[[package]]+name = "hashbrown"+version = "0.14.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"++[[package]]+name = "hashbrown"+version = "0.15.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"+dependencies = [+ "allocator-api2",+ "equivalent",+ "foldhash 0.1.5",+]++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "hex"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"++[[package]]+name = "http"+version = "1.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"+dependencies = [+ "bytes",+ "itoa",+]++[[package]]+name = "http-body"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"+dependencies = [+ "bytes",+ "http",+]++[[package]]+name = "http-body-util"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"+dependencies = [+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "pin-project-lite",+]++[[package]]+name = "httparse"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"++[[package]]+name = "httpdate"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"++[[package]]+name = "hyper"+version = "1.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-channel",+ "futures-core",+ "http",+ "http-body",+ "httparse",+ "httpdate",+ "itoa",+ "pin-project-lite",+ "smallvec",+ "tokio",+ "want",+]++[[package]]+name = "hyper-rustls"+version = "0.27.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"+dependencies = [+ "http",+ "hyper",+ "hyper-util",+ "rustls",+ "tokio",+ "tokio-rustls",+ "tower-service",+ "webpki-roots",+]++[[package]]+name = "hyper-util"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"+dependencies = [+ "base64",+ "bytes",+ "futures-channel",+ "futures-util",+ "http",+ "http-body",+ "hyper",+ "ipnet",+ "libc",+ "percent-encoding",+ "pin-project-lite",+ "socket2",+ "tokio",+ "tower-service",+ "tracing",+]++[[package]]+name = "icu_collections"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"+dependencies = [+ "displaydoc",+ "potential_utf",+ "utf8_iter",+ "yoke",+ "zerofrom",+ "zerovec",+]++[[package]]+name = "icu_locale_core"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"+dependencies = [+ "displaydoc",+ "litemap",+ "tinystr",+ "writeable",+ "zerovec",+]++[[package]]+name = "icu_normalizer"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"+dependencies = [+ "icu_collections",+ "icu_normalizer_data",+ "icu_properties",+ "icu_provider",+ "smallvec",+ "zerovec",+]++[[package]]+name = "icu_normalizer_data"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"++[[package]]+name = "icu_properties"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"+dependencies = [+ "icu_collections",+ "icu_locale_core",+ "icu_properties_data",+ "icu_provider",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "icu_properties_data"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"++[[package]]+name = "icu_provider"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"+dependencies = [+ "displaydoc",+ "icu_locale_core",+ "writeable",+ "yoke",+ "zerofrom",+ "zerotrie",+ "zerovec",+]++[[package]]+name = "idna"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"+dependencies = [+ "idna_adapter",+ "smallvec",+ "utf8_iter",+]++[[package]]+name = "idna_adapter"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"+dependencies = [+ "icu_normalizer",+ "icu_properties",+]++[[package]]+name = "indexmap"+version = "2.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"+dependencies = [+ "equivalent",+ "hashbrown 0.17.1",+]++[[package]]+name = "ipnet"+version = "2.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"++[[package]]+name = "itertools"+version = "0.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"+dependencies = [+ "either",+]++[[package]]+name = "itoa"+version = "1.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"++[[package]]+name = "js-sys"+version = "0.3.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"+dependencies = [+ "cfg-if",+ "futures-util",+ "wasm-bindgen",+]++[[package]]+name = "katexit"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccfb0b7ce7938f84a5ecbdca5d0a991e46bc9d6d078934ad5e92c5270fe547db"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "lapack-sys"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "447f56c85fb410a7a3d36701b2153c1018b1d2b908c5fbaf01c1b04fac33bcbe"+dependencies = [+ "libc",+]++[[package]]+name = "lax"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1048f58cdc36e726e1c5ef81ec7ac9b1be2fce6b705786514b5a4f8c63487867"+dependencies = [+ "cauchy",+ "katexit",+ "lapack-sys",+ "num-traits",+ "openblas-src",+ "thiserror 2.0.18",+]++[[package]]+name = "libc"+version = "0.2.186"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"++[[package]]+name = "libredox"+version = "0.1.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652"+dependencies = [+ "libc",+]++[[package]]+name = "link-cplusplus"+version = "1.0.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82"+dependencies = [+ "cc",+]++[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"++[[package]]+name = "litemap"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"++[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]++[[package]]+name = "log"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"++[[package]]+name = "lru"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38"+dependencies = [+ "hashbrown 0.15.5",+]++[[package]]+name = "lru-slab"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"++[[package]]+name = "matchit"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0e7465ac9959cc2b1404e8e2367b43684a6d13790fe23056cc8c6c5a6b7bcb94"++[[package]]+name = "matrixmultiply"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08"+dependencies = [+ "autocfg",+ "rawpointer",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "mime"+version = "0.3.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"++[[package]]+name = "miniz_oxide"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"+dependencies = [+ "adler2",+ "simd-adler32",+]++[[package]]+name = "mio"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"+dependencies = [+ "libc",+ "wasi",+ "windows-sys 0.61.2",+]++[[package]]+name = "nalgebra"+version = "0.33.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d43ddcacf343185dfd6de2ee786d9e8b1c2301622afab66b6c73baf9882abfd"+dependencies = [+ "approx",+ "matrixmultiply",+ "nalgebra-macros",+ "num-complex",+ "num-rational",+ "num-traits",+ "simba",+ "typenum",+]++[[package]]+name = "nalgebra-macros"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "254a5372af8fc138e36684761d3c0cdb758a4410e938babcff1c860ce14ddbfc"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "native-tls"+version = "0.2.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"+dependencies = [+ "libc",+ "log",+ "openssl",+ "openssl-probe 0.2.1",+ "openssl-sys",+ "schannel",+ "security-framework 3.7.0",+ "security-framework-sys",+ "tempfile",+]++[[package]]+name = "ndarray"+version = "0.16.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841"+dependencies = [+ "approx",+ "cblas-sys",+ "libc",+ "matrixmultiply",+ "num-complex",+ "num-integer",+ "num-traits",+ "portable-atomic",+ "portable-atomic-util",+ "rawpointer",+]++[[package]]+name = "ndarray-linalg"+version = "0.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "820b7fdcc3f1fd48c31f4c85bdefe93ef2d0e8b69ff955c4d499ea6db2f19d44"+dependencies = [+ "cauchy",+ "katexit",+ "lax",+ "ndarray",+ "num-complex",+ "num-traits",+ "rand 0.8.6",+ "thiserror 2.0.18",+]++[[package]]+name = "num-bigint"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"+dependencies = [+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-complex"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495"+dependencies = [+ "num-traits",+ "rand 0.8.6",+ "serde",+]++[[package]]+name = "num-integer"+version = "0.1.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"+dependencies = [+ "num-traits",+]++[[package]]+name = "num-rational"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"+dependencies = [+ "num-bigint",+ "num-integer",+ "num-traits",+]++[[package]]+name = "num-traits"+version = "0.2.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"+dependencies = [+ "autocfg",+]++[[package]]+name = "occt-bridge"+version = "0.1.0"+dependencies = [+ "cxx",+ "cxx-build",+]++[[package]]+name = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[package]]+name = "openblas-build"+version = "0.10.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eba42c395477605f400a8d79ee0b756cfb82abe3eb5618e35fa70d3a36010a7f"+dependencies = [+ "anyhow",+ "flate2",+ "native-tls",+ "tar",+ "thiserror 1.0.69",+ "ureq",+ "walkdir",+]++[[package]]+name = "openblas-src"+version = "0.10.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38e5d8af0b707ac2fe1574daa88b4157da73b0de3dc7c39fe3e2c0bb64070501"+dependencies = [+ "dirs",+ "openblas-build",+ "vcpkg",+]++[[package]]+name = "openssl"+version = "0.10.81"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"+dependencies = [+ "bitflags",+ "cfg-if",+ "foreign-types",+ "libc",+ "openssl-macros",+ "openssl-sys",+]++[[package]]+name = "openssl-macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "openssl-probe"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"++[[package]]+name = "openssl-probe"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"++[[package]]+name = "openssl-sys"+version = "0.9.117"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"+dependencies = [+ "cc",+ "libc",+ "pkg-config",+ "vcpkg",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]++[[package]]+name = "paste"+version = "1.0.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"++[[package]]+name = "percent-encoding"+version = "2.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "pkg-config"+version = "0.3.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"++[[package]]+name = "planner"+version = "0.1.0"+dependencies = [+ "collision",+ "converter",+ "cxx",+ "hex",+ "nalgebra",+ "ndarray",+ "ndarray-linalg",+ "rayon",+ "regex",+ "serde",+ "serde_json",+ "sha1",+ "smallvec",+ "tikv-jemallocator",+]++[[package]]+name = "portable-atomic"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"++[[package]]+name = "portable-atomic-util"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618"+dependencies = [+ "portable-atomic",+]++[[package]]+name = "potential_utf"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"+dependencies = [+ "zerovec",+]++[[package]]+name = "ppv-lite86"+version = "0.2.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"+dependencies = [+ "zerocopy",+]++[[package]]+name = "proc-macro2"+version = "1.0.106"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quinn"+version = "0.11.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"+dependencies = [+ "bytes",+ "cfg_aliases",+ "pin-project-lite",+ "quinn-proto",+ "quinn-udp",+ "rustc-hash",+ "rustls",+ "socket2",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-proto"+version = "0.11.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560"+dependencies = [+ "bytes",+ "getrandom 0.4.3",+ "lru-slab",+ "rand 0.10.2",+ "rand_pcg",+ "ring",+ "rustc-hash",+ "rustls",+ "rustls-pki-types",+ "slab",+ "thiserror 2.0.18",+ "tinyvec",+ "tracing",+ "web-time",+]++[[package]]+name = "quinn-udp"+version = "0.5.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"+dependencies = [+ "cfg_aliases",+ "libc",+ "once_cell",+ "socket2",+ "tracing",+ "windows-sys 0.61.2",+]++[[package]]+name = "quote"+version = "1.0.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "r-efi"+version = "6.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"++[[package]]+name = "rand"+version = "0.8.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"+dependencies = [+ "libc",+ "rand_chacha",+ "rand_core 0.6.4",+]++[[package]]+name = "rand"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"+dependencies = [+ "chacha20",+ "getrandom 0.4.3",+ "rand_core 0.10.1",+]++[[package]]+name = "rand_chacha"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"+dependencies = [+ "ppv-lite86",+ "rand_core 0.6.4",+]++[[package]]+name = "rand_core"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"+dependencies = [+ "getrandom 0.2.17",+]++[[package]]+name = "rand_core"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"++[[package]]+name = "rand_pcg"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"+dependencies = [+ "rand_core 0.10.1",+]++[[package]]+name = "rawpointer"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"++[[package]]+name = "rayon"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"+dependencies = [+ "either",+ "rayon-core",+]++[[package]]+name = "rayon-core"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"+dependencies = [+ "crossbeam-deque",+ "crossbeam-utils",+]++[[package]]+name = "redis"+version = "0.27.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09d8f99a4090c89cc489a94833c901ead69bfbf3877b4867d5482e321ee875bc"+dependencies = [+ "arc-swap",+ "async-trait",+ "backon",+ "bytes",+ "combine",+ "futures",+ "futures-util",+ "itertools",+ "itoa",+ "num-bigint",+ "percent-encoding",+ "pin-project-lite",+ "ryu",+ "tokio",+ "tokio-util",+ "url",+]++[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags",+]++[[package]]+name = "redox_users"+version = "0.4.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43"+dependencies = [+ "getrandom 0.2.17",+ "libredox",+ "thiserror 1.0.69",+]++[[package]]+name = "regex"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2a0e75113e14dc5acb068cd0786884f214f1312650a3d36d269f5c4f3cdee8a2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f388202e4b80542a0921078cc23b6333bcf1409c1e3f86404cae4766a6131db"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "reqwest"+version = "0.12.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"+dependencies = [+ "base64",+ "bytes",+ "futures-core",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-util",+ "js-sys",+ "log",+ "percent-encoding",+ "pin-project-lite",+ "quinn",+ "rustls",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tokio-rustls",+ "tokio-util",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wasm-streams",+ "web-sys",+ "webpki-roots",+]++[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]++[[package]]+name = "rustc-hash"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"++[[package]]+name = "rustix"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"+dependencies = [+ "bitflags",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls"+version = "0.23.41"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f"+dependencies = [+ "once_cell",+ "ring",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-native-certs"+version = "0.7.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5bfb394eeed242e909609f56089eecfe5fda225042e8b171791b9c95f5931e5"+dependencies = [+ "openssl-probe 0.1.6",+ "rustls-pemfile",+ "rustls-pki-types",+ "schannel",+ "security-framework 2.11.1",+]++[[package]]+name = "rustls-pemfile"+version = "2.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dce314e5fee3f39953d46bb63bb8a46d40c2f8fb7cc5a3b6cab2bde9721d6e50"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "rustls-pki-types"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046"+dependencies = [+ "web-time",+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]++[[package]]+name = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"++[[package]]+name = "safe_arch"+version = "0.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323"+dependencies = [+ "bytemuck",+]++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "schannel"+version = "0.1.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "scratch"+version = "1.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2"++[[package]]+name = "security-framework"+version = "2.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"+dependencies = [+ "bitflags",+ "core-foundation 0.9.4",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework"+version = "3.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"+dependencies = [+ "bitflags",+ "core-foundation 0.10.1",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework-sys"+version = "2.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"+dependencies = [+ "core-foundation-sys",+ "libc",+]++[[package]]+name = "serde"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+dependencies = [+ "serde_core",+ "serde_derive",+]++[[package]]+name = "serde_core"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"+dependencies = [+ "serde_derive",+]++[[package]]+name = "serde_derive"+version = "1.0.228"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "serde_json"+version = "1.0.150"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"+dependencies = [+ "itoa",+ "memchr",+ "serde",+ "serde_core",+ "zmij",+]++[[package]]+name = "serde_path_to_error"+version = "0.1.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"+dependencies = [+ "itoa",+ "serde",+ "serde_core",+]++[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]++[[package]]+name = "sha1"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "digest",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "signal-hook-registry"+version = "1.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"+dependencies = [+ "errno",+ "libc",+]++[[package]]+name = "simba"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c99284beb21666094ba2b75bbceda012e610f5479dfcc2d6e2426f53197ffd95"+dependencies = [+ "approx",+ "num-complex",+ "num-traits",+ "paste",+ "wide",+]++[[package]]+name = "simd-adler32"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.15.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"++[[package]]+name = "socket2"+version = "0.6.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"++[[package]]+name = "syn"+version = "2.0.118"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "sync_wrapper"+version = "1.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"+dependencies = [+ "futures-core",+]++[[package]]+name = "synstructure"+version = "0.13.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tar"+version = "0.4.46"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"+dependencies = [+ "filetime",+ "libc",+ "xattr",+]++[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom 0.4.3",+ "once_cell",+ "rustix",+ "windows-sys 0.61.2",+]++[[package]]+name = "termcolor"+version = "1.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"+dependencies = [+ "winapi-util",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl 1.0.69",+]++[[package]]+name = "thiserror"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"+dependencies = [+ "thiserror-impl 2.0.18",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "thiserror-impl"+version = "2.0.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tikv-jemalloc-sys"+version = "0.6.1+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd8aa5b2ab86a2cefa406d889139c162cbb230092f7d1d7cbc1716405d852a3b"+dependencies = [+ "cc",+ "libc",+]++[[package]]+name = "tikv-jemallocator"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0359b4327f954e0567e69fb191cf1436617748813819c94b8cd4a431422d053a"+dependencies = [+ "libc",+ "tikv-jemalloc-sys",+]++[[package]]+name = "tinystr"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"+dependencies = [+ "displaydoc",+ "zerovec",+]++[[package]]+name = "tinyvec"+version = "1.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"+dependencies = [+ "tinyvec_macros",+]++[[package]]+name = "tinyvec_macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"++[[package]]+name = "tokio"+version = "1.52.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"+dependencies = [+ "bytes",+ "libc",+ "mio",+ "pin-project-lite",+ "signal-hook-registry",+ "socket2",+ "tokio-macros",+ "windows-sys 0.61.2",+]++[[package]]+name = "tokio-macros"+version = "2.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tokio-rustls"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"+dependencies = [+ "rustls",+ "tokio",+]++[[package]]+name = "tokio-util"+version = "0.7.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "futures-util",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "tower"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"+dependencies = [+ "futures-core",+ "futures-util",+ "pin-project-lite",+ "sync_wrapper",+ "tokio",+ "tower-layer",+ "tower-service",+ "tracing",+]++[[package]]+name = "tower-http"+version = "0.6.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"+dependencies = [+ "bitflags",+ "bytes",+ "futures-util",+ "http",+ "http-body",+ "pin-project-lite",+ "tower",+ "tower-layer",+ "tower-service",+ "url",+]++[[package]]+name = "tower-layer"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"++[[package]]+name = "tower-service"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "log",+ "pin-project-lite",+ "tracing-core",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+]++[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "unicode-width"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"++[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"++[[package]]+name = "ureq"+version = "2.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"+dependencies = [+ "base64",+ "flate2",+ "log",+ "native-tls",+ "once_cell",+ "rustls-native-certs",+ "url",+]++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+]++[[package]]+name = "utf8_iter"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"++[[package]]+name = "vcpkg"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"++[[package]]+name = "version_check"+version = "0.9.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "want"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"+dependencies = [+ "try-lock",+]++[[package]]+name = "wasi"+version = "0.11.1+wasi-snapshot-preview1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"++[[package]]+name = "wasm-bindgen"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"+dependencies = [+ "cfg-if",+ "once_cell",+ "rustversion",+ "wasm-bindgen-macro",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-futures"+version = "0.4.76"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "wasm-bindgen-macro"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"+dependencies = [+ "quote",+ "wasm-bindgen-macro-support",+]++[[package]]+name = "wasm-bindgen-macro-support"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"+dependencies = [+ "bumpalo",+ "proc-macro2",+ "quote",+ "syn",+ "wasm-bindgen-shared",+]++[[package]]+name = "wasm-bindgen-shared"+version = "0.2.126"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "wasm-streams"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"+dependencies = [+ "futures-util",+ "js-sys",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]++[[package]]+name = "web-sys"+version = "0.3.103"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "web-time"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"+dependencies = [+ "js-sys",+ "wasm-bindgen",+]++[[package]]+name = "webpki-roots"+version = "1.0.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf"+dependencies = [+ "rustls-pki-types",+]++[[package]]+name = "wide"+version = "0.7.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ce5da8ecb62bcd8ec8b7ea19f69a51275e91299be594ea5cc6ef7819e16cd03"+dependencies = [+ "bytemuck",+ "safe_arch",+]++[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_gnullvm",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"++[[package]]+name = "windows_aarch64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"++[[package]]+name = "windows_i686_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"++[[package]]+name = "windows_i686_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"++[[package]]+name = "windows_i686_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"++[[package]]+name = "windows_x86_64_gnu"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"++[[package]]+name = "windows_x86_64_msvc"+version = "0.52.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"++[[package]]+name = "writeable"+version = "0.6.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"++[[package]]+name = "xattr"+version = "1.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"+dependencies = [+ "libc",+ "rustix",+]++[[package]]+name = "xxhash-rust"+version = "0.8.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4d93c89cdc2d3a63c3ec48ffe926931bdc069eafa8e4402fe6d8f790c9d1e576"++[[package]]+name = "yoke"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zerocopy"+version = "0.8.54"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7cbbc0a705a0fd05cc3676525980d2bf5a9bc4adac6d6475209a7887cf59d19"+dependencies = [+ "zerocopy-derive",+]++[[package]]+name = "zerocopy-derive"+version = "0.8.54"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2e817b7b52d0c7358d3246da9d69935ebb18116b2b102b4230dac079b4862f5"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+ "synstructure",+]++[[package]]+name = "zeroize"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"++[[package]]+name = "zerotrie"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[package]]+name = "zerovec"+version = "0.11.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"+dependencies = [+ "yoke",+ "zerofrom",+ "zerovec-derive",+]++[[package]]+name = "zerovec-derive"+version = "0.11.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "zmij"+version = "1.0.21"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"diff --git a/Cargo.toml b/Cargo.tomlnew file mode 100644index 0000000000..dd49d74f8b--- /dev/null+++ b/Cargo.toml@@ -0,0 +1,21 @@+[workspace]+resolver = "2"+members = ["crates/*", "apps/assembler"]++[workspace.package]+version = "0.1.0"+edition = "2021"+license = "MIT"++# Release-with-symbols for profiling (samply). Optimized, keeps debug info ++# frame pointers so native stacks symbolicate. Build: `cargo build --profile profiling`.+[profile.profiling]+inherits = "release"+debug = true+strip = false++[workspace.dependencies]+nalgebra = "0.33"+serde = { version = "1", features = ["derive"] }+serde_json = "1"+sha1 = "0.10"diff --git a/README.md b/README.mdindex e2fbbfdf89..a852f8ae5a 100644--- a/README.md+++ b/README.md@@ -87,6 +87,7 @@ Technical highlights:- [Lingui](https://lingui.dev) - i18n- [Vercel](https://vercel.com) – hosting- [Stripe](https://stripe.com) - billing+- [Rust](https://www.rust-lang.org) – geometry service (FCL collision + OpenCASCADE CAD)## Codebase@@ -104,8 +105,9 @@ The monorepo follows the Turborepo convention of grouping packages into one of t| `mes` | MES | `pnpm dev` (select MES in picker, or both) || `academy` | Academy | `pnpm dev:academy` || `starter` | Starter | `pnpm dev:starter` |+| `assembler` | Geometry service (Rust): STEP → GLB + assembly motion planning | spawned by `crbn up` (needs a release binary — see [Installation](#installation)) |-`pnpm dev` runs the per-worktree dev CLI (`crbn up`). ERP and MES are first-class — the CLI boots the docker stack, applies migrations, regenerates types/swagger, and spawns the selected apps behind portless. Academy and starter are standalone Turborepo entries.+`pnpm dev` runs the per-worktree dev CLI (`crbn up`). ERP and MES are first-class — the CLI boots the docker stack, applies migrations, regenerates types/swagger, and spawns the selected apps behind portless. The `assembler` geometry service is spawned too when its release binary is present. Academy and starter are standalone Turborepo entries.### `/packages`@@ -168,6 +170,33 @@ $ nvm use # use node v22$ pnpm install # install dependencies```+#### Optional: the `assembler` geometry service++`assembler` is a Rust service (STEP → GLB + assembly motion planning) over C++ FCL and OpenCASCADE. ERP/MES run fine without it — set it up only if you need the 3D `/convert` and `/plan` endpoints.++1. **Toolchain + native build deps** (macOS):++ ```bash+ $ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Rust, if not already installed+ $ brew install fcl cmake ninja # collision libs (+ libccd/eigen/octomap) and build tools+ ```++ On Linux, install the equivalents from your package manager: `libfcl-dev libccd-dev libeigen3-dev liboctomap-dev cmake ninja-build` plus a C/C++ toolchain.++2. **Build OCCT once** — a patched static OpenCASCADE, cached in `~/.cache/carbon-occt`. Slow (~15–30 min) but one-time per machine; re-running is a no-op once cached:++ ```bash+ $ ./apps/assembler/scripts/build-occt.sh+ ```++3. **Build the service** — seconds once OCCT is cached (`build.rs` finds it automatically):++ ```bash+ $ cargo build --release -p assembler+ ```++`crbn up` spawns the binary when it's present. Verify it's up with `curl -sf "$ASSEMBLER_SERVICE_URL/health"` (the URL is in your worktree's `.env.local`) or by watching the `asm |` lines in the `crbn up` output. Without the binary the rest of the stack still runs — only `/convert` and `/plan` are unavailable.+The dev stack (Postgres, GoTrue, Kong, Storage, Inngest, Inbucket, Studio, Realtime) is booted later by `crbn up` — see [Local dev CLI](#local-dev-cli-crbn) below. There is no separate "start the database" step.### Local dev CLI (`crbn`)diff --git a/apps/assembler/AGENTS.md b/apps/assembler/AGENTS.mdnew file mode 100644index 0000000000..798e5ea4bb--- /dev/null+++ b/apps/assembler/AGENTS.md@@ -0,0 +1,155 @@+# assembler — Agent Guide++The geometry service: STEP → GLB + assembly graph (`/convert`) and collision-free+disassembly motion planning (`/plan`), as a Rust **axum** HTTP service. It runs+over the C++ **FCL** (collision) and **OpenCASCADE** (CAD) libraries via `cxx`+bridges. Ported from a former Python/FastAPI service; the byte-for-byte outputs+(nodeIds, geometry hashes, collision truth) are preserved so previously stored+graphs and plans stay valid.++Design + history: `.ai/plans/2026-07-10-geometry-service-rust-rewrite.md`,+`.ai/runs/2026-07-10-geometry-rust-rewrite.md`.++## Workspace++The service binary is `apps/assembler`; the heavy lifting lives in workspace crates:++```+apps/assembler/ # axum HTTP: /health, /convert, /plan (async; long-poll GET /plan/{id}?wait=),+ # /cache/invalidate; Memory|Redis job+result store (ASSEMBLER_REDIS_URL)+ # + bearer auth, URL validation, concurrency semaphore, graceful shutdown+crates/+├── collision/ # cxx bridge over C++ FCL 0.7.0. new_bvh / collide_pair / distance_pair.+├── occt-bridge/ # cxx bridge over OpenCASCADE. read_step: XCAF walk + tessellation → flat node tree.+│ # Flat multi-body products (one PRODUCT, ≥2 solids, no assembly tree — the common+│ # Fusion/SolidWorks export) split into per-solid child components; guarded so any+│ # sheet/surface geometry beside the solids keeps the merged mesh (nothing vanishes).+│ # write_test_step generates hermetic multi-solid STEP fixtures for tests.+├── converter/ # STEP → graph.json + GLB. nodeid (sha1), graph (tree/bbox/source-unit), convert, glb.+└── planner/ # assembly-by-disassembly motion planner: greedy/geom/fasteners/collide/steps.+ # stability.rs adds a support-polygon check (part CoM outside the hull of the+ # contact points below it ⇒ `needsSupport`); pipeline2 `compute_waves` levels+ # the precedence DAG into parallel-buildable `wave`s. Both purely additive to+ # plan.json — the linear `sequence` is unchanged.+ # view.rs bakes a mesh-precise per-step camera DIRECTION into plan.json+ # (`viewDirection`): Fibonacci-hemisphere candidates scored by ray-vs-triangle+ # sight lines (Möller–Trumbore + AABB broadphase) against the bodies installed+ # earlier in the sequence, so a part seating inside a hollow enclosure gets a+ # view through the open side. The viewer fits the frame live at the real aspect.+```++Dependency flow: `apps/assembler → planner → converter → occt-bridge`; `planner → collision`.++## Native deps++**Dev (macOS):** `brew install fcl opencascade` (pulls libccd, eigen, octomap).+Each bridge's `build.rs` resolves the lib prefix from `<PKG>_PREFIX` env, else a+fixed per-target default (macOS-arm `/opt/homebrew/opt/<pkg>`, Linux `/usr`) — no+`brew` shell-out, so the build is reproducible.++**Deploy (Docker):** OCCT and FCL/ccd are **static-linked into the binary**, so the+runtime image is just the ~24 MB binary + OpenBLAS/libstdc++ (no collision or OCCT+shared objects). `occt.Dockerfile` builds a kept base image `carbon-occt` (OCCT+**V8_0_0_p1** static + the thread_local allocator patch in `occt-patches/`);+`Dockerfile` builds FCL 0.7 + libccd static (`FCL_STATIC_LIBRARY=ON`, no octomap)+and links it all in. Build the base image once; app-image builds then take minutes.++## Why bind the same C++ libs (not parry3d / pure-Rust)++The planner's correctness keys off FCL penetration depths at a 0.15mm tolerance;+parry3d's contact model differs structurally and can't match it. nodeIds derive+from a sha1 of quantized tessellation vertices; a different OCCT version tessellates+differently → different nodeIds → existing stored graphs/plans break. So both are+bound via `cxx`, not reimplemented.++## Verification++Self-contained Rust tests (no live Python):++```bash+cargo test -p collision -p converter -p planner --tests+```++- **`collision/tests/calibration.rs`** — the FCL byte-parity guard: replays a+ committed fixture (`calibration.json`, generated from python-fcl 0.7.0.11 /+ FCL 0.7.0) and asserts identical contacts/distances. This is what proves the+ C++ collision layer stays faithful.+- **`planner/tests/{synthetic_plan,plan_step_smoke}.rs`** — planner behaviour over+ in-code synthetic geometry + a smoke plan.+- **`converter`** unit tests (nodeid / source-unit / geom byte-parity).+- `converter/tests/convert_parity.rs` diffs graph.json against Python reference+ fixtures — **dormant**: it skips unless `ASSEMBLER_FIXTURES` points at a fixture+ dir (the former Python service produced these; only regenerate if re-establishing+ cross-impl parity).++## Run++```bash+ASSEMBLER_DEV_MODE=true cargo run -p assembler # listens on 0.0.0.0:8000 (ASSEMBLER_BIND to override)+```++Env: `ASSEMBLER_SERVICE_API_KEY` (bearer auth), `ASSEMBLER_DEV_MODE=true` (allow+unauth + http + skip TLS verify, local only), `ASSEMBLER_MAX_SOURCE_MB` (250),+`ASSEMBLER_MAX_PARTS` (5000), `ASSEMBLER_MAX_CONCURRENCY` (2),+`ASSEMBLER_SHUTDOWN_GRACE_S` (600), `ASSEMBLER_ALLOWED_URL_HOSTS`,+`ASSEMBLER_REDIS_URL` (unset ⇒ in-memory store), `ASSEMBLER_JOB_TTL_SECS`+(86400), `ASSEMBLER_RESULT_TTL_SECS` (86400), `ASSEMBLER_PENDING_TTL_SECS` (300),+`ASSEMBLER_MAX_LONG_POLL_S` (25).++## Completion & lifecycle++`/plan` is async: POST returns 202, the plan runs in a background task holding a+concurrency slot. Callers **long-poll** `GET /plan/{jobId}?wait=<secs>` — the+request is held open (server-capped at `ASSEMBLER_MAX_LONG_POLL_S`) until the job+reaches a terminal state, so completion is near-immediate and a whole plan costs+a handful of checkpointed Inngest steps rather than ~180 short polls (`?wait`+absent ⇒ immediate return, back-compat).++**Job status + pointers live in a backend-selectable store** (`plan_jobs.rs`),+chosen at boot by `ASSEMBLER_REDIS_URL`:+- unset ⇒ `Memory` (process-local DashMaps, single-process behavior);+- set + reachable ⇒ `Redis` (a set-but-unreachable URL logs and falls back to+ memory — never refuses to boot).+Redis holds **only status + pointers, never plan/glb bytes**: `asm:job:{jobId}` →+`{status, planPath, stats, …}` (TTL `ASSEMBLER_JOB_TTL_SECS`). This is what makes+the service **stateless** — a restart or a sibling replica can still answer the+poll (no 404-on-restart loss).++**The plan artifact is offloaded to storage (late-mint).** The service has **no+persistent storage credentials**; instead the app mints a FRESH signed upload URL+on *each* long-poll and sends it as the `X-Plan-Upload-Url` header. On completion+the service marks the job `uploading` and parks the plan bytes in a short-TTL+hand-off buffer (`asm:pending:{jobId}` hash in Redis, or in-process in memory+mode); the next poll carrying a URL drains it — PUTting plan.json with a+seconds-old token, then returning the `{planPath, stats}` pointer. Minting late+(not at submit) keeps the token short-lived instead of needing one that outlives+the whole plan; buffering in Redis (not one replica's memory) means **any**+replica's poll can finalize, so it's not single-process/sticky. A plan not drained+within `ASSEMBLER_PENDING_TTL_SECS` is abandoned (the job re-plans). (Legacy: a job+with no `planPath` in meta returns the plan inline for the app to upload.)++**Content-hash result cache** (`asm:result:{model}:{contentHash}:{optsHash}:v{CODE_VERSION}`+→ pointer, TTL `ASSEMBLER_RESULT_TTL_SECS`): a repeat of the same model + bytes ++options + code version reuses the prior plan's storage pointer, skipping the FCL+compute. `CODE_VERSION` (`cache.rs`, shared with the convert LRU) is the single+version lever — **bump it on any converter OR planner behavior change** to+auto-invalidate every cache. `optsHash` includes `units`/`sequence`, so a fresh+regenerate that drops auto-swarm units misses automatically. `POST /cache/invalidate`+`{modelUploadId}` is the central explicit bust (called best-effort from the app's+`invalidateAssemblyPlanCache`/`invalidateAssemblyModelCache`).++On SIGTERM/SIGINT the service stops accepting requests, drains in-flight converts+and plan jobs, then force-exits after `ASSEMBLER_SHUTDOWN_GRACE_S`.++## Not yet done++- **meshopt compression** — the converter serves an uncompressed (contract-valid)+ GLB. In-process `meshopt` + `EXT_meshopt_compression` is a follow-up.+- **CI + registry** — no workflow yet builds/publishes the `carbon-occt` base or+ the `carbon-assembler` image, or deploys the container.++## Never++- Never swap the FCL/OCCT bridges for parry3d or a pure-Rust CAD lib — parity breaks.+- Never change nodeId derivation (`crates/converter/src/nodeid.rs`) — stored graphs+ reference these IDs. The byte-parity unit tests guard it.diff --git a/apps/assembler/Cargo.toml b/apps/assembler/Cargo.tomlnew file mode 100644index 0000000000..592805e3f6--- /dev/null+++ b/apps/assembler/Cargo.toml@@ -0,0 +1,28 @@+[package]+name = "assembler"+version.workspace = true+edition.workspace = true+license.workspace = true++[[bin]]+name = "assembler"+path = "src/main.rs"++[dependencies]+converter = { path = "../../crates/converter" }+planner = { path = "../../crates/planner" }+serde.workspace = true+serde_json.workspace = true+axum = "0.7"+tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "fs", "signal", "time"] }+reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream"] }+dashmap = "6"+bytes = "1"+lru = "0.12"+xxhash-rust = { version = "0.8", features = ["xxh3"] }+futures-util = "0.3"+tokio-util = { version = "0.7", features = ["rt"] }+redis = { version = "0.27", default-features = false, features = ["tokio-comp", "connection-manager"] }++[target.'cfg(target_os = "linux")'.dependencies]+tikv-jemallocator = "0.6"diff --git a/apps/assembler/Dockerfile b/apps/assembler/Dockerfilenew file mode 100644index 0000000000..7e6414d23d--- /dev/null+++ b/apps/assembler/Dockerfile@@ -0,0 +1,96 @@+# syntax=docker/dockerfile:1.7+# Carbon assembler service (Rust): STEP -> GLB + assembly graph, and+# collision-free disassembly motion planning.+#+# OCCT is STATIC-LINKED into the binary from the prebuilt carbon-occt base+# image (OCCT V8_0_0_p1 + the CommonBaseAllocator thread_local patch — see+# occt.Dockerfile). Build that base ONCE and keep it:+# docker build -f apps/assembler/occt.Dockerfile -t carbon-occt:8.0.0-p1 apps/assembler+# Then this image builds in ~minutes (cargo cache mounts make code-only+# rebuilds seconds), and the runtime stage is a slim image with just the+# stripped binary — OCCT and FCL/ccd are static-linked in, so no collision or+# OCCT shared objects and no X11; only OpenBLAS + the C++/Fortran runtimes.+#+# Build from the REPO ROOT (the cargo workspace spans crates/* + apps/assembler):+# docker build -f apps/assembler/Dockerfile -t carbon-assembler .+# Override the base tag with --build-arg OCCT_IMAGE=<registry>/carbon-occt:TAG.++ARG OCCT_IMAGE=carbon-occt:8.0.0-p1++# ---- prebuilt static OCCT (kept base image; no source compile) ----+FROM ${OCCT_IMAGE} AS occt++# ---- static FCL + libccd (built from source; Debian ships only .so) ----+# The collision shim uses BVH mesh collision only — no octree — so FCL is built+# minimal (FCL_WITH_OCTOMAP=OFF) and STATIC, so it links into the binary and the+# runtime image carries no fcl/ccd/octomap shared objects. Fast (~minutes) and+# Docker-layer cached; only rebuilt when the pinned versions below change.+FROM debian:bookworm-slim AS fcl+# SIMD baseline for the compiled GJK/EPA bits (the templated hot path is compiled+# in the collision shim instead). x86-64-v3 = AVX2+FMA, the x86_64 Fargate fleet;+# override for a different target arch (e.g. an arm64 image needs an -mcpu value).+ARG MARCH=x86-64-v3+RUN apt-get update && apt-get install -y --no-install-recommends \+ git cmake ninja-build g++ libeigen3-dev ca-certificates \+ && rm -rf /var/lib/apt/lists/*+# libccd — double precision (FCL requires it), static.+RUN git clone --depth 1 --branch v2.1 https://github.com/danfis/libccd.git /ccd \+ && cmake -S /ccd -B /ccd/b -G Ninja -DCMAKE_BUILD_TYPE=Release \+ -DCMAKE_INSTALL_PREFIX=/opt/fcl -DCMAKE_POSITION_INDEPENDENT_CODE=ON \+ -DCMAKE_CXX_FLAGS_RELEASE="-O3 -march=${MARCH}" \+ -DBUILD_SHARED_LIBS=OFF -DENABLE_DOUBLE_PRECISION=ON \+ && cmake --build /ccd/b --target install+# FCL 0.7.0 — static, no octomap; finds ccd + Eigen under the same prefix.+# FCL ignores BUILD_SHARED_LIBS; its own FCL_STATIC_LIBRARY flag is what selects+# a static archive (verified: without it FCL builds libfcl.so regardless).+RUN git clone --depth 1 --branch 0.7.0 https://github.com/flexible-collision-library/fcl.git /fcl \+ && cmake -S /fcl -B /fcl/b -G Ninja -DCMAKE_BUILD_TYPE=Release \+ -DCMAKE_INSTALL_PREFIX=/opt/fcl -DCMAKE_PREFIX_PATH=/opt/fcl \+ -DCMAKE_POSITION_INDEPENDENT_CODE=ON \+ -DCMAKE_CXX_FLAGS_RELEASE="-O3 -march=${MARCH}" \+ -DFCL_STATIC_LIBRARY=ON -DFCL_WITH_OCTOMAP=OFF -DFCL_BUILD_TESTS=OFF \+ && cmake --build /fcl/b --target install++# ---- Rust builder ----+FROM rust:1.90-bookworm AS build+# Eigen headers for the cxx shim; OpenBLAS/gfortran for the planner's BLAS.+# FCL/ccd come from the static build above (no libfcl-dev/libccd-dev).+RUN apt-get update && apt-get install -y --no-install-recommends \+ libeigen3-dev libopenblas-dev gfortran \+ && rm -rf /var/lib/apt/lists/*+COPY --from=occt /opt/occt /opt/occt+COPY --from=fcl /opt/fcl /opt/fcl+WORKDIR /app+# Only the Rust workspace — not the whole monorepo (see Dockerfile.dockerignore).+COPY Cargo.toml Cargo.lock ./+COPY crates ./crates+COPY apps/assembler ./apps/assembler+# Point the cxx bridges at the static OCCT + static FCL/ccd (build.rs picks+# `static=` when it finds a .a at the prefix). Eigen headers from apt.+ENV OCCT_PREFIX=/opt/occt OCCT_LINK=static \+ FCL_PREFIX=/opt/fcl LIBCCD_PREFIX=/opt/fcl EIGEN_PREFIX=/usr OCTOMAP_PREFIX=/usr+# Cache mounts: the cargo registry and the target dir survive across builds,+# so a code-only change relinks instead of recompiling every dependency.+# The binary is copied out because cache mounts vanish after the RUN.+RUN --mount=type=cache,target=/usr/local/cargo/registry \+ --mount=type=cache,target=/app/target \+ cargo build --release -p assembler \+ && cp target/release/assembler /usr/local/bin/assembler \+ && strip /usr/local/bin/assembler++# ---- runtime ----+# OCCT and FCL/ccd are inside the binary; the only dynamic native deps left are+# OpenBLAS (planner linear algebra) + the C++/Fortran runtimes. No -dev headers+# or toolchain, non-root user, healthcheck against the service's own /health.+FROM debian:bookworm-slim AS runtime+RUN apt-get update && apt-get install -y --no-install-recommends \+ libopenblas0-pthread libgfortran5 libstdc++6 \+ curl ca-certificates \+ && rm -rf /var/lib/apt/lists/* \+ && useradd --system --uid 1001 --create-home assembler+COPY --from=build /usr/local/bin/assembler /usr/local/bin/assembler+USER assembler+EXPOSE 8000+HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \+ CMD curl -fsS http://127.0.0.1:8000/health || exit 1+CMD ["assembler"]diff --git a/apps/assembler/Dockerfile.dockerignore b/apps/assembler/Dockerfile.dockerignorenew file mode 100644index 0000000000..08d467c539--- /dev/null+++ b/apps/assembler/Dockerfile.dockerignore@@ -0,0 +1,19 @@+# Build context is the repo root (docker build -f apps/assembler/Dockerfile .).+# The Dockerfile only COPYs Cargo.toml, Cargo.lock, crates/, apps/assembler/.+# This keeps the context tarball small.+**/target+**/node_modules+apps/erp+apps/mes+apps/academy+apps/starter+apps/docs+packages+docs+services+contrib+.git+.github+.ai+.agents+.claudediff --git a/apps/assembler/build.rs b/apps/assembler/build.rsnew file mode 100644index 0000000000..320e2918fe--- /dev/null+++ b/apps/assembler/build.rs@@ -0,0 +1,40 @@+use std::path::PathBuf;++/// Same OCCT discovery as crates/occt-bridge/build.rs: `OCCT_PREFIX` env → the+/// per-machine static-build cache → a fixed per-target default. No `brew`+/// shell-out, so the build never depends on Homebrew being installed or on PATH.+fn occt_prefix() -> String {+ if let Ok(p) = std::env::var("OCCT_PREFIX") {+ if !p.is_empty() {+ return p;+ }+ }+ // The per-machine static build (apps/assembler/scripts/build-occt.sh).+ if let Some(home) = std::env::var_os("HOME") {+ let cached = PathBuf::from(home).join(".cache/carbon-occt/8.0.0-p1");+ if cached.join("lib/libTKernel.a").exists() {+ return cached.to_string_lossy().into_owned();+ }+ }+ let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();+ let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();+ match os.as_str() {+ "macos" if arch == "aarch64" => "/opt/homebrew/opt/opencascade".to_string(),+ "macos" => "/usr/local/opt/opencascade".to_string(),+ _ => "/usr".to_string(),+ }+}++fn main() {+ // Static OCCT (the deployment build) is linked into the binary — no rpath+ // needed. Only a dynamic OCCT (e.g. a brew fallback) needs its lib dir on+ // the runtime search path; embed it so the binary runs without+ // DYLD_LIBRARY_PATH/LD_LIBRARY_PATH (macOS SIP strips DYLD_* across+ // protected binaries like nohup).+ let lib = PathBuf::from(format!("{}/lib", occt_prefix()));+ let is_static = lib.join("libTKernel.a").exists();+ if !is_static && lib.exists() {+ println!("cargo:rustc-link-arg=-Wl,-rpath,{}", lib.display());+ }+ println!("cargo:rerun-if-env-changed=OCCT_PREFIX");+}diff --git a/apps/assembler/occt-patches/0001-common-base-allocator-thread-local.patch b/apps/assembler/occt-patches/0001-common-base-allocator-thread-local.patchnew file mode 100644index 0000000000..07418b778e--- /dev/null+++ b/apps/assembler/occt-patches/0001-common-base-allocator-thread-local.patch@@ -0,0 +1,17 @@+Subject: [PATCH] NCollection_BaseAllocator: make CommonBaseAllocator thread_local++The single process-wide CommonBaseAllocator singleton is copied into every+NCollection container ctor/dtor, so its atomic refcount is a true-sharing+hotspot: under multithreaded DataExchange (parallel STEP convert) every core+RMWs the same cache line, capping in-process scaling at ~3.5x on a 10-P-core+box regardless of jemalloc/mutex changes. A per-thread instance keeps refcount+traffic core-local (measured 3.5x -> ~8.5x, output bit-identical). The allocator+is stateless (a malloc wrapper) and handle refcounting keeps each thread's+instance alive across any cross-thread handoff, so this is semantics-preserving.+--- a/src/FoundationClasses/TKernel/NCollection/NCollection_BaseAllocator.cxx++++ b/src/FoundationClasses/TKernel/NCollection/NCollection_BaseAllocator.cxx+@@ CommonBaseAllocator+- static occ::handle<NCollection_BaseAllocator>* THE_SINGLETON_ALLOC =++ static thread_local occ::handle<NCollection_BaseAllocator>* THE_SINGLETON_ALLOC =+ new occ::handle<NCollection_BaseAllocator>(new NCollection_BaseAllocator);+ return *THE_SINGLETON_ALLOC;diff --git a/apps/assembler/occt-patches/apply.sh b/apps/assembler/occt-patches/apply.shnew file mode 100755index 0000000000..3452a5072f--- /dev/null+++ b/apps/assembler/occt-patches/apply.sh@@ -0,0 +1,9 @@+#!/usr/bin/env bash+# Apply Carbon's OCCT source patches in-place. Idempotent-ish; fails loud.+set -euo pipefail+SRC="${1:?usage: apply.sh <occt-src-dir>}"+f="$SRC/src/FoundationClasses/TKernel/NCollection/NCollection_BaseAllocator.cxx"+grep -q 'static thread_local occ::handle<NCollection_BaseAllocator>\* THE_SINGLETON_ALLOC' "$f" && { echo "already patched"; exit 0; }+perl -0pi -e 's/static (occ::handle<NCollection_BaseAllocator>\* THE_SINGLETON_ALLOC)/static thread_local $1/' "$f"+grep -q 'static thread_local occ::handle<NCollection_BaseAllocator>\* THE_SINGLETON_ALLOC' "$f" || { echo "PATCH FAILED"; exit 1; }+echo "patched CommonBaseAllocator -> thread_local"diff --git a/apps/assembler/occt.Dockerfile b/apps/assembler/occt.Dockerfilenew file mode 100644index 0000000000..c1e5b1bdd4--- /dev/null+++ b/apps/assembler/occt.Dockerfile@@ -0,0 +1,41 @@+# Prebuilt STATIC OCCT base image for the assembler service. Built ONCE and+# kept (OCCT + the patch change ~never); the app Dockerfile FROMs this so+# per-code rebuilds skip the ~30-min OCCT compile entirely.+#+# docker build -f apps/assembler/occt.Dockerfile -t carbon-occt:8.0.0-p1 apps/assembler+# # push to a registry so CI / other machines reuse it:+# # docker tag carbon-occt:8.0.0-p1 <registry>/carbon-occt:8.0.0-p1 && docker push ...+#+# OCCT V8_0_0_p1 + the CommonBaseAllocator thread_local patch (occt-patches/) —+# THE lever that lifts in-process STEP-convert scaling from ~3.5x to near-linear+# on many cores. Built STATIC with everything visual/scripting disabled+# (USE_XLIB/FREETYPE/OPENGL/TK/TCL off — no X11/fontconfig deps at all, the+# opencascade-rs recipe), so the app binary links OCCT in and ships+# self-contained. Build context is apps/assembler (for occt-patches/).+FROM debian:bookworm-slim AS occt+RUN apt-get update && apt-get install -y --no-install-recommends \+ git cmake g++ make ninja-build ca-certificates perl \+ && rm -rf /var/lib/apt/lists/*+RUN git clone --depth 1 --branch V8_0_0_p1 https://github.com/Open-Cascade-SAS/OCCT.git /src+COPY occt-patches /occt-patches+RUN /occt-patches/apply.sh /src+WORKDIR /src/build+RUN cmake -G Ninja .. \+ -DCMAKE_BUILD_TYPE=Release \+ -DCMAKE_INSTALL_PREFIX=/opt/occt \+ -DBUILD_LIBRARY_TYPE=Static \+ -DBUILD_MODULE_Draw=OFF \+ -DBUILD_MODULE_Visualization=OFF \+ -DBUILD_MODULE_ApplicationFramework=ON \+ -DBUILD_MODULE_DataExchange=ON \+ -DBUILD_MODULE_ModelingAlgorithms=ON \+ -DBUILD_MODULE_ModelingData=ON \+ -DBUILD_MODULE_FoundationClasses=ON \+ -DUSE_FREETYPE=OFF -DUSE_XLIB=OFF -DUSE_TK=OFF -DUSE_TCL=OFF \+ -DUSE_OPENGL=OFF -DUSE_GLES2=OFF -DUSE_RAPIDJSON=OFF -DUSE_TBB=OFF \+ -DUSE_FREEIMAGE=OFF -DUSE_DRACO=OFF -DUSE_VTK=OFF -DUSE_FFMPEG=OFF \+ && ninja && ninja install++# Minimal image that just carries /opt/occt so the app Dockerfile can COPY it.+FROM debian:bookworm-slim+COPY --from=occt /opt/occt /opt/occtdiff --git a/apps/assembler/scripts/build-occt.sh b/apps/assembler/scripts/build-occt.shnew file mode 100755index 0000000000..2fa6cef943--- /dev/null+++ b/apps/assembler/scripts/build-occt.sh@@ -0,0 +1,57 @@+#!/usr/bin/env bash+# Build the patched static OCCT the assembler links against — ONE TIME per+# machine (~15-30 min), installed to ~/.cache/carbon-occt/<version> by default.+# Then: OCCT_PREFIX=~/.cache/carbon-occt/8.0.0-p1 cargo build --release -p assembler+# (or export OCCT_PREFIX from your shell profile).+#+# OCCT V8_0_0_p1, static, no visualization/X11/freetype — plus Carbon's+# CommonBaseAllocator thread_local patch (../occt-patches), the lever that makes+# parallel STEP conversion scale near-linearly across cores.+#+# usage: build-occt.sh [install-prefix]+set -euo pipefail++VERSION_TAG="V8_0_0_p1"+PREFIX="${1:-$HOME/.cache/carbon-occt/8.0.0-p1}"+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+PATCHES="$SCRIPT_DIR/../occt-patches"+WORK="$(mktemp -d)"+trap 'rm -rf "$WORK"' EXIT++if [ -f "$PREFIX/lib/libTKernel.a" ]; then+ echo "already built: $PREFIX (delete it to rebuild)"+ exit 0+fi++command -v cmake >/dev/null || { echo "cmake required (brew install cmake / apt install cmake)"; exit 1; }+GEN_ARGS=()+command -v ninja >/dev/null && GEN_ARGS=(-G Ninja)++echo "==> cloning OCCT $VERSION_TAG"+git clone --depth 1 --branch "$VERSION_TAG" https://github.com/Open-Cascade-SAS/OCCT.git "$WORK/src"++echo "==> applying Carbon patches"+"$PATCHES/apply.sh" "$WORK/src"++echo "==> configuring (static, minimal)"+cmake "${GEN_ARGS[@]}" -S "$WORK/src" -B "$WORK/build" \+ -DCMAKE_BUILD_TYPE=Release \+ -DCMAKE_INSTALL_PREFIX="$PREFIX" \+ -DBUILD_LIBRARY_TYPE=Static \+ -DBUILD_MODULE_Draw=OFF \+ -DBUILD_MODULE_Visualization=OFF \+ -DBUILD_MODULE_ApplicationFramework=ON \+ -DBUILD_MODULE_DataExchange=ON \+ -DBUILD_MODULE_ModelingAlgorithms=ON \+ -DBUILD_MODULE_ModelingData=ON \+ -DBUILD_MODULE_FoundationClasses=ON \+ -DUSE_FREETYPE=OFF -DUSE_XLIB=OFF -DUSE_TK=OFF -DUSE_TCL=OFF \+ -DUSE_OPENGL=OFF -DUSE_GLES2=OFF -DUSE_RAPIDJSON=OFF -DUSE_TBB=OFF \+ -DUSE_FREEIMAGE=OFF -DUSE_DRACO=OFF -DUSE_VTK=OFF -DUSE_FFMPEG=OFF++echo "==> building (this is the long part)"+cmake --build "$WORK/build" --parallel+cmake --install "$WORK/build"++echo "==> done: $PREFIX"+echo "build with: OCCT_PREFIX=$PREFIX cargo build --release -p assembler"diff --git a/apps/assembler/src/cache.rs b/apps/assembler/src/cache.rsnew file mode 100644index 0000000000..34e4ee9a38--- /dev/null+++ b/apps/assembler/src/cache.rs@@ -0,0 +1,93 @@+//! Content-addressed result cache for `/convert`. Conversion is a deterministic+//! function of (STEP bytes, deflection, code version), so the same model+//! re-requested (re-plan, re-motion, multiple viewers) skips OCCT tessellation+//! entirely and just re-uploads the cached GLB/graph. This is the throughput+//! lever for the real workload — distinct models are still core-bound, but+//! repeated ones become near-free.++use bytes::Bytes;+use lru::LruCache;+use std::sync::{Arc, Mutex};++/// Single version lever for ALL cached geometry results — the in-process convert+/// LRU (below) AND the Redis job/result-pointer store (`store.rs`). Bump on ANY+/// converter OR planner behavior change so every stale entry, in every cache,+/// auto-misses. This is the "content-hash key + CODE_VERSION" auto-invalidation.+pub const CODE_VERSION: u32 = 1;++pub struct CachedConvert {+ pub glb: Bytes,+ pub graph_bytes: Bytes,+ pub component_count: i64,+ pub triangles: i64,+ pub unit: serde_json::Value,+}++impl CachedConvert {+ fn size(&self) -> usize {+ self.glb.len() + self.graph_bytes.len()+ }+}++struct Inner {+ lru: LruCache<String, Arc<CachedConvert>>,+ bytes: usize,+}++/// Byte-bounded LRU. A single mutex is fine here: the hit path is upload-bound+/// (ms), the lock is held for a map op (ns), and it's only ever taken from+/// sync/blocking contexts — never across an await.+pub struct ResultCache {+ inner: Mutex<Inner>,+ budget: usize,+}++impl ResultCache {+ pub fn new(budget_bytes: usize) -> Self {+ ResultCache {+ inner: Mutex::new(Inner {+ lru: LruCache::unbounded(),+ bytes: 0,+ }),+ budget: budget_bytes,+ }+ }++ /// `content_hash` = xxh3-128 of the STEP bytes, computed while the source+ /// streams to disk (see `http::download_hashed`) — the key costs nothing.+ pub fn key(content_hash: u128, lin: f64, ang: f64) -> String {+ format!("{content_hash:032x}:{lin}:{ang}:v{CODE_VERSION}")+ }++ /// Key from a caller-declared content identity (`source.contentHash`, e.g.+ /// the storage object's etag). Lets a hit skip the download entirely. The+ /// caller vouches that the value changes whenever the bytes change; a+ /// distinct `ch:` keyspace keeps declared keys from ever colliding with+ /// computed byte-hash keys.+ pub fn key_declared(content_hash: &str, lin: f64, ang: f64) -> String {+ format!("ch:{content_hash}:{lin}:{ang}:v{CODE_VERSION}")+ }++ pub fn get(&self, key: &str) -> Option<Arc<CachedConvert>> {+ // LruCache::get bumps recency.+ self.inner.lock().unwrap().lru.get(key).map(Arc::clone)+ }++ pub fn insert(&self, key: String, value: Arc<CachedConvert>) {+ if self.budget == 0 {+ return;+ }+ let size = value.size();+ let mut inner = self.inner.lock().unwrap();+ if let Some((_, old)) = inner.lru.push(key, value) {+ inner.bytes = inner.bytes.saturating_sub(old.size());+ }+ inner.bytes += size;+ while inner.bytes > self.budget {+ match inner.lru.pop_lru() {+ Some((_, v)) => inner.bytes = inner.bytes.saturating_sub(v.size()),+ None => break,+ }+ }+ }+}diff --git a/apps/assembler/src/config.rs b/apps/assembler/src/config.rsnew file mode 100644index 0000000000..5654a7dc64--- /dev/null+++ b/apps/assembler/src/config.rs@@ -0,0 +1,135 @@+//! Operational limits + URL policy — port of `app/config.py` + `_validate_url`.++use crate::error::ApiError;++fn int_env(name: &str, default: usize) -> usize {+ std::env::var(name)+ .ok()+ .and_then(|s| s.parse().ok())+ .unwrap_or(default)+}++pub fn max_source_bytes() -> usize {+ int_env("ASSEMBLER_MAX_SOURCE_MB", 250) * 1024 * 1024+}++pub fn max_parts() -> usize {+ int_env("ASSEMBLER_MAX_PARTS", 5000)+}++/// How long shutdown waits for running plan tasks after the HTTP listener+/// drains. Match the orchestrator's termination grace period.+pub fn shutdown_grace() -> std::time::Duration {+ std::time::Duration::from_secs(int_env("ASSEMBLER_SHUTDOWN_GRACE_S", 600) as u64)+}++/// Result-cache budget (bytes). 0 disables the cache.+pub fn cache_bytes() -> usize {+ int_env("ASSEMBLER_CACHE_MB", 512) * 1024 * 1024+}++pub fn max_concurrency() -> usize {+ int_env("ASSEMBLER_MAX_CONCURRENCY", 2).max(1)+}++/// Redis URL for the shared job/result store. Unset => in-process backend (the+/// single-process default). A set-but-unreachable URL falls back to memory at+/// boot rather than refusing to start (mirrors @carbon/kv's soft-fail).+pub fn redis_url() -> Option<String> {+ std::env::var("ASSEMBLER_REDIS_URL")+ .ok()+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+}++/// TTL (seconds) for a Redis job-status entry — long enough to outlive any poll+/// window, short enough that abandoned jobs self-evict. Default 24h.+pub fn job_ttl_secs() -> u64 {+ int_env("ASSEMBLER_JOB_TTL_SECS", 86400) as u64+}++/// TTL (seconds) for a Redis content-hash result-pointer entry. Default 24h.+pub fn result_ttl_secs() -> u64 {+ int_env("ASSEMBLER_RESULT_TTL_SECS", 86400) as u64+}++/// TTL (seconds) for a computed-but-unuploaded plan held in Redis for hand-off+/// (compute -> the poll that uploads it). Short: a plan not drained within this+/// window is abandoned and the job re-plans. Default 5 min.+pub fn pending_ttl_secs() -> u64 {+ int_env("ASSEMBLER_PENDING_TTL_SECS", 300) as u64+}++/// Server-side cap on the `?wait=` long-poll hold (seconds). Kept under typical+/// proxy/LB idle timeouts so a held request never trips them.+pub fn max_long_poll_secs() -> u64 {+ int_env("ASSEMBLER_MAX_LONG_POLL_S", 25) as u64+}++/// Cap on tokio's blocking pool — the implicit convert queue. OCCT scales to+/// ~core count; beyond that extra blocking threads just oversubscribe (c=64+/// measured: p99 7.2s uncapped). Excess spawn_blocking tasks queue inside the+/// pool, so overload degrades to waiting, never to 429s. +2 headroom keeps+/// tokio::fs ops from starving behind long converts.+pub fn blocking_threads() -> usize {+ let cores = std::thread::available_parallelism().map_or(8, |n| n.get());+ int_env("ASSEMBLER_BLOCKING_THREADS", cores + 2).max(2)+}++pub fn allowed_url_hosts() -> Vec<String> {+ std::env::var("ASSEMBLER_ALLOWED_URL_HOSTS")+ .unwrap_or_default()+ .split(',')+ .map(|s| s.trim().to_lowercase())+ .filter(|s| !s.is_empty())+ .collect()+}++pub fn require_https() -> bool {+ std::env::var("ASSEMBLER_DEV_MODE").as_deref() != Ok("true")+}++pub fn verify_tls() -> bool {+ std::env::var("ASSEMBLER_DEV_MODE").as_deref() != Ok("true")+}++pub fn validate_url(url: &str) -> Result<(), ApiError> {+ let parsed = reqwest::Url::parse(url).map_err(|_| ApiError::invalid("invalid URL"))?;+ let scheme = parsed.scheme();+ if require_https() && scheme != "https" {+ return Err(ApiError::invalid("URLs must use https"));+ }+ if scheme != "http" && scheme != "https" {+ return Err(ApiError::invalid(format!(+ "unsupported URL scheme: {scheme}"+ )));+ }+ let allowed = allowed_url_hosts();+ if !allowed.is_empty() {+ let host = parsed.host_str().unwrap_or("").to_lowercase();+ if !allowed.contains(&host) {+ return Err(ApiError::invalid("URL host is not allowed"));+ }+ } else if require_https() {+ // No explicit allowlist, and not dev mode: default-deny SSRF against+ // internal targets by rejecting private/loopback/link-local IP literals.+ // (Dev fetches source URLs from local storage over portless, so this+ // only applies when ASSEMBLER_DEV_MODE != "true".) Set+ // ASSEMBLER_ALLOWED_URL_HOSTS in production for a positive allowlist.+ if let Some(host) = parsed.host_str() {+ let literal = host.trim_start_matches('[').trim_end_matches(']');+ if let Ok(ip) = literal.parse::<std::net::IpAddr>() {+ let blocked = match ip {+ std::net::IpAddr::V4(v4) => {+ v4.is_private() || v4.is_loopback() || v4.is_link_local()+ }+ std::net::IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),+ };+ if blocked {+ return Err(ApiError::invalid("URL host is not allowed"));+ }+ }+ }+ }+ Ok(())+}diff --git a/apps/assembler/src/error.rs b/apps/assembler/src/error.rsnew file mode 100644index 0000000000..a5ccc831c1--- /dev/null+++ b/apps/assembler/src/error.rs@@ -0,0 +1,60 @@+//! Error contract — `{ok:false, error, code}` with the status codes from+//! `app/errors.py` / `app/main.py`.++use axum::{http::StatusCode, response::IntoResponse, Json};+use serde_json::json;++pub struct ApiError {+ pub status: u16,+ pub code: String,+ pub message: String,+}++impl ApiError {+ pub fn new(status: u16, code: &str, message: impl Into<String>) -> Self {+ ApiError {+ status,+ code: code.to_string(),+ message: message.into(),+ }+ }+ pub fn invalid(message: impl Into<String>) -> Self {+ ApiError::new(400, "INVALID_INPUT", message)+ }+ pub fn unauthorized(message: impl Into<String>) -> Self {+ ApiError::new(401, "UNAUTHORIZED", message)+ }+}++impl From<converter::convert::ConvertError> for ApiError {+ fn from(e: converter::convert::ConvertError) -> Self {+ let status = match e.code.as_str() {+ "READ_FAILED" => 422,+ "TESSELLATION_FAILED" => 500,+ "UPLOAD_FAILED" => 502,+ "INVALID_INPUT" => 400,+ "LIMIT_EXCEEDED" => 413,+ "BUSY" => 429,+ _ => 500,+ };+ ApiError::new(status, &e.code, e.message)+ }+}++impl IntoResponse for ApiError {+ fn into_response(self) -> axum::response::Response {+ let status = StatusCode::from_u16(self.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);+ let mut resp = (+ status,+ Json(json!({"ok": false, "error": self.message, "code": self.code})),+ )+ .into_response();+ // 429s tell callers when to come back so their retries don't hammer+ // the concurrency semaphore (the app honors this with backoff).+ if self.status == 429 {+ resp.headers_mut()+ .insert("Retry-After", axum::http::HeaderValue::from_static("15"));+ }+ resp+ }+}diff --git a/apps/assembler/src/http.rs b/apps/assembler/src/http.rsnew file mode 100644index 0000000000..9fb9f4d830--- /dev/null+++ b/apps/assembler/src/http.rs@@ -0,0 +1,156 @@+//! Signed-URL download/upload + temp files — port of `_download`/`_upload`.++use crate::config;+use crate::error::ApiError;+use std::path::PathBuf;+use std::sync::atomic::{AtomicU64, Ordering};++static COUNTER: AtomicU64 = AtomicU64::new(0);++pub fn temp_path(ext: &str) -> PathBuf {+ let n = COUNTER.fetch_add(1, Ordering::Relaxed);+ let nanos = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_nanos())+ .unwrap_or(0);+ std::env::temp_dir().join(format!("geometry-{}-{n}-{nanos}.{ext}", std::process::id()))+}++/// One shared client for the process: reuses connections (keep-alive/h2)+/// instead of paying a fresh pool + TLS handshake per download/upload.+fn client() -> &'static reqwest::Client {+ static CLIENT: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();+ CLIENT.get_or_init(|| {+ reqwest::Client::builder()+ .danger_accept_invalid_certs(!config::verify_tls())+ .connect_timeout(std::time::Duration::from_secs(10))+ // Idle-read timeout, not a total deadline: a large source can stream+ // for a while, but a stalled connection (no bytes for 60s) must fail+ // so it can't hold a concurrency slot forever.+ .read_timeout(std::time::Duration::from_secs(60))+ .build()+ .expect("reqwest client")+ })+}++/// Stream the source to disk, hashing as it flows — one pass, no full-body RAM+/// buffer, and the content hash comes out free for the result-cache key.+/// `progress` (when given) is ticked with bytes done/total for live status.+pub async fn download_hashed(+ url: &str,+ dest: &std::path::Path,+ progress: Option<&crate::progress::JobProgress>,+) -> Result<u128, ApiError> {+ use futures_util::StreamExt;+ use tokio::io::AsyncWriteExt;++ let limit = config::max_source_bytes();+ let resp = client().get(url).send().await.map_err(|e| {+ ApiError::new(+ 422,+ "READ_FAILED",+ format!("could not download source: {e}"),+ )+ })?;+ if !resp.status().is_success() {+ return Err(ApiError::new(+ 422,+ "READ_FAILED",+ format!("could not download source: {}", resp.status()),+ ));+ }+ if let Some(len) = resp.content_length() {+ if len as usize > limit {+ return Err(ApiError::new(+ 413,+ "LIMIT_EXCEEDED",+ "source file exceeds the size limit",+ ));+ }+ if let Some(p) = progress {+ p.total.store(len, std::sync::atomic::Ordering::Relaxed);+ }+ }++ let mut file = tokio::fs::File::create(dest).await.map_err(|e| {+ ApiError::new(+ 500,+ "READ_FAILED",+ format!("could not write temp file: {e}"),+ )+ })?;+ let mut hasher = xxhash_rust::xxh3::Xxh3::new();+ let mut written = 0usize;+ let mut stream = resp.bytes_stream();+ while let Some(chunk) = stream.next().await {+ // Any mid-stream failure must remove the partial temp file — leaving it+ // leaks disk (callers don't clean up on error).+ let chunk = match chunk {+ Ok(c) => c,+ Err(e) => {+ let _ = tokio::fs::remove_file(dest).await;+ return Err(ApiError::new(+ 422,+ "READ_FAILED",+ format!("could not download source: {e}"),+ ));+ }+ };+ written += chunk.len();+ if written > limit {+ let _ = tokio::fs::remove_file(dest).await;+ return Err(ApiError::new(+ 413,+ "LIMIT_EXCEEDED",+ "source file exceeds the size limit",+ ));+ }+ if let Some(p) = progress {+ p.done+ .store(written as u64, std::sync::atomic::Ordering::Relaxed);+ }+ hasher.update(&chunk);+ if let Err(e) = file.write_all(&chunk).await {+ let _ = tokio::fs::remove_file(dest).await;+ return Err(ApiError::new(+ 500,+ "READ_FAILED",+ format!("could not write temp file: {e}"),+ ));+ }+ }+ file.flush().await.ok();+ Ok(hasher.digest128())+}++pub async fn upload(+ url: &str,+ body: impl Into<reqwest::Body>,+ content_type: &str,+) -> Result<(), ApiError> {+ let resp = client()+ .put(url)+ .header("Content-Type", content_type)+ .header("x-upsert", "true") // retried jobs re-upload to the same path+ .body(body.into())+ .send()+ .await+ .map_err(|e| {+ ApiError::new(+ 502,+ "UPLOAD_FAILED",+ format!("could not upload artifact: {e}"),+ )+ })?;+ if !resp.status().is_success() {+ let status = resp.status();+ let detail = resp.text().await.unwrap_or_default();+ let detail: String = detail.chars().take(200).collect();+ return Err(ApiError::new(+ 502,+ "UPLOAD_FAILED",+ format!("could not upload artifact: {status} {detail}"),+ ));+ }+ Ok(())+}diff --git a/apps/assembler/src/main.rs b/apps/assembler/src/main.rsnew file mode 100644index 0000000000..af4d51026d--- /dev/null+++ b/apps/assembler/src/main.rs@@ -0,0 +1,487 @@+//! Carbon assembler service (Rust) — axum HTTP server: GET /health,+//! POST /convert (STEP -> GLB + assembly graph), POST /plan (202 async,+//! collision-free disassembly motion planning) + GET /plan/{jobId}. Wires the+//! `converter` and `planner` crates.++mod cache;+mod config;+mod error;+mod http;+mod plan_jobs;+mod progress;++use axum::{+ extract::{Path, Query, State},+ http::HeaderMap,+ routing::{get, post},+ Json, Router,+};+use error::ApiError;+use serde_json::{json, Value};+use std::sync::Arc;+use tokio::sync::Semaphore;++const VERSION: &str = "0.1.0";++// jemalloc on the Linux deploy target: the planner's blocking tasks allocate+// heavily from many threads (rayon sweeps + tokio workers); glibc malloc is the+// case it beats. Measured on macOS it LOSES (~+6% wall), so it stays Linux-only.+#[cfg(target_os = "linux")]+#[global_allocator]+static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;++#[derive(Clone)]+struct AppState {+ slots: Arc<Semaphore>,+ jobs: plan_jobs::JobStore,+ cache: Arc<cache::ResultCache>,+ progress: progress::ProgressStore,+}++fn main() {+ // Manual runtime: cap the blocking pool at ~cores so converts queue inside+ // tokio instead of oversubscribing OCCT threads (async workers stay default+ // = cores, they only do I/O).+ tokio::runtime::Builder::new_multi_thread()+ .enable_all()+ .max_blocking_threads(config::blocking_threads())+ .build()+ .expect("tokio runtime")+ .block_on(serve());+}++async fn serve() {+ // Throughput vs latency is picked by env, not code:+ // ASSEMBLER_MESH_PARALLEL=0 + ASSEMBLER_SEQUENTIAL=1 + max_concurrency=cores+ // runs each request single-threaded on its own worker (N concurrent requests+ // = N cores, no oversubscription). The defaults keep each request all-core+ // for lowest single-request latency (CLI / low-concurrency use).+ let max = config::max_concurrency();+ let state = AppState {+ slots: Arc::new(Semaphore::new(max)),+ jobs: plan_jobs::JobStore::from_env().await,+ cache: Arc::new(cache::ResultCache::new(config::cache_bytes())),+ progress: progress::ProgressStore::default(),+ };+ let slots = Arc::clone(&state.slots);+ let app = Router::new()+ .route("/health", get(health))+ .route("/convert", post(convert))+ .route("/convert/status/:job_id", get(convert_status))+ .route("/plan", post(plan))+ .route("/plan/:job_id", get(plan_status))+ .route("/cache/invalidate", post(cache_invalidate))+ .with_state(state);++ eprintln!(+ "assembler config: version={VERSION} concurrency={max} cacheMB={} maxParts={} maxSourceMB={} longPollCap={}s jobTtl={}s resultTtl={}s",+ config::cache_bytes() / 1024 / 1024,+ config::max_parts(),+ config::max_source_bytes() / 1024 / 1024,+ config::max_long_poll_secs(),+ config::job_ttl_secs(),+ config::result_ttl_secs(),+ );++ let addr = std::env::var("ASSEMBLER_BIND").unwrap_or_else(|_| "0.0.0.0:8000".into());+ let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();+ eprintln!("assembler (rust) listening on {addr}");++ axum::serve(listener, app)+ .with_graceful_shutdown(shutdown_signal())+ .await+ .unwrap();++ // The listener has stopped and in-flight HTTP requests have drained (convert+ // is request-bound). Plan jobs run detached (POST /plan returns 202) and+ // each holds a slot, so wait for every slot to free — no permits held means+ // no plan is still running — before exiting, so a deploy/scale-down doesn't+ // kill a plan mid-flight. The grace deadline armed in shutdown_signal+ // force-exits if a wedged job overruns, so shutdown can't hang forever.+ eprintln!("assembler draining in-flight plan jobs");+ let _ = slots.acquire_many(max as u32).await;+ eprintln!("assembler drained cleanly; exiting");+}++/// Resolves on SIGTERM (container stop) or SIGINT (Ctrl-C), then arms a hard+/// deadline: if the graceful drain isn't done within ASSEMBLER_SHUTDOWN_GRACE_S,+/// the process force-exits — we stop on our own terms rather than waiting for+/// the orchestrator's SIGKILL.+async fn shutdown_signal() {+ let ctrl_c = async {+ tokio::signal::ctrl_c().await.ok();+ };+ #[cfg(unix)]+ let terminate = async {+ tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())+ .expect("install SIGTERM handler")+ .recv()+ .await;+ };+ #[cfg(not(unix))]+ let terminate = std::future::pending::<()>();++ tokio::select! {+ _ = ctrl_c => {}+ _ = terminate => {}+ }++ let grace = config::shutdown_grace();+ eprintln!("assembler received shutdown signal; draining (grace {grace:?})");+ tokio::spawn(async move {+ tokio::time::sleep(grace).await;+ eprintln!("assembler shutdown grace elapsed; forcing exit");+ std::process::exit(0);+ });+}++async fn health() -> Json<Value> {+ Json(json!({"ok": true, "version": VERSION}))+}++fn require_auth(headers: &HeaderMap) -> Result<(), ApiError> {+ let api_key = std::env::var("ASSEMBLER_SERVICE_API_KEY")+ .ok()+ .filter(|s| !s.is_empty());+ match api_key {+ None => {+ if std::env::var("ASSEMBLER_DEV_MODE").as_deref() == Ok("true") {+ Ok(())+ } else {+ Err(ApiError::unauthorized(+ "ASSEMBLER_SERVICE_API_KEY is not configured",+ ))+ }+ }+ Some(key) => {+ let auth = headers+ .get("authorization")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("");+ let (scheme, token) = auth.split_once(' ').unwrap_or(("", ""));+ if scheme.eq_ignore_ascii_case("bearer") && constant_eq(token, &key) {+ Ok(())+ } else {+ Err(ApiError::unauthorized("Invalid or missing bearer token"))+ }+ }+ }+}++/// Read at most `cap` bytes from the head of a file, lossy-decoded.+fn read_head_lossy(path: &str, cap: usize) -> Result<String, converter::convert::ConvertError> {+ use std::io::Read;+ let file = std::fs::File::open(path).map_err(|e| {+ converter::convert::ConvertError::new("READ_FAILED", format!("read temp: {e}"))+ })?;+ let mut buf = Vec::new();+ file.take(cap as u64).read_to_end(&mut buf).map_err(|e| {+ converter::convert::ConvertError::new("READ_FAILED", format!("read temp: {e}"))+ })?;+ Ok(String::from_utf8_lossy(&buf).into_owned())+}++fn constant_eq(a: &str, b: &str) -> bool {+ let (a, b) = (a.as_bytes(), b.as_bytes());+ if a.len() != b.len() {+ return false;+ }+ let mut diff = 0u8;+ for i in 0..a.len() {+ diff |= a[i] ^ b[i];+ }+ diff == 0+}++async fn convert(+ State(state): State<AppState>,+ headers: HeaderMap,+ body: Result<Json<Value>, axum::extract::rejection::JsonRejection>,+) -> Result<Json<Value>, ApiError> {+ require_auth(&headers)?;+ let Json(req) = body.map_err(|_| ApiError::invalid("invalid JSON body"))?;++ let source_url = req["source"]["url"]+ .as_str()+ .ok_or_else(|| ApiError::invalid("missing source.url"))?;+ let glb_url = req["outputs"]["glb"]["url"]+ .as_str()+ .ok_or_else(|| ApiError::invalid("missing outputs.glb.url"))?;+ let graph_url = req["outputs"]["graph"]["url"]+ .as_str()+ .ok_or_else(|| ApiError::invalid("missing outputs.graph.url"))?;+ for url in [source_url, glb_url, graph_url] {+ config::validate_url(url)?;+ }+ let job_id = req["jobId"]+ .as_str()+ .filter(|s| !s.is_empty())+ .ok_or_else(|| ApiError::invalid("missing jobId"))?+ .to_string();+ let lin = req["options"]["linearDeflection"].as_f64().unwrap_or(0.1);+ let ang = req["options"]["angularDeflection"].as_f64().unwrap_or(0.5);++ // No slot gate: OCCT reads scale across threads (thread_local allocator+ // patch) and the bounded blocking pool is the queue — overload waits, never+ // 429s. spawn_blocking, not inline: the sync OCCT call would pin an async+ // worker for its full duration (measured at c=64: /health p99 7ms -> 296ms+ // inline, and real files convert in 30-60s). One blocking hop does file+ // read + cache lookup + convert; DashMap ops are sync, never held across+ // an await.+ let started = std::time::Instant::now();+ // Live phase tracking for GET /convert/status/{jobId}; the guard removes+ // the entry when this request ends either way.+ let tracker = state.progress.start(&job_id);++ // Caller-declared content identity (storage etag): a hit here skips the+ // source download entirely.+ let declared = req["source"]["contentHash"]+ .as_str()+ .map(str::trim)+ .filter(|s| !s.is_empty() && s.len() <= 128)+ .map(str::to_string);+ if let Some(h) = &declared {+ let key = cache::ResultCache::key_declared(h, lin, ang);+ if let Some(entry) = state.cache.get(&key) {+ tracker.progress.set_phase(progress::PHASE_UPLOAD);+ return respond_convert(&job_id, entry, true, glb_url, graph_url, started).await;+ }+ }++ let tmp = http::temp_path("step");+ // Hash rides the download stream; a cache hit never touches the blocking+ // pool — it goes straight to the uploads.+ let content_hash =+ http::download_hashed(source_url, &tmp, Some(&tracker.progress)).await?;+ tracker.progress.set_phase(progress::PHASE_CONVERT);+ // Declared key when given (so the next declared lookup hits pre-download);+ // computed byte-hash key otherwise.+ let key = match &declared {+ Some(h) => cache::ResultCache::key_declared(h, lin, ang),+ None => cache::ResultCache::key(content_hash, lin, ang),+ };+ let hit = state.cache.get(&key);+ let was_hit = hit.is_some();+ let entry = match hit {+ Some(entry) => {+ let _ = tokio::fs::remove_file(&tmp).await;+ entry+ }+ None => {+ let tmp_str = tmp.to_string_lossy().to_string();+ let cache = Arc::clone(&state.cache);+ tokio::task::spawn_blocking(move || {+ // Unit detection scans at most the first 32MB (its own cap) —+ // never load the full source into RAM.+ let text = read_head_lossy(&tmp_str, 32 * 1024 * 1024)?;+ let out =+ converter::convert::convert_step(&tmp_str, &text, lin, ang).map(|conv| {+ let entry = Arc::new(cache::CachedConvert {+ glb: conv.glb.into(),+ graph_bytes: serde_json::to_vec(&conv.graph).unwrap().into(),+ component_count: conv.component_count,+ triangles: conv.triangles,+ unit: conv.graph["unit"].clone(),+ });+ cache.insert(key, Arc::clone(&entry));+ entry+ });+ let _ = std::fs::remove_file(&tmp_str);+ out+ })+ .await+ .map_err(|e| {+ ApiError::new(500, "TESSELLATION_FAILED", format!("convert panicked: {e}"))+ })?+ .map_err(ApiError::from)?+ }+ };++ tracker.progress.set_phase(progress::PHASE_UPLOAD);+ respond_convert(&job_id, entry, was_hit, glb_url, graph_url, started).await+}++async fn convert_status(+ State(state): State<AppState>,+ headers: HeaderMap,+ Path(job_id): Path<String>,+) -> Result<Json<Value>, ApiError> {+ require_auth(&headers)?;+ match state.progress.get(&job_id) {+ Some(p) => {+ let (phase, done, total) = p.snapshot();+ Ok(Json(+ json!({"ok": true, "jobId": job_id, "phase": phase, "done": done, "total": total}),+ ))+ }+ None => Err(ApiError::new(+ 404,+ "NOT_FOUND",+ format!("no in-flight convert {job_id}"),+ )),+ }+}++/// Limit check + concurrent artifact PUTs + response — shared by the+/// pre-download declared-hash hit and the normal path.+async fn respond_convert(+ job_id: &str,+ entry: Arc<cache::CachedConvert>,+ was_hit: bool,+ glb_url: &str,+ graph_url: &str,+ started: std::time::Instant,+) -> Result<Json<Value>, ApiError> {+ let mp = config::max_parts();+ if entry.component_count > mp as i64 {+ return Err(ApiError::new(+ 413,+ "LIMIT_EXCEEDED",+ format!(+ "assembly has {} part instances; the limit is {mp}",+ entry.component_count+ ),+ ));+ }++ // Independent PUTs — run them concurrently.+ let (glb_res, graph_res) = tokio::join!(+ http::upload(glb_url, entry.glb.clone(), "model/gltf-binary"),+ http::upload(graph_url, entry.graph_bytes.clone(), "application/json"),+ );+ glb_res?;+ graph_res?;++ let convert_ms = started.elapsed().as_millis() as i64;+ eprintln!(+ "[{job_id}] convert done: {} parts, {} triangles, {convert_ms}ms{}",+ entry.component_count,+ entry.triangles,+ if was_hit { " (cache hit)" } else { "" }+ );+ Ok(Json(json!({+ "ok": true,+ "componentCount": entry.component_count,+ "unit": entry.unit,+ "stats": {"convertMs": convert_ms, "meshTriangles": entry.triangles, "warnings": []},+ })))+}++async fn plan(+ State(state): State<AppState>,+ headers: HeaderMap,+ body: Result<Json<Value>, axum::extract::rejection::JsonRejection>,+) -> Result<(axum::http::StatusCode, Json<Value>), ApiError> {+ require_auth(&headers)?;+ let Json(req) = body.map_err(|_| ApiError::invalid("invalid JSON body"))?;+ let source_url = req["source"]["url"]+ .as_str()+ .ok_or_else(|| ApiError::invalid("missing source.url"))?;+ config::validate_url(source_url)?;+ let job_id = req["jobId"]+ .as_str()+ .filter(|s| !s.is_empty())+ .ok_or_else(|| ApiError::invalid("missing jobId"))?+ .to_string();++ // Opaque caller context echoed back in status responses; the storage path ++ // model id inside it also drive the completion pointer and the content-hash+ // result cache.+ let meta = match &req["meta"] {+ Value::Null => None,+ m => Some(m.clone()),+ };+ let plan_path = meta+ .as_ref()+ .and_then(|m| m["planPath"].as_str())+ .map(str::to_string);+ let model_upload_id = meta+ .as_ref()+ .and_then(|m| m["modelUploadId"].as_str())+ .map(str::to_string);++ // Idempotent: attach to an in-flight run rather than starting a second.+ if let Some(status) = state.jobs.existing_active(&job_id).await {+ return Ok((+ axum::http::StatusCode::ACCEPTED,+ Json(json!({"ok": true, "jobId": job_id, "status": status})),+ ));+ }+ eprintln!(+ "[{job_id}] plan queued (model={})",+ model_upload_id.as_deref().unwrap_or("?")+ );+ state.jobs.set_pending(&job_id, meta.clone()).await;+ state.jobs.spawn(+ &state,+ &job_id,+ plan_jobs::PlanReq {+ source_url: source_url.to_string(),+ plan_path,+ model_upload_id,+ options: req["options"].clone(),+ },+ );++ Ok((+ axum::http::StatusCode::ACCEPTED,+ Json(json!({"ok": true, "jobId": job_id, "status": "pending"})),+ ))+}++#[derive(serde::Deserialize)]+struct WaitQuery {+ /// Long-poll hold in seconds; server-capped. Absent => return immediately.+ wait: Option<u64>,+}++async fn plan_status(+ State(state): State<AppState>,+ headers: HeaderMap,+ Path(job_id): Path<String>,+ Query(q): Query<WaitQuery>,+) -> Result<Json<Value>, ApiError> {+ require_auth(&headers)?;+ // Late-mint offload: the app hands a FRESH signed upload URL on each poll, so+ // the service PUTs the finished plan.json the instant it's ready with a token+ // minted seconds ago (no long-lived URL). Absent for non-offload callers.+ let upload_url = headers+ .get("x-plan-upload-url")+ .and_then(|v| v.to_str().ok())+ .filter(|s| !s.is_empty())+ .map(str::to_string);+ if let Some(u) = &upload_url {+ config::validate_url(u)?;+ }+ let max = match q.wait {+ Some(secs) if secs > 0 => Some(std::time::Duration::from_secs(+ secs.min(config::max_long_poll_secs()),+ )),+ _ => None,+ };+ state+ .jobs+ .poll(&job_id, upload_url.as_deref(), max)+ .await+ .ok_or_else(|| ApiError::new(404, "NOT_FOUND", format!("no plan job {job_id}")))+ .map(Json)+}++/// Central explicit cache invalidation: drop every content-hash result pointer+/// for a model so the next plan re-derives. Best-effort from the app's+/// invalidateAssemblyPlanCache / invalidateAssemblyModelCache.+async fn cache_invalidate(+ State(state): State<AppState>,+ headers: HeaderMap,+ body: Result<Json<Value>, axum::extract::rejection::JsonRejection>,+) -> Result<Json<Value>, ApiError> {+ require_auth(&headers)?;+ let Json(req) = body.map_err(|_| ApiError::invalid("invalid JSON body"))?;+ let model = req["modelUploadId"]+ .as_str()+ .filter(|s| !s.is_empty())+ .ok_or_else(|| ApiError::invalid("missing modelUploadId"))?;+ let cleared = state.jobs.invalidate_model(model).await;+ eprintln!("cache invalidate: model={model} cleared={cleared}");+ Ok(Json(json!({"ok": true, "cleared": cleared})))+}diff --git a/apps/assembler/src/plan_jobs.rs b/apps/assembler/src/plan_jobs.rsnew file mode 100644index 0000000000..21df98e84a--- /dev/null+++ b/apps/assembler/src/plan_jobs.rs@@ -0,0 +1,707 @@+//! Async plan jobs + shared job/result store. A job runs in a Tokio task+//! (holding a concurrency slot); callers long-poll GET /plan/{jobId}?wait=.+//!+//! The store is backend-selectable at boot (`ASSEMBLER_REDIS_URL`):+//! - `Memory` (default): process-local DashMaps — single-process behavior.+//! - `Redis`: status + pointers (never plan/glb bytes) live in Redis, so a+//! restart or a sibling replica can still answer the poll. This is what+//! makes the service stateless. A set-but-unreachable URL falls back to+//! memory at boot rather than refusing to start.+//!+//! On completion the plan artifact is PUT to the caller-signed `outputs.plan.url`+//! (offload) and only the `{planPath, stats, …}` POINTER is stored — the plan+//! JSON never enters Redis or lingers in memory.++use crate::{cache::CODE_VERSION, config, http, AppState};+use dashmap::DashMap;+use planner::steps::PlanUnit;+use redis::AsyncCommands;+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::sync::Arc;+use std::time::{Duration, Instant};+use tokio::sync::Notify;++/// One job's persisted state. Serializable so the Redis backend stores it as a+/// JSON blob and the memory backend keeps the same shape. `done` holds the+/// completion POINTER (planPath/stats/counts) — not the plan itself.+#[derive(Clone, Serialize, Deserialize)]+struct JobRecord {+ status: String, // pending | running | done | error+ #[serde(skip_serializing_if = "Option::is_none")]+ done: Option<Value>,+ #[serde(skip_serializing_if = "Option::is_none")]+ error: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ meta: Option<Value>,+}++#[derive(Clone)]+enum Backend {+ Memory {+ jobs: Arc<DashMap<String, JobRecord>>,+ results: Arc<DashMap<String, Value>>,+ },+ Redis {+ conn: redis::aio::ConnectionManager,+ },+}++/// A finished plan held in memory until a long-poll hands the service a fresh+/// signed upload URL to PUT it to (late-mint offload). Never touches Redis (it's+/// bytes, not a pointer); lives only on the replica that computed the plan.+struct Pending {+ plan: Vec<u8>,+ /// The completion pointer to publish once the upload succeeds.+ done: Value,+ /// Content-hash cache key `(model, contentHash, optsHash)` — the pointer is+ /// only cached once the artifact is durably uploaded (never a dangling path).+ cache: Option<(String, u128, u64)>,+}++/// Shared job + content-hash result store. Cloned into every handler via+/// `AppState`; all inner state is `Arc`/manager-cloned so clones share one store.+#[derive(Clone)]+pub struct JobStore {+ backend: Backend,+ /// Per-job in-process wakeups so a same-replica long-poll returns the instant+ /// the worker finishes (cross-replica completion is caught by the Redis+ /// re-check inside `wait_status`).+ notifiers: Arc<DashMap<String, Arc<Notify>>>,+ /// Computed-but-not-yet-uploaded plans, keyed by job id. A long-poll that+ /// carries an upload URL drains this via `try_finalize`.+ pending: Arc<DashMap<String, Pending>>,+}++/// Outcome of a finalize attempt during a long-poll.+pub enum Finalize {+ /// Uploaded — the returned value is the terminal `done` status.+ Uploaded(Value),+ /// Nothing to upload here (already finalized, or the artifact lives on+ /// another replica) — keep waiting.+ NotPending,+ /// Upload failed transiently; the artifact is kept for the next poll to retry.+ Retry,+}++/// Everything a plan task needs from the request.+pub struct PlanReq {+ pub source_url: String,+ /// Storage path recorded in the completion pointer (what the app persists).+ /// The plan.json is PUT here later via a per-poll signed URL (late-mint).+ pub plan_path: Option<String>,+ /// Scopes the content-hash result cache; None disables caching for this job.+ pub model_upload_id: Option<String>,+ pub options: Value,+}++impl JobStore {+ /// Build from env: Redis when `ASSEMBLER_REDIS_URL` is set and reachable,+ /// else in-memory. Never refuses to boot.+ pub async fn from_env() -> Self {+ let notifiers = Arc::new(DashMap::new());+ if let Some(url) = config::redis_url() {+ match connect(&url).await {+ Ok(conn) => {+ eprintln!("assembler: redis job store enabled");+ return JobStore {+ backend: Backend::Redis { conn },+ notifiers,+ pending: Arc::new(DashMap::new()),+ };+ }+ Err(e) => {+ eprintln!(+ "assembler: ASSEMBLER_REDIS_URL unreachable ({e}); falling back to in-memory store"+ );+ }+ }+ } else {+ eprintln!("assembler: in-memory job store (ASSEMBLER_REDIS_URL unset)");+ }+ JobStore {+ backend: Backend::Memory {+ jobs: Arc::new(DashMap::new()),+ results: Arc::new(DashMap::new()),+ },+ notifiers,+ pending: Arc::new(DashMap::new()),+ }+ }++ // --- job status (pointer, not content) ---------------------------------++ async fn read(&self, id: &str) -> Option<JobRecord> {+ match &self.backend {+ Backend::Memory { jobs, .. } => jobs.get(id).map(|j| j.clone()),+ Backend::Redis { conn } => {+ let mut c = conn.clone();+ match c.get::<_, Option<String>>(job_key(id)).await {+ Ok(Some(s)) => serde_json::from_str(&s).ok(),+ Ok(None) => None,+ Err(e) => {+ eprintln!("assembler: redis job read failed: {e}");+ None+ }+ }+ }+ }+ }++ async fn write(&self, id: &str, rec: &JobRecord) {+ match &self.backend {+ Backend::Memory { jobs, .. } => {+ jobs.insert(id.to_string(), rec.clone());+ }+ Backend::Redis { conn } => {+ let Ok(payload) = serde_json::to_string(rec) else {+ return;+ };+ let mut c = conn.clone();+ if let Err(e) = c+ .set_ex::<_, _, ()>(job_key(id), payload, config::job_ttl_secs())+ .await+ {+ eprintln!("assembler: redis job write failed: {e}");+ }+ }+ }+ }++ pub async fn existing_active(&self, id: &str) -> Option<String> {+ self.read(id)+ .await+ .filter(|j| j.status == "pending" || j.status == "running")+ .map(|j| j.status)+ }++ pub async fn set_pending(&self, id: &str, meta: Option<Value>) {+ self.write(+ id,+ &JobRecord {+ status: "pending".into(),+ done: None,+ error: None,+ meta,+ },+ )+ .await;+ }++ async fn set_status(&self, id: &str, status: &str) {+ if let Some(mut rec) = self.read(id).await {+ rec.status = status.to_string();+ self.write(id, &rec).await;+ }+ }++ async fn set_done(&self, id: &str, done: Value) {+ let meta = self.read(id).await.and_then(|r| r.meta);+ self.write(+ id,+ &JobRecord {+ status: "done".into(),+ done: Some(done),+ error: None,+ meta,+ },+ )+ .await;+ self.wake(id);+ }++ async fn set_error(&self, id: &str, error: String) {+ let meta = self.read(id).await.and_then(|r| r.meta);+ self.write(+ id,+ &JobRecord {+ status: "error".into(),+ done: None,+ error: Some(error),+ meta,+ },+ )+ .await;+ self.wake(id);+ }++ fn render(rec: &JobRecord) -> Value {+ let mut out = match rec.status.as_str() {+ "done" => rec+ .done+ .clone()+ .unwrap_or_else(|| json!({"ok": true, "status": "done"})),+ "error" => json!({"ok": true, "status": "error", "error": rec.error}),+ s => json!({"ok": true, "status": s}),+ };+ if let Some(meta) = &rec.meta {+ out["meta"] = meta.clone();+ }+ out+ }++ pub async fn status(&self, id: &str) -> Option<Value> {+ self.read(id).await.map(|r| Self::render(&r))+ }++ /// Long-poll a job to a terminal state. `upload_url` (when the request+ /// carried one) is used to drain a computed-but-unuploaded plan the instant+ /// it's ready (late-mint offload). With `max`, holds until terminal or the+ /// deadline (same-replica wake via `Notify`, cross-replica via the ~500ms+ /// re-read); without `max`, a single shot. `None` only if the job is unknown.+ pub async fn poll(+ &self,+ id: &str,+ upload_url: Option<&str>,+ max: Option<Duration>,+ ) -> Option<Value> {+ let deadline = max.map(|m| Instant::now() + m);+ loop {+ let cur = self.status(id).await;+ if let Some(v) = &cur {+ match v["status"].as_str().unwrap_or("") {+ "done" | "error" => return cur,+ "uploading" => {+ if let Some(u) = upload_url {+ if let Finalize::Uploaded(done) = self.try_finalize(id, u).await {+ return Some(done);+ }+ }+ }+ _ => {}+ }+ }+ let Some(dl) = deadline else {+ return cur; // single shot: current status (or None if unknown)+ };+ let now = Instant::now();+ if now >= dl {+ return cur;+ }+ let notify = self.notifier(id);+ let tick = (dl - now).min(Duration::from_millis(500));+ tokio::select! {+ _ = notify.notified() => {}+ _ = tokio::time::sleep(tick) => {}+ }+ }+ }++ fn notifier(&self, id: &str) -> Arc<Notify> {+ self.notifiers+ .entry(id.to_string())+ .or_insert_with(|| Arc::new(Notify::new()))+ .clone()+ }++ fn wake(&self, id: &str) {+ if let Some(n) = self.notifiers.get(id) {+ n.notify_waiters();+ }+ }++ /// Hold a computed-but-unuploaded plan for hand-off. Memory backend keeps it+ /// in-process; Redis backend stores it (bytes + pointer) under a short TTL so+ /// ANY replica's poll can drain it — removing the single-process constraint.+ async fn pending_put(+ &self,+ id: &str,+ plan: Vec<u8>,+ done: Value,+ cache: Option<(String, u128, u64)>,+ ) {+ match &self.backend {+ Backend::Memory { .. } => {+ self.pending+ .insert(id.to_string(), Pending { plan, done, cache });+ }+ Backend::Redis { conn } => {+ let cache_s = cache.map(|(m, c, o)| format!("{m}|{c:032x}|{o}"));+ let mut c = conn.clone();+ let mut pipe = redis::pipe();+ pipe.hset(pending_key(id), "plan", plan)+ .ignore()+ .hset(pending_key(id), "done", done.to_string())+ .ignore();+ if let Some(cs) = cache_s {+ pipe.hset(pending_key(id), "cache", cs).ignore();+ }+ pipe.expire(pending_key(id), config::pending_ttl_secs() as i64)+ .ignore();+ if let Err(e) = pipe.query_async::<()>(&mut c).await {+ eprintln!("assembler: redis pending_put failed: {e}");+ }+ }+ }+ }++ async fn pending_take(&self, id: &str) -> Option<(Vec<u8>, Value, Option<(String, u128, u64)>)> {+ match &self.backend {+ Backend::Memory { .. } => self+ .pending+ .get(id)+ .map(|p| (p.plan.clone(), p.done.clone(), p.cache.clone())),+ Backend::Redis { conn } => {+ let mut c = conn.clone();+ let res: redis::RedisResult<(Option<Vec<u8>>, Option<String>, Option<String>)> =+ redis::pipe()+ .hget(pending_key(id), "plan")+ .hget(pending_key(id), "done")+ .hget(pending_key(id), "cache")+ .query_async(&mut c)+ .await;+ let (plan, done_s, cache_s) = match res {+ Ok(t) => t,+ Err(e) => {+ eprintln!("assembler: redis pending_take failed: {e}");+ return None;+ }+ };+ let done: Value = serde_json::from_str(&done_s?).ok()?;+ Some((plan?, done, cache_s.and_then(parse_cache)))+ }+ }+ }++ async fn pending_remove(&self, id: &str) {+ match &self.backend {+ Backend::Memory { .. } => {+ self.pending.remove(id);+ }+ Backend::Redis { conn } => {+ let mut c = conn.clone();+ if let Err(e) = c.del::<_, ()>(pending_key(id)).await {+ eprintln!("assembler: redis pending_remove failed: {e}");+ }+ }+ }+ }++ /// Drain a computed-but-unuploaded plan to `upload_url` (called from a+ /// long-poll that carried a fresh signed URL). On success publishes the+ /// terminal `done` pointer; on transient failure keeps the artifact so the+ /// next poll can retry with a fresher URL.+ pub async fn try_finalize(&self, id: &str, upload_url: &str) -> Finalize {+ let Some((plan, done, cache)) = self.pending_take(id).await else {+ return Finalize::NotPending;+ };+ match http::upload(upload_url, plan, "application/json").await {+ Ok(()) => {+ self.pending_remove(id).await;+ if let Some((model, content, opts)) = cache {+ self.result_put(&model, content, opts, done.clone()).await;+ }+ self.set_done(id, done.clone()).await;+ Finalize::Uploaded(done)+ }+ Err(e) => {+ eprintln!("[{id}] plan upload failed (will retry next poll): {}", e.message);+ Finalize::Retry+ }+ }+ }++ // --- content-hash result-pointer cache (CODE_VERSION-stamped) ----------++ async fn result_get(&self, model: &str, content: u128, opts: u64) -> Option<Value> {+ let key = result_key(model, content, opts);+ match &self.backend {+ Backend::Memory { results, .. } => results.get(&key).map(|v| v.clone()),+ Backend::Redis { conn } => {+ let mut c = conn.clone();+ match c.get::<_, Option<String>>(&key).await {+ Ok(Some(s)) => serde_json::from_str(&s).ok(),+ Ok(None) => None,+ Err(e) => {+ eprintln!("assembler: redis result read failed: {e}");+ None+ }+ }+ }+ }+ }++ async fn result_put(&self, model: &str, content: u128, opts: u64, pointer: Value) {+ let key = result_key(model, content, opts);+ match &self.backend {+ Backend::Memory { results, .. } => {+ results.insert(key, pointer);+ }+ Backend::Redis { conn } => {+ let Ok(payload) = serde_json::to_string(&pointer) else {+ return;+ };+ let mut c = conn.clone();+ if let Err(e) = c+ .set_ex::<_, _, ()>(&key, payload, config::result_ttl_secs())+ .await+ {+ eprintln!("assembler: redis result write failed: {e}");+ }+ }+ }+ }++ /// Central explicit invalidation: drop every cached result pointer for a+ /// model so the next plan re-derives. Returns how many entries were cleared.+ pub async fn invalidate_model(&self, model: &str) -> usize {+ let prefix = format!("asm:result:{model}:");+ match &self.backend {+ Backend::Memory { results, .. } => {+ let keys: Vec<String> = results+ .iter()+ .filter(|e| e.key().starts_with(&prefix))+ .map(|e| e.key().clone())+ .collect();+ for k in &keys {+ results.remove(k);+ }+ keys.len()+ }+ Backend::Redis { conn } => {+ let pattern = format!("{prefix}*");+ let mut scan = conn.clone();+ let mut keys: Vec<String> = Vec::new();+ match scan.scan_match::<_, String>(&pattern).await {+ Ok(mut iter) => {+ while let Some(k) = iter.next_item().await {+ keys.push(k);+ }+ }+ Err(e) => {+ eprintln!("assembler: redis invalidate scan failed: {e}");+ return 0;+ }+ }+ if keys.is_empty() {+ return 0;+ }+ let mut c = conn.clone();+ if let Err(e) = c.del::<_, ()>(&keys).await {+ eprintln!("assembler: redis invalidate del failed: {e}");+ return 0;+ }+ keys.len()+ }+ }+ }++ // --- the plan task ------------------------------------------------------++ pub fn spawn(&self, state: &AppState, job_id: &str, req: PlanReq) {+ let jobs = self.clone();+ let slots = Arc::clone(&state.slots);+ let job_id = job_id.to_string();+ tokio::spawn(async move {+ let _permit = slots.acquire().await;+ jobs.set_status(&job_id, "running").await;+ eprintln!("[{job_id}] plan running");+ let started = Instant::now();++ let tmp = http::temp_path("step");+ let content_hash = match http::download_hashed(&req.source_url, &tmp, None).await {+ Ok(h) => h,+ Err(e) => {+ let msg = e.message;+ eprintln!("[{job_id}] plan failed: source download: {msg}");+ let _ = tokio::fs::remove_file(&tmp).await;+ jobs.set_error(&job_id, msg).await;+ return;+ }+ };+ let opts_hash = opts_hash(&req.options);++ // Content-hash result cache: same model + same bytes + same options ++ // same CODE_VERSION => reuse the prior plan's storage pointer, skip+ // the FCL compute. Same-model scoped so a reused pointer shares the+ // model's invalidation (never a cross-model dangling path).+ if let Some(model) = &req.model_upload_id {+ if let Some(ptr) = jobs.result_get(model, content_hash, opts_hash).await {+ let _ = tokio::fs::remove_file(&tmp).await;+ eprintln!("[{job_id}] plan cache hit ({} parts)", ptr["componentCount"]);+ jobs.set_done(&job_id, ptr).await;+ return;+ }+ }++ let tmp_str = tmp.to_string_lossy().to_string();+ let (lin, ang, clearance, path_samples, units, sequence, tolerance) =+ parse_options(&req.options);+ let mp = config::max_parts();++ let res = tokio::task::spawn_blocking(move || {+ planner::steps::plan_step(+ &tmp_str,+ lin,+ ang,+ clearance,+ path_samples,+ Some(mp),+ units,+ sequence,+ tolerance,+ )+ })+ .await;+ let _ = tokio::fs::remove_file(&tmp).await;++ match res {+ Ok(Ok(r)) => {+ let plan_ms = started.elapsed().as_millis() as i64;+ let stats = json!({+ "planMs": plan_ms,+ "tiers": r.tiers,+ "warnings": r.warnings,+ "verifiedCount": r.verified_count,+ "componentCount": r.component_count,+ "plannedCount": r.planned_count,+ });+ let pointer = json!({+ "ok": true,+ "status": "done",+ "planPath": req.plan_path,+ "componentCount": r.component_count,+ "plannedCount": r.planned_count,+ "stats": stats,+ });+ eprintln!(+ "[{job_id}] plan computed: {} parts, {} planned, {plan_ms}ms",+ r.component_count, r.planned_count+ );++ match &req.plan_path {+ // Late-mint offload: hold the plan in memory and mark the+ // job "uploading"; a long-poll carrying a fresh signed URL+ // drains it (try_finalize) and publishes the pointer.+ Some(_) => match serde_json::to_vec(&r.plan) {+ Ok(bytes) => {+ let cache = req+ .model_upload_id+ .as_ref()+ .map(|m| (m.clone(), content_hash, opts_hash));+ jobs.pending_put(&job_id, bytes, pointer, cache).await;+ jobs.set_status(&job_id, "uploading").await;+ jobs.wake(&job_id);+ }+ Err(e) => {+ jobs.set_error(&job_id, format!("serialize plan: {e}")).await+ }+ },+ // No storage path (None meta): return the plan inline in+ // the status body for the app to persist itself.+ None => {+ let mut done = pointer;+ done["plan"] = r.plan;+ jobs.set_done(&job_id, done).await;+ }+ }+ }+ Ok(Err(e)) => {+ eprintln!("[{job_id}] plan failed: {}", e.message);+ jobs.set_error(&job_id, e.message).await;+ }+ Err(e) => {+ let msg = format!("plan panicked: {e}");+ eprintln!("[{job_id}] {msg}");+ jobs.set_error(&job_id, msg).await;+ }+ }+ });+ }+}++async fn connect(url: &str) -> redis::RedisResult<redis::aio::ConnectionManager> {+ let client = redis::Client::open(url)?;+ let mut conn = client.get_connection_manager().await?;+ // Validate the URL at boot so a bad one falls back to memory now, not on the+ // first job.+ redis::cmd("PING").query_async::<()>(&mut conn).await?;+ Ok(conn)+}++fn job_key(id: &str) -> String {+ format!("asm:job:{id}")+}++fn result_key(model: &str, content: u128, opts: u64) -> String {+ format!("asm:result:{model}:{content:032x}:{opts:016x}:v{CODE_VERSION}")+}++fn pending_key(id: &str) -> String {+ format!("asm:pending:{id}")+}++/// Parse a `"model|contentHex|opts"` cache tuple stored alongside a pending plan.+fn parse_cache(s: String) -> Option<(String, u128, u64)> {+ let mut it = s.splitn(3, '|');+ let model = it.next()?.to_string();+ let content = u128::from_str_radix(it.next()?, 16).ok()?;+ let opts = it.next()?.parse().ok()?;+ Some((model, content, opts))+}++/// Stable hash of the plan options. serde_json serializes object keys sorted+/// (BTreeMap), so the string is deterministic; it includes units/sequence, so+/// dropping auto-swarm units on a fresh regenerate changes the key and misses.+fn opts_hash(options: &Value) -> u64 {+ xxhash_rust::xxh3::xxh3_64(options.to_string().as_bytes())+}++type Opts = (+ f64,+ f64,+ f64,+ usize,+ Option<Vec<PlanUnit>>,+ Option<Vec<Vec<String>>>,+ Option<f64>,+);++fn parse_options(options: &Value) -> Opts {+ let lin = options["linearDeflection"].as_f64().unwrap_or(0.1);+ let ang = options["angularDeflection"].as_f64().unwrap_or(0.5);+ let clearance = options["clearance"].as_f64().unwrap_or(0.5);+ let path_samples = options["pathSamples"].as_u64().unwrap_or(60) as usize;+ // Optional explicit penetration tolerance (mm); absent => inferred from+ // linearDeflection inside plan_step.+ let tolerance = options["tolerance"].as_f64();++ let units = options["units"].as_array().map(|arr| {+ arr.iter()+ .map(|u| PlanUnit {+ id: u["id"].as_str().unwrap_or("").to_string(),+ name: u["name"].as_str().map(|s| s.to_string()),+ node_ids: u["nodeIds"]+ .as_array()+ .map(|a| {+ a.iter()+ .filter_map(|v| v.as_str().map(|s| s.to_string()))+ .collect()+ })+ .unwrap_or_default(),+ })+ .collect()+ });+ let sequence = options["sequence"].as_array().map(|arr| {+ arr.iter()+ .map(|g| {+ g.as_array()+ .map(|a| {+ a.iter()+ .filter_map(|v| v.as_str().map(|s| s.to_string()))+ .collect()+ })+ .unwrap_or_default()+ })+ .collect()+ });+ (+ lin,+ ang,+ clearance,+ path_samples,+ units,+ sequence,+ tolerance,+ )+}diff --git a/apps/assembler/src/progress.rs b/apps/assembler/src/progress.rsnew file mode 100644index 0000000000..504c811475--- /dev/null+++ b/apps/assembler/src/progress.rs@@ -0,0 +1,83 @@+//! Live per-job convert progress, served by `GET /convert/status/{jobId}` so+//! the app can render a real phase checklist instead of a bare spinner.+//! Entries exist only while a convert is in flight; unknown id => 404 and the+//! caller falls back to its coarse DB status.++use dashmap::DashMap;+use std::sync::atomic::{AtomicU64, AtomicU8, Ordering};+use std::sync::Arc;++pub const PHASE_DOWNLOAD: u8 = 0;+pub const PHASE_CONVERT: u8 = 1;+pub const PHASE_UPLOAD: u8 = 2;++pub struct JobProgress {+ phase: AtomicU8,+ /// Bytes downloaded so far (only meaningful in the download phase).+ pub done: AtomicU64,+ /// Total bytes when known from Content-Length, else 0.+ pub total: AtomicU64,+}++impl JobProgress {+ pub fn set_phase(&self, phase: u8) {+ self.phase.store(phase, Ordering::Relaxed);+ }++ pub fn snapshot(&self) -> (&'static str, u64, u64) {+ let phase = match self.phase.load(Ordering::Relaxed) {+ PHASE_DOWNLOAD => "downloading",+ PHASE_CONVERT => "converting",+ _ => "uploading",+ };+ (+ phase,+ self.done.load(Ordering::Relaxed),+ self.total.load(Ordering::Relaxed),+ )+ }+}++#[derive(Clone, Default)]+pub struct ProgressStore {+ inner: Arc<DashMap<String, Arc<JobProgress>>>,+}++impl ProgressStore {+ /// Register a job and get a guard that removes it when the request ends+ /// (success or error) — a finished job must read as 404, not a stale phase.+ pub fn start(&self, job_id: &str) -> ProgressGuard {+ let progress = Arc::new(JobProgress {+ phase: AtomicU8::new(PHASE_DOWNLOAD),+ done: AtomicU64::new(0),+ total: AtomicU64::new(0),+ });+ self.inner.insert(job_id.to_string(), Arc::clone(&progress));+ ProgressGuard {+ store: self.clone(),+ job_id: job_id.to_string(),+ progress,+ }+ }++ pub fn get(&self, job_id: &str) -> Option<Arc<JobProgress>> {+ self.inner.get(job_id).map(|e| Arc::clone(e.value()))+ }+}++pub struct ProgressGuard {+ store: ProgressStore,+ job_id: String,+ pub progress: Arc<JobProgress>,+}++impl Drop for ProgressGuard {+ fn drop(&mut self) {+ // Only clear the entry THIS guard created: a concurrent start() for the+ // same job_id (an idempotent retry) may have replaced it, and that newer+ // live entry must survive so its GET /convert/status stays valid.+ self.store+ .inner+ .remove_if(&self.job_id, |_, v| Arc::ptr_eq(v, &self.progress));+ }+}diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex 78e24e0a84..a1887c1ca1 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -54,7 +54,7 @@ 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) |+| `assemblyInstruction` / `assemblyInstructionStep` | 3D model-based assembly instructions (Draft/Published/Archived); steps carry `componentNodeIds` + `motion`/`camera` JSON for the viewer, a `buildWave` INTEGER (the step's longest-path level in the planner's precedence DAG — steps sharing a wave have no ordering constraint and can be built in parallel by different people/stations; NULL for cycle-affected or hand-authored steps; informational, `sortOrder` still governs playback), and `warnings.needsSupport` (a part in the step tips once placed — center of mass outside the support polygon of the parts below it — likely needs a fixture or a second hand; shown as a "Hold" badge) 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. **Step camera is a discriminated union**: a manual `{position,target,fov}` pose (applied verbatim), OR a planner hint `{source:"plan",direction}` — a mesh-precise view DIRECTION the Rust planner bakes per step (`crates/planner/src/view.rs` `best_view_direction`: sight lines against the real triangles of everything installed earlier, so it sees a hollow enclosure's open top where the viewer's AABB scoring can't). The viewer applies the hint with LIVE framing — target, standing distance, frustum fit at the real viewport aspect (`fitFraming`, `@carbon/viewer`). `null` = fully live AABB framing (fallback for hand-edited steps / old plans). Generated steps carry the plan hint (the TS-side camera bake was removed); re-motion refreshes it but never clobbers a manual pose. 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 |@@ -78,10 +78,10 @@ pnpm --filter @carbon/erp test- `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)+- `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); a **floater fold** using the plan's `contacts` graph merges a placed-but-detached part with the immediately-following step that attaches to it (collision precedence forces the part in first, so it would otherwise render as a lone floating island for one step) — the pair installs as one rigid step along the detached part's motion; skipped on older plans lacking `contacts`; `mode: "regenerate"` replaces existing steps, refused while any step is `planConfidence: "manual"` or status `Done`. Persists a human `title` on every step via `describeStep` (`@carbon/viewer`) — real editable data, not just a render-time fallback. Seeds each step's materials from the component→BOM mappings (best-effort): auto-runs `autoMatchAssemblyComponents` once when the model has no mappings yet, and returns `unmappedComponentCount` (distinct geometry groups with no BOM item) which the generate route surfaces as a "use Match BOM" nudge- `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+- **Unit derivation**: the geometry planner itself auto-detects "detail swarms" — a populated PCB's hundreds of tiny components seated on a board — from pure geometry (`detect_swarm_units`, `crates/planner/src/pipeline2.rs`: a substantial host part + many tiny parts in narrowphase contact with it, each dwarfed by the host; fastener-named parts never join so screws keep their own animations). No BOM or LLM involved. The only TS-side unit source is the user-authored `assemblyUnit` rows ("plan as one component" from the BOM tree), which `loadPlanUnits` (`@carbon/jobs`) sends as `options.units`; the planner merges units for planning and expands them back to member leaves with a named `groups` entry (→ one titled step). Detected groups are ALSO materialized as `assemblyUnit` rows at step generation (`sourceGroupId` = the plan group id, e.g. `swarm:<hostNodeId>`; UNIQUE `(modelUploadId, sourceGroupId)`, upsert DO NOTHING so user renames/edits/deletions win within a plan — a regenerate re-materializes deleted ones) — the Components tab shows them like authored units with an "Auto" badge, and `loadPlanUnits` feeds them back to the planner as caller units so re-plans respect user edits. Flat multi-body STEP uploads (one PRODUCT, many solids, no assembly tree — the common Fusion/SolidWorks export shape) are split into per-solid components by the converter (`crates/occt-bridge` `read_step`), so they plan like proper assemblies instead of one un-plannable blob- `getFlattenedBomMaterials` — the item's engineering BOM flattened through Make subassemblies; feeds the assembly BOM tree and the per-step material picker## Key Exportsdiff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.tsindex 0d9a7724a5..afb6ddb754 100644--- a/apps/erp/app/modules/production/production.models.ts+++ b/apps/erp/app/modules/production/production.models.ts@@ -83,18 +83,23 @@ export function isJobLocked(status: string | null | undefined): boolean {* them to Failed.*/const ASSEMBLY_PLAN_QUEUED_STALE_MS = 2 * 60 * 1000;+// A Processing row with no live worker behind it (worker crash, or the dev+// Inngest server — which keeps runs in memory — restarting mid-run) would+// otherwise read as "running" forever: the UI spins and the re-run guard+// blocks recovery. The worker's own budget is ~30 min of waiting plus+// retries, so anything past this is an orphan.+const ASSEMBLY_PLAN_PROCESSING_STALE_MS = 45 * 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- );+ const age = Date.now() - new Date(job.createdAt).getTime();+ if (job.status === "Processing") {+ return age < ASSEMBLY_PLAN_PROCESSING_STALE_MS;+ }+ return job.status === "Queued" && age < ASSEMBLY_PLAN_QUEUED_STALE_MS;}export const jobOperationStatus = [@@ -1121,11 +1126,20 @@ export const motionSchema = z.discriminatedUnion("type", [z.object({ type: z.literal("none") })]);-export const cameraSchema = z.object({- position: vector3,- target: vector3,- fov: z.number().positive()-});+// A step camera is either a manual "Set view" pose (applied verbatim) or a+// planner-baked view-direction hint (mesh-precise sight lines; the viewer+// derives target/distance/frustum fit live at the real viewport aspect).+export const cameraSchema = z.union([+ z.object({+ position: vector3,+ target: vector3,+ fov: z.number().positive()+ }),+ z.object({+ source: z.literal("plan"),+ direction: vector3+ })+]);export const fastenerSchema = z.object({spec: z.string().optional(),@@ -1143,7 +1157,13 @@ export const fastenerSchema = z.object({*/export const stepPlanWarningsSchema = z.object({flagged: z.boolean().optional(),- blockedBy: z.array(z.string()).optional()+ blockedBy: z.array(z.string()).optional(),+ /**+ * A part in this step will tip once placed (its center of mass falls outside+ * the support polygon of the parts below it) — likely needs a fixture or a+ * second hand. Diagnostic only; never blocks generation or playback.+ */+ needsSupport: z.boolean().optional()});const jsonField = <T extends z.ZodTypeAny>(schema: T) =>@@ -1314,6 +1334,18 @@ export const assemblyInstructionStepComponentsValidator = z.object({componentNodeIds: jsonField(z.array(z.string()))});+export const assemblyStepComponentsReassignValidator = z+ .object({+ // Absent for "remove" (unassign from every step); required otherwise.+ targetStepId: z.string().optional(),+ componentNodeIds: jsonField(z.array(z.string()).min(1)),+ mode: z.enum(["move", "duplicate", "remove"])+ })+ .refine((v) => v.mode === "remove" || !!v.targetStepId, {+ message: "A target step is required",+ path: ["targetStepId"]+ });+export const assemblyInstructionStepStatusValidator = z.object({status: z.enum(assemblyStepStatuses)});diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.tsindex a6e5552d1f..2bf99c6642 100644--- a/apps/erp/app/modules/production/production.server.ts+++ b/apps/erp/app/modules/production/production.server.ts@@ -1,8 +1,50 @@+import { ASSEMBLER_SERVICE_URL } from "@carbon/env";import { trigger } from "@carbon/jobs";import { isInternalEmail } from "@carbon/utils";import { redirect } from "react-router";import { path } from "~/utils/path";+// The geometry (assembler) service backs model conversion and motion planning.+// When it's unreachable those actions can't run, so loaders probe its health and+// the UI soft-gates the assembler-dependent controls. Result cached briefly so a+// navigation burst doesn't fan out one probe per route.+const ASSEMBLER_HEALTH_TTL_MS = 15_000;+const ASSEMBLER_HEALTH_TIMEOUT_MS = 2_000;+let assemblerHealthCache: { healthy: boolean; expires: number } | null = null;++export async function isAssemblerServiceHealthy(): Promise<boolean> {+ if (!ASSEMBLER_SERVICE_URL) return false;++ const now = Date.now();+ if (assemblerHealthCache && assemblerHealthCache.expires > now) {+ return assemblerHealthCache.healthy;+ }++ let healthy = false;+ const controller = new AbortController();+ const timeout = setTimeout(+ () => controller.abort(),+ ASSEMBLER_HEALTH_TIMEOUT_MS+ );+ try {+ const response = await fetch(`${ASSEMBLER_SERVICE_URL}/health`, {+ method: "GET",+ signal: controller.signal+ });+ healthy = response.ok;+ } catch {+ healthy = false;+ } finally {+ clearTimeout(timeout);+ }++ assemblerHealthCache = {+ healthy,+ expires: now + ASSEMBLER_HEALTH_TTL_MS+ };+ return healthy;+}+/*** Assemblies (animated work instructions) are internal-only while the module* matures. Mirrors the backups gate in settings.diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 32fc0f0552..2ff20391d1 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -1,6 +1,7 @@import type { Database, Json } from "@carbon/database";import { fetchAllFromTable } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";import { getLogger } from "@carbon/logger";import type { JSONContent } from "@carbon/react";import { nameSimilarity, tiptapToText } from "@carbon/utils";@@ -13,7 +14,7 @@ import type {import {buildAssemblyStepGroups,CURRENT_PLAN_VERSION,- computeStepCameras,+ describeStep,groupComponentNodeIds,indexAssemblyGraph} from "@carbon/viewer";@@ -4006,6 +4007,33 @@ export async function deleteAssemblyInstruction(return deletion;}+/**+ * Best-effort: tell the assembler to drop its content-hash result-pointer cache+ * for a model, so a re-plan of unchanged bytes+options re-derives instead of+ * reusing a stale pointer. The DB/storage invalidation is the real gate; this is+ * belt-and-suspenders (the service cache also auto-invalidates on CODE_VERSION+ * and any option change). Skips silently when the service URL is unset, and+ * never throws — a failed notify must not block the DB invalidation.+ */+async function notifyAssemblerInvalidate(modelUploadId: string) {+ if (!ASSEMBLER_SERVICE_URL) return;+ try {+ await fetch(`${ASSEMBLER_SERVICE_URL}/cache/invalidate`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(ASSEMBLER_SERVICE_API_KEY+ ? { Authorization: `Bearer ${ASSEMBLER_SERVICE_API_KEY}` }+ : {})+ },+ body: JSON.stringify({ modelUploadId }),+ signal: AbortSignal.timeout(5000)+ });+ } catch {+ // swallow — best-effort+ }+}+/*** 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@@ -4026,16 +4054,25 @@ async function invalidateAssemblyPlanCache(const planJobs = await client.from("assemblyPlanJob")- .select("planPath")+ .select("id, companyId, planPath").eq("modelUploadId", modelUploadId).eq("kind", "plan");- const planPaths = (planJobs.data ?? [])- .map((job) => job.planPath)- .filter((planPath): planPath is string => Boolean(planPath));+ // Remove the recorded planPath AND the deterministic per-job path: a job+ // that failed or was cancelled after the service uploaded plan.json never+ // got planPath set on its row, and would otherwise leave an orphan file.+ const planPaths = [+ ...new Set(+ (planJobs.data ?? []).flatMap((job) => [+ ...(job.planPath ? [job.planPath] : []),+ `${job.companyId}/models/${modelUploadId}/${job.id}/plan.json`+ ])+ )+ ];if (planPaths.length > 0) {- // Best-effort artifact cleanup; deleting the rows below is what actually- // invalidates the cache (getLatestAssemblyPlan then finds nothing).+ // Best-effort artifact cleanup (removing a nonexistent path is a no-op);+ // deleting the rows below is what actually invalidates the cache+ // (getLatestAssemblyPlan then finds nothing).await client.storage.from("private").remove(planPaths);}@@ -4044,6 +4081,86 @@ async function invalidateAssemblyPlanCache(.delete().eq("modelUploadId", modelUploadId).eq("kind", "plan");++ // Auto-detected groups (swarms) get materialized as `assemblyUnit` rows, which+ // FREEZE detection: `loadPlanUnits` feeds them back to the planner as caller+ // units, so a re-plan merges them as-is and never re-runs swarm detection.+ // They're derived cache — invalidating the plan must drop them too, else a+ // deleted-then-recreated instruction re-plans against the frozen unit and+ // resurrects the stale grouping (defeating any planner improvement). The guard+ // above already ensured no other instruction authors against this model, so+ // this is safe. User-authored units (sourceGroupId null) are kept.+ await client+ .from("assemblyUnit")+ .delete()+ .eq("modelUploadId", modelUploadId)+ .not("sourceGroupId", "is", null);++ await notifyAssemblerInvalidate(modelUploadId);+}++/**+ * Explicitly invalidates EVERY cached artifact for a model — plan rows ++ * plan.json files (for all instructions on the model) and the conversion+ * output (glb/graph files + paths) — and resets processingStatus so a fresh+ * convert can run. This is the user-facing escape hatch for stale caches+ * (e.g. after a geometry-service upgrade that changes nodeIds); routine+ * instruction deletion uses the narrower invalidateAssemblyPlanCache instead.+ */+export async function invalidateAssemblyModelCache(+ client: SupabaseClient<Database>,+ modelUploadId: string+) {+ const planJobs = await client+ .from("assemblyPlanJob")+ .select("id, companyId, planPath")+ .eq("modelUploadId", modelUploadId)+ .eq("kind", "plan");++ const paths = new Set<string>();+ for (const job of planJobs.data ?? []) {+ if (job.planPath) paths.add(job.planPath);+ paths.add(`${job.companyId}/models/${modelUploadId}/${job.id}/plan.json`);+ }++ const model = await client+ .from("modelUpload")+ .select("glbPath, graphPath")+ .eq("id", modelUploadId)+ .maybeSingle();+ if (model.data?.glbPath) paths.add(model.data.glbPath);+ if (model.data?.graphPath) paths.add(model.data.graphPath);++ if (paths.size > 0) {+ // Best-effort file cleanup; the row updates below are what invalidate.+ await client.storage.from("private").remove([...paths]);+ }++ await client+ .from("assemblyPlanJob")+ .delete()+ .eq("modelUploadId", modelUploadId)+ .eq("kind", "plan");++ // Drop auto-materialized swarm units too (see invalidateAssemblyPlanCache) —+ // they freeze detection, so a full model-cache reset must re-derive them.+ await client+ .from("assemblyUnit")+ .delete()+ .eq("modelUploadId", modelUploadId)+ .not("sourceGroupId", "is", null);++ await notifyAssemblerInvalidate(modelUploadId);++ return client+ .from("modelUpload")+ .update({+ processingStatus: "Idle",+ processingError: null,+ glbPath: null,+ graphPath: null+ })+ .eq("id", modelUploadId);}export async function upsertAssemblyInstructionStep(@@ -4209,6 +4326,153 @@ export async function updateAssemblyStepComponents(.single();}+// Assign a set of component instances to a target step. `duplicate` unions them+// onto the target only (a component may live on several steps). `move` unions+// them onto the target AND strips them from every other step, so the component+// ends up on exactly the target. `remove` (no target) strips them from EVERY+// step, unassigning them entirely. One transaction: a half-applied move (added+// to target but not removed from the source, or vice versa) would be a real bug.+export async function reassignAssemblyStepComponents(+ db: Kysely<KyselyDatabase>,+ data: {+ assemblyInstructionId: string;+ companyId: string;+ targetStepId?: string;+ componentNodeIds: string[];+ mode: "move" | "duplicate" | "remove";+ updatedBy: string;+ }+) {+ const moving = new Set(data.componentNodeIds);+ return db.transaction().execute(async (trx) => {+ const steps = await trx+ .selectFrom("assemblyInstructionStep")+ .select(["id", "componentNodeIds"])+ .where("assemblyInstructionId", "=", data.assemblyInstructionId)+ .where("companyId", "=", data.companyId)+ .execute();++ const now = new Date().toISOString();+ for (const step of steps) {+ const current = (step.componentNodeIds ?? []) as string[];+ let next: string[];+ if (data.mode !== "remove" && step.id === data.targetStepId) {+ const merged = new Set(current);+ for (const nodeId of moving) merged.add(nodeId);+ next = [...merged];+ } else if (data.mode === "move" || data.mode === "remove") {+ next = current.filter((nodeId) => !moving.has(nodeId));+ } else {+ continue; // duplicate: other steps are untouched+ }+ // Skip a no-op write (nothing added/removed for this step).+ if (+ next.length === current.length &&+ next.every((nodeId, index) => nodeId === current[index])+ ) {+ continue;+ }+ // A move that empties a source step (it had components, now none) leaves a+ // meaningless orphan — drop it. The target step is never emptied (it gains+ // parts), and an already-empty process step (current.length === 0) is left+ // alone.+ if (+ step.id !== data.targetStepId &&+ current.length > 0 &&+ next.length === 0+ ) {+ await trx+ .deleteFrom("assemblyInstructionStep")+ .where("id", "=", step.id)+ .where("companyId", "=", data.companyId)+ .execute();+ continue;+ }+ await trx+ .updateTable("assemblyInstructionStep")+ .set({+ componentNodeIds: next,+ updatedBy: data.updatedBy,+ updatedAt: now+ })+ .where("id", "=", step.id)+ .where("companyId", "=", data.companyId)+ .execute();+ }++ // Keep UNIT membership in step with STEP membership. The Components tab+ // groups by `assemblyUnit`, so moving a part into a step that installs a unit+ // (e.g. the PCB step) must also add it to that unit — otherwise it shows as a+ // loose leaf that never joins the group. `assemblyUnit` is model-scoped.+ const targetStep = steps.find((s) => s.id === data.targetStepId);+ const preMove = ((targetStep?.componentNodeIds ?? []) as string[]).filter(+ (nodeId) => !moving.has(nodeId)+ );+ const model = await trx+ .selectFrom("assemblyInstruction")+ .select("modelUploadId")+ .where("id", "=", data.assemblyInstructionId)+ .where("companyId", "=", data.companyId)+ .executeTakeFirst();+ if (model?.modelUploadId) {+ const units = await trx+ .selectFrom("assemblyUnit")+ .select(["id", "componentNodeIds"])+ .where("modelUploadId", "=", model.modelUploadId)+ .where("companyId", "=", data.companyId)+ .execute();++ // The unit the target step installs = the tightest unit whose members+ // cover the step's pre-move components. None ⇒ a loose step (leave units).+ let targetUnitId: string | null = null;+ if (preMove.length > 0) {+ let bestSize = Number.POSITIVE_INFINITY;+ for (const unit of units) {+ const members = new Set((unit.componentNodeIds ?? []) as string[]);+ if (+ preMove.every((nodeId) => members.has(nodeId)) &&+ members.size < bestSize+ ) {+ bestSize = members.size;+ targetUnitId = unit.id;+ }+ }+ }++ for (const unit of units) {+ const members = new Set((unit.componentNodeIds ?? []) as string[]);+ let changed = false;+ // move/remove: a component leaves every unit it was in (units stay+ // disjoint; a pure remove just unassigns it)…+ if (data.mode === "move" || data.mode === "remove") {+ for (const nodeId of moving)+ if (members.delete(nodeId)) changed = true;+ }+ // …and joins the unit its new step installs.+ if (unit.id === targetUnitId) {+ for (const nodeId of moving)+ if (!members.has(nodeId)) {+ members.add(nodeId);+ changed = true;+ }+ }+ if (changed) {+ await trx+ .updateTable("assemblyUnit")+ .set({+ componentNodeIds: [...members],+ updatedBy: data.updatedBy,+ updatedAt: now+ })+ .where("id", "=", unit.id)+ .where("companyId", "=", data.companyId)+ .execute();+ }+ }+ }+ });+}+async function getNextStepSortOrder(client: SupabaseClient<Database>,data: { assemblyInstructionId: string }@@ -5104,44 +5368,61 @@ export async function autoMatchAssemblyComponents(}// Quantity fallback: a still-unmatched part whose instance count equals- // exactly one still-unmatched BOM line's quantity+ // exactly one still-unmatched BOM line's quantity. Index the unmatched groups+ // and BOM lines by count once (instead of rescanning both per group), and+ // prune the buckets as matches land so the "exactly one" checks stay O(1).+ const unmatchedGroupsByCount = new Map<number, string[]>();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- ) {+ const bucket = unmatchedGroupsByCount.get(group.count);+ if (bucket) bucket.push(hash);+ else unmatchedGroupsByCount.set(group.count, [hash]);+ }+ const unmatchedBomByCount = new Map<number, string[]>();+ for (const material of bom) {+ if (matchedItems.has(material.itemId)) continue;+ const count = Math.round(material.quantity);+ const bucket = unmatchedBomByCount.get(count);+ if (bucket) bucket.push(material.itemId);+ else unmatchedBomByCount.set(count, [material.itemId]);+ }+ for (const [hash, group] of componentGroups) {+ if (matchedHashes.has(hash)) continue;+ const groupBucket = unmatchedGroupsByCount.get(group.count) ?? [];+ const bomBucket = unmatchedBomByCount.get(group.count) ?? [];+ const candidateItemId = bomBucket[0];+ if (groupBucket.length === 1 && bomBucket.length === 1 && candidateItemId) {matchedHashes.add(hash);- matchedItems.add(candidate.itemId);+ matchedItems.add(candidateItemId);+ unmatchedGroupsByCount.set(group.count, []);+ unmatchedBomByCount.set(group.count, []);accepted.push({geometryHash: hash,- itemId: candidate.itemId,+ itemId: candidateItemId,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- });+ // One bulk upsert instead of a round-trip per accepted mapping — this runs on+ // the first-generation critical path. Same conflict target as the single-row+ // helper (upsertAssemblyComponentMapping).+ if (accepted.length > 0) {+ const now = new Date().toISOString();+ await client.from("assemblyComponentMapping").upsert(+ accepted.map((suggestion) => ({+ modelUploadId: instruction.data.modelUploadId,+ geometryHash: suggestion.geometryHash,+ itemId: suggestion.itemId,+ confidence: suggestion.confidence,+ companyId: args.companyId,+ createdBy: args.userId,+ updatedBy: args.userId,+ updatedAt: now+ })),+ { onConflict: "modelUploadId,geometryHash" }+ );}return {@@ -5157,7 +5438,7 @@ export async function autoMatchAssemblyComponents(}type GenerateStepsResult =- | { ok: true; created: number }+ | { ok: true; created: number; unmappedComponentCount: number }| {ok: false;reason: "no-model" | "no-plan" | "steps-exist" | "steps-locked" | "error";@@ -5252,11 +5533,77 @@ export async function generateAssemblyStepsFromPlan(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) : [];+ // Materialize planner-DETECTED groups (id "swarm:<host>" — e.g. a populated+ // PCB's detail swarm) as assemblyUnit rows so the Components tab shows them+ // like authored units, editable through the same UI. Caller-unit groups+ // already ARE rows. Best-effort: a failure here must not block step generation.+ //+ // This is a SYSTEM/derived-data write (reflecting the plan), not a user+ // creating a unit — so the generate route passes a bypassRls (service-role)+ // `client`. The assemblyUnit INSERT/DELETE RLS policies require+ // `production_create`/`production_delete`, but generate only authorizes+ // `production_update`; through a plain RLS client the write silently no-ops+ // (steps get built, units never do). Scoped to companyId, so it's tenant-safe.+ const detectedUnits = Object.entries(plan.groups ?? {})+ .filter(([groupId]) => groupId.startsWith("swarm:"))+ .map(([groupId, group]) => ({+ modelUploadId,+ name: group.name ?? "Detected group",+ componentNodeIds: group.componentNodeIds,+ sourceGroupId: groupId,+ companyId: args.companyId,+ createdBy: args.userId+ }));+ if (args.mode === "regenerate") {+ // Fresh regenerate: the auto-units were deliberately NOT deleted before the+ // plan (a delete-then-failed-re-plan would strand the model ungrouped).+ // Swap them HERE, atomically with the just-rebuilt steps — drop the old auto+ // rows and insert the freshly detected ones so new detection (absorption+ // etc.) wins. If detection now finds no swarm, they clear (the steps don't+ // group it either — consistent).+ const dropped = await client+ .from("assemblyUnit")+ .delete()+ .eq("modelUploadId", modelUploadId)+ .eq("companyId", args.companyId)+ .not("sourceGroupId", "is", null);+ if (dropped.error) {+ logger.error("Failed to clear detected assembly units", {+ error: dropped.error+ });+ }+ if (detectedUnits.length > 0) {+ const inserted = await client.from("assemblyUnit").insert(detectedUnits);+ if (inserted.error) {+ logger.error("Failed to materialize detected assembly units", {+ error: inserted.error+ });+ }+ }+ } else if (detectedUnits.length > 0) {+ // First generation: DO NOTHING on conflict — once materialized the row+ // belongs to the user (renames/member edits survive).+ const materialized = await client+ .from("assemblyUnit")+ .upsert(detectedUnits, {+ onConflict: "modelUploadId,sourceGroupId",+ ignoreDuplicates: true+ });+ if (materialized.error) {+ logger.error("Failed to materialize detected assembly units", {+ error: materialized.error+ });+ }+ }++ // Authored subassembly units name their steps; the rest derive a human title+ // from the components (same `describeStep` the viewer/explorer render), so the+ // title is real editable data instead of a render-time fallback.+ const units = await getAssemblyUnits(client, modelUploadId);+ const namedUnits = (units.data ?? []).map((unit) => ({+ name: unit.name,+ componentNodeIds: unit.componentNodeIds ?? []+ }));const rows = groups.map((group, index) => {const motion = motionSchema.safeParse(group.motion);@@ -5265,14 +5612,40 @@ export async function generateAssemblyStepsFromPlan(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,+ title:+ group.name ??+ describeStep(+ {+ title: null,+ componentNodeIds: group.componentNodeIds,+ fastener: null+ },+ graphIndex,+ namedUnits+ ) ??+ 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,+ // Planner-baked view direction (mesh-precise sight lines); the viewer+ // applies it with live framing — target, distance, frustum fit at the+ // real viewport aspect. Manual "Set view" poses replace this wholesale.+ camera: (group.viewDirection+ ? { source: "plan", direction: group.viewDirection }+ : null) as Json | null,+ warnings: ((): Json | null => {+ const w: Record<string, Json> = {};+ if (group.blockedBy.length > 0) {+ w.flagged = true;+ w.blockedBy = group.blockedBy;+ }+ if (group.needsSupport) {+ w.needsSupport = true;+ }+ return Object.keys(w).length > 0 ? (w as Json) : null;+ })(),+ // Parallel-buildable wave (steps sharing one have no ordering constraint);+ // null for cycle-affected steps. Informational — sortOrder still governs.+ buildWave: group.wave ?? null,planConfidence: group.confidence,status: "Review" as const,companyId: args.companyId,@@ -5290,8 +5663,21 @@ export async function generateAssemblyStepsFromPlan(// Seed each step's materials from the model's component→BOM mappings —// best-effort; generation succeeds regardless.+ let unmappedComponentCount = 0;if (graphIndex && insert.data?.length) {- const mappings = await getAssemblyComponentMappings(client, modelUploadId);+ let mappings = await getAssemblyComponentMappings(client, modelUploadId);+ // First generation usually has no mappings yet. Rather than silently seed+ // nothing (and leave the user to discover "Match BOM"), auto-match once so+ // steps come out with their materials populated. Best-effort: a missing BOM+ // or a match failure just leaves mappings empty and the warning below fires.+ if ((mappings.data ?? []).length === 0) {+ await autoMatchAssemblyComponents(client, {+ assemblyInstructionId: args.assemblyInstructionId,+ companyId: args.companyId,+ userId: args.userId+ });+ mappings = await getAssemblyComponentMappings(client, modelUploadId);+ }const itemIdByGeometryHash = new Map((mappings.data ?? []).map((mapping) => [mapping.geometryHash,@@ -5308,9 +5694,18 @@ export async function generateAssemblyStepsFromPlan(await insertAssemblyStepMaterialSeeds(client, seeds, args);}}+ // Surface how many distinct geometry groups still have no BOM item, so the+ // route can nudge the user to Match BOM instead of a silent gap.+ const allNodeIds = insert.data.flatMap(+ (step) => step.componentNodeIds ?? []+ );+ unmappedComponentCount = groupComponentNodeIds(+ allNodeIds,+ graphIndex+ ).filter((group) => !itemIdByGeometryHash.has(group.key)).length;}- return { ok: true, created: rows.length };+ return { ok: true, created: rows.length, unmappedComponentCount };}/**diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsxindex aea23df405..b9af34ba48 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx@@ -12,6 +12,8 @@ import {Modal,ModalBody,ModalContent,+ ModalDescription,+ ModalFooter,ModalHeader,ModalTitle,Popover,@@ -27,7 +29,7 @@ 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 { useCallback, useEffect, useMemo, useRef, useState } from "react";import {LuArrowDownAZ,LuArrowDownWideNarrow,@@ -37,6 +39,8 @@ import {LuCirclePlus,LuEye,LuEyeOff,+ LuListPlus,+ LuListX,LuMerge,LuPencil,LuSearch,@@ -175,6 +179,13 @@ export default function AssemblyBomTree({[componentMappings]);+ // itemId → BOM line, so each ComponentRow resolves its mapped line in O(1)+ // instead of a linear scan of every BOM material per row per render.+ const bomByItemId = useMemo(+ () => new Map(bomMaterials.map((material) => [material.itemId, material])),+ [bomMaterials]+ );+const [sortMode, setSortMode] = useState<SortMode>("count");const [search, setSearch] = useState("");// Selection and visibility are tracked per instance (nodeId), so a group with@@ -222,6 +233,8 @@ export default function AssemblyBomTree({: { ...group, nodeIds, count: nodeIds.length });}+ // Every mode falls back to alphabetical: count sorts by instance count then+ // by name so equal-count components stay A→Z, and alpha is pure name order.if (sortMode === "count") {groups.sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));} else {@@ -292,16 +305,23 @@ export default function AssemblyBomTree({if (existing) existing.nodeIds.push(nodeId);else byGroup.set(group.key, { group, nodeIds: [nodeId] });}- map.set(unit.id, [...byGroup.values()]);+ map.set(+ unit.id,+ [...byGroup.values()].sort((a, b) =>+ a.group.name.localeCompare(b.group.name)+ )+ );}return map;}, [units, graphIndex]);const visibleUnits = useMemo(() => {- if (!normalizedSearch) return units;- return units.filter((unit) =>- unit.name.toLowerCase().includes(normalizedSearch)- );+ const filtered = normalizedSearch+ ? units.filter((unit) =>+ unit.name.toLowerCase().includes(normalizedSearch)+ )+ : units;+ return [...filtered].sort((a, b) => a.name.localeCompare(b.name));}, [units, normalizedSearch]);// Flatten subassemblies and component groups (each with their expanded children)@@ -338,6 +358,94 @@ export default function AssemblyBomTree({const hasSelection = selectedNodeIds.length > 0;+ // Assign the current selection to an existing step. `move` strips it from the+ // steps it's already on; `duplicate` leaves those. When the selection is+ // already used elsewhere we ask which — otherwise assign straight away.+ const reassignFetcher = useFetcher<{ success: boolean }>();+ const [assignPickerOpen, setAssignPickerOpen] = useState(false);+ const [pendingAssign, setPendingAssign] = useState<{+ targetStepId: string;+ targetTitle: string;+ conflictTitles: string[];+ } | null>(null);++ const stepList = useMemo(+ () =>+ steps.map((step, index) => ({+ id: step.id,+ index,+ title:+ describeStep(toViewerStep(step), graphIndex, namedUnits) ??+ step.title ??+ "Untitled step"+ })),+ [steps, graphIndex, namedUnits]+ );++ const submitAssign = useCallback(+ (targetStepId: string, mode: "move" | "duplicate") => {+ const formData = new FormData();+ formData.set("targetStepId", targetStepId);+ formData.set("componentNodeIds", JSON.stringify(selectedNodeIds));+ formData.set("mode", mode);+ reassignFetcher.submit(formData, {+ method: "post",+ action: path.to.assemblyInstructionStepComponentsReassign(id)+ });+ },+ [reassignFetcher, id, selectedNodeIds]+ );++ // Unassign the selection from every step (no target). Enabled only when the+ // selection is actually installed on some step.+ const selectionOnSomeStep = useMemo(+ () =>+ steps.some((step) =>+ (step.componentNodeIds ?? []).some((nodeId) => selectedSet.has(nodeId))+ ),+ [steps, selectedSet]+ );+ const submitRemove = useCallback(() => {+ setAssignPickerOpen(false);+ const formData = new FormData();+ formData.set("componentNodeIds", JSON.stringify(selectedNodeIds));+ formData.set("mode", "remove");+ reassignFetcher.submit(formData, {+ method: "post",+ action: path.to.assemblyInstructionStepComponentsReassign(id)+ });+ }, [reassignFetcher, id, selectedNodeIds]);++ const onPickAssignStep = useCallback(+ (targetStepId: string) => {+ setAssignPickerOpen(false);+ // Steps (other than the target) that already install any selected instance.+ const conflictTitles = stepList+ .filter(+ (entry) =>+ entry.id !== targetStepId &&+ (steps+ .find((step) => step.id === entry.id)+ ?.componentNodeIds?.some((nodeId) => selectedSet.has(nodeId)) ??+ false)+ )+ .map((entry) => `${entry.index + 1}. ${entry.title}`);+ if (conflictTitles.length === 0) {+ // Not on any other step — nothing to move, just add it here.+ submitAssign(targetStepId, "duplicate");+ return;+ }+ setPendingAssign({+ targetStepId,+ targetTitle:+ stepList.find((entry) => entry.id === targetStepId)?.title ??+ "this step",+ conflictTitles+ });+ },+ [stepList, steps, selectedSet, submitAssign]+ );+// Push the hidden instance set up to the viewer.useEffect(() => {onHideComponents([...hiddenNodeIds]);@@ -483,6 +591,68 @@ export default function AssemblyBomTree({<TooltipContent>Match components to BOM items</TooltipContent></Tooltip>)}+ {hasSelection && canAddStep && stepList.length > 0 && (+ <Popover open={assignPickerOpen} onOpenChange={setAssignPickerOpen}>+ <Tooltip>+ <TooltipTrigger asChild>+ <PopoverTrigger asChild>+ <IconButton+ aria-label="Add selection to a step"+ icon={<LuListPlus />}+ variant="ghost"+ size="sm"+ isDisabled={reassignFetcher.state !== "idle"}+ />+ </PopoverTrigger>+ </TooltipTrigger>+ <TooltipContent>Add to step</TooltipContent>+ </Tooltip>+ <PopoverContent+ align="end"+ className="w-64 p-1"+ onWheel={(e) => e.stopPropagation()}+ onTouchMove={(e) => e.stopPropagation()}+ >+ <p className="px-2 py-1.5 text-xxs font-medium uppercase tracking-wide text-muted-foreground">+ Add {selectedNodeIds.length} to step+ </p>+ <ul className="max-h-64 overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">+ {stepList.map((entry) => (+ <li key={entry.id}>+ <button+ type="button"+ className="flex w-full items-center gap-2 truncate rounded-sm px-2 py-1.5 text-left text-sm hover:bg-accent"+ title={entry.title}+ onClick={() => onPickAssignStep(entry.id)}+ >+ <span className="text-muted-foreground tabular-nums">+ {entry.index + 1}.+ </span>+ <span className="min-w-0 flex-1 truncate">+ {entry.title}+ </span>+ </button>+ </li>+ ))}+ </ul>+ {selectionOnSomeStep && (+ <>+ <div className="my-1 h-px bg-border" />+ <button+ type="button"+ className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm text-destructive hover:bg-destructive/10"+ onClick={submitRemove}+ >+ <LuListX className="size-4 shrink-0" />+ <span className="min-w-0 flex-1 truncate">+ Remove from steps+ </span>+ </button>+ </>+ )}+ </PopoverContent>+ </Popover>+ )}{hasSelection && canGroup && (<Tooltip><TooltipTrigger asChild>@@ -652,6 +822,7 @@ export default function AssemblyBomTree({usage={stepUsage.get(group.key) ?? []}mapping={mappingsByHash.get(group.key) ?? null}bomMaterials={bomMaterials}+ bomByItemId={bomByItemId}canMap={canMap}modelUploadId={modelUploadId}instructionId={id}@@ -750,6 +921,54 @@ export default function AssemblyBomTree({}}/>)}+ {pendingAssign && (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) setPendingAssign(null);+ }}+ >+ <ModalContent>+ <ModalHeader>+ <ModalTitle>Move or add a copy?</ModalTitle>+ <ModalDescription>+ {selectedNodeIds.length} component+ {selectedNodeIds.length === 1 ? " is" : "s are"} already used in{" "}+ {pendingAssign.conflictTitles.join(", ")}. Move{" "}+ {selectedNodeIds.length === 1 ? "it" : "them"} to{" "}+ {pendingAssign.targetTitle}, or keep a copy on both?+ </ModalDescription>+ </ModalHeader>+ <ModalFooter>+ <Button+ variant="secondary"+ onClick={() => setPendingAssign(null)}+ >+ Cancel+ </Button>+ <Button+ variant="secondary"+ isDisabled={reassignFetcher.state !== "idle"}+ onClick={() => {+ submitAssign(pendingAssign.targetStepId, "duplicate");+ setPendingAssign(null);+ }}+ >+ Add a copy+ </Button>+ <Button+ isDisabled={reassignFetcher.state !== "idle"}+ onClick={() => {+ submitAssign(pendingAssign.targetStepId, "move");+ setPendingAssign(null);+ }}+ >+ Move here+ </Button>+ </ModalFooter>+ </ModalContent>+ </Modal>+ )}</div>);}@@ -849,6 +1068,15 @@ function UnitListRow({<span className="min-w-0 flex-1 truncate font-medium" title={unit.name}>{unit.name}</span>+ {unit.sourceGroupId && (+ <Badge+ variant="outline"+ className="text-muted-foreground"+ title="Detected by the motion planner"+ >+ Auto+ </Badge>+ )}<Badge variant="secondary" className="tabular-nums">×{memberCount}</Badge>@@ -1228,6 +1456,7 @@ function ComponentRow({usage,mapping,bomMaterials,+ bomByItemId,canMap,modelUploadId,instructionId,@@ -1244,6 +1473,7 @@ function ComponentRow({usage: { stepId: string; index: number; title: string }[];mapping: AssemblyComponentMapping | null;bomMaterials: FlattenedBomMaterial[];+ bomByItemId: Map<string, FlattenedBomMaterial>;canMap: boolean;modelUploadId: string | null;instructionId: string;@@ -1253,9 +1483,7 @@ function ComponentRow({onToggleExpand: () => void;onSelectStep: (stepId: string) => void;}) {- const bomLine = mapping- ? bomMaterials.find((material) => material.itemId === mapping.itemId)- : undefined;+ const bomLine = mapping ? bomByItemId.get(mapping.itemId) : undefined;const quantityMismatch =bomLine !== undefined && Math.round(bomLine.quantity) !== group.count;const allHidden = hidden === "all";diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsxindex 05a3376a98..76c342f5cf 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx@@ -8,7 +8,6 @@ import {DropdownMenuRadioGroup,DropdownMenuRadioItem,DropdownMenuTrigger,- HStack,IconButton,Input,Modal,@@ -17,6 +16,7 @@ import {ModalFooter,ModalHeader,ModalTitle,+ Spinner,Tabs,TabsContent,TabsList,@@ -32,24 +32,31 @@ import {synthesizeFallbackMotion} from "@carbon/viewer";import type { DragControls } from "framer-motion";-import { Reorder, useDragControls } from "framer-motion";+import { MotionConfig, Reorder, useDragControls } from "framer-motion";import type { ReactNode } from "react";-import { useEffect, useMemo, useRef, useState } from "react";+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";import {LuChevronDown,LuCirclePlus,LuEllipsisVertical,LuGripVertical,+ LuHand,LuSearch,LuSparkles,LuTrash,+ LuTriangleAlert,LuWaypoints} from "react-icons/lu";-import { useFetcher, useParams, useRevalidator } from "react-router";+import {+ useFetcher,+ useParams,+ useRevalidator,+ useSearchParams+} from "react-router";import { Empty } from "~/components";import { ProcedureStepTypeIcon } from "~/components/Icons";import { ConfirmDelete } from "~/components/Modals";-import { usePermissions } from "~/hooks";+import { usePermissions, useRealtime } from "~/hooks";import { path } from "~/utils/path";import { isAssemblyPlanRunning } from "../../production.models";import type { FlattenedBomMaterial } from "../../production.service";@@ -68,6 +75,8 @@ type AssemblyInstructionExplorerProps = {isDisabled: boolean;/** The CAD model is still being converted — block step generation until it lands */isConverting: boolean;+ /** The geometry service is reachable — required to convert models and plan steps */+ assemblerAvailable: boolean;graphIndex: AssemblyGraphIndex | null;/** A successful motion plan exists for the model */hasPlan: boolean;@@ -84,16 +93,22 @@ type AssemblyInstructionExplorerProps = {/** Current component selection (shared with the viewer) — highlighted in the Components tab */selectedNodeIds: string[];onSelectStep: (stepId: string) => void;+ /** Double-click a step — preview (play) its insertion motion */+ onPreviewStep: (stepId: string) => void;onHighlightComponents: (nodeIds: string[]) => void;onHideComponents: (nodeIds: string[]) => void;};-export default function AssemblyInstructionExplorer({+// Memoized: the parent route re-renders on every motion-drag frame+// (draftMotion state) but none of this panel's props change during a drag, so+// the ~30 step rows skip re-rendering entirely.+function AssemblyInstructionExplorer({steps,units,selectedStepId,isDisabled,isConverting,+ assemblerAvailable,graphIndex,hasPlan,planJob,@@ -102,6 +117,7 @@ export default function AssemblyInstructionExplorer({bomMaterials,selectedNodeIds,onSelectStep,+ onPreviewStep,onHighlightComponents,onHideComponents}: AssemblyInstructionExplorerProps) {@@ -121,18 +137,78 @@ export default function AssemblyInstructionExplorer({// 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);+ // planning:true. We hold the button in a pending state until the plan lands,+ // then generate the steps automatically — the click already expressed the+ // intent. The intent persists per-instruction in sessionStorage so it+ // survives a remount or navigating away and back mid-plan (first-time plans+ // run for tens of seconds); without it the auto-generate effect never fires+ // and the plan lands Success with zero steps and no path forward except a+ // second manual click.+ const awaitingPlanKey = `assembly-awaiting-plan:${id}`;+ const [isAwaitingPlan, setIsAwaitingPlanState] = useState(() => {+ try {+ return sessionStorage.getItem(awaitingPlanKey) === "1";+ } catch {+ return false;+ }+ });+ const setIsAwaitingPlan = useCallback(+ (value: boolean) => {+ setIsAwaitingPlanState(value);+ try {+ if (value) {+ sessionStorage.setItem(awaitingPlanKey, "1");+ } else {+ sessionStorage.removeItem(awaitingPlanKey);+ }+ } catch {+ // sessionStorage unavailable — fall back to ephemeral state only+ }+ },+ [awaitingPlanKey]+ );++ // Plan completion is pushed: the worker flips assemblyPlanJob to+ // Success/Failed, realtime revalidates the loader, and the awaiting effect+ // below generates the steps — the 5s poll stays only as a fallback.+ useRealtime(+ "assemblyPlanJob",+ `modelUploadId=eq.${modelUploadId ?? "__none__"}`+ );// Controlled so the Components tab knows when it becomes active — it scrolls the// current selection into view on activationconst [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);+ // outcome of the run we're waiting on. Persisted next to the awaiting flag:+ // after a remount mid-plan the flag survives, so this must too, or the stale+ // failure reads as ours.+ const ignoredFailedKey = `assembly-ignored-failed:${id}`;+ const ignoredFailedJobId = useRef<string | null>(+ (() => {+ try {+ return sessionStorage.getItem(ignoredFailedKey);+ } catch {+ return null;+ }+ })()+ );+ const setIgnoredFailedJobId = useCallback(+ (value: string | null) => {+ ignoredFailedJobId.current = value;+ try {+ if (value) {+ sessionStorage.setItem(ignoredFailedKey, value);+ } else {+ sessionStorage.removeItem(ignoredFailedKey);+ }+ } catch {+ // sessionStorage unavailable — ref only+ }+ },+ [ignoredFailedKey]+ );const planFailed =isAwaitingPlan &&planJob?.status === "Failed" &&@@ -147,6 +223,23 @@ export default function AssemblyInstructionExplorer({}, [generateFetcher.data]);const [showRerunConfirm, setShowRerunConfirm] = useState(false);+ const [showRegenerateConfirm, setShowRegenerateConfirm] = useState(false);+ // Which generate mode the pending click asked for — the awaiting-plan effect+ // re-submits after the plan lands, and a "Regenerate Steps" click must stay+ // a regenerate (a plain re-submit would no-op with "steps-exist").+ const generateModeRef = useRef<"generate" | "regenerate">("generate");+ const submitGenerate = useCallback(+ (mode: "generate" | "regenerate") => {+ generateModeRef.current = mode;+ const formData = new FormData();+ formData.set("mode", mode);+ generateFetcher.submit(formData, {+ method: "post",+ action: path.to.generateAssemblyInstructionSteps(id)+ });+ },+ [generateFetcher, id]+ );// 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@@ -192,6 +285,37 @@ export default function AssemblyInstructionExplorer({).padStart(2, "0")}`;const rerunPlanFetcher = useFetcher<{ success: boolean }>();+ // Any planner work in flight — a re-motion run, a regenerate solve, or the+ // submit round-trips themselves. Drives the footer's planner-menu spinner.+ const isPlannerBusy =+ isPlanning ||+ isSolving ||+ rerunPlanFetcher.state !== "idle" ||+ generateFetcher.state !== "idle";++ // ?autogen=1 (set by the create-assembly redirect): a model-backed+ // instruction generates its steps without a click. One Generate submit —+ // if the plan is already there the steps land instantly; otherwise the+ // action kicks planning and returns planning:true, which arms the same+ // persisted awaiting machinery a manual click would. The param is stripped+ // immediately so reloads and shared links don't re-fire it.+ const [searchParams, setSearchParams] = useSearchParams();+ const autogenFired = useRef(false);+ useEffect(() => {+ if (searchParams.get("autogen") !== "1" || autogenFired.current) return;+ autogenFired.current = true;+ setSearchParams(+ (prev) => {+ const next = new URLSearchParams(prev);+ next.delete("autogen");+ return next;+ },+ { replace: true }+ );+ if (steps.length > 0 || !permissions.can("update", "production")) return;+ submitGenerate("generate");+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [searchParams]);// 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@@ -199,16 +323,19 @@ export default function AssemblyInstructionExplorer({// 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) {+ if (+ !isAwaitingPlan ||+ generateFetcher.state !== "idle" ||+ rerunPlanFetcher.state !== "idle"+ ) {return;}- generateFetcher.submit(new FormData(), {- method: "post",- action: path.to.generateAssemblyInstructionSteps(id)- });+ // Still working — keep waiting. Checked BEFORE hasPlan so a fresh re-plan+ // (Regenerate) isn't short-circuited by a STALE plan that still exists:+ // wait for the running plan, then generate from it.+ if (isConverting || isPlanning || planFailed) return;+ if (hasPlan) setIsAwaitingPlan(false);+ submitGenerate(generateModeRef.current);}, [isAwaitingPlan,hasPlan,@@ -216,6 +343,8 @@ export default function AssemblyInstructionExplorer({isPlanning,planFailed,generateFetcher,+ rerunPlanFetcher.state,+ submitGenerate,id]);@@ -225,10 +354,37 @@ export default function AssemblyInstructionExplorer({const [sortOrder, setSortOrder] = useState<string[]>(steps.map((step) => step.id));+ // A local reorder saves on a 2500ms debounce; until it lands, a revalidation+ // still carries the PRE-reorder server order. Track the pending save so the+ // sync effect below doesn't snap the user's drag back.+ const orderSavePendingRef = useRef(false);useEffect(() => {- setSortOrder(steps.map((step) => step.id));- }, [steps]);+ setSortOrder((prev) => {+ const nextIds = steps.map((step) => step.id);+ const prevSet = new Set(prev);+ const sameSet =+ prev.length === nextIds.length &&+ nextIds.every((id) => prevSet.has(id));+ if (sameSet) {+ // Same steps, possibly reordered upstream. Keep the local order while a+ // save is in flight; otherwise adopt the server order (source of truth).+ const savePending =+ orderSavePendingRef.current || sortOrderFetcher.state !== "idle";+ if (savePending) return prev;+ const sameOrder = nextIds.every((id, i) => prev[i] === id);+ return sameOrder ? prev : nextIds;+ }+ // Steps added or removed — resync to the server list.+ return nextIds;+ });+ }, [steps, sortOrderFetcher.state]);++ useEffect(() => {+ if (sortOrderFetcher.state === "idle" && sortOrderFetcher.data?.success) {+ orderSavePendingRef.current = false;+ }+ }, [sortOrderFetcher.state, sortOrderFetcher.data]);// Select the newly created stepuseEffect(() => {@@ -238,11 +394,7 @@ export default function AssemblyInstructionExplorer({}, [newStepFetcher.data, onSelectStep]);const stepMap = useMemo(- () =>- steps.reduce<Record<string, AssemblyInstructionStepRow>>(- (acc, step) => ({ ...acc, [step.id]: step }),- {}- ),+ () => new Map(steps.map((step) => [step.id, step])),[steps]);@@ -257,16 +409,26 @@ export default function AssemblyInstructionExplorer({[units]);+ // Derive the viewer shape once — both stepTitles and searchText need it, and+ // toViewerStep otherwise runs twice per step per render.+ const viewerStepMap = useMemo(+ () => new Map(steps.map((step) => [step.id, toViewerStep(step)])),+ [steps]+ );+const stepTitles = useMemo(() =>new Map(steps.map((step) => [step.id,- describeStep(toViewerStep(step), graphIndex, namedUnits) ??- "Untitled step"+ describeStep(+ viewerStepMap.get(step.id) ?? toViewerStep(step),+ graphIndex,+ namedUnits+ ) ?? "Untitled step"])),- [steps, graphIndex, namedUnits]+ [steps, viewerStepMap, graphIndex, namedUnits]);const [search, setSearch] = useState("");@@ -276,7 +438,7 @@ export default function AssemblyInstructionExplorer({const searchText = useMemo(() => {const map = new Map<string, string>();for (const step of steps) {- const viewerStep = toViewerStep(step);+ const viewerStep = viewerStepMap.get(step.id) ?? toViewerStep(step);const componentNames = graphIndex? groupComponentNodeIds(viewerStep.componentNodeIds, graphIndex).map((group) => group.name)@@ -296,7 +458,7 @@ export default function AssemblyInstructionExplorer({);}return map;- }, [steps, graphIndex, stepTitles]);+ }, [steps, viewerStepMap, graphIndex, stepTitles]);const visibleOrder = useMemo(() => {if (!isSearching) return sortOrder;@@ -326,6 +488,7 @@ export default function AssemblyInstructionExplorer({newOrder.forEach((stepId, index) => {updates[stepId] = index + 1;});+ orderSavePendingRef.current = true;setSortOrder(newOrder);updateSortOrder(updates);};@@ -396,78 +559,126 @@ export default function AssemblyInstructionExplorer({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)}+ <MotionConfig reducedMotion="user">+ <Reorder.Group+ axis="y"+ values={visibleOrder}+ onReorder={onReorder}+ className="w-full"+ disabled={isDisabled || isSearching}+ >+ {visibleOrder.map((stepId) => {+ const step = stepMap.get(stepId);+ if (!step) return null;+ return (+ <DraggableStepItem+ key={stepId}+ stepId={stepId}isDisabled={isDisabled || isSearching}- isSelected={stepId === selectedStepId}- dragControls={dragControls}- onSelect={() => onSelectStep(stepId)}- onDelete={() => setStepToDelete(stepMap[stepId])}- />+ >+ {(dragControls) => (+ <StepItem+ step={step}+ title={stepTitles.get(stepId) ?? "Untitled step"}+ index={sortOrder.indexOf(stepId)}+ isDisabled={isDisabled || isSearching}+ isSelected={stepId === selectedStepId}+ dragControls={dragControls}+ onSelect={() => onSelectStep(stepId)}+ onPreview={() => onPreviewStep(stepId)}+ onDelete={() => setStepToDelete(step)}+ />+ )}+ </DraggableStepItem>+ );+ })}+ </Reorder.Group>+ </MotionConfig>+ ) : permissions.can("update", "production") ? (+ <div className="flex h-full w-full flex-col items-center justify-center px-6 py-10">+ <div className="flex w-full max-w-[280px] flex-col items-center text-center">+ <div+ className={cn(+ "mb-4 flex size-12 items-center justify-center rounded-full",+ planFailed+ ? "bg-destructive/10 text-destructive"+ : "bg-primary/10 text-primary")}- </DraggableStepItem>- ))}- </Reorder.Group>- ) : (- <Empty>- {permissions.can("update", "production") && (- <VStack spacing={2} className="items-center">+ >+ {isSolving ? (+ <Spinner className="size-5" />+ ) : planFailed ? (+ <LuTriangleAlert className="size-5" />+ ) : (+ <LuSparkles className="size-5" />+ )}+ </div>+ <h3 className="text-sm font-medium text-foreground">+ {planFailed+ ? "Couldn't generate steps"+ : isSolving+ ? "Solving assembly motions"+ : "No steps yet"}+ </h3>+ <p className="mt-1 text-pretty text-xs text-muted-foreground">+ {planFailed+ ? (planJob?.error ??+ "Motion planning failed. Retry to run it again.")+ : isSolving+ ? "Reading the model's geometry to work out the build order. Usually 1–3 minutes."+ : hasPlan+ ? "Generate draft steps with motions solved from the model, or add one yourself."+ : "Run the motion planner over the model to create draft steps, or add one yourself."}+ </p>+ {isSolving && (+ <p className="mt-1.5 text-[0.6875rem] tabular-nums text-muted-foreground/70">+ {solveElapsedLabel} elapsed+ </p>+ )}+ {!assemblerAvailable && !hasPlan && !isSolving && (+ <p className="mt-2 text-pretty text-xs text-amber-600 dark:text-amber-500">+ The geometry service is offline — motion planning is+ unavailable right now.+ </p>+ )}+ <div className="mt-5 flex w-full flex-col gap-2"><Button- isDisabled={isDisabled || isConverting || isSolving}+ className="w-full"+ isDisabled={+ isDisabled ||+ isConverting ||+ isSolving ||+ (!assemblerAvailable && !hasPlan)+ }isLoading={isSolving}- leftIcon={<LuSparkles />}+ leftIcon={planFailed ? undefined : <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;+ setIgnoredFailedJobId(+ planJob?.status === "Failed" ? planJob.id : null+ );setIsAwaitingPlan(false);- generateFetcher.submit(new FormData(), {- method: "post",- action: path.to.generateAssemblyInstructionSteps(id)- });+ submitGenerate("generate");}}>{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+ className="w-full"isDisabled={isDisabled}leftIcon={<LuCirclePlus />}variant="secondary"onClick={onAddStep}>- Add Step Manually+ Add step manually</Button>- </VStack>- )}- </Empty>+ </div>+ </div>+ </div>+ ) : (+ <Empty />)}{steps.length > 0 && isSearching && visibleOrder.length === 0 && (<p className="w-full px-4 py-3 text-center text-xs text-muted-foreground">@@ -476,27 +687,9 @@ export default function AssemblyInstructionExplorer({)}</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>- )}+ <div className="flex w-full flex-none items-center gap-2 border-t border-border p-4"><Button- className="w-full"+ className="flex-1"isDisabled={isDisabled ||!permissions.can("update", "production") ||@@ -509,6 +702,60 @@ export default function AssemblyInstructionExplorer({>Add Step</Button>+ {modelUploadId && permissions.can("update", "production") && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label={+ isPlannerBusy+ ? "Motion planning in progress"+ : "Motion planner actions"+ }+ icon={+ isPlannerBusy ? (+ <Spinner className="size-4" />+ ) : (+ <LuSparkles />+ )+ }+ isDisabled={isDisabled || isPlannerBusy}+ variant="secondary"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {!assemblerAvailable && (+ <p className="px-2 py-1.5 text-xs text-amber-600 dark:text-amber-500">+ Geometry service offline — motion planning unavailable.+ </p>+ )}+ <DropdownMenuItem+ disabled={!assemblerAvailable}+ onClick={() => setShowRerunConfirm(true)}+ >+ <DropdownMenuIcon icon={<LuWaypoints />} />+ <div>+ Run Motion Planning+ <p className="text-xs text-muted-foreground">+ Recompute motions, keep step order+ </p>+ </div>+ </DropdownMenuItem>+ <DropdownMenuItem+ destructive+ disabled={!assemblerAvailable}+ onClick={() => setShowRegenerateConfirm(true)}+ >+ <DropdownMenuIcon icon={<LuSparkles />} />+ <div>+ Regenerate Steps+ <p className="text-xs text-muted-foreground">+ Replace all steps from the latest plan+ </p>+ </div>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}</div>)}</TabsContent>@@ -547,6 +794,66 @@ export default function AssemblyInstructionExplorer({onSubmit={() => setStepToDelete(null)}/>)}+ {showRegenerateConfirm && (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) setShowRegenerateConfirm(false);+ }}+ >+ <ModalContent>+ <ModalHeader>+ <ModalTitle>Regenerate steps?</ModalTitle>+ <ModalDescription>+ Replaces all existing steps with fresh drafts from the latest+ motion plan — titles, descriptions, and other edits on the+ current steps are lost. Refused if any step is manually authored+ or marked Done.+ </ModalDescription>+ </ModalHeader>+ <ModalFooter>+ <Button+ variant="secondary"+ onClick={() => setShowRegenerateConfirm(false)}+ >+ Cancel+ </Button>+ <Button+ variant="destructive"+ isDisabled={+ generateFetcher.state !== "idle" ||+ rerunPlanFetcher.state !== "idle"+ }+ isLoading={+ generateFetcher.state !== "idle" ||+ rerunPlanFetcher.state !== "idle"+ }+ onClick={() => {+ // Regenerate = re-plan from scratch, then rebuild steps from+ // the fresh plan. Kick a fresh DERIVE plan and arm the+ // awaiting machinery in regenerate mode; when the plan lands+ // it replaces the steps. (A stored plan is never reused —+ // that's what made planner changes invisible.)+ setIgnoredFailedJobId(+ planJob?.status === "Failed" ? planJob.id : null+ );+ generateModeRef.current = "regenerate";+ setIsAwaitingPlan(true);+ const formData = new FormData();+ formData.set("fresh", "1");+ rerunPlanFetcher.submit(formData, {+ method: "post",+ action: path.to.assemblyPlanRerun(id)+ });+ setShowRegenerateConfirm(false);+ }}+ >+ Regenerate+ </Button>+ </ModalFooter>+ </ModalContent>+ </Modal>+ )}{showRerunConfirm && (<Modalopen@@ -714,6 +1021,7 @@ type StepItemProps = {isSelected: boolean;dragControls?: DragControls;onSelect: () => void;+ onPreview: () => void;onDelete: () => void;};@@ -725,6 +1033,7 @@ function StepItem({isSelected,dragControls,onSelect,+ onPreview,onDelete}: StepItemProps) {const permissions = usePermissions();@@ -732,75 +1041,98 @@ function StepItem({const componentCount = step.componentNodeIds?.length ?? 0;+ const needsSupport = (step.warnings as { needsSupport?: boolean } | null)+ ?.needsSupport;+return (- <HStack+ <divclassName={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"+ "group relative flex w-full cursor-pointer select-none items-center gap-1.5 border-b border-border bg-card py-3 pl-1.5 pr-2.5 hover:bg-accent/30",+ isSelected && "bg-accent/40 hover:bg-accent/40")}onClick={onSelect}+ onDoubleClick={onPreview}+ title="Double-click to play this step">+ {isSelected && (+ <span+ aria-hidden+ className="pointer-events-none absolute inset-y-0 left-0 w-0.5 bg-primary"+ />+ )}<IconButtonaria-label="Drag handle"icon={<LuGripVertical />}variant="ghost"+ size="sm"disabled={isDisabled}- className="cursor-grab active:cursor-grabbing shrink-0"+ className="size-6 shrink-0 cursor-grab text-muted-foreground/50 hover:text-muted-foreground active:cursor-grabbing"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>+ <span className="w-5 shrink-0 text-right text-xs tabular-nums text-muted-foreground">+ {index + 1}+ </span>+ <ProcedureStepTypeIcon+ type={step.type ?? "Task"}+ className="size-3.5 shrink-0 text-muted-foreground"+ />+ <span+ className="min-w-0 flex-1 truncate text-sm text-foreground"+ title={title}+ >+ {title}+ </span>+ {needsSupport && (+ <span+ className="shrink-0 text-amber-600 dark:text-amber-500"+ title="A part in this step may tip once placed — consider a fixture or a second person."+ >+ <LuHand className="size-3.5" />+ </span>+ )}+ <span+ className="shrink-0 text-xs tabular-nums text-muted-foreground"+ title={`${componentCount} component${componentCount === 1 ? "" : "s"}`}+ >+ ×{componentCount}+ </span>+ <StepStatusControl+ stepId={step.id}+ status={step.status ?? "Todo"}+ isDisabled={isDisabled}+ />{!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>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="More"+ size="sm"+ variant="ghost"+ className="size-6 shrink-0 opacity-0 group-hover:opacity-100 data-[state=open]:opacity-100"+ icon={<LuEllipsisVertical />}+ 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>)}- </HStack>+ </div>);}++export default memo(AssemblyInstructionExplorer);diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionHeader.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionHeader.tsxindex 0a54ddb57a..94d0b98055 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionHeader.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionHeader.tsx@@ -17,6 +17,7 @@ import {LuEllipsisVertical,LuPanelLeft,LuPanelRight,+ LuRefreshCw,LuTrash} from "react-icons/lu";import { Link, useFetcher, useParams } from "react-router";@@ -55,6 +56,7 @@ const AssemblyInstructionHeader = () => {const nameFetcher = useFetcher<{}>();const statusFetcher = useFetcher<{}>();+ const invalidateFetcher = useFetcher<{ success: boolean }>();const [name, setName] = useState(instruction?.name ?? "");@@ -135,6 +137,21 @@ const AssemblyInstructionHeader = () => {</Link></DropdownMenuItem>)}+ <DropdownMenuItem+ disabled={+ !permissions.can("update", "production") ||+ invalidateFetcher.state !== "idle"+ }+ onClick={() =>+ invalidateFetcher.submit(null, {+ method: "post",+ action: path.to.assemblyModelInvalidate(id)+ })+ }+ >+ <DropdownMenuIcon icon={<LuRefreshCw />} />+ Re-convert Model+ </DropdownMenuItem><DropdownMenuItemdisabled={!permissions.can("delete", "production") ||diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsxindex d6b23b4402..960f4c55ec 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionProperties.tsx@@ -28,10 +28,14 @@ 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 { memo, useMemo, useState } from "react";+import {+ LuCirclePlus,+ LuMousePointerClick,+ LuTriangleAlert,+ 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";@@ -55,6 +59,10 @@ import AssemblyStepRequirements from "./AssemblyStepRequirements";type AssemblyInstructionPropertiesProps = {step: AssemblyInstructionStepRow | null;+ /** Zero-based index of the selected step; null when nothing is selected */+ stepIndex: number | null;+ /** Total step count, for the "Step N of M" header */+ stepCount: number;draftComponentNodeIds: string[] | null;/** Current viewer/Components-panel selection — marks the matching component rows */selectedNodeIds: string[];@@ -82,6 +90,8 @@ type AssemblyInstructionPropertiesProps = {const AssemblyInstructionProperties = ({step,+ stepIndex,+ stepCount,draftComponentNodeIds,selectedNodeIds,isAddingComponents,@@ -105,18 +115,62 @@ const AssemblyInstructionProperties = ({const { id: instructionId } = useParams();if (!instructionId) throw new Error("Could not find id");+ const componentCount = (draftComponentNodeIds ?? step?.componentNodeIds ?? [])+ .length;+ const title =+ (step &&+ (step.title ||+ describeStep(toStepDescriptor(step), graphIndex, units))) ||+ "Untitled step";+ const flagged =+ step != null &&+ stepPlanWarningsSchema.safeParse(step.warnings).data?.flagged === true;+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"+ spacing={0}+ className="w-[450px] bg-card h-full overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent border-l border-border text-sm">- <VStack spacing={2}>- <h3 className="text-xxs text-foreground/70 uppercase font-light tracking-wide">- Step- </h3>- </VStack>+ {/* Sticky panel header: which step you're editing, its status, and a+ one-glance summary (component count, flagged). */}+ <div className="sticky top-0 z-10 w-full min-w-0 flex-none border-b border-border bg-card/95 px-4 py-3 backdrop-blur">+ {step ? (+ <VStack spacing={1} className="w-full min-w-0">+ <HStack className="w-full min-w-0 items-center justify-between gap-2">+ <span className="shrink-0 text-xxs font-medium uppercase tracking-wide text-muted-foreground tabular-nums">+ {stepIndex != null+ ? `Step ${stepIndex + 1} of ${stepCount}`+ : "Step"}+ </span>+ <StepStatusPill status={normalizeStatus(step.status)} />+ </HStack>+ <h3 className="w-full min-w-0 truncate text-sm font-medium text-foreground">+ {title}+ </h3>+ <HStack className="w-full min-w-0 items-center gap-1.5 text-xs text-muted-foreground tabular-nums">+ <span>+ {componentCount}{" "}+ {componentCount === 1 ? "component" : "components"}+ </span>+ {flagged && (+ <>+ <span aria-hidden>·</span>+ <span className="inline-flex items-center gap-1 text-amber-600 dark:text-amber-500">+ <LuTriangleAlert className="size-3" />+ No collision-free path+ </span>+ </>+ )}+ </HStack>+ </VStack>+ ) : (+ <span className="text-xxs font-medium uppercase tracking-wide text-muted-foreground">+ Step+ </span>+ )}+ </div>{step ? (- <Tabs defaultValue="details" className="w-full">+ <Tabs defaultValue="details" className="w-full px-4 pb-2 pt-3"><TabsList className="w-full mb-4"><TabsTrigger className="flex-1" value="details">Details@@ -182,13 +236,60 @@ const AssemblyInstructionProperties = ({</TabsContent></Tabs>) : (- <Empty className="border-none">Select a step to edit it</Empty>+ <div className="flex w-full flex-1 flex-col items-center justify-center gap-2 px-6 py-16 text-center">+ <div className="flex size-10 items-center justify-center rounded-full bg-muted text-muted-foreground">+ <LuMousePointerClick className="size-5" />+ </div>+ <p className="text-sm font-medium text-foreground">+ No step selected+ </p>+ <p className="max-w-[30ch] text-xs text-muted-foreground">+ Pick a step from the list to edit its details, components, and+ materials.+ </p>+ </div>)}</VStack>);};-export default AssemblyInstructionProperties;+const stepStatusStyles: Record<string, string> = {+ Todo: "bg-red-500",+ Review: "bg-yellow-500",+ Done: "bg-green-500"+};++function normalizeStatus(status: string | null | undefined): string {+ return status && status in stepStatusStyles ? status : "Todo";+}++/** Compact status chip for the panel header — mirrors the Explorer's status dot. */+function StepStatusPill({ status }: { status: string }) {+ return (+ <span className="inline-flex h-5 shrink-0 items-center gap-1.5 rounded-md border border-border px-1.5 text-xxs font-medium text-foreground">+ <span+ className={cn(+ "block size-1.5 shrink-0 rounded-full",+ stepStatusStyles[status] ?? stepStatusStyles.Todo+ )}+ />+ {status}+ </span>+ );+}++/** The minimal descriptor `describeStep` needs to derive a title. */+function toStepDescriptor(step: AssemblyInstructionStepRow) {+ return {+ title: null,+ componentNodeIds: step.componentNodeIds ?? [],+ fastener: fastenerSchema.safeParse(step.fastener).data ?? null+ };+}++// Memoized: skips re-render on the route's per-frame motion-drag updates+// (draftMotion) — none of this panel's props change during a waypoint drag.+export default memo(AssemblyInstructionProperties);function StepForm({step,@@ -358,7 +459,7 @@ function StepForm({onChange={(value) => {setDescription(value);}}- className="[&_.is-empty]:text-muted-foreground min-h-[120px] p-4 rounded-lg border w-full"+ className="[&_.is-empty]:text-muted-foreground min-h-[88px] max-h-[360px] overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent p-3 rounded-lg border w-full"/></VStack>@@ -394,9 +495,17 @@ function StepForm({description="Operators must record this step to complete the operation"/>- <VStack spacing={2} className="w-full">+ <h4 className="w-full pt-1 text-xxs font-medium uppercase tracking-wide text-muted-foreground">+ Playback & components+ </h4>+ <VStack+ spacing={2}+ className="w-full rounded-lg border border-border bg-muted/40 p-3"+ ><HStack className="w-full justify-between">- <Label>Motion</Label>+ <Label className="text-xxs font-medium uppercase tracking-wide text-muted-foreground">+ Motion+ </Label>{!isDisabled && (<Buttonvariant={isEditingMotion ? "primary" : "secondary"}@@ -435,8 +544,13 @@ function StepForm({)}</VStack>- <VStack spacing={2} className="w-full">- <Label>Camera</Label>+ <VStack+ spacing={2}+ className="w-full rounded-lg border border-border bg-muted/40 p-3"+ >+ <Label className="text-xxs font-medium uppercase tracking-wide text-muted-foreground">+ Camera+ </Label><p className="text-xs text-muted-foreground">{hasCamera? "A saved view frames this step during playback."@@ -527,9 +641,14 @@ function StepComponentsEditor({);return (- <VStack spacing={2} className="w-full">+ <VStack+ spacing={2}+ className="w-full rounded-lg border border-border bg-muted/40 p-3"+ ><HStack className="w-full justify-between">- <Label>Components</Label>+ <Label className="text-xxs font-medium uppercase tracking-wide text-muted-foreground">+ Components+ </Label>{!isDisabled && (<Buttonvariant={isAddingComponents ? "primary" : "secondary"}diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsxindex 4c3b056452..4096699417 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepBom.tsx@@ -16,7 +16,11 @@ export default function AssemblyStepBom({}: AssemblyStepBomProps) {const groups = useMemo(() =>- graphIndex ? groupComponentNodeIds(componentNodeIds, graphIndex) : [],+ graphIndex+ ? groupComponentNodeIds(componentNodeIds, graphIndex).sort((a, b) =>+ a.name.localeCompare(b.name)+ )+ : [],[componentNodeIds, graphIndex]);diff --git a/apps/erp/app/modules/production/ui/Assemblies/ModelConvertProgress.tsx b/apps/erp/app/modules/production/ui/Assemblies/ModelConvertProgress.tsxnew file mode 100644index 0000000000..4ef8d26b72--- /dev/null+++ b/apps/erp/app/modules/production/ui/Assemblies/ModelConvertProgress.tsx@@ -0,0 +1,142 @@+import { BarProgress, Button } from "@carbon/react";+import { useEffect, useRef, useState } from "react";+import { LuCheck, LuLoaderCircle } from "react-icons/lu";+import { useFetcher } from "react-router";+import { path } from "~/utils/path";++type ConvertStatus = {+ phase: "downloading" | "converting" | "uploading" | null;+ done: number;+ total: number;+};++const STEPS: { key: NonNullable<ConvertStatus["phase"]>; label: string }[] = [+ { key: "downloading", label: "Reading the CAD file" },+ { key: "converting", label: "Building the 3D geometry" },+ { key: "uploading", label: "Preparing the viewer" }+];++const POLL_MS = 1000;++function formatBytes(n: number) {+ if (n >= 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;+ if (n >= 1024) return `${Math.round(n / 1024)} KB`;+ return `${n} B`;+}++function formatElapsed(seconds: number) {+ if (seconds < 60) return `${seconds}s`;+ return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;+}++/**+ * Live checklist for a running model conversion (same visual language as the+ * backup/restore progress modal): per-phase check/spinner/dot, a real progress+ * bar, byte counts for the download phase, and an elapsed clock. Falls back to+ * an indeterminate first step while the job is still queued (no live signal).+ */+export function ModelConvertProgress({+ modelUploadId,+ instructionId+}: {+ modelUploadId: string;+ instructionId: string;+}) {+ const cancelFetcher = useFetcher<{ success: boolean }>();+ const statusFetcher = useFetcher<ConvertStatus>();+ const loadRef = useRef(statusFetcher.load);+ loadRef.current = statusFetcher.load;++ const [elapsed, setElapsed] = useState(0);++ useEffect(() => {+ const url = path.to.api.modelConvertStatus(modelUploadId);+ loadRef.current(url);+ const poll = setInterval(() => loadRef.current(url), POLL_MS);+ const clock = setInterval(() => setElapsed((s) => s + 1), 1000);+ return () => {+ clearInterval(poll);+ clearInterval(clock);+ };+ }, [modelUploadId]);++ const status = statusFetcher.data ?? { phase: null, done: 0, total: 0 };+ const activeIndex = status.phase+ ? STEPS.findIndex((s) => s.key === status.phase)+ : 0;+ const queued = status.phase === null;++ // Real fraction: completed phases + download sub-progress when known.+ const subProgress =+ status.phase === "downloading" && status.total > 0+ ? Math.min(status.done / status.total, 1)+ : 0;+ const fraction = queued+ ? 0+ : Math.min((activeIndex + (subProgress || 0.15)) / STEPS.length, 0.97);++ const detail =+ status.phase === "downloading" && status.total > 0+ ? `${formatBytes(status.done)} / ${formatBytes(status.total)} · ${formatElapsed(elapsed)}`+ : `${formatElapsed(elapsed)}`;++ return (+ <div className="flex h-full w-full items-center justify-center p-6">+ <div className="flex w-[340px] flex-col gap-4 rounded-xl border border-border bg-card p-6 shadow-lg">+ <BarProgress progress={fraction} max={1} activeClassName="bg-primary" />+ <div className="flex flex-col gap-2.5">+ {STEPS.map((step, i) => {+ const state =+ !queued && i < activeIndex+ ? "done"+ : i === activeIndex+ ? "active"+ : "pending";+ return (+ <div key={step.key} className="flex items-center gap-2.5 text-sm">+ <span className="flex h-5 w-5 items-center justify-center">+ {state === "done" ? (+ <LuCheck className="h-4 w-4 text-emerald-500 animate-in fade-in zoom-in-75 motion-reduce:animate-none" />+ ) : state === "active" ? (+ <LuLoaderCircle className="h-4 w-4 animate-spin text-primary motion-reduce:animate-none" />+ ) : (+ <span className="h-1.5 w-1.5 rounded-full bg-muted-foreground/30" />+ )}+ </span>+ <span+ className={+ state === "pending"+ ? "text-muted-foreground/40"+ : state === "active"+ ? "text-foreground"+ : "text-muted-foreground"+ }+ >+ {i === 0 && queued ? "Waiting for a worker…" : step.label}+ </span>+ </div>+ );+ })}+ </div>+ <div className="flex items-center justify-between">+ <p className="text-xs tabular-nums text-muted-foreground">{detail}</p>+ <cancelFetcher.Form+ method="post"+ action={path.to.assemblyJobsCancel(instructionId)}+ >+ <input type="hidden" name="kind" value="convert" />+ <Button+ type="submit"+ size="sm"+ variant="ghost"+ isLoading={cancelFetcher.state !== "idle"}+ isDisabled={cancelFetcher.state !== "idle"}+ >+ Cancel+ </Button>+ </cancelFetcher.Form>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/erp/app/modules/production/ui/Assemblies/index.ts b/apps/erp/app/modules/production/ui/Assemblies/index.tsindex ed4b1a25c6..1d1dbe66d0 100644--- a/apps/erp/app/modules/production/ui/Assemblies/index.ts+++ b/apps/erp/app/modules/production/ui/Assemblies/index.ts@@ -5,3 +5,4 @@ export { default as AssemblyInstructionProperties } from "./AssemblyInstructionPexport { default as AssemblyInstructionStatus } from "./AssemblyInstructionStatus";export { default as AssemblyInstructionsTable } from "./AssemblyInstructionsTable";export { default as AssemblyStepMaterials } from "./AssemblyStepMaterials";+export { ModelConvertProgress } from "./ModelConvertProgress";diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.jsonindex efe7bc9b77..76d5ecc6b9 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-12T19:03:31.549Z",- "totalTools": 1304,+ "generated": "2026-07-12T23:58:14.390Z",+ "totalTools": 1306,"modules": 15,"tools": [{@@ -19983,6 +19983,31 @@]}},+ {+ "name": "production_invalidateAssemblyModelCache",+ "module": "production",+ "classification": "WRITE",+ "description": "invalidate assembly model cache",+ "paramCount": 1,+ "serviceParams": [+ "client",+ "modelUploadId"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "modelUploadId": {+ "type": "string"+ }+ },+ "required": [+ "modelUploadId"+ ]+ }+ },{"name": "production_upsertAssemblyInstructionStep","module": "production",@@ -20130,6 +20155,50 @@]}},+ {+ "name": "production_reassignAssemblyStepComponents",+ "module": "production",+ "classification": "WRITE",+ "description": "reassign assembly step components",+ "paramCount": 4,+ "serviceParams": [+ "db",+ "data"+ ],+ "injectAuth": [+ "companyId"+ ],+ "schema": {+ "type": "object",+ "properties": {+ "assemblyInstructionId": {+ "type": "string"+ },+ "targetStepId": {+ "type": "string"+ },+ "componentNodeIds": {+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "mode": {+ "type": "string",+ "enum": [+ "move",+ "duplicate",+ "remove"+ ]+ }+ },+ "required": [+ "assemblyInstructionId",+ "componentNodeIds",+ "mode"+ ]+ }+ },{"name": "production_updateAssemblyInstructionStepStatus","module": "production",diff --git a/apps/erp/app/routes/api+/model.convert-status.$modelUploadId.ts b/apps/erp/app/routes/api+/model.convert-status.$modelUploadId.tsnew file mode 100644index 0000000000..42404021d8--- /dev/null+++ b/apps/erp/app/routes/api+/model.convert-status.$modelUploadId.ts@@ -0,0 +1,58 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";+import type { LoaderFunctionArgs } from "react-router";++const NO_SIGNAL = { phase: null, done: 0, total: 0 } as const;++// Polled by the assembly page while a model converts: resolves the in-flight+// convert job for the model, then proxies the geometry service's live phase+// (downloading / converting / uploading + byte counts for the download).+// phase: null means no live signal — job still queued, already finished, or+// the service doesn't track it — and the client falls back to its coarse+// processingStatus rendering.+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "production",+ role: "employee"+ });+ const { modelUploadId } = params;+ if (!modelUploadId) throw new Response("Not found", { status: 404 });++ const job = await client+ .from("assemblyPlanJob")+ .select("id")+ .eq("modelUploadId", modelUploadId)+ .eq("companyId", companyId)+ .eq("kind", "convert")+ .eq("status", "Processing")+ .order("createdAt", { ascending: false })+ .limit(1)+ .maybeSingle();++ if (!job.data || !ASSEMBLER_SERVICE_URL) return NO_SIGNAL;++ try {+ const response = await fetch(+ `${ASSEMBLER_SERVICE_URL}/convert/status/${job.data.id}`,+ {+ headers: ASSEMBLER_SERVICE_API_KEY+ ? { Authorization: `Bearer ${ASSEMBLER_SERVICE_API_KEY}` }+ : {},+ signal: AbortSignal.timeout(3000)+ }+ );+ if (!response.ok) return NO_SIGNAL;+ const body = (await response.json()) as {+ phase?: string;+ done?: number;+ total?: number;+ };+ return {+ phase: body.phase ?? null,+ done: body.done ?? 0,+ total: body.total ?? 0+ };+ } catch {+ return NO_SIGNAL;+ }+}diff --git a/apps/erp/app/routes/x+/assembly+/$id.jobs.cancel.tsx b/apps/erp/app/routes/x+/assembly+/$id.jobs.cancel.tsxnew file mode 100644index 0000000000..ca7ff1571d--- /dev/null+++ b/apps/erp/app/routes/x+/assembly+/$id.jobs.cancel.tsx@@ -0,0 +1,91 @@+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";++/**+ * Cancels a stuck convert or plan job for the instruction's model by failing+ * its Processing rows, so the retry/generate buttons re-enable. This releases+ * the UI state only — an Inngest run that is genuinely still working isn't+ * killed, but a later completion just overwrites the failed marker, which is+ * harmless. The common case is a job orphaned by a geometry-service outage.+ */+export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId } = await requirePermissions(request, {+ update: "production"+ });++ const { id } = params;+ if (!id) throw new Error("Could not find id");++ const formData = await request.formData();+ const kind = String(formData.get("kind"));+ if (kind !== "convert" && kind !== "plan") {+ return data(+ { success: false },+ await flash(request, error(null, "Invalid job kind"))+ );+ }++ const instruction = await client+ .from("assemblyInstruction")+ .select("modelUploadId")+ .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")+ )+ );+ }+ const modelUploadId = instruction.data.modelUploadId;++ const cancelled = await client+ .from("assemblyPlanJob")+ .update({+ status: "Failed",+ error: "Cancelled by user",+ updatedAt: new Date().toISOString()+ })+ .eq("modelUploadId", modelUploadId)+ .eq("companyId", companyId)+ .eq("kind", kind)+ .eq("status", "Processing")+ .select("id");++ if (cancelled.error) {+ return data(+ { success: false },+ await flash(request, error(cancelled.error, "Could not cancel the job"))+ );+ }++ if (kind === "convert") {+ await client+ .from("modelUpload")+ .update({+ processingStatus: "Failed",+ processingError: "Cancelled by user"+ })+ .eq("id", modelUploadId)+ .eq("companyId", companyId)+ .in("processingStatus", ["Queued", "Processing"]);+ }++ return data(+ { success: true },+ await flash(+ request,+ success(+ cancelled.data.length > 0 ? "Job cancelled" : "No running job to cancel"+ )+ )+ );+}diff --git a/apps/erp/app/routes/x+/assembly+/$id.model.convert.tsx b/apps/erp/app/routes/x+/assembly+/$id.model.convert.tsxindex 36f612ef60..472bef913f 100644--- a/apps/erp/app/routes/x+/assembly+/$id.model.convert.tsx+++ b/apps/erp/app/routes/x+/assembly+/$id.model.convert.tsx@@ -5,6 +5,7 @@ import { trigger } from "@carbon/jobs";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { getAssemblyModelState } from "~/modules/production";+import { isAssemblerServiceHealthy } from "~/modules/production/production.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -55,6 +56,19 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ if (!(await isAssemblerServiceHealthy())) {+ return data(+ { success: false },+ await flash(+ request,+ error(+ null,+ "The geometry service is unavailable — model conversion can't run right now."+ )+ )+ );+ }+await trigger("assembly-convert", {companyId,modelUploadId: instruction.data.modelUpload.id,diff --git a/apps/erp/app/routes/x+/assembly+/$id.model.invalidate.tsx b/apps/erp/app/routes/x+/assembly+/$id.model.invalidate.tsxnew file mode 100644index 0000000000..95b0a89606--- /dev/null+++ b/apps/erp/app/routes/x+/assembly+/$id.model.invalidate.tsx@@ -0,0 +1,62 @@+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 { invalidateAssemblyModelCache } from "~/modules/production";++/**+ * Explicit cache invalidation for the instruction's model: drops the cached+ * motion plans and the conversion artifacts (glb/graph), then kicks a fresh+ * conversion. The escape hatch for stale caches — e.g. after a geometry+ * service upgrade whose output no longer matches previously stored artifacts.+ */+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")+ .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")+ )+ );+ }+ const modelUploadId = instruction.data.modelUploadId;++ const invalidated = await invalidateAssemblyModelCache(client, modelUploadId);+ if (invalidated.error) {+ return data(+ { success: false },+ await flash(+ request,+ error(invalidated.error, "Could not invalidate the model cache")+ )+ );+ }++ await trigger("assembly-convert", { companyId, modelUploadId, userId });++ return data(+ { success: true },+ await flash(+ request,+ success("Model cache invalidated; re-converting from the source file")+ )+ );+}diff --git a/apps/erp/app/routes/x+/assembly+/$id.plan.rerun.tsx b/apps/erp/app/routes/x+/assembly+/$id.plan.rerun.tsxindex 2837014604..bd97d94b1e 100644--- a/apps/erp/app/routes/x+/assembly+/$id.plan.rerun.tsx+++ b/apps/erp/app/routes/x+/assembly+/$id.plan.rerun.tsx@@ -9,6 +9,7 @@ import {getLatestAssemblyPlanJob,isAssemblyPlanRunning} from "~/modules/production";+import { isAssemblerServiceHealthy } from "~/modules/production/production.server";/*** Re-runs motion planning over the instruction's converted model. When the@@ -26,6 +27,12 @@ export async function action({ request, params }: ActionFunctionArgs) {const { id } = params;if (!id) throw new Error("Could not find id");+ // `fresh` forces a from-scratch DERIVE plan (re-detects grouping/swarms and+ // re-orders) even when steps exist — used by "Regenerate Steps". Without it,+ // an instruction with steps re-plans in order-preserving re-motion mode.+ const formData = await request.formData();+ const fresh = formData.get("fresh") === "1";+const instruction = await client.from("assemblyInstruction").select("modelUploadId, modelUpload(processingStatus)")@@ -53,6 +60,20 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ // Every path here triggers the planner, which needs the geometry service.+ if (!(await isAssemblerServiceHealthy())) {+ return data(+ { success: false },+ await flash(+ request,+ error(+ null,+ "The geometry service is unavailable — motion planning can't run right now."+ )+ )+ );+ }+const planJob = await getLatestAssemblyPlanJob(client,instruction.data.modelUploadId@@ -63,14 +84,22 @@ export async function action({ request, params }: ActionFunctionArgs) {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.+ if (+ planJob.data?.status === "Queued" ||+ planJob.data?.status === "Processing"+ ) {+ // Stale row the guard above already ruled non-live: a Queued event that+ // was never picked up, or a Processing run whose worker is gone (crash,+ // or the in-memory dev Inngest server restarting mid-run). 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",+ error:+ planJob.data.status === "Queued"+ ? "Planning never started — the job event was lost"+ : "Planning run was lost (worker restarted mid-run)",updatedAt: new Date().toISOString()}).eq("id", planJob.data.id)@@ -84,7 +113,43 @@ export async function action({ request, params }: ActionFunctionArgs) {.select("id", { count: "exact", head: true }).eq("assemblyInstructionId", id).eq("companyId", companyId);- const hasSteps = (stepCount.count ?? 0) > 0;+ // `fresh` re-derives from scratch (no order preservation), so treat it like+ // "no steps yet" for the trigger below.+ const hasSteps = !fresh && (stepCount.count ?? 0) > 0;++ // Regenerate (fresh) replaces all steps once the plan lands — refuse up front+ // if any step is manually authored or Done, rather than running the planner+ // for ~15s and only then failing the regenerate.+ if (fresh && (stepCount.count ?? 0) > 0) {+ const locked = await client+ .from("assemblyInstructionStep")+ .select("id", { count: "exact", head: true })+ .eq("assemblyInstructionId", id)+ .eq("companyId", companyId)+ .or("planConfidence.eq.manual,status.eq.Done");+ if ((locked.count ?? 0) > 0) {+ return data(+ { success: false },+ await flash(+ request,+ error(+ null,+ "Some steps are manually authored or Done — reset or delete them before regenerating"+ )+ )+ );+ }+ }++ // Auto-detected groups (swarms) are materialized as `assemblyUnit` rows so+ // they show/edit like authored units — but that FREEZES the detection: on the+ // next plan `loadPlanUnits` feeds them back as caller units, so the planner+ // merges them as-is and never re-runs swarm detection (which is where things+ // like board-mounted-component absorption happen). A from-scratch regenerate+ // must re-derive them. We DON'T delete the rows here (a delete-then-failed-+ // re-plan would strand the model ungrouped); instead `reDetectUnits` below+ // tells the worker to omit auto-units for this run so detection re-runs, and+ // step generation swaps the rows atomically once the new plan lands.// Create the job row before sending the event so the UI reflects the run// immediately (the worker adopts it via planJobId). Best-effort: planning@@ -100,7 +165,8 @@ export async function action({ request, params }: ActionFunctionArgs) {companyId,userId,...(created.data?.id ? { planJobId: created.data.id } : {}),- ...(hasSteps ? { reMotionFor: id } : {})+ ...(hasSteps ? { reMotionFor: id } : {}),+ ...(fresh ? { reDetectUnits: true } : {})});return data(@@ -110,7 +176,9 @@ export async function action({ request, params }: ActionFunctionArgs) {success(hasSteps? "Re-planning motions in the current step order — steps update when it finishes"- : "Motion planning started — regenerate steps when it finishes"+ : fresh+ ? "Re-planning from scratch — steps rebuild automatically when it finishes"+ : "Motion planning started — steps generate when it finishes")));diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.components.reassign.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.components.reassign.tsxnew file mode 100644index 0000000000..a8b9d226bd--- /dev/null+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.components.reassign.tsx@@ -0,0 +1,73 @@+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 {+ assemblyStepComponentsReassignValidator,+ reassignAssemblyStepComponents,+ syncAssemblyStepMaterialsFromMappings+} from "~/modules/production";+import { getDatabaseClient } from "~/services/database.server";++// Assign the current selection to an existing step from the BOM tree. `move`+// pulls the components off whatever steps they were on; `duplicate` leaves those+// alone. The reassignment itself is one Kysely transaction; material sync (from+// the component→BOM mappings) is a best-effort follow-up, mirroring the+// per-step components autosave route.+export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "production"+ });++ const { id } = params;+ if (!id) throw notFound("id is not found");++ const validation = await validator(+ assemblyStepComponentsReassignValidator+ ).validate(await request.formData());++ if (validation.error) {+ return data(+ { success: false },+ await flash(+ request,+ error(validation.error, "Failed to assign components")+ )+ );+ }++ const { targetStepId, componentNodeIds, mode } = validation.data;++ try {+ await reassignAssemblyStepComponents(getDatabaseClient(), {+ assemblyInstructionId: id,+ companyId,+ targetStepId,+ componentNodeIds,+ mode,+ updatedBy: userId+ });+ } catch (err) {+ return data(+ { success: false },+ await flash(request, error(err, "Failed to assign components"))+ );+ }++ // Pull the mapped BOM items for the added components onto the target step.+ // Nothing to sync for a pure remove (no target step).+ if (targetStepId) {+ await syncAssemblyStepMaterialsFromMappings(client, {+ assemblyInstructionId: id,+ companyId,+ userId,+ stepIds: [targetStepId],+ onlyComponentNodeIds: componentNodeIds+ });+ }++ return { success: true };+}diff --git a/apps/erp/app/routes/x+/assembly+/$id.steps.generate.tsx b/apps/erp/app/routes/x+/assembly+/$id.steps.generate.tsxindex f9942565bf..aacef61e68 100644--- a/apps/erp/app/routes/x+/assembly+/$id.steps.generate.tsx+++ b/apps/erp/app/routes/x+/assembly+/$id.steps.generate.tsx@@ -10,11 +10,18 @@ import {getLatestAssemblyPlanJob,isAssemblyPlanRunning} from "~/modules/production";+import { isAssemblerServiceHealthy } from "~/modules/production/production.server";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);+ // bypassRls: generateAssemblyStepsFromPlan materializes auto-detected units+ // (a system/derived write) whose INSERT/DELETE RLS needs+ // production_create/_delete — which this update-authorized action's user may+ // lack. Authorization is still gated on production_update above; the service+ // role only bypasses row-level policy for the derived write (companyId-scoped).const { client, companyId, userId } = await requirePermissions(request, {- update: "production"+ update: "production",+ bypassRls: true});const { id } = params;@@ -32,22 +39,43 @@ export async function action({ request, params }: ActionFunctionArgs) {});if (result.ok) {+ const base =+ mode === "regenerate"+ ? `Regenerated ${result.created} steps from the motion plan`+ : `Generated ${result.created} steps from the motion plan`;+ // Some geometry has no BOM match, so those parts got no material — point the+ // user at Match BOM rather than leaving a silent gap.+ const unmapped = result.unmappedComponentCount ?? 0;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`+ unmapped > 0+ ? `${base}. ${unmapped} component${unmapped === 1 ? "" : "s"} have no BOM match — use Match BOM to link their materials.`+ : base)));}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+ // No plan yet — planning is lazy, so this click is what starts it, which+ // needs the geometry service. Refuse when it's down (a stale tab could POST+ // here after the loader gated the button).+ if (!(await isAssemblerServiceHealthy())) {+ return data(+ { success: false },+ await flash(+ request,+ error(+ null,+ "The geometry service is unavailable — motion planning can't run right now."+ )+ )+ );+ }+ // 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([diff --git a/apps/erp/app/routes/x+/assembly+/$id.tsx b/apps/erp/app/routes/x+/assembly+/$id.tsxindex a0a3c8e040..eb1a0c60cd 100644--- a/apps/erp/app/routes/x+/assembly+/$id.tsx+++ b/apps/erp/app/routes/x+/assembly+/$id.tsx@@ -47,9 +47,11 @@ import {toViewerStep,upsertAssemblyInstruction} from "~/modules/production";+import { isAssemblerServiceHealthy } from "~/modules/production/production.server";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 { ModelConvertProgress } from "~/modules/production/ui/Assemblies/ModelConvertProgress";import type { Handle } from "~/utils/handle";import { getPrivateUrl, path } from "~/utils/path";@@ -74,12 +76,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getAssemblyStandardNotes(client, companyId)]);- if (instruction.error) {+ const instructionError = instruction.error;+ if (instructionError || !instruction.data) {+ // A deleted/absent instruction is a normal not-found (PGRST116 = no rows),+ // not a server error. A stale tab left open on a deleted instruction keeps+ // revalidating (realtime + poll); logging error() on every hit spams the+ // service log. Log only genuine DB errors; redirect quietly otherwise.+ // Entered when there's an error OR no row. Not-found = a PGRST116 (no rows)+ // error, or the no-error-no-row case; a genuine DB error falls through to+ // error() so it's still logged.+ const notFound = !instructionError || instructionError.code === "PGRST116";throw redirect(path.to.assemblyInstructions,await flash(request,- error(instruction.error, "Failed to load assembly instruction")+ notFound+ ? { success: false, message: "Assembly instruction not found" }+ : error(instructionError, "Failed to load assembly instruction")));}@@ -92,7 +105,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {planJob,componentMappings,units,- bomMaterials+ bomMaterials,+ assemblerAvailable] = await Promise.all([getAssemblyInstructionStepRequirements(client, stepIds),getAssemblyInstructionStepMaterials(client, stepIds),@@ -110,7 +124,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {: Promise.resolve({ data: [] }),instruction.data.itemId? getFlattenedBomMaterials(client, instruction.data.itemId, companyId)- : Promise.resolve([])+ : Promise.resolve([]),+ isAssemblerServiceHealthy()]);return {@@ -123,7 +138,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {plan,planJob: planJob.data ?? null,componentMappings: componentMappings.data ?? [],- bomMaterials+ bomMaterials,+ assemblerAvailable};}@@ -182,7 +198,8 @@ export default function AssemblyInstructionRoute() {plan,planJob,componentMappings,- bomMaterials+ bomMaterials,+ assemblerAvailable} = useLoaderData<typeof loader>();const permissions = usePermissions();const mode = useMode();@@ -212,16 +229,27 @@ export default function AssemblyInstructionRoute() {// Components panel, and (while authoring a step) stages the step's draft components.const [selectedNodeIds, setSelectedNodeIds] = useState<string[]>([]);const [hiddenNodeIds, setHiddenNodeIds] = useState<string[]>([]);+ // Isolate/focus: picking components in the Components panel shows ONLY them in+ // the viewer (everything else hidden) so the part can be inspected alone.+ // Cleared by a viewer/3D pick, a step change, add-mode, or an empty selection.+ const [focusedNodeIds, setFocusedNodeIds] = 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;+ const { selectedStep, activeStepIndex } = useMemo(() => {+ const step =+ steps.find((candidate) => candidate.id === selectedStepId) ??+ steps[0] ??+ null;+ return {+ selectedStep: step,+ activeStepIndex: step+ ? steps.findIndex((candidate) => candidate.id === step.id)+ : 0+ };+ }, [steps, selectedStepId]);// 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).@@ -244,6 +272,9 @@ export default function AssemblyInstructionRoute() {[componentsFetcher, id]);+ // Bumped to preview (play) the active step — a double-click in the Explorer.+ const [playStepNonce, setPlayStepNonce] = useState(0);+const onSelectStep = useCallback((stepId: string, options?: { selectComponents?: boolean }) => {setSelectedStepId(stepId);@@ -252,6 +283,8 @@ export default function AssemblyInstructionRoute() {// Leave any open motion-path edit session when moving to another step.setEditingStepId(null);setDraftMotion(null);+ // Changing steps drops any isolate — the new step's parts should be visible.+ setFocusedNodeIds([]);// 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@@ -266,12 +299,25 @@ export default function AssemblyInstructionRoute() {[]);+ // Double-clicking a step previews it: select it, then bump the nonce so the+ // player animates its insertion (single-click just shows it seated).+ const onPreviewStep = useCallback(+ (stepId: string) => {+ onSelectStep(stepId);+ setPlayStepNonce((nonce) => nonce + 1);+ },+ [onSelectStep]+ );+// 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);+ // A viewer/3D pick (or the details-panel list) drops any isolate — only+ // the Components panel isolates, via onFocusComponents below.+ setFocusedNodeIds([]);if (isAddingComponents && !isDisabled && selectedStep) {const base =draftComponentNodeIds ?? selectedStep.componentNodeIds ?? [];@@ -289,11 +335,28 @@ export default function AssemblyInstructionRoute() {]);+ // The Components panel selects AND isolates: picking a component shows only it+ // in the viewer. While add-mode is on, panel picks append to the step instead+ // (delegated to onSelectComponents) and don't isolate — you need the whole+ // model visible to pick what to add.+ const onFocusComponents = useCallback(+ (nodeIds: string[]) => {+ if (isAddingComponents) {+ onSelectComponents(nodeIds);+ return;+ }+ setSelectedNodeIds(nodeIds);+ setFocusedNodeIds(nodeIds);+ },+ [isAddingComponents, onSelectComponents]+ );+// 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([]);+ setFocusedNodeIds([]);}, []);const onStopAddComponents = useCallback(@@ -320,6 +383,23 @@ export default function AssemblyInstructionRoute() {const viewerSteps = useMemo(() => steps.map(toViewerStep), [steps]);+ // Per-step requirements/materials for the properties panel — memoized so a+ // per-frame motion-drag re-render (draftMotion) doesn't hand the panel new+ // array identities and re-render it.+ const activeStepId = selectedStep?.id ?? null;+ const stepRequirements = useMemo(+ () =>+ activeStepId ? requirements.filter((r) => r.stepId === activeStepId) : [],+ [requirements, activeStepId]+ );+ const selectedStepMaterials = useMemo(+ () =>+ activeStepId+ ? stepMaterials.filter((m) => m.stepId === activeStepId)+ : [],+ [stepMaterials, activeStepId]+ );+// 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(@@ -336,15 +416,22 @@ export default function AssemblyInstructionRoute() {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 =+ // artifacts may still be in flight. A job that is actually running gets a+ // fast poll + live progress; "Idle" without artifacts (pre-pickup window, or+ // nothing triggered yet) polls gently — an eternal fast loop on the heavy+ // route loader makes the whole page feel sluggish.+ const isActivelyConverting =!glbPath &&(modelUpload?.processingStatus === "Queued" ||- modelUpload?.processingStatus === "Processing" ||- modelUpload?.processingStatus === "Idle");+ modelUpload?.processingStatus === "Processing");+ const isAwaitingPickup = !glbPath && modelUpload?.processingStatus === "Idle";+ const isConverting = isActivelyConverting || isAwaitingPickup;const revalidator = useRevalidator();- useInterval(() => revalidator.revalidate(), isConverting ? 5000 : null);+ useInterval(+ () => revalidator.revalidate(),+ isActivelyConverting ? 2000 : isAwaitingPickup ? 5000 : null+ );+ const cancelPlanFetcher = useFetcher<{ success: boolean }>();const retryFetcher = useFetcher<{}>();// --- Motion path + camera editing (viewer-driven) ------------------------@@ -433,6 +520,7 @@ export default function AssemblyInstructionRoute() {selectedStepId={selectedStep?.id ?? null}isDisabled={isDisabled}isConverting={isConverting}+ assemblerAvailable={assemblerAvailable}graphIndex={graphIndex}hasPlan={Boolean(plan)}planJob={planJob}@@ -441,18 +529,32 @@ export default function AssemblyInstructionRoute() {bomMaterials={bomMaterials}selectedNodeIds={selectedNodeIds}onSelectStep={onSelectStep}- onHighlightComponents={onSelectComponents}+ onPreviewStep={onPreviewStep}+ onHighlightComponents={onFocusComponents}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">+ <div className="absolute left-1/2 top-3 z-10 flex -translate-x-1/2 items-center gap-2 rounded-full border border-border bg-card px-3 py-1.5 shadow-lg"><Spinner className="h-3.5 w-3.5" />- <span className="whitespace-nowrap text-xs text-muted-foreground">- Planning motion+ <span className="whitespace-nowrap text-xs font-medium text-foreground">+ Planning motion…</span>+ <cancelPlanFetcher.Form+ method="post"+ action={path.to.assemblyJobsCancel(id!)}+ >+ <input type="hidden" name="kind" value="plan" />+ <button+ type="submit"+ disabled={cancelPlanFetcher.state !== "idle"}+ className="text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline disabled:opacity-50"+ >+ Cancel+ </button>+ </cancelPlanFetcher.Form></div>)}{glbPath && graphPath ? (@@ -470,6 +572,7 @@ export default function AssemblyInstructionRoute() {graphUrl={getPrivateUrl(graphPath)}steps={viewerSteps}activeStepIndex={Math.max(activeStepIndex, 0)}+ playStepNonce={playStepNonce}onStepChange={(index) => {const step = steps[index];if (step)@@ -481,6 +584,7 @@ export default function AssemblyInstructionRoute() {onGraphLoaded={setGraph}highlightedNodeIds={selectedNodeIds}hiddenNodeIds={hiddenNodeIds}+ focusedNodeIds={focusedNodeIds}readOnly={isDisabled}editMotion={editingStepId &&@@ -492,25 +596,27 @@ export default function AssemblyInstructionRoute() {onMotionChange={onMotionChange}units={namedUnits}suppressFallbackMotions={isPlanning}+ componentPickerActive={isAddingComponents}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>+ ) : (isActivelyConverting || isAwaitingPickup) &&+ modelUpload?.id ? (+ <ModelConvertProgress+ modelUploadId={modelUpload.id}+ instructionId={id!}+ />) : modelUpload?.processingStatus === "Failed" ? (<Empty>- <p className="text-sm text-muted-foreground max-w-[320px] text-center">+ <p className="text-sm font-medium text-foreground">+ Couldn't prepare this model+ </p>+ <p className="max-w-[320px] text-center text-sm text-muted-foreground">{modelUpload?.processingError ??- "Model conversion failed"}+ "Something went wrong converting the CAD file for 3D viewing."}</p><retryFetcher.Formmethod="post"@@ -525,15 +631,18 @@ export default function AssemblyInstructionRoute() {!permissions.can("update", "production")}>- Retry conversion+ Try again</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 className="text-sm font-medium text-foreground">+ Model not ready yet+ </p>+ <p className="max-w-[320px] text-center text-sm text-muted-foreground">+ This model hasn't been prepared for 3D viewing. It'll+ appear here once processing starts.</p></Empty>)}@@ -543,13 +652,15 @@ export default function AssemblyInstructionRoute() {<AssemblyInstructionPropertieskey={selectedStep?.id ?? "empty"}step={selectedStep}+ stepIndex={selectedStep ? activeStepIndex : null}+ stepCount={steps.length}draftComponentNodeIds={draftComponentNodeIds}selectedNodeIds={selectedNodeIds}isAddingComponents={isAddingComponents}isDisabled={isDisabled}graphIndex={graphIndex}units={namedUnits}- onSelectComponents={onSelectComponents}+ onSelectComponents={onFocusComponents}onStartAddComponents={onStartAddComponents}onStopAddComponents={onStopAddComponents}onRemoveComponents={onRemoveComponents}@@ -558,21 +669,8 @@ export default function AssemblyInstructionRoute() {onStopEditMotion={onStopEditMotion}onSetCamera={onSetCamera}onClearCamera={onClearCamera}- requirements={- selectedStep- ? requirements.filter(- (requirement) =>- requirement.stepId === selectedStep.id- )- : []- }- stepMaterials={- selectedStep- ? stepMaterials.filter(- (material) => material.stepId === selectedStep.id- )- : []- }+ requirements={stepRequirements}+ stepMaterials={selectedStepMaterials}bomMaterials={bomMaterials}standardNotes={standardNotes}/>diff --git a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.delete.tsx b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.delete.tsxindex 91cc229c56..3e081be320 100644--- a/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.delete.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.purchasing.$supplierPartId.delete.tsx@@ -16,7 +16,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { supplierPartId } = params;if (!supplierPartId) throw notFound("supplierPartId not found");- // @ts-expect-error TS2589 — Supabase joined-select type instantiation too deep+ // @ts-ignore TS2589 — Supabase joined-select type instantiation too deep; it+ // fires only under some checker states, so ignore (not expect-error) stays+ // green whether or not it triggers.const result = await client.from("supplierPart").select("id, supplierId, supplier:supplierId(name)")diff --git a/apps/erp/app/routes/x+/production+/assemblies.new.tsx b/apps/erp/app/routes/x+/production+/assemblies.new.tsxindex 579c2d2320..14b44082bf 100644--- a/apps/erp/app/routes/x+/production+/assemblies.new.tsx+++ b/apps/erp/app/routes/x+/production+/assemblies.new.tsx@@ -13,7 +13,10 @@ import {getModelForItem,upsertAssemblyInstruction} from "~/modules/production";-import { requireAssembliesInternal } from "~/modules/production/production.server";+import {+ isAssemblerServiceHealthy,+ requireAssembliesInternal+} from "~/modules/production/production.server";import AssemblyInstructionForm from "~/modules/production/ui/Assemblies/AssemblyInstructionForm";import { path } from "~/utils/path";@@ -96,6 +99,24 @@ export async function action({ request }: ActionFunctionArgs) {);}+ // A model that still needs converting can't become a usable instruction while+ // the geometry service is down — refuse rather than create a stuck record.+ const needsConversion =+ modelState === "convertible" || modelState === "failed";+ const assemblerHealthy = await isAssemblerServiceHealthy();+ if (needsConversion && !assemblerHealthy) {+ return data(+ {},+ await flash(+ request,+ error(+ null,+ "The geometry service is unavailable — model conversion can't run right now. Try again shortly."+ )+ )+ );+ }+const create = await upsertAssemblyInstruction(client, {name: derived.item.name || "Assembly",modelUploadId: model.id,@@ -123,10 +144,11 @@ export async function action({ request }: ActionFunctionArgs) {modelUploadId: model.id,userId});- } else if (modelState === "converted") {+ } else if (modelState === "converted" && assemblerHealthy) {// 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.+ // plan is ready by the time the author clicks Generate Steps. Skipped when+ // the geometry service is down; the author's Generate click starts it later.const planJob = await getLatestAssemblyPlanJob(client, model.id);const planStatus = planJob.data?.status;if (@@ -152,8 +174,13 @@ export async function action({ request }: ActionFunctionArgs) {}}+ // A model-backed instruction auto-generates its steps: the explorer sees+ // ?autogen=1 and submits Generate once — if the plan is ready it lands+ // instantly, otherwise the submit kicks planning and the awaiting machinery+ // finishes the chain when the plan completes.+ const autogen = modelState !== "none" ? "?autogen=1" : "";throw redirect(- path.to.assemblyInstruction(create.data.id),+ `${path.to.assemblyInstruction(create.data.id)}${autogen}`,await flash(request, success("Assembly instruction created")));}diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 9e015e68e0..417b22711c 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -117,6 +117,8 @@ export const path = {generatePath(`${api}/mrp${locationId ? `?location=${locationId}` : ""}`),+ modelConvertStatus: (modelUploadId: string) =>+ generatePath(`${api}/model/convert-status/${modelUploadId}`),modelUpload: `${api}/model/upload`,onShapeBom: (documentId: string, versionId: string, elementId: string) =>generatePath(@@ -526,8 +528,12 @@ export const path = {assemblyInstructions: `${x}/production/assemblies`,assemblyInstructionStatus: (id: string) =>generatePath(`${x}/assembly/${id}/status`),+ assemblyJobsCancel: (id: string) =>+ generatePath(`${x}/assembly/${id}/jobs/cancel`),assemblyModelConvert: (id: string) =>generatePath(`${x}/assembly/${id}/model/convert`),+ assemblyModelInvalidate: (id: string) =>+ generatePath(`${x}/assembly/${id}/model/invalidate`),assemblyPlanRerun: (id: string) =>generatePath(`${x}/assembly/${id}/plan/rerun`),deleteAssemblyInstruction: (id: string) =>@@ -541,6 +547,8 @@ export const path = {generatePath(`${x}/assembly/${id}/steps/motion/${stepId}`),assemblyInstructionStepComponents: (id: string, stepId: string) =>generatePath(`${x}/assembly/${id}/steps/components/${stepId}`),+ assemblyInstructionStepComponentsReassign: (id: string) =>+ generatePath(`${x}/assembly/${id}/steps/components/reassign`),deleteAssemblyInstructionStep: (id: string, stepId: string) =>generatePath(`${x}/assembly/${id}/steps/delete/${stepId}`),assemblyInstructionStepOrder: (id: string) =>diff --git a/crates/collision/Cargo.toml b/crates/collision/Cargo.tomlnew file mode 100644index 0000000000..65b0c57ef3--- /dev/null+++ b/crates/collision/Cargo.toml@@ -0,0 +1,17 @@+[package]+name = "collision"+version.workspace = true+edition.workspace = true+license.workspace = true++# Rust bridge over C++ FCL 0.7.0 (mesh-mesh collision / penetration depth).+# build.rs resolves FCL/libccd/eigen/octomap via `<PKG>_PREFIX` env or Homebrew.++[dependencies]+cxx = "1"++[build-dependencies]+cxx-build = "1"++[dev-dependencies]+serde_json = "1"diff --git a/crates/collision/build.rs b/crates/collision/build.rsnew file mode 100644index 0000000000..a2be28f94e--- /dev/null+++ b/crates/collision/build.rs@@ -0,0 +1,79 @@+/// Resolve a library prefix deterministically: `<ENV_KEY>_PREFIX` when set,+/// else a fixed per-target default. No `brew` shell-out, so the build never+/// depends on Homebrew being installed or on PATH. Docker/CI set the `*_PREFIX`+/// envs explicitly (see apps/assembler/Dockerfile); local macOS falls back to+/// the standard Homebrew `opt` layout, Linux to the distro `/usr` layout.+fn prefix(pkg: &str, env_key: &str) -> String {+ if let Ok(p) = std::env::var(format!("{env_key}_PREFIX")) {+ if !p.is_empty() {+ return p;+ }+ }+ // CARGO_CFG_TARGET_* are always set for build scripts — the target we build+ // for, so the default matches where its headers/libs live.+ let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();+ let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();+ match os.as_str() {+ "macos" if arch == "aarch64" => format!("/opt/homebrew/opt/{pkg}"),+ "macos" => format!("/usr/local/opt/{pkg}"),+ _ => "/usr".to_string(),+ }+}++/// Link `lib` from `prefix`, statically when a `.a` is present there, else+/// dynamically. Static keeps the archive's code in the binary (no runtime .so).+fn link_lib(prefix: &str, lib: &str) {+ let static_archive = ["lib", "lib/x86_64-linux-gnu"]+ .iter()+ .any(|sub| std::path::Path::new(&format!("{prefix}/{sub}/lib{lib}.a")).exists());+ let kind = if static_archive { "static" } else { "dylib" };+ println!("cargo:rustc-link-lib={kind}={lib}");+}++fn main() {+ let fcl = prefix("fcl", "FCL");+ let ccd = prefix("libccd", "LIBCCD");+ let eigen = prefix("eigen", "EIGEN");+ let octomap = prefix("octomap", "OCTOMAP");++ let mut build = cxx_build::bridge("src/lib.rs");+ build+ .file("src/shim.cc")+ .std("c++14")+ .include(format!("{fcl}/include"))+ .include(format!("{ccd}/include"))+ .include(format!("{eigen}/include/eigen3"))+ .include(format!("{octomap}/include"))+ .warnings(false);+ // The hot path is here: FCL's OBBRSS BVH + Eigen math are header-only+ // templates instantiated in this shim, so its SIMD baseline — not the FCL+ // .a's — governs their vectorization. On x86_64 deploy targets raise it to+ // AVX2+FMA (x86-64-v3); a conservative fleet baseline, not target-cpu=native+ // (which would SIGILL on older CPUs). Other arches (macOS/arm) keep NEON.+ // FMA shifts FP rounding by ~1 ULP — the calibration fixture's 1e-6 rounding+ // is built to absorb exactly that, but CI must confirm `cargo test -p+ // collision --test calibration` on the x86_64 build.+ if std::env::var("CARGO_CFG_TARGET_ARCH").as_deref() == Ok("x86_64") {+ build.flag_if_supported("-march=x86-64-v3");+ }+ build.compile("carbon_fcl_shim");++ for p in [&fcl, &ccd] {+ println!("cargo:rustc-link-search=native={p}/lib");+ println!("cargo:rustc-link-search=native={p}/lib/x86_64-linux-gnu");+ }+ // Prefer a static archive when the prefix ships one (the deployment build+ // installs libfcl.a/libccd.a → a self-contained binary with no FCL runtime+ // .so); fall back to dynamic where only a shared lib exists (macOS/brew dev).+ // FCL depends on ccd, so fcl must be listed before ccd for the static link.+ link_lib(&fcl, "fcl");+ link_lib(&ccd, "ccd");++ println!("cargo:rerun-if-changed=src/lib.rs");+ println!("cargo:rerun-if-changed=src/shim.cc");+ println!("cargo:rerun-if-changed=src/shim.h");+ // Rebuild when a prefix override changes (dynamic ↔ static, moved libs).+ for k in ["FCL_PREFIX", "LIBCCD_PREFIX", "EIGEN_PREFIX", "OCTOMAP_PREFIX"] {+ println!("cargo:rerun-if-env-changed={k}");+ }+}diff --git a/crates/collision/src/lib.rs b/crates/collision/src/lib.rsnew file mode 100644index 0000000000..d42f2cad39--- /dev/null+++ b/crates/collision/src/lib.rs@@ -0,0 +1,177 @@+//! cxx bridge over C++ FCL 0.7.0: triangle-mesh BVH build, a persistent+//! `DynamicAABBTreeCollisionManager` broadphase, and the moving-object queries+//! the planner drives (max penetration depth per neighbor, with a skip set and+//! a threshold-classified early-stop variant).++#[cxx::bridge(namespace = "carbon_fcl")]+pub mod ffi {+ /// One FCL contact between the two BVHs, in the exact FCL definition.+ #[derive(Debug, Clone)]+ pub struct Contact {+ pub depth: f64,+ pub nx: f64,+ pub ny: f64,+ pub nz: f64,+ pub px: f64,+ pub py: f64,+ pub pz: f64,+ /// Triangle index in the first / second BVH (FCL `b1` / `b2`).+ pub b1: i32,+ pub b2: i32,+ }++ /// One internal all-pairs contact from the broadphase manager, in the+ /// manager's traversal order. `a`/`b` index into the manager's registered+ /// objects (registration order).+ #[derive(Debug, Clone)]+ pub struct InternalContact {+ pub a: usize,+ pub b: usize,+ pub depth: f64,+ pub nx: f64,+ pub ny: f64,+ pub nz: f64,+ pub px: f64,+ pub py: f64,+ pub pz: f64,+ }++ /// Max penetration depth of a moving object against ONE registered object+ /// (collapsed per-other — every planner sweep consumer wants max-depth).+ #[derive(Debug, Clone)]+ pub struct SingleContact {+ pub other: usize,+ pub depth: f64,+ }++ unsafe extern "C++" {+ include!("collision/src/shim.h");++ /// Opaque `fcl::BVHModel<fcl::OBBRSS<double>>`.+ type Bvh;++ /// `fcl::DynamicAABBTreeCollisionManager<double>`. All-pairs contact+ /// order is stable (registration order), which `seated_pair_depths`+ /// relies on (it caps points/normals at the first 64 in that order).+ type Manager;++ /// Total FCL contacts appended across all narrowphase `collide` calls+ /// (perf diagnostic; process-global, monotonic).+ fn raw_contacts_enumerated() -> u64;++ /// Total narrowphase pair `collide` calls (perf diagnostic; global).+ fn narrow_pairs_run() -> u64;++ fn manager_new() -> UniquePtr<Manager>;++ /// Register a BVH at identity transform (world-baked mesh). Index =+ /// registration order.+ fn manager_add(m: Pin<&mut Manager>, bvh: &Bvh);++ /// Build the broadphase tree. Call ONCE after registration changes+ /// (add / set_active); the collide queries then reuse it (never rebuild+ /// per query — that was the whole point of a persistent manager).+ fn manager_setup(m: Pin<&mut Manager>);++ /// All-pairs contacts in the manager's broadphase traversal order.+ fn manager_internal_contacts(m: &Manager, num_max_contacts: usize) -> Vec<InternalContact>;++ /// Toggle a registered object's participation (the `_unregistered`+ /// protocol: unregister a part while sweeping it, re-register after).+ /// Rebuilds the broadphase tree (`update`).+ fn manager_set_active(m: Pin<&mut Manager>, index: usize, active: bool);++ /// Collide a moving object (at translation `tx,ty,tz`, identity rot)+ /// against the currently-active registered objects — the broadphase+ /// equivalent of the planner's `contacts_at`. `moving_index` is the+ /// moving part's own registered index (to exclude self), or -1 when the+ /// moving object is not a registered part (a combined group mesh).+ /// Returns max depth per overlapping other.+ fn manager_collide_single(+ m: &Manager,+ moving: &Bvh,+ moving_index: i64,+ tx: f64,+ ty: f64,+ tz: f64,+ num_max_contacts: usize,+ ) -> Vec<SingleContact>;++ /// Like `manager_collide_single`, but skips a SET of registered objects+ /// (moving part + already-known blockers) at the broadphase callback —+ /// so a deep pass-through stops re-enumerating a known blocker's full+ /// contact set at every subsequent sample, without a manager rebuild.+ /// Returns max depth per remaining other.+ fn manager_collide_single_multi(+ m: &Manager,+ moving: &Bvh,+ skip_indices: &[i64],+ tx: f64,+ ty: f64,+ tz: f64,+ num_max_contacts: usize,+ ) -> Vec<SingleContact>;++ /// Threshold-classified variant of `manager_collide_single_multi`. The+ /// planner's sweep consumers only test three predicates per neighbor —+ /// blocked (depth > threshold), near (> tol/2), touching (any contact) —+ /// so a backend may EARLY-STOP a neighbor's traversal at the first pair+ /// past the relevant threshold instead of enumerating its full contact+ /// set, as long as the returned depth lands in the same predicate+ /// bracket. Per-neighbor thresholds: `ov_idx[i]` gets blocking threshold+ /// `max(tol, ov_am[i])` (mate/seated allowance + margin); +INF means+ /// "never reports". `want_touch_near=false` lets a backend skip the+ /// touch/near probes (free_travel / path_blockers only test blocking).+ ///+ /// Early-stops each neighbor's BVH traversal at the first pair past its+ /// threshold (FCL's own `canStop` hook); a miss has already fully+ /// enumerated, so near/touch classification stays exact.+ #[allow(clippy::too_many_arguments)]+ fn manager_classify_multi(+ m: &Manager,+ moving: &Bvh,+ skip_indices: &[i64],+ ov_idx: &[i64],+ ov_am: &[f64],+ tx: f64,+ ty: f64,+ tz: f64,+ tol: f64,+ want_touch_near: bool,+ num_max_contacts: usize,+ ) -> Vec<SingleContact>;++ /// Build a BVH from flat world-space vertices (n*3 f64) and triangles+ /// (m*3 u32), in the same vertex/triangle order the mesh stores them.+ fn new_bvh(verts: &[f64], tris: &[u32]) -> UniquePtr<Bvh>;++ /// Contacts of BVH `a` translated by (ax,ay,az) against BVH `b`+ /// translated by (bx,by,bz), identity rotation — the only transforms+ /// the planner uses (parts are pre-baked to world space; the moving+ /// part gets a pure translation). `num_max_contacts` matches the+ /// planner's `CollisionRequest(num_max_contacts=100000)`.+ fn collide_pair(+ a: &Bvh,+ ax: f64,+ ay: f64,+ az: f64,+ b: &Bvh,+ bx: f64,+ by: f64,+ bz: f64,+ num_max_contacts: usize,+ ) -> Vec<Contact>;++ /// Exact minimum distance between two BVHs at identity transforms+ /// (0.0 when touching/penetrating, as FCL reports). Used only for the+ /// ordering-adjacency near-contact query.+ fn distance_pair(a: &Bvh, b: &Bvh) -> f64;+ }+}++pub use ffi::{+ collide_pair, distance_pair, manager_add, manager_classify_multi, manager_collide_single,+ manager_collide_single_multi, manager_internal_contacts, manager_new, manager_set_active,+ manager_setup, narrow_pairs_run, new_bvh, raw_contacts_enumerated, Bvh, Contact,+ InternalContact, Manager, SingleContact,+};diff --git a/crates/collision/src/shim.cc b/crates/collision/src/shim.ccnew file mode 100644index 0000000000..5254ce8a91--- /dev/null+++ b/crates/collision/src/shim.cc@@ -0,0 +1,424 @@+#include "collision/src/shim.h"++#include <vector>++#include <fcl/broadphase/broadphase_dynamic_AABB_tree.h>+#include <fcl/geometry/bvh/BVH_model.h>+#include <fcl/math/bv/OBBRSS.h>+#include <fcl/narrowphase/collision.h>+#include <fcl/narrowphase/collision_object.h>+#include <fcl/narrowphase/collision_request.h>+#include <fcl/narrowphase/collision_result.h>+#include <fcl/narrowphase/distance.h>+#include <fcl/narrowphase/distance_request.h>+#include <fcl/narrowphase/distance_result.h>++#include <cmath>+#include <limits>+#include <fcl/narrowphase/detail/traversal/collision/mesh_collision_traversal_node.h>+#include <fcl/narrowphase/detail/traversal/collision_node.h>++#include "collision/src/lib.rs.h"++#include <atomic>+#include <set>++using Model = fcl::BVHModel<fcl::OBBRSS<double>>;++namespace carbon_fcl {++static std::atomic<uint64_t> g_raw_contacts{0};+static std::atomic<uint64_t> g_narrow_pairs{0};++uint64_t raw_contacts_enumerated() { return g_raw_contacts.load(); }+uint64_t narrow_pairs_run() { return g_narrow_pairs.load(); }++static std::shared_ptr<Model> as_model(const Bvh &bvh) {+ return std::static_pointer_cast<Model>(bvh.model);+}++std::unique_ptr<Bvh> new_bvh(rust::Slice<const double> verts,+ rust::Slice<const uint32_t> tris) {+ const size_t n_verts = verts.size() / 3;+ const size_t n_tris = tris.size() / 3;++ std::vector<fcl::Vector3<double>> points;+ points.reserve(n_verts);+ for (size_t i = 0; i < n_verts; ++i) {+ points.emplace_back(verts[i * 3 + 0], verts[i * 3 + 1], verts[i * 3 + 2]);+ }+ std::vector<fcl::Triangle> triangles;+ triangles.reserve(n_tris);+ for (size_t i = 0; i < n_tris; ++i) {+ triangles.emplace_back(tris[i * 3 + 0], tris[i * 3 + 1], tris[i * 3 + 2]);+ }++ auto model = std::make_shared<Model>();+ model->beginModel(n_tris, n_verts);+ model->addSubModel(points, triangles);+ model->endModel();++ auto bvh = std::make_unique<Bvh>();+ bvh->model = model; // shared_ptr<Model> -> shared_ptr<void>+ return bvh;+}++rust::Vec<Contact> collide_pair(const Bvh &a, double ax, double ay, double az,+ const Bvh &b, double bx, double by, double bz,+ size_t num_max_contacts) {+ fcl::Transform3<double> ta = fcl::Transform3<double>::Identity();+ ta.translation() = fcl::Vector3<double>(ax, ay, az);+ fcl::Transform3<double> tb = fcl::Transform3<double>::Identity();+ tb.translation() = fcl::Vector3<double>(bx, by, bz);++ fcl::CollisionObject<double> oa(as_model(a), ta);+ fcl::CollisionObject<double> ob(as_model(b), tb);++ fcl::CollisionRequest<double> request(num_max_contacts, true);+ fcl::CollisionResult<double> result;+ fcl::collide(&oa, &ob, request, result);++ rust::Vec<Contact> out;+ if (!result.isCollision()) {+ return out;+ }+ std::vector<fcl::Contact<double>> contacts;+ result.getContacts(contacts);+ for (const auto &c : contacts) {+ Contact rc;+ rc.depth = c.penetration_depth;+ rc.nx = c.normal[0];+ rc.ny = c.normal[1];+ rc.nz = c.normal[2];+ rc.px = c.pos[0];+ rc.py = c.pos[1];+ rc.pz = c.pos[2];+ rc.b1 = c.b1;+ rc.b2 = c.b2;+ out.push_back(rc);+ }+ return out;+}++double distance_pair(const Bvh &a, const Bvh &b) {+ fcl::Transform3<double> id = fcl::Transform3<double>::Identity();+ fcl::CollisionObject<double> oa(as_model(a), id);+ fcl::CollisionObject<double> ob(as_model(b), id);+ fcl::DistanceRequest<double> request;+ fcl::DistanceResult<double> result;+ fcl::distance(&oa, &ob, request, result);+ return result.min_distance;+}++// --- broadphase manager (DynamicAABBTree) ---++struct ManagerImpl {+ fcl::DynamicAABBTreeCollisionManager<double> mgr;+ std::vector<std::shared_ptr<fcl::CollisionObject<double>>> objs;+ std::map<const fcl::CollisionGeometry<double> *, size_t> index;+};++static ManagerImpl *as_impl(const Manager &m) {+ return static_cast<ManagerImpl *>(m.impl.get());+}++struct AccumData {+ fcl::CollisionRequest<double> request;+ const std::map<const fcl::CollisionGeometry<double> *, size_t> *index;+ rust::Vec<InternalContact> *out;+};++static bool collide_callback(fcl::CollisionObject<double> *o1,+ fcl::CollisionObject<double> *o2, void *cdata) {+ AccumData *d = static_cast<AccumData *>(cdata);+ fcl::CollisionResult<double> res;+ fcl::collide(o1, o2, d->request, res);+ if (res.isCollision()) {+ std::vector<fcl::Contact<double>> cs;+ res.getContacts(cs);+ auto ia = d->index->find(o1->collisionGeometry().get());+ auto ib = d->index->find(o2->collisionGeometry().get());+ if (ia != d->index->end() && ib != d->index->end()) {+ for (const auto &c : cs) {+ InternalContact ic;+ ic.a = ia->second;+ ic.b = ib->second;+ ic.depth = c.penetration_depth;+ ic.nx = c.normal[0];+ ic.ny = c.normal[1];+ ic.nz = c.normal[2];+ ic.px = c.pos[0];+ ic.py = c.pos[1];+ ic.pz = c.pos[2];+ d->out->push_back(ic);+ }+ }+ }+ return false; // continue traversal (accumulate all pairs)+}++std::unique_ptr<Manager> manager_new() {+ auto m = std::make_unique<Manager>();+ m->impl = std::make_shared<ManagerImpl>();+ return m;+}++void manager_add(Manager &m, const Bvh &bvh) {+ ManagerImpl *impl = as_impl(m);+ auto model = std::static_pointer_cast<Model>(bvh.model);+ fcl::Transform3<double> id = fcl::Transform3<double>::Identity();+ auto obj = std::make_shared<fcl::CollisionObject<double>>(model, id);+ impl->mgr.registerObject(obj.get());+ impl->index[obj->collisionGeometry().get()] = impl->objs.size();+ impl->objs.push_back(obj);+}++void manager_setup(Manager &m) { as_impl(m)->mgr.setup(); }++rust::Vec<InternalContact> manager_internal_contacts(const Manager &m, size_t num_max_contacts) {+ ManagerImpl *impl = as_impl(m);+ rust::Vec<InternalContact> out;+ AccumData accum{fcl::CollisionRequest<double>(num_max_contacts, true), &impl->index, &out};+ impl->mgr.collide(&accum, collide_callback);+ return out;+}++void manager_set_active(Manager &m, size_t index, bool active) {+ ManagerImpl *impl = as_impl(m);+ if (index >= impl->objs.size()) {+ return;+ }+ auto *obj = impl->objs[index].get();+ if (active) {+ impl->mgr.registerObject(obj);+ } else {+ impl->mgr.unregisterObject(obj);+ }+ impl->mgr.update();+}++// A single moving object vs the manager: ONE shared CollisionResult with a+// total num_max_contacts budget across all pairs. Delegates to the multi-skip+// form with the moving part's own index as the only skip (so the swept part is+// never narrowphased against its own seated copy).+rust::Vec<SingleContact> manager_collide_single(const Manager &m, const Bvh &moving,+ int64_t moving_index, double tx, double ty,+ double tz, size_t num_max_contacts) {+ int64_t one[1] = {moving_index};+ rust::Slice<const int64_t> s(moving_index >= 0 ? one : nullptr,+ moving_index >= 0 ? 1 : 0);+ return manager_collide_single_multi(m, moving, s, tx, ty, tz, num_max_contacts);+}++// Skip a SET of registered objects at the broadphase callback. Used by+// `_path_blockers`: once a partner is a known blocker its contacts are never+// needed again, so skipping it stops re-enumerating its full triangle-contact+// set (thousands) at every subsequent sample, without a manager rebuild.+struct AccumMulti {+ fcl::CollisionRequest<double> request;+ fcl::CollisionResult<double> result;+ // CollisionOBJECT identities (unique per registration) — NOT geometry+ // pointers, which identical parts share (skipping one would cull them all).+ const std::set<const fcl::CollisionObject<double> *> *skip;+};++static bool multi_callback(fcl::CollisionObject<double> *o1,+ fcl::CollisionObject<double> *o2, void *cdata) {+ AccumMulti *d = static_cast<AccumMulti *>(cdata);+ if (d->skip->count(o1) || d->skip->count(o2)) {+ return false;+ }+ size_t before = d->result.numContacts();+ fcl::collide(o1, o2, d->request, d->result);+ g_narrow_pairs.fetch_add(1, std::memory_order_relaxed);+ g_raw_contacts.fetch_add(d->result.numContacts() - before, std::memory_order_relaxed);+ return d->result.numContacts() >= d->request.num_max_contacts;+}++rust::Vec<SingleContact> manager_collide_single_multi(const Manager &m, const Bvh &moving,+ rust::Slice<const int64_t> skip_indices,+ double tx, double ty, double tz,+ size_t num_max_contacts) {+ ManagerImpl *impl = as_impl(m);+ auto model = std::static_pointer_cast<Model>(moving.model);+ fcl::Transform3<double> tf = fcl::Transform3<double>::Identity();+ tf.translation() = fcl::Vector3<double>(tx, ty, tz);+ fcl::CollisionObject<double> moving_obj(model, tf);++ std::set<const fcl::CollisionObject<double> *> skip;+ for (int64_t idx : skip_indices) {+ if (idx >= 0 && (size_t)idx < impl->objs.size()) {+ skip.insert(impl->objs[idx].get());+ }+ }+ AccumMulti accum{fcl::CollisionRequest<double>(num_max_contacts, true), {}, &skip};+ impl->mgr.collide(&moving_obj, &accum, multi_callback);++ // Collapse the shared contact list to max depth per other. Skipped objects+ // (moving part + known blockers) never narrowphased, so they can't appear here.+ std::vector<fcl::Contact<double>> cs;+ accum.result.getContacts(cs);+ std::map<size_t, double> per_other;+ for (const auto &c : cs) {+ auto i1 = impl->index.find(c.o1);+ auto i2 = impl->index.find(c.o2);+ int64_t other = -1;+ if (i1 != impl->index.end()) {+ other = (int64_t)i1->second;+ } else if (i2 != impl->index.end()) {+ other = (int64_t)i2->second;+ }+ if (other < 0) {+ continue;+ }+ auto it = per_other.find((size_t)other);+ if (it == per_other.end() || c.penetration_depth > it->second) {+ per_other[(size_t)other] = c.penetration_depth;+ }+ }++ rust::Vec<SingleContact> out;+ for (const auto &kv : per_other) {+ SingleContact sc;+ sc.other = kv.first;+ sc.depth = kv.second;+ out.push_back(sc);+ }+ return out;+}++// FCL-native early-stop classify — the avoid-work core, with FCL's exact math.+//+// The planner's sweep consumers only test PREDICATES per neighbor: blocked+// (∃ exempt-filtered pair deeper than t_block = max(tol, allowance+margin)),+// near (> tol/2), touching (any contact). "∃ pair > t_block" ⟺+// "max > t_block", so the deep-overlap case — the one that enumerates+// thousands of triangle contacts today — may STOP at the first such pair with+// a byte-identical verdict (no plan field serializes the depth value; every+// consumer thresholds it). On a miss, the traversal has ALREADY enumerated the+// neighbor's full exact contact set, so near/touch/exempt behavior is+// byte-identical to full enumeration.+//+// Implemented by subclassing FCL's own OBBRSS mesh-mesh traversal node and+// tripping its built-in `canStop()` hook (the mechanism num_max already uses)+// when a contact exceeds the threshold — FCL's traversal order and Intersect+// depths are untouched.+struct ThresholdMeshNode : fcl::detail::MeshCollisionTraversalNodeOBBRSS<double> {+ double threshold = std::numeric_limits<double>::infinity();+ mutable size_t seen = 0;+ mutable bool hit = false;+ mutable double hit_depth = 0.0;++ bool canStop() const override {+ const size_t n = this->result->numContacts();+ for (; seen < n; ++seen) {+ double d = this->result->getContact(seen).penetration_depth;+ if (d > threshold) {+ hit = true;+ hit_depth = d;+ return true;+ }+ }+ return fcl::detail::MeshCollisionTraversalNodeOBBRSS<double>::canStop();+ }+};++struct AccumClassify {+ ManagerImpl *impl;+ const fcl::CollisionObject<double> *moving;+ const std::set<const fcl::CollisionObject<double> *> *skip;+ rust::Slice<const int64_t> ov_idx;+ rust::Slice<const double> ov_am;+ double tol;+ size_t budget_left; // shared num_max budget across neighbors+ std::vector<std::pair<size_t, double>> out;+};++static bool classify_callback(fcl::CollisionObject<double> *o1,+ fcl::CollisionObject<double> *o2, void *cdata) {+ AccumClassify *d = static_cast<AccumClassify *>(cdata);+ if (d->skip->count(o1) || d->skip->count(o2)) {+ return false;+ }+ if (d->budget_left == 0) {+ return true;+ }+ fcl::CollisionObject<double> *reg = (o1 == d->moving) ? o2 : o1;+ auto it = d->impl->index.find(reg->collisionGeometry().get());+ if (it == d->impl->index.end()) {+ return false;+ }+ size_t idx = it->second;+ double am = -1.0;+ for (size_t i = 0; i < d->ov_idx.size(); ++i) {+ if (d->ov_idx[i] == (int64_t)idx) {+ am = d->ov_am[i];+ break;+ }+ }+ if (std::isinf(am)) {+ return false; // infinite allowance: can never block, near, or touch+ }+ double t_block = am > d->tol ? am : d->tol;++ const Model *m1 = static_cast<const Model *>(o1->collisionGeometry().get());+ const Model *m2 = static_cast<const Model *>(o2->collisionGeometry().get());+ fcl::CollisionRequest<double> request(d->budget_left, true);+ fcl::CollisionResult<double> result;+ ThresholdMeshNode node;+ node.threshold = t_block;+ if (!fcl::detail::initialize(node, *m1, o1->getTransform(), *m2, o2->getTransform(), request,+ result)) {+ return false;+ }+ fcl::detail::collide(&node);+ g_narrow_pairs.fetch_add(1, std::memory_order_relaxed);+ g_raw_contacts.fetch_add(result.numContacts(), std::memory_order_relaxed);+ size_t n = result.numContacts();+ d->budget_left = d->budget_left > n ? d->budget_left - n : 0;++ if (node.hit) {+ d->out.emplace_back(idx, node.hit_depth);+ } else if (n > 0) {+ double max_depth = 0.0;+ for (size_t i = 0; i < n; ++i) {+ double dep = result.getContact(i).penetration_depth;+ if (dep > max_depth) max_depth = dep;+ }+ d->out.emplace_back(idx, max_depth);+ }+ return d->budget_left == 0;+}++rust::Vec<SingleContact> manager_classify_multi(const Manager &m, const Bvh &moving,+ rust::Slice<const int64_t> skip_indices,+ rust::Slice<const int64_t> ov_idx,+ rust::Slice<const double> ov_am, double tx,+ double ty, double tz, double tol,+ bool /*want_touch_near*/, size_t num_max_contacts) {+ ManagerImpl *impl = as_impl(m);+ auto model = std::static_pointer_cast<Model>(moving.model);+ fcl::Transform3<double> tf = fcl::Transform3<double>::Identity();+ tf.translation() = fcl::Vector3<double>(tx, ty, tz);+ fcl::CollisionObject<double> moving_obj(model, tf);++ std::set<const fcl::CollisionObject<double> *> skip;+ for (int64_t idx : skip_indices) {+ if (idx >= 0 && (size_t)idx < impl->objs.size()) {+ skip.insert(impl->objs[idx].get());+ }+ }+ AccumClassify accum{impl, &moving_obj, &skip, ov_idx, ov_am, tol, num_max_contacts, {}};+ impl->mgr.collide(&moving_obj, &accum, classify_callback);++ rust::Vec<SingleContact> out;+ for (const auto &kv : accum.out) {+ SingleContact sc;+ sc.other = kv.first;+ sc.depth = kv.second;+ out.push_back(sc);+ }+ return out;+}++} // namespace carbon_fcldiff --git a/crates/collision/src/shim.h b/crates/collision/src/shim.hnew file mode 100644index 0000000000..0a7ba83216--- /dev/null+++ b/crates/collision/src/shim.h@@ -0,0 +1,55 @@+#pragma once+#include <memory>+#include "rust/cxx.h"++#include "rust/cxx.h"+#include <cstddef>++namespace carbon_fcl {+struct Contact; // generated by cxx from the shared struct+struct InternalContact; // generated by cxx from the shared struct+struct SingleContact; // generated by cxx from the shared struct++// Wrapper around fcl::BVHModel<fcl::OBBRSS<double>>. Type-erased so this header+// (included by cxx-generated glue) stays complete without pulling in FCL/Eigen;+// shim.cc casts `model` back to the concrete BVH model.+struct Bvh {+ std::shared_ptr<void> model;+};++// Broadphase manager (type-erased, same rationale as Bvh).+struct Manager {+ std::shared_ptr<void> impl;+};++uint64_t raw_contacts_enumerated();+uint64_t narrow_pairs_run();++std::unique_ptr<Manager> manager_new();+void manager_add(Manager &m, const Bvh &bvh);+void manager_setup(Manager &m);+rust::Vec<InternalContact> manager_internal_contacts(const Manager &m, size_t num_max_contacts);+void manager_set_active(Manager &m, size_t index, bool active);+rust::Vec<SingleContact> manager_collide_single(const Manager &m, const Bvh &moving,+ int64_t moving_index, double tx, double ty,+ double tz, size_t num_max_contacts);+rust::Vec<SingleContact> manager_collide_single_multi(const Manager &m, const Bvh &moving,+ rust::Slice<const int64_t> skip_indices,+ double tx, double ty, double tz,+ size_t num_max_contacts);+rust::Vec<SingleContact> manager_classify_multi(const Manager &m, const Bvh &moving,+ rust::Slice<const int64_t> skip_indices,+ rust::Slice<const int64_t> ov_idx,+ rust::Slice<const double> ov_am, double tx,+ double ty, double tz, double tol,+ bool want_touch_near, size_t num_max_contacts);++std::unique_ptr<Bvh> new_bvh(rust::Slice<const double> verts,+ rust::Slice<const uint32_t> tris);++rust::Vec<Contact> collide_pair(const Bvh &a, double ax, double ay, double az,+ const Bvh &b, double bx, double by, double bz,+ size_t num_max_contacts);++double distance_pair(const Bvh &a, const Bvh &b);+} // namespace carbon_fcldiff --git a/crates/collision/tests/calibration.json b/crates/collision/tests/calibration.jsonnew file mode 100644index 0000000000..a4e761f2a5--- /dev/null+++ b/crates/collision/tests/calibration.json@@ -0,0 +1,1306 @@+{+ "cases": [+ {+ "name": "box_box_overlap_0p5",+ "a": {+ "verts": [+ -10.0, -10.0, 0.0, -10.0, -10.0, 10.0, -10.0, 10.0, 0.0, -10.0, 10.0,+ 10.0, 10.0, -10.0, 0.0, 10.0, -10.0, 10.0, 10.0, 10.0, 0.0, 10.0,+ 10.0, 10.0+ ],+ "faces": [+ 1, 3, 0, 4, 1, 0, 0, 3, 2, 2, 4, 0, 1, 7, 3, 5, 1, 4, 5, 7, 1, 3, 7,+ 2, 6, 4, 2, 2, 7, 6, 6, 5, 4, 7, 5, 6+ ]+ },+ "b": {+ "verts": [+ -10.0, -10.0, 9.5, -10.0, -10.0, 19.5, -10.0, 10.0, 9.5, -10.0, 10.0,+ 19.5, 10.0, -10.0, 9.5, 10.0, -10.0, 19.5, 10.0, 10.0, 9.5, 10.0,+ 10.0, 19.5+ ],+ "faces": [+ 1, 3, 0, 4, 1, 0, 0, 3, 2, 2, 4, 0, 1, 7, 3, 5, 1, 4, 5, 7, 1, 3, 7,+ 2, 6, 4, 2, 2, 7, 6, 6, 5, 4, 7, 5, 6+ ]+ },+ "contacts": [+ [-0.0, 1.0, 0.0, 0.0, -10.0, -10.0, 10.0, 0, 0],+ [-0.0, 1.0, 0.0, 0.0, -10.0, 10.0, 10.0, 0, 0],+ [20.0, 1.0, 0.0, 0.0, 10.0, -10.0, 0.0, 1, 0],+ [20.0, 1.0, 0.0, 0.0, 10.0, -10.0, 10.0, 5, 0],+ [20.0, 1.0, 0.0, 0.0, 10.0, -10.0, 0.0, 5, 0],+ [0.5, 0.0, 0.0, 1.0, -10.0, -10.0, 9.5, 6, 0],+ [0.5, 0.0, 0.0, 1.0, -10.0, -10.0, 9.5, 4, 0],+ [0.5, 0.0, 0.0, 1.0, -10.0, -10.0, 10.0, 0, 3],+ [0.5, 0.0, 0.0, 1.0, -10.0, 10.0, 10.0, 0, 3],+ [0.5, 0.0, 0.0, 1.0, -10.0, -10.0, 10.0, 1, 3],+ [0.5, 0.0, 0.0, 1.0, 10.0, -10.0, 10.0, 5, 3],+ [0.5, 0.0, 0.0, 1.0, -10.0, -10.0, 10.0, 5, 3],+ [0.5, 0.0, 0.0, 1.0, 10.0, -10.0, 10.0, 10, 3],+ [0.5, 0.0, 0.0, 1.0, -10.0, 10.0, 10.0, 2, 3],+ [0.5, 0.0, 0.0, 1.0, -10.0, 10.0, 10.0, 7, 3],+ [0.5, 0.0, 0.0, 1.0, 10.0, 10.0, 10.0, 7, 3],+ [20.0, 0.0, 1.0, 0.0, -10.0, 10.0, 10.0, 0, 1],+ [-0.0, 0.0, 1.0, 0.0, 10.0, -10.0, 0.0, 1, 1],+ [-0.0, 0.0, 1.0, 0.0, -10.0, -10.0, 10.0, 1, 1],+ [-0.0, 0.0, 1.0, 0.0, 10.0, -10.0, 10.0, 5, 1],+ [-0.0, 0.0, 1.0, 0.0, -10.0, -10.0, 10.0, 5, 1],+ [0.5, 0.0, 0.0, 1.0, 10.0, -10.0, 9.5, 6, 1],+ [0.5, 0.0, 0.0, 1.0, -10.0, -10.0, 9.5, 6, 1],+ [20.0, 0.0, 1.0, 0.0, 10.0, 10.0, 0.0, 10, 1],+ [0.5, 0.0, 0.0, 1.0, 10.0, -10.0, 9.5, 4, 1],+ [0.5, 0.0, 0.0, 1.0, -10.0, -10.0, 9.5, 4, 1],+ [-0.0, 0.0, 1.0, 0.0, 10.0, -10.0, 10.0, 5, 5],+ [-0.0, 0.0, 1.0, 0.0, -10.0, -10.0, 10.0, 5, 5],+ [0.5, 0.0, 0.0, 1.0, 10.0, -10.0, 9.5, 6, 5],+ [20.0, 0.0, 1.0, 0.0, 10.0, 10.0, 0.0, 10, 5],+ [20.0, 0.0, 1.0, 0.0, 10.0, 10.0, 10.0, 11, 5],+ [20.0, 0.0, 1.0, 0.0, 10.0, 10.0, 0.0, 11, 5],+ [20.0, -1.0, -0.0, -0.0, -10.0, -10.0, 10.0, 5, 10],+ [0.5, 0.0, 0.0, 1.0, 10.0, 10.0, 9.5, 6, 10],+ [0.5, 0.0, 0.0, 1.0, 10.0, -10.0, 9.5, 6, 10],+ [-0.0, -1.0, -0.0, -0.0, 10.0, 10.0, 0.0, 10, 10],+ [-0.0, -1.0, -0.0, -0.0, 10.0, -10.0, 10.0, 10, 10],+ [20.0, -1.0, -0.0, -0.0, -10.0, 10.0, 0.0, 9, 10],+ [-0.0, -1.0, -0.0, -0.0, 10.0, 10.0, 10.0, 11, 10],+ [-0.0, -1.0, -0.0, -0.0, 10.0, -10.0, 10.0, 11, 10],+ [-0.0, 1.0, 0.0, 0.0, -10.0, -10.0, 10.0, 0, 2],+ [-0.0, 1.0, 0.0, 0.0, -10.0, 10.0, 10.0, 0, 2],+ [20.0, 1.0, 0.0, 0.0, 10.0, -10.0, 0.0, 1, 2],+ [-0.0, 1.0, 0.0, 0.0, -10.0, -10.0, 0.0, 2, 2],+ [-0.0, 1.0, 0.0, 0.0, -10.0, 10.0, 10.0, 2, 2],+ [0.5, 0.0, 0.0, 1.0, -10.0, -10.0, 9.5, 4, 2],+ [0.5, 0.0, 0.0, 1.0, -10.0, 10.0, 9.5, 4, 2],+ [20.0, 1.0, 0.0, 0.0, 10.0, 10.0, 10.0, 7, 2],+ [20.0, 0.0, -1.0, 0.0, -10.0, -10.0, 10.0, 0, 7],+ [20.0, 0.0, -1.0, 0.0, -10.0, -10.0, 0.0, 0, 7],+ [20.0, 0.0, -1.0, 0.0, -10.0, -10.0, 0.0, 2, 7],+ [0.5, 0.0, 0.0, 1.0, -10.0, 10.0, 9.5, 4, 7],+ [-0.0, 0.0, -1.0, 0.0, -10.0, 10.0, 10.0, 7, 7],+ [-0.0, 0.0, -1.0, 0.0, 10.0, 10.0, 10.0, 7, 7],+ [0.5, 0.0, 0.0, 1.0, -10.0, 10.0, 9.5, 6, 9],+ [0.5, 0.0, 0.0, 1.0, 10.0, 10.0, 9.5, 6, 9],+ [20.0, -0.0, -1.0, -0.0, -10.0, -10.0, 0.0, 2, 9],+ [0.5, 0.0, 0.0, 1.0, -10.0, 10.0, 9.5, 4, 9],+ [0.5, 0.0, 0.0, 1.0, 10.0, 10.0, 9.5, 4, 9],+ [-0.0, -0.0, -1.0, -0.0, -10.0, 10.0, 10.0, 7, 9],+ [-0.0, -0.0, -1.0, -0.0, 10.0, 10.0, 10.0, 7, 9],+ [-0.0, -0.0, -1.0, -0.0, -10.0, 10.0, 0.0, 9, 9],+ [-0.0, -0.0, -1.0, -0.0, 10.0, 10.0, 10.0, 9, 9],+ [20.0, -0.0, -1.0, -0.0, 10.0, -10.0, 10.0, 11, 9],+ [0.5, 0.0, 0.0, 1.0, 10.0, -10.0, 10.0, 5, 8],+ [0.5, 0.0, 0.0, 1.0, -10.0, -10.0, 10.0, 5, 8],+ [0.5, 0.0, 0.0, 1.0, 10.0, -10.0, 10.0, 10, 8],+ [0.5, 0.0, 0.0, 1.0, -10.0, 10.0, 10.0, 2, 8],+ [0.5, 0.0, 0.0, 1.0, -10.0, 10.0, 10.0, 7, 8],+ [0.5, 0.0, 0.0, 1.0, 10.0, 10.0, 10.0, 7, 8],+ [0.5, 0.0, 0.0, 1.0, 10.0, 10.0, 10.0, 9, 8],+ [0.5, 0.0, 0.0, 1.0, 10.0, 10.0, 10.0, 11, 8],+ [0.5, 0.0, 0.0, 1.0, 10.0, -10.0, 10.0, 11, 8],+ [0.5, 0.0, 0.0, 1.0, 10.0, 10.0, 9.5, 6, 11],+ [0.5, 0.0, 0.0, 1.0, 10.0, 10.0, 9.5, 4, 11],+ [20.0, -1.0, -0.0, -0.0, -10.0, 10.0, 10.0, 7, 11],+ [20.0, -1.0, -0.0, -0.0, -10.0, 10.0, 0.0, 7, 11],+ [20.0, -1.0, -0.0, -0.0, -10.0, 10.0, 0.0, 9, 11],+ [-0.0, -1.0, -0.0, -0.0, 10.0, 10.0, 10.0, 11, 11],+ [-0.0, -1.0, -0.0, -0.0, 10.0, -10.0, 10.0, 11, 11]+ ]+ },+ {+ "name": "box_box_seated_0p05",+ "a": {+ "verts": [+ -50.0, -50.0, 0.0, -50.0, -50.0, 10.0, -50.0, 50.0, 0.0, -50.0, 50.0,+ 10.0, 50.0, -50.0, 0.0, 50.0, -50.0, 10.0, 50.0, 50.0, 0.0, 50.0,+ 50.0, 10.0+ ],+ "faces": [+ 1, 3, 0, 4, 1, 0, 0, 3, 2, 2, 4, 0, 1, 7, 3, 5, 1, 4, 5, 7, 1, 3, 7,+ 2, 6, 4, 2, 2, 7, 6, 6, 5, 4, 7, 5, 6+ ]+ },+ "b": {+ "verts": [+ -20.0, -20.0, 10.05, -20.0, -20.0, 20.05, -20.0, 20.0, 10.05, -20.0,+ 20.0, 20.05, 20.0, -20.0, 10.05, 20.0, -20.0, 20.05, 20.0, 20.0,+ 10.05, 20.0, 20.0, 20.05+ ],+ "faces": [+ 1, 3, 0, 4, 1, 0, 0, 3, 2, 2, 4, 0, 1, 7, 3, 5, 1, 4, 5, 7, 1, 3, 7,+ 2, 6, 4, 2, 2, 7, 6, 6, 5, 4, 7, 5, 6+ ]+ },+ "contacts": []+ },+ {+ "name": "screw_in_bore",+ "a": {+ "verts": [+ -20.0, -20.0, 0.0, -3.8247601985931396, -2.5556230545043945, 0.0,+ -2.5556230545043945, -3.8247601985931396, 0.0, -3.2526912689208984,+ -3.2526912689208984, 0.0, -4.2498459815979, -1.7603437900543213, 0.0,+ -4.511612415313721, -0.8974154591560364, 0.0, -1.7603437900543213,+ -4.2498459815979, 0.0, -0.8974154591560364, -4.511612415313721, 0.0,+ -20.0, -20.0, 10.0, -3.8247601985931396, -2.5556230545043945, 10.0,+ -2.5556230545043945, -3.8247601985931396, 10.0, -3.2526912689208984,+ -3.2526912689208984, 10.0, -4.2498459815979, -1.7603437900543213,+ 10.0, -4.511612415313721, -0.8974154591560364, 10.0,+ -1.7603437900543213, -4.2498459815979, 10.0, -0.8974154591560364,+ -4.511612415313721, 10.0, -20.0, 20.0, 0.0, -4.599999904632568,+ 5.633375257193976e-16, 0.0, -4.511612415313721, 0.8974154591560364,+ 0.0, -4.2498459815979, 1.7603437900543213, 0.0, -3.8247601985931396,+ 2.5556230545043945, 0.0, -3.2526912689208984, 3.2526912689208984, 0.0,+ -2.5556230545043945, 3.8247601985931396, 0.0, -1.7603437900543213,+ 4.2498459815979, 0.0, -0.8974154591560364, 4.511612415313721, 0.0,+ -20.0, 20.0, 10.0, -4.599999904632568, 5.633375257193976e-16, 10.0,+ -4.511612415313721, 0.8974154591560364, 10.0, -4.2498459815979,+ 1.7603437900543213, 10.0, -3.8247601985931396, 2.5556230545043945,+ 10.0, -3.2526912689208984, 3.2526912689208984, 10.0,+ -2.5556230545043945, 3.8247601985931396, 10.0, -1.7603437900543213,+ 4.2498459815979, 10.0, -0.8974154591560364, 4.511612415313721, 10.0,+ -8.45006315048876e-16, -4.599999904632568, 0.0, 0.8974154591560364,+ -4.511612415313721, 0.0, 1.7603437900543213, -4.2498459815979, 0.0,+ 2.5556230545043945, -3.8247601985931396, 0.0, 3.2526912689208984,+ -3.2526912689208984, 0.0, 3.8247601985931396, -2.5556230545043945,+ 0.0, 4.2498459815979, -1.7603437900543213, 0.0, 4.511612415313721,+ -0.8974154591560364, 0.0, 20.0, -20.0, 0.0, -8.45006315048876e-16,+ -4.599999904632568, 10.0, 0.8974154591560364, -4.511612415313721,+ 10.0, 1.7603437900543213, -4.2498459815979, 10.0, 2.5556230545043945,+ -3.8247601985931396, 10.0, 3.2526912689208984, -3.2526912689208984,+ 10.0, 3.8247601985931396, -2.5556230545043945, 10.0, 4.2498459815979,+ -1.7603437900543213, 10.0, 4.511612415313721, -0.8974154591560364,+ 10.0, 20.0, -20.0, 10.0, 2.816687628596988e-16, 4.599999904632568,+ 0.0, 0.8974154591560364, 4.511612415313721, 0.0, 1.7603437900543213,+ 4.2498459815979, 0.0, 4.599999904632568, 0.0, 0.0, 4.511612415313721,+ 0.8974154591560364, 0.0, 4.2498459815979, 1.7603437900543213, 0.0,+ 3.2526912689208984, 3.2526912689208984, 0.0, 2.5556230545043945,+ 3.8247601985931396, 0.0, 3.8247601985931396, 2.5556230545043945, 0.0,+ 20.0, 20.0, 0.0, 2.816687628596988e-16, 4.599999904632568, 10.0,+ 0.8974154591560364, 4.511612415313721, 10.0, 1.7603437900543213,+ 4.2498459815979, 10.0, 4.599999904632568, 0.0, 10.0,+ 4.511612415313721, 0.8974154591560364, 10.0, 4.2498459815979,+ 1.7603437900543213, 10.0, 3.2526912689208984, 3.2526912689208984,+ 10.0, 2.5556230545043945, 3.8247601985931396, 10.0,+ 3.8247601985931396, 2.5556230545043945, 10.0, 20.0, 20.0, 10.0+ ],+ "faces": [+ 0, 16, 4, 0, 42, 8, 0, 1, 3, 0, 4, 1, 0, 3, 2, 0, 6, 7, 0, 2, 6, 0, 7,+ 34, 0, 34, 35, 0, 35, 36, 0, 8, 25, 8, 51, 14, 8, 12, 13, 8, 11, 9, 8,+ 9, 12, 8, 10, 11, 8, 14, 10, 8, 13, 26, 8, 26, 27, 8, 27, 28, 0, 25,+ 16, 16, 5, 4, 16, 17, 5, 16, 18, 17, 16, 19, 18, 16, 20, 19, 16, 21,+ 20, 16, 22, 21, 16, 23, 22, 16, 61, 23, 8, 28, 25, 25, 28, 29, 25, 29,+ 30, 25, 30, 31, 25, 31, 32, 25, 32, 33, 25, 33, 62, 25, 62, 63, 25,+ 63, 64, 16, 25, 71, 0, 36, 42, 42, 36, 37, 42, 37, 38, 42, 38, 39, 42,+ 39, 40, 42, 40, 41, 42, 41, 55, 42, 55, 56, 42, 56, 57, 42, 61, 51, 8,+ 42, 51, 51, 15, 14, 51, 43, 15, 51, 44, 43, 51, 45, 44, 51, 46, 45,+ 51, 47, 46, 51, 48, 47, 51, 49, 48, 51, 71, 49, 61, 24, 23, 61, 52,+ 24, 61, 53, 52, 61, 59, 54, 61, 54, 53, 61, 58, 59, 61, 57, 60, 61,+ 60, 58, 16, 71, 61, 42, 57, 61, 71, 50, 49, 71, 65, 50, 71, 66, 65,+ 71, 64, 69, 71, 69, 68, 71, 70, 67, 71, 68, 70, 71, 67, 66, 25, 64,+ 71, 51, 61, 71, 3, 1, 9, 2, 3, 11, 1, 4, 12, 4, 5, 13, 5, 17, 26, 6,+ 2, 10, 7, 6, 14, 34, 7, 15, 3, 9, 11, 2, 11, 10, 1, 12, 9, 4, 13, 12,+ 5, 26, 13, 6, 10, 14, 7, 14, 15, 34, 15, 43, 17, 18, 27, 18, 19, 28,+ 19, 20, 29, 20, 21, 30, 31, 21, 22, 32, 22, 23, 33, 23, 24, 62, 24,+ 52, 17, 27, 26, 18, 28, 27, 19, 29, 28, 20, 30, 29, 31, 30, 21, 32,+ 31, 22, 33, 32, 23, 62, 33, 24, 34, 43, 35, 36, 35, 44, 37, 36, 45,+ 38, 37, 46, 47, 39, 38, 48, 40, 39, 49, 41, 40, 41, 50, 55, 35, 43,+ 44, 36, 44, 45, 37, 45, 46, 38, 46, 47, 47, 48, 39, 48, 49, 40, 49,+ 50, 41, 50, 65, 55, 63, 52, 53, 64, 53, 54, 69, 54, 59, 55, 65, 56,+ 66, 57, 56, 67, 60, 57, 68, 59, 58, 70, 58, 60, 63, 62, 52, 64, 63,+ 53, 69, 64, 54, 65, 66, 56, 66, 67, 57, 67, 70, 60, 68, 69, 59, 70,+ 68, 58+ ]+ },+ "b": {+ "verts": [+ 0.0, 0.0, -8.0, 5.0, 0.0, -8.0, 5.0, 0.0, 16.0, 0.0, 0.0, 16.0,+ 4.903926402016152, 0.9754516100806412, -8.0, 4.903926402016152,+ 0.9754516100806412, 16.0, 4.619397662556434, 1.913417161825449, -8.0,+ 4.619397662556434, 1.913417161825449, 16.0, 4.157348061512726,+ 2.777851165098011, -8.0, 4.157348061512726, 2.777851165098011, 16.0,+ 3.5355339059327378, 3.5355339059327373, -8.0, 3.5355339059327378,+ 3.5355339059327373, 16.0, 2.7778511650980113, 4.157348061512726, -8.0,+ 2.7778511650980113, 4.157348061512726, 16.0, 1.9134171618254492,+ 4.619397662556434, -8.0, 1.9134171618254492, 4.619397662556434, 16.0,+ 0.9754516100806416, 4.903926402016152, -8.0, 0.9754516100806416,+ 4.903926402016152, 16.0, 3.061616997868383e-16, 5.0, -8.0,+ 3.061616997868383e-16, 5.0, 16.0, -0.975451610080641,+ 4.903926402016152, -8.0, -0.975451610080641, 4.903926402016152, 16.0,+ -1.9134171618254485, 4.619397662556434, -8.0, -1.9134171618254485,+ 4.619397662556434, 16.0, -2.77785116509801, 4.157348061512726, -8.0,+ -2.77785116509801, 4.157348061512726, 16.0, -3.5355339059327373,+ 3.5355339059327378, -8.0, -3.5355339059327373, 3.5355339059327378,+ 16.0, -4.157348061512726, 2.777851165098011, -8.0, -4.157348061512726,+ 2.777851165098011, 16.0, -4.619397662556434, 1.9134171618254494, -8.0,+ -4.619397662556434, 1.9134171618254494, 16.0, -4.903926402016152,+ 0.9754516100806431, -8.0, -4.903926402016152, 0.9754516100806431,+ 16.0, -5.0, 6.123233995736766e-16, -8.0, -5.0, 6.123233995736766e-16,+ 16.0, -4.903926402016152, -0.9754516100806419, -8.0,+ -4.903926402016152, -0.9754516100806419, 16.0, -4.619397662556434,+ -1.9134171618254483, -8.0, -4.619397662556434, -1.9134171618254483,+ 16.0, -4.157348061512727, -2.77785116509801, -8.0, -4.157348061512727,+ -2.77785116509801, 16.0, -3.5355339059327386, -3.5355339059327373,+ -8.0, -3.5355339059327386, -3.5355339059327373, 16.0,+ -2.777851165098011, -4.157348061512726, -8.0, -2.777851165098011,+ -4.157348061512726, 16.0, -1.9134171618254516, -4.619397662556432,+ -8.0, -1.9134171618254516, -4.619397662556432, 16.0,+ -0.9754516100806433, -4.903926402016151, -8.0, -0.9754516100806433,+ -4.903926402016151, 16.0, -9.184850993605148e-16, -5.0, -8.0,+ -9.184850993605148e-16, -5.0, 16.0, 0.9754516100806415,+ -4.903926402016152, -8.0, 0.9754516100806415, -4.903926402016152,+ 16.0, 1.91341716182545, -4.619397662556433, -8.0, 1.91341716182545,+ -4.619397662556433, 16.0, 2.777851165098009, -4.157348061512727, -8.0,+ 2.777851165098009, -4.157348061512727, 16.0, 3.535533905932737,+ -3.5355339059327386, -8.0, 3.535533905932737, -3.5355339059327386,+ 16.0, 4.157348061512726, -2.777851165098011, -8.0, 4.157348061512726,+ -2.777851165098011, 16.0, 4.619397662556432, -1.913417161825452, -8.0,+ 4.619397662556432, -1.913417161825452, 16.0, 4.903926402016151,+ -0.9754516100806436, -8.0, 4.903926402016151, -0.9754516100806436,+ 16.0+ ],+ "faces": [+ 1, 0, 4, 1, 4, 2, 2, 4, 5, 2, 5, 3, 4, 0, 6, 4, 6, 5, 5, 6, 7, 5, 7,+ 3, 6, 0, 8, 6, 8, 7, 7, 8, 9, 7, 9, 3, 8, 0, 10, 8, 10, 9, 9, 10, 11,+ 9, 11, 3, 10, 0, 12, 10, 12, 11, 11, 12, 13, 11, 13, 3, 12, 0, 14, 12,+ 14, 13, 13, 14, 15, 13, 15, 3, 14, 0, 16, 14, 16, 15, 15, 16, 17, 15,+ 17, 3, 16, 0, 18, 16, 18, 17, 17, 18, 19, 17, 19, 3, 18, 0, 20, 18,+ 20, 19, 19, 20, 21, 19, 21, 3, 20, 0, 22, 20, 22, 21, 21, 22, 23, 21,+ 23, 3, 22, 0, 24, 22, 24, 23, 23, 24, 25, 23, 25, 3, 24, 0, 26, 24,+ 26, 25, 25, 26, 27, 25, 27, 3, 26, 0, 28, 26, 28, 27, 27, 28, 29, 27,+ 29, 3, 28, 0, 30, 28, 30, 29, 29, 30, 31, 29, 31, 3, 30, 0, 32, 30,+ 32, 31, 31, 32, 33, 31, 33, 3, 32, 0, 34, 32, 34, 33, 33, 34, 35, 33,+ 35, 3, 34, 0, 36, 34, 36, 35, 35, 36, 37, 35, 37, 3, 36, 0, 38, 36,+ 38, 37, 37, 38, 39, 37, 39, 3, 38, 0, 40, 38, 40, 39, 39, 40, 41, 39,+ 41, 3, 40, 0, 42, 40, 42, 41, 41, 42, 43, 41, 43, 3, 42, 0, 44, 42,+ 44, 43, 43, 44, 45, 43, 45, 3, 44, 0, 46, 44, 46, 45, 45, 46, 47, 45,+ 47, 3, 46, 0, 48, 46, 48, 47, 47, 48, 49, 47, 49, 3, 48, 0, 50, 48,+ 50, 49, 49, 50, 51, 49, 51, 3, 50, 0, 52, 50, 52, 51, 51, 52, 53, 51,+ 53, 3, 52, 0, 54, 52, 54, 53, 53, 54, 55, 53, 55, 3, 54, 0, 56, 54,+ 56, 55, 55, 56, 57, 55, 57, 3, 56, 0, 58, 56, 58, 57, 57, 58, 59, 57,+ 59, 3, 58, 0, 60, 58, 60, 59, 59, 60, 61, 59, 61, 3, 60, 0, 62, 60,+ 62, 61, 61, 62, 63, 61, 63, 3, 62, 0, 64, 62, 64, 63, 63, 64, 65, 63,+ 65, 3, 64, 0, 1, 64, 1, 65, 65, 1, 2, 65, 2, 3+ ]+ },+ "contacts": [+ [+ 0.398073916, 0.634393284, 0.773010453, 0.0, -2.555623055,+ -3.824760199, 0.0, 4, 81+ ],+ [+ 0.573998114, 0.634393284, 0.773010453, 0.0, -3.824760199,+ -2.555623055, 0.0, 2, 81+ ],+ [+ 0.573998114, 0.634393284, 0.773010453, 0.0, -3.824760199,+ -2.555623055, 10.0, 13, 81+ ],+ [+ 0.398073916, 0.634393284, 0.773010453, 0.0, -2.555623055,+ -3.824760199, 10.0, 15, 81+ ],+ [+ 0.398073916, 0.634393284, 0.773010453, 0.0, -3.252691269,+ -3.252691269, 10.0, 15, 81+ ],+ [+ 0.398073916, 0.773010453, 0.634393284, 0.0, -3.824760199,+ -2.555623055, 0.0, 2, 77+ ],+ [+ 0.398073916, 0.773010453, 0.634393284, 0.0, -3.252691269,+ -3.252691269, 0.0, 2, 77+ ],+ [+ 0.398073916, 0.773010453, 0.634393284, 0.0, -3.824760199,+ -2.555623055, 10.0, 13, 77+ ],+ [+ 0.573997986, 0.773010453, 0.634393284, 0.0, -4.249845982, -1.76034379,+ 0.0, 3, 77+ ],+ [+ 0.398073915, 0.881921264, 0.471396737, 0.0, -3.824760199,+ -2.555623055, 0.0, 3, 73+ ],+ [+ 0.573997986, 0.773010453, 0.634393284, 0.0, -4.249845982, -1.76034379,+ 10.0, 14, 77+ ],+ [+ 0.398073915, 0.881921264, 0.471396737, 0.0, -3.824760199,+ -2.555623055, 10.0, 14, 73+ ],+ [+ 0.398073915, 0.881921264, 0.471396737, 0.0, -4.249845982, -1.76034379,+ 10.0, 14, 73+ ],+ [+ 0.573997989, 0.881921264, 0.471396737, 0.0, -4.511612415,+ -0.897415459, 10.0, 12, 73+ ],+ [+ 0.398073916, 0.634393284, 0.773010453, 0.0, -2.555623055,+ -3.824760199, 0.0, 4, 82+ ],+ [+ 0.573998114, 0.773010453, 0.634393284, 0.0, -2.555623055,+ -3.824760199, 0.0, 4, 78+ ],+ [+ 0.398073916, 0.773010453, 0.634393284, 0.0, -3.824760199,+ -2.555623055, 0.0, 2, 78+ ],+ [+ 0.398073916, 0.773010453, 0.634393284, 0.0, -3.252691269,+ -3.252691269, 0.0, 2, 78+ ],+ [+ 0.398073916, 0.634393284, 0.773010453, 0.0, -2.555623055,+ -3.824760199, 10.0, 15, 82+ ],+ [+ 0.398073916, 0.634393284, 0.773010453, 0.0, -3.252691269,+ -3.252691269, 10.0, 15, 82+ ],+ [+ 0.398073916, 0.773010453, 0.634393284, 0.0, -3.824760199,+ -2.555623055, 10.0, 13, 78+ ],+ [+ 0.573998114, 0.773010453, 0.634393284, 0.0, -2.555623055,+ -3.824760199, 10.0, 15, 78+ ],+ [+ 0.398073915, 0.881921264, 0.471396737, 0.0, -3.824760199,+ -2.555623055, 0.0, 3, 74+ ],+ [+ 0.398073915, 0.881921264, 0.471396737, 0.0, -3.824760199,+ -2.555623055, 10.0, 14, 74+ ],+ [+ 0.398073915, 0.881921264, 0.471396737, 0.0, -4.249845982, -1.76034379,+ 10.0, 14, 74+ ],+ [+ 0.398073777, 0.956940336, 0.290284677, -0.0, -4.511612415,+ -0.897415459, 10.0, 12, 70+ ],+ [+ 0.398073915, 0.471396737, 0.881921264, 0.0, -2.555623055,+ -3.824760199, 0.0, 6, 85+ ],+ [+ 0.398073915, 0.471396737, 0.881921264, 0.0, -1.76034379, -4.249845982,+ 0.0, 6, 85+ ],+ [+ 0.398073915, 0.471396737, 0.881921264, 0.0, -2.555623055,+ -3.824760199, 10.0, 16, 85+ ],+ [+ 0.398073777, 0.290284677, 0.956940336, 0.0, -0.897415459,+ -4.511612415, 0.0, 5, 89+ ],+ [+ 0.398073986, 0.09801714, 0.995184727, 0.0, -0.0, -4.599999905, 0.0, 7,+ 93+ ],+ [+ 0.398073915, 0.471396737, 0.881921264, 0.0, -2.555623055,+ -3.824760199, 0.0, 6, 86+ ],+ [+ 0.398073915, 0.471396737, 0.881921264, 0.0, -1.76034379, -4.249845982,+ 0.0, 6, 86+ ],+ [+ 0.573997986, 0.634393284, 0.773010453, 0.0, -1.76034379, -4.249845982,+ 0.0, 6, 82+ ],+ [+ 0.398073915, 0.471396737, 0.881921264, 0.0, -2.555623055,+ -3.824760199, 10.0, 16, 86+ ],+ [+ 0.573997986, 0.634393284, 0.773010453, 0.0, -1.76034379, -4.249845982,+ 10.0, 16, 82+ ],+ [+ 0.398073777, 0.290284677, 0.956940336, 0.0, -0.897415459,+ -4.511612415, 0.0, 5, 90+ ],+ [+ 0.573997989, 0.471396737, 0.881921264, 0.0, -0.897415459,+ -4.511612415, 0.0, 5, 86+ ],+ [+ 0.57399818, 0.290284677, 0.956940336, 0.0, -0.0, -4.599999905, 0.0, 7,+ 90+ ],+ [+ 0.57399818, 0.956940336, 0.290284677, 0.0, -4.599999905, 0.0, 10.0,+ 17, 69+ ],+ [+ 0.573997962, 0.995184727, 0.09801714, 0.0, -4.511612415, 0.897415459,+ 10.0, 18, 65+ ],+ [+ 0.573997957, 0.995184727, -0.09801714, 0.0, -4.249845982, 1.76034379,+ 10.0, 19, 61+ ],+ [+ 0.57399818, 0.956940336, 0.290284677, -0.0, -4.599999905, 0.0, 10.0,+ 17, 70+ ],+ [+ 0.398073986, 0.995184727, 0.09801714, 0.0, -4.599999905, 0.0, 10.0,+ 17, 66+ ],+ [+ 0.573997962, 0.995184727, 0.09801714, 0.0, -4.511612415, 0.897415459,+ 10.0, 18, 66+ ],+ [+ 0.398073986, 0.995184727, -0.09801714, 0.0, -4.599999905, 0.0, 10.0,+ 18, 62+ ],+ [+ 0.398073986, 0.995184727, -0.09801714, 0.0, -4.511612415, 0.897415459,+ 10.0, 18, 62+ ],+ [+ 0.573997957, 0.995184727, -0.09801714, 0.0, -4.249845982, 1.76034379,+ 10.0, 19, 62+ ],+ [+ 0.398073986, -0.09801714, 0.995184727, 0.0, -0.0, -4.599999905, 0.0,+ 8, 97+ ],+ [+ 0.398073986, -0.09801714, 0.995184727, 0.0, 0.897415459, -4.511612415,+ 0.0, 8, 97+ ],+ [+ 0.573997962, 0.09801714, 0.995184727, 0.0, 0.897415459, -4.511612415,+ 0.0, 8, 93+ ],+ [+ 0.573997957, -0.09801714, 0.995184727, 0.0, 1.76034379, -4.249845982,+ 0.0, 9, 97+ ],+ [+ 0.573997962, 0.09801714, 0.995184727, -0.0, 0.897415459, -4.511612415,+ 0.0, 8, 94+ ],+ [+ 0.573997957, -0.09801714, 0.995184727, 0.0, 1.76034379, -4.249845982,+ 0.0, 9, 98+ ],+ [+ 0.573997957, 0.09801714, 0.995184727, 0.0, -1.76034379, -4.249845982,+ 10.0, 11, 93+ ],+ [+ 0.398073764, 0.290284677, 0.956940336, 0.0, -1.76034379, -4.249845982,+ 10.0, 11, 89+ ],+ [+ 0.398073764, 0.290284677, 0.956940336, 0.0, -1.76034379, -4.249845982,+ 10.0, 11, 90+ ],+ [+ 0.398073774, 0.471396737, 0.881921264, 0.0, -1.76034379, -4.249845982,+ 10.0, 11, 86+ ],+ [+ 0.398073774, -0.471396737, 0.881921264, 0.0, 1.76034379, -4.249845982,+ 0.0, 40, 105+ ],+ [+ 0.398073764, -0.290284677, 0.956940336, 0.0, 1.76034379, -4.249845982,+ 0.0, 40, 101+ ],+ [+ 0.398073764, -0.290284677, 0.956940336, -0.0, 1.76034379,+ -4.249845982, 0.0, 40, 102+ ],+ [+ 0.573997957, -0.09801714, 0.995184727, 0.0, 1.76034379, -4.249845982,+ 0.0, 40, 98+ ],+ [+ 0.573997989, -0.471396737, 0.881921264, 0.0, 0.897415459,+ -4.511612415, 10.0, 54, 105+ ],+ [+ 0.573997986, -0.634393284, 0.773010453, 0.0, 1.76034379, -4.249845982,+ 0.0, 41, 109+ ],+ [+ 0.398073915, -0.471396737, 0.881921264, 0.0, 2.555623055,+ -3.824760199, 0.0, 41, 105+ ],+ [+ 0.573997986, -0.634393284, 0.773010453, 0.0, 1.76034379, -4.249845982,+ 10.0, 55, 109+ ],+ [+ 0.398073915, -0.471396737, 0.881921264, 0.0, 2.555623055,+ -3.824760199, 10.0, 55, 105+ ],+ [+ 0.398073915, -0.471396737, 0.881921264, 0.0, 1.76034379, -4.249845982,+ 10.0, 55, 105+ ],+ [+ 0.398073916, -0.634393284, 0.773010453, 0.0, 2.555623055,+ -3.824760199, 0.0, 42, 109+ ],+ [+ 0.398073916, -0.634393284, 0.773010453, 0.0, 3.252691269,+ -3.252691269, 0.0, 42, 109+ ],+ [+ 0.398073916, -0.634393284, 0.773010453, 0.0, 2.555623055,+ -3.824760199, 10.0, 56, 109+ ],+ [+ 0.398073916, -0.773010453, 0.634393284, 0.0, 3.824760199,+ -2.555623055, 0.0, 43, 113+ ],+ [+ 0.398073916, -0.773010453, 0.634393284, 0.0, 3.824760199,+ -2.555623055, 10.0, 57, 113+ ],+ [+ 0.398073916, -0.773010453, 0.634393284, 0.0, 3.252691269,+ -3.252691269, 10.0, 57, 113+ ],+ [+ 0.573998114, -0.773010453, 0.634393284, 0.0, 2.555623055,+ -3.824760199, 0.0, 42, 113+ ],+ [+ 0.573998114, -0.773010453, 0.634393284, 0.0, 2.555623055,+ -3.824760199, 10.0, 56, 113+ ],+ [+ 0.398073777, -0.290284677, 0.956940336, -0.0, 0.897415459,+ -4.511612415, 10.0, 54, 102+ ],+ [+ 0.398073915, -0.471396737, 0.881921264, -0.0, 2.555623055,+ -3.824760199, 0.0, 41, 106+ ],+ [+ 0.398073915, -0.471396737, 0.881921264, -0.0, 2.555623055,+ -3.824760199, 10.0, 55, 106+ ],+ [+ 0.398073915, -0.471396737, 0.881921264, -0.0, 1.76034379,+ -4.249845982, 10.0, 55, 106+ ],+ [+ 0.398073916, -0.773010453, 0.634393284, -0.0, 3.824760199,+ -2.555623055, 0.0, 43, 114+ ],+ [+ 0.573998114, -0.634393284, 0.773010453, -0.0, 3.824760199,+ -2.555623055, 0.0, 43, 110+ ],+ [+ 0.398073916, -0.773010453, 0.634393284, -0.0, 3.824760199,+ -2.555623055, 10.0, 57, 114+ ],+ [+ 0.398073916, -0.773010453, 0.634393284, -0.0, 3.252691269,+ -3.252691269, 10.0, 57, 114+ ],+ [+ 0.573998114, -0.634393284, 0.773010453, -0.0, 3.824760199,+ -2.555623055, 10.0, 57, 110+ ],+ [+ 0.398073916, -0.634393284, 0.773010453, -0.0, 2.555623055,+ -3.824760199, 0.0, 42, 110+ ],+ [+ 0.398073916, -0.634393284, 0.773010453, -0.0, 3.252691269,+ -3.252691269, 0.0, 42, 110+ ],+ [+ 0.398073916, -0.634393284, 0.773010453, -0.0, 2.555623055,+ -3.824760199, 10.0, 56, 110+ ],+ [+ 0.573997957, 0.09801714, 0.995184727, 0.0, -1.76034379, -4.249845982,+ 10.0, 51, 93+ ],+ [+ 0.573997962, -0.09801714, 0.995184727, 0.0, -0.897415459,+ -4.511612415, 10.0, 52, 97+ ],+ [+ 0.57399818, -0.290284677, 0.956940336, 0.0, -0.0, -4.599999905, 10.0,+ 53, 101+ ],+ [+ 0.573997957, 0.09801714, 0.995184727, -0.0, -1.76034379, -4.249845982,+ 10.0, 51, 94+ ],+ [+ 0.398073986, 0.09801714, 0.995184727, -0.0, -0.0, -4.599999905, 10.0,+ 52, 94+ ],+ [+ 0.398073986, 0.09801714, 0.995184727, -0.0, -0.897415459,+ -4.511612415, 10.0, 52, 94+ ],+ [+ 0.573997962, -0.09801714, 0.995184727, 0.0, -0.897415459,+ -4.511612415, 10.0, 52, 98+ ],+ [+ 0.57399818, -0.290284677, 0.956940336, -0.0, -0.0, -4.599999905, 10.0,+ 53, 102+ ],+ [+ 0.398073986, -0.09801714, 0.995184727, 0.0, -0.0, -4.599999905, 10.0,+ 53, 98+ ],+ [+ 0.398073915, -0.881921264, 0.471396737, 0.0, 3.824760199,+ -2.555623055, 10.0, 58, 117+ ],+ [+ 0.398073915, -0.881921264, 0.471396737, 0.0, 3.824760199,+ -2.555623055, 0.0, 44, 117+ ],+ [+ 0.398073915, -0.881921264, 0.471396737, 0.0, 4.249845982, -1.76034379,+ 0.0, 44, 117+ ],+ [+ 0.398073777, -0.956940336, 0.290284677, 0.0, 4.511612415,+ -0.897415459, 0.0, 45, 121+ ],+ [+ 0.398073986, -0.995184727, 0.09801714, 0.0, 4.599999905, 0.0, 0.0, 46,+ 125+ ],+ [+ 0.398073915, -0.881921264, 0.471396737, 0.0, 3.824760199,+ -2.555623055, 10.0, 58, 118+ ],+ [+ 0.573997986, -0.773010453, 0.634393284, -0.0, 4.249845982,+ -1.76034379, 10.0, 58, 114+ ],+ [+ 0.398073915, -0.881921264, 0.471396737, 0.0, 3.824760199,+ -2.555623055, 0.0, 44, 118+ ],+ [+ 0.398073915, -0.881921264, 0.471396737, 0.0, 4.249845982, -1.76034379,+ 0.0, 44, 118+ ],+ [+ 0.573997986, -0.773010453, 0.634393284, -0.0, 4.249845982,+ -1.76034379, 0.0, 44, 114+ ],+ [+ 0.398073777, -0.956940336, 0.290284677, 0.0, 4.511612415,+ -0.897415459, 0.0, 45, 122+ ],+ [+ 0.573997989, -0.881921264, 0.471396737, 0.0, 4.511612415,+ -0.897415459, 0.0, 45, 118+ ],+ [+ 0.57399818, -0.956940336, 0.290284677, 0.0, 4.599999905, 0.0, 0.0, 46,+ 122+ ],+ [+ 0.398073986, -0.995184727, -0.09801714, 0.0, 4.599999905, 0.0, 0.0,+ 47, 1+ ],+ [+ 0.398073986, -0.995184727, -0.09801714, 0.0, 4.511612415, 0.897415459,+ 0.0, 47, 1+ ],+ [+ 0.573997962, -0.995184727, 0.09801714, 0.0, 4.511612415, 0.897415459,+ 0.0, 47, 125+ ],+ [+ 0.573997957, -0.995184727, -0.09801714, 0.0, 4.249845982, 1.76034379,+ 0.0, 48, 1+ ],+ [+ 0.573997957, -0.995184727, -0.09801714, 0.0, 4.249845982, 1.76034379,+ 0.0, 48, 2+ ],+ [+ 0.573997962, -0.995184727, 0.09801714, -0.0, 4.511612415, 0.897415459,+ 0.0, 47, 126+ ],+ [+ 0.573997957, -0.995184727, 0.09801714, 0.0, 4.249845982, -1.76034379,+ 10.0, 59, 125+ ],+ [+ 0.398073764, -0.956940336, 0.290284677, 0.0, 4.249845982, -1.76034379,+ 10.0, 59, 121+ ],+ [+ 0.398073764, -0.956940336, 0.290284677, 0.0, 4.249845982, -1.76034379,+ 10.0, 59, 122+ ],+ [+ 0.398073774, -0.881921264, 0.471396737, 0.0, 4.249845982, -1.76034379,+ 10.0, 59, 118+ ],+ [+ 0.398073774, -0.881921264, -0.471396737, 0.0, 4.249845982, 1.76034379,+ 0.0, 69, 9+ ],+ [+ 0.398073764, -0.956940336, -0.290284677, 0.0, 4.249845982, 1.76034379,+ 0.0, 69, 5+ ],+ [+ 0.573997957, -0.995184727, -0.09801714, 0.0, 4.249845982, 1.76034379,+ 0.0, 69, 2+ ],+ [+ 0.398073764, -0.956940336, -0.290284677, 0.0, 4.249845982, 1.76034379,+ 0.0, 69, 6+ ],+ [+ 0.398073774, 0.881921264, 0.471396737, 0.0, -4.249845982, -1.76034379,+ 0.0, 0, 73+ ],+ [+ 0.398073764, 0.956940336, 0.290284677, 0.0, -4.249845982, -1.76034379,+ 0.0, 0, 69+ ],+ [+ 0.398073764, 0.956940336, 0.290284677, -0.0, -4.249845982,+ -1.76034379, 0.0, 0, 70+ ],+ [+ 0.573997957, 0.995184727, 0.09801714, 0.0, -4.249845982, -1.76034379,+ 0.0, 0, 66+ ],+ [+ 0.573997957, 0.995184727, -0.09801714, 0.0, -4.249845982, 1.76034379,+ 10.0, 30, 61+ ],+ [+ 0.398073764, 0.956940336, -0.290284677, 0.0, -4.249845982, 1.76034379,+ 10.0, 30, 57+ ],+ [+ 0.398073764, 0.956940336, -0.290284677, 0.0, -4.249845982, 1.76034379,+ 10.0, 30, 58+ ],+ [+ 0.398073774, 0.881921264, -0.471396737, -0.0, -4.249845982,+ 1.76034379, 10.0, 30, 54+ ],+ [+ 0.573997957, 0.995184727, 0.09801714, 0.0, -4.249845982, -1.76034379,+ 0.0, 21, 65+ ],+ [+ 0.398073986, 0.995184727, 0.09801714, 0.0, -4.599999905, 0.0, 0.0, 22,+ 65+ ],+ [+ 0.398073986, 0.995184727, 0.09801714, 0.0, -4.511612415, -0.897415459,+ 0.0, 22, 65+ ],+ [+ 0.573997962, 0.995184727, -0.09801714, 0.0, -4.511612415,+ -0.897415459, 0.0, 22, 61+ ],+ [+ 0.573997957, 0.995184727, 0.09801714, 0.0, -4.249845982, -1.76034379,+ 0.0, 21, 66+ ],+ [+ 0.573997962, 0.995184727, -0.09801714, 0.0, -4.511612415,+ -0.897415459, 0.0, 22, 62+ ],+ [+ 0.398073986, 0.995184727, -0.09801714, 0.0, -4.599999905, 0.0, 0.0,+ 23, 61+ ],+ [+ 0.398073777, 0.956940336, -0.290284677, 0.0, -4.511612415,+ 0.897415459, 0.0, 24, 57+ ],+ [+ 0.398073915, 0.881921264, -0.471396737, 0.0, -3.824760199,+ 2.555623055, 0.0, 25, 53+ ],+ [+ 0.398073915, 0.881921264, -0.471396737, 0.0, -4.249845982, 1.76034379,+ 0.0, 25, 53+ ],+ [+ 0.398073915, 0.881921264, -0.471396737, 0.0, -3.824760199,+ 2.555623055, 10.0, 31, 53+ ],+ [+ 0.57399818, 0.956940336, -0.290284677, 0.0, -4.599999905, 0.0, 0.0,+ 23, 58+ ],+ [+ 0.398073777, 0.956940336, -0.290284677, 0.0, -4.511612415,+ 0.897415459, 0.0, 24, 58+ ],+ [+ 0.573997989, 0.881921264, -0.471396737, -0.0, -4.511612415,+ 0.897415459, 0.0, 24, 54+ ],+ [+ 0.398073915, 0.881921264, -0.471396737, -0.0, -3.824760199,+ 2.555623055, 0.0, 25, 54+ ],+ [+ 0.398073915, 0.881921264, -0.471396737, -0.0, -4.249845982,+ 1.76034379, 0.0, 25, 54+ ],+ [+ 0.573997986, 0.773010453, -0.634393284, -0.0, -4.249845982,+ 1.76034379, 0.0, 25, 50+ ],+ [+ 0.398073915, 0.881921264, -0.471396737, -0.0, -3.824760199,+ 2.555623055, 10.0, 31, 54+ ],+ [+ 0.573997986, 0.773010453, -0.634393284, -0.0, -4.249845982,+ 1.76034379, 10.0, 31, 50+ ],+ [+ 0.57399818, 0.290284677, -0.956940336, 0.0, 0.0, 4.599999905, 10.0,+ 36, 37+ ],+ [+ 0.573997962, 0.09801714, -0.995184727, 0.0, 0.897415459, 4.511612415,+ 10.0, 37, 33+ ],+ [+ 0.573997957, -0.09801714, -0.995184727, 0.0, 1.76034379, 4.249845982,+ 10.0, 38, 29+ ],+ [+ 0.57399818, 0.290284677, -0.956940336, -0.0, 0.0, 4.599999905, 10.0,+ 36, 38+ ],+ [+ 0.398073986, 0.09801714, -0.995184727, 0.0, 0.0, 4.599999905, 10.0,+ 36, 34+ ],+ [+ 0.573997962, 0.09801714, -0.995184727, 0.0, 0.897415459, 4.511612415,+ 10.0, 37, 34+ ],+ [+ 0.398073986, -0.09801714, -0.995184727, -0.0, 0.0, 4.599999905, 10.0,+ 37, 30+ ],+ [+ 0.398073986, -0.09801714, -0.995184727, -0.0, 0.897415459,+ 4.511612415, 10.0, 37, 30+ ],+ [+ 0.573997957, -0.09801714, -0.995184727, -0.0, 1.76034379, 4.249845982,+ 10.0, 38, 30+ ],+ [+ 0.398073916, 0.773010453, -0.634393284, 0.0, -3.824760199,+ 2.555623055, 10.0, 32, 49+ ],+ [+ 0.398073916, 0.773010453, -0.634393284, 0.0, -3.252691269,+ 3.252691269, 10.0, 32, 49+ ],+ [+ 0.398073916, 0.773010453, -0.634393284, 0.0, -3.824760199,+ 2.555623055, 0.0, 26, 49+ ],+ [+ 0.573998114, 0.773010453, -0.634393284, 0.0, -2.555623055,+ 3.824760199, 0.0, 27, 49+ ],+ [+ 0.573998114, 0.773010453, -0.634393284, 0.0, -2.555623055,+ 3.824760199, 10.0, 33, 49+ ],+ [+ 0.398073916, 0.634393284, -0.773010453, 0.0, -2.555623055,+ 3.824760199, 0.0, 27, 45+ ],+ [+ 0.398073916, 0.634393284, -0.773010453, 0.0, -3.252691269,+ 3.252691269, 0.0, 27, 45+ ],+ [+ 0.398073916, 0.634393284, -0.773010453, 0.0, -2.555623055,+ 3.824760199, 10.0, 33, 45+ ],+ [+ 0.573997986, 0.634393284, -0.773010453, 0.0, -1.76034379, 4.249845982,+ 10.0, 34, 45+ ],+ [+ 0.398073915, 0.471396737, -0.881921264, 0.0, -2.555623055,+ 3.824760199, 10.0, 34, 41+ ],+ [+ 0.398073915, 0.471396737, -0.881921264, 0.0, -1.76034379, 4.249845982,+ 10.0, 34, 41+ ],+ [+ 0.573997986, 0.634393284, -0.773010453, 0.0, -1.76034379, 4.249845982,+ 0.0, 28, 45+ ],+ [+ 0.398073915, 0.471396737, -0.881921264, 0.0, -2.555623055,+ 3.824760199, 0.0, 28, 41+ ],+ [+ 0.573997989, 0.471396737, -0.881921264, 0.0, -0.897415459,+ 4.511612415, 10.0, 35, 41+ ],+ [+ 0.573998114, 0.634393284, -0.773010453, -0.0, -3.824760199,+ 2.555623055, 10.0, 32, 46+ ],+ [+ 0.573998114, 0.634393284, -0.773010453, -0.0, -3.824760199,+ 2.555623055, 0.0, 26, 46+ ],+ [+ 0.398073916, 0.634393284, -0.773010453, -0.0, -2.555623055,+ 3.824760199, 0.0, 27, 46+ ],+ [+ 0.398073916, 0.634393284, -0.773010453, -0.0, -3.252691269,+ 3.252691269, 0.0, 27, 46+ ],+ [+ 0.398073916, 0.634393284, -0.773010453, -0.0, -2.555623055,+ 3.824760199, 10.0, 33, 46+ ],+ [+ 0.398073915, 0.471396737, -0.881921264, -0.0, -2.555623055,+ 3.824760199, 10.0, 34, 42+ ],+ [+ 0.398073915, 0.471396737, -0.881921264, -0.0, -1.76034379,+ 4.249845982, 10.0, 34, 42+ ],+ [+ 0.398073915, 0.471396737, -0.881921264, -0.0, -2.555623055,+ 3.824760199, 0.0, 28, 42+ ],+ [+ 0.398073777, 0.290284677, -0.956940336, -0.0, -0.897415459,+ 4.511612415, 10.0, 35, 38+ ],+ [+ 0.398073916, 0.773010453, -0.634393284, -0.0, -3.824760199,+ 2.555623055, 10.0, 32, 50+ ],+ [+ 0.398073916, 0.773010453, -0.634393284, -0.0, -3.252691269,+ 3.252691269, 10.0, 32, 50+ ],+ [+ 0.398073916, 0.773010453, -0.634393284, -0.0, -3.824760199,+ 2.555623055, 0.0, 26, 50+ ],+ [+ 0.398073774, 0.471396737, -0.881921264, 0.0, -1.76034379, 4.249845982,+ 0.0, 29, 41+ ],+ [+ 0.398073764, 0.290284677, -0.956940336, 0.0, -1.76034379, 4.249845982,+ 0.0, 29, 37+ ],+ [+ 0.398073764, 0.290284677, -0.956940336, -0.0, -1.76034379,+ 4.249845982, 0.0, 29, 38+ ],+ [+ 0.573997957, 0.09801714, -0.995184727, 0.0, -1.76034379, 4.249845982,+ 0.0, 29, 34+ ],+ [+ 0.573997957, -0.09801714, -0.995184727, 0.0, 1.76034379, 4.249845982,+ 10.0, 78, 29+ ],+ [+ 0.398073764, -0.290284677, -0.956940336, 0.0, 1.76034379, 4.249845982,+ 10.0, 78, 25+ ],+ [+ 0.398073774, -0.471396737, -0.881921264, 0.0, 1.76034379, 4.249845982,+ 10.0, 78, 22+ ],+ [+ 0.398073764, -0.290284677, -0.956940336, 0.0, 1.76034379, 4.249845982,+ 10.0, 78, 26+ ],+ [+ 0.573997957, 0.09801714, -0.995184727, 0.0, -1.76034379, 4.249845982,+ 0.0, 60, 33+ ],+ [+ 0.398073986, 0.09801714, -0.995184727, 0.0, 0.0, 4.599999905, 0.0, 61,+ 33+ ],+ [+ 0.398073986, 0.09801714, -0.995184727, 0.0, -0.897415459, 4.511612415,+ 0.0, 61, 33+ ],+ [+ 0.573997962, -0.09801714, -0.995184727, 0.0, -0.897415459,+ 4.511612415, 0.0, 61, 29+ ],+ [+ 0.573997957, 0.09801714, -0.995184727, 0.0, -1.76034379, 4.249845982,+ 0.0, 60, 34+ ],+ [+ 0.573997962, -0.09801714, -0.995184727, -0.0, -0.897415459,+ 4.511612415, 0.0, 61, 30+ ],+ [+ 0.573997957, -0.995184727, 0.09801714, 0.0, 4.249845982, -1.76034379,+ 10.0, 70, 125+ ],+ [+ 0.573997962, -0.995184727, -0.09801714, 0.0, 4.511612415,+ -0.897415459, 10.0, 71, 1+ ],+ [+ 0.57399818, -0.956940336, -0.290284677, 0.0, 4.599999905, 0.0, 10.0,+ 72, 5+ ],+ [+ 0.573997962, -0.995184727, -0.09801714, 0.0, 4.511612415,+ -0.897415459, 10.0, 71, 2+ ],+ [+ 0.398073986, -0.995184727, -0.09801714, 0.0, 4.599999905, 0.0, 10.0,+ 72, 2+ ],+ [+ 0.573997957, -0.995184727, 0.09801714, -0.0, 4.249845982, -1.76034379,+ 10.0, 70, 126+ ],+ [+ 0.398073986, -0.995184727, 0.09801714, -0.0, 4.599999905, 0.0, 10.0,+ 71, 126+ ],+ [+ 0.398073986, -0.995184727, 0.09801714, -0.0, 4.511612415,+ -0.897415459, 10.0, 71, 126+ ],+ [+ 0.57399818, -0.956940336, -0.290284677, 0.0, 4.599999905, 0.0, 10.0,+ 72, 6+ ],+ [+ 0.398073986, -0.09801714, -0.995184727, 0.0, 0.0, 4.599999905, 0.0,+ 62, 29+ ],+ [+ 0.398073777, -0.290284677, -0.956940336, 0.0, 0.897415459,+ 4.511612415, 0.0, 64, 25+ ],+ [+ 0.398073915, -0.471396737, -0.881921264, 0.0, 2.555623055,+ 3.824760199, 0.0, 63, 21+ ],+ [+ 0.398073915, -0.471396737, -0.881921264, 0.0, 1.76034379, 4.249845982,+ 0.0, 63, 21+ ],+ [+ 0.398073915, -0.471396737, -0.881921264, 0.0, 2.555623055,+ 3.824760199, 10.0, 73, 21+ ],+ [+ 0.573997989, -0.471396737, -0.881921264, 0.0, 0.897415459,+ 4.511612415, 0.0, 64, 22+ ],+ [+ 0.398073915, -0.471396737, -0.881921264, 0.0, 2.555623055,+ 3.824760199, 0.0, 63, 22+ ],+ [+ 0.398073915, -0.471396737, -0.881921264, 0.0, 1.76034379, 4.249845982,+ 0.0, 63, 22+ ],+ [+ 0.573997986, -0.634393284, -0.773010453, 0.0, 1.76034379, 4.249845982,+ 0.0, 63, 18+ ],+ [+ 0.398073915, -0.471396737, -0.881921264, 0.0, 2.555623055,+ 3.824760199, 10.0, 73, 22+ ],+ [+ 0.573997986, -0.634393284, -0.773010453, 0.0, 1.76034379, 4.249845982,+ 10.0, 73, 18+ ],+ [+ 0.57399818, -0.290284677, -0.956940336, 0.0, 0.0, 4.599999905, 0.0,+ 62, 26+ ],+ [+ 0.398073777, -0.290284677, -0.956940336, 0.0, 0.897415459,+ 4.511612415, 0.0, 64, 26+ ],+ [+ 0.573997989, -0.881921264, -0.471396737, 0.0, 4.511612415,+ 0.897415459, 10.0, 77, 9+ ],+ [+ 0.573997986, -0.773010453, -0.634393284, 0.0, 4.249845982, 1.76034379,+ 10.0, 75, 13+ ],+ [+ 0.398073915, -0.881921264, -0.471396737, 0.0, 3.824760199,+ 2.555623055, 10.0, 75, 9+ ],+ [+ 0.398073915, -0.881921264, -0.471396737, 0.0, 4.249845982, 1.76034379,+ 10.0, 75, 9+ ],+ [+ 0.573997986, -0.773010453, -0.634393284, 0.0, 4.249845982, 1.76034379,+ 0.0, 66, 13+ ],+ [+ 0.398073915, -0.881921264, -0.471396737, 0.0, 3.824760199,+ 2.555623055, 0.0, 66, 9+ ],+ [+ 0.398073916, -0.634393284, -0.773010453, 0.0, 2.555623055,+ 3.824760199, 10.0, 74, 17+ ],+ [+ 0.398073916, -0.634393284, -0.773010453, 0.0, 3.252691269,+ 3.252691269, 10.0, 74, 17+ ],+ [+ 0.573998114, -0.634393284, -0.773010453, 0.0, 3.824760199,+ 2.555623055, 0.0, 67, 17+ ],+ [+ 0.398073916, -0.634393284, -0.773010453, 0.0, 2.555623055,+ 3.824760199, 0.0, 65, 17+ ],+ [+ 0.573998114, -0.634393284, -0.773010453, 0.0, 3.824760199,+ 2.555623055, 10.0, 76, 17+ ],+ [+ 0.398073916, -0.773010453, -0.634393284, 0.0, 3.824760199,+ 2.555623055, 0.0, 67, 13+ ],+ [+ 0.398073916, -0.773010453, -0.634393284, 0.0, 3.252691269,+ 3.252691269, 0.0, 67, 13+ ],+ [+ 0.398073916, -0.773010453, -0.634393284, 0.0, 3.824760199,+ 2.555623055, 10.0, 76, 13+ ],+ [+ 0.398073915, -0.881921264, -0.471396737, 0.0, 3.824760199,+ 2.555623055, 10.0, 75, 10+ ],+ [+ 0.398073915, -0.881921264, -0.471396737, 0.0, 4.249845982, 1.76034379,+ 10.0, 75, 10+ ],+ [+ 0.398073915, -0.881921264, -0.471396737, 0.0, 3.824760199,+ 2.555623055, 0.0, 66, 10+ ],+ [+ 0.398073916, -0.634393284, -0.773010453, 0.0, 2.555623055,+ 3.824760199, 10.0, 74, 18+ ],+ [+ 0.398073916, -0.634393284, -0.773010453, 0.0, 3.252691269,+ 3.252691269, 10.0, 74, 18+ ],+ [+ 0.398073916, -0.634393284, -0.773010453, 0.0, 2.555623055,+ 3.824760199, 0.0, 65, 18+ ],+ [+ 0.398073777, -0.956940336, -0.290284677, 0.0, 4.511612415,+ 0.897415459, 10.0, 77, 6+ ],+ [+ 0.573998114, -0.773010453, -0.634393284, 0.0, 2.555623055,+ 3.824760199, 10.0, 74, 14+ ],+ [+ 0.398073916, -0.773010453, -0.634393284, 0.0, 3.824760199,+ 2.555623055, 0.0, 67, 14+ ],+ [+ 0.398073916, -0.773010453, -0.634393284, 0.0, 3.252691269,+ 3.252691269, 0.0, 67, 14+ ],+ [+ 0.573998114, -0.773010453, -0.634393284, 0.0, 2.555623055,+ 3.824760199, 0.0, 65, 14+ ],+ [+ 0.398073916, -0.773010453, -0.634393284, 0.0, 3.824760199,+ 2.555623055, 10.0, 76, 14+ ]+ ]+ },+ {+ "name": "box_box_gap_3",+ "a": {+ "verts": [+ -5.0, -5.0, -5.0, -5.0, -5.0, 5.0, -5.0, 5.0, -5.0, -5.0, 5.0, 5.0,+ 5.0, -5.0, -5.0, 5.0, -5.0, 5.0, 5.0, 5.0, -5.0, 5.0, 5.0, 5.0+ ],+ "faces": [+ 1, 3, 0, 4, 1, 0, 0, 3, 2, 2, 4, 0, 1, 7, 3, 5, 1, 4, 5, 7, 1, 3, 7,+ 2, 6, 4, 2, 2, 7, 6, 6, 5, 4, 7, 5, 6+ ]+ },+ "b": {+ "verts": [+ 8.0, -5.0, -5.0, 8.0, -5.0, 5.0, 8.0, 5.0, -5.0, 8.0, 5.0, 5.0, 18.0,+ -5.0, -5.0, 18.0, -5.0, 5.0, 18.0, 5.0, -5.0, 18.0, 5.0, 5.0+ ],+ "faces": [+ 1, 3, 0, 4, 1, 0, 0, 3, 2, 2, 4, 0, 1, 7, 3, 5, 1, 4, 5, 7, 1, 3, 7,+ 2, 6, 4, 2, 2, 7, 6, 6, 5, 4, 7, 5, 6+ ]+ },+ "distance": 3.0+ }+ ]+}diff --git a/crates/collision/tests/calibration.rs b/crates/collision/tests/calibration.rsnew file mode 100644index 0000000000..6f829ef52a--- /dev/null+++ b/crates/collision/tests/calibration.rs@@ -0,0 +1,105 @@+//! Byte-parity proof: the Rust FCL bridge must reproduce python-fcl's contacts+//! and distances exactly (fixture generated from python-fcl 0.7.0.11 / FCL 0.7.0).++use collision::{collide_pair, distance_pair, new_bvh};+use serde_json::Value;++fn f64s(v: &Value) -> Vec<f64> {+ v.as_array()+ .unwrap()+ .iter()+ .map(|x| x.as_f64().unwrap())+ .collect()+}++fn u32s(v: &Value) -> Vec<u32> {+ v.as_array()+ .unwrap()+ .iter()+ .map(|x| x.as_i64().unwrap() as u32)+ .collect()+}++/// Round to 6 dp and pack a contact into a comparable key (absorbs last-ULP+/// noise between the two FCL builds; still far tighter than the 0.15mm planner+/// tolerance).+fn key(depth: f64, n: [f64; 3], p: [f64; 3], b1: i64, b2: i64) -> String {+ let r = |x: f64| (x * 1e6).round() as i64;+ format!(+ "{}|{},{},{}|{},{},{}|{},{}",+ r(depth),+ r(n[0]),+ r(n[1]),+ r(n[2]),+ r(p[0]),+ r(p[1]),+ r(p[2]),+ b1,+ b2+ )+}++#[test]+fn rust_fcl_matches_python_fcl() {+ let path = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/calibration.json");+ let data: Value = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();++ for case in data["cases"].as_array().unwrap() {+ let name = case["name"].as_str().unwrap();+ let a = new_bvh(&f64s(&case["a"]["verts"]), &u32s(&case["a"]["faces"]));+ let b = new_bvh(&f64s(&case["b"]["verts"]), &u32s(&case["b"]["faces"]));++ if let Some(expected) = case.get("contacts").and_then(|c| c.as_array()) {+ let got = collide_pair(&a, 0.0, 0.0, 0.0, &b, 0.0, 0.0, 0.0, 100_000);+ assert_eq!(+ got.len(),+ expected.len(),+ "[{name}] contact count: rust={} python={}",+ got.len(),+ expected.len()+ );++ let mut got_keys: Vec<String> = got+ .iter()+ .map(|c| {+ key(+ c.depth,+ [c.nx, c.ny, c.nz],+ [c.px, c.py, c.pz],+ c.b1 as i64,+ c.b2 as i64,+ )+ })+ .collect();+ let mut exp_keys: Vec<String> = expected+ .iter()+ .map(|c| {+ let a = f64s(c);+ key(+ a[0],+ [a[1], a[2], a[3]],+ [a[4], a[5], a[6]],+ a[7] as i64,+ a[8] as i64,+ )+ })+ .collect();+ got_keys.sort();+ exp_keys.sort();+ assert_eq!(got_keys, exp_keys, "[{name}] contact multiset mismatch");++ let max_got = got.iter().map(|c| c.depth).fold(f64::MIN, f64::max);+ let max_exp = expected.iter().map(|c| f64s(c)[0]).fold(f64::MIN, f64::max);+ assert!(+ (max_got - max_exp).abs() < 1e-6,+ "[{name}] max depth: rust={max_got} python={max_exp}"+ );+ } else if let Some(expected) = case.get("distance").and_then(|d| d.as_f64()) {+ let got = distance_pair(&a, &b);+ assert!(+ (got - expected).abs() < 1e-6,+ "[{name}] distance: rust={got} python={expected}"+ );+ }+ }+}diff --git a/crates/converter/Cargo.toml b/crates/converter/Cargo.tomlnew file mode 100644index 0000000000..87ad1afa7c--- /dev/null+++ b/crates/converter/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "converter"+version.workspace = true+edition.workspace = true+license.workspace = true++# STEP -> GLB + graph.json. Deterministic pieces (nodeId, graph, GLB) are pure;+# STEP ingestion + tessellation come from the occt-bridge crate (Phase B).++[dependencies]+occt-bridge = { path = "../occt-bridge" }+nalgebra.workspace = true+serde.workspace = true+serde_json.workspace = true+sha1.workspace = true+regex = "1"diff --git a/crates/converter/examples/conc_convert.rs b/crates/converter/examples/conc_convert.rsnew file mode 100644index 0000000000..c716798606--- /dev/null+++ b/crates/converter/examples/conc_convert.rs@@ -0,0 +1,74 @@+//! Concurrency correctness + scaling probe for the full convert path. Each of N+//! threads runs convert_step in a loop and hashes the ENTIRE output (glb bytes ++//! graph json). If concurrent reads corrupt anything — e.g. the OCCT 7.9.3+//! shared-Bigint strtod race that mis-parses floats under load — the hash set+//! grows beyond one. One distinct hash across all threads == bit-for-bit+//! deterministic under concurrency. Also reports throughput scaling.+//!+//! cargo run --release -p converter --example conc_convert -- <file.step> [iters]++use sha1::{Digest, Sha1};+use std::collections::HashSet;+use std::sync::{Arc, Mutex};+use std::time::Instant;++fn hash_output(step_path: &str, text: &str) -> String {+ let c = converter::convert::convert_step(step_path, text, 0.1, 0.5).expect("convert failed");+ let mut h = Sha1::new();+ h.update(&c.glb);+ h.update(serde_json::to_vec(&c.graph).unwrap());+ format!("{:x}", h.finalize())+}++fn run(path: &Arc<String>, text: &Arc<String>, threads: usize, iters: usize) -> (f64, HashSet<String>) {+ let hashes = Arc::new(Mutex::new(HashSet::new()));+ let start = Instant::now();+ let mut handles = Vec::new();+ for _ in 0..threads {+ let (p, t, hs) = (Arc::clone(path), Arc::clone(text), Arc::clone(&hashes));+ handles.push(std::thread::spawn(move || {+ for _ in 0..iters {+ let hash = hash_output(p.as_str(), t.as_str());+ hs.lock().unwrap().insert(hash);+ }+ }));+ }+ for h in handles {+ h.join().expect("thread panicked");+ }+ let secs = start.elapsed().as_secs_f64();+ let rps = (threads * iters) as f64 / secs;+ let set = Arc::try_unwrap(hashes).unwrap().into_inner().unwrap();+ (rps, set)+}++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let path = Arc::new(args.get(1).cloned().expect("usage: conc_convert <file.step> [iters]"));+ let iters: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(20);+ let text = Arc::new(std::fs::read_to_string(path.as_str()).expect("read step"));+ let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(8);++ // Establish the golden hash single-threaded.+ let golden = hash_output(path.as_str(), text.as_str());+ println!("golden (T=1, serial): {golden}");++ let (rps1, _) = run(&path, &text, 1, iters);+ println!("T= 1: {rps1:7.2} conv/s (baseline)");++ let sweep: Vec<usize> = std::env::var("SWEEP")+ .ok()+ .map(|s| s.split(',').filter_map(|x| x.parse().ok()).collect())+ .unwrap_or_else(|| vec![2, 4, cores]);+ for &t in &sweep {+ let (rps, set) = run(&path, &text, t, iters);+ let scale = rps / rps1;+ let clean = set.len() == 1 && set.contains(&golden);+ println!(+ "T={t:2}: {rps:7.2} conv/s {scale:4.2}x {} ({} distinct hash{})",+ if clean { "CORRECT" } else { "!! CORRUPTION !!" },+ set.len(),+ if set.len() == 1 { "" } else { "es" },+ );+ }+}diff --git a/crates/converter/examples/convert_file.rs b/crates/converter/examples/convert_file.rsnew file mode 100644index 0000000000..ce376edbe2--- /dev/null+++ b/crates/converter/examples/convert_file.rs@@ -0,0 +1,18 @@+//! Convert a STEP file and write its graph.json. Usage:+//! cargo run -p converter --example convert_file -- <in.step> <out.graph.json>++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let step = &args[1];+ let out = &args[2];+ let text = std::fs::read_to_string(step).unwrap_or_default();+ let t = std::time::Instant::now();+ let conv = converter::convert::convert_step(step, &text, 0.1, 0.5).expect("convert");+ std::fs::write(out, serde_json::to_vec(&conv.graph).unwrap()).unwrap();+ eprintln!(+ "comps={} tris={} {:.1}s -> {out}",+ conv.component_count,+ conv.triangles,+ t.elapsed().as_secs_f64()+ );+}diff --git a/crates/converter/src/convert.rs b/crates/converter/src/convert.rsnew file mode 100644index 0000000000..490f12d81d--- /dev/null+++ b/crates/converter/src/convert.rs@@ -0,0 +1,118 @@+//! STEP → graph.json (+ GLB) driver. Reads the OCCT tree from the occt-bridge,+//! assigns nodeIds, computes world bboxes, emits graph.json. Mirrors+//! `app/convert.py::convert_step`.++use crate::graph::{+ assign_node_ids, build_graph, compute_world_bboxes, count_leaves, count_triangles,+ detect_source_unit, AssemblyNode, PartMesh,+};+use nalgebra::Matrix4;+use serde_json::Value;++pub struct Conversion {+ pub graph: Value,+ pub glb: Vec<u8>,+ pub root: AssemblyNode,+ pub component_count: i64,+ pub triangles: i64,+}++#[derive(Debug)]+pub struct ConvertError {+ pub code: String,+ pub message: String,+}++impl ConvertError {+ pub fn new(code: &str, message: impl Into<String>) -> Self {+ ConvertError {+ code: code.to_string(),+ message: message.into(),+ }+ }+}++fn to_node(tree: &occt_bridge::Tree, index: u64) -> AssemblyNode {+ let raw = &tree.nodes[index as usize];+ let mut transform = [0.0f64; 16];+ for (i, v) in raw.transform.iter().take(16).enumerate() {+ transform[i] = *v;+ }+ let mesh = if raw.has_mesh {+ let positions: Vec<[f32; 3]> = raw+ .vertices+ .chunks_exact(3)+ .map(|c| [c[0], c[1], c[2]])+ .collect();+ let indices: Vec<[u32; 3]> = raw+ .indices+ .chunks_exact(3)+ .map(|c| [c[0], c[1], c[2]])+ .collect();+ Some(PartMesh::new(positions, indices, raw.is_proxy))+ } else {+ None+ };+ let color = if raw.has_color && raw.color.len() == 4 {+ Some([raw.color[0], raw.color[1], raw.color[2], raw.color[3]])+ } else {+ None+ };+ let volume = if raw.has_volume {+ Some(raw.volume)+ } else {+ None+ };+ let children = raw.children.iter().map(|&c| to_node(tree, c)).collect();+ AssemblyNode {+ name: raw.name.clone(),+ product_name: raw.product_name.clone(),+ transform,+ is_assembly: raw.is_assembly,+ mesh,+ color,+ volume,+ children,+ node_id: String::new(),+ bbox_min: [0.0; 3],+ bbox_max: [0.0; 3],+ }+}++/// Read a STEP file into the assembly tree with nodeIds + world bboxes assigned,+/// without emitting graph.json or GLB. Shared by `convert_step` and the planner.+pub fn build_tree(+ step_path: &str,+ linear_deflection: f64,+ angular_deflection: f64,+) -> Result<AssemblyNode, ConvertError> {+ let tree = occt_bridge::read_step(step_path, linear_deflection, angular_deflection);+ if !tree.ok {+ return Err(ConvertError::new("READ_FAILED", tree.error.clone()));+ }+ let mut root = to_node(&tree, tree.root_index);+ assign_node_ids(&mut root);+ compute_world_bboxes(&mut root, &Matrix4::identity());+ Ok(root)+}++pub fn convert_step(+ step_path: &str,+ step_text: &str,+ linear_deflection: f64,+ angular_deflection: f64,+) -> Result<Conversion, ConvertError> {+ let source_unit = detect_source_unit(step_text);+ let root = build_tree(step_path, linear_deflection, angular_deflection)?;+ let component_count = count_leaves(&root);+ let triangles = count_triangles(&root);+ let graph = build_graph(&root, &source_unit);+ let glb = crate::glb::write_glb(&root);+ Ok(Conversion {+ graph,+ glb,+ root,+ component_count,+ triangles,+ })+}diff --git a/crates/converter/src/glb.rs b/crates/converter/src/glb.rsnew file mode 100644index 0000000000..fdb5561818--- /dev/null+++ b/crates/converter/src/glb.rs@@ -0,0 +1,244 @@+//! Write a GLB from the tessellated assembly tree — port of `app/glb.py`. The+//! glTF node tree mirrors graph.json 1:1, every node carries `extras.nodeId`,+//! identical parts (same geometryHash) share one mesh, materials dedupe by RGBA.+//! We write the container ourselves (not byte-identical to pygltflib, but the+//! same node/mesh/material contract the viewer depends on).++use crate::graph::{AssemblyNode, PartMesh};+use serde_json::{json, Value};+use std::collections::HashMap;++const ARRAY_BUFFER: i64 = 34962;+const ELEMENT_ARRAY_BUFFER: i64 = 34963;+const FLOAT: i64 = 5126;+const UNSIGNED_INT: i64 = 5125;+const DEFAULT_COLOR: [f64; 4] = [0.65, 0.65, 0.65, 1.0];+const IDENTITY: [f64; 16] = [+ 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,+];++struct Builder {+ blob: Vec<u8>,+ buffer_views: Vec<Value>,+ accessors: Vec<Value>,+ meshes: Vec<Value>,+ materials: Vec<Value>,+ nodes: Vec<Value>,+ mesh_by_hash: HashMap<String, usize>,+ material_by_color: HashMap<String, usize>,+}++impl Builder {+ fn new() -> Self {+ Builder {+ blob: Vec::new(),+ buffer_views: Vec::new(),+ accessors: Vec::new(),+ meshes: Vec::new(),+ materials: Vec::new(),+ nodes: Vec::new(),+ mesh_by_hash: HashMap::new(),+ material_by_color: HashMap::new(),+ }+ }++ fn append_buffer_view(&mut self, data: &[u8], target: i64) -> usize {+ while self.blob.len() % 4 != 0 {+ self.blob.push(0);+ }+ let offset = self.blob.len();+ self.blob.extend_from_slice(data);+ self.buffer_views.push(json!({+ "buffer": 0, "byteOffset": offset, "byteLength": data.len(), "target": target+ }));+ self.buffer_views.len() - 1+ }++ fn material(&mut self, color: Option<[f64; 4]>) -> usize {+ let rgba = color.unwrap_or(DEFAULT_COLOR);+ let key = format!("{:?}", rgba);+ if let Some(&i) = self.material_by_color.get(&key) {+ return i;+ }+ self.materials.push(json!({+ "pbrMetallicRoughness": {+ "baseColorFactor": rgba.to_vec(),+ "metallicFactor": 0.1,+ "roughnessFactor": 0.8+ },+ "alphaMode": if rgba[3] < 1.0 { "BLEND" } else { "OPAQUE" },+ "doubleSided": false+ }));+ let i = self.materials.len() - 1;+ self.material_by_color.insert(key, i);+ i+ }++ fn mesh(&mut self, part: &PartMesh, color: Option<[f64; 4]>, name: &str) -> usize {+ if let Some(&i) = self.mesh_by_hash.get(&part.geometry_hash) {+ return i;+ }+ let positions = &part.positions;+ let normals = vertex_normals(positions, &part.indices);++ let mut pos_bytes = Vec::with_capacity(positions.len() * 12);+ let mut min = [f32::INFINITY; 3];+ let mut max = [f32::NEG_INFINITY; 3];+ for p in positions {+ for k in 0..3 {+ pos_bytes.extend_from_slice(&p[k].to_le_bytes());+ min[k] = min[k].min(p[k]);+ max[k] = max[k].max(p[k]);+ }+ }+ let mut nrm_bytes = Vec::with_capacity(normals.len() * 12);+ for n in &normals {+ for k in 0..3 {+ nrm_bytes.extend_from_slice(&n[k].to_le_bytes());+ }+ }+ let mut idx_bytes = Vec::with_capacity(part.indices.len() * 12);+ let mut idx_count = 0usize;+ for tri in &part.indices {+ for &i in tri {+ idx_bytes.extend_from_slice(&i.to_le_bytes());+ idx_count += 1;+ }+ }++ let pos_view = self.append_buffer_view(&pos_bytes, ARRAY_BUFFER);+ let nrm_view = self.append_buffer_view(&nrm_bytes, ARRAY_BUFFER);+ let idx_view = self.append_buffer_view(&idx_bytes, ELEMENT_ARRAY_BUFFER);++ self.accessors.push(json!({+ "bufferView": pos_view, "componentType": FLOAT, "count": positions.len(),+ "type": "VEC3", "min": min.to_vec(), "max": max.to_vec()+ }));+ let pos_acc = self.accessors.len() - 1;+ self.accessors.push(json!({+ "bufferView": nrm_view, "componentType": FLOAT, "count": normals.len(), "type": "VEC3"+ }));+ let nrm_acc = self.accessors.len() - 1;+ self.accessors.push(json!({+ "bufferView": idx_view, "componentType": UNSIGNED_INT, "count": idx_count, "type": "SCALAR"+ }));+ let idx_acc = self.accessors.len() - 1;++ let material = self.material(color);+ self.meshes.push(json!({+ "name": name,+ "primitives": [{+ "attributes": {"POSITION": pos_acc, "NORMAL": nrm_acc},+ "indices": idx_acc,+ "material": material+ }]+ }));+ let i = self.meshes.len() - 1;+ self.mesh_by_hash.insert(part.geometry_hash.clone(), i);+ i+ }++ fn add_node(&mut self, node: &AssemblyNode) -> usize {+ let mut gltf_node = json!({"name": node.name, "extras": {"nodeId": node.node_id}});+ if node.transform != IDENTITY {+ gltf_node["matrix"] = json!(node.transform.to_vec());+ }+ if let Some(mesh) = &node.mesh {+ if !mesh.positions.is_empty() {+ let m = self.mesh(mesh, node.color, &node.product_name);+ gltf_node["mesh"] = json!(m);+ }+ }+ self.nodes.push(gltf_node);+ let index = self.nodes.len() - 1;+ let children: Vec<usize> = node.children.iter().map(|c| self.add_node(c)).collect();+ if !children.is_empty() {+ self.nodes[index]["children"] = json!(children);+ }+ index+ }+}++/// Area-weighted smooth vertex normals — port of `_vertex_normals`.+fn vertex_normals(positions: &[[f32; 3]], indices: &[[u32; 3]]) -> Vec<[f32; 3]> {+ let mut normals = vec![[0.0f64; 3]; positions.len()];+ for tri in indices {+ let a = positions[tri[0] as usize];+ let b = positions[tri[1] as usize];+ let c = positions[tri[2] as usize];+ let ab = [+ (b[0] - a[0]) as f64,+ (b[1] - a[1]) as f64,+ (b[2] - a[2]) as f64,+ ];+ let ac = [+ (c[0] - a[0]) as f64,+ (c[1] - a[1]) as f64,+ (c[2] - a[2]) as f64,+ ];+ let fn_ = [+ ab[1] * ac[2] - ab[2] * ac[1],+ ab[2] * ac[0] - ab[0] * ac[2],+ ab[0] * ac[1] - ab[1] * ac[0],+ ];+ for &v in tri {+ for k in 0..3 {+ normals[v as usize][k] += fn_[k];+ }+ }+ }+ normals+ .into_iter()+ .map(|n| {+ let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();+ let l = if len == 0.0 { 1.0 } else { len };+ [(n[0] / l) as f32, (n[1] / l) as f32, (n[2] / l) as f32]+ })+ .collect()+}++/// Write the GLB container (binary glTF) for the assembly tree.+pub fn write_glb(root: &AssemblyNode) -> Vec<u8> {+ let mut b = Builder::new();+ let root_index = b.add_node(root);++ let mut gltf = json!({+ "asset": {"version": "2.0", "generator": "carbon-assembler"},+ "scene": 0,+ "scenes": [{"nodes": [root_index]}],+ "nodes": b.nodes,+ "meshes": b.meshes,+ "accessors": b.accessors,+ "bufferViews": b.buffer_views,+ "materials": b.materials,+ });+ if !b.blob.is_empty() {+ gltf["buffers"] = json!([{"byteLength": b.blob.len()}]);+ }++ let mut json_bytes = serde_json::to_vec(&gltf).unwrap();+ while json_bytes.len() % 4 != 0 {+ json_bytes.push(b' ');+ }+ let mut bin = b.blob;+ while bin.len() % 4 != 0 {+ bin.push(0);+ }++ let total = 12 + 8 + json_bytes.len() + if bin.is_empty() { 0 } else { 8 + bin.len() };+ let mut out = Vec::with_capacity(total);+ out.extend_from_slice(b"glTF");+ out.extend_from_slice(&2u32.to_le_bytes());+ out.extend_from_slice(&(total as u32).to_le_bytes());+ // JSON chunk+ out.extend_from_slice(&(json_bytes.len() as u32).to_le_bytes());+ out.extend_from_slice(b"JSON");+ out.extend_from_slice(&json_bytes);+ // BIN chunk+ if !bin.is_empty() {+ out.extend_from_slice(&(bin.len() as u32).to_le_bytes());+ out.extend_from_slice(&[b'B', b'I', b'N', 0]);+ out.extend_from_slice(&bin);+ }+ out+}diff --git a/crates/converter/src/graph.rs b/crates/converter/src/graph.rsnew file mode 100644index 0000000000..b969981207--- /dev/null+++ b/crates/converter/src/graph.rs@@ -0,0 +1,266 @@+//! Assembly tree, world bboxes, source-unit detection, and graph.json emission —+//! ported 1:1 from `app/convert.py`. Deterministic; no OCCT.++use crate::nodeid::{geometry_hash, node_id};+use nalgebra::{Matrix4, Vector3};+use regex::Regex;+use serde_json::{json, Value};+use std::collections::HashMap;+use std::sync::OnceLock;++pub const GRAPH_VERSION: i64 = 1;+pub const OUTPUT_UNIT: &str = "mm";++pub const IDENTITY_4X4: [f64; 16] = [+ 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,+];++#[derive(Debug, Clone)]+pub struct PartMesh {+ pub positions: Vec<[f32; 3]>, // part-local, mm+ pub indices: Vec<[u32; 3]>,+ pub geometry_hash: String,+ pub is_proxy: bool,+}++impl PartMesh {+ pub fn new(positions: Vec<[f32; 3]>, indices: Vec<[u32; 3]>, is_proxy: bool) -> Self {+ let geometry_hash = geometry_hash(&positions, &indices);+ PartMesh {+ positions,+ indices,+ geometry_hash,+ is_proxy,+ }+ }+}++#[derive(Debug, Clone)]+pub struct AssemblyNode {+ pub name: String,+ pub product_name: String,+ pub transform: [f64; 16], // local 4x4, column-major+ pub is_assembly: bool,+ pub mesh: Option<PartMesh>,+ pub color: Option<[f64; 4]>,+ pub volume: Option<f64>,+ pub children: Vec<AssemblyNode>,+ pub node_id: String,+ pub bbox_min: [f64; 3],+ pub bbox_max: [f64; 3],+}++impl AssemblyNode {+ fn hash_key(&self) -> &str {+ self.mesh+ .as_ref()+ .map(|m| m.geometry_hash.as_str())+ .unwrap_or("")+ }+}++// --- source unit detection ---------------------------------------------------++fn unit_names(name: &str) -> Option<&'static str> {+ match name {+ "INCH" => Some("inch"),+ "FOOT" => Some("foot"),+ "MILE" => Some("mile"),+ "YARD" => Some("yard"),+ _ => None,+ }+}++fn si_prefix(p: &str) -> &'static str {+ match p {+ "MILLI" => "mm",+ "CENTI" => "cm",+ "DECI" => "dm",+ "MICRO" => "um",+ "KILO" => "km",+ _ => "m",+ }+}++/// `_detect_source_unit`: best-effort read of the STEP declared length unit.+pub fn detect_source_unit(text: &str) -> String {+ static STMT: OnceLock<Regex> = OnceLock::new();+ static CONV: OnceLock<Regex> = OnceLock::new();+ static SI: OnceLock<Regex> = OnceLock::new();+ let stmt =+ STMT.get_or_init(|| Regex::new(r"(?s)\(([^;]*?LENGTH_UNIT\(\)[^;]*?)\)\s*;").unwrap());+ let conv = CONV.get_or_init(|| Regex::new(r"CONVERSION_BASED_UNIT\s*\(\s*'([^']+)'").unwrap());+ let si =+ SI.get_or_init(|| Regex::new(r"SI_UNIT\s*\(\s*(?:\.(\w+)\.|\$)\s*,\s*\.METRE\.").unwrap());++ let cap = 32 * 1024 * 1024;+ let text = if text.len() > cap { &text[..cap] } else { text };++ for m in stmt.captures_iter(text) {+ let body = &m[1];+ if let Some(c) = conv.captures(body) {+ let name = c[1].to_uppercase();+ return unit_names(&name)+ .map(|s| s.to_string())+ .unwrap_or_else(|| c[1].to_lowercase());+ }+ if let Some(c) = si.captures(body) {+ let prefix = c.get(1).map(|g| g.as_str()).unwrap_or("");+ return si_prefix(prefix).to_string();+ }+ }+ OUTPUT_UNIT.to_string()+}++// --- stable node IDs ---------------------------------------------------------++pub fn assign_node_ids(root: &mut AssemblyNode) {+ root.node_id = node_id(root.hash_key(), "", 0);+ assign_child_ids(root, "");+}++fn assign_child_ids(node: &mut AssemblyNode, parent_path: &str) {+ let path = if parent_path.is_empty() {+ node.product_name.clone()+ } else {+ format!("{parent_path}/{}", node.product_name)+ };+ let mut ordinals: HashMap<String, usize> = HashMap::new();+ for child in &mut node.children {+ let key = child.hash_key().to_string();+ let ordinal = *ordinals.get(&key).unwrap_or(&0);+ ordinals.insert(key.clone(), ordinal + 1);+ child.node_id = node_id(&key, &path, ordinal);+ assign_child_ids(child, &path);+ }+}++// --- world-space bounding boxes ----------------------------------------------++pub fn compute_world_bboxes(node: &mut AssemblyNode, parent_world: &Matrix4<f64>) {+ let local = Matrix4::from_column_slice(&node.transform);+ let world = parent_world * local;+ let r = world.fixed_view::<3, 3>(0, 0).into_owned();+ let t = Vector3::new(world[(0, 3)], world[(1, 3)], world[(2, 3)]);++ if let Some(mesh) = &node.mesh {+ if !mesh.positions.is_empty() {+ let mut lo = Vector3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);+ let mut hi = Vector3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+ for p in &mesh.positions {+ let v = Vector3::new(p[0] as f64, p[1] as f64, p[2] as f64);+ let w = r * v + t;+ lo = lo.inf(&w);+ hi = hi.sup(&w);+ }+ node.bbox_min = [lo[0], lo[1], lo[2]];+ node.bbox_max = [hi[0], hi[1], hi[2]];+ } else {+ node.bbox_min = [t[0], t[1], t[2]];+ node.bbox_max = [t[0], t[1], t[2]];+ }+ } else {+ node.bbox_min = [t[0], t[1], t[2]];+ node.bbox_max = [t[0], t[1], t[2]];+ }++ for child in &mut node.children {+ compute_world_bboxes(child, &world);+ }++ if !node.children.is_empty() {+ let mut lo = Vector3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);+ let mut hi = Vector3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+ for c in &node.children {+ lo = lo.inf(&Vector3::new(c.bbox_min[0], c.bbox_min[1], c.bbox_min[2]));+ hi = hi.sup(&Vector3::new(c.bbox_max[0], c.bbox_max[1], c.bbox_max[2]));+ }+ let has_mesh = node+ .mesh+ .as_ref()+ .map(|m| !m.positions.is_empty())+ .unwrap_or(false);+ if has_mesh {+ lo = lo.inf(&Vector3::new(+ node.bbox_min[0],+ node.bbox_min[1],+ node.bbox_min[2],+ ));+ hi = hi.sup(&Vector3::new(+ node.bbox_max[0],+ node.bbox_max[1],+ node.bbox_max[2],+ ));+ }+ node.bbox_min = [lo[0], lo[1], lo[2]];+ node.bbox_max = [hi[0], hi[1], hi[2]];+ }+}++// --- graph.json --------------------------------------------------------------++pub fn count_leaves(node: &AssemblyNode) -> i64 {+ if !node.is_assembly {+ return 1;+ }+ node.children.iter().map(count_leaves).sum()+}++pub fn count_triangles(node: &AssemblyNode) -> i64 {+ let own = node+ .mesh+ .as_ref()+ .map(|m| m.indices.len() as i64)+ .unwrap_or(0);+ own + node.children.iter().map(count_triangles).sum::<i64>()+}++pub fn node_to_dict(node: &AssemblyNode) -> Value {+ json!({+ "nodeId": node.node_id,+ "name": node.name,+ "isAssembly": node.is_assembly,+ "geometryHash": node.mesh.as_ref().map(|m| m.geometry_hash.clone()),+ "transform": node.transform.to_vec(),+ "bbox": {"min": node.bbox_min.to_vec(), "max": node.bbox_max.to_vec()},+ "volume": if node.is_assembly { Value::Null } else { node.volume.map(|v| json!(v)).unwrap_or(Value::Null) },+ "color": node.color.map(|c| c.to_vec()),+ "children": node.children.iter().map(node_to_dict).collect::<Vec<_>>(),+ })+}++pub fn build_graph(root: &AssemblyNode, source_unit: &str) -> Value {+ json!({+ "version": GRAPH_VERSION,+ "unit": OUTPUT_UNIT,+ "sourceUnit": source_unit,+ "componentCount": count_leaves(root),+ "root": node_to_dict(root),+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn source_unit_detection() {+ // Cases from the former Python service's test_source_unit_detection.+ assert_eq!(+ detect_source_unit("DATA;\n#41=( CONVERSION_BASED_UNIT('INCH',#38) LENGTH_UNIT() NAMED_UNIT(#40) );\nENDSEC;"),+ "inch"+ );+ assert_eq!(+ detect_source_unit(+ "DATA;\n#41=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT($,.METRE.) );\nENDSEC;"+ ),+ "m"+ );+ assert_eq!(detect_source_unit("DATA;\nENDSEC;"), "mm");+ // Extra: millimetre SI unit.+ assert_eq!(+ detect_source_unit("#5=( LENGTH_UNIT() NAMED_UNIT(*) SI_UNIT(.MILLI.,.METRE.) );"),+ "mm"+ );+ }+}diff --git a/crates/converter/src/lib.rs b/crates/converter/src/lib.rsnew file mode 100644index 0000000000..367d5f7c65--- /dev/null+++ b/crates/converter/src/lib.rs@@ -0,0 +1,7 @@+//! STEP → GLB + graph.json converter (ported from the former Python geometry+//! service). Deterministic pieces here; OCCT ingestion via the occt-bridge crate.++pub mod convert;+pub mod glb;+pub mod graph;+pub mod nodeid;diff --git a/crates/converter/src/nodeid.rs b/crates/converter/src/nodeid.rsnew file mode 100644index 0000000000..353f75acd0--- /dev/null+++ b/crates/converter/src/nodeid.rs@@ -0,0 +1,73 @@+//! Stable nodeId derivation — byte-identical to `app/convert.py`+//! (`_geometry_hash`, `_node_id`). Existing stored graphs/plans reference these+//! IDs, so they must match Python exactly.++use sha1::{Digest, Sha1};++/// `_geometry_hash`: sha1 over quantized positions (mm×1000, round-half-even to+/// int64) then uint32 indices, both little-endian row-major — matching numpy+/// `.astype(float64)*1000`, `np.round` (rint = ties-to-even), `.tobytes()`.+pub fn geometry_hash(positions: &[[f32; 3]], indices: &[[u32; 3]]) -> String {+ let mut hasher = Sha1::new();+ for p in positions {+ for &c in p {+ let q = (c as f64 * 1000.0).round_ties_even() as i64;+ hasher.update(q.to_le_bytes());+ }+ }+ for tri in indices {+ for &i in tri {+ hasher.update(i.to_le_bytes());+ }+ }+ hex(&hasher.finalize())+}++/// `_node_id`: `sha1("{hash_key}:{parent_path}:{sibling_ordinal}")[:16]`.+pub fn node_id(hash_key: &str, parent_path: &str, sibling_ordinal: usize) -> String {+ let raw = format!("{hash_key}:{parent_path}:{sibling_ordinal}");+ let mut hasher = Sha1::new();+ hasher.update(raw.as_bytes());+ hex(&hasher.finalize())[..16].to_string()+}++fn hex(bytes: &[u8]) -> String {+ let mut s = String::with_capacity(bytes.len() * 2);+ for b in bytes {+ s.push_str(&format!("{b:02x}"));+ }+ s+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn geometry_hash_matches_python() {+ // Reference values captured from app.convert._geometry_hash.+ let pos = [+ [0.0f32, 0.0, 0.0],+ [1.0, 0.0, 0.0],+ [0.0, 1.0, 0.0],+ [1.0, 1.0, 1.0],+ ];+ let idx = [[0u32, 1, 2], [1, 3, 2]];+ assert_eq!(+ geometry_hash(&pos, &idx),+ "9e21fed301a9b2683e3e381282e35ac1bb0576fb"+ );+ }++ #[test]+ fn node_id_matches_python() {+ // Reference values captured from app.convert._node_id.+ assert_eq!(+ node_id("9e21fed301a9b2683e3e381282e35ac1bb0576fb", "A/B", 2),+ "e7e90bb71c31f2f8"+ );+ assert_eq!(node_id("", "", 0), "df6bf0c022b56e83");+ assert_eq!(node_id("abc123", "PLATE", 0), "d5dc7338a9bc0158");+ assert_eq!(node_id("abc123", "STACK-ASSY/PLATE", 1), "cfb23fd2f838d9a5");+ }+}diff --git a/crates/converter/tests/convert_parity.rs b/crates/converter/tests/convert_parity.rsnew file mode 100644index 0000000000..ab384f8e04--- /dev/null+++ b/crates/converter/tests/convert_parity.rs@@ -0,0 +1,138 @@+//! Convert the STEP fixtures with the Rust converter and assert the graph.json+//! matches the Python reference (nodeId + geometryHash byte-identical; transforms/+//! bbox/volume/color within epsilon). Env ASSEMBLER_FIXTURES points at a dir with+//! {box,plates,nested}.step + {name}.graph.json (Python output). Skips if unset.++use converter::convert::convert_step;+use serde_json::Value;++fn approx_eq(a: &Value, b: &Value, eps: f64) -> bool {+ match (a, b) {+ (Value::Null, Value::Null) => true,+ (Value::Number(x), Value::Number(y)) => {+ (x.as_f64().unwrap() - y.as_f64().unwrap()).abs() <= eps+ }+ (Value::Array(x), Value::Array(y)) => {+ x.len() == y.len() && x.iter().zip(y).all(|(u, v)| approx_eq(u, v, eps))+ }+ _ => a == b,+ }+}++fn compare(rust: &Value, py: &Value, path: &str) -> Result<(), String> {+ for key in ["nodeId", "name", "isAssembly", "geometryHash"] {+ if rust[key] != py[key] {+ return Err(format!("{path}.{key}: rust={} py={}", rust[key], py[key]));+ }+ }+ for (key, eps) in [("transform", 1e-6), ("volume", 0.01), ("color", 0.02)] {+ if !approx_eq(&rust[key], &py[key], eps) {+ return Err(format!("{path}.{key}: rust={} py={}", rust[key], py[key]));+ }+ }+ // bbox within 0.5mm (tessellation-dependent, matching test_convert tolerances)+ for mm in ["min", "max"] {+ if !approx_eq(&rust["bbox"][mm], &py["bbox"][mm], 0.5) {+ return Err(format!(+ "{path}.bbox.{mm}: rust={} py={}",+ rust["bbox"][mm], py["bbox"][mm]+ ));+ }+ }+ let rc = rust["children"].as_array().unwrap();+ let pc = py["children"].as_array().unwrap();+ if rc.len() != pc.len() {+ return Err(format!(+ "{path}.children len rust={} py={}",+ rc.len(),+ pc.len()+ ));+ }+ for (i, (r, p)) in rc.iter().zip(pc).enumerate() {+ compare(r, p, &format!("{path}.children[{i}]"))?;+ }+ Ok(())+}++fn graph_node_ids(node: &Value) -> Vec<String> {+ let mut ids = vec![node["nodeId"].as_str().unwrap().to_string()];+ for c in node["children"].as_array().unwrap() {+ ids.extend(graph_node_ids(c));+ }+ ids+}++fn glb_node_ids(glb: &[u8]) -> std::collections::HashSet<String> {+ // Parse the JSON chunk (starts at byte 20 after 12-byte header + 8-byte chunk header).+ let json_len = u32::from_le_bytes([glb[12], glb[13], glb[14], glb[15]]) as usize;+ let json: Value = serde_json::from_slice(&glb[20..20 + json_len]).unwrap();+ let mut ids = std::collections::HashSet::new();+ for node in json["nodes"].as_array().unwrap() {+ if let Some(id) = node+ .get("extras")+ .and_then(|e| e.get("nodeId"))+ .and_then(|v| v.as_str())+ {+ ids.insert(id.to_string());+ }+ }+ ids+}++#[test]+fn convert_matches_python() {+ let dir = match std::env::var("ASSEMBLER_FIXTURES") {+ Ok(d) => d,+ Err(_) => {+ eprintln!("ASSEMBLER_FIXTURES unset; skipping");+ return;+ }+ };+ let mut failures = Vec::new();+ for name in ["box", "plates", "nested"] {+ let step = format!("{dir}/{name}.step");+ let text = std::fs::read_to_string(&step).unwrap_or_default();+ let conv = convert_step(&step, &text, 0.1, 0.5).expect("convert");+ let py: Value = serde_json::from_str(+ &std::fs::read_to_string(format!("{dir}/{name}.graph.json")).unwrap(),+ )+ .unwrap();++ for key in ["version", "unit", "sourceUnit", "componentCount"] {+ if conv.graph[key] != py[key] {+ failures.push(format!(+ "{name}.{key}: rust={} py={}",+ conv.graph[key], py[key]+ ));+ }+ }+ match compare(&conv.graph["root"], &py["root"], name) {+ Ok(()) => eprintln!(+ "PASS graph {name} (components={}, triangles={})",+ conv.component_count, conv.triangles+ ),+ Err(e) => failures.push(e),+ }+ // GLB: valid magic, and every graph nodeId is stamped on a glTF node.+ if &conv.glb[..4] != b"glTF" {+ failures.push(format!("{name}: GLB bad magic"));+ }+ let glb_ids = glb_node_ids(&conv.glb);+ let graph_ids = graph_node_ids(&conv.graph["root"]);+ for id in &graph_ids {+ if !glb_ids.contains(id) {+ failures.push(format!("{name}: graph nodeId {id} missing from GLB"));+ }+ }+ eprintln!(+ "PASS glb {name} ({} nodes, {} bytes)",+ glb_ids.len(),+ conv.glb.len()+ );+ }+ assert!(+ failures.is_empty(),+ "convert parity failures:\n{}",+ failures.join("\n")+ );+}diff --git a/crates/converter/tests/multibody_split.rs b/crates/converter/tests/multibody_split.rsnew file mode 100644index 0000000000..5f9323b2be--- /dev/null+++ b/crates/converter/tests/multibody_split.rs@@ -0,0 +1,84 @@+//! Flat multi-body STEP (one PRODUCT, N solids, no assembly tree — the common+//! Fusion/SolidWorks export shape) must split into per-solid components.+//! Hermetic: the STEP fixtures are generated by the occt bridge itself.++use converter::convert::convert_step;+use serde_json::Value;++fn convert(boxes: u32) -> Value {+ let dir = std::env::temp_dir().join(format!("carbon-multibody-{boxes}"));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("fixture.step");+ let path_str = path.to_str().unwrap();+ assert!(+ occt_bridge::write_test_step(path_str, boxes),+ "failed to write test STEP"+ );+ let text = std::fs::read_to_string(path_str).unwrap();+ let conv = convert_step(path_str, &text, 0.1, 0.5).expect("convert");+ conv.graph+}++fn leaves(node: &Value, out: &mut Vec<Value>) {+ let children = node["children"].as_array().cloned().unwrap_or_default();+ if children.is_empty() && node["isAssembly"] == Value::Bool(false) {+ out.push(node.clone());+ return;+ }+ for child in &children {+ leaves(child, out);+ }+}++#[test]+fn splits_a_flat_two_solid_product_into_two_components() {+ let graph = convert(2);+ assert_eq!(graph["componentCount"], 2, "expected a per-solid split");++ let mut parts = Vec::new();+ leaves(&graph["root"], &mut parts);+ assert_eq!(parts.len(), 2);++ // Distinct identity per solid+ let ids: Vec<&str> = parts.iter().map(|p| p["nodeId"].as_str().unwrap()).collect();+ assert_ne!(ids[0], ids[1], "solids must get distinct nodeIds");+ let hashes: Vec<&str> = parts+ .iter()+ .map(|p| p["geometryHash"].as_str().unwrap())+ .collect();+ // Identical boxes at different local positions: positions are baked into+ // the part-local mesh, so the hashes differ too+ assert_ne!(hashes[0], hashes[1]);++ for part in &parts {+ assert!(+ part["volume"].as_f64().unwrap() > 0.0,+ "per-solid volume expected"+ );+ assert_eq!(part["isAssembly"], Value::Bool(false));+ }++ // The synthetic parent is an assembly (no mesh identity, null volume)+ let mut parent = &graph["root"];+ // Root may BE the parent, or wrap it — find the node whose children are the parts+ if parent["children"].as_array().map(|c| c.len()) != Some(2) {+ parent = &parent["children"][0];+ }+ assert_eq!(parent["isAssembly"], Value::Bool(true));+ assert_eq!(parent["geometryHash"], Value::Null);+ assert_eq!(parent["volume"], Value::Null);++ // Display + id-path naming: deterministic per solid+ let names: Vec<&str> = parts.iter().map(|p| p["name"].as_str().unwrap()).collect();+ assert_ne!(names[0], names[1], "solids must get distinct display names");+}++#[test]+fn keeps_a_single_solid_product_as_one_leaf() {+ let graph = convert(1);+ assert_eq!(graph["componentCount"], 1, "single solid must not split");+ let mut parts = Vec::new();+ leaves(&graph["root"], &mut parts);+ assert_eq!(parts.len(), 1);+ assert!(parts[0]["volume"].as_f64().unwrap() > 0.0);+}diff --git a/crates/occt-bridge/Cargo.toml b/crates/occt-bridge/Cargo.tomlnew file mode 100644index 0000000000..f0fffca715--- /dev/null+++ b/crates/occt-bridge/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "occt-bridge"+version.workspace = true+edition.workspace = true+license.workspace = true++# cxx bridge over OpenCASCADE 7.9.3 (== cadquery-ocp's OCCT). One C++ entry point+# walks the XCAF assembly tree + tessellates, returning a flat node list to Rust.++[dependencies]+cxx = "1"++[build-dependencies]+cxx-build = "1"diff --git a/crates/occt-bridge/build.rs b/crates/occt-bridge/build.rsnew file mode 100644index 0000000000..6c8bb2fcd8--- /dev/null+++ b/crates/occt-bridge/build.rs@@ -0,0 +1,122 @@+use std::path::{Path, PathBuf};++/// Resolve the OCCT install prefix deterministically: `OCCT_PREFIX` env+/// (Docker/CI/custom) → the per-machine static build cache+/// (apps/assembler/scripts/build-occt.sh) → a fixed per-target default. No+/// `brew` shell-out, so the build never depends on Homebrew being installed or+/// on PATH; Docker/CI set OCCT_PREFIX explicitly.+fn occt_prefix() -> String {+ if let Ok(p) = std::env::var("OCCT_PREFIX") {+ if !p.is_empty() {+ return p;+ }+ }+ if let Some(home) = std::env::var_os("HOME") {+ let cached = PathBuf::from(home).join(".cache/carbon-occt/8.0.0-p1");+ if cached.join("lib/libTKernel.a").exists() {+ return cached.to_string_lossy().into_owned();+ }+ }+ // CARGO_CFG_TARGET_* is the target we build for. macOS dev = the standard+ // Homebrew opt layout; Linux = the distro `/usr` layout.+ let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();+ let arch = std::env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();+ match os.as_str() {+ "macos" if arch == "aarch64" => "/opt/homebrew/opt/opencascade".to_string(),+ "macos" => "/usr/local/opt/opencascade".to_string(),+ _ => "/usr".to_string(),+ }+}++/// Candidate lib directories under a prefix — the prefix's own `lib` plus the+/// Debian/Ubuntu multiarch subdirs where a distro OCCT actually installs. Must+/// match the linker search paths added in `main`.+fn lib_dirs(lib_dir: &Path) -> Vec<PathBuf> {+ vec![+ lib_dir.to_path_buf(),+ lib_dir.join("x86_64-linux-gnu"),+ lib_dir.join("aarch64-linux-gnu"),+ ]+}++/// All OCCT toolkits present under `lib_dir` (and its multiarch subdirs), and+/// whether they are static archives. Prefers static (`libTK*.a`) when present —+/// the deployment build — else dynamic (`libTK*.dylib`/`.so`, e.g. brew/apt).+fn toolkits(lib_dir: &Path) -> (Vec<String>, bool) {+ let mut static_libs = Vec::new();+ let mut dylibs = Vec::new();+ for dir in lib_dirs(lib_dir) {+ let Ok(entries) = std::fs::read_dir(&dir) else {+ continue;+ };+ for e in entries.flatten() {+ let name = e.file_name().to_string_lossy().to_string();+ let Some(stem) = name.strip_prefix("lib") else {+ continue;+ };+ if let Some(s) = stem.strip_suffix(".a") {+ if s.starts_with("TK") && !s.contains('.') {+ static_libs.push(s.to_string());+ }+ } else if let Some(s) = stem+ .strip_suffix(".dylib")+ .or_else(|| stem.strip_suffix(".so"))+ {+ // Skip versioned files (libTKFoo.so.8.0.0) so each links once.+ if s.starts_with("TK") && !s.contains('.') {+ dylibs.push(s.to_string());+ }+ }+ }+ }+ let is_static = !static_libs.is_empty();+ let mut libs = if is_static { static_libs } else { dylibs };+ libs.sort();+ libs.dedup();+ (libs, is_static)+}++fn main() {+ let occt = occt_prefix();+ let include_dir = format!("{occt}/include/opencascade");+ let lib_dir = PathBuf::from(format!("{occt}/lib"));++ cxx_build::bridge("src/lib.rs")+ .file("src/occt.cc")+ .std("c++17")+ .include(&include_dir)+ .warnings(false)+ .compile("carbon_occt_shim");++ for dir in lib_dirs(&lib_dir) {+ println!("cargo:rustc-link-search=native={}", dir.display());+ }++ // Link every OpenCASCADE toolkit found — the STEP+XCAF+Mesh path pulls in a+ // broad transitive set; linking all TK* avoids hand-maintaining the list.+ // NOTE: must be rustc-link-lib (rustc-link-arg from a lib crate's build+ // script is dropped by cargo and never reaches the final binary link).+ // rustc wraps the native/crate library section in a --start-group on GNU+ // targets, so alphabetical order is fine for the inter-archive references.+ let (libs, is_static) = toolkits(&lib_dir);+ // Deployment builds set OCCT_LINK=static so a slim runtime image never ships+ // OCCT shared objects — fail loud if the static archives aren't there rather+ // than silently linking a dynamic OCCT the runtime lacks.+ if std::env::var("OCCT_LINK").as_deref() == Ok("static") && !is_static {+ panic!(+ "OCCT_LINK=static but no static OCCT archives (libTK*.a) found under {} \+ — check OCCT_PREFIX / the static OCCT build.",+ lib_dir.display()+ );+ }+ let kind = if is_static { "static" } else { "dylib" };+ for lib in &libs {+ println!("cargo:rustc-link-lib={kind}={lib}");+ }++ println!("cargo:rerun-if-changed=src/lib.rs");+ println!("cargo:rerun-if-changed=src/occt.cc");+ println!("cargo:rerun-if-changed=src/occt.h");+ println!("cargo:rerun-if-env-changed=OCCT_PREFIX");+ println!("cargo:rerun-if-env-changed=OCCT_LINK");+}diff --git a/crates/occt-bridge/examples/conc_read.rs b/crates/occt-bridge/examples/conc_read.rsnew file mode 100644index 0000000000..3343f15ed0--- /dev/null+++ b/crates/occt-bridge/examples/conc_read.rs@@ -0,0 +1,60 @@+//! Isolated concurrency probe for `read_step`. Does OCCT 7.9.3 STEP reading+//! actually parallelize across threads, or serialize / crash on shared global+//! state? Bypasses the HTTP path entirely: N OS threads each call read_step in a+//! tight loop, measured at T=1 then T=THREADS. Linear scaling => parallel; flat+//! throughput => serialized; SIGABRT/SIGSEGV => 7.9.3 concurrency bug.+//!+//! cargo run --release -p occt-bridge --example conc_read -- <file.step> [iters]++use std::sync::Arc;+use std::time::Instant;++fn run(path: &Arc<String>, threads: usize, iters: usize) -> (f64, u64) {+ let start = Instant::now();+ let mut handles = Vec::new();+ for _ in 0..threads {+ let p = Arc::clone(path);+ handles.push(std::thread::spawn(move || {+ let mut nodes = 0u64;+ for _ in 0..iters {+ let t = occt_bridge::read_step(p.as_str(), 0.1, 0.5);+ assert!(t.ok, "read failed: {}", t.error);+ nodes += t.nodes.len() as u64;+ }+ nodes+ }));+ }+ let mut total = 0u64;+ for h in handles {+ total += h.join().expect("thread panicked");+ }+ let secs = start.elapsed().as_secs_f64();+ let reads = (threads * iters) as f64;+ (reads / secs, total)+}++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let path = Arc::new(args.get(1).cloned().expect("usage: conc_read <file.step> [iters]"));+ let iters: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(100);+ let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(8);++ // Warm globals single-threaded (mirrors the call_once init path).+ let _ = occt_bridge::read_step(path.as_str(), 0.1, 0.5);++ let (rps1, _) = run(&path, 1, iters);+ println!("T= 1: {rps1:8.1} reads/s (baseline)");++ for &t in &[2usize, 4, cores] {+ let (rps, _) = run(&path, t, iters);+ let scale = rps / rps1;+ let verdict = if scale > t as f64 * 0.7 {+ "PARALLEL"+ } else if scale < 1.4 {+ "SERIALIZED"+ } else {+ "partial"+ };+ println!("T={t:2}: {rps:8.1} reads/s {scale:4.2}x [{verdict}]");+ }+}diff --git a/crates/occt-bridge/src/lib.rs b/crates/occt-bridge/src/lib.rsnew file mode 100644index 0000000000..ef14dd964b--- /dev/null+++ b/crates/occt-bridge/src/lib.rs@@ -0,0 +1,51 @@+//! cxx bridge over OpenCASCADE. `read_step` reads a STEP file into an XCAF+//! document, walks the assembly tree (names, per-instance transforms, colors),+//! tessellates each unique part once, and returns a FLAT node list (children as+//! indices) — mirroring `app/convert.py`'s `_build_tree`/`_tessellate`. The Rust+//! `converter` crate turns this into nodeIds + graph.json + GLB.++#[cxx::bridge(namespace = "carbon_occt")]+pub mod ffi {+ /// One node of the assembly tree, flattened. `children` holds indices into+ /// the returned `nodes` vector.+ #[derive(Debug, Clone)]+ pub struct RawNode {+ pub name: String,+ pub product_name: String,+ pub transform: Vec<f64>, // 16, column-major+ pub is_assembly: bool,+ pub has_mesh: bool,+ pub is_proxy: bool,+ pub vertices: Vec<f32>, // flat n*3, part-local mm+ pub indices: Vec<u32>, // flat m*3+ pub has_color: bool,+ pub color: Vec<f64>, // 4 when has_color+ pub has_volume: bool,+ pub volume: f64,+ pub children: Vec<u64>,+ }++ /// Result of reading a STEP file.+ #[derive(Debug, Clone)]+ pub struct Tree {+ pub ok: bool,+ pub error: String,+ pub root_index: u64,+ pub nodes: Vec<RawNode>,+ }++ unsafe extern "C++" {+ include!("occt-bridge/src/occt.h");++ /// Read + tessellate a STEP file. `ok=false` with `error` on failure+ /// (unreadable STEP, transfer failure, no shapes).+ fn read_step(path: &str, linear_deflection: f64, angular_deflection: f64) -> Tree;++ /// Test fixture generator: write `boxes` disjoint solids as ONE+ /// product (flat multi-body, no assembly tree) to a STEP file.+ /// Hermetic tests use this instead of committed fixture files.+ fn write_test_step(path: &str, boxes: u32) -> bool;+ }+}++pub use ffi::{read_step, write_test_step, RawNode, Tree};diff --git a/crates/occt-bridge/src/occt.cc b/crates/occt-bridge/src/occt.ccnew file mode 100644index 0000000000..b27aa1c594--- /dev/null+++ b/crates/occt-bridge/src/occt.cc@@ -0,0 +1,506 @@+#include "occt-bridge/src/occt.h"++#include <map>+#include <string>+#include <vector>++#include <BRepBndLib.hxx>+#include <BRepGProp.hxx>+#include <chrono>+#include <mutex>+#include <cstdio>+#include <cstdlib>+#include <BRepMesh_IncrementalMesh.hxx>+#include <BRepPrimAPI_MakeBox.hxx>+#include <BRep_Builder.hxx>+#include <BRep_Tool.hxx>+#include <Bnd_Box.hxx>+#include <GProp_GProps.hxx>+#include <IFSelect_ReturnStatus.hxx>+#include <Interface_Static.hxx>+#include <Poly_Triangle.hxx>+#include <Poly_Triangulation.hxx>+#include <Quantity_ColorRGBA.hxx>+#include <STEPCAFControl_Reader.hxx>+#include <STEPControl_Controller.hxx>+#include <STEPControl_Writer.hxx>+#include <Standard_Failure.hxx>+#include <TCollection_AsciiString.hxx>+#include <TCollection_ExtendedString.hxx>+#include <TDF_Label.hxx>+#include <TDF_LabelSequence.hxx>+#include <TDF_Tool.hxx>+#include <TDataStd_Name.hxx>+#include <TDocStd_Document.hxx>+#include <TopAbs_Orientation.hxx>+#include <TopAbs_ShapeEnum.hxx>+#include <TopExp_Explorer.hxx>+#include <TopLoc_Location.hxx>+#include <TopoDS.hxx>+#include <TopoDS_Compound.hxx>+#include <TopoDS_Face.hxx>+#include <TopoDS_Shape.hxx>+#include <XCAFDoc_ColorTool.hxx>+#include <XCAFDoc_ColorType.hxx>+#include <XCAFDoc_DocumentTool.hxx>+#include <XCAFDoc_ShapeTool.hxx>+#include <gp_Pnt.hxx>+#include <gp_Trsf.hxx>++#include "occt-bridge/src/lib.rs.h"++namespace carbon_occt {++static const std::vector<double> IDENTITY_4X4 = {+ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1};++// UTF-8, not TCollection_AsciiString: the ASCII conversion replaces every+// non-Latin character with '?', which mangles e.g. CJK part names.+static std::string to_utf8(const TCollection_ExtendedString &ext) {+ const int len = ext.LengthOfCString();+ if (len <= 0) return "";+ std::string out(static_cast<size_t>(len) + 1, '\0');+ Standard_PCharacter p = out.data();+ ext.ToUTF8CString(p);+ out.resize(static_cast<size_t>(len));+ return out;+}++static std::string label_name(const TDF_Label &label) {+ Handle(TDataStd_Name) attr;+ if (label.FindAttribute(TDataStd_Name::GetID(), attr)) {+ return to_utf8(attr->Get());+ }+ return "";+}++static std::string label_entry(const TDF_Label &label) {+ TCollection_AsciiString entry;+ TDF_Tool::Entry(label, entry);+ return std::string(entry.ToCString());+}++static bool label_color(const TDF_Label &a, const TDF_Label &b, bool have_b,+ std::vector<double> &out) {+ Quantity_ColorRGBA rgba;+ const XCAFDoc_ColorType types[2] = {XCAFDoc_ColorSurf, XCAFDoc_ColorGen};+ const TDF_Label labels[2] = {a, b};+ const int n = have_b ? 2 : 1;+ for (int i = 0; i < n; ++i) {+ if (labels[i].IsNull()) continue;+ for (int t = 0; t < 2; ++t) {+ if (XCAFDoc_ColorTool::GetColor(labels[i], types[t], rgba)) {+ Quantity_Color rgb = rgba.GetRGB();+ out = {rgb.Red(), rgb.Green(), rgb.Blue(), rgba.Alpha()};+ return true;+ }+ }+ }+ return false;+}++static std::vector<double> location_col_major(const TopLoc_Location &loc) {+ gp_Trsf t = loc.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};+}++struct MeshData {+ std::vector<float> vertices;+ std::vector<uint32_t> indices;+ bool is_proxy;+};++// ASSEMBLER_MESH_PARALLEL=0 => serial per-request meshing. A server handling+// concurrent requests wants this: each convert runs single-threaded on its own+// worker thread, so N concurrent converts use N cores cleanly instead of each+// fanning out to all cores and oversubscribing. Default (unset) = parallel, for+// lowest single-request latency (CLI / one-shot use).+static bool mesh_parallel() {+ static bool v = []() {+ const char *e = std::getenv("ASSEMBLER_MESH_PARALLEL");+ return !(e && e[0] == '0');+ }();+ return v;+}++static void tessellate(const TopoDS_Shape &shape, double lin, double ang,+ std::vector<float> &verts, std::vector<uint32_t> &indices) {+ BRepMesh_IncrementalMesh(shape, lin, Standard_False, ang,+ mesh_parallel() ? Standard_True : Standard_False);+ uint32_t offset = 0;+ for (TopExp_Explorer exp(shape, TopAbs_FACE); exp.More(); exp.Next()) {+ TopoDS_Face face = TopoDS::Face(exp.Current());+ TopLoc_Location loc;+ Handle(Poly_Triangulation) tri = BRep_Tool::Triangulation(face, loc);+ if (tri.IsNull()) continue;+ gp_Trsf trsf = loc.Transformation();+ const int nn = tri->NbNodes();+ for (int i = 1; i <= nn; ++i) {+ gp_Pnt p = tri->Node(i).Transformed(trsf);+ verts.push_back(static_cast<float>(p.X()));+ verts.push_back(static_cast<float>(p.Y()));+ verts.push_back(static_cast<float>(p.Z()));+ }+ const bool reversed = face.Orientation() == TopAbs_REVERSED;+ const int nt = tri->NbTriangles();+ for (int i = 1; i <= nt; ++i) {+ Standard_Integer a, b, c;+ tri->Triangle(i).Get(a, b, c);+ if (reversed) {+ indices.push_back(a - 1 + offset);+ indices.push_back(c - 1 + offset);+ indices.push_back(b - 1 + offset);+ } else {+ indices.push_back(a - 1 + offset);+ indices.push_back(b - 1 + offset);+ indices.push_back(c - 1 + offset);+ }+ }+ offset += nn;+ }+}++static void bbox_proxy(const TopoDS_Shape &shape, std::vector<float> &verts,+ std::vector<uint32_t> &indices) {+ Bnd_Box box;+ BRepBndLib::Add(shape, box);+ if (box.IsVoid()) return;+ Standard_Real xmin, ymin, zmin, xmax, ymax, zmax;+ box.Get(xmin, ymin, zmin, xmax, ymax, zmax);+ const float corners[8][3] = {+ {(float)xmin, (float)ymin, (float)zmin}, {(float)xmax, (float)ymin, (float)zmin},+ {(float)xmax, (float)ymax, (float)zmin}, {(float)xmin, (float)ymax, (float)zmin},+ {(float)xmin, (float)ymin, (float)zmax}, {(float)xmax, (float)ymin, (float)zmax},+ {(float)xmax, (float)ymax, (float)zmax}, {(float)xmin, (float)ymax, (float)zmax}};+ for (auto &c : corners) {+ verts.push_back(c[0]);+ verts.push_back(c[1]);+ verts.push_back(c[2]);+ }+ const uint32_t faces[12][3] = {{0, 2, 1}, {0, 3, 2}, {4, 5, 6}, {4, 6, 7},+ {0, 1, 5}, {0, 5, 4}, {1, 2, 6}, {1, 6, 5},+ {2, 3, 7}, {2, 7, 6}, {3, 0, 4}, {3, 4, 7}};+ for (auto &f : faces) {+ indices.push_back(f[0]);+ indices.push_back(f[1]);+ indices.push_back(f[2]);+ }+}++static double shape_volume(const TopoDS_Shape &shape) {+ try {+ GProp_GProps props;+ BRepGProp::VolumeProperties(shape, props);+ double v = props.Mass();+ if (v > 0) return v;+ } catch (...) {+ }+ Bnd_Box box;+ BRepBndLib::Add(shape, box);+ if (box.IsVoid()) return 0.0;+ Standard_Real xmin, ymin, zmin, xmax, ymax, zmax;+ box.Get(xmin, ymin, zmin, xmax, ymax, zmax);+ double dx = xmax - xmin, dy = ymax - ymin, dz = zmax - zmin;+ if (dx < 0) dx = 0;+ if (dy < 0) dy = 0;+ if (dz < 0) dz = 0;+ return dx * dy * dz;+}++static int count_faces(const TopoDS_Shape &shape) {+ int n = 0;+ for (TopExp_Explorer exp(shape, TopAbs_FACE); exp.More(); exp.Next()) n++;+ return n;+}++// Every face of the shape belongs to exactly one of the solids? Sheet/surface+// bodies living beside the solids would silently vanish from a per-solid+// split, so their presence keeps the merged mesh instead.+static bool faces_covered_by_solids(const TopoDS_Shape &shape,+ const std::vector<TopoDS_Shape> &solids) {+ int covered = 0;+ for (const auto &solid : solids) covered += count_faces(solid);+ return covered == count_faces(shape);+}++class Builder {+ public:+ Builder(double lin, double ang, const Handle(XCAFDoc_ShapeTool) &shapeTool)+ : lin_(lin), ang_(ang), shape_tool_(shapeTool) {}++ std::vector<RawNode> nodes;++ uint64_t build(const TDF_Label &product, const TDF_Label &instance, bool have_instance,+ const TopLoc_Location &loc, bool have_loc) {+ std::string product_name = label_name(product);+ std::string instance_name = have_instance ? label_name(instance) : "";+ std::string name = !product_name.empty() ? product_name : instance_name;++ RawNode node;+ node.transform = have_loc ? to_vec(location_col_major(loc)) : to_vec(IDENTITY_4X4);+ std::vector<double> color;+ node.has_color = label_color(have_instance ? instance : product, product, have_instance, color);+ if (node.has_color) node.color = to_vec(color);++ if (XCAFDoc_ShapeTool::IsAssembly(product)) {+ TDF_LabelSequence components;+ XCAFDoc_ShapeTool::GetComponents(product, components);+ std::vector<uint64_t> children;+ for (int i = 1; i <= components.Length(); ++i) {+ TDF_Label comp = components.Value(i);+ TDF_Label referred;+ if (!XCAFDoc_ShapeTool::GetReferredShape(comp, referred)) continue;+ TopLoc_Location cloc = XCAFDoc_ShapeTool::GetLocation(comp);+ children.push_back(build(referred, comp, true, cloc, true));+ }+ node.name = name.empty() ? "ASSEMBLY" : name;+ node.product_name = product_name.empty() ? "ASSEMBLY" : product_name;+ node.is_assembly = true;+ node.has_mesh = false;+ node.is_proxy = false;+ node.has_volume = false;+ node.volume = 0.0;+ for (auto c : children) node.children.push_back(c);+ nodes.push_back(node);+ return nodes.size() - 1;+ }++ TopoDS_Shape shape = XCAFDoc_ShapeTool::GetShape(product);+ const std::string base_name = name.empty() ? "PART" : name;+ const std::string base_product = product_name.empty() ? "PART" : product_name;++ // Flat multi-body products (common Fusion/SolidWorks export shape: one+ // PRODUCT, many solids, no assembly tree) split into per-solid child+ // components — merged they'd be one un-plannable blob. Only when every+ // face belongs to some solid; otherwise (sheet/surface bodies present)+ // keep the merged mesh so no geometry is lost.+ std::vector<TopoDS_Shape> solids;+ for (TopExp_Explorer exp(shape, TopAbs_SOLID); exp.More(); exp.Next()) {+ solids.push_back(exp.Current());+ }+ if (solids.size() >= 2 && faces_covered_by_solids(shape, solids)) {+ const std::string entry = label_entry(product);+ std::vector<uint64_t> children;+ for (size_t i = 0; i < solids.size(); ++i) {+ RawNode child;+ // Solids are already in product-local coordinates+ child.transform = to_vec(IDENTITY_4X4);+ // Display name from the solid's own XCAF sub-label when present;+ // the id-path product_name stays a pure function of (product, index)+ // so nodeIds don't depend on optional naming.+ std::string solid_name;+ std::vector<double> solid_color;+ bool solid_has_color = false;+ TDF_Label sub;+ if (!shape_tool_.IsNull() &&+ shape_tool_->FindSubShape(product, solids[i], sub)) {+ solid_name = label_name(sub);+ solid_has_color = label_color(sub, TDF_Label(), false, solid_color);+ }+ child.name = !solid_name.empty()+ ? solid_name+ : base_name + " Body " + std::to_string(i + 1);+ child.product_name = base_product + "#" + std::to_string(i);+ child.has_color = solid_has_color || node.has_color;+ if (solid_has_color) {+ child.color = to_vec(solid_color);+ } else if (node.has_color) {+ child.color = node.color;+ }+ MeshData mesh = mesh_for(entry + "#" + std::to_string(i), solids[i]);+ child.is_assembly = false;+ child.has_mesh = true;+ child.is_proxy = mesh.is_proxy;+ for (float v : mesh.vertices) child.vertices.push_back(v);+ for (uint32_t idx : mesh.indices) child.indices.push_back(idx);+ child.has_volume = true;+ child.volume = shape_volume(solids[i]);+ nodes.push_back(child);+ children.push_back(nodes.size() - 1);+ }+ node.name = base_name;+ node.product_name = base_product;+ node.is_assembly = true;+ node.has_mesh = false;+ node.is_proxy = false;+ node.has_volume = false;+ node.volume = 0.0;+ for (auto c : children) node.children.push_back(c);+ nodes.push_back(node);+ return nodes.size() - 1;+ }++ MeshData mesh = mesh_for(label_entry(product), shape);+ node.name = base_name;+ node.product_name = base_product;+ node.is_assembly = false;+ node.has_mesh = true;+ node.is_proxy = mesh.is_proxy;+ for (float v : mesh.vertices) node.vertices.push_back(v);+ for (uint32_t i : mesh.indices) node.indices.push_back(i);+ node.has_volume = true;+ node.volume = shape_volume(shape);+ nodes.push_back(node);+ return nodes.size() - 1;+ }++ private:+ double lin_, ang_;+ Handle(XCAFDoc_ShapeTool) shape_tool_;+ std::map<std::string, MeshData> cache_;++ MeshData mesh_for(const std::string &key, const TopoDS_Shape &shape) {+ auto it = cache_.find(key);+ if (it != cache_.end()) return it->second;+ MeshData m;+ m.is_proxy = false;+ try {+ tessellate(shape, lin_, ang_, m.vertices, m.indices);+ } catch (...) {+ m.vertices.clear();+ m.indices.clear();+ }+ if (m.indices.empty()) {+ m.vertices.clear();+ m.indices.clear();+ bbox_proxy(shape, m.vertices, m.indices);+ m.is_proxy = true;+ }+ cache_[key] = m;+ return m;+ }++ static rust::Vec<double> to_vec(const std::vector<double> &v) {+ rust::Vec<double> out;+ for (double x : v) out.push_back(x);+ return out;+ }+};++Tree read_step(rust::Str path, double linear_deflection, double angular_deflection) {+ Tree t;+ t.ok = false;+ t.root_index = 0;+ const bool prof = std::getenv("OCCT_PROFILE") != nullptr;+ auto now = [] { return std::chrono::steady_clock::now(); };+ auto ms = [](auto a, auto b) {+ return std::chrono::duration_cast<std::chrono::milliseconds>(b - a).count();+ };+ try {+ auto t0 = now();+ // OCCT STEP reading is thread-safe under a strict contract: one reader per+ // thread AND no per-request mutation of the process-wide Interface_Static /+ // no concurrent STEPControl_Controller::Init(). So warm both ONCE here,+ // single-threaded; concurrent read_step calls then only touch their own+ // local reader instance and read (never write) the shared config.+ static std::once_flag occt_init;+ std::call_once(occt_init, [] {+ STEPControl_Controller::Init();+ Interface_Static::SetCVal("xstep.cascade.unit", "MM");+ });+ STEPCAFControl_Reader reader;+ reader.SetColorMode(true);+ reader.SetNameMode(true);+ reader.SetLayerMode(false);+ reader.SetMatMode(false);+ std::string p(path);+ if (reader.ReadFile(p.c_str()) != IFSelect_RetDone) {+ t.error = "could not read STEP file";+ return t;+ }+ auto t1 = now();+ Handle(TDocStd_Document) doc = new TDocStd_Document(TCollection_ExtendedString("BinXCAF"));+ if (!reader.Transfer(doc)) {+ t.error = "STEP transfer to XCAF failed";+ return t;+ }+ auto t2 = now();+ Handle(XCAFDoc_ShapeTool) shapeTool = XCAFDoc_DocumentTool::ShapeTool(doc->Main());+ TDF_LabelSequence freeShapes;+ shapeTool->GetFreeShapes(freeShapes);+ if (freeShapes.Length() == 0) {+ t.error = "STEP file contains no shapes";+ return t;+ }++ Builder b(linear_deflection, angular_deflection, shapeTool);+ std::vector<uint64_t> roots;+ for (int i = 1; i <= freeShapes.Length(); ++i) {+ roots.push_back(b.build(freeShapes.Value(i), TDF_Label(), false, TopLoc_Location(), false));+ }+ if (prof) {+ auto t3 = now();+ fprintf(stderr, "OCCT read=%lldms transfer=%lldms walk+mesh=%lldms\n",+ (long long)ms(t0, t1), (long long)ms(t1, t2), (long long)ms(t2, t3));+ }+ uint64_t root_index;+ if (roots.size() == 1) {+ root_index = roots[0];+ } else {+ RawNode r;+ r.name = "ROOT";+ r.product_name = "ROOT";+ for (double x : IDENTITY_4X4) r.transform.push_back(x);+ r.is_assembly = true;+ r.has_mesh = false;+ r.is_proxy = false;+ r.has_color = false;+ r.has_volume = false;+ r.volume = 0.0;+ for (auto c : roots) r.children.push_back(c);+ b.nodes.push_back(r);+ root_index = b.nodes.size() - 1;+ }++ for (auto &n : b.nodes) t.nodes.push_back(n);+ t.root_index = root_index;+ t.ok = true;+ } catch (Standard_Failure &e) {+ t.error = std::string("OCCT error: ") + e.GetMessageString();+ } catch (...) {+ t.error = "unknown OCCT error";+ }+ return t;+}++// Test fixture generator: writes `boxes` disjoint solids as ONE product (a+// compound, no assembly tree) — the flat multi-body export shape the split+// path handles. Hermetic converter tests build their own STEP with this+// instead of committing fixture files.+bool write_test_step(rust::Str path, uint32_t boxes) {+ try {+ static std::once_flag occt_init;+ std::call_once(occt_init, [] {+ STEPControl_Controller::Init();+ Interface_Static::SetCVal("xstep.cascade.unit", "MM");+ });+ TopoDS_Shape shape;+ if (boxes <= 1) {+ shape = BRepPrimAPI_MakeBox(10.0, 10.0, 10.0).Shape();+ } else {+ TopoDS_Compound compound;+ BRep_Builder builder;+ builder.MakeCompound(compound);+ for (uint32_t i = 0; i < boxes; ++i) {+ builder.Add(compound,+ BRepPrimAPI_MakeBox(gp_Pnt(i * 30.0, 0.0, 0.0), 10.0, 10.0,+ 10.0)+ .Shape());+ }+ shape = compound;+ }+ STEPControl_Writer writer;+ if (writer.Transfer(shape, STEPControl_AsIs) != IFSelect_RetDone) {+ return false;+ }+ std::string p(path);+ return writer.Write(p.c_str()) == IFSelect_RetDone;+ } catch (...) {+ return false;+ }+}++} // namespace carbon_occtdiff --git a/crates/occt-bridge/src/occt.h b/crates/occt-bridge/src/occt.hnew file mode 100644index 0000000000..985be13958--- /dev/null+++ b/crates/occt-bridge/src/occt.h@@ -0,0 +1,11 @@+#pragma once+#include <cstdint>+#include "rust/cxx.h"++namespace carbon_occt {+struct Tree; // generated by cxx from the shared struct++Tree read_step(rust::Str path, double linear_deflection, double angular_deflection);++bool write_test_step(rust::Str path, uint32_t boxes);+} // namespace carbon_occtdiff --git a/crates/planner/Cargo.toml b/crates/planner/Cargo.tomlnew file mode 100644index 0000000000..81107ae06d--- /dev/null+++ b/crates/planner/Cargo.toml@@ -0,0 +1,23 @@+[package]+name = "planner"+version.workspace = true+edition.workspace = true+license.workspace = true++[dependencies]+collision = { path = "../collision" }+converter = { path = "../converter" }+cxx = "1"+hex = "0.4.3"+nalgebra.workspace = true+ndarray = "0.16"+ndarray-linalg = { version = "0.17", features = ["openblas-system"] }+rayon = "1.10"+regex = "1"+serde.workspace = true+serde_json.workspace = true+sha1.workspace = true+smallvec = "1.13"++[target.'cfg(target_os = "linux")'.dev-dependencies]+tikv-jemallocator = "0.6"diff --git a/crates/planner/examples/bench_plan.rs b/crates/planner/examples/bench_plan.rsnew file mode 100644index 0000000000..11f90ce27f--- /dev/null+++ b/crates/planner/examples/bench_plan.rs@@ -0,0 +1,62 @@+//! Statistical planner benchmark — isolates the PLANNER from OCCT load and+//! process startup, and reports a distribution rather than one noisy wall-clock.+//!+//! cargo run --profile bench -p planner --example bench_plan -- <in.step> [samples]+//!+//! Loads + tessellates the STEP ONCE, then times only `plan_parts` over N fresh+//! clones (each clone has empty bvh/vol/sym caches — the pristine source is never+//! planned — so every sample is production-representative, not cache-warmed).+//! Reports min / median / mean / stddev; min is the least-noisy "how fast can it+//! go", median the typical. Following std-dev-guide: warm up, take many samples,+//! prefer min/median over a single run.++use std::time::Instant;++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let step = &args[1];+ let samples: usize = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(10);++ // Load + tessellate once (excluded from the measured region).+ let t_load = Instant::now();+ let root = converter::convert::build_tree(step, 0.1, 0.5).expect("build_tree");+ let parts0 = planner::steps::collect_world_parts(&root); // pristine, never planned+ let load_s = t_load.elapsed().as_secs_f64();+ let tolerance = planner::consts::mesh_tolerance(0.1);++ eprintln!(+ "loaded {} parts in {:.2}s (tessellation, excluded from bench)",+ parts0.len(),+ load_s+ );++ // One warmup (JIT of code paths, allocator warmup) — discarded.+ {+ let mut w = Vec::new();+ let _ = planner::pipeline2::plan_parts(parts0.clone(), 0.5, 60, tolerance, None, &mut w);+ }++ let mut times: Vec<f64> = Vec::with_capacity(samples);+ for _ in 0..samples {+ let parts = parts0.clone(); // fresh empty caches, matches a real request+ let mut warnings = Vec::new();+ let t = Instant::now();+ let out = planner::pipeline2::plan_parts(parts, 0.5, 60, tolerance, None, &mut warnings);+ times.push(t.elapsed().as_secs_f64());+ std::hint::black_box(&out);+ }++ times.sort_by(|a, b| a.partial_cmp(b).unwrap());+ let n = times.len();+ let min = times[0];+ let max = times[n - 1];+ let median = times[n / 2];+ let mean = times.iter().sum::<f64>() / n as f64;+ let var = times.iter().map(|t| (t - mean).powi(2)).sum::<f64>() / n as f64;+ let stddev = var.sqrt();++ println!(+ "plan_parts n={n} min={min:.3}s median={median:.3}s mean={mean:.3}s max={max:.3}s stddev={stddev:.3}s (±{:.1}%)",+ 100.0 * stddev / mean+ );+}diff --git a/crates/planner/examples/contact_probe.rs b/crates/planner/examples/contact_probe.rsnew file mode 100644index 0000000000..56ffb16c7b--- /dev/null+++ b/crates/planner/examples/contact_probe.rs@@ -0,0 +1,109 @@+//! Diagnostic: measure the min mesh distance between contact-graph components,+//! to size ORDERING_CONTACT_MM. Usage:+//! cargo run --release -p planner --example contact_probe -- <in.step> [contact_mm]++use converter::convert::build_tree;+use planner::pipeline::{ordering_adjacency, PairDepths};+use planner::steps::collect_world_parts;+use std::collections::{HashMap, HashSet, VecDeque};++fn components(adj: &HashMap<String, HashSet<String>>) -> Vec<Vec<String>> {+ let mut seen: HashSet<String> = HashSet::new();+ let mut comps = Vec::new();+ for start in adj.keys() {+ if seen.contains(start) {+ continue;+ }+ let mut q = VecDeque::from([start.clone()]);+ let mut comp = Vec::new();+ seen.insert(start.clone());+ while let Some(n) = q.pop_front() {+ comp.push(n.clone());+ for nb in adj.get(&n).into_iter().flatten() {+ if seen.insert(nb.clone()) {+ q.push_back(nb.clone());+ }+ }+ }+ comps.push(comp);+ }+ comps+}++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let step = &args[1];+ let probe_mm: f64 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(0.5);++ let root = build_tree(step, 0.1, 0.5).expect("build");+ let parts = collect_world_parts(&root);+ let idx: HashMap<String, usize> =+ parts.iter().enumerate().map(|(i, p)| (p.node_id.clone(), i)).collect();+ let name = |id: &str| -> String {+ parts[*idx.get(id).unwrap()].name.clone()+ };++ // Baseline adjacency at the given threshold → components.+ let pair_depths: PairDepths = HashMap::new();+ let adj = ordering_adjacency(&parts, &pair_depths, probe_mm);+ let mut comps = components(&adj);+ comps.sort_by_key(|c| std::cmp::Reverse(c.len()));+ let edges: usize = adj.values().map(|s| s.len()).sum::<usize>() / 2;+ let n = parts.len();+ let max_edges = n * (n - 1) / 2;+ eprintln!(+ "parts={} contact_mm={} components={} sizes={:?} edges={}/{} (avg_deg={:.1})",+ n,+ probe_mm,+ comps.len(),+ comps.iter().map(|c| c.len()).collect::<Vec<_>>(),+ edges,+ max_edges,+ 2.0 * edges as f64 / n as f64+ );++ // For every pair of DIFFERENT components, the closest mesh distance.+ let comp_of: HashMap<String, usize> = comps+ .iter()+ .enumerate()+ .flat_map(|(ci, c)| c.iter().map(move |id| (id.clone(), ci)))+ .collect();++ let n = parts.len();+ let mut best_between: HashMap<(usize, usize), (f64, String, String)> = HashMap::new();+ for i in 0..n {+ for j in (i + 1)..n {+ let ci = comp_of[&parts[i].node_id];+ let cj = comp_of[&parts[j].node_id];+ if ci == cj {+ continue;+ }+ let key = (ci.min(cj), ci.max(cj));+ // bbox prefilter to keep it cheap: only measure pairs within 20mm bbox+ let within = (0..3).all(|k| {+ parts[i].bbox_min[k] - 20.0 <= parts[j].bbox_max[k]+ && parts[j].bbox_min[k] - 20.0 <= parts[i].bbox_max[k]+ });+ if !within {+ continue;+ }+ let d = collision::distance_pair(&parts[i].bvh(), &parts[j].bvh());+ let e = best_between+ .entry(key)+ .or_insert((f64::INFINITY, String::new(), String::new()));+ if d < e.0 {+ *e = (d, name(&parts[i].node_id), name(&parts[j].node_id));+ }+ }+ }+ let mut rows: Vec<_> = best_between.into_iter().collect();+ rows.sort_by(|a, b| a.1 .0.partial_cmp(&b.1 .0).unwrap());+ eprintln!("closest inter-component mesh distances (bbox<20mm pairs):");+ for ((ci, cj), (d, a, b)) in rows.iter().take(20) {+ eprintln!(+ " comp{ci}(n={}) <-> comp{cj}(n={}) : {d:.3} mm [{a} <-> {b}]",+ comps[*ci].len(),+ comps[*cj].len()+ );+ }+}diff --git a/crates/planner/examples/plan_file.rs b/crates/planner/examples/plan_file.rsnew file mode 100644index 0000000000..7fdd224dd3--- /dev/null+++ b/crates/planner/examples/plan_file.rs@@ -0,0 +1,30 @@+//! Plan a STEP file and write plan.json. Usage:+//! cargo run --release -p planner --example plan_file -- <in.step> <out.plan.json>++// jemalloc on Linux only: measured on macOS it LOSES to the system allocator+// (~+6% wall on all three real assemblies); glibc malloc under rayon-threaded+// allocation churn is the case it wins. Matches the server binary's gating.+#[cfg(target_os = "linux")]+#[global_allocator]+static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;++fn main() {+ let args: Vec<String> = std::env::args().collect();+ let step = &args[1];+ let out = &args[2];+ let t = std::time::Instant::now();+ let r = planner::steps::plan_step(step, 0.1, 0.5, 0.5, 60, Some(5000), None, None, None)+ .expect("plan");+ std::fs::write(out, serde_json::to_vec(&r.plan).unwrap()).unwrap();+ eprintln!(+ "comps={} planned={} verified={} {:.1}s tiers={:?} contacts_at_calls={} narrow_pairs={} raw_contacts={}",+ r.component_count,+ r.planned_count,+ r.verified_count,+ t.elapsed().as_secs_f64(),+ r.tiers.iter().filter(|(_, v)| **v > 0).collect::<Vec<_>>(),+ planner::collide::contacts_at_calls(),+ collision::narrow_pairs_run(),+ collision::raw_contacts_enumerated(),+ );+}diff --git a/crates/planner/examples/stress.rs b/crates/planner/examples/stress.rsnew file mode 100644index 0000000000..be305a6f72--- /dev/null+++ b/crates/planner/examples/stress.rs@@ -0,0 +1,128 @@+//! Stress/quality harness: plan every STEP file given (files or a directory),+//! score plan QUALITY — the new bar is "minimize manual intervention", i.e.+//! flagged/escape parts — not byte-parity with the Python planner (which the+//! domain owner rates "just ok, required manual intervention on all of them").+//!+//! cargo run --release -p planner --example stress -- <step-or-dir>... [--json out.json]+//!+//! Per file: tier counts, flagged part names (the manual-work list), verified+//! ratio, plan wall time, determinism (2 runs must hash identical). JSON+//! artifact lets two planner versions be diffed honestly.++use serde_json::{json, Value};+use std::collections::hash_map::DefaultHasher;+use std::hash::{Hash, Hasher};++fn plan_hash(plan: &Value) -> u64 {+ let mut h = DefaultHasher::new();+ serde_json::to_string(plan).unwrap().hash(&mut h);+ h.finish()+}++fn main() {+ let mut args: Vec<String> = std::env::args().skip(1).collect();+ let mut json_out = None;+ if let Some(i) = args.iter().position(|a| a == "--json") {+ json_out = args.get(i + 1).cloned();+ args.drain(i..=i.min(args.len() - 2) + 1);+ }+ let mut files: Vec<std::path::PathBuf> = Vec::new();+ for a in &args {+ let p = std::path::PathBuf::from(a);+ if p.is_dir() {+ let mut v: Vec<_> = std::fs::read_dir(&p)+ .unwrap()+ .filter_map(|e| e.ok().map(|e| e.path()))+ .filter(|p| {+ p.extension()+ .map(|e| {+ let e = e.to_string_lossy().to_lowercase();+ e == "step" || e == "stp"+ })+ .unwrap_or(false)+ })+ .collect();+ v.sort();+ files.extend(v);+ } else {+ files.push(p);+ }+ }++ let mut reports = Vec::new();+ println!(+ "{:<24} {:>5} {:>7} {:>7} {:>6} {:>6} {:>8} {:>7} det",+ "file", "parts", "linear", "flagged", "escape", "group", "verified", "plan_s"+ );+ for f in &files {+ let name = f.file_stem().unwrap().to_string_lossy().to_string();+ let path = f.to_string_lossy().to_string();+ let t = std::time::Instant::now();+ let r1 =+ match planner::steps::plan_step(&path, 0.1, 0.5, 0.5, 60, Some(5000), None, None, None)+ {+ Ok(r) => r,+ Err(e) => {+ println!("{name:<24} ERROR: {}", e.message);+ reports.push(json!({"file": name, "error": e.message}));+ continue;+ }+ };+ let plan_s = t.elapsed().as_secs_f64();+ let r2 = planner::steps::plan_step(&path, 0.1, 0.5, 0.5, 60, Some(5000), None, None, None)+ .expect("second run");+ let deterministic = plan_hash(&r1.plan) == plan_hash(&r2.plan);++ let tiers: std::collections::BTreeMap<String, i64> =+ r1.tiers.iter().map(|(k, v)| (k.clone(), *v)).collect();+ let g = |k: &str| tiers.get(k).copied().unwrap_or(0);+ // The manual-work list: flagged parts by name (falls back to nodeId).+ let comps = r1.plan["components"]+ .as_object()+ .cloned()+ .unwrap_or_default();+ let flagged: Vec<String> = comps+ .iter()+ .filter(|(_, v)| v["tier"].as_str() == Some("flagged"))+ .map(|(k, v)| {+ v["name"]+ .as_str()+ .filter(|s| !s.is_empty())+ .unwrap_or(k)+ .to_string()+ })+ .collect();++ println!(+ "{:<24} {:>5} {:>7} {:>7} {:>6} {:>6} {:>7}/{:<3} {:>6.1}s {}",+ &name[..name.len().min(24)],+ r1.component_count,+ g("linear") + g("l"),+ g("flagged"),+ g("escape"),+ g("group"),+ r1.verified_count,+ r1.planned_count,+ plan_s,+ if deterministic { "ok" } else { "NONDET!" },+ );+ for fp in &flagged {+ println!("{:<24} flagged: {fp}", "");+ }+ reports.push(json!({+ "file": name,+ "components": r1.component_count,+ "tiers": tiers,+ "flagged_parts": flagged,+ "planned": r1.planned_count,+ "verified": r1.verified_count,+ "plan_seconds": plan_s,+ "deterministic": deterministic,+ "warnings": r1.warnings,+ }));+ }+ if let Some(out) = json_out {+ std::fs::write(&out, serde_json::to_vec_pretty(&json!(reports)).unwrap()).unwrap();+ eprintln!("wrote {out}");+ }+}diff --git a/crates/planner/src/collide.rs b/crates/planner/src/collide.rsnew file mode 100644index 0000000000..2ba2f2892c--- /dev/null+++ b/crates/planner/src/collide.rs@@ -0,0 +1,538 @@+//! Collision-query core over the FCL bridge: `contacts_at` (max penetration+//! depth per neighbor), the `classify` early-stop path, path/free-travel sweeps,+//! and the mate/seated/self exemption maps.++use crate::consts::*;+use crate::types::{Component, FastenerInfo};+use nalgebra::Vector3;+use smallvec::SmallVec;+use std::collections::HashMap;++/// Per-query contact list. Almost every sample touches ≤8 others, so the list+/// lives inline on the stack — millions of `contacts_at` calls (2.9M on the+/// 431-part BCU) stop paying a heap alloc each.+pub type Contacts = SmallVec<[(String, f64); 8]>;++/// Global count of `contacts_at` calls (perf diagnostic; read via `contacts_at_calls`).+pub static CONTACTS_AT_CALLS: std::sync::atomic::AtomicUsize =+ std::sync::atomic::AtomicUsize::new(0);++/// Snapshot the current `contacts_at` call count.+pub fn contacts_at_calls() -> usize {+ CONTACTS_AT_CALLS.load(std::sync::atomic::Ordering::Relaxed)+}++/// Per-query FCL contact budget. Every consumer collapses contacts to+/// max-depth-per-neighbor, so this only bounds pathological deep overlaps; the+/// classify path early-stops well before it.+const NUM_MAX_CONTACTS: usize = 100_000;++/// An allowance map: partner nodeId -> allowed seated interference (mm).+/// `f64::INFINITY` means "the moving part / group member itself" — never counts+/// as touching or blocking.+pub type Exempt = HashMap<String, f64>;++/// One FCL broadphase manager built from a set of static parts, reused across+/// all samples of a sweep — the algorithmic replacement for the old+/// per-sample-per-other pairwise `collide`. The moving part is expected to be+/// absent from `others` (callers pass `others` = the current set minus the+/// moving part), so no self-collision cost is paid.+pub struct Broadphase {+ manager: cxx::UniquePtr<collision::Manager>,+ index_to_node: Vec<String>,+}++impl Broadphase {+ pub fn new(others: &[&Component]) -> Self {+ let mut manager = collision::manager_new();+ let mut index_to_node = Vec::with_capacity(others.len());+ for o in others {+ collision::manager_add(manager.pin_mut(), &o.bvh());+ index_to_node.push(o.node_id.clone());+ }+ collision::manager_setup(manager.pin_mut());+ Broadphase {+ manager,+ index_to_node,+ }+ }++ /// `_contacts_at`: (otherName, max_depth) for `part` translated by+ /// `translation` against the registered others. One broadphase query.+ pub fn contacts_at(&self, part: &Component, translation: &Vector3<f64>) -> Contacts {+ CONTACTS_AT_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ let bvh = part.bvh();+ let cs = collision::manager_collide_single(+ &self.manager,+ &bvh,+ -1,+ translation[0],+ translation[1],+ translation[2],+ NUM_MAX_CONTACTS,+ );+ cs.into_iter()+ .map(|c| (self.index_to_node[c.other].clone(), c.depth))+ .collect()+ }+}++/// `_contacts_at` (one-shot): builds a broadphase over `others` and queries once.+/// Prefer building a `Broadphase` when sweeping many samples.+pub fn contacts_at(+ part: &Component,+ others: &[&Component],+ translation: &Vector3<f64>,+) -> Contacts {+ Broadphase::new(others).contacts_at(part, translation)+}++/// A PERSISTENT broadphase manager for a working set of parts — built once and+/// reused across the whole plan. Sweeps exclude the moving part by its index+/// (no per-sweep rebuild, no unregister); parts are set inactive on removal.+/// This is the algorithmic key to matching/beating Python's speed: Python keeps+/// one `DynamicAABBTreeCollisionManager` for the entire greedy loop.+pub struct CollisionWorld {+ manager: cxx::UniquePtr<collision::Manager>,+ node_to_index: HashMap<String, usize>,+ index_to_node: Vec<String>,+}++// SAFETY: the parallel greedy sweeps share ONE `&CollisionWorld` across rayon+// workers, each issuing read-only `contacts_at*` queries. Those bottom out in+// FCL's `DynamicAABBTreeCollisionManager::collide(obj, cdata, cb) const` — a pure+// read (BV overlap + callback; the manager has no `mutable` members and the+// narrowphase result/contact state is call-local), over BVHModels frozen after+// `endModel` (see `SharedBvh`). The only structural mutations (`add`,+// `set_active`) take `&mut self`, so Rust statically forbids them from+// overlapping the shared `&self` queries. `manager_new`/`manager_add`/etc. are+// never called concurrently on one instance.+unsafe impl Sync for CollisionWorld {}++impl CollisionWorld {+ pub fn new(parts: &[&Component]) -> Self {+ let mut manager = collision::manager_new();+ let mut node_to_index = HashMap::new();+ let mut index_to_node = Vec::with_capacity(parts.len());+ for (i, p) in parts.iter().enumerate() {+ collision::manager_add(manager.pin_mut(), &p.bvh());+ node_to_index.insert(p.node_id.clone(), i);+ index_to_node.push(p.node_id.clone());+ }+ collision::manager_setup(manager.pin_mut());+ CollisionWorld {+ manager,+ node_to_index,+ index_to_node,+ }+ }++ pub fn from_components(parts: &[Component]) -> Self {+ let refs: Vec<&Component> = parts.iter().collect();+ Self::new(&refs)+ }++ pub fn index_of(&self, node_id: &str) -> i64 {+ self.node_to_index+ .get(node_id)+ .map(|&i| i as i64)+ .unwrap_or(-1)+ }++ /// Register a new body (a merged/combined mesh) mid-plan. Returns its index.+ pub fn add(&mut self, node_id: &str, part: &Component) -> usize {+ collision::manager_add(self.manager.pin_mut(), &part.bvh());+ collision::manager_setup(self.manager.pin_mut());+ let idx = self.index_to_node.len();+ self.node_to_index.insert(node_id.to_string(), idx);+ self.index_to_node.push(node_id.to_string());+ idx+ }++ /// Toggle a body's participation (removal, or the group unregister protocol).+ pub fn set_active(&mut self, node_id: &str, active: bool) {+ if let Some(&i) = self.node_to_index.get(node_id) {+ collision::manager_set_active(self.manager.pin_mut(), i, active);+ }+ }++ /// `_contacts_at`: (otherName, max_depth) for `part` (moving) translated by+ /// `translation`, against the active bodies — one broadphase query, self+ /// excluded by index.+ pub fn contacts_at(&self, part: &Component, translation: &Vector3<f64>) -> Contacts {+ CONTACTS_AT_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ let bvh = part.bvh();+ let mi = self.index_of(&part.node_id);+ let cs = collision::manager_collide_single(+ &self.manager,+ &bvh,+ mi,+ translation[0],+ translation[1],+ translation[2],+ NUM_MAX_CONTACTS,+ );+ cs.into_iter()+ .map(|c| (self.index_to_node[c.other].clone(), c.depth))+ .collect()+ }++ /// Resolve an exempt map (name → allowance) into index-space blocking+ /// thresholds for `classify`: each finite allowance becomes+ /// `allowance + MATE_DEPTH_MARGIN_MM` (the exact skip predicate the Rust+ /// consumers apply); infinite allowances pass through as +INF (the backend+ /// drops those neighbors entirely — they can never block, near, or touch).+ pub fn resolve_exempt(&self, exempt: Option<&Exempt>) -> (Vec<i64>, Vec<f64>) {+ let mut idx = Vec::new();+ let mut am = Vec::new();+ if let Some(ex) = exempt {+ for (name, &allow) in ex {+ if let Some(&i) = self.node_to_index.get(name) {+ idx.push(i as i64);+ am.push(if allow == f64::INFINITY {+ f64::INFINITY+ } else {+ allow + MATE_DEPTH_MARGIN_MM+ });+ }+ }+ }+ (idx, am)+ }++ /// Threshold-classified `_contacts_at` for the sweep consumers: same+ /// (other, depth) shape, but the backend may early-stop each neighbor at+ /// the first pair past its predicate threshold (see the bridge doc). On+ /// the FCL backend this is EXACTLY `contacts_at` (hints ignored) — parity+ /// holds by construction. `want_touch_near=false` when the caller only+ /// tests blocking (free_travel / path_blockers).+ #[allow(clippy::too_many_arguments)]+ pub fn classify(+ &self,+ part: &Component,+ translation: &Vector3<f64>,+ skip_nodes: &std::collections::BTreeSet<String>,+ ov: &(Vec<i64>, Vec<f64>),+ tol: f64,+ want_touch_near: bool,+ ) -> Contacts {+ CONTACTS_AT_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ let bvh = part.bvh();+ let mut skip: SmallVec<[i64; 16]> = SmallVec::with_capacity(skip_nodes.len() + 1);+ skip.push(self.index_of(&part.node_id));+ for n in skip_nodes {+ if let Some(&i) = self.node_to_index.get(n) {+ skip.push(i as i64);+ }+ }+ let cs = collision::manager_classify_multi(+ &self.manager,+ &bvh,+ &skip,+ &ov.0,+ &ov.1,+ translation[0],+ translation[1],+ translation[2],+ tol,+ want_touch_near,+ NUM_MAX_CONTACTS,+ );+ cs.into_iter()+ .map(|c| (self.index_to_node[c.other].clone(), c.depth))+ .collect()+ }++ /// `_contacts_at` with extra bodies culled at the broadphase — the moving+ /// part plus any `skip_nodes` (known blockers a sweep no longer needs to+ /// re-enumerate). One broadphase query; skipped bodies never narrowphase.+ pub fn contacts_at_excluding(+ &self,+ part: &Component,+ translation: &Vector3<f64>,+ skip_nodes: &std::collections::BTreeSet<String>,+ ) -> Contacts {+ CONTACTS_AT_CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);+ let bvh = part.bvh();+ let mut skip: SmallVec<[i64; 16]> = SmallVec::with_capacity(skip_nodes.len() + 1);+ skip.push(self.index_of(&part.node_id));+ for n in skip_nodes {+ if let Some(&i) = self.node_to_index.get(n) {+ skip.push(i as i64);+ }+ }+ let cs = collision::manager_collide_single_multi(+ &self.manager,+ &bvh,+ &skip,+ translation[0],+ translation[1],+ translation[2],+ NUM_MAX_CONTACTS,+ );+ cs.into_iter()+ .map(|c| (self.index_to_node[c.other].clone(), c.depth))+ .collect()+ }+}++/// `_blocking_depth`: max blocking penetration over a sample's contacts.+pub fn blocking_depth(contacts: &[(String, f64)], exempt: Option<&Exempt>) -> f64 {+ let mut depth = 0.0;+ for (other, cd) in contacts {+ if let Some(ex) = exempt {+ if let Some(&allow) = ex.get(other) {+ if *cd <= allow + MATE_DEPTH_MARGIN_MM {+ continue;+ }+ }+ }+ if *cd > depth {+ depth = *cd;+ }+ }+ depth+}++/// `_mate_exempt`: bore-engagement allowances for this part along `direction`.+pub fn mate_exempt(+ part: &Component,+ direction: &Vector3<f64>,+ fasteners: &HashMap<String, FastenerInfo>,+) -> Option<Exempt> {+ let info = fasteners.get(&part.node_id)?;+ if info.mates.is_empty() && info.sliding.is_empty() {+ return None;+ }+ if direction.dot(&info.axis).abs() > 0.99 {+ let mut merged: Exempt = info.sliding.clone();+ for (k, v) in &info.mates {+ merged.insert(k.clone(), *v); // mates win on collision, per {**sliding, **mates}+ }+ return Some(merged);+ }+ None+}++/// `_seated_exempt`: sandwich-squish allowances valid along `direction`.+pub fn seated_exempt(part: &Component, direction: &Vector3<f64>) -> Option<Exempt> {+ if part.seated_allowance.is_empty() {+ return None;+ }+ let mut allowed: Exempt = HashMap::new();+ for (partner, depth) in &part.seated_allowance {+ if let Some(axis) = part.seated_allowance_axes.get(partner) {+ if direction.dot(axis).abs() > 0.99 {+ allowed.insert(partner.clone(), *depth);+ }+ }+ }+ if allowed.is_empty() {+ None+ } else {+ Some(allowed)+ }+}++/// `_self_exempt`: merge an infinite allowance for the moving part(s).+pub fn self_exempt(exempt: Option<Exempt>, self_ids: &[&str]) -> Exempt {+ let mut merged = exempt.unwrap_or_default();+ for id in self_ids {+ merged.insert((*id).to_string(), f64::INFINITY);+ }+ merged+}++/// numpy `np.linspace(start, end, n, endpoint=True)[1:]`.+fn linspace_tail(start: f64, end: f64, n: usize) -> Vec<f64> {+ if n <= 1 {+ return vec![end];+ }+ let step = (end - start) / (n as f64 - 1.0);+ (1..n).map(|i| start + i as f64 * step).collect()+}++/// Python `int(x)` truncation toward zero, used for the sample-count formula.+fn sample_count(samples: usize, span: f64) -> usize {+ let by_spacing = (span / MAX_SAMPLE_SPACING_MM).trunc() as i64 + 1;+ samples+ .max(by_spacing.max(0) as usize)+ .min(MAX_PATH_SAMPLES)+}++/// `_path_is_clear`: dense sampling; None if blocked, else the last touching+/// distance (0.0 for a free flight).+#[allow(clippy::too_many_arguments)]+pub fn path_is_clear(+ part: &Component,+ world: &CollisionWorld,+ direction: &Vector3<f64>,+ start: f64,+ end: f64,+ samples: usize,+ tolerance: f64,+ base_offset: Option<&Vector3<f64>>,+ exempt: Option<Exempt>,+ check_until: Option<f64>,+) -> Option<f64> {+ if end <= start {+ return None;+ }+ // Compliant squish along the sandwich axis never blocks; explicit+ // exemptions keep precedence when larger.+ let mut exempt = exempt;+ if let Some(seated) = seated_exempt(part, direction) {+ let mut merged = seated;+ if let Some(ex) = &exempt {+ for (k, v) in ex {+ let e = merged.entry(k.clone()).or_insert(f64::MIN);+ *e = e.max(*v);+ }+ }+ exempt = Some(merged);+ }+ let n = sample_count(samples, end - start);+ let offsets = linspace_tail(start, end, n);+ let spacing = (end - start) / (n.max(2) as f64 - 1.0);++ let no_skip = std::collections::BTreeSet::new();+ let ov = world.resolve_exempt(exempt.as_ref());+ let blocked_at = |distance: f64| -> (bool, bool, bool) {+ let mut translation = direction * distance;+ if let Some(off) = base_offset {+ translation += off;+ }+ let contacts = world.classify(part, &translation, &no_skip, &ov, tolerance, true);+ if contacts.is_empty() {+ return (false, false, false);+ }+ let depth = blocking_depth(&contacts, exempt.as_ref());+ let touching = contacts.iter().any(|(other, _)| {+ !matches!(exempt.as_ref().and_then(|e| e.get(other)), Some(&a) if a == f64::INFINITY)+ });+ (depth > tolerance, depth > tolerance * 0.5, touching)+ };++ let mut last_touch = 0.0;+ for &s in &offsets {+ if let Some(cu) = check_until {+ if s > cu {+ break;+ }+ }+ let (blocked, near, touching) = blocked_at(s);+ if blocked {+ return None;+ }+ if touching {+ last_touch = s;+ }+ if near {+ let half = spacing / 2.0;+ for probe in [s - half, s + half] {+ if probe <= start || probe >= end {+ continue;+ }+ if blocked_at(probe).0 {+ return None;+ }+ }+ }+ }+ Some(last_touch)+}++/// `_free_travel`: furthest clear translation along `direction` from `base_offset`.+#[allow(clippy::too_many_arguments)]+pub fn free_travel(+ part: &Component,+ world: &CollisionWorld,+ direction: &Vector3<f64>,+ base_offset: &Vector3<f64>,+ cap: f64,+ samples: usize,+ exempt: Option<&Exempt>,+ tolerance: f64,+) -> f64 {+ if cap <= 0.0 {+ return 0.0;+ }+ let n = sample_count(samples, cap);+ let offsets = linspace_tail(0.0, cap, n);+ let no_skip = std::collections::BTreeSet::new();+ let ov = world.resolve_exempt(exempt);+ let mut clear = 0.0;+ for s in offsets {+ let translation = direction * s + base_offset;+ let contacts = world.classify(part, &translation, &no_skip, &ov, tolerance, false);+ if !contacts.is_empty() {+ let depth = blocking_depth(&contacts, exempt);+ if depth > tolerance {+ return clear;+ }+ }+ clear = s;+ }+ clear+}++/// `_path_blockers`: every present part the removal path cuts through+/// (union over segments). Mirrors Python's unregister-mid-sweep: once a partner+/// is a confirmed blocker its identity is all this returns, so it is culled from+/// every later sample (`contacts_at_excluding`) — otherwise a deep pass-through+/// re-enumerates that blocker's full triangle-contact set at every sample (the+/// dominant cost). Sound: a recorded blocker can't be un-recorded, and FCL+/// enumerates pairs independently, so culling one never hides another's contacts.+#[allow(clippy::too_many_arguments)]+pub fn path_blockers(+ part: &Component,+ world: &CollisionWorld,+ segments: &[(Vector3<f64>, f64)],+ samples: usize,+ fasteners: &HashMap<String, FastenerInfo>,+ extra_exempt: Option<&Exempt>,+ tolerance: f64,+) -> std::collections::BTreeSet<String> {+ let mut blockers = std::collections::BTreeSet::new();+ let mut offset = Vector3::zeros();+ for (direction, distance) in segments {+ let mut exempt = mate_exempt(part, direction, fasteners);+ if let Some(seated) = seated_exempt(part, direction) {+ let mut merged = seated;+ if let Some(ex) = exempt {+ for (k, v) in ex {+ merged.insert(k, v);+ }+ }+ exempt = Some(merged);+ }+ if let Some(extra) = extra_exempt {+ let mut merged = exempt.unwrap_or_default();+ for (k, v) in extra {+ merged.insert(k.clone(), *v);+ }+ exempt = Some(merged);+ }+ let count = sample_count(samples, *distance);+ let ov = world.resolve_exempt(exempt.as_ref());+ for s in linspace_tail(0.0, *distance, count) {+ let translation = offset + direction * s;+ for (other, depth) in+ world.classify(part, &translation, &blockers, &ov, tolerance, false)+ {+ if let Some(ex) = &exempt {+ if let Some(&allow) = ex.get(&other) {+ if depth <= allow + MATE_DEPTH_MARGIN_MM {+ continue;+ }+ }+ }+ if depth > tolerance {+ blockers.insert(other);+ }+ }+ }+ offset += direction * *distance;+ }+ blockers+}diff --git a/crates/planner/src/consts.rs b/crates/planner/src/consts.rsnew file mode 100644index 0000000000..cf0dbe3b6c--- /dev/null+++ b/crates/planner/src/consts.rs@@ -0,0 +1,116 @@+//! Planner constants (tolerances, sampling, sandwich/fastener thresholds).++use nalgebra::Vector3;++/// Default allowed surface penetration (mm) along a removal path.+pub const PENETRATION_TOLERANCE_MM: f64 = 0.15;++/// Effective tolerance scales with the deflection used to mesh the model.+pub fn mesh_tolerance(linear_deflection: f64) -> f64 {+ PENETRATION_TOLERANCE_MM.max(2.5 * linear_deflection)+}++/// Margin (mm) past the assembly bounds before a part counts as "out".+pub const EXIT_MARGIN_MM: f64 = 5.0;++pub const MAX_SAMPLE_SPACING_MM: f64 = 2.0;+pub const MAX_PATH_SAMPLES: usize = 400;++pub const MATE_MIN_DEPTH_MM: f64 = 0.2;+pub const MATE_DEPTH_MARGIN_MM: f64 = 0.3;++/// How many blocking parts a flagged component reports. The full blocker set is+/// computed everywhere `blocked_by` is set; this caps only what reaches the wire+/// (a heavily-flagged flat-export model can block on dozens of parts — 32 is a+/// generous diagnostic width without pathological JSON size).+pub const MAX_REPORTED_BLOCKERS: usize = 32;++pub const ORDERING_CONTACT_MM: f64 = 0.5;+pub const MAX_ADJACENCY_DISTANCE_PAIRS: usize = 20000;++/// Proximity (mm) at which two parts are treated as "related" — connected for+/// sequencing-connectivity and the emitted viewer contact graph, even when they+/// don't touch. Real assemblies hold parts together across mm-scale clearance+/// gaps (fasteners in clearance holes, snug slip-fits) that strict+/// `ORDERING_CONTACT_MM` contact can't see, which otherwise splits one physical+/// assembly into phantom-disconnected islands. Scaled to assembly size and+/// clamped; collision correctness still uses strict contact, so a generous value+/// here only softens the connectivity *preference* — it never permits a+/// colliding sequence.+pub fn relatedness_mm(assembly_diagonal: f64) -> f64 {+ (0.025 * assembly_diagonal).clamp(3.0, 25.0)+}++#[cfg(test)]+mod tests {+ use super::relatedness_mm;++ #[test]+ fn relatedness_scales_and_clamps() {+ // Floor for tiny assemblies, ceiling for huge ones, ~2.5% between.+ assert_eq!(relatedness_mm(40.0), 3.0);+ assert!((relatedness_mm(644.0) - 16.1).abs() < 0.05);+ assert_eq!(relatedness_mm(4000.0), 25.0);+ // Strictly exceeds strict contact so clearance-fit neighbors connect.+ assert!(relatedness_mm(644.0) > super::ORDERING_CONTACT_MM);+ }+}++pub const SANDWICH_MAX_THICKNESS_RATIO: f64 = 0.3;+pub const SANDWICH_MAX_THICKNESS_MM: f64 = 6.0;+pub const SANDWICH_AXIS_ALIGNMENT: f64 = 0.9;+pub const SANDWICH_MAX_SQUISH_MM: f64 = 0.6;++pub const MAX_FASTENER_DIAGONAL_FRACTION: f64 = 0.35;+pub const MAX_FASTENER_EXTENT_MM: f64 = 100.0;++pub const MAX_ESCAPE_SEGMENTS: usize = 3;+pub const MAX_ESCAPE_EXPANSIONS: usize = 24;+pub const MIN_HOP_FRACTION: f64 = 0.25;++pub const MAX_GROUP_SIZE: usize = 4;+pub const MAX_GROUP_TESTS: usize = 40;+pub const GROUP_PROXIMITY_MM: f64 = 2.0;++// --- Detail-swarm auto-detection (populated PCBs) -------------------------+// A populated PCB is geometrically unmistakable: one substantial host part+// (the bare board) carrying dozens-hundreds of tiny parts seated on it.+// Detected from pure geometry before planning so a 430-component board plans+// (and animates) as ONE rigid unit — no BOM or LLM assignment required.++/// A part is swarm-member "tiny" when its bbox diagonal is below this fraction+/// of the assembly diagonal (SA BCU components: ~0.6%; mechanical parts on the+/// corpus models: well above 10%).+pub const SWARM_TINY_FRACTION: f64 = 0.1;+/// A host forms a swarm unit only with at least this many seated tiny parts.+/// Deliberately above the "8 screws on a lid" shape (fasteners are excluded by+/// name anyway; this guards unnamed tiny hardware on a bracket).+pub const SWARM_MIN_MEMBERS: usize = 12;+/// Narrowphase distance (mm) at which a tiny part counts as seated ON a host.+/// Contact, not bbox overlap — a hollow enclosure's bbox contains everything.+pub const SWARM_CONTACT_MM: f64 = ORDERING_CONTACT_MM;+/// A member must also be dwarfed by its HOST (below this fraction of the host's+/// diagonal). PCB components are ~1% of their board; the counter-example is a+/// large assembly whose mid-size parts (rollers on a rail at ~15-18% of the+/// host) read as "tiny vs the assembly" but are real hand-assembled parts.+pub const SWARM_HOST_FRACTION: f64 = 0.1;+/// Once a host already carries a real tiny swarm (>= SWARM_MIN_MEMBERS), it is a+/// populated board — so a bigger board-mounted part (a chip, a connector) that+/// CONTACTS it and is still clearly smaller than it belongs to the same unit,+/// even though it is above the strict "tiny" gate. This looser fraction only+/// applies as an absorption pass into an ALREADY-detected swarm, so a bare rail+/// (no swarm) never sweeps up its mid-size rollers.+pub const SWARM_ABSORB_FRACTION: f64 = 0.35;++/// World axes in the exact order the Python planner tries them:+/// +Z, -Z, +X, -X, +Y, -Y.+pub fn world_axes() -> [Vector3<f64>; 6] {+ [+ Vector3::new(0.0, 0.0, 1.0),+ Vector3::new(0.0, 0.0, -1.0),+ Vector3::new(1.0, 0.0, 0.0),+ Vector3::new(-1.0, 0.0, 0.0),+ Vector3::new(0.0, 1.0, 0.0),+ Vector3::new(0.0, -1.0, 0.0),+ ]+}diff --git a/crates/planner/src/contains.rs b/crates/planner/src/contains.rsnew file mode 100644index 0000000000..5cf16cf33a--- /dev/null+++ b/crates/planner/src/contains.rs@@ -0,0 +1,108 @@+//! Point-in-mesh containment via ray casting. Used by embedded-pair and+//! fastener-joint detection, which vote on an aggregate fraction, so per-point+//! robustness matters more than the exact backend. A single ray in a+//! non-axis-aligned direction (avoids edge/vertex degeneracy) with odd-crossing+//! parity is the standard watertight test.++use crate::types::Mesh;+use nalgebra::Vector3;++/// Möller–Trumbore, forward hits only (t > eps).+fn ray_hits_triangle(+ origin: &Vector3<f64>,+ dir: &Vector3<f64>,+ v0: &Vector3<f64>,+ v1: &Vector3<f64>,+ v2: &Vector3<f64>,+) -> bool {+ const EPS: f64 = 1e-9;+ let e1 = v1 - v0;+ let e2 = v2 - v0;+ let p = dir.cross(&e2);+ let det = e1.dot(&p);+ if det.abs() < EPS {+ return false;+ }+ let inv = 1.0 / det;+ let t = origin - v0;+ let u = t.dot(&p) * inv;+ if u < 0.0 || u > 1.0 {+ return false;+ }+ let q = t.cross(&e1);+ let v = dir.dot(&q) * inv;+ if v < 0.0 || u + v > 1.0 {+ return false;+ }+ let dist = e2.dot(&q) * inv;+ dist > EPS+}++/// Which of `points` lie inside `mesh` (odd forward-crossing count).+pub fn mesh_contains(mesh: &Mesh, points: &[Vector3<f64>]) -> Vec<bool> {+ // A general direction: no exact axis component, so rays rarely graze a+ // coplanar face or slip through a shared edge.+ let dir = Vector3::new(1.0, 0.000_913_3, 0.000_731_7).normalize();+ points+ .iter()+ .map(|p| {+ let mut crossings = 0usize;+ for f in &mesh.faces {+ let v0 = &mesh.vertices[f[0] as usize];+ let v1 = &mesh.vertices[f[1] as usize];+ let v2 = &mesh.vertices[f[2] as usize];+ if ray_hits_triangle(p, &dir, v0, v1, v2) {+ crossings += 1;+ }+ }+ crossings % 2 == 1+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn unit_box() -> Mesh {+ // 2x2x2 box centered at origin.+ let v = [+ [-1., -1., -1.],+ [1., -1., -1.],+ [1., 1., -1.],+ [-1., 1., -1.],+ [-1., -1., 1.],+ [1., -1., 1.],+ [1., 1., 1.],+ [-1., 1., 1.],+ ];+ let vertices = v.iter().map(|c| Vector3::new(c[0], c[1], c[2])).collect();+ let faces = vec![+ [0, 2, 1],+ [0, 3, 2],+ [4, 5, 6],+ [4, 6, 7],+ [0, 1, 5],+ [0, 5, 4],+ [1, 2, 6],+ [1, 6, 5],+ [2, 3, 7],+ [2, 7, 6],+ [3, 0, 4],+ [3, 4, 7],+ ];+ Mesh { vertices, faces }+ }++ #[test]+ fn inside_outside() {+ let m = unit_box();+ let pts = vec![+ Vector3::new(0.0, 0.0, 0.0), // inside+ Vector3::new(5.0, 0.0, 0.0), // outside+ Vector3::new(0.5, 0.5, 0.5), // inside+ Vector3::new(-3.0, 0.0, 0.0), // outside+ ];+ assert_eq!(mesh_contains(&m, &pts), vec![true, false, true, false]);+ }+}diff --git a/crates/planner/src/fasteners.rs b/crates/planner/src/fasteners.rsnew file mode 100644index 0000000000..73488edfbb--- /dev/null+++ b/crates/planner/src/fasteners.rs@@ -0,0 +1,134 @@+//! Fastener classification helpers: name/geometry test and head direction.++use crate::consts::world_axes;+use crate::types::{Component, FastenerInfo};+use nalgebra::Vector3;+use regex::Regex;+use std::collections::HashMap;+use std::sync::OnceLock;++fn fastener_name_re() -> &'static Regex {+ static RE: OnceLock<Regex> = OnceLock::new();+ RE.get_or_init(|| {+ Regex::new(+ r"(?i)\b(screw|bolt|nut|washer|rivet|stud|dowel)s?\b|\bM\d+(x[\d.]+)?\b|\bDIN ?\d+|\bISO ?\d+",+ )+ .unwrap()+ })+}++/// `_is_fastener`: does the part's name match the fastener pattern?+pub fn is_fastener(part: &Component) -> bool {+ fastener_name_re().is_match(&part.name)+}++/// `_head_direction`: tip → head sense of a fastener's axis.+pub fn head_direction(+ part: &Component,+ info: &FastenerInfo,+ units_by_id: Option<&HashMap<String, Component>>,+) -> Vector3<f64> {+ let axis = info.axis;+ let verts = &part.mesh.vertices;+ if verts.len() >= 8 {+ let center = (part.bbox_min + part.bbox_max) / 2.0;+ let mut projs = Vec::with_capacity(verts.len());+ let mut radials = Vec::with_capacity(verts.len());+ for v in verts {+ let rel = v - center;+ let proj = rel.dot(&axis);+ projs.push(proj);+ radials.push((rel - axis * proj).norm());+ }+ let pmax = projs.iter().cloned().fold(f64::MIN, f64::max);+ let pmin = projs.iter().cloned().fold(f64::MAX, f64::min);+ let span = pmax - pmin;+ if span > 1e-6 {+ let mut hi = 0.0f64;+ let mut lo = 0.0f64;+ let mut any_hi = false;+ let mut any_lo = false;+ for (i, &p) in projs.iter().enumerate() {+ if p > span * 0.25 {+ hi = hi.max(radials[i]);+ any_hi = true;+ }+ if p < -span * 0.25 {+ lo = lo.max(radials[i]);+ any_lo = true;+ }+ }+ let hi = if any_hi { hi } else { 0.0 };+ let lo = if any_lo { lo } else { 0.0 };+ if (hi - lo).abs() > 0.2 {+ return if hi > lo { axis } else { -axis };+ }+ }+ }+ if let Some(units) = units_by_id {+ if !info.mates.is_empty() {+ let mut centers = Vec::new();+ for m in info.mates.keys() {+ if let Some(u) = units.get(m) {+ centers.push((u.bbox_min + u.bbox_max) / 2.0);+ }+ }+ if !centers.is_empty() {+ let f_center = (part.bbox_min + part.bbox_max) / 2.0;+ let mut mean = Vector3::zeros();+ for c in ¢ers {+ mean += c;+ }+ mean /= centers.len() as f64;+ let away = f_center - mean;+ if away.dot(&axis) < 0.0 {+ return -axis;+ }+ }+ }+ }+ axis+}++/// `_axis_span`: the part's bbox extent projected onto an axis line through origin.+pub fn axis_span(part: &Component, axis: &Vector3<f64>, origin: &Vector3<f64>) -> (f64, f64) {+ let mut lo = f64::INFINITY;+ let mut hi = f64::NEG_INFINITY;+ for xi in 0..2 {+ for yi in 0..2 {+ for zi in 0..2 {+ let corner = Vector3::new(+ if xi == 0 {+ part.bbox_min[0]+ } else {+ part.bbox_max[0]+ },+ if yi == 0 {+ part.bbox_min[1]+ } else {+ part.bbox_max[1]+ },+ if zi == 0 {+ part.bbox_min[2]+ } else {+ part.bbox_max[2]+ },+ );+ let p = (corner - origin).dot(axis);+ lo = lo.min(p);+ hi = hi.max(p);+ }+ }+ }+ (lo, hi)+}++/// Snap an axis to a positive world axis when aligned (shared helper).+pub fn snap_world(axis: Vector3<f64>) -> Vector3<f64> {+ for w in world_axes() {+ if axis.dot(&w) > 0.999 {+ return w;+ }+ }+ axis+}diff --git a/crates/planner/src/geom.rs b/crates/planner/src/geom.rsnew file mode 100644index 0000000000..74e616b6f6--- /dev/null+++ b/crates/planner/src/geom.rs@@ -0,0 +1,391 @@+//! Pure geometry helpers: volumes, symmetry axes (SVD), candidate directions,+//! structural sort key. Deterministic vector math, no collision library.++use crate::consts::{world_axes, EXIT_MARGIN_MM};+use crate::types::{Component, FastenerKind, Mesh};+use nalgebra::{DMatrix, Vector3};++/// Python's `round(x, ndigits)` — round half to even (banker's rounding).+pub fn round_py(x: f64, ndigits: i32) -> f64 {+ if !x.is_finite() {+ return x;+ }+ let factor = 10f64.powi(ndigits);+ let scaled = x * factor;+ let floor = scaled.floor();+ let diff = scaled - floor;+ let rounded = if (diff - 0.5).abs() < 1e-9 {+ // exactly halfway: round to even+ if (floor as i64) % 2 == 0 {+ floor+ } else {+ floor + 1.0+ }+ } else {+ scaled.round()+ };+ rounded / factor+}++/// Component-wise absolute value.+pub fn vabs(v: &Vector3<f64>) -> Vector3<f64> {+ Vector3::new(v[0].abs(), v[1].abs(), v[2].abs())+}++/// `_separation_distance`: translation along `direction` until the AABBs separate.+pub fn separation_distance(+ bbox_min: &Vector3<f64>,+ bbox_max: &Vector3<f64>,+ static_min: &Vector3<f64>,+ static_max: &Vector3<f64>,+ direction: &Vector3<f64>,+) -> f64 {+ let mut travel = f64::INFINITY;+ for axis in 0..3 {+ let d = direction[axis];+ if d > 1e-6 {+ let needed = static_max[axis] - bbox_min[axis];+ travel = travel.min((needed / d).max(0.0));+ } else if d < -1e-6 {+ let needed = bbox_max[axis] - static_min[axis];+ travel = travel.min((needed / -d).max(0.0));+ }+ }+ if travel == f64::INFINITY {+ 0.0+ } else {+ travel+ }+}++/// `_exit_travel`: distance along `direction` until the part's AABB clears the assembly.+pub fn exit_travel(+ part: &Component,+ static_min: &Vector3<f64>,+ static_max: &Vector3<f64>,+ direction: &Vector3<f64>,+ base_offset: Option<&Vector3<f64>>,+) -> f64 {+ let zero = Vector3::zeros();+ let off = base_offset.unwrap_or(&zero);+ let bbox_min = part.bbox_min + off;+ let bbox_max = part.bbox_max + off;+ let mut travel = separation_distance(&bbox_min, &bbox_max, static_min, static_max, direction);+ let diagonal = (static_max - static_min).norm();+ travel = travel.min(diagonal * 1.5);+ let extent = vabs(direction).dot(&(bbox_max - bbox_min));+ travel.max(extent) + EXIT_MARGIN_MM+}++/// `_recorded_travel`: the travel to record for the animation.+pub fn recorded_travel(+ part: &Component,+ direction: &Vector3<f64>,+ full_travel: f64,+ last_touch: f64,+) -> f64 {+ let extent = vabs(direction).dot(&(part.bbox_max - part.bbox_min));+ round_py(full_travel.min(last_touch + extent + EXIT_MARGIN_MM), 3)+}++/// `_bbox_axis_kind`: rod/disc axis from bbox extents when SVD is inconclusive.+pub fn bbox_axis_kind(part: &Component) -> Option<(Vector3<f64>, FastenerKind)> {+ let extents = vabs(&(part.bbox_max - part.bbox_min));+ // argsort ascending+ let mut order = [0usize, 1, 2];+ order.sort_by(|&a, &b| extents[a].partial_cmp(&extents[b]).unwrap());+ let smallest = extents[order[0]];+ let mid = extents[order[1]];+ let largest = extents[order[2]];+ if mid <= 1e-9 {+ return None;+ }+ let mut axis = Vector3::zeros();+ if largest > 1.4 * mid {+ axis[order[2]] = 1.0;+ return Some((axis, FastenerKind::Rod));+ }+ if smallest < 0.6 * mid {+ axis[order[0]] = 1.0;+ return Some((axis, FastenerKind::Disc));+ }+ None+}++/// Snap a unit direction to a clean world axis when within 0.999 dot.+pub fn snap_to_world(axis: Vector3<f64>) -> Vector3<f64> {+ for w in world_axes() {+ if axis.dot(&w) > 0.999 {+ return w;+ }+ }+ axis+}++/// Signed mesh volume via the divergence theorem (abs).+fn signed_volume(mesh: &Mesh) -> f64 {+ let mut s = 0.0;+ for f in &mesh.faces {+ let a = &mesh.vertices[f[0] as usize];+ let b = &mesh.vertices[f[1] as usize];+ let c = &mesh.vertices[f[2] as usize];+ s += a.dot(&b.cross(c));+ }+ (s / 6.0).abs()+}++/// trimesh `is_watertight`: every sorted edge is shared by exactly two faces.+/// Pure integer logic — bit-exact across implementations. OCCT-tessellated parts+/// duplicate vertices per B-rep face, so real parts are essentially never+/// watertight (matching the Python service).+pub fn is_watertight(mesh: &Mesh) -> bool {+ if mesh.faces.is_empty() {+ return false;+ }+ let mut counts: std::collections::HashMap<(u32, u32), u32> = std::collections::HashMap::new();+ for f in &mesh.faces {+ for (a, b) in [(f[0], f[1]), (f[1], f[2]), (f[2], f[0])] {+ let key = if a <= b { (a, b) } else { (b, a) };+ *counts.entry(key).or_insert(0) += 1;+ }+ }+ counts.values().all(|&c| c == 2)+}++/// `_part_volume`: material volume (mm³). Faithful to the DEPLOYED Python+/// service: watertight → mesh volume; otherwise the split-into-bodies fallback+/// RAISES there (trimesh's repair path needs networkx, absent from the service+/// deps) → `except: volume = 0.0` → **bbox volume**. Real OCCT-tessellated parts+/// are never watertight, so bbox volume is the production path (verified+/// bit-identical on real assemblies).+pub fn part_volume(part: &Component) -> f64 {+ if let Some(v) = part.cached_volume {+ return v;+ }+ *part.vol_cache.get_or_init(|| {+ let v = if is_watertight(&part.mesh) {+ signed_volume(&part.mesh)+ } else {+ 0.0+ };+ if v > 1e-9 {+ return v;+ }+ let e = part.bbox_max - part.bbox_min;+ (e[0] * e[1] * e[2]).abs().max(1e-9)+ })+}++/// `_assembly_centroid`: bbox center over all parts.+pub fn assembly_centroid(parts: &[Component]) -> Vector3<f64> {+ let mut lo = Vector3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);+ let mut hi = Vector3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+ for p in parts {+ lo = lo.inf(&p.bbox_min);+ hi = hi.sup(&p.bbox_max);+ }+ (lo + hi) / 2.0+}++/// `_structural_key`: (−volume, bucket) — big & central first (ascending key).+pub fn structural_key(part: &Component, centroid: &Vector3<f64>, diagonal: f64) -> (f64, f64) {+ let center = (part.bbox_min + part.bbox_max) / 2.0;+ let offset = center - centroid;+ let distance = offset[0].hypot(offset[1]);+ let bucket = round_py(distance / diagonal.max(1e-6) * 20.0, 0) / 20.0;+ (-part_volume(part), bucket)+}++/// `_symmetry_axis_kind`: rod/disc insertion axis via SVD of the vertex cloud.+/// numpy-matching: mean via numpy's pairwise summation, SVD via LAPACK dgesdd —+/// so the axis SIGN matches Python's (no canonicalization).+///+/// Memoized per Component: the SVD is pure in the mesh vertices, and the greedy+/// loop re-asks the same part every iteration. `Component::new` gives each part+/// (and merged unit) a fresh cell, so clones never carry a stale axis.+pub fn symmetry_axis_kind(part: &Component) -> Option<(Vector3<f64>, FastenerKind)> {+ *part+ .sym_axis_cache+ .get_or_init(|| symmetry_axis_kind_uncached(part))+}++fn symmetry_axis_kind_uncached(part: &Component) -> Option<(Vector3<f64>, FastenerKind)> {+ let verts = &part.mesh.vertices;+ if verts.len() < 3 {+ return None;+ }+ let mean = crate::npy::mean_rows(verts);+ let mut m = DMatrix::<f64>::zeros(verts.len(), 3);+ for (i, v) in verts.iter().enumerate() {+ let c = v - mean;+ m[(i, 0)] = c[0];+ m[(i, 1)] = c[1];+ m[(i, 2)] = c[2];+ }+ let (s, vt) = crate::npy::svd_rows(&m)?;+ let (s1, s2, s3) = (s[0], s[1], s[2]);+ if s2 <= 1e-9 {+ return None;+ }+ let row = |i: usize| Vector3::new(vt[(i, 0)], vt[(i, 1)], vt[(i, 2)]);+ let (axis, kind) = if s1 > 1.4 * s2 {+ (row(0), FastenerKind::Rod)+ } else if s3 > 1e-9 && s2 > 1.4 * s3 && s1 < 1.25 * s2 {+ (row(2), FastenerKind::Disc)+ } else {+ return None;+ };+ let norm = axis.norm();+ if norm <= 1e-9 {+ return None;+ }+ let axis = axis / norm;+ for w in world_axes() {+ if axis.dot(&w) > 0.999 {+ return Some((w, kind));+ }+ }+ Some((axis, kind))+}++pub fn symmetry_axis(part: &Component) -> Option<Vector3<f64>> {+ symmetry_axis_kind(part).map(|(a, _)| a)+}++/// `_normal_clusters`: dominant contact-normal directions (greedy clustering).+pub fn normal_clusters(normals: &[Vector3<f64>], top: usize) -> Vec<Vector3<f64>> {+ let mut clusters: Vec<(Vector3<f64>, usize)> = Vec::new();+ for normal in normals {+ let length = normal.norm();+ if length <= 1e-9 {+ continue;+ }+ let unit = normal / length;+ let mut matched = false;+ for c in clusters.iter_mut() {+ if c.0.dot(&unit).abs() > 0.95 {+ c.1 += 1;+ matched = true;+ break;+ }+ }+ if !matched {+ clusters.push((unit, 1));+ }+ }+ clusters.sort_by(|a, b| b.1.cmp(&a.1));+ let mut results = Vec::new();+ for (center, _) in clusters.into_iter().take(top) {+ let mut snapped = center;+ for w in world_axes() {+ let d = center.dot(&w);+ if d.abs() > 0.999 {+ snapped = if d > 0.0 { w } else { -w };+ break;+ }+ }+ results.push(snapped);+ }+ results+}++/// `_candidate_directions`: removal directions to try, most natural first.+pub fn candidate_directions(part: &Component) -> Vec<Vector3<f64>> {+ let mut candidates: Vec<Vector3<f64>> = Vec::new();+ if let Some(axis) = symmetry_axis(part) {+ candidates.push(axis);+ candidates.push(-axis);+ }+ for normal in normal_clusters(&part.contact_normals, 3) {+ for candidate in [normal, -normal] {+ if candidates.iter().all(|c| candidate.dot(c) < 0.999) {+ candidates.push(candidate);+ }+ }+ }+ for w in world_axes() {+ if candidates.iter().all(|c| w.dot(c) < 0.999) {+ candidates.push(w);+ }+ }+ candidates+}++/// `_axis_from_contacts`: bore axis from a cylindrical band of contact points.+pub fn axis_from_contacts(points: &[Vector3<f64>]) -> Option<Vector3<f64>> {+ if points.len() < 8 {+ return None;+ }+ let mean = crate::npy::mean_rows(points);+ let mut m = DMatrix::<f64>::zeros(points.len(), 3);+ for (i, p) in points.iter().enumerate() {+ let c = p - mean;+ m[(i, 0)] = c[0];+ m[(i, 1)] = c[1];+ m[(i, 2)] = c[2];+ }+ let (_s, vt) = crate::npy::svd_rows(&m)?;+ let row = |i: usize| Vector3::new(vt[(i, 0)], vt[(i, 1)], vt[(i, 2)]);+ let mut candidates = vec![row(0), row(2)];+ candidates.extend(world_axes());++ let centered: Vec<Vector3<f64>> = points.iter().map(|p| p - mean).collect();+ let mut best_axis: Option<Vector3<f64>> = None;+ let mut best_spread = f64::INFINITY;+ for candidate in candidates {+ let norm = candidate.norm();+ if norm <= 1e-9 {+ continue;+ }+ let axis = candidate / norm;+ let radii: Vec<f64> = centered+ .iter()+ .map(|c| (c - axis * c.dot(&axis)).norm())+ .collect();+ let mean_radius = crate::npy::mean(&radii);+ if mean_radius <= 1e-6 {+ continue;+ }+ let spread = crate::npy::std(&radii);+ if spread < best_spread {+ best_spread = spread;+ best_axis = Some(axis);+ }+ }+ let best_axis = best_axis?;+ if best_spread > 0.5 {+ return None;+ }+ for w in world_axes() {+ if best_axis.dot(&w) > 0.999 {+ return Some(w);+ }+ }+ Some(best_axis)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn round_py_banker() {+ assert_eq!(round_py(0.5, 0), 0.0);+ assert_eq!(round_py(1.5, 0), 2.0);+ assert_eq!(round_py(2.5, 0), 2.0);+ assert_eq!(round_py(0.125, 2), 0.12);+ assert_eq!(round_py(0.135, 2), 0.14);+ }++ #[test]+ fn separation_stacked_z() {+ // moving box z[10,20], static z[0,10] -> moving up +Z separates instantly (needed<=0)+ let bmin = Vector3::new(-5.0, -5.0, 10.0);+ let bmax = Vector3::new(5.0, 5.0, 20.0);+ let smin = Vector3::new(-50.0, -50.0, 0.0);+ let smax = Vector3::new(50.0, 50.0, 10.0);+ let up = Vector3::new(0.0, 0.0, 1.0);+ // +Z: needed = static_max.z - bbox_min.z = 10-10 = 0 -> travel 0+ assert_eq!(separation_distance(&bmin, &bmax, &smin, &smax, &up), 0.0);+ }+}diff --git a/crates/planner/src/greedy.rs b/crates/planner/src/greedy.rsnew file mode 100644index 0000000000..6109cf2f85--- /dev/null+++ b/crates/planner/src/greedy.rs@@ -0,0 +1,1526 @@+//! Greedy disassembly: per-part removal-motion search (linear / L / escape),+//! single-blocker rigid merge, subassembly group extraction, and flagging.++use crate::collide::*;+use crate::consts::*;+use crate::fasteners::{head_direction, is_fastener};+use crate::geom::*;+use crate::types::{Component, FastenerInfo, Motion, MotionSegment, PlannedComponent};+use nalgebra::Vector3;+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};++pub type Tiers = BTreeMap<String, i64>;++/// Evaluate greedy candidates (`order`, in priority order) in parallel and return+/// the first-in-priority that yields a plan — byte-identical to the sequential+/// "try each in order, take the first success" because each `eval` is a pure,+/// read-only sweep (no shared mutation). Each worker thread builds its OWN FCL+/// managers once (`map_init`) over the shared immutable BVHs — the managers are+/// `!Send` but never leave their thread. `world` = the active set (`remaining`);+/// `full` (only when `build_full`) = every part. The moving part is excluded+/// per-query by index, and all `contacts_at` consumers are order-independent+/// (max-depth / set-membership), so the worker-local index order is irrelevant.+/// How many leading candidates to try sequentially before fanning the rest out.+/// Since 2.1 made worker fan-out share ONE `CollisionWorld` (no per-candidate+/// rebuild), fan-out is nearly free, so 1 is best overall: a stuck pass on a large+/// assembly parallelizes immediately (BCU 47→36s, Packing Arm →10.5s) at the cost+/// of a little speculation on Seat Rail's cheap early-success iterations (+0.8s).+/// The value never affects output — only speculation-vs-latency. Override with+/// ASSEMBLER_SEQ_PROBE; ASSEMBLER_SEQUENTIAL forces a fully sequential parity oracle.+const SEQ_PROBE: usize = 1;++#[allow(clippy::type_complexity, clippy::too_many_arguments)]+fn par_first_success<F>(+ order: &[String],+ remaining: &HashMap<String, Component>,+ seq_world: &CollisionWorld,+ seq_full: Option<&CollisionWorld>,+ eval: F,+) -> Option<(usize, PlannedComponent)>+where+ F: Fn(+ &Component,+ &[&Component],+ &CollisionWorld,+ Option<&CollisionWorld>,+ ) -> Option<PlannedComponent>+ + Sync,+{+ use rayon::prelude::*;+ if order.is_empty() {+ return None;+ }+ let others_of =+ |id: &str| -> Vec<&Component> { remaining.values().filter(|c| c.node_id != id).collect() };+ // Fast path: probe the top candidate(s) sequentially. Greedy takes the+ // first-in-priority success, so an early hit ends here with no thread fan-out+ // and no speculative sweeps — the Seat Rail / BCU case. ASSEMBLER_SEQUENTIAL+ // forces every candidate down this path (parity oracle: parallel must equal it).+ let seq_probe = std::env::var("ASSEMBLER_SEQ_PROBE")+ .ok()+ .and_then(|v| v.parse().ok())+ .unwrap_or(SEQ_PROBE);+ let probe = if std::env::var("ASSEMBLER_SEQUENTIAL").is_ok() {+ order.len()+ } else {+ seq_probe.min(order.len())+ };+ for (i, id) in order.iter().enumerate().take(probe) {+ if let Some(p) = eval(&remaining[id], &others_of(id), seq_world, seq_full) {+ return Some((i, p));+ }+ }+ if order.len() <= probe {+ return None;+ }+ // The top candidate(s) are stuck — fan the remainder across cores against the+ // SAME shared managers (CollisionWorld is Sync; queries are read-only). No+ // per-candidate world rebuild — the win that lets a stuck pass parallelize for+ // free. `find_map_first` returns the lowest surviving index and cancels the+ // rest, so the result is still the first-in-priority success.+ (probe..order.len()).into_par_iter().find_map_first(|i| {+ let id = &order[i];+ eval(&remaining[id], &others_of(id), seq_world, seq_full).map(|p| (i, p))+ })+}++pub fn new_tiers() -> Tiers {+ let mut t = BTreeMap::new();+ for k in [+ "linear",+ "l",+ "escape",+ "group",+ "flagged",+ "forced",+ "unplanned",+ ] {+ t.insert(k.to_string(), 0);+ }+ t+}++fn bounds_over(parts: &[&Component]) -> (Vector3<f64>, Vector3<f64>) {+ let mut lo = Vector3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);+ let mut hi = Vector3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+ for p in parts {+ lo = lo.inf(&p.bbox_min);+ hi = hi.sup(&p.bbox_max);+ }+ (lo, hi)+}++fn neg(v: &Vector3<f64>) -> [f64; 3] {+ [-v[0], -v[1], -v[2]]+}+fn arr(v: &Vector3<f64>) -> [f64; 3] {+ [v[0], v[1], v[2]]+}++/// `_plan_removal`: tier 1 (straight line, least-entangling) then tier 2 ("L").+#[allow(clippy::too_many_arguments)]+pub fn plan_removal(+ part: &Component,+ remaining_map: &HashMap<String, Component>,+ others: &[&Component],+ world: &CollisionWorld,+ full_world: Option<&CollisionWorld>,+ _clearance: f64,+ path_samples: usize,+ fasteners: &HashMap<String, FastenerInfo>,+ tolerance: f64,+) -> Option<PlannedComponent> {+ if others.is_empty() {+ return None;+ }+ let (static_min, static_max) = bounds_over(others);+ let info = fasteners.get(&part.node_id);++ let directions: Vec<Vector3<f64>> = if is_fastener(part) && info.is_some() {+ let head = head_direction(part, info.unwrap(), Some(remaining_map));+ vec![head, -head]+ } else {+ candidate_directions(part)+ };++ // Tier 1: collect every clear direction.+ let mut clear: Vec<(usize, Vector3<f64>, f64)> = Vec::new();+ for (index, direction) in directions.iter().enumerate() {+ let travel = exit_travel(part, &static_min, &static_max, direction, None);+ if travel <= 0.0 {+ continue;+ }+ let separation = separation_distance(+ &part.bbox_min,+ &part.bbox_max,+ &static_min,+ &static_max,+ direction,+ );+ let exempt = self_exempt(mate_exempt(part, direction, fasteners), &[&part.node_id]);+ let last_touch = path_is_clear(+ part,+ world,+ direction,+ 0.0,+ travel,+ path_samples,+ tolerance,+ None,+ Some(exempt),+ Some(separation + 2.0 * MAX_SAMPLE_SPACING_MM),+ );+ if let Some(lt) = last_touch {+ clear.push((+ index,+ *direction,+ recorded_travel(part, direction, travel, lt),+ ));+ }+ }++ if !clear.is_empty() {+ let (_index, direction, recorded) = if clear.len() == 1 || full_world.is_none() {+ clear[0]+ } else {+ let full = full_world.unwrap();+ let samples_segment = (path_samples / 3).max(12);+ let mut extra: Exempt = HashMap::new();+ extra.insert(part.node_id.clone(), f64::INFINITY);+ *clear+ .iter()+ .min_by_key(|(index, direction, recorded)| {+ let blockers = path_blockers(+ part,+ full,+ &[(*direction, *recorded)],+ samples_segment,+ fasteners,+ Some(&extra),+ tolerance,+ );+ (blockers.len(), *index)+ })+ .unwrap()+ };+ let confidence = if part.is_proxy { "low" } else { "high" };+ return Some(PlannedComponent {+ node_id: part.node_id.clone(),+ motion: Motion::Linear {+ direction: neg(&direction),+ distance: recorded,+ },+ confidence: Some(confidence.to_string()),+ removal_direction: Some(arr(&direction)),+ blocked_by: Vec::new(),+ tier: Some("linear".to_string()),+ verified: false,+ group_id: None,+ });+ }++ // Tier 2: lift then slide ("L").+ let part_size = part.bbox_max - part.bbox_min;+ let hop = {+ let n = part_size.norm();+ if n == 0.0 {+ 1.0+ } else {+ n+ }+ };+ let samples_segment = (path_samples / 3).max(12);+ for first in world_axes() {+ let exempt = self_exempt(mate_exempt(part, &first, fasteners), &[&part.node_id]);+ if path_is_clear(+ part,+ world,+ &first,+ 0.0,+ hop,+ samples_segment,+ tolerance,+ None,+ Some(exempt),+ None,+ )+ .is_none()+ {+ continue;+ }+ let offset = first * hop;+ for second in world_axes() {+ if first.dot(&second).abs() > 0.99 {+ continue;+ }+ let travel = exit_travel(part, &static_min, &static_max, &second, Some(&offset));+ if travel <= 0.0 {+ continue;+ }+ let separation = separation_distance(+ &(part.bbox_min + offset),+ &(part.bbox_max + offset),+ &static_min,+ &static_max,+ &second,+ );+ let exempt2 = self_exempt(mate_exempt(part, &second, fasteners), &[&part.node_id]);+ let second_touch = path_is_clear(+ part,+ world,+ &second,+ 0.0,+ travel,+ samples_segment,+ tolerance,+ Some(&offset),+ Some(exempt2),+ Some(separation + 2.0 * MAX_SAMPLE_SPACING_MM),+ );+ if let Some(st) = second_touch {+ return Some(PlannedComponent {+ node_id: part.node_id.clone(),+ motion: Motion::L {+ segments: vec![+ MotionSegment {+ direction: neg(&second),+ distance: recorded_travel(part, &second, travel, st),+ },+ MotionSegment {+ direction: neg(&first),+ distance: round_py(hop, 3),+ },+ ],+ },+ confidence: Some("low".to_string()),+ removal_direction: Some(arr(&first)),+ blocked_by: Vec::new(),+ tier: Some("L".to_string()),+ verified: false,+ group_id: None,+ });+ }+ }+ }+ None+}++/// `_removal_segments_to_planned`: reverse a removal chain into an insertion motion.+fn removal_segments_to_planned(+ part: &Component,+ removal: &[(Vector3<f64>, f64)],+) -> PlannedComponent {+ let first_direction = removal[0].0;+ let motion = if removal.len() == 1 {+ let (direction, distance) = removal[0];+ Motion::Linear {+ direction: neg(&direction),+ distance: round_py(distance, 3),+ }+ } else {+ let segments = removal+ .iter()+ .rev()+ .map(|(direction, distance)| MotionSegment {+ direction: neg(direction),+ distance: round_py(*distance, 3),+ })+ .collect();+ Motion::L { segments }+ };+ PlannedComponent {+ node_id: part.node_id.clone(),+ motion,+ confidence: Some("low".to_string()),+ removal_direction: Some(arr(&first_direction)),+ blocked_by: Vec::new(),+ tier: Some("escape".to_string()),+ verified: false,+ group_id: None,+ }+}++/// `_plan_escape`: tier-3 BFS over axis-aligned hops.+pub fn plan_escape(+ part: &Component,+ others: &[&Component],+ world: &CollisionWorld,+ path_samples: usize,+ fasteners: &HashMap<String, FastenerInfo>,+ tolerance: f64,+) -> Option<PlannedComponent> {+ plan_escape_annotated(part, others, world, path_samples, fasteners, tolerance).0+}++/// `plan_escape` plus a FROZEN flag: true when the BFS never left the root node+/// (the part cannot exit or advance a `min_hop` in any direction). A frozen part+/// stays frozen until a neighbor capping one of its hops leaves — the assembly+/// bounds shrinking can't help (the obstruction is adjacent, not the exit+/// distance; and phase 1 re-checks the exit path every round before phase 2).+/// The flag is a free byproduct of the escape search, so the caller can cache it+/// with a neighbor-only invalidation and skip the frozen re-search across bounds+/// epochs — the bulk of the escape phase on dense assemblies.+pub fn plan_escape_annotated(+ part: &Component,+ others: &[&Component],+ world: &CollisionWorld,+ path_samples: usize,+ fasteners: &HashMap<String, FastenerInfo>,+ tolerance: f64,+) -> (Option<PlannedComponent>, bool) {+ if others.is_empty() {+ return (None, false);+ }+ let (static_min, static_max) = bounds_over(others);+ let part_diagonal = {+ let n = (part.bbox_max - part.bbox_min).norm();+ if n == 0.0 {+ 1.0+ } else {+ n+ }+ };+ let min_hop = (part_diagonal * MIN_HOP_FRACTION).max(2.0);+ let hop_cap = part_diagonal * 1.5;+ let samples_segment = (path_samples / 3).max(12);+ let directions = candidate_directions(part);++ let mut queue: std::collections::VecDeque<(Vector3<f64>, Vec<(Vector3<f64>, f64)>)> =+ std::collections::VecDeque::new();+ queue.push_back((Vector3::zeros(), Vec::new()));+ let mut visited: HashSet<(i64, i64, i64)> = HashSet::new();+ visited.insert((0, 0, 0));+ let mut expansions = 0;++ while let Some((offset, segments)) = queue.pop_front() {+ if expansions >= MAX_ESCAPE_EXPANSIONS {+ break;+ }+ expansions += 1;+ for direction in &directions {+ if let Some(last) = segments.last() {+ if direction.dot(&last.0).abs() > 0.99 {+ continue;+ }+ }+ let exempt = self_exempt(mate_exempt(part, direction, fasteners), &[&part.node_id]);++ let travel = exit_travel(part, &static_min, &static_max, direction, Some(&offset));+ let separation = separation_distance(+ &(part.bbox_min + offset),+ &(part.bbox_max + offset),+ &static_min,+ &static_max,+ direction,+ );+ if travel > 0.0 {+ let exit_touch = path_is_clear(+ part,+ world,+ direction,+ 0.0,+ travel,+ samples_segment,+ tolerance,+ Some(&offset),+ Some(exempt.clone()),+ Some(separation + 2.0 * MAX_SAMPLE_SPACING_MM),+ );+ if let Some(et) = exit_touch {+ let mut removal = segments.clone();+ removal.push((*direction, recorded_travel(part, direction, travel, et)));+ return (Some(removal_segments_to_planned(part, &removal)), false);+ }+ }++ if segments.len() + 1 >= MAX_ESCAPE_SEGMENTS {+ continue;+ }++ let free = free_travel(+ part,+ world,+ direction,+ &offset,+ hop_cap,+ samples_segment,+ Some(&exempt),+ tolerance,+ );+ if free < min_hop {+ continue;+ }+ let new_offset = offset + direction * free;+ let key = (+ (new_offset[0] / min_hop).round() as i64,+ (new_offset[1] / min_hop).round() as i64,+ (new_offset[2] / min_hop).round() as i64,+ );+ if visited.contains(&key) {+ continue;+ }+ visited.insert(key);+ let mut new_segments = segments.clone();+ new_segments.push((*direction, free));+ queue.push_back((new_offset, new_segments));+ }+ }+ // Frozen iff the search never enqueued a hop (only the root was visited).+ (None, visited.len() <= 1)+}++/// Per-direction escape blockers: for each candidate direction with positive+/// exit travel, the exact set of parts blocking that sweep. The union form+/// (`escape_blockers`, the Python-parity behavior) over-counts — a part whose+/// BEST direction is blocked by exactly one neighbor is a valid single-blocker+/// merge even when other directions add more blockers to the union. The flag+/// autopsy on the real assemblies showed this exact pattern behind most+/// manually-authored parts (panel pairs, servo/mount clusters).+pub fn escape_blockers_by_direction(+ part: &Component,+ remaining_map: &HashMap<String, Component>,+ others: &[&Component],+ world: &CollisionWorld,+ fasteners: &HashMap<String, FastenerInfo>,+ tolerance: f64,+ path_samples: usize,+) -> Vec<(Vector3<f64>, f64, BTreeSet<String>)> {+ if others.is_empty() {+ return Vec::new();+ }+ let (static_min, static_max) = bounds_over(others);+ let samples_segment = (path_samples / 3).max(12);+ let info = fasteners.get(&part.node_id);+ let directions: Vec<Vector3<f64>> = if is_fastener(part) && info.is_some() {+ let head = head_direction(part, info.unwrap(), Some(remaining_map));+ vec![head, -head]+ } else {+ candidate_directions(part)+ };+ let mut extra: Exempt = HashMap::new();+ extra.insert(part.node_id.clone(), f64::INFINITY);+ let mut out = Vec::new();+ for direction in directions {+ let travel = exit_travel(part, &static_min, &static_max, &direction, None);+ if travel <= 0.0 {+ continue;+ }+ let mut blockers = path_blockers(+ part,+ world,+ &[(direction, travel)],+ samples_segment,+ fasteners,+ Some(&extra),+ tolerance,+ );+ blockers.remove(&part.node_id);+ out.push((direction, travel, blockers));+ }+ out+}++/// `_escape_blockers`: union of sweep blockers over the part's candidate directions.+pub fn escape_blockers(+ part: &Component,+ remaining_map: &HashMap<String, Component>,+ others: &[&Component],+ world: &CollisionWorld,+ fasteners: &HashMap<String, FastenerInfo>,+ tolerance: f64,+ path_samples: usize,+) -> Vec<String> {+ if others.is_empty() {+ return Vec::new();+ }+ let (static_min, static_max) = bounds_over(others);+ let samples_segment = (path_samples / 3).max(12);+ let info = fasteners.get(&part.node_id);+ let directions: Vec<Vector3<f64>> = if is_fastener(part) && info.is_some() {+ let head = head_direction(part, info.unwrap(), Some(remaining_map));+ vec![head, -head]+ } else {+ candidate_directions(part)+ };+ let mut extra: Exempt = HashMap::new();+ extra.insert(part.node_id.clone(), f64::INFINITY);+ let mut blockers: BTreeSet<String> = BTreeSet::new();+ for direction in directions {+ let travel = exit_travel(part, &static_min, &static_max, &direction, None);+ if travel <= 0.0 {+ continue;+ }+ blockers.extend(path_blockers(+ part,+ world,+ &[(direction, travel)],+ samples_segment,+ fasteners,+ Some(&extra),+ tolerance,+ ));+ }+ blockers.remove(&part.node_id);+ blockers+ .into_iter()+ .take(crate::consts::MAX_REPORTED_BLOCKERS)+ .collect()+}++/// `_blockers`: parts whose bounding boxes overlap this part's (rough set).+fn bbox_blockers(part: &Component, remaining: &HashMap<String, Component>) -> Vec<String> {+ let mut out = Vec::new();+ for other in remaining.values() {+ if other.node_id == part.node_id {+ continue;+ }+ let overlaps = (0..3).all(|i| part.bbox_min[i] <= other.bbox_max[i])+ && (0..3).all(|i| other.bbox_min[i] <= part.bbox_max[i]);+ if overlaps {+ out.push(other.node_id.clone());+ }+ }+ out.truncate(crate::consts::MAX_REPORTED_BLOCKERS);+ out+}++/// `_group_exempt`: merged threaded-mate + sandwich allowances for a group.+fn group_exempt(+ members: &[&Component],+ direction: &Vector3<f64>,+ fasteners: &HashMap<String, FastenerInfo>,+ member_ids: &HashSet<String>,+) -> Option<Exempt> {+ let mut merged: Exempt = HashMap::new();+ let mut add = |k: &String, v: f64| {+ if member_ids.contains(k) {+ return;+ }+ let e = merged.entry(k.clone()).or_insert(f64::MIN);+ if v > *e {+ *e = v;+ }+ };+ for member in members {+ if let Some(exempt) = mate_exempt(member, direction, fasteners) {+ for (k, v) in &exempt {+ add(k, *v);+ }+ }+ if let Some(seated) = seated_exempt(member, direction) {+ for (k, v) in &seated {+ add(k, *v);+ }+ }+ }+ if merged.is_empty() {+ None+ } else {+ Some(merged)+ }+}++fn bbox_volume(part: &Component) -> f64 {+ let e = part.bbox_max - part.bbox_min;+ (e[0] * e[1] * e[2]).abs()+}++/// `_plan_group_removal`: find a connected subassembly that removes as one unit.+#[allow(clippy::too_many_arguments)]+pub fn plan_group_removal(+ remaining: &HashMap<String, Component>,+ world: &mut CollisionWorld,+ path_samples: usize,+ fasteners: &HashMap<String, FastenerInfo>,+ combined_cache: &mut HashMap<BTreeSet<String>, Component>,+ tolerance: f64,+ deep_bitten: &HashSet<String>,+) -> Option<(Vec<String>, Component, PlannedComponent)> {+ let parts: Vec<&Component> = remaining.values().collect();+ if parts.len() <= 2 {+ return None;+ }++ // Proximity adjacency (inflated bboxes).+ let mut adjacency: HashMap<String, HashSet<String>> = parts+ .iter()+ .map(|p| (p.node_id.clone(), HashSet::new()))+ .collect();+ for i in 0..parts.len() {+ for j in (i + 1)..parts.len() {+ let a = parts[i];+ let b = parts[j];+ let close = (0..3).all(|k| a.bbox_min[k] - GROUP_PROXIMITY_MM <= b.bbox_max[k])+ && (0..3).all(|k| b.bbox_min[k] - GROUP_PROXIMITY_MM <= a.bbox_max[k]);+ if close {+ adjacency+ .get_mut(&a.node_id)+ .unwrap()+ .insert(b.node_id.clone());+ adjacency+ .get_mut(&b.node_id)+ .unwrap()+ .insert(a.node_id.clone());+ }+ }+ }++ let diagonal = |p: &Component| (p.bbox_max - p.bbox_min).norm();+ let samples_segment = (path_samples / 3).max(12);+ let mut tests = 0usize;++ let mut seeds: Vec<&Component> = parts.clone();+ seeds.sort_by(|a, b| {+ b.bbox_max[2]+ .partial_cmp(&a.bbox_max[2])+ .unwrap()+ .then(a.node_id.cmp(&b.node_id))+ });++ for seed in seeds {+ if tests >= MAX_GROUP_TESTS {+ break;+ }+ let mut members: Vec<Component> = vec![seed.clone()];+ let mut member_ids: HashSet<String> = HashSet::from([seed.node_id.clone()]);++ while members.len() < MAX_GROUP_SIZE && tests < MAX_GROUP_TESTS {+ let mut neighbor_ids: Vec<String> = Vec::new();+ for member in &members {+ if let Some(adj) = adjacency.get(&member.node_id) {+ for nid in adj {+ if !member_ids.contains(nid) && remaining.contains_key(nid) {+ neighbor_ids.push(nid.clone());+ }+ }+ }+ }+ neighbor_ids.sort();+ neighbor_ids.dedup();+ if neighbor_ids.is_empty() {+ break;+ }+ neighbor_ids.sort_by(|a, b| {+ let pa = &remaining[a];+ let pb = &remaining[b];+ let ka = (deep_bitten.contains(a) as i32, diagonal(pa), a.clone());+ let kb = (deep_bitten.contains(b) as i32, diagonal(pb), b.clone());+ ka.0.cmp(&kb.0)+ .then(ka.1.partial_cmp(&kb.1).unwrap())+ .then(ka.2.cmp(&kb.2))+ });+ let chosen = remaining[&neighbor_ids[0]].clone();+ member_ids.insert(chosen.node_id.clone());+ members.push(chosen);+ if members.len() >= remaining.len() {+ break;+ }++ let others: Vec<&Component> = parts+ .iter()+ .filter(|p| !member_ids.contains(&p.node_id))+ .copied()+ .collect();+ let (static_min, static_max) = bounds_over(&others);++ let cache_key: BTreeSet<String> = member_ids.iter().cloned().collect();+ let combined = combined_cache.entry(cache_key).or_insert_with(|| {+ let member_refs: Vec<&crate::types::Mesh> =+ members.iter().map(|m| &m.mesh).collect();+ let combined_mesh = crate::types::Mesh::concatenate(&member_refs);+ let rep = members+ .iter()+ .max_by(|a, b| bbox_volume(a).partial_cmp(&bbox_volume(b)).unwrap())+ .unwrap();+ let mut lo = members[0].bbox_min;+ let mut hi = members[0].bbox_max;+ for m in &members {+ lo = lo.inf(&m.bbox_min);+ hi = hi.sup(&m.bbox_max);+ }+ let name = members+ .iter()+ .map(|m| m.name.clone())+ .collect::<Vec<_>>()+ .join(" + ");+ let mut c = Component::new(+ rep.node_id.clone(),+ name,+ combined_mesh,+ lo,+ hi,+ members.iter().any(|m| m.is_proxy),+ );+ c.cached_volume = Some(members.iter().map(part_volume).sum());+ c+ });+ let combined = combined.clone();++ // Candidate directions from member axes, then world axes.+ let mut directions: Vec<Vector3<f64>> = Vec::new();+ for member in &members {+ let mut axes: Vec<Vector3<f64>> = Vec::new();+ if let Some(mi) = fasteners.get(&member.node_id) {+ axes.push(mi.axis);+ }+ if let Some(a) = symmetry_axis(member) {+ axes.push(a);+ }+ for base in axes {+ for cand in [base, -base] {+ if directions.iter().all(|d| cand.dot(d) < 0.999) {+ directions.push(cand);+ }+ }+ }+ }+ for w in world_axes() {+ if directions.iter().all(|d| w.dot(d) < 0.999) {+ directions.push(w);+ }+ }++ let member_id_list: Vec<&str> = member_ids.iter().map(|s| s.as_str()).collect();+ // Test the group against the OTHERS by hiding its members in the+ // persistent world, instead of rebuilding a fresh manager over ~n+ // parts every growth step. Restored before returning either way.+ for id in &member_id_list {+ world.set_active(id, false);+ }+ let mut winner: Option<(Vector3<f64>, f64, f64)> = None;+ for direction in &directions {+ tests += 1;+ let travel = exit_travel(&combined, &static_min, &static_max, direction, None);+ if travel <= 0.0 {+ if tests >= MAX_GROUP_TESTS {+ break;+ }+ continue;+ }+ let separation = separation_distance(+ &combined.bbox_min,+ &combined.bbox_max,+ &static_min,+ &static_max,+ direction,+ );+ let exempt = self_exempt(+ group_exempt(+ &members.iter().collect::<Vec<_>>(),+ direction,+ fasteners,+ &member_ids,+ ),+ &member_id_list,+ );+ let touch = path_is_clear(+ &combined,+ &world,+ direction,+ 0.0,+ travel,+ samples_segment,+ tolerance,+ None,+ Some(exempt),+ Some(separation + 2.0 * MAX_SAMPLE_SPACING_MM),+ );+ if let Some(t) = touch {+ winner = Some((*direction, travel, t));+ break;+ }+ if tests >= MAX_GROUP_TESTS {+ break;+ }+ }+ for id in &member_id_list {+ world.set_active(id, true);+ }+ if let Some((direction, travel, touch)) = winner {+ let entry = PlannedComponent {+ node_id: combined.node_id.clone(),+ motion: Motion::Linear {+ direction: neg(&direction),+ distance: recorded_travel(&combined, &direction, travel, touch),+ },+ confidence: Some("low".to_string()),+ removal_direction: Some(arr(&direction)),+ blocked_by: Vec::new(),+ tier: Some("group".to_string()),+ verified: false,+ group_id: None,+ };+ let ordered: Vec<String> = members.iter().map(|m| m.node_id.clone()).collect();+ return Some((ordered, combined, entry));+ }+ }+ }+ None+}++/// `removal_priority`: fasteners first, then smallest/peripheral (ascending).+fn removal_priority(+ remaining: &HashMap<String, Component>,+ fasteners: &HashMap<String, FastenerInfo>,+ centroid: &Vector3<f64>,+ diagonal: f64,+) -> Vec<String> {+ // Precompute each part's sort key once (the comparator would otherwise+ // recompute structural_key — hypot/round/part_volume — O(n log n) times per+ // call). Fasteners first (0), then negate each structural-key component+ // (Python: `0 if fastener else 1`, then `tuple(-c for c in key)`).+ let mut keyed: Vec<(i32, f64, f64, &String)> = remaining+ .keys()+ .map(|id| {+ let (v, b) = structural_key(&remaining[id], centroid, diagonal);+ let f = if fasteners.contains_key(id) { 0 } else { 1 };+ (f, -v, -b, id)+ })+ .collect();+ keyed.sort_by(|a, b| {+ a.0.cmp(&b.0)+ .then(a.1.partial_cmp(&b.1).unwrap())+ .then(a.2.partial_cmp(&b.2).unwrap())+ .then(a.3.cmp(b.3))+ });+ keyed.into_iter().map(|(_, _, _, id)| id.clone()).collect()+}++/// Conservative "who could unblock this part" set for the blocked memo: every+/// remaining part whose bbox intersects any of the part's possible sweep+/// regions — the bbox inflated by the search's wander reach, extruded along+/// every direction the search can try (candidate directions, the fastener axis,+/// world axes) out to the assembly diagonal (≥ any exit travel). Fastener+/// mates/sliders are added unconditionally: exemptions and head-direction+/// heuristics read the mate set, so a mate's removal can change the verdict+/// without ever being geometrically in the way.+fn blocked_watch_set(+ part: &Component,+ remaining: &HashMap<String, Component>,+ fasteners: &HashMap<String, FastenerInfo>,+ reach: f64,+ travel: f64,+) -> HashSet<String> {+ let mut dirs = candidate_directions(part);+ if let Some(info) = fasteners.get(&part.node_id) {+ dirs.push(info.axis);+ dirs.push(-info.axis);+ }+ for w in world_axes() {+ if dirs.iter().all(|c| c.dot(&w) < 0.999) {+ dirs.push(w);+ }+ }+ let bmin = part.bbox_min.add_scalar(-reach);+ let bmax = part.bbox_max.add_scalar(reach);+ let mut watch: HashSet<String> = HashSet::new();+ for q in remaining.values() {+ if q.node_id == part.node_id {+ continue;+ }+ let hit = dirs.iter().any(|d| {+ let end_min = bmin + d * travel;+ let end_max = bmax + d * travel;+ let smin = bmin.inf(&end_min);+ let smax = bmax.sup(&end_max);+ (0..3).all(|k| smin[k] <= q.bbox_max[k] && q.bbox_min[k] <= smax[k])+ });+ if hit {+ watch.insert(q.node_id.clone());+ }+ }+ if let Some(info) = fasteners.get(&part.node_id) {+ watch.extend(info.mates.keys().cloned());+ watch.extend(info.sliding.keys().cloned());+ }+ for (fid, info) in fasteners {+ if info.mates.contains_key(&part.node_id) || info.sliding.contains_key(&part.node_id) {+ watch.insert(fid.clone());+ }+ }+ watch+}++/// Drop the removed part's own memo and every memo watching it.+fn blocked_memo_invalidate(memo: &mut HashMap<String, HashSet<String>>, removed: &str) {+ memo.remove(removed);+ memo.retain(|_, watch| !watch.contains(removed));+}++/// `_greedy_disassembly`: the full greedy loop over world-space parts.+#[allow(clippy::too_many_arguments)]+pub fn greedy_disassembly(+ parts: &[Component],+ _clearance: f64,+ path_samples: usize,+ tolerance: f64,+ fasteners: &HashMap<String, FastenerInfo>,+ deep_bitten: &HashSet<String>,+ sandwiched: &HashSet<String>,+ protected: Option<&HashSet<String>>,+ group_units: &mut HashMap<String, (Component, Vec<String>)>,+ late_merges: &mut HashMap<String, String>,+ warnings: &mut Vec<String>,+) -> (Vec<PlannedComponent>, Vec<String>, Tiers) {+ let mut remaining: HashMap<String, Component> = parts+ .iter()+ .map(|p| (p.node_id.clone(), p.clone()))+ .collect();++ let centroid = assembly_centroid(parts);+ let (amin, amax) = {+ let refs: Vec<&Component> = parts.iter().collect();+ bounds_over(&refs)+ };+ let assembly_diagonal = {+ let n = (amax - amin).norm();+ if n == 0.0 {+ 1.0+ } else {+ n+ }+ };++ // Build every part's BVH up front, in parallel — `bvh()` is a thread-safe+ // OnceLock, and the two world builds below (plus every per-thread world) hit+ // them serially otherwise. Biggest on large assemblies (431 BVHs on BCU).+ {+ use rayon::prelude::*;+ parts.par_iter().for_each(|p| {+ p.bvh();+ });+ }++ // Persistent broadphase managers reused across the whole greedy loop+ // (Python keeps one). `world` mirrors `remaining` (parts set inactive on+ // removal); `full_world` holds every part always. The moving part is+ // excluded per-query by index, so no per-sweep rebuild or unregister.+ let mut world = CollisionWorld::from_components(parts);+ let full_world = CollisionWorld::from_components(parts);++ // The presumptive base: the largest-volume part (mirrors pipeline2's base+ // pick, which is connectivity-first with volume as the dominant tiebreak).+ // Phase-3 single-blocker merges must never fold a part INTO the base —+ // a knob merged into the frame simply vanishes from the instructions,+ // and any real removal motion it might have had (found once neighbors+ // clear) is lost. Stuck parts against the base get flagged instead,+ // preserving their install step. Merges into movable hosts (nut->bolt,+ // servo->mount, panel pairs) are unaffected.+ let base_candidate: Option<String> = parts+ .iter()+ .max_by(|a, b| {+ part_volume(a)+ .partial_cmp(&part_volume(b))+ .unwrap_or(std::cmp::Ordering::Equal)+ .then_with(|| a.node_id.cmp(&b.node_id))+ })+ .map(|c| c.node_id.clone());++ let mut removal_order: Vec<PlannedComponent> = Vec::new();+ let mut group_mesh_cache: HashMap<BTreeSet<String>, Component> = HashMap::new();+ let mut stuck_blockers_cache: HashMap<String, Vec<String>> = HashMap::new();+ let mut tiers = new_tiers();++ let base_entry = |id: &str| PlannedComponent {+ node_id: id.to_string(),+ motion: Motion::None,+ confidence: Some("high".to_string()),+ removal_direction: None,+ blocked_by: Vec::new(),+ tier: Some("base".to_string()),+ verified: false,+ group_id: None,+ };++ let _timing = std::env::var("ASSEMBLER_TIMING").is_ok();+ let (mut t_p1, mut t_p2, mut t_p3, mut t_p4, mut t_p5) = (0.0f64, 0.0, 0.0, 0.0, 0.0);++ // Wilson-style blocked memo (the NDBG insight as exact memoization): a part+ // that failed its removal search stays failed until something that could+ // possibly unblock it leaves the world — a watched neighbor is removed, or+ // the assembly bounds shrink (which shortens exit travels and can clear a+ // path all by itself). Skipping re-tests of still-blocked parts turns the+ // O(rounds x remaining) re-search into near O(remaining) without changing a+ // single verdict. Keyed per phase: a phase-1 failure says nothing about+ // escape, so each memoizes independently (escape's wander reach is larger).+ let mut blocked_p1: HashMap<String, HashSet<String>> = HashMap::new();+ let mut blocked_p2: HashMap<String, HashSet<String>> = HashMap::new();+ // Frozen parts (immobile from their seat). Unlike blocked_p2 this is NOT+ // cleared on a bounds change — a frozen part is held by an adjacent+ // neighbor, not by the exit distance, so only a watched neighbor's removal+ // can free it. Populated as a free byproduct of the escape search.+ let mut frozen: HashMap<String, HashSet<String>> = HashMap::new();+ let mut bounds_epoch: Option<(Vector3<f64>, Vector3<f64>)> = None;+ let (mut memo_skips_p1, mut memo_skips_p2) = (0usize, 0usize);+ let watch_margin = tolerance + 2.0 * MAX_SAMPLE_SPACING_MM;++ let mut progressed = true;+ while !remaining.is_empty() && progressed {+ progressed = false;+ let _ts = std::time::Instant::now();++ // Bounds shrink when an extremal part leaves; exit_travel shrinks with+ // them, which can clear a previously-blocked path without any watched+ // part being removed — the memo cannot survive that.+ {+ let refs: Vec<&Component> = remaining.values().collect();+ let bounds = bounds_over(&refs);+ let changed = bounds_epoch+ .map(|(lo, hi)| lo != bounds.0 || hi != bounds.1)+ .unwrap_or(true);+ if changed {+ blocked_p1.clear();+ blocked_p2.clear();+ bounds_epoch = Some(bounds);+ }+ }++ // Phase 1: straight-line / L removal. Candidates are evaluated in+ // parallel; the first-in-priority success is taken (identical to the+ // sequential break-on-first — each eval is a pure read-only sweep).+ // Memoized-blocked parts are skipped: their verdict provably cannot+ // have changed, so the filtered first-success is the same first-success.+ let order = removal_priority(&remaining, fasteners, ¢roid, assembly_diagonal);+ if remaining.len() == 1 {+ let id = order.into_iter().next().unwrap();+ remaining.remove(&id);+ world.set_active(&id, false);+ removal_order.push(base_entry(&id));+ progressed = true;+ } else {+ memo_skips_p1 += order.iter().filter(|id| blocked_p1.contains_key(*id)).count();+ let tryable: Vec<String> = order+ .into_iter()+ .filter(|id| !blocked_p1.contains_key(id))+ .collect();+ let result = par_first_success(+ &tryable,+ &remaining,+ &world,+ Some(&full_world),+ |part, others, w, fw| {+ plan_removal(+ part,+ &remaining,+ others,+ w,+ fw,+ _clearance,+ path_samples,+ fasteners,+ tolerance,+ )+ },+ );+ // Everything before the first success (or everything, on a full+ // fail) was evaluated and failed — memoize those verdicts.+ let failed_upto = result.as_ref().map(|(i, _)| *i).unwrap_or(tryable.len());+ for id in &tryable[..failed_upto] {+ let part = &remaining[id];+ let reach = (part.bbox_max - part.bbox_min).norm().max(1.0) + watch_margin;+ blocked_p1.insert(+ id.clone(),+ blocked_watch_set(part, &remaining, fasteners, reach, assembly_diagonal),+ );+ }+ if let Some((i, p)) = result {+ let id = tryable[i].clone();+ let key = if p.tier.as_deref() == Some("linear") {+ "linear"+ } else {+ "l"+ };+ *tiers.get_mut(key).unwrap() += 1;+ removal_order.push(p);+ remaining.remove(&id);+ world.set_active(&id, false);+ blocked_memo_invalidate(&mut blocked_p1, &id);+ blocked_memo_invalidate(&mut blocked_p2, &id);+ blocked_memo_invalidate(&mut frozen, &id);+ progressed = true;+ }+ }++ t_p1 += _ts.elapsed().as_secs_f64();+ let _ts = std::time::Instant::now();+ // Phase 2: tier-3 escape (parallel candidate evaluation, first success).+ if !progressed && remaining.len() > 1 {+ let order = removal_priority(&remaining, fasteners, ¢roid, assembly_diagonal);+ memo_skips_p2 += order+ .iter()+ .filter(|id| blocked_p2.contains_key(*id) || frozen.contains_key(*id))+ .count();+ // Skip both the (bounds-sensitive) escape memo and the+ // (neighbor-sensitive) frozen cache. A frozen part never wins the+ // first-success, so excluding it can't change which part wins.+ let tryable: Vec<String> = order+ .into_iter()+ .filter(|id| !blocked_p2.contains_key(id) && !frozen.contains_key(id))+ .collect();+ // Fan the candidates across cores and take the first-in-priority+ // escape, exactly like the other phases (find_map_first cancels the+ // rest once the lowest surviving index is found). The frozen flag+ // rides the escape's own root node, so each worker records its+ // verdict into a per-candidate atomic bit — a free byproduct,+ // collected lock-free with no separate immobility pass.+ let frozen_flags: Vec<std::sync::atomic::AtomicBool> =+ (0..tryable.len()).map(|_| std::sync::atomic::AtomicBool::new(false)).collect();+ let winner = {+ use rayon::prelude::*;+ use std::sync::atomic::Ordering::Relaxed;+ (0..tryable.len()).into_par_iter().find_map_first(|i| {+ let id = &tryable[i];+ let others: Vec<&Component> =+ remaining.values().filter(|c| &c.node_id != id).collect();+ let (res, is_frozen) = plan_escape_annotated(+ &remaining[id],+ &others,+ &world,+ path_samples,+ fasteners,+ tolerance,+ );+ if is_frozen {+ frozen_flags[i].store(true, Relaxed);+ }+ res.map(|p| (i, p))+ })+ };+ let is_frozen_at =+ |i: usize| frozen_flags[i].load(std::sync::atomic::Ordering::Relaxed);+ let failed_upto = winner.as_ref().map(|(i, _)| *i).unwrap_or(tryable.len());+ // Cache every frozen verdict found (persist across bounds epochs);+ // memoize the non-frozen failures below the winner into the+ // bounds-sensitive escape memo, as before.+ for (i, id) in tryable.iter().enumerate() {+ if !is_frozen_at(i) {+ continue;+ }+ let part = &remaining[id];+ let hop_cap = (part.bbox_max - part.bbox_min).norm().max(1.0) * 1.5;+ frozen.insert(+ id.clone(),+ blocked_watch_set(part, &remaining, fasteners, watch_margin, hop_cap),+ );+ }+ for (i, id) in tryable[..failed_upto].iter().enumerate() {+ if is_frozen_at(i) {+ continue;+ }+ let part = &remaining[id];+ // Escape wanders up to MAX_ESCAPE_SEGMENTS hops of 1.5x the part+ // diagonal before its exit sweep — the watch region reaches that+ // much further than phase 1's single hop.+ let reach = (MAX_ESCAPE_SEGMENTS as f64)+ * 1.5+ * (part.bbox_max - part.bbox_min).norm().max(1.0)+ + watch_margin;+ blocked_p2.insert(+ id.clone(),+ blocked_watch_set(part, &remaining, fasteners, reach, assembly_diagonal),+ );+ }+ if let Some((i, p)) = winner {+ let id = tryable[i].clone();+ *tiers.get_mut("escape").unwrap() += 1;+ removal_order.push(p);+ remaining.remove(&id);+ world.set_active(&id, false);+ blocked_memo_invalidate(&mut blocked_p1, &id);+ blocked_memo_invalidate(&mut blocked_p2, &id);+ blocked_memo_invalidate(&mut frozen, &id);+ progressed = true;+ }+ }++ t_p2 += _ts.elapsed().as_secs_f64();+ let _ts = std::time::Instant::now();+ // Phase 3: single-blocker rigid merge.+ if !progressed && remaining.len() > 1 {+ let order = removal_priority(&remaining, fasteners, ¢roid, assembly_diagonal);+ for id in order.into_iter().take(8) {+ if sandwiched.contains(&id) {+ continue;+ }+ if protected.map(|p| p.contains(&id)).unwrap_or(false) {+ continue;+ }+ // The presumptive base neither merges into anything nor+ // absorbs stuck parts (see base_candidate above) — otherwise+ // the whole frame collapses into one step.+ if base_candidate.as_deref() == Some(id.as_str()) {+ continue;+ }+ let cached_ok = stuck_blockers_cache+ .get(&id)+ .map(|c| c.iter().all(|b| remaining.contains_key(b)))+ .unwrap_or(false);+ let blockers = if cached_ok {+ stuck_blockers_cache[&id].clone()+ } else {+ // The part's BEST (least-blocked) escape direction decides the+ // merge: a part whose best direction has exactly one blocker+ // merges with it, even when other directions add more blockers+ // to the union (panel pairs, servo/mount and nut/bolt clusters).+ let b: Vec<String> = {+ let part = &remaining[&id];+ let others: Vec<&Component> =+ remaining.values().filter(|c| c.node_id != id).collect();+ escape_blockers_by_direction(+ part,+ &remaining,+ &others,+ &world,+ fasteners,+ tolerance,+ path_samples,+ )+ .into_iter()+ .filter(|(_, _, b)| !b.is_empty())+ .min_by_key(|(_, _, b)| b.len())+ .map(|(_, _, b)| b.into_iter().take(8).collect())+ .unwrap_or_default()+ };+ stuck_blockers_cache.insert(id.clone(), b.clone());+ b+ };+ if blockers.len() != 1 {+ continue;+ }+ let host_id = blockers[0].clone();+ if !remaining.contains_key(&host_id) || sandwiched.contains(&host_id) {+ continue;+ }+ if base_candidate.as_deref() == Some(host_id.as_str()) {+ continue;+ }+ if protected.map(|p| p.contains(&host_id)).unwrap_or(false) {+ continue;+ }+ let part = remaining[&id].clone();+ let host = remaining[&host_id].clone();+ let combined_mesh = crate::types::Mesh::concatenate(&[&host.mesh, &part.mesh]);+ let mut merged_allowance = part.seated_allowance.clone();+ for (k, v) in &host.seated_allowance {+ merged_allowance.insert(k.clone(), *v);+ }+ let mut merged_axes = part.seated_allowance_axes.clone();+ for (k, v) in &host.seated_allowance_axes {+ merged_axes.insert(k.clone(), *v);+ }+ merged_allowance.remove(&host.node_id);+ merged_allowance.remove(&part.node_id);+ merged_axes.remove(&host.node_id);+ merged_axes.remove(&part.node_id);+ let mut combined = Component::new(+ host.node_id.clone(),+ host.name.clone(),+ combined_mesh,+ host.bbox_min.inf(&part.bbox_min),+ host.bbox_max.sup(&part.bbox_max),+ host.is_proxy || part.is_proxy,+ );+ combined.cached_volume = Some(part_volume(&host) + part_volume(&part));+ combined.seated_allowance = merged_allowance;+ combined.seated_allowance_axes = merged_axes;+ warnings.push(format!(+ "'{}' cannot separate from '{}'; planned as one rigid unit",+ if part.name.is_empty() {+ &part.node_id+ } else {+ &part.name+ },+ if host.name.is_empty() {+ &host_id+ } else {+ &host.name+ },+ ));+ world.set_active(&id, false);+ world.set_active(&host_id, false);+ remaining.remove(&id);+ world.add(&host_id, &combined);+ remaining.insert(host_id.clone(), combined);+ late_merges.insert(id.clone(), host_id.clone());+ // The member left and the host's geometry changed — both must+ // fall out of the blocked memos (the grown host can only add+ // blockage, but its own cached verdict is stale).+ for memo in [&mut blocked_p1, &mut blocked_p2, &mut frozen] {+ blocked_memo_invalidate(memo, &id);+ blocked_memo_invalidate(memo, &host_id);+ }+ progressed = true;+ break;+ }+ if progressed {+ continue;+ }+ }++ t_p3 += _ts.elapsed().as_secs_f64();+ let _ts = std::time::Instant::now();+ // Phase 4: subassembly extraction.+ if !progressed && remaining.len() > 2 {+ let mut group = plan_group_removal(+ &remaining,+ &mut world,+ path_samples,+ fasteners,+ &mut group_mesh_cache,+ tolerance,+ deep_bitten,+ );+ if let Some((members, _, _)) = &group {+ if let Some(p) = protected {+ if members.iter().any(|m| p.contains(m)) {+ group = None;+ }+ }+ }+ if let Some((members, combined, entry)) = group {+ for member_id in &members {+ remaining.remove(member_id);+ world.set_active(member_id, false);+ for memo in [&mut blocked_p1, &mut blocked_p2, &mut frozen] {+ blocked_memo_invalidate(memo, member_id);+ }+ }+ let rep = entry.node_id.clone();+ removal_order.push(entry);+ group_units.insert(rep, (combined, members));+ *tiers.get_mut("group").unwrap() += 1;+ progressed = true;+ continue;+ }+ }++ t_p4 += _ts.elapsed().as_secs_f64();+ let _ts = std::time::Instant::now();+ // Phase 5: flag.+ if !progressed && remaining.len() > 1 {+ let id =+ removal_priority(&remaining, fasteners, ¢roid, assembly_diagonal)[0].clone();+ let blocked_by = {+ let part = &remaining[&id];+ let others: Vec<&Component> =+ remaining.values().filter(|c| c.node_id != id).collect();+ let eb = escape_blockers(+ part,+ &remaining,+ &others,+ &world,+ fasteners,+ tolerance,+ path_samples,+ );+ if eb.is_empty() {+ bbox_blockers(part, &remaining)+ } else {+ eb+ }+ };+ let name = {+ let part = &remaining[&id];+ if part.name.is_empty() {+ id.clone()+ } else {+ part.name.clone()+ }+ };+ warnings.push(format!(+ "'{name}' has no collision-free escape; flagged for review — it fades in during playback"+ ));+ // ASSEMBLER_EXPLAIN=1: autopsy every flag — per candidate direction,+ // how far it could exit and exactly who blocks it. Quality work is+ // aimed at this output ("minimize manual intervention"), so the+ // failure reasons must be inspectable, not inferred.+ if std::env::var("ASSEMBLER_EXPLAIN").is_ok() {+ let part = &remaining[&id];+ let others: Vec<&Component> =+ remaining.values().filter(|c| c.node_id != id).collect();+ let (smin, smax) = bounds_over(&others);+ let info = fasteners.get(&id);+ let dirs = if is_fastener(part) && info.is_some() {+ let h = head_direction(part, info.unwrap(), Some(&remaining));+ vec![h, -h]+ } else {+ candidate_directions(part)+ };+ eprintln!(+ "EXPLAIN flag {name} ({id}) remaining={} fastener={} dirs={}",+ remaining.len(),+ info.is_some(),+ dirs.len()+ );+ let mut extra: Exempt = HashMap::new();+ extra.insert(id.clone(), f64::INFINITY);+ for d in &dirs {+ let travel = exit_travel(part, &smin, &smax, d, None);+ if travel <= 0.0 {+ eprintln!(+ " dir=[{:+.2},{:+.2},{:+.2}] travel=0 (inside bounds)",+ d[0], d[1], d[2]+ );+ continue;+ }+ let blockers = path_blockers(+ part,+ &world,+ &[(*d, travel)],+ (path_samples / 3).max(12),+ fasteners,+ Some(&extra),+ tolerance,+ );+ let names: Vec<String> = blockers+ .iter()+ .map(|b| {+ remaining+ .get(b)+ .map(|p| {+ if p.name.is_empty() {+ b.clone()+ } else {+ p.name.clone()+ }+ })+ .unwrap_or_else(|| b.clone())+ })+ .collect();+ eprintln!(+ " dir=[{:+.2},{:+.2},{:+.2}] travel={travel:.1} blockers={names:?}",+ d[0], d[1], d[2]+ );+ }+ }+ removal_order.push(PlannedComponent {+ node_id: id.clone(),+ motion: Motion::None,+ confidence: Some("low".to_string()),+ removal_direction: None,+ blocked_by,+ tier: Some("flagged".to_string()),+ verified: false,+ group_id: None,+ });+ *tiers.get_mut("flagged").unwrap() += 1;+ remaining.remove(&id);+ world.set_active(&id, false);+ for memo in [&mut blocked_p1, &mut blocked_p2, &mut frozen] {+ blocked_memo_invalidate(memo, &id);+ }+ progressed = true;+ }+ t_p5 += _ts.elapsed().as_secs_f64();+ }+ if _timing {+ eprintln!(" greedy phases: p1_removal={:.1}s p2_escape={:.1}s p3_merge={:.1}s p4_group={:.1}s p5_flag={:.1}s memo_skips p1={memo_skips_p1} p2={memo_skips_p2}", t_p1, t_p2, t_p3, t_p4, t_p5);+ }++ let sequence: Vec<String> = removal_order+ .iter()+ .rev()+ .map(|e| e.node_id.clone())+ .collect();+ (removal_order, sequence, tiers)+}diff --git a/crates/planner/src/lib.rs b/crates/planner/src/lib.rsnew file mode 100644index 0000000000..ac4636e793--- /dev/null+++ b/crates/planner/src/lib.rs@@ -0,0 +1,17 @@+//! Carbon geometry planner: collision-free disassembly motion + assembly+//! sequence for a tessellated CAD assembly. Collision via FCL (the `collision`+//! crate); numerics via `npy` (LAPACK/BLAS).++pub mod collide;+pub mod consts;+pub mod contains;+pub mod fasteners;+pub mod geom;+pub mod greedy;+pub mod npy;+pub mod pipeline;+pub mod pipeline2;+pub mod stability;+pub mod steps;+pub mod types;+pub mod view;diff --git a/crates/planner/src/npy.rs b/crates/planner/src/npy.rsnew file mode 100644index 0000000000..52485c7a37--- /dev/null+++ b/crates/planner/src/npy.rs@@ -0,0 +1,509 @@+//! Numerics on **ndarray**: pairwise summation for mean/std, sequential+//! row-reduction, LAPACK SVD/eigh, and BLAS world transforms. The float+//! evaluation order is fixed so planner ordering heuristics are reproducible.++use nalgebra::{DMatrix, Matrix3, Vector3};+#[cfg(not(target_os = "macos"))]+use ndarray::{Array1, Array2};+#[cfg(not(target_os = "macos"))]+use ndarray_linalg::{Eigh, JobSvd, SVDDC, UPLO};++// --- numpy pairwise summation (exact algorithm) ----------------------------++const PW_BLOCKSIZE: usize = 128;++/// numpy `pairwise_sum_DOUBLE` over a contiguous slice.+pub fn pairwise_sum(a: &[f64]) -> f64 {+ let n = a.len();+ if n < 8 {+ let mut res = 0.0;+ for &x in a {+ res += x;+ }+ res+ } else if n <= PW_BLOCKSIZE {+ let mut r = [a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]];+ let mut i = 8;+ while i < n - (n % 8) {+ for j in 0..8 {+ r[j] += a[i + j];+ }+ i += 8;+ }+ let mut res = ((r[0] + r[1]) + (r[2] + r[3])) + ((r[4] + r[5]) + (r[6] + r[7]));+ while i < n {+ res += a[i];+ i += 1;+ }+ res+ } else {+ let mut n2 = n / 2;+ n2 -= n2 % 8;+ pairwise_sum(&a[..n2]) + pairwise_sum(&a[n2..])+ }+}++/// `arr.sum(axis=0)` for a C-contiguous (n,3): numpy reduces the NON-contiguous+/// axis SEQUENTIALLY (pairwise summation only applies along the fast axis) —+/// verified bit-for-bit against numpy on real data.+fn sum_rows_sequential(rows: &[Vector3<f64>]) -> Vector3<f64> {+ let mut s = Vector3::zeros();+ for r in rows {+ s += r;+ }+ s+}++/// `np.mean(a)`.+pub fn mean(a: &[f64]) -> f64 {+ pairwise_sum(a) / a.len() as f64+}++/// `np.std(a)`: sqrt(mean(|x - mean|^2)), numpy summation.+pub fn std(a: &[f64]) -> f64 {+ let m = mean(a);+ let sq: Vec<f64> = a+ .iter()+ .map(|&x| {+ let d = x - m;+ d * d+ })+ .collect();+ mean(&sq).sqrt()+}++/// `arr.mean(axis=0)` over (n,3) rows.+pub fn mean_rows(rows: &[Vector3<f64>]) -> Vector3<f64> {+ sum_rows_sequential(rows) / rows.len() as f64+}++/// `np.percentile(a, 25)` (linear interpolation).+pub fn percentile25(a: &[f64]) -> f64 {+ let mut v = a.to_vec();+ v.sort_by(|x, y| x.partial_cmp(y).unwrap());+ let n = v.len();+ if n == 0 {+ return 0.0;+ }+ if n == 1 {+ return v[0];+ }+ let idx = 0.25 * (n as f64 - 1.0);+ let lo = idx.floor() as usize;+ let frac = idx - lo as f64;+ if lo + 1 < n {+ v[lo] * (1.0 - frac) + v[lo + 1] * frac+ } else {+ v[lo]+ }+}++// --- LAPACK via ndarray-linalg ---------------------------------------------++/// `np.linalg.svd(m, full_matrices=False)` for an (n,3) row matrix via LAPACK+/// dgesdd (`SVDDC`, JobSvd::Some == economy). Returns (singular values desc,+/// vt) — `vt` row i is numpy's `basis[i]`. None on LinAlgError (degenerate).+#[cfg(not(target_os = "macos"))]+pub fn svd_rows(m: &DMatrix<f64>) -> Option<(Vector3<f64>, Matrix3<f64>)> {+ if m.ncols() != 3 || m.nrows() < 1 {+ return None;+ }+ let mut arr = Array2::<f64>::zeros((m.nrows(), 3));+ for i in 0..m.nrows() {+ for j in 0..3 {+ arr[[i, j]] = m[(i, j)];+ }+ }+ let (_u, s, vt) = arr.svddc(JobSvd::Some).ok()?;+ let vt = vt?;+ let mut svals = Vector3::zeros();+ for (i, &v) in s.iter().take(3).enumerate() {+ svals[i] = v;+ }+ let mut out = Matrix3::zeros();+ for i in 0..vt.shape()[0].min(3) {+ for j in 0..3 {+ out[(i, j)] = vt[[i, j]];+ }+ }+ Some((svals, out))+}++/// `np.linalg.eigh(m)` for a symmetric 3x3 (UPLO='L', numpy's default).+/// Returns (eigenvalues asc, eigenvectors as columns).+#[cfg(not(target_os = "macos"))]+pub fn eigh3(m: &Matrix3<f64>) -> Option<(Vector3<f64>, Matrix3<f64>)> {+ let mut arr = Array2::<f64>::zeros((3, 3));+ for i in 0..3 {+ for j in 0..3 {+ arr[[i, j]] = m[(i, j)];+ }+ }+ let (w, v): (Array1<f64>, Array2<f64>) = arr.eigh(UPLO::Lower).ok()?;+ let mut vecs = Matrix3::zeros();+ for i in 0..3 {+ for j in 0..3 {+ vecs[(i, j)] = v[[i, j]];+ }+ }+ Some((Vector3::new(w[0], w[1], w[2]), vecs))+}++// --- macOS: Accelerate new-LAPACK (the exact library numpy >=2.0 mac wheels link) ---++#[cfg(target_os = "macos")]+mod accelerate {+ #[link(name = "Accelerate", kind = "framework")]+ extern "C" {+ #[link_name = "dgesdd$NEWLAPACK"]+ pub fn dgesdd(+ jobz: *const u8,+ m: *const i32,+ n: *const i32,+ a: *mut f64,+ lda: *const i32,+ s: *mut f64,+ u: *mut f64,+ ldu: *const i32,+ vt: *mut f64,+ ldvt: *const i32,+ work: *mut f64,+ lwork: *const i32,+ iwork: *mut i32,+ info: *mut i32,+ );+ #[link_name = "dsyevd$NEWLAPACK"]+ pub fn dsyevd(+ jobz: *const u8,+ uplo: *const u8,+ n: *const i32,+ a: *mut f64,+ lda: *const i32,+ w: *mut f64,+ work: *mut f64,+ lwork: *const i32,+ iwork: *mut i32,+ liwork: *const i32,+ info: *mut i32,+ );+ #[link_name = "cblas_dgemm$NEWLAPACK"]+ pub fn cblas_dgemm(+ layout: i32,+ transa: i32,+ transb: i32,+ m: i32,+ n: i32,+ k: i32,+ alpha: f64,+ a: *const f64,+ lda: i32,+ b: *const f64,+ ldb: i32,+ beta: f64,+ c: *mut f64,+ ldc: i32,+ );+ }+}++#[cfg(not(target_os = "macos"))]+mod openblas_cblas {+ #[link(name = "openblas")]+ extern "C" {+ pub fn cblas_dgemm(+ layout: i32,+ transa: i32,+ transb: i32,+ m: i32,+ n: i32,+ k: i32,+ alpha: f64,+ a: *const f64,+ lda: i32,+ b: *const f64,+ ldb: i32,+ beta: f64,+ c: *mut f64,+ ldc: i32,+ );+ }+}++const CBLAS_ROW_MAJOR: i32 = 101;+const CBLAS_NO_TRANS: i32 = 111;+const CBLAS_TRANS: i32 = 112;++unsafe fn dgemm(+ transa: i32,+ transb: i32,+ m: i32,+ n: i32,+ k: i32,+ a: *const f64,+ lda: i32,+ b: *const f64,+ ldb: i32,+ c: *mut f64,+ ldc: i32,+) {+ #[cfg(target_os = "macos")]+ accelerate::cblas_dgemm(+ CBLAS_ROW_MAJOR,+ transa,+ transb,+ m,+ n,+ k,+ 1.0,+ a,+ lda,+ b,+ ldb,+ 0.0,+ c,+ ldc,+ );+ #[cfg(not(target_os = "macos"))]+ openblas_cblas::cblas_dgemm(+ CBLAS_ROW_MAJOR,+ transa,+ transb,+ m,+ n,+ k,+ 1.0,+ a,+ lda,+ b,+ ldb,+ 0.0,+ c,+ ldc,+ );+}++/// numpy `a @ b` for row-major 4x4 f64 matrices (BLAS dgemm, matching+/// `parent_world @ local`). `a`, `b`, returned matrix: row-major [f64; 16].+pub fn mat4_matmul(a: &[f64; 16], b: &[f64; 16]) -> [f64; 16] {+ let mut c = [0.0f64; 16];+ unsafe {+ dgemm(+ CBLAS_NO_TRANS,+ CBLAS_NO_TRANS,+ 4,+ 4,+ 4,+ a.as_ptr(),+ 4,+ b.as_ptr(),+ 4,+ c.as_mut_ptr(),+ 4,+ );+ }+ c+}++/// numpy `positions @ r.T + t` (BLAS dgemm, matching `_collect_world_parts`).+/// `positions`: (n,3) row-major f64; `r`: row-major 3x3 (world[:3,:3]); `t`: world[:3,3].+pub fn transform_points(positions: &[f64], r: &[f64; 9], t: &[f64; 3]) -> Vec<f64> {+ let n = (positions.len() / 3) as i32;+ let mut out = vec![0.0f64; positions.len()];+ unsafe {+ // positions @ r.T == dgemm(NoTrans, Trans)+ dgemm(+ CBLAS_NO_TRANS,+ CBLAS_TRANS,+ n,+ 3,+ 3,+ positions.as_ptr(),+ 3,+ r.as_ptr(),+ 3,+ out.as_mut_ptr(),+ 3,+ );+ }+ for chunk in out.chunks_exact_mut(3) {+ chunk[0] += t[0];+ chunk[1] += t[1];+ chunk[2] += t[2];+ }+ out+}++/// `np.linalg.svd(m, full_matrices=False)` via Accelerate dgesdd (macOS).+#[cfg(target_os = "macos")]+pub fn svd_rows(m: &DMatrix<f64>) -> Option<(Vector3<f64>, Matrix3<f64>)> {+ let n = m.nrows() as i32;+ if m.ncols() != 3 || n < 1 {+ return None;+ }+ let k = 3i32;+ let rows = m.nrows();+ let mut a = vec![0.0f64; rows * 3];+ for i in 0..rows {+ for j in 0..3 {+ a[i + j * rows] = m[(i, j)];+ }+ }+ let min_mn = n.min(3);+ let mut s = [0.0f64; 3];+ let mut u = vec![0.0f64; rows * (min_mn as usize)];+ let mut vt = vec![0.0f64; (min_mn as usize) * 3];+ let mut iwork = vec![0i32; 8 * 3];+ let mut info = 0i32;+ let jobz = b'S';+ let mut wq = [0.0f64; 1];+ let lq = -1i32;+ unsafe {+ accelerate::dgesdd(+ &jobz,+ &n,+ &k,+ a.as_mut_ptr(),+ &n,+ s.as_mut_ptr(),+ u.as_mut_ptr(),+ &n,+ vt.as_mut_ptr(),+ &min_mn,+ wq.as_mut_ptr(),+ &lq,+ iwork.as_mut_ptr(),+ &mut info,+ );+ }+ if info != 0 {+ return None;+ }+ let lwork = wq[0] as i32;+ let mut work = vec![0.0f64; lwork as usize];+ unsafe {+ accelerate::dgesdd(+ &jobz,+ &n,+ &k,+ a.as_mut_ptr(),+ &n,+ s.as_mut_ptr(),+ u.as_mut_ptr(),+ &n,+ vt.as_mut_ptr(),+ &min_mn,+ work.as_mut_ptr(),+ &lwork,+ iwork.as_mut_ptr(),+ &mut info,+ );+ }+ if info != 0 {+ return None;+ }+ let mut out = Matrix3::zeros();+ for i in 0..(min_mn as usize) {+ for j in 0..3 {+ out[(i, j)] = vt[i + j * (min_mn as usize)];+ }+ }+ Some((Vector3::new(s[0], s[1], s[2]), out))+}++/// `np.linalg.eigh` via Accelerate dsyevd (macOS).+#[cfg(target_os = "macos")]+pub fn eigh3(m: &Matrix3<f64>) -> Option<(Vector3<f64>, Matrix3<f64>)> {+ let n = 3i32;+ let mut a = [0.0f64; 9];+ for i in 0..3 {+ for j in 0..3 {+ a[i + j * 3] = m[(i, j)];+ }+ }+ let mut w = [0.0f64; 3];+ let mut info = 0i32;+ let (jobz, uplo) = (b'V', b'L');+ let mut wq = [0.0f64; 1];+ let mut iq = [0i32; 1];+ let m1 = -1i32;+ unsafe {+ accelerate::dsyevd(+ &jobz,+ &uplo,+ &n,+ a.as_mut_ptr(),+ &n,+ w.as_mut_ptr(),+ wq.as_mut_ptr(),+ &m1,+ iq.as_mut_ptr(),+ &m1,+ &mut info,+ );+ }+ if info != 0 {+ return None;+ }+ let lwork = wq[0] as i32;+ let liwork = iq[0];+ let mut work = vec![0.0f64; lwork as usize];+ let mut iwork = vec![0i32; liwork as usize];+ unsafe {+ accelerate::dsyevd(+ &jobz,+ &uplo,+ &n,+ a.as_mut_ptr(),+ &n,+ w.as_mut_ptr(),+ work.as_mut_ptr(),+ &lwork,+ iwork.as_mut_ptr(),+ &liwork,+ &mut info,+ );+ }+ if info != 0 {+ return None;+ }+ let mut vecs = Matrix3::zeros();+ for i in 0..3 {+ for j in 0..3 {+ vecs[(i, j)] = a[i + j * 3];+ }+ }+ Some((Vector3::new(w[0], w[1], w[2]), vecs))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn pairwise_and_stats() {+ let a: Vec<f64> = (0..1000).map(|i| (i as f64) * 0.1 + 0.01).collect();+ assert!((mean(&a) - 49.96).abs() < 1e-9);+ assert!(std(&a) > 28.0 && std(&a) < 29.0);+ }++ #[test]+ fn svd_rod_axis() {+ let mut m = DMatrix::zeros(100, 3);+ for i in 0..100 {+ m[(i, 0)] = i as f64 - 49.5;+ m[(i, 1)] = ((i % 7) as f64 - 3.0) * 0.01;+ m[(i, 2)] = ((i % 5) as f64 - 2.0) * 0.01;+ }+ let (s, vt) = svd_rows(&m).unwrap();+ assert!(s[0] > 10.0 * s[1]);+ assert!(vt[(0, 0)].abs() > 0.999);+ }++ #[test]+ fn eigh_diag() {+ let m = Matrix3::from_diagonal(&Vector3::new(1.0, 3.0, 2.0));+ let (w, v) = eigh3(&m).unwrap();+ assert!((w[0] - 1.0).abs() < 1e-12 && (w[2] - 3.0).abs() < 1e-12);+ assert!(v[(1, 2)].abs() > 0.999);+ }+}diff --git a/crates/planner/src/pipeline.rs b/crates/planner/src/pipeline.rsnew file mode 100644index 0000000000..822c3c5a2f--- /dev/null+++ b/crates/planner/src/pipeline.rs@@ -0,0 +1,694 @@+//! Ordering pipeline, part 1: seated pair depths, fastener/sandwich+//! classification, rigid merge, joints, and ordering adjacency.+//! (Precedence edges, topo sort, verification, and the drivers are in pipeline2.)++use crate::consts::*;+use crate::contains::mesh_contains;+use crate::fasteners::{axis_span, is_fastener};+use crate::geom::*;+use crate::types::{Component, FastenerInfo, FastenerKind};+use nalgebra::{Matrix3, Vector3};+use std::collections::{BTreeMap, HashMap, HashSet};++pub fn pair_key(a: &str, b: &str) -> (String, String) {+ if a <= b {+ (a.to_string(), b.to_string())+ } else {+ (b.to_string(), a.to_string())+ }+}++#[derive(Clone)]+pub struct PairData {+ pub a: String,+ pub b: String,+ pub depth: f64,+ pub points: Vec<Vector3<f64>>,+ pub normals: Vec<Vector3<f64>>,+ pub tensor: Matrix3<f64>,+}++impl PairData {+ pub fn other(&self, id: &str) -> &str {+ if self.a == id {+ &self.b+ } else {+ &self.a+ }+ }+}++pub type PairDepths = HashMap<(String, String), PairData>;++/// Max depth + capped contact points/normals + structure tensor per touching+/// pair, over the broadphase all-pairs contact set. `points`/`normals` are+/// capped at the first 64 in traversal order, feeding sandwich-side means,+/// fastener ring-axis fits, and support normals.+pub fn seated_pair_depths(parts: &[Component]) -> PairDepths {+ let mut mgr = collision::manager_new();+ for p in parts {+ collision::manager_add(mgr.pin_mut(), &p.bvh());+ }+ collision::manager_setup(mgr.pin_mut());+ let contacts = collision::manager_internal_contacts(&mgr, 100_000);++ let mut pairs: PairDepths = HashMap::new();+ for c in &contacts {+ let pa = &parts[c.a];+ let pb = &parts[c.b];+ let (lo, hi) = if pa.node_id <= pb.node_id {+ (pa, pb)+ } else {+ (pb, pa)+ };+ let entry = pairs+ .entry(pair_key(&lo.node_id, &hi.node_id))+ .or_insert_with(|| PairData {+ a: lo.node_id.clone(),+ b: hi.node_id.clone(),+ depth: 0.0,+ points: Vec::new(),+ normals: Vec::new(),+ tensor: Matrix3::zeros(),+ });+ entry.depth = entry.depth.max(c.depth);+ if entry.points.len() < 64 {+ entry.points.push(Vector3::new(c.px, c.py, c.pz));+ entry.normals.push(Vector3::new(c.nx, c.ny, c.nz));+ }+ let normal = Vector3::new(c.nx, c.ny, c.nz);+ let len = normal.norm();+ if len > 1e-9 {+ let u = normal / len;+ entry.tensor += u * u.transpose();+ }+ }+ pairs+}++fn center(part: &Component) -> Vector3<f64> {+ (part.bbox_min + part.bbox_max) / 2.0+}++/// `_shank_radius`.+fn shank_radius(+ part: &Component,+ axis: &Vector3<f64>,+ mate_points: &[Vector3<f64>],+) -> Option<f64> {+ let c = center(part);+ let radial = |p: &Vector3<f64>| {+ let rel = p - c;+ (rel - axis * rel.dot(axis)).norm()+ };+ let radius = if mate_points.len() >= 8 {+ let vals: Vec<f64> = mate_points.iter().map(radial).collect();+ crate::npy::mean(&vals)+ } else {+ let verts = &part.mesh.vertices;+ if verts.len() < 8 {+ return None;+ }+ let vals: Vec<f64> = verts.iter().map(radial).collect();+ crate::npy::percentile25(&vals)+ };+ if radius <= 0.2 {+ None+ } else {+ Some(radius)+ }+}++/// `_classify_fasteners`.+pub fn classify_fasteners(+ parts: &[Component],+ pair_depths: &PairDepths,+) -> HashMap<String, FastenerInfo> {+ let refs: Vec<&Component> = parts.iter().collect();+ let (amin, amax) = bounds(&refs);+ let assembly_diagonal = (amax - amin).norm();+ let max_extent = MAX_FASTENER_EXTENT_MM.max(MAX_FASTENER_DIAGONAL_FRACTION * assembly_diagonal);++ let mut fasteners = HashMap::new();+ for part in parts {+ if !is_fastener(part) {+ continue;+ }+ if (part.bbox_max - part.bbox_min).norm() > max_extent {+ continue;+ }+ let mut mates: HashMap<String, f64> = HashMap::new();+ let mut mate_points: Vec<Vector3<f64>> = Vec::new();+ let mut all_points: Vec<Vector3<f64>> = Vec::new();+ // Deterministic pair iteration (sorted) for stable point order.+ let mut keys: Vec<&(String, String)> = pair_depths.keys().collect();+ keys.sort();+ for k in keys {+ let data = &pair_depths[k];+ if data.a != part.node_id && data.b != part.node_id {+ continue;+ }+ all_points.extend(data.points.iter().cloned());+ if data.depth > MATE_MIN_DEPTH_MM {+ let other = data.other(&part.node_id).to_string();+ mates.insert(other, data.depth);+ mate_points.extend(data.points.iter().cloned());+ }+ }++ let axis_kind = symmetry_axis_kind(part).or_else(|| bbox_axis_kind(part));+ let (axis, kind): (Vector3<f64>, Option<FastenerKind>) = match axis_kind {+ Some((a, k)) => (a, Some(k)),+ None => {+ let ring = axis_from_contacts(&mate_points)+ .or_else(|| axis_from_contacts(&all_points))+ .or_else(|| normal_clusters(&part.contact_normals, 1).into_iter().next());+ match ring {+ Some(a) => (a, None),+ None => continue,+ }+ }+ };+ let sr = shank_radius(part, &axis, &mate_points);+ fasteners.insert(+ part.node_id.clone(),+ FastenerInfo {+ axis,+ mates,+ kind,+ shank_radius: sr,+ sliding: HashMap::new(),+ },+ );+ }+ fasteners+}++pub fn bounds(parts: &[&Component]) -> (Vector3<f64>, Vector3<f64>) {+ let mut lo = Vector3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);+ let mut hi = Vector3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+ for p in parts {+ lo = lo.inf(&p.bbox_min);+ hi = hi.sup(&p.bbox_max);+ }+ (lo, hi)+}++/// `_embedded_pairs`: (inner, outer) where inner sits fully inside outer.+pub fn embedded_pairs(parts: &[Component]) -> Vec<(String, String)> {+ let epsilon = 0.01;+ let mut out = Vec::new();+ for inner in parts {+ for outer in parts {+ if inner.node_id == outer.node_id {+ continue;+ }+ let contained = (0..3).all(|i| inner.bbox_min[i] >= outer.bbox_min[i] - epsilon)+ && (0..3).all(|i| inner.bbox_max[i] <= outer.bbox_max[i] + epsilon);+ if !contained {+ continue;+ }+ let verts = &inner.mesh.vertices;+ if verts.is_empty() {+ continue;+ }+ let step = (verts.len() / 24).max(1);+ let sample: Vec<Vector3<f64>> = verts.iter().step_by(step).take(24).cloned().collect();+ let inside = mesh_contains(&outer.mesh, &sample);+ let frac = inside.iter().filter(|&&b| b).count() as f64 / inside.len() as f64;+ if frac > 0.8 {+ out.push((inner.node_id.clone(), outer.node_id.clone()));+ }+ }+ }+ out+}++/// `_merge_rigid_groups`: union-find over embedded (contained) pairs.+pub fn merge_rigid_groups(+ parts: &[Component],+ _pair_depths: &PairDepths,+ fasteners: &HashMap<String, FastenerInfo>,+ warnings: &mut Vec<String>,+) -> (Vec<Component>, HashMap<String, String>) {+ let mut parent: HashMap<String, String> = parts+ .iter()+ .map(|p| (p.node_id.clone(), p.node_id.clone()))+ .collect();+ fn find(parent: &mut HashMap<String, String>, x: &str) -> String {+ let mut cur = x.to_string();+ while parent[&cur] != cur {+ let gp = parent[&parent[&cur]].clone();+ parent.insert(cur.clone(), gp.clone());+ cur = gp;+ }+ cur+ }+ for (inner, outer) in embedded_pairs(parts) {+ let ra = find(&mut parent, &inner);+ let rb = find(&mut parent, &outer);+ if ra != rb {+ parent.insert(rb, ra);+ }+ }++ let by_id: HashMap<&str, &Component> = parts.iter().map(|p| (p.node_id.as_str(), p)).collect();+ let mut clusters: BTreeMap<String, Vec<String>> = BTreeMap::new();+ let ids: Vec<String> = parts.iter().map(|p| p.node_id.clone()).collect();+ for id in &ids {+ let root = find(&mut parent, id);+ clusters.entry(root).or_default().push(id.clone());+ }++ let bbox_vol = |p: &Component| {+ let e = p.bbox_max - p.bbox_min;+ (e[0] * e[1] * e[2]).abs()+ };++ let mut units: Vec<Component> = Vec::new();+ let mut merged_into: HashMap<String, String> = HashMap::new();+ // Preserve input order of representatives for determinism.+ let mut seen_roots: Vec<String> = Vec::new();+ for id in &ids {+ let root = find(&mut parent, id);+ if !seen_roots.contains(&root) {+ seen_roots.push(root);+ }+ }+ for root in seen_roots {+ let members_ids = &clusters[&root];+ let members: Vec<&Component> = members_ids.iter().map(|m| by_id[m.as_str()]).collect();+ if members.len() == 1 {+ units.push(members[0].clone());+ continue;+ }+ let rep = members+ .iter()+ .max_by(|a, b| {+ let ka = (fasteners.contains_key(&a.node_id) as i32, bbox_vol(a));+ let kb = (fasteners.contains_key(&b.node_id) as i32, bbox_vol(b));+ ka.0.cmp(&kb.0).then(ka.1.partial_cmp(&kb.1).unwrap())+ })+ .unwrap();+ let meshes: Vec<&crate::types::Mesh> = members.iter().map(|m| &m.mesh).collect();+ let combined_mesh = crate::types::Mesh::concatenate(&meshes);+ let (lo, hi) = bounds(&members);+ let mut combined = Component::new(+ rep.node_id.clone(),+ rep.name.clone(),+ combined_mesh,+ lo,+ hi,+ members.iter().any(|m| m.is_proxy),+ );+ combined.cached_volume = Some(members.iter().map(|m| part_volume(m)).sum());+ units.push(combined);+ for m in &members {+ if m.node_id != rep.node_id {+ merged_into.insert(m.node_id.clone(), rep.node_id.clone());+ }+ }+ let names: Vec<String> = members+ .iter()+ .map(|m| {+ format!(+ "'{}'",+ if m.name.is_empty() {+ &m.node_id+ } else {+ &m.name+ }+ )+ })+ .collect();+ warnings.push(format!(+ "{} interpenetrate when seated; planned as one rigid unit",+ names.join(", ")+ ));+ }+ (units, merged_into)+}++/// Largest eigenvector (by eigenvalue) of a symmetric 3x3 matrix — numpy+/// `eigh(...)[1][:, -1]`.+pub fn dominant_eigenvector(m: &Matrix3<f64>) -> Vector3<f64> {+ // numpy eigh (dsyevd): ascending eigenvalues, vectors as columns -> [:, -1]+ match crate::npy::eigh3(m) {+ Some((_w, vecs)) => vecs.column(2).into(),+ None => {+ let eig = m.symmetric_eigen();+ let mut best = 0;+ for i in 1..3 {+ if eig.eigenvalues[i] > eig.eigenvalues[best] {+ best = i;+ }+ }+ eig.eigenvectors.column(best).into()+ }+ }+}++/// A sandwiched compliant part and its two sides.+pub struct SandwichInfo {+ pub axis: Vector3<f64>,+ pub side_a: HashSet<String>,+ pub side_b: HashSet<String>,+}++/// `_fastener_joints`: parts each fastener joins → projection along its axis.+pub fn fastener_joints(+ parts: &[Component],+ fasteners: &HashMap<String, FastenerInfo>,+) -> HashMap<String, HashMap<String, f64>> {+ let by_id: HashMap<&str, &Component> = parts.iter().map(|p| (p.node_id.as_str(), p)).collect();+ let mut joints: HashMap<String, HashMap<String, f64>> = HashMap::new();++ for part in parts {+ let info = match fasteners.get(&part.node_id) {+ Some(i) => i,+ None => continue,+ };+ let fid = &part.node_id;+ let center0 = center(part);+ let mut joint: HashMap<String, f64> = HashMap::new();+ for mate in info.mates.keys() {+ if let Some(mp) = by_id.get(mate.as_str()) {+ joint.insert(mate.clone(), (center(mp) - center0).dot(&info.axis));+ }+ }+ if let Some(radius) = info.shank_radius {+ let axis = info.axis;+ let c = center0;+ let seed = if axis.dot(&world_axes()[0]).abs() < 0.9 {+ world_axes()[0]+ } else {+ world_axes()[2]+ };+ let mut u = axis.cross(&seed);+ let un = u.norm();+ u /= if un == 0.0 { 1.0 } else { un };+ let v = axis.cross(&u);+ let ring_radii = [radius * 1.2, radius * 1.2 + 2.0];+ let ring_offsets: Vec<Vector3<f64>> = (0..8)+ .map(|i| {+ let a = i as f64 * 2.0 * std::f64::consts::PI / 8.0;+ u * a.cos() + v * a.sin()+ })+ .collect();+ let (f_lo, f_hi) = axis_span(part, &axis, &c);+ let max_radial = part+ .mesh+ .vertices+ .iter()+ .map(|p| {+ let rel = p - c;+ (rel - axis * rel.dot(&axis)).norm()+ })+ .fold(0.0, f64::max);+ let probe_cap = max_radial * 5.0 + 5.0;++ for other in parts {+ if other.node_id == *fid || joint.contains_key(&other.node_id) {+ continue;+ }+ let inflate = probe_cap + 2.0;+ let near = (0..3).all(|k| part.bbox_min[k] - inflate <= other.bbox_max[k])+ && (0..3).all(|k| other.bbox_min[k] - inflate <= part.bbox_max[k]);+ if !near {+ continue;+ }+ let (o_lo, o_hi) = axis_span(other, &axis, &c);+ let lo = f_lo.max(o_lo);+ let hi = f_hi.min(o_hi);+ if hi - lo < 0.5 {+ continue;+ }+ let mut probe_radii = ring_radii.to_vec();+ let mut probe_heights = vec![+ lo + (hi - lo) * 0.5,+ lo + (hi - lo) * 0.25,+ lo + (hi - lo) * 0.75,+ ];+ let in_span: Vec<(&Vector3<f64>, f64)> = other+ .mesh+ .vertices+ .iter()+ .filter_map(|vtx| {+ let proj = (vtx - c).dot(&axis);+ if proj >= lo && proj <= hi {+ Some((vtx, proj))+ } else {+ None+ }+ })+ .collect();+ if in_span.len() >= 3 {+ let mut min_radial = f64::INFINITY;+ let mut rim_t = 0.0;+ for (vtx, proj) in &in_span {+ let rel = *vtx - c;+ let r = (rel - axis * rel.dot(&axis)).norm();+ if r < min_radial {+ min_radial = r;+ rim_t = *proj;+ }+ }+ let adaptive = min_radial * 1.05 + 0.5;+ if adaptive <= probe_cap {+ probe_radii.push(adaptive);+ probe_heights.push(rim_t.clamp(lo + 0.25, hi - 0.25));+ }+ }++ let mut surrounded = false;+ let mut surround_t = 0.0;+ 'outer: for t in &probe_heights {+ for rr in &probe_radii {+ let ring: Vec<Vector3<f64>> = ring_offsets+ .iter()+ .map(|o| c + axis * *t + o * *rr)+ .collect();+ let inside = mesh_contains(&other.mesh, &ring);+ if !inside.is_empty() {+ let frac =+ inside.iter().filter(|&&b| b).count() as f64 / inside.len() as f64;+ if frac >= 0.75 {+ surrounded = true;+ surround_t = *t;+ break 'outer;+ }+ }+ }+ }+ if surrounded {+ joint.insert(other.node_id.clone(), surround_t);+ }+ }+ }+ joints.insert(fid.clone(), joint);+ }+ joints+}++/// `_sandwiched_parts`: thin parts pressed from both sides along one axis.+/// Mutates each partner's `seated_allowance` / `seated_allowance_axes`.+pub fn sandwiched_parts(+ units: &mut [Component],+ pair_depths: &PairDepths,+ fasteners: &HashMap<String, FastenerInfo>,+ merged_into: &HashMap<String, String>,+) -> HashMap<String, SandwichInfo> {+ let unit_ids: HashSet<String> = units.iter().map(|u| u.node_id.clone()).collect();+ // unit -> partner -> (tensor, points, depth)+ let mut contacts: HashMap<String, HashMap<String, (Matrix3<f64>, Vec<Vector3<f64>>, f64)>> =+ HashMap::new();+ let mut keys: Vec<&(String, String)> = pair_depths.keys().collect();+ keys.sort();+ for k in keys {+ let data = &pair_depths[k];+ let unit_a = merged_into+ .get(&data.a)+ .cloned()+ .unwrap_or_else(|| data.a.clone());+ let unit_b = merged_into+ .get(&data.b)+ .cloned()+ .unwrap_or_else(|| data.b.clone());+ if unit_a == unit_b || !unit_ids.contains(&unit_a) || !unit_ids.contains(&unit_b) {+ continue;+ }+ for (me, other) in [(&unit_a, &unit_b), (&unit_b, &unit_a)] {+ let slot = contacts+ .entry(me.clone())+ .or_default()+ .entry(other.clone())+ .or_insert_with(|| (Matrix3::zeros(), Vec::new(), 0.0));+ slot.0 += data.tensor;+ slot.1.extend(data.points.iter().cloned());+ slot.2 = slot.2.max(data.depth);+ }+ }++ let unit_by_id: HashMap<String, (Vector3<f64>, Vector3<f64>, bool)> = units+ .iter()+ .map(|u| (u.node_id.clone(), (u.bbox_min, u.bbox_max, u.is_proxy)))+ .collect();++ let mut result: HashMap<String, SandwichInfo> = HashMap::new();+ // (unit_id, partner_id, allowance, axis)+ let mut updates: Vec<(String, String, f64, Vector3<f64>)> = Vec::new();++ for unit in units.iter() {+ if unit.is_proxy || fasteners.contains_key(&unit.node_id) {+ continue;+ }+ let empty = HashMap::new();+ let all = contacts.get(&unit.node_id).unwrap_or(&empty);+ let mut partner_ids: Vec<&String> = all+ .iter()+ .filter(|(other, slot)| !fasteners.contains_key(*other) && !slot.1.is_empty())+ .map(|(other, _)| other)+ .collect();+ partner_ids.sort();+ if partner_ids.len() < 2 {+ continue;+ }+ let axes: Vec<Vector3<f64>> = partner_ids+ .iter()+ .map(|p| dominant_eigenvector(&all[*p].0))+ .collect();+ let axis = axes[0];+ if axes[1..]+ .iter()+ .any(|a| axis.dot(a).abs() < SANDWICH_AXIS_ALIGNMENT)+ {+ continue;+ }+ let extents = unit.bbox_max - unit.bbox_min;+ let thickness = crate::geom::vabs(&axis).dot(&extents);+ let max_extent = extents.iter().cloned().fold(f64::MIN, f64::max);+ if thickness > SANDWICH_MAX_THICKNESS_RATIO * max_extent {+ continue;+ }+ if thickness > SANDWICH_MAX_THICKNESS_MM {+ continue;+ }+ if partner_ids+ .iter()+ .any(|p| all[*p].2 > SANDWICH_MAX_SQUISH_MM)+ {+ continue;+ }+ let center_axis = axis.dot(&((unit.bbox_min + unit.bbox_max) / 2.0));+ let mut side_a: HashSet<String> = HashSet::new();+ let mut side_b: HashSet<String> = HashSet::new();+ for p in &partner_ids {+ let pts = &all[*p].1;+ let mean = crate::npy::mean_rows(pts);+ let m = axis.dot(&mean);+ if m < center_axis {+ side_a.insert((*p).clone());+ } else {+ side_b.insert((*p).clone());+ }+ }+ if side_a.is_empty() || side_b.is_empty() {+ continue;+ }+ for p in &partner_ids {+ let allowance = all[*p].2.max(0.0);+ updates.push((unit.node_id.clone(), (*p).clone(), allowance, axis));+ updates.push(((*p).clone(), unit.node_id.clone(), allowance, axis));+ }+ result.insert(+ unit.node_id.clone(),+ SandwichInfo {+ axis,+ side_a,+ side_b,+ },+ );+ }+ let _ = unit_by_id;++ // Apply allowance updates (max wins).+ let mut idx: HashMap<String, usize> = units+ .iter()+ .enumerate()+ .map(|(i, u)| (u.node_id.clone(), i))+ .collect();+ for (unit_id, partner, allowance, axis) in updates {+ if let Some(&i) = idx.get(&unit_id) {+ let cur = units[i]+ .seated_allowance+ .get(&partner)+ .cloned()+ .unwrap_or(0.0);+ if allowance > cur {+ units[i].seated_allowance.insert(partner.clone(), allowance);+ units[i].seated_allowance_axes.insert(partner, axis);+ }+ }+ }+ let _ = &mut idx;+ result+}++/// `_ordering_adjacency`: leaf-level "mates with" graph for ordering.+pub fn ordering_adjacency(+ parts: &[Component],+ pair_depths: &PairDepths,+ contact_mm: f64,+) -> HashMap<String, HashSet<String>> {+ let mut adjacency: HashMap<String, HashSet<String>> = parts+ .iter()+ .map(|p| (p.node_id.clone(), HashSet::new()))+ .collect();+ for data in pair_depths.values() {+ adjacency.get_mut(&data.a).unwrap().insert(data.b.clone());+ adjacency.get_mut(&data.b).unwrap().insert(data.a.clone());+ }+ let count = parts.len();+ if count < 2 {+ return adjacency;+ }+ let mins: Vec<Vector3<f64>> = parts+ .iter()+ .map(|p| p.bbox_min.add_scalar(-contact_mm))+ .collect();+ let maxs: Vec<Vector3<f64>> = parts+ .iter()+ .map(|p| p.bbox_max.add_scalar(contact_mm))+ .collect();+ let mut candidates: Vec<(usize, usize)> = Vec::new();+ for i in 0..(count - 1) {+ for j in (i + 1)..count {+ let overlap = (0..3).all(|k| mins[i][k] <= maxs[j][k] && mins[j][k] <= maxs[i][k]);+ if !overlap {+ continue;+ }+ if adjacency[&parts[i].node_id].contains(&parts[j].node_id) {+ continue;+ }+ candidates.push((i, j));+ }+ }+ let exact = candidates.len() <= MAX_ADJACENCY_DISTANCE_PAIRS;+ for (i, j) in candidates {+ if exact {+ let d = collision::distance_pair(&parts[i].bvh(), &parts[j].bvh());+ if d > contact_mm {+ continue;+ }+ }+ adjacency+ .get_mut(&parts[i].node_id)+ .unwrap()+ .insert(parts[j].node_id.clone());+ adjacency+ .get_mut(&parts[j].node_id)+ .unwrap()+ .insert(parts[i].node_id.clone());+ }+ adjacency+}diff --git a/crates/planner/src/pipeline2.rs b/crates/planner/src/pipeline2.rsnew file mode 100644index 0000000000..cac5d6a771--- /dev/null+++ b/crates/planner/src/pipeline2.rs@@ -0,0 +1,2000 @@+//! Ordering pipeline, part 2: precedence DAG, joint/sandwich/support edges,+//! base reselection, preference topo sort, connectivity repair, forward+//! verification, and the `plan_parts` / `plan_fixed_sequence` drivers.++#[allow(unused_imports)]+use crate::collide::*;+use crate::collide::{CollisionWorld, Exempt};+use crate::consts::*;+use crate::fasteners::head_direction;+use crate::geom::*;+use crate::greedy::{greedy_disassembly, new_tiers, plan_escape, plan_removal, Tiers};+use crate::pipeline::*;+use crate::types::{Component, FastenerInfo, FastenerKind, Motion, PlannedComponent};+use nalgebra::Vector3;+use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};++type Edges = HashMap<String, HashSet<String>>;++#[derive(Clone)]+pub struct GroupPayload {+ pub component_node_ids: Vec<String>,+ pub motion: Motion,+ pub name: Option<String>,+}++pub struct PlanOutcome {+ pub planned: Vec<PlannedComponent>,+ pub sequence: Vec<String>,+ pub tiers: Tiers,+ pub merged_into: HashMap<String, String>,+ pub groups: BTreeMap<String, GroupPayload>,+ pub verified_count: i64,+ pub edges: Edges,+ pub adjacency: Edges,+ /// Proximity-based "related parts" graph (strict `adjacency` augmented with+ /// clearance-fit neighbors, see `relatedness_mm`). Drives the sequencing+ /// connectivity preference and the emitted viewer contact graph. Strict+ /// `adjacency` still governs base selection and collision correctness.+ pub relatedness: Edges,+ /// Leaf node ids whose center of mass falls outside the support polygon of+ /// the parts placed below them (support-polygon check, `stability.rs`).+ /// Purely diagnostic — surfaced per step as `needsSupport`.+ pub needs_support: HashSet<String>,+ /// Unit id → build wave (longest-path level in the precedence DAG). Units+ /// sharing a wave have no ordering constraint and can be built in parallel.+ /// Cycle-affected units are absent. Purely additive; the linear `sequence`+ /// is unchanged.+ pub waves: HashMap<String, i64>,+}++/// `_removal_segments`: a stored INSERTION motion as removal segments.+fn removal_segments(motion: &Motion) -> Option<Vec<(Vector3<f64>, f64)>> {+ match motion {+ Motion::Linear {+ direction,+ distance,+ } => {+ let d = Vector3::new(-direction[0], -direction[1], -direction[2]);+ let n = d.norm();+ let n = if n == 0.0 { 1.0 } else { n };+ Some(vec![(d / n, *distance)])+ }+ Motion::L { segments } => {+ let mut out = Vec::new();+ for seg in segments.iter().rev() {+ let d = Vector3::new(-seg.direction[0], -seg.direction[1], -seg.direction[2]);+ let n = d.norm();+ let n = if n == 0.0 { 1.0 } else { n };+ out.push((d / n, seg.distance));+ }+ Some(out)+ }+ Motion::None => None,+ }+}++fn others_excluding<'a>(+ units_by_id: &'a HashMap<String, Component>,+ id: &str,+) -> Vec<&'a Component> {+ units_by_id.values().filter(|c| c.node_id != id).collect()+}++/// `_derive_precedence`: U → X where X's seated body blocks U's insertion path.+fn derive_precedence(+ planned: &[PlannedComponent],+ units_by_id: &HashMap<String, Component>,+ fasteners: &HashMap<String, FastenerInfo>,+ path_samples: usize,+ tolerance: f64,+) -> Edges {+ let samples_segment = (path_samples / 3).max(12);+ let units: Vec<&Component> = units_by_id.values().collect();+ let world = CollisionWorld::new(&units);+ let mut edges: Edges = planned+ .iter()+ .map(|e| (e.node_id.clone(), HashSet::new()))+ .collect();+ for entry in planned {+ let segments = match removal_segments(&entry.motion) {+ Some(s) => s,+ None => continue,+ };+ let part = &units_by_id[&entry.node_id];+ let mut extra: Exempt = HashMap::new();+ extra.insert(part.node_id.clone(), f64::INFINITY);+ let blockers = path_blockers(+ part,+ &world,+ &segments,+ samples_segment,+ fasteners,+ Some(&extra),+ tolerance,+ );+ edges.get_mut(&entry.node_id).unwrap().extend(blockers);+ }+ edges+}++/// Longest-path level of each unit in the hard-precedence DAG (`edges[before] =+/// {after}`): 0 for units with no predecessor, else `1 + max(predecessor wave)`.+/// Units sharing a wave have no ordering constraint between them — the parallel-+/// buildable group. Deterministic (sorted traversal). Units on a precedence+/// cycle are omitted (→ no wave; the consumer shows them strictly sequential).+pub fn compute_waves(edges: &Edges) -> HashMap<String, i64> {+ let mut indegree: HashMap<&str, usize> = edges.keys().map(|k| (k.as_str(), 0usize)).collect();+ for afters in edges.values() {+ for after in afters {+ *indegree.entry(after.as_str()).or_insert(0) += 1;+ }+ }+ let mut wave: HashMap<String, i64> = HashMap::new();+ let mut roots: Vec<&str> = indegree+ .iter()+ .filter(|(_, &d)| d == 0)+ .map(|(&n, _)| n)+ .collect();+ roots.sort();+ let mut queue: std::collections::VecDeque<&str> = roots.into_iter().collect();+ for &n in &queue {+ wave.insert(n.to_string(), 0);+ }+ while let Some(n) = queue.pop_front() {+ let wn = wave[n];+ let Some(afters) = edges.get(n) else {+ continue;+ };+ let mut sorted: Vec<&str> = afters.iter().map(|s| s.as_str()).collect();+ sorted.sort();+ for after in sorted {+ let w = wave.get(after).copied().unwrap_or(-1).max(wn + 1);+ wave.insert(after.to_string(), w);+ if let Some(d) = indegree.get_mut(after) {+ *d -= 1;+ if *d == 0 {+ queue.push_back(after);+ }+ }+ }+ }+ // Any unit still with unresolved predecessors sits on a cycle — it can't be+ // leveled, so drop its partial wave.+ for (n, &d) in &indegree {+ if d > 0 {+ wave.remove(*n);+ }+ }+ wave+}++fn reaches(edges: &Edges, source: &str, target: &str) -> bool {+ let mut stack = vec![source.to_string()];+ let mut seen = HashSet::new();+ while let Some(node) = stack.pop() {+ if node == target {+ return true;+ }+ if !seen.insert(node.clone()) {+ continue;+ }+ if let Some(next) = edges.get(&node) {+ stack.extend(next.iter().cloned());+ }+ }+ false+}++/// `_add_joint_edges`.+fn add_joint_edges(+ fasteners: &HashMap<String, FastenerInfo>,+ joints: &HashMap<String, HashMap<String, f64>>,+ units_by_id: &HashMap<String, Component>,+ edges: &mut Edges,+ warnings: &mut Vec<String>,+) {+ let add_edge = |edges: &mut Edges,+ warnings: &mut Vec<String>,+ before: &str,+ after: &str,+ label: &str| {+ if edges+ .get(before)+ .map(|s| s.contains(after))+ .unwrap_or(false)+ {+ return;+ }+ if reaches(edges, after, before) {+ warnings.push(format!(+ "{label} preference between '{before}' and '{after}' conflicts with collision constraints; skipped"+ ));+ return;+ }+ edges.get_mut(before).unwrap().insert(after.to_string());+ };++ // Deterministic fastener iteration.+ let mut fids: Vec<&String> = fasteners.keys().collect();+ fids.sort();+ for fastener_id in fids {+ if !edges.contains_key(fastener_id) {+ continue;+ }+ let info = &fasteners[fastener_id];+ let empty = HashMap::new();+ let joint = joints.get(fastener_id).unwrap_or(&empty);+ let mut chain: Vec<String> = Vec::new();+ let mut members: Vec<&String> = joint.keys().collect();+ members.sort();+ for member in members {+ if !edges.contains_key(member) {+ continue;+ }+ let member_info = fasteners.get(member);+ let is_rod_disc_mate = info.mates.contains_key(member)+ && member_info+ .map(|mi| mi.kind == Some(FastenerKind::Disc))+ .unwrap_or(false)+ && info.kind == Some(FastenerKind::Rod);+ if is_rod_disc_mate {+ add_edge(edges, warnings, fastener_id, member, "joint-order");+ } else {+ add_edge(edges, warnings, member, fastener_id, "joint-order");+ chain.push(member.clone());+ }+ }++ let fastener_part = match units_by_id.get(fastener_id) {+ Some(p) => p,+ None => continue,+ };+ if chain.len() < 2 {+ continue;+ }+ let head_dir = head_direction(fastener_part, info, Some(units_by_id));+ let sign = if head_dir.dot(&info.axis) >= 0.0 {+ 1.0+ } else {+ -1.0+ };+ let head_projection = |member: &str| sign * joint.get(member).cloned().unwrap_or(0.0);+ chain.sort_by(|a, b| {+ head_projection(a)+ .partial_cmp(&head_projection(b))+ .unwrap()+ .then(a.cmp(b))+ });+ for w in chain.windows(2) {+ let (tip_side, head_side) = (&w[0], &w[1]);+ if (head_projection(head_side) - head_projection(tip_side)).abs() < 0.5 {+ continue;+ }+ add_edge(edges, warnings, tip_side, head_side, "joint-stack");+ }+ }+}++/// `_add_sandwich_edges` (soft).+fn add_sandwich_edges(+ sandwiches: &HashMap<String, SandwichInfo>,+ units_by_id: &HashMap<String, Component>,+ merged_into: &HashMap<String, String>,+ edges: &mut Edges,+ warnings: &mut Vec<String>,+) {+ let add_edge = |edges: &mut Edges, warnings: &mut Vec<String>, before: &str, after: &str| {+ if edges+ .get(before)+ .map(|s| s.contains(after))+ .unwrap_or(false)+ {+ return;+ }+ if reaches(edges, after, before) {+ warnings.push(format!(+ "sandwich preference between '{before}' and '{after}' conflicts with collision constraints; skipped"+ ));+ return;+ }+ edges.get_mut(before).unwrap().insert(after.to_string());+ };+ let mut node_ids: Vec<&String> = sandwiches.keys().collect();+ node_ids.sort();+ for node_id in node_ids {+ if !edges.contains_key(node_id) {+ continue;+ }+ let info = &sandwiches[node_id];+ let resolve = |side: &HashSet<String>| -> BTreeSet<String> {+ side.iter()+ .map(|o| merged_into.get(o).cloned().unwrap_or_else(|| o.clone()))+ .filter(|u| edges.contains_key(u) && u != node_id)+ .collect()+ };+ let side_a = resolve(&info.side_a);+ let side_b = resolve(&info.side_b);+ if side_a.is_empty() || side_b.is_empty() {+ continue;+ }+ let side_volume = |side: &BTreeSet<String>| -> f64 {+ side.iter().map(|o| part_volume(&units_by_id[o])).sum()+ };+ let va = side_volume(&side_a);+ let vb = side_volume(&side_b);+ if va.max(vb) <= 0.0 {+ continue;+ }+ if (va - vb).abs() < 0.05 * va.max(vb) {+ warnings.push(format!(+ "sandwiched part '{node_id}' has near-equal sides; no ordering preference added"+ ));+ continue;+ }+ let (first, second) = if va > vb {+ (&side_a, &side_b)+ } else {+ (&side_b, &side_a)+ };+ for o in first {+ add_edge(edges, warnings, o, node_id);+ }+ for o in second {+ add_edge(edges, warnings, node_id, o);+ }+ }+}++/// `_add_support_edges` (soft).+fn add_support_edges(+ parts: &[Component],+ pair_depths: &PairDepths,+ fasteners: &HashMap<String, FastenerInfo>,+ merged_into: &HashMap<String, String>,+ edges: &mut Edges,+ warnings: &mut Vec<String>,+) {+ let by_id: HashMap<&str, &Component> = parts.iter().map(|p| (p.node_id.as_str(), p)).collect();+ let mut keys: Vec<&(String, String)> = pair_depths.keys().collect();+ keys.sort();+ for k in keys {+ let data = &pair_depths[k];+ let (a, b) = (&data.a, &data.b);+ if fasteners.contains_key(a) || fasteners.contains_key(b) {+ continue;+ }+ let unit_a = merged_into.get(a).cloned().unwrap_or_else(|| a.clone());+ let unit_b = merged_into.get(b).cloned().unwrap_or_else(|| b.clone());+ if unit_a == unit_b || !edges.contains_key(&unit_a) || !edges.contains_key(&unit_b) {+ continue;+ }+ if data.normals.is_empty() {+ continue;+ }+ let aligned: Vec<nalgebra::Vector3<f64>> = data+ .normals+ .iter()+ .map(|n| {+ let flip = if n[2] > 0.0 {+ 1.0+ } else if n[2] < 0.0 {+ -1.0+ } else {+ 1.0+ };+ n * flip+ })+ .collect();+ let mean = crate::npy::mean_rows(&aligned);+ let length = mean.norm();+ if length <= 1e-9 || (mean[2] / length).abs() < 0.5 {+ continue;+ }+ let (pa, pb) = match (by_id.get(a.as_str()), by_id.get(b.as_str())) {+ (Some(pa), Some(pb)) => (pa, pb),+ _ => continue,+ };+ let ca = (pa.bbox_min[2] + pa.bbox_max[2]) / 2.0;+ let cb = (pb.bbox_min[2] + pb.bbox_max[2]) / 2.0;+ if (ca - cb).abs() < 1e-6 {+ continue;+ }+ let (lower, upper) = if ca < cb {+ (&unit_a, &unit_b)+ } else {+ (&unit_b, &unit_a)+ };+ if edges[lower].contains(upper) {+ continue;+ }+ if reaches(edges, upper, lower) {+ warnings.push(format!(+ "support-order preference between '{lower}' and '{upper}' conflicts with collision constraints; skipped"+ ));+ continue;+ }+ edges.get_mut(lower).unwrap().insert(upper.clone());+ }+}++/// `_rollup_adjacency`.+fn rollup_adjacency(+ leaf_adjacency: &Edges,+ merged_into: &HashMap<String, String>,+ group_units: &HashMap<String, (Component, Vec<String>)>,+ units_by_id: &HashMap<String, Component>,+) -> Edges {+ let mut member_to_rep: HashMap<String, String> = HashMap::new();+ for (rep_id, (_c, members)) in group_units {+ for m in members {+ member_to_rep.insert(m.clone(), rep_id.clone());+ }+ }+ let final_unit = |leaf: &str| -> String {+ let unit = merged_into+ .get(leaf)+ .cloned()+ .unwrap_or_else(|| leaf.to_string());+ member_to_rep.get(&unit).cloned().unwrap_or(unit)+ };+ let mut adjacency: Edges = units_by_id+ .keys()+ .map(|u| (u.clone(), HashSet::new()))+ .collect();+ for (leaf, neighbors) in leaf_adjacency {+ let unit_a = final_unit(leaf);+ if !adjacency.contains_key(&unit_a) {+ continue;+ }+ for neighbor in neighbors {+ let unit_b = final_unit(neighbor);+ if unit_b == unit_a || !adjacency.contains_key(&unit_b) {+ continue;+ }+ adjacency.get_mut(&unit_a).unwrap().insert(unit_b.clone());+ adjacency.get_mut(&unit_b).unwrap().insert(unit_a.clone());+ }+ }+ adjacency+}++/// `_reselect_base`.+fn reselect_base(+ planned: &mut [PlannedComponent],+ units_by_id: &HashMap<String, Component>,+ unit_adjacency: &Edges,+ fasteners: &HashMap<String, FastenerInfo>,+ warnings: &mut Vec<String>,+) {+ let base_idx = match planned+ .iter()+ .position(|e| e.tier.as_deref() == Some("base"))+ {+ Some(i) => i,+ None => return,+ };+ let score = |node_id: &str| -> (usize, f64) {+ (+ unit_adjacency.get(node_id).map(|s| s.len()).unwrap_or(0),+ part_volume(&units_by_id[node_id]),+ )+ };+ let base_id = planned[base_idx].node_id.clone();+ let candidates: Vec<usize> = planned+ .iter()+ .enumerate()+ .filter(|(_, e)| {+ e.tier.as_deref() != Some("base")+ && units_by_id.contains_key(&e.node_id)+ && !fasteners.contains_key(&e.node_id)+ && !units_by_id[&e.node_id].is_proxy+ })+ .map(|(i, _)| i)+ .collect();+ if candidates.is_empty() {+ return;+ }+ let winner_idx = *candidates+ .iter()+ .max_by(|&&a, &&b| {+ let sa = score(&planned[a].node_id);+ let sb = score(&planned[b].node_id);+ (sa.0, sa.1, planned[a].node_id.clone())+ .partial_cmp(&(sb.0, sb.1, planned[b].node_id.clone()))+ .unwrap()+ })+ .unwrap();+ let (base_degree, base_volume) = score(&base_id);+ let (win_degree, win_volume) = score(&planned[winner_idx].node_id);+ if (win_degree as f64) < 1.5 * (base_degree.max(1) as f64) || win_volume < 0.5 * base_volume {+ return;+ }+ let winner_name = {+ let u = &units_by_id[&planned[winner_idx].node_id];+ if u.name.is_empty() {+ planned[winner_idx].node_id.clone()+ } else {+ u.name.clone()+ }+ };+ let base_name = {+ let u = &units_by_id[&base_id];+ if u.name.is_empty() {+ base_id.clone()+ } else {+ u.name.clone()+ }+ };+ warnings.push(format!(+ "base re-anchored to '{winner_name}' ({win_degree} mates) — '{base_name}' was the last removable part, not the part the assembly mounts into; it fades in at its ordered position instead"+ ));+ planned[winner_idx].tier = Some("base".to_string());+ planned[winner_idx].motion = Motion::None;+ planned[winner_idx].confidence = Some("high".to_string());+ planned[winner_idx].removal_direction = None;+ planned[winner_idx].blocked_by = Vec::new();+ let mut base_blockers: Vec<String> = unit_adjacency+ .get(&base_id)+ .map(|s| s.iter().cloned().collect())+ .unwrap_or_default();+ base_blockers.sort();+ base_blockers.truncate(crate::consts::MAX_REPORTED_BLOCKERS);+ planned[base_idx].tier = Some("flagged".to_string());+ planned[base_idx].motion = Motion::None;+ planned[base_idx].confidence = Some("low".to_string());+ planned[base_idx].removal_direction = None;+ planned[base_idx].blocked_by = base_blockers;+}++/// `_connectivity_repair`.+/// Reorder for island-connectivity. `hard_edges` (improved mode) constrains the+/// repair to never hoist a part above one of its collision predecessors — the+/// Python version reorders on adjacency alone, and every hard-edge violation it+/// introduces surfaces later as a "failed forward verification" demotion (the+/// flag autopsy traced ALL of Packing Arm's demotions to exactly this).+fn connectivity_repair(+ order: &[String],+ adjacency: &Edges,+ hard_edges: Option<&Edges>,+) -> Vec<String> {+ // For each node in `order`, the set of in-order nodes that must precede it.+ let in_order: HashSet<&String> = order.iter().collect();+ let mut preds: HashMap<&String, Vec<&String>> = HashMap::new();+ if let Some(edges) = hard_edges {+ for (before, afters) in edges {+ if !in_order.contains(before) {+ continue;+ }+ for after in afters {+ if in_order.contains(after) {+ preds.entry(after).or_default().push(before);+ }+ }+ }+ }+ let mut result: Vec<String> = Vec::new();+ let mut placed: HashSet<String> = HashSet::new();+ let mut deferred: Vec<String> = Vec::new();+ let mut remaining: std::collections::VecDeque<String> = order.iter().cloned().collect();+ let empty = HashSet::new();+ let touches = |node: &str, placed: &HashSet<String>| -> bool {+ placed.is_empty()+ || adjacency+ .get(node)+ .unwrap_or(&empty)+ .intersection(placed)+ .next()+ .is_some()+ };+ let preds_ok = |node: &String, placed: &HashSet<String>| -> bool {+ preds+ .get(node)+ .map(|ps| ps.iter().all(|p| placed.contains(*p)))+ .unwrap_or(true)+ };+ while !remaining.is_empty() || !deferred.is_empty() {+ let mut pick: Option<String> = None;+ if let Some(pos) = deferred+ .iter()+ .position(|n| touches(n, &placed) && preds_ok(n, &placed))+ {+ pick = Some(deferred.remove(pos));+ }+ if pick.is_none() {+ while let Some(node) = remaining.pop_front() {+ if touches(&node, &placed) && preds_ok(&node, &placed) {+ pick = Some(node);+ break;+ }+ deferred.push(node);+ }+ }+ // Nothing both touches and is precedence-ready: prefer precedence-ready+ // (drop the connectivity preference — a detached island beats a+ // collision), then fall back to the old head-of-deferred (cycle valve).+ let pick = pick+ .or_else(|| {+ deferred+ .iter()+ .position(|n| preds_ok(n, &placed))+ .map(|pos| deferred.remove(pos))+ })+ .unwrap_or_else(|| deferred.remove(0));+ placed.insert(pick.clone());+ result.push(pick);+ }+ result+}++fn tally_tiers(planned: &[PlannedComponent]) -> Tiers {+ let mut tiers = new_tiers();+ let mut counted: HashSet<String> = HashSet::new();+ for e in planned {+ match e.tier.as_deref() {+ Some("linear") => *tiers.get_mut("linear").unwrap() += 1,+ Some("L") => *tiers.get_mut("l").unwrap() += 1,+ Some("escape") => *tiers.get_mut("escape").unwrap() += 1,+ Some("flagged") => *tiers.get_mut("flagged").unwrap() += 1,+ Some("group") => {+ if e.group_id.is_none() || !counted.contains(e.group_id.as_ref().unwrap()) {+ *tiers.get_mut("group").unwrap() += 1;+ if let Some(g) = &e.group_id {+ counted.insert(g.clone());+ }+ }+ }+ _ => {}+ }+ }+ tiers+}++/// `_verify_sequence`: forward replay; demote a colliding insertion to flagged.+fn verify_sequence(+ sequence: &[String],+ planned: &mut Vec<PlannedComponent>,+ units_by_id: &HashMap<String, Component>,+ fasteners: &HashMap<String, FastenerInfo>,+ path_samples: usize,+ warnings: &mut Vec<String>,+ tolerance: f64,+) {+ let samples_segment = (path_samples / 3).max(12);+ let idx: HashMap<String, usize> = planned+ .iter()+ .enumerate()+ .map(|(i, e)| (e.node_id.clone(), i))+ .collect();+ let mut world = CollisionWorld::new(&[]);+ for node_id in sequence {+ let i = match idx.get(node_id) {+ Some(&i) => i,+ None => continue,+ };+ let part = &units_by_id[node_id];+ let segments = removal_segments(&planned[i].motion);+ match segments {+ None => {+ planned[i].verified = planned[i].tier.as_deref() == Some("base");+ }+ Some(segs) => {+ let blockers = path_blockers(+ part,+ &world,+ &segs,+ samples_segment,+ fasteners,+ None,+ tolerance,+ );+ if !blockers.is_empty() {+ let name = if part.name.is_empty() {+ node_id.clone()+ } else {+ part.name.clone()+ };+ // ASSEMBLER_EXPLAIN=1: demotion autopsy — who blocks the forward+ // replay, how deep, and which exemptions the part carried.+ if std::env::var("ASSEMBLER_EXPLAIN").is_ok() {+ eprintln!(+ "EXPLAIN verify-demote {name} ({node_id}) tier={:?} group={:?} segs={:?}",+ planned[i].tier, planned[i].group_id,+ segs.iter().map(|(d, l)| format!("[{:+.2},{:+.2},{:+.2}]x{l:.1}", d[0], d[1], d[2])).collect::<Vec<_>>()+ );+ let mut offset = Vector3::zeros();+ for (dir, dist) in &segs {+ let me = crate::collide::mate_exempt(part, dir, fasteners);+ let se = crate::collide::seated_exempt(part, dir);+ eprintln!(+ " dir=[{:+.2},{:+.2},{:+.2}] mate_exempt={:?} seated_exempt={:?}",+ dir[0],+ dir[1],+ dir[2],+ me.map(|m| m.into_iter().collect::<Vec<_>>()),+ se.map(|m| m.into_iter().collect::<Vec<_>>()),+ );+ let n = ((samples_segment).max(2)).min(40);+ let mut worst: HashMap<String, f64> = HashMap::new();+ for k in 1..=n {+ let s = *dist * (k as f64) / (n as f64);+ for (o, d) in world.contacts_at(part, &(offset + dir * s)) {+ let e = worst.entry(o).or_insert(0.0);+ if d > *e {+ *e = d;+ }+ }+ }+ let mut w: Vec<_> = worst.into_iter().collect();+ w.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap());+ for (o, d) in w.iter().take(5) {+ let on = units_by_id+ .get(o)+ .map(|p| p.name.clone())+ .filter(|s| !s.is_empty())+ .unwrap_or_else(|| o.clone());+ eprintln!(+ " blocker {on}: max_depth={d:.3} (tol={tolerance:.3})"+ );+ }+ offset += dir * *dist;+ }+ }+ warnings.push(format!(+ "'{name}' failed forward verification; flagged for review — it fades in during playback"+ ));+ planned[i].motion = Motion::None;+ planned[i].tier = Some("flagged".to_string());+ planned[i].confidence = Some("low".to_string());+ planned[i].removal_direction = None;+ let mut bl: Vec<String> = blockers.into_iter().collect();+ bl.sort();+ bl.truncate(crate::consts::MAX_REPORTED_BLOCKERS);+ planned[i].blocked_by = bl;+ planned[i].verified = false;+ } else {+ planned[i].verified = true;+ }+ }+ }+ world.add(node_id, part);+ }+}++fn centroid_bounds(units: &[&Component]) -> (Vector3<f64>, Vector3<f64>, Vector3<f64>) {+ let (lo, hi) = bounds(units);+ ((lo + hi) / 2.0, lo, hi)+}++fn motion_identity(unit: &Component, motion: &Motion) -> String {+ // Python compares identity TUPLES, where -0.0 == 0.0. Motion directions+ // routinely carry -0.0 (negated +0.0), so normalize before formatting or+ // identical parts' identities spuriously differ and the "keep runs of+ // identical parts together" preference breaks.+ let r3 = |c: f64| round_py(c, 3) + 0.0; // -0.0 + 0.0 == +0.0+ let mk = match motion {+ Motion::Linear { direction, .. } => format!(+ "linear:{:.3},{:.3},{:.3}",+ r3(direction[0]),+ r3(direction[1]),+ r3(direction[2])+ ),+ Motion::L { segments } => {+ let mut s = String::from("L");+ for seg in segments {+ s += &format!(+ ":{:.3},{:.3},{:.3}",+ r3(seg.direction[0]),+ r3(seg.direction[1]),+ r3(seg.direction[2])+ );+ }+ s+ }+ Motion::None => "none".to_string(),+ };+ format!("{}|{}", unit.name, mk)+}++/// `_preference_topo_sort`: deterministic scored Kahn's over the precedence DAG.+#[allow(clippy::too_many_arguments)]+pub fn preference_topo_sort(+ planned: &[PlannedComponent],+ units_by_id: &HashMap<String, Component>,+ edges: &Edges,+ fasteners: &HashMap<String, FastenerInfo>,+ joints: &HashMap<String, HashMap<String, f64>>,+ fallback_order: &[String],+ warnings: &mut Vec<String>,+ group_members: &HashMap<String, Vec<String>>,+ fastened: &HashSet<String>,+ contact_count: &HashMap<String, i64>,+ adjacency: Option<&Edges>,+ soft_edges: &Edges,+) -> Vec<String> {+ let units: Vec<&Component> = units_by_id.values().collect();+ let (centroid, amin, amax) = centroid_bounds(&units);+ let diagonal = {+ let n = (amax - amin).norm();+ if n == 0.0 {+ 1.0+ } else {+ n+ }+ };++ let mut fastener_units: HashSet<String> = fasteners.keys().cloned().collect();+ for (rep_id, members) in group_members {+ if members.iter().any(|m| fasteners.contains_key(m)) {+ fastener_units.insert(rep_id.clone());+ }+ }++ let by_id: HashMap<&str, &PlannedComponent> =+ planned.iter().map(|e| (e.node_id.as_str(), e)).collect();+ let base_id = planned+ .iter()+ .find(|e| e.tier.as_deref() == Some("base"))+ .map(|e| e.node_id.clone());++ let empty_members: Vec<String> = Vec::new();+ let is_securing = |node_id: &str| -> bool {+ let candidates = std::iter::once(node_id.to_string()).chain(+ group_members+ .get(node_id)+ .unwrap_or(&empty_members)+ .iter()+ .cloned(),+ );+ for candidate in candidates {+ if let Some(info) = fasteners.get(&candidate) {+ let empty = HashMap::new();+ let joint = joints.get(&candidate).unwrap_or(&empty);+ if joint.keys().any(|member| {+ !info.mates.contains_key(member) && Some(member) != base_id.as_ref()+ }) {+ return true;+ }+ }+ }+ false+ };++ // predecessors+ let mut predecessors: HashMap<String, HashSet<String>> =+ edges.keys().map(|k| (k.clone(), HashSet::new())).collect();+ for (before, afters) in edges {+ for after in afters {+ predecessors.get_mut(after).unwrap().insert(before.clone());+ }+ }+ let mut soft_predecessors: HashMap<String, HashSet<String>> =+ edges.keys().map(|k| (k.clone(), HashSet::new())).collect();+ for (before, afters) in soft_edges {+ for after in afters {+ if let Some(s) = soft_predecessors.get_mut(after) {+ s.insert(before.clone());+ }+ }+ }+ let outgoing = |node_id: &str| -> bool {+ edges.get(node_id).map(|s| !s.is_empty()).unwrap_or(false)+ || soft_edges+ .get(node_id)+ .map(|s| !s.is_empty())+ .unwrap_or(false)+ };++ let is_weakly_secured = |node_id: &str, placed_set: &HashSet<String>| -> bool {+ let _ = placed_set;+ if fastener_units.contains(node_id) {+ return false;+ }+ let entry = by_id[node_id];+ if !matches!(entry.tier.as_deref(), Some("linear") | Some("L")) {+ return false;+ }+ if units_by_id[node_id].is_proxy {+ return false;+ }+ if outgoing(node_id) {+ return false;+ }+ let members: Vec<String> = std::iter::once(node_id.to_string())+ .chain(+ group_members+ .get(node_id)+ .unwrap_or(&empty_members)+ .iter()+ .cloned(),+ )+ .collect();+ if members.iter().any(|m| fastened.contains(m)) {+ return false;+ }+ members+ .iter()+ .map(|m| contact_count.get(m).cloned().unwrap_or(0))+ .max()+ .unwrap_or(0)+ == 1+ };++ let empty_set: HashSet<String> = HashSet::new();+ let mut placed: Vec<String> = Vec::new();+ let mut placed_set: HashSet<String> = HashSet::new();+ let mut pending: HashSet<String> = edges.keys().cloned().collect();+ let mut previous_identity: Option<String> = None;++ while !pending.is_empty() {+ let mut available: Vec<String> = pending+ .iter()+ .filter(|n| predecessors[*n].is_subset(&placed_set))+ .cloned()+ .collect();+ if available.is_empty() {+ warnings.push(+ "precedence cycle detected; keeping the greedy order for the remaining parts"+ .to_string(),+ );+ for n in fallback_order {+ if pending.contains(n) {+ placed.push(n.clone());+ }+ }+ break;+ }++ if let Some(adj) = adjacency {+ if !placed_set.is_empty() {+ let touching: Vec<String> = available+ .iter()+ .filter(|n| {+ adj.get(*n)+ .unwrap_or(&empty_set)+ .intersection(&placed_set)+ .next()+ .is_some()+ })+ .cloned()+ .collect();+ if !touching.is_empty() {+ available = touching;+ } else {+ let pending_touchers: Vec<String> = pending+ .iter()+ .filter(|n| {+ adj.get(*n)+ .unwrap_or(&empty_set)+ .intersection(&placed_set)+ .next()+ .is_some()+ })+ .cloned()+ .collect();+ if !pending_touchers.is_empty() {+ let mut need: HashSet<String> = HashSet::new();+ let mut stack = pending_touchers.clone();+ while let Some(node) = stack.pop() {+ for before in predecessors.get(&node).unwrap_or(&empty_set) {+ if !placed_set.contains(before) && need.insert(before.clone()) {+ stack.push(before.clone());+ }+ }+ }+ let gated: Vec<String> = available+ .iter()+ .filter(|n| need.contains(*n))+ .cloned()+ .collect();+ if !gated.is_empty() {+ available = gated;+ }+ } else {+ let anchor = available+ .iter()+ .max_by(|a, b| {+ let ka = (+ adj.get(*a).map(|s| s.len()).unwrap_or(0),+ part_volume(&units_by_id[*a]),+ (*a).clone(),+ );+ let kb = (+ adj.get(*b).map(|s| s.len()).unwrap_or(0),+ part_volume(&units_by_id[*b]),+ (*b).clone(),+ );+ ka.0.cmp(&kb.0)+ .then(ka.1.partial_cmp(&kb.1).unwrap())+ .then(ka.2.cmp(&kb.2))+ })+ .unwrap()+ .clone();+ let name = {+ let u = &units_by_id[&anchor];+ if u.name.is_empty() {+ anchor.clone()+ } else {+ u.name.clone()+ }+ };+ warnings.push(format!(+ "'{name}' starts a detached island — nothing already placed touches it"+ ));+ available = vec![anchor];+ }+ }+ }+ }++ let key_of = |node_id: &str| -> (Vec<f64>, String) {+ let entry = by_id[node_id];+ let unit = &units_by_id[node_id];+ let ident = motion_identity(unit, &entry.motion);+ let (sv, sb) = structural_key(unit, ¢roid, diagonal);+ let flagged_pref = entry.tier.as_deref() == Some("flagged")+ && !fastener_units.contains(node_id)+ && entry.blocked_by.iter().any(|b| pending.contains(b));+ let soft_present = !soft_predecessors+ .get(node_id)+ .unwrap_or(&empty_set)+ .is_subset(&placed_set);+ let key = vec![+ if entry.tier.as_deref() == Some("base") {+ 0.0+ } else {+ 1.0+ },+ if previous_identity.as_deref() == Some(ident.as_str()) {+ 0.0+ } else {+ 1.0+ },+ if is_securing(node_id) { 0.0 } else { 1.0 },+ if flagged_pref { 0.0 } else { 1.0 },+ if soft_present { 1.0 } else { 0.0 },+ if outgoing(node_id) { 0.0 } else { 1.0 },+ if is_weakly_secured(node_id, &placed_set) {+ 1.0+ } else {+ 0.0+ },+ sv,+ sb,+ unit.bbox_min[2],+ ];+ (key, node_id.to_string())+ };++ let chosen = available+ .iter()+ .min_by(|a, b| {+ let ka = key_of(a);+ let kb = key_of(b);+ for (x, y) in ka.0.iter().zip(kb.0.iter()) {+ match x.partial_cmp(y).unwrap() {+ std::cmp::Ordering::Equal => continue,+ o => return o,+ }+ }+ ka.1.cmp(&kb.1)+ })+ .unwrap()+ .clone();+ previous_identity = Some(motion_identity(+ &units_by_id[&chosen],+ &by_id[chosen.as_str()].motion,+ ));+ placed.push(chosen.clone());+ placed_set.insert(chosen.clone());+ pending.remove(&chosen);+ }++ if let Some(adj) = adjacency {+ // The repair may not reorder a part above one of its collision+ // predecessors, or the forward-verification pass demotes it later.+ placed = connectivity_repair(&placed, adj, Some(edges));+ }+ placed+}++/// Auto-detect "detail swarms" — a populated PCB's board carrying dozens to+/// hundreds of tiny components — from pure geometry, and emit `merge_units`+/// specs (`(id, name, member_node_ids)`) so each board plans as ONE rigid unit.+///+/// Shape: a substantial HOST part with many TINY parts seated on it. Seeding+/// uses narrowphase contact distance (a hollow enclosure's bbox contains+/// everything, so bbox overlap can't tell "inside" from "mounted on"), then+/// grows transitively over bbox proximity for stacked components (IC on board,+/// cap on IC). Fastener-named parts never join a swarm — screws keep their own+/// removal animations. `skip` holds ids already consumed by caller/authored+/// units (never re-swallowed; a merged unit body is non-tiny anyway).+pub fn detect_swarm_units(+ parts: &[Component],+ skip: &HashSet<String>,+) -> Vec<(String, Option<String>, Vec<String>)> {+ let refs: Vec<&Component> = parts.iter().collect();+ if refs.len() < SWARM_MIN_MEMBERS + 1 {+ return Vec::new();+ }+ let (alo, ahi) = bounds(&refs);+ let asm_diag = (ahi - alo).norm().max(1.0);+ let diag = |p: &Component| (p.bbox_max - p.bbox_min).norm();+ let tiny_limit = SWARM_TINY_FRACTION * asm_diag;++ let eligible = |p: &Component| !skip.contains(&p.node_id) && !crate::fasteners::is_fastener(p);+ let mut hosts: Vec<usize> = (0..parts.len())+ .filter(|&i| eligible(&parts[i]) && diag(&parts[i]) >= tiny_limit)+ .collect();+ // Largest-first so the board outranks brackets when distances tie.+ hosts.sort_by(|&a, &b| diag(&parts[b]).total_cmp(&diag(&parts[a])));+ let tiny: Vec<usize> = (0..parts.len())+ .filter(|&i| eligible(&parts[i]) && diag(&parts[i]) < tiny_limit)+ .collect();+ if hosts.is_empty() || tiny.len() < SWARM_MIN_MEMBERS {+ return Vec::new();+ }++ let overlaps = |p: &Component, q: &Component, pad: f64| -> bool {+ (0..3).all(|k| p.bbox_min[k] - pad <= q.bbox_max[k] && q.bbox_min[k] - pad <= p.bbox_max[k])+ };++ // Seed: each tiny part joins the nearest host it CONTACTS (bbox prefilter,+ // then exact narrowphase distance over the cached BVHs) — and only a host+ // that DWARFS it. "Tiny vs the assembly" alone misfires on large models+ // whose mid-size parts sit on a rail; a PCB component is ~1% of its board.+ let dwarfed_by = |t: usize, h: usize| diag(&parts[t]) < SWARM_HOST_FRACTION * diag(&parts[h]);+ let mut member_host: HashMap<usize, usize> = HashMap::new();+ for &t in &tiny {+ let mut best: Option<(f64, usize)> = None;+ for &h in &hosts {+ if !dwarfed_by(t, h) || !overlaps(&parts[t], &parts[h], SWARM_CONTACT_MM) {+ continue;+ }+ let d = collision::distance_pair(&parts[t].bvh(), &parts[h].bvh());+ if d <= SWARM_CONTACT_MM && best.is_none_or(|(bd, _)| d < bd) {+ best = Some((d, h));+ }+ }+ if let Some((_, h)) = best {+ member_host.insert(t, h);+ }+ }++ // Grow: unassigned tiny parts touching (bbox proximity) an assigned member+ // join that member's swarm — stacked components don't touch the board.+ loop {+ let mut grew = false;+ for &t in &tiny {+ if member_host.contains_key(&t) {+ continue;+ }+ let joined = member_host+ .iter()+ .find(|&(&m, &h)| {+ dwarfed_by(t, h) && overlaps(&parts[t], &parts[m], GROUP_PROXIMITY_MM)+ })+ .map(|(_, &h)| h);+ if let Some(h) = joined {+ member_host.insert(t, h);+ grew = true;+ }+ }+ if !grew {+ break;+ }+ }++ let mut by_host: HashMap<usize, Vec<usize>> = HashMap::new();+ for (&m, &h) in &member_host {+ by_host.entry(h).or_default().push(m);+ }++ // Absorb: a host that already carries a real tiny swarm is a populated+ // board. Sweep in any remaining eligible part that CONTACTS such a host and+ // is still clearly smaller than it (SWARM_ABSORB_FRACTION, looser than the+ // strict tiny gate) — a chip or connector mounted on the board, which the+ // tiny gate leaves loose (it's above tiny_limit, so it was a host candidate+ // with no members of its own). Gated on the host ALREADY being a swarm, so a+ // bare rail never absorbs its mid-size rollers.+ let swarm_hosts: Vec<usize> = by_host+ .iter()+ .filter(|(_, members)| members.len() >= SWARM_MIN_MEMBERS)+ .map(|(&h, _)| h)+ .collect();+ if !swarm_hosts.is_empty() {+ let absorbed_by =+ |t: usize, h: usize| diag(&parts[t]) < SWARM_ABSORB_FRACTION * diag(&parts[h]);+ let mut absorbed: Vec<(usize, usize)> = Vec::new();+ for i in 0..parts.len() {+ if !eligible(&parts[i])+ || member_host.contains_key(&i)+ || swarm_hosts.contains(&i)+ {+ continue;+ }+ let mut best: Option<(f64, usize)> = None;+ for &h in &swarm_hosts {+ if !absorbed_by(i, h) || !overlaps(&parts[i], &parts[h], SWARM_CONTACT_MM) {+ continue;+ }+ let d = collision::distance_pair(&parts[i].bvh(), &parts[h].bvh());+ if d <= SWARM_CONTACT_MM && best.is_none_or(|(bd, _)| d < bd) {+ best = Some((d, h));+ }+ }+ if let Some((_, h)) = best {+ absorbed.push((i, h));+ }+ }+ for (i, h) in absorbed {+ member_host.insert(i, h);+ by_host.entry(h).or_default().push(i);+ }+ }++ let mut specs: Vec<(String, Option<String>, Vec<String>)> = Vec::new();+ for &h in &hosts {+ let Some(members) = by_host.get(&h) else {+ continue;+ };+ if members.len() < SWARM_MIN_MEMBERS {+ continue;+ }+ // Host + members, host first. Distinct "swarm:" id namespace so the+ // group id can never collide with a member nodeId.+ let mut node_ids = vec![parts[h].node_id.clone()];+ let mut sorted = members.clone();+ sorted.sort();+ node_ids.extend(sorted.iter().map(|&m| parts[m].node_id.clone()));+ specs.push((+ format!("swarm:{}", parts[h].node_id),+ Some(parts[h].name.clone()),+ node_ids,+ ));+ }+ specs+}++/// `_merge_units`: merge each multi-member caller unit into one rigid body.+pub fn merge_units(+ parts: &[Component],+ units_spec: &[(String, Option<String>, Vec<String>)],+) -> (+ Vec<Component>,+ HashMap<String, (Vec<String>, Option<String>)>,+) {+ let by_id: HashMap<&str, &Component> = parts.iter().map(|p| (p.node_id.as_str(), p)).collect();+ let mut expansion: HashMap<String, (Vec<String>, Option<String>)> = HashMap::new();+ let mut consumed: HashSet<String> = HashSet::new();+ let mut merged: Vec<Component> = Vec::new();+ for (uid, name, node_ids) in units_spec {+ let members: Vec<String> = node_ids+ .iter()+ .filter(|n| by_id.contains_key(n.as_str()) && !consumed.contains(*n))+ .cloned()+ .collect();+ if uid.is_empty() || members.len() <= 1 {+ continue;+ }+ let member_refs: Vec<&Component> = members.iter().map(|m| by_id[m.as_str()]).collect();+ let meshes: Vec<&crate::types::Mesh> = member_refs.iter().map(|m| &m.mesh).collect();+ let combined_mesh = crate::types::Mesh::concatenate(&meshes);+ let (lo, hi) = bounds(&member_refs);+ let cname = name+ .clone()+ .unwrap_or_else(|| by_id[members[0].as_str()].name.clone());+ let combined = Component::new(+ uid.clone(),+ cname,+ combined_mesh,+ lo,+ hi,+ member_refs.iter().any(|m| m.is_proxy),+ );+ merged.push(combined);+ expansion.insert(uid.clone(), (members.clone(), name.clone()));+ consumed.extend(members);+ }+ let mut remaining: Vec<Component> = parts+ .iter()+ .filter(|p| !consumed.contains(&p.node_id))+ .cloned()+ .collect();+ remaining.extend(merged);+ (remaining, expansion)+}++fn fill_contact_normals(parts: &mut [Component], pair_depths: &PairDepths) {+ let idx: HashMap<String, usize> = parts+ .iter()+ .enumerate()+ .map(|(i, p)| (p.node_id.clone(), i))+ .collect();+ let mut keys: Vec<&(String, String)> = pair_depths.keys().collect();+ keys.sort();+ for k in keys {+ let data = &pair_depths[k];+ for node in [&data.a, &data.b] {+ if let Some(&i) = idx.get(node) {+ if parts[i].contact_normals.len() < 128 {+ parts[i]+ .contact_normals+ .extend(data.normals.iter().cloned());+ }+ }+ }+ }+}++/// `_plan_parts`: the full pipeline over world-space parts.+pub fn plan_parts(+ mut parts: Vec<Component>,+ clearance: f64,+ path_samples: usize,+ tolerance: f64,+ protected: Option<&HashSet<String>>,+ warnings: &mut Vec<String>,+) -> PlanOutcome {+ let _timing = std::env::var("ASSEMBLER_TIMING").is_ok();+ let mut _t = std::time::Instant::now();+ macro_rules! lap {+ ($n:expr) => {+ if _timing {+ eprintln!(" [{}] {:.2}s", $n, _t.elapsed().as_secs_f64());+ _t = std::time::Instant::now();+ }+ };+ }+ let pair_depths = seated_pair_depths(&parts);+ lap!("seated_pair_depths");+ let leaf_adjacency = ordering_adjacency(&parts, &pair_depths, ORDERING_CONTACT_MM);+ fill_contact_normals(&mut parts, &pair_depths);++ let mut fasteners = classify_fasteners(&parts, &pair_depths);+ lap!("classify");+ let (mut units, mut merged_into) =+ merge_rigid_groups(&parts, &pair_depths, &fasteners, warnings);+ lap!("merge_rigid");++ // Joints over original parts, then remap through merges.+ let mut joints = fastener_joints(&parts, &fasteners);+ lap!("fastener_joints");+ if !merged_into.is_empty() {+ let mut remapped: HashMap<String, HashMap<String, f64>> = HashMap::new();+ for (fid, members) in &joints {+ if merged_into.contains_key(fid) {+ continue;+ }+ let mut entry: HashMap<String, f64> = HashMap::new();+ for (member, projection) in members {+ let unit = merged_into+ .get(member)+ .cloned()+ .unwrap_or_else(|| member.clone());+ if &unit == fid {+ continue;+ }+ let take = !entry.contains_key(&unit) || projection.abs() < entry[&unit].abs();+ if take {+ entry.insert(unit, *projection);+ }+ }+ remapped.insert(fid.clone(), entry);+ }+ joints = remapped;+ }+ for (fid, members) in &joints {+ if let Some(info) = fasteners.get_mut(fid) {+ for member in members.keys() {+ if !info.mates.contains_key(member) {+ info.sliding.insert(member.clone(), tolerance);+ }+ }+ }+ }++ let sandwiches = sandwiched_parts(&mut units, &pair_depths, &fasteners, &merged_into);+ lap!("sandwiched");++ // fastened set+ let fastened: HashSet<String> = joints.values().flat_map(|m| m.keys().cloned()).collect();++ // contact_count (unit-level, fastener-excluded, deduped)+ let mut contact_count: HashMap<String, i64> = HashMap::new();+ let mut counted_pairs: HashSet<(String, String)> = HashSet::new();+ for data in pair_depths.values() {+ let unit_a = merged_into+ .get(&data.a)+ .cloned()+ .unwrap_or_else(|| data.a.clone());+ let unit_b = merged_into+ .get(&data.b)+ .cloned()+ .unwrap_or_else(|| data.b.clone());+ if unit_a == unit_b {+ continue;+ }+ let pk = pair_key(&unit_a, &unit_b);+ if !counted_pairs.insert(pk) {+ continue;+ }+ for (me, other) in [(&unit_a, &unit_b), (&unit_b, &unit_a)] {+ if fasteners.contains_key(other) {+ continue;+ }+ *contact_count.entry(me.clone()).or_insert(0) += 1;+ }+ }++ // deep_bitten+ let mut deep_bitten: HashSet<String> = HashSet::new();+ for (k, data) in &pair_depths {+ let _ = k;+ if data.depth > 1.0 {+ for node in [&data.a, &data.b] {+ let other = data.other(node);+ if let Some(info) = fasteners.get(node) {+ if info.mates.contains_key(other) {+ continue;+ }+ }+ let unit = merged_into+ .get(node)+ .cloned()+ .unwrap_or_else(|| node.clone());+ if sandwiches.contains_key(&unit) {+ continue;+ }+ deep_bitten.insert(node.clone());+ }+ }+ }++ let sandwiched_set: HashSet<String> = sandwiches.keys().cloned().collect();+ let mut group_units: HashMap<String, (Component, Vec<String>)> = HashMap::new();+ let mut late_merges: HashMap<String, String> = HashMap::new();+ let (mut planned, greedy_sequence, _greedy_tiers) = greedy_disassembly(+ &units,+ clearance,+ path_samples,+ tolerance,+ &fasteners,+ &deep_bitten,+ &sandwiched_set,+ protected,+ &mut group_units,+ &mut late_merges,+ warnings,+ );+ lap!("greedy");++ // Chase late-merge chains.+ if !late_merges.is_empty() {+ let keys: Vec<String> = late_merges.keys().cloned().collect();+ for member in keys {+ let mut host = late_merges[&member].clone();+ while late_merges.contains_key(&host) {+ host = late_merges[&host].clone();+ }+ late_merges.insert(member, host);+ }+ for (m, h) in &late_merges {+ merged_into.insert(m.clone(), h.clone());+ }+ }++ // units_by_id (final planning units).+ let mut units_by_id: HashMap<String, Component> =+ units.into_iter().map(|u| (u.node_id.clone(), u)).collect();+ for member in late_merges.keys() {+ units_by_id.remove(member);+ }+ for (rep_id, (combined, members)) in &group_units {+ units_by_id.insert(rep_id.clone(), combined.clone());+ for m in members {+ if m != rep_id {+ units_by_id.remove(m);+ }+ }+ }++ let unit_adjacency =+ rollup_adjacency(&leaf_adjacency, &merged_into, &group_units, &units_by_id);+ // Relatedness: strict contact plus clearance-fit neighbors, so parts a+ // fastener/slip-fit holds together across a gap are sequenced adjacently+ // instead of appearing as detached floating islands. Collision correctness+ // stays on `unit_adjacency`/hard edges; this only softens the connectivity+ // preference and feeds the emitted viewer contact graph.+ let relatedness = {+ let refs: Vec<&Component> = parts.iter().collect();+ let (amin, amax) = bounds(&refs);+ let mm = crate::consts::relatedness_mm((amax - amin).norm());+ let leaf = ordering_adjacency(&parts, &pair_depths, mm);+ rollup_adjacency(&leaf, &merged_into, &group_units, &units_by_id)+ };+ reselect_base(+ &mut planned,+ &units_by_id,+ &unit_adjacency,+ &fasteners,+ warnings,+ );++ // Recompute flagged-structural blockers against the full seated assembly.+ let flagged_ids: Vec<String> = planned+ .iter()+ .filter(|e| {+ e.tier.as_deref() == Some("flagged")+ && units_by_id.contains_key(&e.node_id)+ && !fasteners.contains_key(&e.node_id)+ })+ .map(|e| e.node_id.clone())+ .collect();+ if !flagged_ids.is_empty() {+ let seated_units: Vec<&Component> = units_by_id.values().collect();+ let seated_world = CollisionWorld::new(&seated_units);+ for id in &flagged_ids {+ let part = &units_by_id[id];+ let others = others_excluding(&units_by_id, id);+ let blockers = crate::greedy::escape_blockers(+ part,+ &units_by_id,+ &others,+ &seated_world,+ &fasteners,+ tolerance,+ path_samples,+ );+ if !blockers.is_empty() {+ let i = planned.iter().position(|e| &e.node_id == id).unwrap();+ planned[i].blocked_by = blockers;+ }+ }+ }++ let mut edges = derive_precedence(&planned, &units_by_id, &fasteners, path_samples, tolerance);+ lap!("derive_precedence");+ add_joint_edges(&fasteners, &joints, &units_by_id, &mut edges, warnings);++ let mut soft_edges: Edges = units_by_id+ .keys()+ .map(|k| (k.clone(), HashSet::new()))+ .collect();+ add_sandwich_edges(+ &sandwiches,+ &units_by_id,+ &merged_into,+ &mut soft_edges,+ warnings,+ );+ add_support_edges(+ &parts,+ &pair_depths,+ &fasteners,+ &merged_into,+ &mut soft_edges,+ warnings,+ );++ let base_id = planned+ .iter()+ .find(|e| e.tier.as_deref() == Some("base"))+ .map(|e| e.node_id.clone());+ if let Some(bid) = &base_id {+ for afters in edges.values_mut() {+ afters.remove(bid);+ }+ for afters in soft_edges.values_mut() {+ afters.remove(bid);+ }+ }++ let group_members: HashMap<String, Vec<String>> = group_units+ .iter()+ .map(|(rep, (_c, members))| (rep.clone(), members.clone()))+ .collect();++ let mut sequence = preference_topo_sort(+ &planned,+ &units_by_id,+ &edges,+ &fasteners,+ &joints,+ &greedy_sequence,+ warnings,+ &group_members,+ &fastened,+ &contact_count,+ Some(&relatedness),+ &soft_edges,+ );++ // ASSEMBLER_EXPLAIN=1: sanity-check the GREEDY order first — greedy's own+ // sequence is supposed to be collision-consistent by construction, so any+ // demotion here means greedy emitted a colliding motion (validation bug),+ // while a clean pass pins the blame on the reordering machinery.+ if std::env::var("ASSEMBLER_EXPLAIN").is_ok() {+ let mut probe = planned.clone();+ let mut w2: Vec<String> = Vec::new();+ verify_sequence(+ &greedy_sequence,+ &mut probe,+ &units_by_id,+ &fasteners,+ path_samples,+ &mut w2,+ tolerance,+ );+ let demoted = w2+ .iter()+ .filter(|w| w.contains("forward verification"))+ .count();+ eprintln!("EXPLAIN greedy-order verify: {demoted} demotions (final-order comes below)");+ }++ // ASSEMBLER_EXPLAIN=1: report hard precedence edges the FINAL sequence+ // violates (the collision-consistency contract the topo sort + repair are+ // supposed to preserve; each violation is a forward-verify failure waiting).+ if std::env::var("ASSEMBLER_EXPLAIN").is_ok() {+ let pos: HashMap<&String, usize> =+ sequence.iter().enumerate().map(|(i, s)| (s, i)).collect();+ for (before, afters) in &edges {+ for after in afters {+ if let (Some(&pb), Some(&pa)) = (pos.get(before), pos.get(after)) {+ if pb > pa {+ let nm = |id: &String| {+ units_by_id+ .get(id)+ .map(|p| p.name.clone())+ .filter(|s| !s.is_empty())+ .unwrap_or_else(|| id.clone())+ };+ eprintln!(+ "EXPLAIN edge-violated: '{}'({}) must precede '{}'({}) but seq has {} > {}",+ nm(before), &before[..8], nm(after), &after[..8], pb, pa+ );+ }+ }+ }+ }+ }++ verify_sequence(+ &sequence,+ &mut planned,+ &units_by_id,+ &fasteners,+ path_samples,+ warnings,+ tolerance,+ );+ lap!("verify_sequence");++ // Expand subassembly units into their members.+ let mut groups_payload: BTreeMap<String, GroupPayload> = BTreeMap::new();+ if !group_units.is_empty() {+ let mut group_ids: HashMap<String, String> = HashMap::new();+ let mut counter = 0;+ for node in &sequence {+ if group_units.contains_key(node) {+ counter += 1;+ group_ids.insert(node.clone(), format!("g{counter}"));+ }+ }+ let mut expanded: Vec<String> = Vec::new();+ for node in &sequence {+ if let Some((_c, members)) = group_units.get(node) {+ expanded.extend(members.iter().cloned());+ } else {+ expanded.push(node.clone());+ }+ }+ sequence = expanded;++ for (rep_id, (_combined, members)) in &group_units {+ let gid = group_ids[rep_id].clone();+ let rep_i = planned.iter().position(|e| &e.node_id == rep_id).unwrap();+ planned[rep_i].group_id = Some(gid.clone());+ let rep = planned[rep_i].clone();+ groups_payload.insert(+ gid.clone(),+ GroupPayload {+ component_node_ids: members.clone(),+ motion: rep.motion.clone(),+ name: None,+ },+ );+ for member_id in members {+ if member_id == rep_id {+ continue;+ }+ planned.push(PlannedComponent {+ node_id: member_id.clone(),+ motion: rep.motion.clone(),+ confidence: rep.confidence.clone(),+ removal_direction: rep.removal_direction,+ blocked_by: rep.blocked_by.clone(),+ tier: rep.tier.clone(),+ verified: rep.verified,+ group_id: Some(gid.clone()),+ });+ }+ }+ }++ let tiers = tally_tiers(&planned);+ let verified_count = planned.iter().filter(|e| e.verified).count() as i64;+ let needs_support =+ crate::stability::support_check(&sequence, &parts, &pair_depths, &fasteners);+ let waves = compute_waves(&edges);+ PlanOutcome {+ planned,+ sequence,+ tiers,+ merged_into,+ groups: groups_payload,+ verified_count,+ edges,+ adjacency: unit_adjacency,+ relatedness,+ needs_support,+ waves,+ }+}++/// `_plan_fixed_sequence`: caller-fixed order + grouping; compute each group's+/// forward-collision insertion motion (no reordering).+pub fn plan_fixed_sequence(+ mut parts: Vec<Component>,+ groups_in_order: &[Vec<String>],+ clearance: f64,+ path_samples: usize,+ tolerance: f64,+ warnings: &mut Vec<String>,+) -> PlanOutcome {+ let by_id: HashSet<String> = parts.iter().map(|p| p.node_id.clone()).collect();++ // Map caller groups onto present, unclaimed leaves.+ let mut cleaned_groups: Vec<Vec<String>> = Vec::new();+ let mut consumed: HashSet<String> = HashSet::new();+ for (index, group) in groups_in_order.iter().enumerate() {+ let mut members: Vec<String> = Vec::new();+ for node_id in group {+ if !by_id.contains(node_id) {+ warnings.push(format!(+ "group {}: nodeId '{node_id}' is not in the model; dropped",+ index + 1+ ));+ continue;+ }+ if consumed.contains(node_id) {+ warnings.push(format!(+ "group {}: nodeId '{node_id}' already belongs to an earlier group; dropped",+ index + 1+ ));+ continue;+ }+ members.push(node_id.clone());+ consumed.insert(node_id.clone());+ }+ if members.is_empty() {+ warnings.push(format!(+ "group {} has no parts present in the model; skipped",+ index + 1+ ));+ continue;+ }+ cleaned_groups.push(members);+ }++ if cleaned_groups.is_empty() {+ return PlanOutcome {+ planned: Vec::new(),+ sequence: Vec::new(),+ tiers: new_tiers(),+ merged_into: HashMap::new(),+ groups: BTreeMap::new(),+ verified_count: 0,+ edges: HashMap::new(),+ adjacency: HashMap::new(),+ relatedness: HashMap::new(),+ needs_support: HashSet::new(),+ waves: HashMap::new(),+ };+ }++ // Classification over the sequence parts only.+ let seq_unfilled: Vec<Component> = parts+ .iter()+ .filter(|p| consumed.contains(&p.node_id))+ .cloned()+ .collect();+ let pair_depths = seated_pair_depths(&seq_unfilled);+ fill_contact_normals(&mut parts, &pair_depths);+ let seq_parts: Vec<Component> = parts+ .iter()+ .filter(|p| consumed.contains(&p.node_id))+ .cloned()+ .collect();+ let fasteners = classify_fasteners(&seq_parts, &pair_depths);++ // Each group → one rigid body (single-member groups stay as the leaf).+ let units_spec: Vec<(String, Option<String>, Vec<String>)> = cleaned_groups+ .iter()+ .map(|m| (m[0].clone(), None, m.clone()))+ .collect();+ let (merged_parts, _expansion) = merge_units(&parts, &units_spec);+ let merged_by_id: HashMap<String, Component> = merged_parts+ .into_iter()+ .map(|p| (p.node_id.clone(), p))+ .collect();+ let groups_ordered: Vec<(String, Component, Vec<String>)> = cleaned_groups+ .iter()+ .enumerate()+ .map(|(i, m)| {+ (+ format!("g{}", i + 1),+ merged_by_id[&m[0]].clone(),+ m.clone(),+ )+ })+ .collect();++ let all_bodies: Vec<&Component> = groups_ordered.iter().map(|(_, b, _)| b).collect();++ let mut placed: HashMap<String, Component> = HashMap::new();+ let mut planned: Vec<PlannedComponent> = Vec::new();+ let mut units_by_id: HashMap<String, Component> = HashMap::new();++ // Persistent broadphase: `full_world` = every sequence body; `placed_world`+ // grows as bodies are placed (the forward-collision set).+ let full_world = CollisionWorld::new(&all_bodies);+ let mut placed_world = CollisionWorld::new(&[]);++ for (order_index, (_label, body, _members)) in groups_ordered.iter().enumerate() {+ units_by_id.insert(body.node_id.clone(), body.clone());+ let entry = if order_index == 0 {+ PlannedComponent {+ node_id: body.node_id.clone(),+ motion: Motion::None,+ confidence: Some("high".to_string()),+ removal_direction: None,+ blocked_by: Vec::new(),+ tier: Some("base".to_string()),+ verified: false,+ group_id: None,+ }+ } else {+ let mut remaining_map: HashMap<String, Component> = placed.clone();+ remaining_map.insert(body.node_id.clone(), body.clone());+ let others: Vec<&Component> = placed.values().collect();+ let mut e = plan_removal(+ body,+ &remaining_map,+ &others,+ &placed_world,+ Some(&full_world),+ clearance,+ path_samples,+ &fasteners,+ tolerance,+ );+ if e.is_none() {+ e = plan_escape(+ body,+ &others,+ &placed_world,+ path_samples,+ &fasteners,+ tolerance,+ );+ }+ match e {+ Some(e) => e,+ None => {+ let name = if body.name.is_empty() {+ body.node_id.clone()+ } else {+ body.name.clone()+ };+ warnings.push(format!(+ "'{name}' has no collision-free insertion after the earlier groups; flagged for review — it fades in during playback"+ ));+ let blocked_by = crate::greedy::escape_blockers(+ body,+ &remaining_map,+ &others,+ &placed_world,+ &fasteners,+ tolerance,+ path_samples,+ );+ PlannedComponent {+ node_id: body.node_id.clone(),+ motion: Motion::None,+ confidence: Some("low".to_string()),+ removal_direction: None,+ blocked_by,+ tier: Some("flagged".to_string()),+ verified: false,+ group_id: None,+ }+ }+ }+ };+ planned.push(entry);+ placed_world.add(&body.node_id, body);+ placed.insert(body.node_id.clone(), body.clone());+ }++ let sequence_bodies: Vec<String> = groups_ordered+ .iter()+ .map(|(_, b, _)| b.node_id.clone())+ .collect();+ verify_sequence(+ &sequence_bodies,+ &mut planned,+ &units_by_id,+ &fasteners,+ path_samples,+ warnings,+ tolerance,+ );+ let tiers = tally_tiers(&planned);++ // Expand each group body back to its member leaves.+ let mut groups_payload: BTreeMap<String, GroupPayload> = BTreeMap::new();+ let mut expanded: Vec<PlannedComponent> = Vec::new();+ let mut sequence: Vec<String> = Vec::new();+ for (label, body, members) in &groups_ordered {+ let rep_i = planned+ .iter()+ .position(|e| e.node_id == body.node_id)+ .unwrap();+ planned[rep_i].group_id = Some(label.clone());+ let rep = planned[rep_i].clone();+ groups_payload.insert(+ label.clone(),+ GroupPayload {+ component_node_ids: members.clone(),+ motion: rep.motion.clone(),+ name: None,+ },+ );+ sequence.extend(members.iter().cloned());+ for member_id in members {+ if member_id == &body.node_id {+ expanded.push(rep.clone());+ } else {+ expanded.push(PlannedComponent {+ node_id: member_id.clone(),+ motion: rep.motion.clone(),+ confidence: rep.confidence.clone(),+ removal_direction: rep.removal_direction,+ blocked_by: rep.blocked_by.clone(),+ tier: rep.tier.clone(),+ verified: rep.verified,+ group_id: Some(label.clone()),+ });+ }+ }+ }++ let verified_count = expanded.iter().filter(|e| e.verified).count() as i64;+ let needs_support =+ crate::stability::support_check(&sequence, &parts, &pair_depths, &fasteners);+ PlanOutcome {+ planned: expanded,+ sequence,+ tiers,+ merged_into: HashMap::new(),+ groups: groups_payload,+ verified_count,+ edges: HashMap::new(),+ adjacency: HashMap::new(),+ relatedness: HashMap::new(),+ needs_support,+ waves: HashMap::new(),+ }+}diff --git a/crates/planner/src/stability.rs b/crates/planner/src/stability.rsnew file mode 100644index 0000000000..ef1a9f7e0a--- /dev/null+++ b/crates/planner/src/stability.rs@@ -0,0 +1,245 @@+//! Post-plan support-polygon stability check. Purely diagnostic and additive:+//! for each part, in final placement order, does its center of mass project+//! inside the convex hull of the contact points from ALREADY-PLACED parts that+//! support it from below? If not, the part will tip and needs holding — the+//! planner surfaces that as `needsSupport` on the step.+//!+//! Reads only geometry already computed upstream (PairData contact points ++//! normals, Component bboxes). No collision queries, no physics engine, no new+//! dependency. Gravity is -Z (matching `add_support_edges`), so the support+//! polygon lives in the XY plane and the CoM proxy is the bbox center.++use std::collections::{HashMap, HashSet};++use nalgebra::Vector3;++use crate::pipeline::{PairData, PairDepths};+use crate::types::{Component, FastenerInfo};++/// Fraction of a pair's mean contact normal that must align with gravity (Z)+/// for the pair to count as a vertical support rather than a side contact.+const SUPPORT_NORMAL_MIN_Z: f64 = 0.5;+/// The CoM must fall at least this far (mm) OUTSIDE the support hull before we+/// flag it — a part whose CoM sits right on the boundary isn't reported.+const SUPPORT_MARGIN_MM: f64 = 0.5;+/// Fewer than this many supporting contact points is a line/point contact, not+/// a gravity-resting seat (press-fit / mated / base) — never flagged.+const MIN_SUPPORT_POINTS: usize = 3;++/// 2D monotone-chain convex hull. Points are `[x, y]`; output is the hull in+/// counter-clockwise order with no repeated vertex. Degenerate inputs (< 3+/// unique points) are returned as-is (the caller treats those as no polygon).+pub fn convex_hull_2d(points: &[[f64; 2]]) -> Vec<[f64; 2]> {+ let mut pts: Vec<[f64; 2]> = points.to_vec();+ pts.sort_by(|a, b| {+ a[0].partial_cmp(&b[0])+ .unwrap_or(std::cmp::Ordering::Equal)+ .then(a[1].partial_cmp(&b[1]).unwrap_or(std::cmp::Ordering::Equal))+ });+ pts.dedup_by(|a, b| a[0] == b[0] && a[1] == b[1]);+ let n = pts.len();+ if n < 3 {+ return pts;+ }+ let cross = |o: [f64; 2], a: [f64; 2], b: [f64; 2]| {+ (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])+ };+ let mut hull: Vec<[f64; 2]> = Vec::with_capacity(2 * n);+ for &p in &pts {+ while hull.len() >= 2 && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {+ hull.pop();+ }+ hull.push(p);+ }+ let lower = hull.len() + 1;+ for &p in pts.iter().rev() {+ while hull.len() >= lower && cross(hull[hull.len() - 2], hull[hull.len() - 1], p) <= 0.0 {+ hull.pop();+ }+ hull.push(p);+ }+ hull.pop();+ hull+}++/// Signed distance from `p` to a CCW convex polygon: positive inside (distance+/// to the nearest edge), negative outside. A hull with < 3 vertices is always+/// "outside" (returns the negative distance to it).+pub fn point_in_hull_margin(p: [f64; 2], hull: &[[f64; 2]]) -> f64 {+ let n = hull.len();+ if n == 0 {+ return f64::NEG_INFINITY;+ }+ if n == 1 {+ return -((p[0] - hull[0][0]).hypot(p[1] - hull[0][1]));+ }+ if n == 2 {+ return -dist_point_segment(p, hull[0], hull[1]);+ }+ let mut min_signed = f64::INFINITY;+ for i in 0..n {+ let a = hull[i];+ let b = hull[(i + 1) % n];+ let len = (b[0] - a[0]).hypot(b[1] - a[1]);+ if len < 1e-12 {+ continue;+ }+ // CCW interior is to the left of each edge a→b.+ let signed = ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])) / len;+ min_signed = min_signed.min(signed);+ }+ min_signed+}++fn dist_point_segment(p: [f64; 2], a: [f64; 2], b: [f64; 2]) -> f64 {+ let ab = [b[0] - a[0], b[1] - a[1]];+ let l2 = ab[0] * ab[0] + ab[1] * ab[1];+ if l2 < 1e-12 {+ return (p[0] - a[0]).hypot(p[1] - a[1]);+ }+ let t = (((p[0] - a[0]) * ab[0] + (p[1] - a[1]) * ab[1]) / l2).clamp(0.0, 1.0);+ (p[0] - (a[0] + t * ab[0])).hypot(p[1] - (a[1] + t * ab[1]))+}++/// Pair's mean contact normal is predominantly vertical (a gravity support,+/// not a side wall). Mirrors the Z-alignment test in `add_support_edges`.+fn is_vertical_support(data: &PairData) -> bool {+ if data.normals.is_empty() {+ return false;+ }+ let mut mean = Vector3::zeros();+ for n in &data.normals {+ let flip = if n[2] >= 0.0 { 1.0 } else { -1.0 };+ mean += n * flip;+ }+ mean /= data.normals.len() as f64;+ let len = mean.norm();+ len > 1e-9 && (mean[2] / len).abs() >= SUPPORT_NORMAL_MIN_Z+}++/// Parts whose center of mass falls outside the convex hull of the contact+/// points supporting them from below, given the final placement `sequence`.+/// Only parts with a real gravity-resting seat (≥ MIN_SUPPORT_POINTS supporting+/// contacts from earlier-placed, lower neighbors) are candidates — base /+/// press-fit / fully-mated parts are never flagged.+pub fn support_check(+ sequence: &[String],+ parts: &[Component],+ pair_depths: &PairDepths,+ fasteners: &HashMap<String, FastenerInfo>,+) -> HashSet<String> {+ let by_id: HashMap<&str, &Component> = parts.iter().map(|p| (p.node_id.as_str(), p)).collect();+ let seq_pos: HashMap<&str, usize> = sequence+ .iter()+ .enumerate()+ .map(|(i, s)| (s.as_str(), i))+ .collect();++ let mut needs: HashSet<String> = HashSet::new();++ for part in parts {+ let pid = part.node_id.as_str();+ // Fasteners are held by threads / press-fit, not by a gravity support+ // polygon — never flag them (matches `add_support_edges`).+ if fasteners.contains_key(pid) {+ continue;+ }+ let pos = match seq_pos.get(pid) {+ Some(&p) => p,+ None => continue,+ };+ let p_center_z = (part.bbox_min[2] + part.bbox_max[2]) / 2.0;+ let com_xy = [+ (part.bbox_min[0] + part.bbox_max[0]) / 2.0,+ (part.bbox_min[1] + part.bbox_max[1]) / 2.0,+ ];++ let mut support_pts: Vec<[f64; 2]> = Vec::new();+ for data in pair_depths.values() {+ let other = if data.a == pid {+ &data.b+ } else if data.b == pid {+ &data.a+ } else {+ continue;+ };+ // A fastener doesn't hold a part up against gravity.+ if fasteners.contains_key(other.as_str()) {+ continue;+ }+ // Supporter must already be placed when this part goes on.+ match seq_pos.get(other.as_str()) {+ Some(&op) if op < pos => {}+ _ => continue,+ }+ let oc = match by_id.get(other.as_str()) {+ Some(c) => c,+ None => continue,+ };+ let o_center_z = (oc.bbox_min[2] + oc.bbox_max[2]) / 2.0;+ if o_center_z >= p_center_z {+ continue; // not below+ }+ if !is_vertical_support(data) {+ continue;+ }+ for pt in &data.points {+ support_pts.push([pt[0], pt[1]]);+ }+ }++ if support_pts.len() < MIN_SUPPORT_POINTS {+ continue;+ }+ let hull = convex_hull_2d(&support_pts);+ if point_in_hull_margin(com_xy, &hull) < -SUPPORT_MARGIN_MM {+ needs.insert(part.node_id.clone());+ }+ }+ needs+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn hull_of_a_square_is_four_corners() {+ let pts = [+ [0.0, 0.0],+ [1.0, 0.0],+ [1.0, 1.0],+ [0.0, 1.0],+ [0.5, 0.5], // interior, must be dropped+ ];+ let hull = convex_hull_2d(&pts);+ assert_eq!(hull.len(), 4);+ }++ #[test]+ fn point_inside_square_has_positive_margin() {+ let hull = convex_hull_2d(&[[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]]);+ assert!(point_in_hull_margin([1.0, 1.0], &hull) > 0.9);+ assert!(point_in_hull_margin([1.0, 1.0], &hull) <= 1.0 + 1e-9);+ }++ #[test]+ fn point_outside_square_has_negative_margin() {+ let hull = convex_hull_2d(&[[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]]);+ assert!(point_in_hull_margin([3.0, 1.0], &hull) < 0.0);+ assert!(point_in_hull_margin([1.0, -0.5], &hull) < 0.0);+ }++ #[test]+ fn degenerate_hulls_are_outside() {+ assert!(point_in_hull_margin([0.0, 0.0], &[]) < 0.0);+ assert!(point_in_hull_margin([0.0, 0.0], &[[1.0, 1.0]]) < 0.0);+ assert!(point_in_hull_margin([0.0, 0.0], &[[1.0, 0.0], [2.0, 0.0]]) < 0.0);+ }++ #[test]+ fn collinear_points_do_not_form_a_polygon() {+ let hull = convex_hull_2d(&[[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]]);+ assert!(hull.len() < 3);+ }+}diff --git a/crates/planner/src/steps.rs b/crates/planner/src/steps.rsnew file mode 100644index 0000000000..b89fdb0a44--- /dev/null+++ b/crates/planner/src/steps.rs@@ -0,0 +1,436 @@+//! `plan_step`: STEP file -> plan.json (version 3) — ties the converter (OCCT+//! assembly tree) to the planner and emits the wire format.++use crate::consts::mesh_tolerance;+use crate::pipeline2::{+ detect_swarm_units, merge_units, plan_fixed_sequence, plan_parts, GroupPayload, PlanOutcome,+};+use crate::types::{Component, Mesh, Motion, PlannedComponent};+use converter::convert::{build_tree, ConvertError};+use converter::graph::AssemblyNode;+use nalgebra::Vector3;+use serde_json::{json, Map, Value};+use std::collections::{HashMap, HashSet};++pub const PLAN_VERSION: i64 = 3;++pub struct PlanResult {+ pub plan: Value,+ pub component_count: i64,+ pub planned_count: i64,+ pub tiers: std::collections::BTreeMap<String, i64>,+ pub warnings: Vec<String>,+ pub verified_count: i64,+}++/// `_collect_world_parts`: flatten leaves into world-space collision components.+pub fn collect_world_parts(root: &AssemblyNode) -> Vec<Component> {+ let mut parts = Vec::new();+ let identity: [f64; 16] = [+ 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,+ ];+ visit(root, &identity, &mut parts);+ parts+}++fn visit(node: &AssemblyNode, parent_world: &[f64; 16], parts: &mut Vec<Component>) {+ // numpy-exact: `local = transform.reshape(4,4).T` (column-major list -> row-major+ // matrix), `world = parent_world @ local` via BLAS dgemm, and+ // `positions @ world[:3,:3].T + world[:3,3]` via dgemm — matching+ // `_collect_world_parts` bit-for-bit.+ let mut local = [0.0f64; 16];+ for i in 0..4 {+ for j in 0..4 {+ local[i * 4 + j] = node.transform[j * 4 + i];+ }+ }+ let world = crate::npy::mat4_matmul(parent_world, &local);+ if let Some(mesh) = &node.mesh {+ if !mesh.positions.is_empty() {+ let mut r = [0.0f64; 9];+ for i in 0..3 {+ for j in 0..3 {+ r[i * 3 + j] = world[i * 4 + j];+ }+ }+ let t = [world[3], world[7], world[11]];+ let flat: Vec<f64> = mesh+ .positions+ .iter()+ .flat_map(|p| [p[0] as f64, p[1] as f64, p[2] as f64])+ .collect();+ let out = crate::npy::transform_points(&flat, &r, &t);+ let vertices: Vec<Vector3<f64>> = out+ .chunks_exact(3)+ .map(|c| Vector3::new(c[0], c[1], c[2]))+ .collect();+ let faces = mesh.indices.clone();+ let m = Mesh { vertices, faces };+ let (lo, hi) = m.bbox();+ parts.push(Component::new(+ node.node_id.clone(),+ node.name.clone(),+ m,+ lo,+ hi,+ mesh.is_proxy,+ ));+ }+ }+ for child in &node.children {+ visit(child, &world, parts);+ }+}++fn motion_to_json(m: &Motion) -> Value {+ match m {+ Motion::None => json!({"type": "none"}),+ Motion::Linear {+ direction,+ distance,+ } => {+ json!({"type": "linear", "direction": direction.to_vec(), "distance": distance})+ }+ Motion::L { segments } => {+ let segs: Vec<Value> = segments+ .iter()+ .map(|s| json!({"direction": s.direction.to_vec(), "distance": s.distance}))+ .collect();+ json!({"type": "L", "segments": segs})+ }+ }+}++/// `_part_to_dict`. `needs_support` is the set of leaf ids flagged tippy by the+/// stability check; a member's own id (not the group rep's) decides its flag.+/// `waves` maps a unit/rep id to its build wave — group members share the rep's.+fn part_to_dict(+ entry: &PlannedComponent,+ needs_support: &HashSet<String>,+ waves: &HashMap<String, i64>,+) -> Value {+ let mut m = Map::new();+ m.insert("motion".into(), motion_to_json(&entry.motion));+ if let Some(c) = &entry.confidence {+ m.insert("confidence".into(), json!(c));+ }+ if let Some(d) = &entry.removal_direction {+ m.insert("removalDirection".into(), json!(d.to_vec()));+ }+ if !entry.blocked_by.is_empty() {+ m.insert("blockedBy".into(), json!(entry.blocked_by));+ }+ if let Some(t) = &entry.tier {+ m.insert("tier".into(), json!(t));+ }+ if let Some(g) = &entry.group_id {+ m.insert("groupId".into(), json!(g));+ }+ if needs_support.contains(&entry.node_id) {+ m.insert("needsSupport".into(), json!(true));+ }+ if let Some(w) = waves.get(&entry.node_id) {+ m.insert("wave".into(), json!(w));+ }+ m.insert("verified".into(), json!(entry.verified));+ Value::Object(m)+}++fn group_to_json(g: &GroupPayload) -> Value {+ let mut m = Map::new();+ m.insert("componentNodeIds".into(), json!(g.component_node_ids));+ m.insert("motion".into(), motion_to_json(&g.motion));+ if let Some(n) = &g.name {+ m.insert("name".into(), json!(n));+ }+ Value::Object(m)+}++/// Union AABB of every planned body (the standing camera framing bounds).+fn assembly_bounds(parts: &[Component]) -> (Vector3<f64>, Vector3<f64>) {+ let mut min = Vector3::repeat(f64::INFINITY);+ let mut max = Vector3::repeat(f64::NEG_INFINITY);+ for part in parts {+ min = min.inf(&part.bbox_min);+ max = max.sup(&part.bbox_max);+ }+ if !min.x.is_finite() {+ return (Vector3::zeros(), Vector3::zeros());+ }+ (min, max)+}++/// One caller unit: id, optional name, member nodeIds.+pub struct PlanUnit {+ pub id: String,+ pub name: Option<String>,+ pub node_ids: Vec<String>,+}++#[allow(clippy::too_many_arguments)]+pub fn plan_step(+ step_path: &str,+ linear_deflection: f64,+ angular_deflection: f64,+ clearance: f64,+ path_samples: usize,+ max_parts: Option<usize>,+ units: Option<Vec<PlanUnit>>,+ sequence: Option<Vec<Vec<String>>>,+ // Penetration tolerance override (mm). None => inferred from the meshing+ // deflection via `mesh_tolerance` (max(0.15, 2.5 * linear_deflection)) --+ // the tolerance must scale with tessellation error or clean seated+ // contacts read as collisions. Explicit values are honored as-is.+ tolerance: Option<f64>,+) -> Result<PlanResult, ConvertError> {+ let root = build_tree(step_path, linear_deflection, angular_deflection)?;+ let mut parts = collect_world_parts(&root);+ let leaf_count = parts.len() as i64;++ // Caller units → merged bodies (expansion maps unit id → members).+ let mut expansion: HashMap<String, (Vec<String>, Option<String>)> = HashMap::new();+ if let (Some(units), None) = (&units, &sequence) {+ let spec: Vec<(String, Option<String>, Vec<String>)> = units+ .iter()+ .map(|u| (u.id.clone(), u.name.clone(), u.node_ids.clone()))+ .collect();+ let (merged, exp) = merge_units(&parts, &spec);+ parts = merged;+ expansion = exp;+ }++ // Auto-detect detail swarms (populated PCBs) from pure geometry so a+ // 400-component board plans as one rigid unit even with no caller units+ // (no BOM, no LLM assignment). Runs after caller units (their merged+ // bodies are never re-swallowed) and never in fixed-sequence re-motion+ // (the sequence references the existing step structure).+ if sequence.is_none() {+ let consumed: HashSet<String> = expansion.keys().cloned().collect();+ let spec = detect_swarm_units(&parts, &consumed);+ if !spec.is_empty() {+ let (merged, exp) = merge_units(&parts, &spec);+ parts = merged;+ expansion.extend(exp);+ }+ }++ let planned_body_count = sequence.as_ref().map(|s| s.len()).unwrap_or(parts.len());+ if let Some(mp) = max_parts {+ if planned_body_count > mp {+ return Err(ConvertError::new(+ "LIMIT_EXCEEDED",+ format!("assembly has {planned_body_count} part instances; the limit is {mp}"),+ ));+ }+ }++ let mut warnings: Vec<String> = Vec::new();+ if parts.iter().any(|p| p.is_proxy) {+ warnings.push(+ "some parts use bounding-box proxy meshes; their motions are low confidence".into(),+ );+ }++ let tolerance = tolerance.unwrap_or_else(|| mesh_tolerance(linear_deflection));+ // The planner consumes `parts`; keep the merged bodies (meshes + bounds)+ // for the per-step view-direction rays afterward. FCL BVHs are Arc-shared+ // across clones, so this is a mesh-buffer copy only.+ let view_parts: Vec<Component> = parts.clone();+ let outcome: PlanOutcome = if let Some(seq) = &sequence {+ plan_fixed_sequence(+ parts,+ seq,+ clearance,+ path_samples,+ tolerance,+ &mut warnings,+ )+ } else {+ let protected: HashSet<String> = expansion.keys().cloned().collect();+ let prot = if protected.is_empty() {+ None+ } else {+ Some(&protected)+ };+ plan_parts(+ parts,+ clearance,+ path_samples,+ tolerance,+ prot,+ &mut warnings,+ )+ };++ // Mesh-precise view direction per planned body: sight lines against the+ // triangles of everything installed earlier in the sequence. Keyed in the+ // pre-expansion (merged-body) space, same as `outcome.sequence`.+ let view: HashMap<String, ([f64; 3], f64)> = {+ let view_start = std::time::Instant::now();+ let by_id: HashMap<&str, &Component> =+ view_parts.iter().map(|p| (p.node_id.as_str(), p)).collect();+ let motion_by_id: HashMap<&str, &Motion> = outcome+ .planned+ .iter()+ .map(|e| (e.node_id.as_str(), &e.motion))+ .collect();+ let (assembly_min, assembly_max) = assembly_bounds(&view_parts);+ // Bodies not yet installed when this step plays. They're hidden/ghosted+ // during playback, so they score at a low weight — but a direction that+ // also clears them survives the viewer's "show all future parts" toggle.+ let mut future_ids: HashSet<&str> = view_parts.iter().map(|p| p.node_id.as_str()).collect();+ let mut installed: Vec<&Component> = Vec::with_capacity(view_parts.len());+ let mut out = HashMap::new();+ let mut worst: (f64, &str) = (0.0, "");+ for node_id in &outcome.sequence {+ let Some(subject) = by_id.get(node_id.as_str()) else {+ continue;+ };+ future_ids.remove(node_id.as_str());+ let motion = motion_by_id+ .get(node_id.as_str())+ .copied()+ .unwrap_or(&Motion::None);+ let future: Vec<&Component> = future_ids+ .iter()+ .filter_map(|id| by_id.get(id).copied())+ .collect();+ let (direction, obstruction) = crate::view::best_view_direction(+ subject,+ motion,+ &installed,+ &future,+ &assembly_min,+ &assembly_max,+ );+ if obstruction > worst.0 {+ worst = (obstruction, node_id.as_str());+ }+ out.insert(node_id.clone(), (direction, obstruction));+ installed.push(subject);+ }+ eprintln!(+ "view: {} bodies in {:?}; worst obstruction {:.2} ({})",+ out.len(),+ view_start.elapsed(),+ worst.0,+ worst.1+ );+ out+ };++ // Expand merged units back to member leaves.+ let mut groups: Map<String, Value> = outcome+ .groups+ .iter()+ .map(|(k, v)| {+ let mut payload = group_to_json(v);+ if let Some((d, obstruction)) = view.get(k) {+ payload["viewDirection"] = json!(d.to_vec());+ payload["viewObstruction"] = json!(obstruction);+ }+ (k.clone(), payload)+ })+ .collect();+ let mut components: Map<String, Value> = Map::new();+ for entry in &outcome.planned {+ let view_entry = view.get(&entry.node_id);+ match expansion.get(&entry.node_id) {+ None => {+ let mut payload = part_to_dict(entry, &outcome.needs_support, &outcome.waves);+ if let Some((d, obstruction)) = view_entry {+ payload["viewDirection"] = json!(d.to_vec());+ payload["viewObstruction"] = json!(obstruction);+ }+ components.insert(entry.node_id.clone(), payload);+ }+ Some((members, name)) => {+ let mut member_payload =+ part_to_dict(entry, &outcome.needs_support, &outcome.waves);+ member_payload["groupId"] = json!(entry.node_id);+ for member in members {+ // needsSupport is per leaf, not per group rep.+ let mut mp = member_payload.clone();+ if outcome.needs_support.contains(member) {+ mp["needsSupport"] = json!(true);+ } else if let Some(obj) = mp.as_object_mut() {+ obj.remove("needsSupport");+ }+ components.insert(member.clone(), mp);+ }+ let mut gp = Map::new();+ gp.insert("componentNodeIds".into(), json!(members));+ gp.insert("motion".into(), motion_to_json(&entry.motion));+ if let Some(n) = name {+ gp.insert("name".into(), json!(n));+ }+ if let Some((d, obstruction)) = view_entry {+ gp.insert("viewDirection".into(), json!(d.to_vec()));+ gp.insert("viewObstruction".into(), json!(obstruction));+ }+ groups.insert(entry.node_id.clone(), Value::Object(gp));+ }+ }+ }+ for (member, rep) in &outcome.merged_into {+ components.insert(+ member.clone(),+ json!({"motion": {"type": "none"}, "mergedInto": rep}),+ );+ }++ let mut sequence_out: Vec<String> = Vec::new();+ for node_id in &outcome.sequence {+ match expansion.get(node_id) {+ None => sequence_out.push(node_id.clone()),+ Some((members, _)) => sequence_out.extend(members.iter().cloned()),+ }+ }++ let mut plan = json!({+ "version": PLAN_VERSION,+ "unit": "mm",+ "sequence": sequence_out,+ "components": Value::Object(components),+ "warnings": warnings.clone(),+ });+ if !groups.is_empty() {+ plan["groups"] = Value::Object(groups);+ }+ // Body-level relatedness graph (planned-body node_id -> related bodies): the+ // strict contact graph augmented with clearance-fit neighbors (fasteners and+ // slip-fits that hold parts together across a gap strict contact can't see),+ // so the viewer relates a placed part to the assembly instead of rendering it+ // as a floating island. Used by the step grouping's floater fold + phase+ // partition. Keys are in the pre-expansion body space, matching a member's+ // `components[member].groupId ?? member`. Deterministic ordering. Falls back+ // to strict adjacency when relatedness is unavailable (fixed-sequence mode).+ let contact_graph = if outcome.relatedness.is_empty() {+ &outcome.adjacency+ } else {+ &outcome.relatedness+ };+ plan["contacts"] = json!(contact_graph+ .iter()+ .map(|(k, v)| {+ let mut neighbors: Vec<_> = v.iter().cloned().collect();+ neighbors.sort(); // HashSet order is run-nondeterministic+ (k.clone(), neighbors)+ })+ .collect::<std::collections::BTreeMap<_, _>>());++ let planned_count = outcome+ .planned+ .iter()+ .filter(|e| !matches!(e.motion, Motion::None))+ .count() as i64;++ Ok(PlanResult {+ plan,+ component_count: leaf_count,+ planned_count,+ tiers: outcome.tiers,+ warnings,+ verified_count: outcome.verified_count,+ })+}diff --git a/crates/planner/src/types.rs b/crates/planner/src/types.rsnew file mode 100644index 0000000000..2ef54860c5--- /dev/null+++ b/crates/planner/src/types.rs@@ -0,0 +1,210 @@+//! Core planner data structures.++use cxx::UniquePtr;+use nalgebra::Vector3;+use std::sync::{Arc, OnceLock};++/// A built FCL BVH, safe to share read-only across threads. `BVHModel` is+/// immutable after `endModel` (the only builder), and every FCL query+/// (`collide`/`distance`) reads it without mutation — cxx `UniquePtr` is a plain+/// owning pointer, so concurrent `&`-access for read-only collision is sound.+/// This is what lets the greedy candidate sweeps run on multiple threads (each+/// thread builds its own `Manager` over these shared BVHs).+pub struct SharedBvh(UniquePtr<collision::Bvh>);+// SAFETY: read-only shared access to an immutable BVHModel; see the type doc.+unsafe impl Send for SharedBvh {}+unsafe impl Sync for SharedBvh {}+impl std::ops::Deref for SharedBvh {+ type Target = collision::Bvh;+ fn deref(&self) -> &collision::Bvh {+ &self.0+ }+}++/// A triangle mesh in world space.+#[derive(Debug, Clone)]+pub struct Mesh {+ pub vertices: Vec<Vector3<f64>>,+ pub faces: Vec<[u32; 3]>,+}++impl Mesh {+ pub fn bbox(&self) -> (Vector3<f64>, Vector3<f64>) {+ let mut lo = Vector3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);+ let mut hi = Vector3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);+ for v in &self.vertices {+ lo = lo.inf(v);+ hi = hi.sup(v);+ }+ (lo, hi)+ }++ /// Flat row-major vertex coordinates for BVH construction.+ pub fn flat_vertices(&self) -> Vec<f64> {+ let mut out = Vec::with_capacity(self.vertices.len() * 3);+ for v in &self.vertices {+ out.push(v[0]);+ out.push(v[1]);+ out.push(v[2]);+ }+ out+ }++ /// Flat row-major triangle indices for BVH construction.+ pub fn flat_faces(&self) -> Vec<u32> {+ let mut out = Vec::with_capacity(self.faces.len() * 3);+ for f in &self.faces {+ out.extend_from_slice(f);+ }+ out+ }++ /// Concatenate two meshes (triangle-soup union), reindexing faces.+ pub fn concatenate(meshes: &[&Mesh]) -> Mesh {+ let mut vertices = Vec::new();+ let mut faces = Vec::new();+ let mut offset = 0u32;+ for m in meshes {+ vertices.extend_from_slice(&m.vertices);+ for f in &m.faces {+ faces.push([f[0] + offset, f[1] + offset, f[2] + offset]);+ }+ offset += m.vertices.len() as u32;+ }+ Mesh { vertices, faces }+ }+}++/// A leaf part (or merged unit) in world space.+#[derive(Clone)]+pub struct Component {+ pub node_id: String,+ pub name: String,+ pub mesh: Mesh,+ pub bbox_min: Vector3<f64>,+ pub bbox_max: Vector3<f64>,+ pub is_proxy: bool,+ /// Seated contact normals with neighbors (filled during planning).+ pub contact_normals: Vec<Vector3<f64>>,+ /// Sandwich seated-interference allowances (nodeId -> mm) and their axes.+ pub seated_allowance: std::collections::HashMap<String, f64>,+ pub seated_allowance_axes: std::collections::HashMap<String, Vector3<f64>>,+ /// Explicit material-volume override (merged units set this to the member+ /// sum). When `None`, `part_volume` computes and memoizes into `vol_cache`.+ pub cached_volume: Option<f64>,+ /// Lazily-built FCL BVH, shared across clones.+ bvh: OnceLock<Arc<SharedBvh>>,+ /// Lazily-built triangle BVH for view-baking rays, shared across clones.+ view_bvh: OnceLock<Arc<crate::view::TriBvh>>,+ /// Memoized `part_volume` result (the watertight test builds a full-mesh+ /// edge map — costly, and called repeatedly during greedy sorting).+ pub(crate) vol_cache: OnceLock<f64>,+ /// Memoized `symmetry_axis_kind` result — a LAPACK SVD of the vertex cloud,+ /// pure in the mesh, recomputed once per candidate per greedy iteration+ /// without this cache. `None`-vs-cached distinguished by the outer Option.+ pub(crate) sym_axis_cache: OnceLock<Option<(Vector3<f64>, FastenerKind)>>,+}++impl Component {+ pub fn new(+ node_id: String,+ name: String,+ mesh: Mesh,+ bbox_min: Vector3<f64>,+ bbox_max: Vector3<f64>,+ is_proxy: bool,+ ) -> Self {+ Component {+ node_id,+ name,+ mesh,+ bbox_min,+ bbox_max,+ is_proxy,+ contact_normals: Vec::new(),+ seated_allowance: Default::default(),+ seated_allowance_axes: Default::default(),+ cached_volume: None,+ bvh: OnceLock::new(),+ view_bvh: OnceLock::new(),+ vol_cache: OnceLock::new(),+ sym_axis_cache: OnceLock::new(),+ }+ }++ /// The part's FCL BVH, built once and cached. The handle is+ /// `Arc<SharedBvh>` so it can be shared read-only across the parallel+ /// greedy sweeps.+ pub fn bvh(&self) -> Arc<SharedBvh> {+ self.bvh+ .get_or_init(|| {+ let verts = self.mesh.flat_vertices();+ let faces = self.mesh.flat_faces();+ Arc::new(SharedBvh(collision::new_bvh(&verts, &faces)))+ })+ .clone()+ }++ /// The part's triangle BVH for view-baking sight-line rays, built once and+ /// cached. Separate from the FCL BVH (collision-only; the bridge exposes no+ /// ray query). `Arc` so it survives the `view_parts` clone and is shared+ /// across the rayon-parallel candidate scoring.+ pub fn view_bvh(&self) -> Arc<crate::view::TriBvh> {+ self.view_bvh+ .get_or_init(|| Arc::new(crate::view::TriBvh::build(&self.mesh)))+ .clone()+ }+}++/// Classified fastener (axis, mates, kind, shank radius, sliding allowances).+#[derive(Debug, Clone)]+pub struct FastenerInfo {+ pub axis: Vector3<f64>,+ pub mates: std::collections::HashMap<String, f64>,+ pub kind: Option<FastenerKind>,+ pub shank_radius: Option<f64>,+ pub sliding: std::collections::HashMap<String, f64>,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum FastenerKind {+ Rod,+ Disc,+}++/// A planned removal/insertion in the plan.json contract.+#[derive(Debug, Clone)]+pub struct PlannedComponent {+ pub node_id: String,+ pub motion: Motion,+ pub confidence: Option<String>,+ pub removal_direction: Option<[f64; 3]>,+ pub blocked_by: Vec<String>,+ pub tier: Option<String>,+ pub verified: bool,+ pub group_id: Option<String>,+}++/// An insertion motion (removal reversed), matching the plan.json contract.+#[derive(Debug, Clone, PartialEq)]+pub enum Motion {+ None,+ Linear { direction: [f64; 3], distance: f64 },+ L { segments: Vec<MotionSegment> },+}++#[derive(Debug, Clone, PartialEq)]+pub struct MotionSegment {+ pub direction: [f64; 3],+ pub distance: f64,+}++impl Motion {+ pub fn type_str(&self) -> &'static str {+ match self {+ Motion::None => "none",+ Motion::Linear { .. } => "linear",+ Motion::L { .. } => "L",+ }+ }+}diff --git a/crates/planner/src/view.rs b/crates/planner/src/view.rsnew file mode 100644index 0000000000..ef6bb21de3--- /dev/null+++ b/crates/planner/src/view.rs@@ -0,0 +1,642 @@+//! Mesh-precise per-step view directions, baked into plan.json.+//!+//! Picks the camera direction with the clearest actual-triangle sight line to+//! a step's action (the seated part plus its travel). An AABB-only occlusion+//! test cannot do this job: a container's box CONTAINS the seat of the part+//! going into it, so every direction looks equally blocked and the choice+//! degenerates to tie-breakers — the BCU's PCB-into-enclosure step picked a+//! view straight through the box wall. Only rays against real triangles can+//! tell "through the open top" from "through a wall".+//!+//! The planner is the right home: it holds every tessellated mesh and the+//! authoritative install sequence (occluders for step i = bodies installed+//! before i). The viewer applies the baked direction with LIVE framing math+//! (target, standing distance, frustum fit with the real viewport aspect).++use crate::types::{Component, Mesh, Motion};+use nalgebra::Vector3;+use rayon::prelude::*;++/// Stage-1 candidates kept for full-ray rescoring.+const REFINE_TOP: usize = 8;+/// Blocked sight lines dominate the preference terms.+const BLOCK_WEIGHT: f64 = 10.0;+/// Penalty for travel running into the screen instead of across it.+const TRAVEL_INTO_SCREEN_WEIGHT: f64 = 4.0;++/// Where a body starts relative to its seated pose; `None` if it doesn't move.+fn travel_start_offset(motion: &Motion) -> Option<Vector3<f64>> {+ match motion {+ Motion::None => None,+ Motion::Linear { direction, distance } => {+ let d = Vector3::from_column_slice(direction);+ let n = d.norm();+ (n > 1e-9).then(|| d * (-distance / n))+ }+ Motion::L { segments } => {+ let mut offset = Vector3::zeros();+ for segment in segments {+ let d = Vector3::from_column_slice(&segment.direction);+ let n = d.norm();+ if n > 1e-9 {+ offset += d * (-segment.distance / n);+ }+ }+ (offset.norm() > 1e-9).then_some(offset)+ }+ }+}++/// Dominant travel direction; `None` if the body doesn't move.+fn travel_direction(motion: &Motion) -> Option<Vector3<f64>> {+ match motion {+ Motion::None => None,+ Motion::Linear { direction, .. } => {+ let d = Vector3::from_column_slice(direction);+ let n = d.norm();+ (n > 1e-9).then(|| d / n)+ }+ Motion::L { segments } => segments+ .iter()+ .max_by(|a, b| a.distance.abs().total_cmp(&b.distance.abs()))+ .and_then(|s| {+ let d = Vector3::from_column_slice(&s.direction);+ let n = d.norm();+ (n > 1e-9).then(|| d / n)+ }),+ }+}++/// Slab test: does the segment origin→end pass through the AABB? The segment+/// stops just short of the end so geometry AT the sample point (the seat the+/// part rests on) doesn't read as blocking it.+fn segment_hits_aabb(+ origin: &Vector3<f64>,+ end: &Vector3<f64>,+ min: &Vector3<f64>,+ max: &Vector3<f64>,+) -> bool {+ let mut t_min = 0.0f64;+ let mut t_max = 0.98f64;+ for axis in 0..3 {+ let o = origin[axis];+ let delta = end[axis] - o;+ if delta.abs() < 1e-9 {+ if o < min[axis] || o > max[axis] {+ return false;+ }+ continue;+ }+ let mut t_near = (min[axis] - o) / delta;+ let mut t_far = (max[axis] - o) / delta;+ if t_near > t_far {+ std::mem::swap(&mut t_near, &mut t_far);+ }+ t_min = t_min.max(t_near);+ t_max = t_max.min(t_far);+ if t_min > t_max {+ return false;+ }+ }+ true+}++/// Möller–Trumbore for one triangle: does the segment origin→(origin+dir) cross+/// it inside t ∈ (1e-9, 0.98)? `dir` is the full segment vector (end − origin).+fn triangle_hit(+ origin: &Vector3<f64>,+ dir: &Vector3<f64>,+ a: &Vector3<f64>,+ b: &Vector3<f64>,+ c: &Vector3<f64>,+) -> bool {+ let e1 = b - a;+ let e2 = c - a;+ let p = dir.cross(&e2);+ let det = e1.dot(&p);+ if det.abs() < 1e-12 {+ return false;+ }+ let inv_det = 1.0 / det;+ let s = origin - a;+ let u = s.dot(&p) * inv_det;+ if !(0.0..=1.0).contains(&u) {+ return false;+ }+ let q = s.cross(&e1);+ let v = dir.dot(&q) * inv_det;+ if v < 0.0 || u + v > 1.0 {+ return false;+ }+ let t = e2.dot(&q) * inv_det;+ t > 1e-9 && t < 0.98+}++/// Blocked weight on the sight line eye→point. AABB broadphase per occluder,+/// then a BVH-accelerated triangle test; `installed` count at full weight,+/// `future` (hidden/ghosted at playback) at a low weight so a view that also+/// clears the "show all" toggle wins ties without dominating.+fn blocked_weight(+ eye: &Vector3<f64>,+ point: &Vector3<f64>,+ installed: &[&Component],+ future: &[&Component],+) -> f64 {+ let hits = |group: &[&Component]| -> usize {+ group+ .iter()+ .filter(|occ| {+ segment_hits_aabb(eye, point, &occ.bbox_min, &occ.bbox_max)+ && occ.view_bvh().ray_hits(eye, point)+ })+ .count()+ };+ hits(installed) as f64 + FUTURE_OCCLUDER_WEIGHT * hits(future) as f64+}++/// Weight of a not-yet-installed occluder (hidden/ghosted by default; matches+/// the viewer's ghost opacity semantics).+const FUTURE_OCCLUDER_WEIGHT: f64 = 0.3;++/// A median-split triangle BVH for repeated ray-vs-mesh sight-line tests.+/// The FCL BVH on `Component` is collision-only (no ray query in the bridge),+/// so view baking builds its own. Verdict is identical to a linear triangle+/// walk — only faster (occluder meshes reach ~200k triangles and each is hit+/// by hundreds of rays across the candidate search).+pub struct TriBvh {+ verts: Vec<Vector3<f64>>,+ /// Triangle vertex indices, reordered so each node owns a contiguous range.+ tris: Vec<[u32; 3]>,+ nodes: Vec<BvhNode>,+}++struct BvhNode {+ min: Vector3<f64>,+ max: Vector3<f64>,+ /// Leaf (`count > 0`): triangle range [start, start+count) into `tris`.+ /// Interior (`count == 0`): `start` = left child index, `right` = right+ /// child index. The right child is NOT left+1 — the left subtree pushes its+ /// own descendants first — so both indices are stored explicitly.+ start: u32,+ right: u32,+ count: u32,+}++const BVH_LEAF_TRIS: usize = 8;++impl TriBvh {+ pub fn build(mesh: &Mesh) -> TriBvh {+ let verts = mesh.vertices.clone();+ let tris = mesh.faces.clone();+ let mut bvh = TriBvh {+ verts,+ tris,+ nodes: Vec::new(),+ };+ if bvh.tris.is_empty() {+ return bvh;+ }+ let count = bvh.tris.len();+ bvh.nodes.reserve(2 * count / BVH_LEAF_TRIS + 1);+ bvh.build_node(0, count);+ bvh+ }++ /// Build a node over tris[start..start+count), return its index.+ fn build_node(&mut self, start: usize, count: usize) -> u32 {+ let (mut min, mut max) = (+ Vector3::repeat(f64::INFINITY),+ Vector3::repeat(f64::NEG_INFINITY),+ );+ for tri in &self.tris[start..start + count] {+ for &vi in tri {+ let v = &self.verts[vi as usize];+ min = min.inf(v);+ max = max.sup(v);+ }+ }+ let index = self.nodes.len() as u32;+ self.nodes.push(BvhNode {+ min,+ max,+ start: start as u32,+ right: 0,+ count: count as u32,+ });+ if count <= BVH_LEAF_TRIS {+ return index;+ }+ // Split along the widest extent at the centroid median.+ let extent = max - min;+ let axis = if extent.x >= extent.y && extent.x >= extent.z {+ 0+ } else if extent.y >= extent.z {+ 1+ } else {+ 2+ };+ let centroid = |tri: &[u32; 3]| -> f64 {+ (self.verts[tri[0] as usize][axis]+ + self.verts[tri[1] as usize][axis]+ + self.verts[tri[2] as usize][axis])+ / 3.0+ };+ let mid = start + count / 2;+ self.tris[start..start + count]+ .select_nth_unstable_by(count / 2, |a, b| {+ centroid(a).total_cmp(¢roid(b))+ });+ // Degenerate split (all centroids equal) → keep as a leaf.+ if mid == start || mid == start + count {+ self.nodes[index as usize].count = count as u32;+ return index;+ }+ self.nodes[index as usize].count = 0;+ let left = self.build_node(start, mid - start);+ let right = self.build_node(mid, start + count - mid);+ self.nodes[index as usize].start = left;+ self.nodes[index as usize].right = right;+ index+ }++ /// Does the segment eye→point cross any triangle inside t ∈ (1e-9, 0.98)?+ pub fn ray_hits(&self, eye: &Vector3<f64>, point: &Vector3<f64>) -> bool {+ if self.nodes.is_empty() {+ return false;+ }+ let dir = point - eye;+ let mut stack = [0u32; 64];+ let mut sp = 0usize;+ stack[sp] = 0;+ sp += 1;+ while sp > 0 {+ sp -= 1;+ let node = &self.nodes[stack[sp] as usize];+ if !segment_hits_aabb(eye, point, &node.min, &node.max) {+ continue;+ }+ if node.count > 0 {+ let range = node.start as usize..(node.start + node.count) as usize;+ for tri in &self.tris[range] {+ let a = &self.verts[tri[0] as usize];+ let b = &self.verts[tri[1] as usize];+ let c = &self.verts[tri[2] as usize];+ if triangle_hit(eye, &dir, a, b, c) {+ return true;+ }+ }+ } else if sp + 2 <= stack.len() {+ stack[sp] = node.start;+ sp += 1;+ stack[sp] = node.right;+ sp += 1;+ }+ }+ false+ }+}++/// ~48 unit directions on the upper hemisphere (Z-up CAD models), Fibonacci+/// spiral over elevation z ∈ [0.15, 0.92] — low grazing views and the exact+/// zenith (degenerate camera up) are both excluded.+fn candidate_directions() -> Vec<Vector3<f64>> {+ const COUNT: usize = 48;+ const GOLDEN_ANGLE: f64 = 2.399963229728653; // π(3 − √5)+ (0..COUNT)+ .map(|i| {+ let z = 0.15 + (0.92 - 0.15) * (i as f64 + 0.5) / COUNT as f64;+ let r = (1.0 - z * z).sqrt();+ let azimuth = GOLDEN_ANGLE * i as f64;+ Vector3::new(r * azimuth.cos(), r * azimuth.sin(), z)+ })+ .collect()+}++/// The 8 corners of a bbox, optionally translated.+fn corners(min: &Vector3<f64>, max: &Vector3<f64>, offset: Option<&Vector3<f64>>) -> Vec<Vector3<f64>> {+ (0..8)+ .map(|i| {+ let mut corner = Vector3::new(+ if i & 1 != 0 { max.x } else { min.x },+ if i & 2 != 0 { max.y } else { min.y },+ if i & 4 != 0 { max.z } else { min.z },+ );+ if let Some(o) = offset {+ corner += o;+ }+ corner+ })+ .collect()+}++/// The clearest view direction for one planned body: sight lines from the+/// standing-distance eye to the seated body and its travel, rays against the+/// occluders' real triangles. `installed` are the bodies present when this one+/// animates (full weight); `future` are the not-yet-installed bodies (low+/// weight — hidden/ghosted at playback, but a direction that also clears them+/// survives the viewer's "show all" toggle). Mirrors the viewer's framing+/// geometry (target = assembly center nudged 30% toward the subject;+/// whole-assembly standing distance) so the direction transfers to the live+/// camera. Returns the chosen unit direction and its obstruction (0 = every+/// sight line clear; grows as the winning view is still blocked — the signal+/// for "this step's action is inherently hidden").+pub fn best_view_direction(+ subject: &Component,+ motion: &Motion,+ installed: &[&Component],+ future: &[&Component],+ assembly_min: &Vector3<f64>,+ assembly_max: &Vector3<f64>,+) -> ([f64; 3], f64) {+ let subject_center = (subject.bbox_min + subject.bbox_max) * 0.5;+ let assembly_center = (assembly_min + assembly_max) * 0.5;+ let assembly_radius = ((assembly_max - assembly_min).norm() / 2.0).max(1e-6);+ // fov 45°, framed at 1.25× — the viewer's standing-distance formula+ let distance = (assembly_radius / (22.5f64.to_radians().tan()) * 1.25)+ .max(assembly_radius * 2.0);+ let target = assembly_center.lerp(&subject_center, 0.3);++ let start_offset = travel_start_offset(motion);+ let travel = travel_direction(motion);++ // Full sample set: center + seated corners + travel start/midpoint+ let mut points: Vec<Vector3<f64>> = vec![subject_center];+ points.extend(corners(&subject.bbox_min, &subject.bbox_max, None));+ if let Some(offset) = &start_offset {+ points.push(subject_center + offset * 0.5);+ points.push(subject_center + offset);+ }+ // Cheap stage-1 set: the ends of the action. A seated part (no travel)+ // still needs more than its center — one ray can't tell a clear approach+ // from a blocked one — so seed two opposite corners.+ let coarse: Vec<Vector3<f64>> = match &start_offset {+ Some(offset) => vec![subject_center, subject_center + offset],+ None => vec![subject.bbox_min, subject_center, subject.bbox_max],+ };++ let preference = |candidate: &Vector3<f64>| -> f64 {+ match &travel {+ // Prefer travel running across the screen, not into it+ Some(t) => TRAVEL_INTO_SCREEN_WEIGHT * (candidate.dot(t).abs() - 0.6).max(0.0),+ None => 0.0,+ }+ };++ // Mean blocked weight per sample point (0 when every sight line is clear).+ let obstruction_of = |candidate: &Vector3<f64>, samples: &[Vector3<f64>]| -> f64 {+ let eye = target + candidate * distance;+ samples+ .iter()+ .map(|point| blocked_weight(&eye, point, installed, future))+ .sum::<f64>()+ / samples.len() as f64+ };+ let score_with = |candidate: &Vector3<f64>, samples: &[Vector3<f64>]| -> f64 {+ BLOCK_WEIGHT * obstruction_of(candidate, samples) + preference(candidate)+ };++ let candidates = candidate_directions();+ let mut coarse_scores: Vec<(f64, usize)> = candidates+ .par_iter()+ .enumerate()+ .map(|(index, candidate)| (score_with(candidate, &coarse), index))+ .collect();+ coarse_scores.sort_by(|a, b| a.0.total_cmp(&b.0));++ let best = coarse_scores+ .iter()+ .take(REFINE_TOP)+ .map(|&(_, index)| index)+ .collect::<Vec<_>>()+ .into_par_iter()+ .map(|index| (score_with(&candidates[index], &points), index))+ .min_by(|a, b| a.0.total_cmp(&b.0))+ .map(|(_, index)| index)+ .unwrap_or(0);++ let direction = candidates[best];+ let obstruction = obstruction_of(&direction, &points);+ ([direction.x, direction.y, direction.z], obstruction)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::types::Mesh;++ /// Axis-aligned solid slab as a 12-triangle mesh.+ fn slab(min: Vector3<f64>, max: Vector3<f64>) -> Mesh {+ let v = |x: f64, y: f64, z: f64| Vector3::new(x, y, z);+ let vertices = vec![+ v(min.x, min.y, min.z),+ v(max.x, min.y, min.z),+ v(max.x, max.y, min.z),+ v(min.x, max.y, min.z),+ v(min.x, min.y, max.z),+ v(max.x, min.y, max.z),+ v(max.x, max.y, max.z),+ v(min.x, max.y, max.z),+ ];+ let faces: Vec<[u32; 3]> = vec![+ [0, 2, 1],+ [0, 3, 2], // bottom+ [4, 5, 6],+ [4, 6, 7], // top+ [0, 1, 5],+ [0, 5, 4], // -y+ [2, 3, 7],+ [2, 7, 6], // +y+ [0, 4, 7],+ [0, 7, 3], // -x+ [1, 2, 6],+ [1, 6, 5], // +x+ ];+ Mesh { vertices, faces }+ }++ fn component(name: &str, mesh: Mesh) -> Component {+ let (bbox_min, bbox_max) = mesh.bbox();+ Component::new(name.to_string(), name.to_string(), mesh, bbox_min, bbox_max, false)+ }++ /// Hollow open-top box (4 walls + floor) around a small subject cube: the+ /// BCU failure. Every AABB-only score ties (the box's bbox contains the+ /// subject); only triangle rays discover the open top.+ #[test]+ fn picks_the_open_top_of_a_hollow_box() {+ let walls = [+ slab(Vector3::new(-50.0, -50.0, 0.0), Vector3::new(-45.0, 50.0, 80.0)),+ slab(Vector3::new(45.0, -50.0, 0.0), Vector3::new(50.0, 50.0, 80.0)),+ slab(Vector3::new(-50.0, -50.0, 0.0), Vector3::new(50.0, -45.0, 80.0)),+ slab(Vector3::new(-50.0, 45.0, 0.0), Vector3::new(50.0, 50.0, 80.0)),+ slab(Vector3::new(-50.0, -50.0, -5.0), Vector3::new(50.0, 50.0, 0.0)),+ ];+ let occluders: Vec<Component> = walls+ .into_iter()+ .enumerate()+ .map(|(i, mesh)| component(&format!("wall{i}"), mesh))+ .collect();+ let occluder_refs: Vec<&Component> = occluders.iter().collect();++ let subject = component(+ "pcb",+ slab(Vector3::new(-20.0, -20.0, 5.0), Vector3::new(20.0, 20.0, 10.0)),+ );+ // Drops straight down into the box+ let motion = Motion::Linear {+ direction: [0.0, 0.0, -1.0],+ distance: 120.0,+ };++ let (direction, obstruction) = best_view_direction(+ &subject,+ &motion,+ &occluder_refs,+ &[],+ &Vector3::new(-50.0, -50.0, -5.0),+ &Vector3::new(50.0, 50.0, 80.0),+ );+ // The only clear sight line into the box interior is from high above+ assert!(+ direction[2] > 0.6,+ "expected a steep top-down view, got {direction:?}"+ );+ // Open top → the chosen view sees the action; obstruction stays low.+ assert!(+ obstruction < 0.5,+ "open-top box should have a mostly-clear view, got {obstruction}"+ );+ }++ /// Sealed box: every direction is blocked — must still return a sane unit+ /// direction (least-blocked) without panicking.+ #[test]+ fn sealed_box_still_returns_a_direction() {+ let mut walls = vec![+ slab(Vector3::new(-50.0, -50.0, 0.0), Vector3::new(-45.0, 50.0, 80.0)),+ slab(Vector3::new(45.0, -50.0, 0.0), Vector3::new(50.0, 50.0, 80.0)),+ slab(Vector3::new(-50.0, -50.0, 0.0), Vector3::new(50.0, -45.0, 80.0)),+ slab(Vector3::new(-50.0, 45.0, 0.0), Vector3::new(50.0, 50.0, 80.0)),+ slab(Vector3::new(-50.0, -50.0, -5.0), Vector3::new(50.0, 50.0, 0.0)),+ ];+ walls.push(slab(+ Vector3::new(-50.0, -50.0, 80.0),+ Vector3::new(50.0, 50.0, 85.0),+ ));+ let occluders: Vec<Component> = walls+ .into_iter()+ .enumerate()+ .map(|(i, mesh)| component(&format!("wall{i}"), mesh))+ .collect();+ let occluder_refs: Vec<&Component> = occluders.iter().collect();+ let subject = component(+ "pcb",+ slab(Vector3::new(-20.0, -20.0, 5.0), Vector3::new(20.0, 20.0, 10.0)),+ );+ let (direction, obstruction) = best_view_direction(+ &subject,+ &Motion::None,+ &occluder_refs,+ &[],+ &Vector3::new(-50.0, -50.0, -5.0),+ &Vector3::new(50.0, 50.0, 85.0),+ );+ let n = (direction[0] * direction[0]+ + direction[1] * direction[1]+ + direction[2] * direction[2])+ .sqrt();+ assert!((n - 1.0).abs() < 1e-6);+ // Fully enclosed → every sight line is blocked; obstruction is high,+ // and notably higher than the open-top box (the signal for "hidden").+ assert!(+ obstruction > 0.9,+ "sealed box should report near-total obstruction, got {obstruction}"+ );+ }++ /// No occluders at all: an unobstructed part must not get a view fighting+ /// its travel (travel across the screen, not into it).+ #[test]+ fn open_air_prefers_travel_across_the_screen() {+ let subject = component(+ "bracket",+ slab(Vector3::new(-10.0, -10.0, 0.0), Vector3::new(10.0, 10.0, 10.0)),+ );+ let motion = Motion::Linear {+ direction: [1.0, 0.0, 0.0],+ distance: 50.0,+ };+ let (direction, obstruction) = best_view_direction(+ &subject,+ &motion,+ &[],+ &[],+ &Vector3::new(-100.0, -100.0, -10.0),+ &Vector3::new(100.0, 100.0, 50.0),+ );+ // |dot(view, +X travel)| stays under the 0.6 penalty knee+ assert!(+ direction[0].abs() < 0.7,+ "view fights the travel direction: {direction:?}"+ );+ // Nothing in the way → perfectly clear.+ assert_eq!(obstruction, 0.0);+ }++ /// The triangle BVH must return the exact same hit/no-hit verdict as a+ /// brute-force triangle walk — it's a pure speedup, not an approximation.+ /// Uses a MANY-slab scene so the tree is several levels deep with interior+ /// children: a shallow two-leaf tree hides right-child indexing bugs.+ #[test]+ fn bvh_matches_brute_force() {+ // 27 scattered slabs → hundreds of triangles → a multi-level BVH.+ let mut vertices = Vec::new();+ let mut faces = Vec::new();+ for gx in -1..=1 {+ for gy in -1..=1 {+ for gz in -1..=1 {+ let c = Vector3::new(gx as f64 * 40.0, gy as f64 * 40.0, gz as f64 * 40.0);+ let s = slab(c - Vector3::repeat(8.0), c + Vector3::repeat(8.0));+ let base = vertices.len() as u32;+ vertices.extend(s.vertices);+ faces.extend(s.faces.iter().map(|f| [f[0] + base, f[1] + base, f[2] + base]));+ }+ }+ }+ let mesh = Mesh { vertices, faces };+ assert!(mesh.faces.len() > 4 * BVH_LEAF_TRIS, "scene must force a deep tree");+ let bvh = TriBvh::build(&mesh);+ let brute = |eye: &Vector3<f64>, point: &Vector3<f64>| -> bool {+ let dir = point - eye;+ mesh.faces.iter().any(|f| {+ triangle_hit(+ eye,+ &dir,+ &mesh.vertices[f[0] as usize],+ &mesh.vertices[f[1] as usize],+ &mesh.vertices[f[2] as usize],+ )+ })+ };+ // A dense grid of segments through the scene: hits, misses, grazes.+ let coords = [-120.0, -40.0, -8.0, 0.0, 8.0, 40.0, 120.0];+ let mut any_hit = false;+ let mut any_miss = false;+ for &x in &coords {+ for &z in &coords {+ let eye = Vector3::new(x, -150.0, z);+ let point = Vector3::new(-x * 0.5, 150.0, z * 0.5);+ let bvh_hit = bvh.ray_hits(&eye, &point);+ assert_eq!(+ bvh_hit,+ brute(&eye, &point),+ "BVH disagrees with brute force for {eye:?}->{point:?}"+ );+ any_hit |= bvh_hit;+ any_miss |= !bvh_hit;+ }+ }+ // Not vacuous: the grid must contain both hits and misses.+ assert!(any_hit && any_miss, "test rays must cover hit and miss");+ }+}diff --git a/crates/planner/tests/plan_step_smoke.rs b/crates/planner/tests/plan_step_smoke.rsnew file mode 100644index 0000000000..0358d2c5a5--- /dev/null+++ b/crates/planner/tests/plan_step_smoke.rs@@ -0,0 +1,41 @@+//! End-to-end smoke: STEP fixture -> plan.json (version 3) via plan_step.++use planner::steps::plan_step;++#[test]+fn plan_step_plates() {+ let dir = match std::env::var("ASSEMBLER_FIXTURES") {+ Ok(d) => d,+ Err(_) => {+ eprintln!("ASSEMBLER_FIXTURES unset; skipping");+ return;+ }+ };+ let step = format!("{dir}/plates.step");+ let result =+ plan_step(&step, 0.1, 0.5, 0.5, 60, Some(5000), None, None, None).expect("plan_step");+ let plan = &result.plan;+ assert_eq!(plan["version"], 3);+ assert_eq!(plan["unit"], "mm");+ assert_eq!(result.component_count, 5);+ let seq = plan["sequence"].as_array().unwrap();+ assert_eq!(seq.len(), 5, "all 5 leaves sequenced");+ let comps = plan["components"].as_object().unwrap();+ assert_eq!(comps.len(), 5);+ // Every sequenced node has a component entry with a motion.+ for id in seq {+ let c = &comps[id.as_str().unwrap()];+ assert!(c.get("motion").is_some(), "component {id} has motion");+ }+ eprintln!(+ "plan_step plates: seq={:?} planned={} verified={} tiers={:?}",+ seq.iter().map(|v| v.as_str().unwrap()).collect::<Vec<_>>(),+ result.planned_count,+ result.verified_count,+ result+ .tiers+ .iter()+ .filter(|(_, v)| **v > 0)+ .collect::<Vec<_>>(),+ );+}diff --git a/crates/planner/tests/synthetic_plan.rs b/crates/planner/tests/synthetic_plan.rsnew file mode 100644index 0000000000..d2a3be728b--- /dev/null+++ b/crates/planner/tests/synthetic_plan.rs@@ -0,0 +1,237 @@+//! Planner core tests over synthetic geometry — no STEP/OCCT/fixtures, meshes+//! built in code. Mirrors the spirit of the former Python planner's test_plan:+//! assert plan behavior (sequencing, tiers, ordering invariants), not byte+//! output. Kept to robust invariants that any correct plan must satisfy, so+//! they don't wobble on exact float geometry.++use nalgebra::Vector3;+use planner::pipeline2::plan_parts;+use planner::types::{Component, Mesh, Motion};++/// Axis-aligned box: 8 corners, 12 triangles. `extents` are full side lengths.+fn box_part(node_id: &str, extents: [f64; 3], center: [f64; 3]) -> Component {+ let h = [extents[0] / 2.0, extents[1] / 2.0, extents[2] / 2.0];+ let mut verts = Vec::with_capacity(8);+ for &sz in &[-1.0f64, 1.0] {+ for &sy in &[-1.0f64, 1.0] {+ for &sx in &[-1.0f64, 1.0] {+ verts.push(Vector3::new(+ center[0] + sx * h[0],+ center[1] + sy * h[1],+ center[2] + sz * h[2],+ ));+ }+ }+ }+ // Corner index bits: bit0=x, bit1=y, bit2=z.+ let faces: Vec<[u32; 3]> = vec![+ [0, 1, 3],+ [0, 3, 2],+ [4, 7, 5],+ [4, 6, 7],+ [0, 4, 5],+ [0, 5, 1],+ [2, 3, 7],+ [2, 7, 6],+ [0, 2, 6],+ [0, 6, 4],+ [1, 5, 7],+ [1, 7, 3],+ ];+ let mesh = Mesh {+ vertices: verts,+ faces,+ };+ let (lo, hi) = mesh.bbox();+ Component::new(+ node_id.to_string(),+ node_id.to_string(),+ mesh,+ lo,+ hi,+ false,+ )+}++fn plan(parts: Vec<Component>) -> planner::pipeline2::PlanOutcome {+ let mut warnings = Vec::new();+ plan_parts(parts, 0.5, 40, 0.15, None, &mut warnings)+}++fn tier(outcome: &planner::pipeline2::PlanOutcome, key: &str) -> i64 {+ outcome.tiers.get(key).copied().unwrap_or(0)+}++#[test]+fn free_parts_all_plan_cleanly() {+ // Three well-separated boxes — all trivially removable, none flagged.+ let outcome = plan(vec![+ box_part("a", [4.0, 4.0, 4.0], [0.0, 0.0, 0.0]),+ box_part("b", [4.0, 4.0, 4.0], [20.0, 0.0, 0.0]),+ box_part("c", [4.0, 4.0, 4.0], [40.0, 0.0, 0.0]),+ ]);+ assert_eq!(outcome.sequence.len(), 3, "all three sequenced");+ assert_eq!(tier(&outcome, "forced"), 0);+ assert_eq!(tier(&outcome, "flagged"), 0);+ assert_eq!(tier(&outcome, "unplanned"), 0);+ // A part with a free direction gets a real linear motion.+ let any_linear = outcome+ .planned+ .iter()+ .any(|p| matches!(p.motion, Motion::Linear { .. }));+ assert!(+ any_linear,+ "at least one free part removed by a linear motion"+ );+}++#[test]+fn stacked_boxes_top_removed_before_base() {+ // Base on the ground, top seated on it. Whatever the exact motion, the top+ // must be sequenced before the base it rests on, and nothing is unplanned.+ let base = box_part("base", [10.0, 10.0, 4.0], [0.0, 0.0, 2.0]);+ let top = box_part("top", [10.0, 10.0, 4.0], [0.0, 0.0, 6.05]);+ let outcome = plan(vec![base, top]);++ assert_eq!(tier(&outcome, "unplanned"), 0, "both parts planned");+ let pos = |id: &str| outcome.sequence.iter().position(|s| s == id);+ let (top_i, base_i) = (pos("top"), pos("base"));+ assert!(top_i.is_some() && base_i.is_some(), "both in sequence");+ assert!(+ top_i < base_i,+ "top removed before base: {:?}",+ outcome.sequence+ );+}++#[test]+fn every_planned_part_is_sequenced_once() {+ // Structural invariant: the sequence is a permutation of the planned set —+ // no dropped or duplicated components.+ let outcome = plan(vec![+ box_part("p0", [6.0, 6.0, 4.0], [0.0, 0.0, 2.0]),+ box_part("p1", [6.0, 6.0, 4.0], [0.0, 0.0, 6.05]),+ box_part("p2", [4.0, 4.0, 4.0], [30.0, 0.0, 0.0]),+ ]);+ let mut seq = outcome.sequence.clone();+ seq.sort();+ seq.dedup();+ assert_eq!(+ seq.len(),+ outcome.sequence.len(),+ "no duplicate in sequence"+ );+ assert_eq!(outcome.sequence.len(), 3, "all components sequenced");+ assert_eq!(tier(&outcome, "unplanned"), 0);+}++#[test]+fn detects_a_pcb_detail_swarm_and_excludes_fasteners() {+ use planner::pipeline2::detect_swarm_units;+ use std::collections::HashSet;++ // A populated board: 100x80 plate with 20 tiny components seated on its top+ // face — plus a far-away bracket carrying 8 tiny screw-named parts (a lid+ // shape that must NOT become a swarm: fastener-named parts never join).+ let mut parts = vec![box_part("board", [100.0, 80.0, 1.6], [0.0, 0.0, 0.8])];+ for i in 0..20 {+ let x = -45.0 + 4.5 * i as f64;+ parts.push(box_part(&format!("c{i}"), [2.0, 1.0, 1.0], [x, 10.0, 2.1]));+ }+ parts.push(box_part("bracket", [60.0, 60.0, 3.0], [220.0, 0.0, 1.5]));+ for i in 0..8 {+ let x = 195.0 + 7.0 * i as f64;+ parts.push(box_part(+ &format!("m3 screw {i}"),+ [2.0, 2.0, 2.0],+ [x, 0.0, 4.0],+ ));+ }++ let specs = detect_swarm_units(&parts, &HashSet::new());+ assert_eq!(specs.len(), 1, "exactly one swarm: {specs:?}");+ let (id, name, node_ids) = &specs[0];+ assert_eq!(id, "swarm:board");+ assert_eq!(name.as_deref(), Some("board"));+ assert_eq!(node_ids.len(), 21, "board + 20 components");+ assert!(node_ids.iter().all(|n| !n.contains("screw")));+}++#[test]+fn mid_size_parts_on_a_rail_are_not_a_swarm() {+ use planner::pipeline2::detect_swarm_units;+ use std::collections::HashSet;++ // Packing-Arm shape: a long rail in a LARGE assembly carrying 14 mid-size+ // parts. They are tiny vs the assembly (~4%) but NOT dwarfed by the host+ // (~23% of its diagonal) — real hand-assembled parts, not a PCB swarm.+ let mut parts = vec![box_part("rail", [180.0, 40.0, 10.0], [0.0, 0.0, 5.0])];+ for i in 0..14 {+ let x = -78.0 + 12.0 * i as f64;+ parts.push(box_part(+ &format!("roller{i}"),+ [25.0, 15.0, 12.0],+ [x, 0.0, 16.05],+ ));+ }+ // A distant part stretches the assembly bounds (mimics the wide machine).+ parts.push(box_part("far", [40.0, 40.0, 40.0], [650.0, 0.0, 20.0]));++ let specs = detect_swarm_units(&parts, &HashSet::new());+ assert!(specs.is_empty(), "no swarm expected: {specs:?}");+}++#[cfg(test)]+mod waves {+ use planner::pipeline2::compute_waves;+ use std::collections::{HashMap, HashSet};++ fn edges(pairs: &[(&str, &[&str])]) -> HashMap<String, HashSet<String>> {+ // Every node that appears must be a key (derive_precedence seeds all).+ let mut e: HashMap<String, HashSet<String>> = HashMap::new();+ for (k, vs) in pairs {+ e.entry(k.to_string()).or_default();+ for v in *vs {+ e.entry(v.to_string()).or_default();+ e.get_mut(*k).unwrap().insert(v.to_string());+ }+ }+ e+ }++ #[test]+ fn linear_chain_levels_incrementally() {+ // a -> b -> c (a before b before c)+ let w = compute_waves(&edges(&[("a", &["b"]), ("b", &["c"])]));+ assert_eq!(w["a"], 0);+ assert_eq!(w["b"], 1);+ assert_eq!(w["c"], 2);+ }++ #[test]+ fn diamond_shares_a_middle_wave() {+ // a -> b, a -> c, b -> d, c -> d+ let w = compute_waves(&edges(&[("a", &["b", "c"]), ("b", &["d"]), ("c", &["d"])]));+ assert_eq!(w["a"], 0);+ assert_eq!(w["b"], 1);+ assert_eq!(w["c"], 1); // b and c: same wave, no constraint between them+ assert_eq!(w["d"], 2);+ }++ #[test]+ fn independent_parts_are_all_wave_zero() {+ let w = compute_waves(&edges(&[("a", &[]), ("b", &[]), ("c", &[])]));+ assert_eq!(w["a"], 0);+ assert_eq!(w["b"], 0);+ assert_eq!(w["c"], 0);+ }++ #[test]+ fn cycle_nodes_get_no_wave() {+ // a -> b -> a is a cycle; c is a clean root+ let w = compute_waves(&edges(&[("a", &["b"]), ("b", &["a"]), ("c", &[])]));+ assert!(!w.contains_key("a"));+ assert!(!w.contains_key("b"));+ assert_eq!(w["c"], 0);+ }+}diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex e043bc1969..17bca5f8be 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -357,6 +357,7 @@ export type Database = {lotSizeVarianceAccount: stringmaintenanceAccount: stringmaterialVarianceAccount: string+ overheadAbsorptionAccount: string | nulloverheadVarianceAccount: stringpayablesAccount: stringprepaymentAccount: string@@ -374,6 +375,7 @@ export type Database = {serviceChargeAccount: stringsubcontractingVarianceAccount: stringsupplierPaymentDiscountAccount: string+ supplierPrepaymentAccount: stringsupplierWriteOffAccount: stringupdatedBy: string | nullworkInProgressAccount: string@@ -407,6 +409,7 @@ export type Database = {lotSizeVarianceAccount: stringmaintenanceAccount: stringmaterialVarianceAccount: string+ overheadAbsorptionAccount?: string | nulloverheadVarianceAccount: stringpayablesAccount: stringprepaymentAccount: string@@ -424,6 +427,7 @@ export type Database = {serviceChargeAccount: stringsubcontractingVarianceAccount: stringsupplierPaymentDiscountAccount: string+ supplierPrepaymentAccount: stringsupplierWriteOffAccount: stringupdatedBy?: string | nullworkInProgressAccount: string@@ -457,6 +461,7 @@ export type Database = {lotSizeVarianceAccount?: stringmaintenanceAccount?: stringmaterialVarianceAccount?: string+ overheadAbsorptionAccount?: string | nulloverheadVarianceAccount?: stringpayablesAccount?: stringprepaymentAccount?: string@@ -474,6 +479,7 @@ export type Database = {serviceChargeAccount?: stringsubcontractingVarianceAccount?: stringsupplierPaymentDiscountAccount?: string+ supplierPrepaymentAccount?: stringsupplierWriteOffAccount?: stringupdatedBy?: string | nullworkInProgressAccount?: string@@ -885,6 +891,20 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_overheadAbsorptionAccount_fkey"+ columns: ["overheadAbsorptionAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_overheadAbsorptionAccount_fkey"+ columns: ["overheadAbsorptionAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_overheadVarianceAccount_fkey"columns: ["overheadVarianceAccount"]@@ -1123,6 +1143,20 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_supplierPrepaymentAccount_fkey"+ columns: ["supplierPrepaymentAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_supplierPrepaymentAccount_fkey"+ columns: ["supplierPrepaymentAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_supplierWriteOffAccount_fkey"columns: ["supplierWriteOffAccount"]@@ -2064,200 +2098,200 @@ export type Database = {},]}- assemblyUnit: {+ assemblyComponentMapping: {Row: {companyId: string+ confidence: stringcreatedAt: stringcreatedBy: string+ geometryHash: stringid: string- itemId: string | null+ itemId: stringmodelUploadId: string- name: string- componentNodeIds: string[]updatedAt: string | nullupdatedBy: string | null}Insert: {companyId: string+ confidence?: stringcreatedAt?: stringcreatedBy: string+ geometryHash: stringid?: string- itemId?: string | null+ itemId: stringmodelUploadId: string- name: string- componentNodeIds?: string[]updatedAt?: string | nullupdatedBy?: string | null}Update: {companyId?: string+ confidence?: stringcreatedAt?: stringcreatedBy?: string+ geometryHash?: stringid?: string- itemId?: string | null+ itemId?: stringmodelUploadId?: string- name?: string- componentNodeIds?: string[]updatedAt?: string | nullupdatedBy?: string | null}Relationships: [{- foreignKeyName: "assemblyUnit_companyId_fkey"+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "companies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_companyId_fkey"+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "company"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_companyId_fkey"+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "customFieldTables"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyUnit_companyId_fkey"+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "integrations"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyUnit_createdBy_fkey"+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_createdBy_fkey"+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_createdBy_fkey"+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_createdBy_fkey"+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_createdBy_fkey"+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "userDefaults"referencedColumns: ["userId"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "consumables"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "item"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "materials"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "parts"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "services"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "tools"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_modelUploadId_fkey"+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "jobs"referencedColumns: ["modelId"]},{- foreignKeyName: "assemblyUnit_modelUploadId_fkey"+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "modelUpload"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_modelUploadId_fkey"+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "salesRfqLines"referencedColumns: ["modelId"]},{- foreignKeyName: "assemblyUnit_updatedBy_fkey"+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_updatedBy_fkey"+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_updatedBy_fkey"+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_updatedBy_fkey"+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_updatedBy_fkey"+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "userDefaults"@@ -2494,8 +2528,10 @@ export type Database = {assemblyInstructionStep: {Row: {assemblyInstructionId: string+ buildWave: number | nullcamera: Json | nullcompanyId: string+ componentNodeIds: string[]createdAt: stringcreatedBy: stringdescription: Json | null@@ -2511,7 +2547,6 @@ export type Database = {motion: Jsonnotes: Json | nullparentStepId: string | null- componentNodeIds: string[]planConfidence: stringrequired: boolean | nullsortOrder: number@@ -2525,8 +2560,10 @@ export type Database = {}Insert: {assemblyInstructionId: string+ buildWave?: number | nullcamera?: Json | nullcompanyId: string+ componentNodeIds?: string[]createdAt?: stringcreatedBy: stringdescription?: Json | null@@ -2542,7 +2579,6 @@ export type Database = {motion?: Jsonnotes?: Json | nullparentStepId?: string | null- componentNodeIds?: string[]planConfidence?: stringrequired?: boolean | nullsortOrder?: number@@ -2556,8 +2592,10 @@ export type Database = {}Update: {assemblyInstructionId?: string+ buildWave?: number | nullcamera?: Json | nullcompanyId?: string+ componentNodeIds?: string[]createdAt?: stringcreatedBy?: stringdescription?: Json | null@@ -2573,7 +2611,6 @@ export type Database = {motion?: Jsonnotes?: Json | nullparentStepId?: string | null- componentNodeIds?: string[]planConfidence?: stringrequired?: boolean | nullsortOrder?: number@@ -3096,462 +3133,465 @@ export type Database = {},]}- assemblyComponentMapping: {+ assemblyPlanJob: {Row: {companyId: string- confidence: stringcreatedAt: stringcreatedBy: string- geometryHash: string+ error: string | nullid: string- itemId: string+ kind: stringmodelUploadId: string+ planPath: string | null+ stats: Json | null+ status: Database["public"]["Enums"]["modelProcessingStatus"]updatedAt: string | null- updatedBy: string | null}Insert: {companyId: string- confidence?: stringcreatedAt?: stringcreatedBy: string- geometryHash: string+ error?: string | nullid?: string- itemId: string+ kind: stringmodelUploadId: string+ planPath?: string | null+ stats?: Json | null+ status?: Database["public"]["Enums"]["modelProcessingStatus"]updatedAt?: string | null- updatedBy?: string | null}Update: {companyId?: string- confidence?: stringcreatedAt?: stringcreatedBy?: string- geometryHash?: string+ error?: string | nullid?: string- itemId?: string+ kind?: stringmodelUploadId?: string+ planPath?: string | null+ stats?: Json | null+ status?: Database["public"]["Enums"]["modelProcessingStatus"]updatedAt?: string | null- updatedBy?: string | null}Relationships: [{- foreignKeyName: "assemblyComponentMapping_companyId_fkey"+ foreignKeyName: "assemblyPlanJob_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "companies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_companyId_fkey"+ foreignKeyName: "assemblyPlanJob_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "company"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_companyId_fkey"+ foreignKeyName: "assemblyPlanJob_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "customFieldTables"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyComponentMapping_companyId_fkey"+ foreignKeyName: "assemblyPlanJob_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "integrations"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyComponentMapping_createdBy_fkey"+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_createdBy_fkey"+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_createdBy_fkey"+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_createdBy_fkey"+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_createdBy_fkey"+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "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"+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "jobs"referencedColumns: ["modelId"]},{- foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "modelUpload"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "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: {+ assemblyStandardNote: {Row: {companyId: string+ content: stringcreatedAt: stringcreatedBy: string- error: string | nullid: string- kind: string- modelUploadId: string- planPath: string | null- stats: Json | null- status: Database["public"]["Enums"]["modelProcessingStatus"]+ name: string+ severity: Database["public"]["Enums"]["assemblyNoteSeverity"]updatedAt: string | null+ updatedBy: string | null}Insert: {companyId: string+ content: stringcreatedAt?: stringcreatedBy: string- error?: string | nullid?: string- kind: string- modelUploadId: string- planPath?: string | null- stats?: Json | null- status?: Database["public"]["Enums"]["modelProcessingStatus"]+ name: string+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]updatedAt?: string | null+ updatedBy?: string | null}Update: {companyId?: string+ content?: stringcreatedAt?: stringcreatedBy?: string- error?: string | nullid?: string- kind?: string- modelUploadId?: string- planPath?: string | null- stats?: Json | null- status?: Database["public"]["Enums"]["modelProcessingStatus"]+ name?: string+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]updatedAt?: string | null+ updatedBy?: string | null}Relationships: [{- foreignKeyName: "assemblyPlanJob_companyId_fkey"+ foreignKeyName: "assemblyStandardNote_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "companies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_companyId_fkey"+ foreignKeyName: "assemblyStandardNote_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "company"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_companyId_fkey"+ foreignKeyName: "assemblyStandardNote_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "customFieldTables"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyPlanJob_companyId_fkey"+ foreignKeyName: "assemblyStandardNote_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "integrations"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyPlanJob_createdBy_fkey"+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_createdBy_fkey"+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_createdBy_fkey"+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_createdBy_fkey"+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_createdBy_fkey"+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "userDefaults"referencedColumns: ["userId"]},{- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"- columns: ["modelUploadId"]+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ columns: ["updatedBy"]isOneToOne: false- referencedRelation: "jobs"- referencedColumns: ["modelId"]+ referencedRelation: "employees"+ referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"- columns: ["modelUploadId"]+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ columns: ["updatedBy"]isOneToOne: false- referencedRelation: "modelUpload"+ referencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"- columns: ["modelUploadId"]+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ columns: ["updatedBy"]isOneToOne: false- referencedRelation: "salesRfqLines"- referencedColumns: ["modelId"]+ 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"]},]}- assemblyStandardNote: {+ assemblyUnit: {Row: {companyId: string- content: string+ componentNodeIds: string[]createdAt: stringcreatedBy: stringid: string+ itemId: string | null+ modelUploadId: stringname: string- severity: Database["public"]["Enums"]["assemblyNoteSeverity"]+ sourceGroupId: string | nullupdatedAt: string | nullupdatedBy: string | null}Insert: {companyId: string- content: string+ componentNodeIds?: string[]createdAt?: stringcreatedBy: stringid?: string+ itemId?: string | null+ modelUploadId: stringname: string- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]+ sourceGroupId?: string | nullupdatedAt?: string | nullupdatedBy?: string | null}Update: {companyId?: string- content?: string+ componentNodeIds?: string[]createdAt?: stringcreatedBy?: stringid?: string+ itemId?: string | null+ modelUploadId?: stringname?: string- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]+ sourceGroupId?: string | nullupdatedAt?: string | nullupdatedBy?: string | null}Relationships: [{- foreignKeyName: "assemblyStandardNote_companyId_fkey"+ foreignKeyName: "assemblyUnit_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "companies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_companyId_fkey"+ foreignKeyName: "assemblyUnit_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "company"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_companyId_fkey"+ foreignKeyName: "assemblyUnit_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "customFieldTables"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyStandardNote_companyId_fkey"+ foreignKeyName: "assemblyUnit_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "integrations"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyStandardNote_createdBy_fkey"+ foreignKeyName: "assemblyUnit_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_createdBy_fkey"+ foreignKeyName: "assemblyUnit_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_createdBy_fkey"+ foreignKeyName: "assemblyUnit_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_createdBy_fkey"+ foreignKeyName: "assemblyUnit_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_createdBy_fkey"+ foreignKeyName: "assemblyUnit_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "userDefaults"referencedColumns: ["userId"]},{- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ 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: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ foreignKeyName: "assemblyUnit_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ foreignKeyName: "assemblyUnit_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ foreignKeyName: "assemblyUnit_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ foreignKeyName: "assemblyUnit_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "userDefaults"@@ -25939,6 +25979,7 @@ export type Database = {Row: {autodeskUrn: string | nullcompanyId: string+ componentCount: number | nullcreatedAt: string | nullcreatedBy: stringglbPath: string | null@@ -25946,7 +25987,6 @@ export type Database = {id: stringmodelPath: stringname: string | null- componentCount: number | nullprocessedAt: string | nullprocessingError: string | nullprocessingStatus: Database["public"]["Enums"]["modelProcessingStatus"]@@ -25958,6 +25998,7 @@ export type Database = {Insert: {autodeskUrn?: string | nullcompanyId: string+ componentCount?: number | nullcreatedAt?: string | nullcreatedBy: stringglbPath?: string | null@@ -25965,7 +26006,6 @@ export type Database = {id?: stringmodelPath: stringname?: string | null- componentCount?: number | nullprocessedAt?: string | nullprocessingError?: string | nullprocessingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]@@ -25977,6 +26017,7 @@ export type Database = {Update: {autodeskUrn?: string | nullcompanyId?: string+ componentCount?: number | nullcreatedAt?: string | nullcreatedBy?: stringglbPath?: string | null@@ -25984,7 +26025,6 @@ export type Database = {id?: stringmodelPath?: stringname?: string | null- componentCount?: number | nullprocessedAt?: string | nullprocessingError?: string | nullprocessingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]@@ -43578,48 +43618,6 @@ 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@@ -60045,14 +60043,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -61692,14 +61690,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -65076,21 +65074,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -65638,14 +65636,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -69398,6 +69396,7 @@ export type Database = {p_exclude_lineside?: booleanp_item_id: stringp_location_id: string+ p_sort_method?: string}Returns: {availableQuantity: numberdiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex e043bc1969..17bca5f8be 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -357,6 +357,7 @@ export type Database = {lotSizeVarianceAccount: stringmaintenanceAccount: stringmaterialVarianceAccount: string+ overheadAbsorptionAccount: string | nulloverheadVarianceAccount: stringpayablesAccount: stringprepaymentAccount: string@@ -374,6 +375,7 @@ export type Database = {serviceChargeAccount: stringsubcontractingVarianceAccount: stringsupplierPaymentDiscountAccount: string+ supplierPrepaymentAccount: stringsupplierWriteOffAccount: stringupdatedBy: string | nullworkInProgressAccount: string@@ -407,6 +409,7 @@ export type Database = {lotSizeVarianceAccount: stringmaintenanceAccount: stringmaterialVarianceAccount: string+ overheadAbsorptionAccount?: string | nulloverheadVarianceAccount: stringpayablesAccount: stringprepaymentAccount: string@@ -424,6 +427,7 @@ export type Database = {serviceChargeAccount: stringsubcontractingVarianceAccount: stringsupplierPaymentDiscountAccount: string+ supplierPrepaymentAccount: stringsupplierWriteOffAccount: stringupdatedBy?: string | nullworkInProgressAccount: string@@ -457,6 +461,7 @@ export type Database = {lotSizeVarianceAccount?: stringmaintenanceAccount?: stringmaterialVarianceAccount?: string+ overheadAbsorptionAccount?: string | nulloverheadVarianceAccount?: stringpayablesAccount?: stringprepaymentAccount?: string@@ -474,6 +479,7 @@ export type Database = {serviceChargeAccount?: stringsubcontractingVarianceAccount?: stringsupplierPaymentDiscountAccount?: string+ supplierPrepaymentAccount?: stringsupplierWriteOffAccount?: stringupdatedBy?: string | nullworkInProgressAccount?: string@@ -885,6 +891,20 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_overheadAbsorptionAccount_fkey"+ columns: ["overheadAbsorptionAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_overheadAbsorptionAccount_fkey"+ columns: ["overheadAbsorptionAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_overheadVarianceAccount_fkey"columns: ["overheadVarianceAccount"]@@ -1123,6 +1143,20 @@ export type Database = {referencedRelation: "accounts"referencedColumns: ["id"]},+ {+ foreignKeyName: "accountDefault_supplierPrepaymentAccount_fkey"+ columns: ["supplierPrepaymentAccount"]+ isOneToOne: false+ referencedRelation: "account"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "accountDefault_supplierPrepaymentAccount_fkey"+ columns: ["supplierPrepaymentAccount"]+ isOneToOne: false+ referencedRelation: "accounts"+ referencedColumns: ["id"]+ },{foreignKeyName: "accountDefault_supplierWriteOffAccount_fkey"columns: ["supplierWriteOffAccount"]@@ -2064,200 +2098,200 @@ export type Database = {},]}- assemblyUnit: {+ assemblyComponentMapping: {Row: {companyId: string+ confidence: stringcreatedAt: stringcreatedBy: string+ geometryHash: stringid: string- itemId: string | null+ itemId: stringmodelUploadId: string- name: string- componentNodeIds: string[]updatedAt: string | nullupdatedBy: string | null}Insert: {companyId: string+ confidence?: stringcreatedAt?: stringcreatedBy: string+ geometryHash: stringid?: string- itemId?: string | null+ itemId: stringmodelUploadId: string- name: string- componentNodeIds?: string[]updatedAt?: string | nullupdatedBy?: string | null}Update: {companyId?: string+ confidence?: stringcreatedAt?: stringcreatedBy?: string+ geometryHash?: stringid?: string- itemId?: string | null+ itemId?: stringmodelUploadId?: string- name?: string- componentNodeIds?: string[]updatedAt?: string | nullupdatedBy?: string | null}Relationships: [{- foreignKeyName: "assemblyUnit_companyId_fkey"+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "companies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_companyId_fkey"+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "company"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_companyId_fkey"+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "customFieldTables"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyUnit_companyId_fkey"+ foreignKeyName: "assemblyComponentMapping_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "integrations"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyUnit_createdBy_fkey"+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_createdBy_fkey"+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_createdBy_fkey"+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_createdBy_fkey"+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_createdBy_fkey"+ foreignKeyName: "assemblyComponentMapping_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "userDefaults"referencedColumns: ["userId"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "consumables"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "item"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "materials"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "parts"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "services"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_itemId_fkey"+ foreignKeyName: "assemblyComponentMapping_itemId_fkey"columns: ["itemId"]isOneToOne: falsereferencedRelation: "tools"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_modelUploadId_fkey"+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "jobs"referencedColumns: ["modelId"]},{- foreignKeyName: "assemblyUnit_modelUploadId_fkey"+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "modelUpload"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_modelUploadId_fkey"+ foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "salesRfqLines"referencedColumns: ["modelId"]},{- foreignKeyName: "assemblyUnit_updatedBy_fkey"+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_updatedBy_fkey"+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_updatedBy_fkey"+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_updatedBy_fkey"+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyUnit_updatedBy_fkey"+ foreignKeyName: "assemblyComponentMapping_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "userDefaults"@@ -2494,8 +2528,10 @@ export type Database = {assemblyInstructionStep: {Row: {assemblyInstructionId: string+ buildWave: number | nullcamera: Json | nullcompanyId: string+ componentNodeIds: string[]createdAt: stringcreatedBy: stringdescription: Json | null@@ -2511,7 +2547,6 @@ export type Database = {motion: Jsonnotes: Json | nullparentStepId: string | null- componentNodeIds: string[]planConfidence: stringrequired: boolean | nullsortOrder: number@@ -2525,8 +2560,10 @@ export type Database = {}Insert: {assemblyInstructionId: string+ buildWave?: number | nullcamera?: Json | nullcompanyId: string+ componentNodeIds?: string[]createdAt?: stringcreatedBy: stringdescription?: Json | null@@ -2542,7 +2579,6 @@ export type Database = {motion?: Jsonnotes?: Json | nullparentStepId?: string | null- componentNodeIds?: string[]planConfidence?: stringrequired?: boolean | nullsortOrder?: number@@ -2556,8 +2592,10 @@ export type Database = {}Update: {assemblyInstructionId?: string+ buildWave?: number | nullcamera?: Json | nullcompanyId?: string+ componentNodeIds?: string[]createdAt?: stringcreatedBy?: stringdescription?: Json | null@@ -2573,7 +2611,6 @@ export type Database = {motion?: Jsonnotes?: Json | nullparentStepId?: string | null- componentNodeIds?: string[]planConfidence?: stringrequired?: boolean | nullsortOrder?: number@@ -3096,462 +3133,465 @@ export type Database = {},]}- assemblyComponentMapping: {+ assemblyPlanJob: {Row: {companyId: string- confidence: stringcreatedAt: stringcreatedBy: string- geometryHash: string+ error: string | nullid: string- itemId: string+ kind: stringmodelUploadId: string+ planPath: string | null+ stats: Json | null+ status: Database["public"]["Enums"]["modelProcessingStatus"]updatedAt: string | null- updatedBy: string | null}Insert: {companyId: string- confidence?: stringcreatedAt?: stringcreatedBy: string- geometryHash: string+ error?: string | nullid?: string- itemId: string+ kind: stringmodelUploadId: string+ planPath?: string | null+ stats?: Json | null+ status?: Database["public"]["Enums"]["modelProcessingStatus"]updatedAt?: string | null- updatedBy?: string | null}Update: {companyId?: string- confidence?: stringcreatedAt?: stringcreatedBy?: string- geometryHash?: string+ error?: string | nullid?: string- itemId?: string+ kind?: stringmodelUploadId?: string+ planPath?: string | null+ stats?: Json | null+ status?: Database["public"]["Enums"]["modelProcessingStatus"]updatedAt?: string | null- updatedBy?: string | null}Relationships: [{- foreignKeyName: "assemblyComponentMapping_companyId_fkey"+ foreignKeyName: "assemblyPlanJob_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "companies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_companyId_fkey"+ foreignKeyName: "assemblyPlanJob_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "company"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_companyId_fkey"+ foreignKeyName: "assemblyPlanJob_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "customFieldTables"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyComponentMapping_companyId_fkey"+ foreignKeyName: "assemblyPlanJob_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "integrations"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyComponentMapping_createdBy_fkey"+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_createdBy_fkey"+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_createdBy_fkey"+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_createdBy_fkey"+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_createdBy_fkey"+ foreignKeyName: "assemblyPlanJob_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "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"+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "jobs"referencedColumns: ["modelId"]},{- foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "modelUpload"referencedColumns: ["id"]},{- foreignKeyName: "assemblyComponentMapping_modelUploadId_fkey"+ foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"columns: ["modelUploadId"]isOneToOne: falsereferencedRelation: "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: {+ assemblyStandardNote: {Row: {companyId: string+ content: stringcreatedAt: stringcreatedBy: string- error: string | nullid: string- kind: string- modelUploadId: string- planPath: string | null- stats: Json | null- status: Database["public"]["Enums"]["modelProcessingStatus"]+ name: string+ severity: Database["public"]["Enums"]["assemblyNoteSeverity"]updatedAt: string | null+ updatedBy: string | null}Insert: {companyId: string+ content: stringcreatedAt?: stringcreatedBy: string- error?: string | nullid?: string- kind: string- modelUploadId: string- planPath?: string | null- stats?: Json | null- status?: Database["public"]["Enums"]["modelProcessingStatus"]+ name: string+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]updatedAt?: string | null+ updatedBy?: string | null}Update: {companyId?: string+ content?: stringcreatedAt?: stringcreatedBy?: string- error?: string | nullid?: string- kind?: string- modelUploadId?: string- planPath?: string | null- stats?: Json | null- status?: Database["public"]["Enums"]["modelProcessingStatus"]+ name?: string+ severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]updatedAt?: string | null+ updatedBy?: string | null}Relationships: [{- foreignKeyName: "assemblyPlanJob_companyId_fkey"+ foreignKeyName: "assemblyStandardNote_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "companies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_companyId_fkey"+ foreignKeyName: "assemblyStandardNote_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "company"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_companyId_fkey"+ foreignKeyName: "assemblyStandardNote_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "customFieldTables"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyPlanJob_companyId_fkey"+ foreignKeyName: "assemblyStandardNote_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "integrations"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyPlanJob_createdBy_fkey"+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_createdBy_fkey"+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_createdBy_fkey"+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_createdBy_fkey"+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_createdBy_fkey"+ foreignKeyName: "assemblyStandardNote_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "userDefaults"referencedColumns: ["userId"]},{- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"- columns: ["modelUploadId"]+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ columns: ["updatedBy"]isOneToOne: false- referencedRelation: "jobs"- referencedColumns: ["modelId"]+ referencedRelation: "employees"+ referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"- columns: ["modelUploadId"]+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ columns: ["updatedBy"]isOneToOne: false- referencedRelation: "modelUpload"+ referencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyPlanJob_modelUploadId_fkey"- columns: ["modelUploadId"]+ foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ columns: ["updatedBy"]isOneToOne: false- referencedRelation: "salesRfqLines"- referencedColumns: ["modelId"]+ 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"]},]}- assemblyStandardNote: {+ assemblyUnit: {Row: {companyId: string- content: string+ componentNodeIds: string[]createdAt: stringcreatedBy: stringid: string+ itemId: string | null+ modelUploadId: stringname: string- severity: Database["public"]["Enums"]["assemblyNoteSeverity"]+ sourceGroupId: string | nullupdatedAt: string | nullupdatedBy: string | null}Insert: {companyId: string- content: string+ componentNodeIds?: string[]createdAt?: stringcreatedBy: stringid?: string+ itemId?: string | null+ modelUploadId: stringname: string- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]+ sourceGroupId?: string | nullupdatedAt?: string | nullupdatedBy?: string | null}Update: {companyId?: string- content?: string+ componentNodeIds?: string[]createdAt?: stringcreatedBy?: stringid?: string+ itemId?: string | null+ modelUploadId?: stringname?: string- severity?: Database["public"]["Enums"]["assemblyNoteSeverity"]+ sourceGroupId?: string | nullupdatedAt?: string | nullupdatedBy?: string | null}Relationships: [{- foreignKeyName: "assemblyStandardNote_companyId_fkey"+ foreignKeyName: "assemblyUnit_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "companies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_companyId_fkey"+ foreignKeyName: "assemblyUnit_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "company"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_companyId_fkey"+ foreignKeyName: "assemblyUnit_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "customFieldTables"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyStandardNote_companyId_fkey"+ foreignKeyName: "assemblyUnit_companyId_fkey"columns: ["companyId"]isOneToOne: falsereferencedRelation: "integrations"referencedColumns: ["companyId"]},{- foreignKeyName: "assemblyStandardNote_createdBy_fkey"+ foreignKeyName: "assemblyUnit_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_createdBy_fkey"+ foreignKeyName: "assemblyUnit_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_createdBy_fkey"+ foreignKeyName: "assemblyUnit_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_createdBy_fkey"+ foreignKeyName: "assemblyUnit_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_createdBy_fkey"+ foreignKeyName: "assemblyUnit_createdBy_fkey"columns: ["createdBy"]isOneToOne: falsereferencedRelation: "userDefaults"referencedColumns: ["userId"]},{- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ 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: falsereferencedRelation: "employees"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ foreignKeyName: "assemblyUnit_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employeesAcrossCompanies"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ foreignKeyName: "assemblyUnit_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "employeeSummary"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ foreignKeyName: "assemblyUnit_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "user"referencedColumns: ["id"]},{- foreignKeyName: "assemblyStandardNote_updatedBy_fkey"+ foreignKeyName: "assemblyUnit_updatedBy_fkey"columns: ["updatedBy"]isOneToOne: falsereferencedRelation: "userDefaults"@@ -25939,6 +25979,7 @@ export type Database = {Row: {autodeskUrn: string | nullcompanyId: string+ componentCount: number | nullcreatedAt: string | nullcreatedBy: stringglbPath: string | null@@ -25946,7 +25987,6 @@ export type Database = {id: stringmodelPath: stringname: string | null- componentCount: number | nullprocessedAt: string | nullprocessingError: string | nullprocessingStatus: Database["public"]["Enums"]["modelProcessingStatus"]@@ -25958,6 +25998,7 @@ export type Database = {Insert: {autodeskUrn?: string | nullcompanyId: string+ componentCount?: number | nullcreatedAt?: string | nullcreatedBy: stringglbPath?: string | null@@ -25965,7 +26006,6 @@ export type Database = {id?: stringmodelPath: stringname?: string | null- componentCount?: number | nullprocessedAt?: string | nullprocessingError?: string | nullprocessingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]@@ -25977,6 +26017,7 @@ export type Database = {Update: {autodeskUrn?: string | nullcompanyId?: string+ componentCount?: number | nullcreatedAt?: string | nullcreatedBy?: stringglbPath?: string | null@@ -25984,7 +26025,6 @@ export type Database = {id?: stringmodelPath?: stringname?: string | null- componentCount?: number | nullprocessedAt?: string | nullprocessingError?: string | nullprocessingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]@@ -43578,48 +43618,6 @@ 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@@ -60045,14 +60043,14 @@ export type Database = {},{foreignKeyName: "partner_id_fkey"- columns: ["id"]+ columns: ["supplierLocationId"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]},{foreignKeyName: "partner_id_fkey"- columns: ["supplierLocationId"]+ columns: ["id"]isOneToOne: falsereferencedRelation: "supplierLocation"referencedColumns: ["id"]@@ -61692,14 +61690,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -65076,21 +65074,21 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["shipmentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["invoiceCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["invoiceCountryCode"]+ columns: ["shipmentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -65638,14 +65636,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["paymentCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["paymentCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]@@ -69398,6 +69396,7 @@ export type Database = {p_exclude_lineside?: booleanp_item_id: stringp_location_id: string+ p_sort_method?: string}Returns: {availableQuantity: numberdiff --git a/packages/database/supabase/migrations/20260711000415_enable_realtime_assembly_plan_job.sql b/packages/database/supabase/migrations/20260711000415_enable_realtime_assembly_plan_job.sqlnew file mode 100644index 0000000000..b432f54fe3--- /dev/null+++ b/packages/database/supabase/migrations/20260711000415_enable_realtime_assembly_plan_job.sql@@ -0,0 +1,5 @@+-- Realtime on assemblyPlanJob: the assembly-instruction UI subscribes to plan+-- job status flips (Queued → Processing → Success/Failed) so plan completion+-- pushes to the browser instead of relying on a component-local polling flag+-- that dies on remount.+ALTER PUBLICATION supabase_realtime ADD TABLE "assemblyPlanJob";diff --git a/packages/database/supabase/migrations/20260712163840_assembly-unit-source-group.sql b/packages/database/supabase/migrations/20260712163840_assembly-unit-source-group.sqlnew file mode 100644index 0000000000..d6a82167d1--- /dev/null+++ b/packages/database/supabase/migrations/20260712163840_assembly-unit-source-group.sql@@ -0,0 +1,11 @@+-- Planner-detected groups (e.g. PCB detail swarms, plan.json groups with+-- id "swarm:<hostNodeId>") are materialized as assemblyUnit rows at step+-- generation so the Components tab shows them like authored units.+-- sourceGroupId carries the plan group id; NULL = user-authored.+-- The UNIQUE pair makes re-generation idempotent (upsert DO NOTHING);+-- NULLs are distinct, so authored rows are unaffected.+ALTER TABLE "assemblyUnit" ADD COLUMN "sourceGroupId" TEXT;++ALTER TABLE "assemblyUnit"+ ADD CONSTRAINT "assemblyUnit_modelUploadId_sourceGroupId_key"+ UNIQUE ("modelUploadId", "sourceGroupId");diff --git a/packages/database/supabase/migrations/20260712180545_assembly-step-build-wave.sql b/packages/database/supabase/migrations/20260712180545_assembly-step-build-wave.sqlnew file mode 100644index 0000000000..b929f9346b--- /dev/null+++ b/packages/database/supabase/migrations/20260712180545_assembly-step-build-wave.sql@@ -0,0 +1,6 @@+-- Build wave: the step's longest-path level in the planner's precedence DAG.+-- Steps sharing a wave have no ordering constraint between them and can be+-- built in parallel (different people / stations). NULL = no wave (a step on a+-- precedence cycle, or authored/re-planned outside the wave analysis). Purely+-- informational — the linear step sortOrder is unchanged.+ALTER TABLE "assemblyInstructionStep" ADD COLUMN "buildWave" INTEGER;diff --git a/packages/dev/docker/docker-compose.dev.yml b/packages/dev/docker/docker-compose.dev.ymlindex da9de173ed..d141bb4b54 100644--- a/packages/dev/docker/docker-compose.dev.yml+++ b/packages/dev/docker/docker-compose.dev.yml@@ -133,6 +133,12 @@ services:PGRST_DB_SCHEMAS: public,storage,graphql_publicPGRST_DB_ANON_ROLE: anonPGRST_JWT_SECRET: ${SUPABASE_JWT_SECRET}+ # Pool default is 10 — a burst of concurrent authed queries (the /x loader+ # alone fires ~16) plus any aborted-mid-transaction requests exhausts it and+ # every subsequent query blocks. Bigger pool + a bounded acquisition timeout+ # so a saturated pool fails fast instead of hanging the request forever.+ PGRST_DB_POOL: ${PGRST_DB_POOL:-25}+ PGRST_DB_POOL_ACQUISITION_TIMEOUT: ${PGRST_DB_POOL_ACQUISITION_TIMEOUT:-10}PGRST_DB_USE_LEGACY_GUCS: "false"PGRST_APP_SETTINGS_JWT_SECRET: ${SUPABASE_JWT_SECRET}PGRST_APP_SETTINGS_JWT_EXP: 3600diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.tsindex f1d8ad9ad4..c1a699ae90 100644--- a/packages/dev/src/commands/up.ts+++ b/packages/dev/src/commands/up.ts@@ -8,10 +8,11 @@ import { currentBranch } from "../git.js";import { onShutdown } from "../helpers.js";import { pickApps, pickBorrowSlug } from "../prompts.js";import {+ assertAssemblerDepsBuilt,installDeps,installSkills,spawnApps,- spawnGeometry,+ spawnAssembler,spawnStripeListener,syncEnvSymlinks} from "../services/apps.js";@@ -156,9 +157,14 @@ export async function up(opts: UpOpts = {}) {const allApps = opts.all === true;const selectedApps = appsRequested? allApps- ? APP_CHOICES.map((c) => c.value)+ ? // --all excludes the assembler: it needs a one-time native OCCT build,+ // so it stays opt-in (CARBON_DEV_APPS or an explicit pick).+ APP_CHOICES.map((c) => c.value).filter((v) => v !== "assembler"): await pickApps(): [];+ // Fail before booting anything heavy (docker, migrations) if the assembler is+ // selected without its one-time OCCT build.+ if (selectedApps.includes("assembler")) assertAssemblerDepsBuilt();const slug = resolveSlug(root);// Resolve borrowed slot before ensureSlugAvailable (borrowing doesn't start@@ -208,8 +214,8 @@ export async function up(opts: UpOpts = {}) {log.info("stripe listener spawned (CARBON_EDITION=cloud)");}- if (selectedApps.includes("geometry")) {- spawnGeometry({ root, ports: ctx.ports });+ if (selectedApps.includes("assembler")) {+ spawnAssembler({ root, ports: ctx.ports });}box(@@ -595,7 +601,7 @@ async function runAppsThenTeardown(portless: boolean,stripeChild?: ExecaChildProcess) {- const reactRouterApps = selectedApps.filter((id) => id !== "geometry");+ const reactRouterApps = selectedApps.filter((id) => id !== "assembler");await spawnApps({ root, apps: reactRouterApps, ports, portless });// Apps exit on Ctrl+C; auto-`down` so compose stack isn't orphaned.diff --git a/packages/dev/src/constants.ts b/packages/dev/src/constants.tsindex 3e3b4d2042..644f59c2fc 100644--- a/packages/dev/src/constants.ts+++ b/packages/dev/src/constants.ts@@ -12,7 +12,11 @@ export const COMPOSE_DEV_FILE_LEGACY = "docker-compose.dev.yml";export const APP_CHOICES = [{ value: "erp", label: "ERP", hint: "main app" },{ value: "mes", label: "MES", hint: "shop floor" },- { value: "geometry", label: "Geometry", hint: "3D engine" }+ {+ value: "assembler",+ label: "Assembler",+ hint: "CAD convert + motion planning"+ }] 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.tsindex 7eceef36ac..373dec766c 100644--- a/packages/dev/src/env.test.ts+++ b/packages/dev/src/env.test.ts@@ -10,7 +10,7 @@ const ports: PortMap = {PORT_INNGEST: 54004,PORT_ERP: 54005,PORT_MES: 54006,- PORT_GEOMETRY: 54007+ PORT_ASSEMBLER: 54007};const jwt: JwtCreds = {diff --git a/packages/dev/src/env.ts b/packages/dev/src/env.tsindex 69d0476caf..329e6ec836 100644--- a/packages/dev/src/env.ts+++ b/packages/dev/src/env.ts@@ -96,11 +96,11 @@ 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("# Assembler service (CAD conversion + motion planning)");lines.push(- `GEOMETRY_SERVICE_URL=${portless ? `https://${host("geometry")}` : local(ports.PORT_GEOMETRY)}`+ `ASSEMBLER_SERVICE_URL=${portless ? `https://${host("assembler")}` : local(ports.PORT_ASSEMBLER)}`);- lines.push("GEOMETRY_SERVICE_API_KEY=dev-local-key");+ lines.push("ASSEMBLER_SERVICE_API_KEY=dev-local-key");lines.push("");lines.push("# Dev auth bypass");lines.push("[email protected]");diff --git a/packages/dev/src/prompts.ts b/packages/dev/src/prompts.tsindex 3b4144892d..7bc44c7bdc 100644--- a/packages/dev/src/prompts.ts+++ b/packages/dev/src/prompts.ts@@ -56,7 +56,12 @@ export async function pickApps(): Promise<AppId[]> {.map((s) => s.trim()).filter((s): s is AppId => APP_CHOICES.some((c) => c.value === s));}- if (!process.stdin.isTTY) return APP_CHOICES.map((c) => c.value);+ // The assembler is opt-in: it needs a one-time native OCCT build, so it's+ // never selected by default — only via CARBON_DEV_APPS or an explicit check.+ const defaultApps = APP_CHOICES.filter((c) => c.value !== "assembler").map(+ (c) => c.value+ );+ if (!process.stdin.isTTY) return defaultApps;note("When no apps are selected it will only run (postgres, kong, supabase, inngest, mail) without spawning ERP/MES dev servers.",@@ -69,7 +74,7 @@ export async function pickApps(): Promise<AppId[]> {label: c.label,hint: c.hint})),- initialValues: APP_CHOICES.map((c) => c.value),+ initialValues: defaultApps,required: false});if (isCancel(picked)) abort();diff --git a/packages/dev/src/services/apps.ts b/packages/dev/src/services/apps.tsindex 19a7f9fcd6..36ac838889 100644--- a/packages/dev/src/services/apps.ts+++ b/packages/dev/src/services/apps.ts@@ -229,59 +229,76 @@ export function spawnApps(opts: {});}-export function spawnGeometry(opts: {+const ASSEMBLER_PREFIX = pc.yellow(pc.bold("asm | "));++/**+ * Fail fast (before spawning) when the assembler is selected but its one-time+ * native OCCT dependency isn't built. `cargo run --release` would otherwise+ * either fail deep in a cc/link error or trigger a ~30-min build — neither is+ * what a plain `crbn up` should do. We never auto-build it: the user runs the+ * OCCT script once, then the assembler is available.+ */+export function assertAssemblerDepsBuilt(): void {+ const prefix =+ process.env.OCCT_PREFIX ||+ join(homedir(), ".cache", "carbon-occt", "8.0.0-p1");+ if (!existsSync(prefix)) {+ throw new Error(+ `Assembler selected, but its OCCT dependency isn't built.\n` ++ ` expected: ${prefix}\n` ++ ` build it once (~15-30 min): apps/assembler/scripts/build-occt.sh\n` ++ ` then re-run, or run without the assembler app.`+ );+ }+}++export function spawnAssembler(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 port = ports.PORT_ASSEMBLER;+ const prefix = ASSEMBLER_PREFIX;++ // `cargo run --release` compiles-if-stale then runs, so a Rust change is+ // picked up on the next `crbn up` (the CLI does not watch/rebuild otherwise).+ // First build is slow (OCCT/FCL); incremental is quick. Run from the workspace+ // root so cargo resolves the `assembler` package.+ const file = "cargo";+ const args = ["run", "--release", "-p", "assembler"];+ const cwd = root;+ // Merge the worktree .env* stack so the assembler shares the same REDIS_URL as+ // the apps (keys are asm:-prefixed, so sharing the logical DB is safe).+ const appEnv = spawnAppEnv(root, "assembler");+ // ASSEMBLER_DEV_MODE=true also disables TLS verification in the service, so+ // portless's self-signed CA needs no extra trust wiring. Passing+ // ASSEMBLER_REDIS_URL flips the service to the stateless Redis-backed job ++ // result store; unset (no worktree REDIS_URL) => in-memory, single-process.+ const extraEnv: NodeJS.ProcessEnv = {+ ASSEMBLER_BIND: `127.0.0.1:${port}`,+ ASSEMBLER_SERVICE_API_KEY: "dev-local-key",+ ASSEMBLER_DEV_MODE: "true",+ ...(appEnv.REDIS_URL ? { ASSEMBLER_REDIS_URL: appEnv.REDIS_URL } : {})+ };+ process.stderr.write(+ `${prefix}${pc.dim(+ appEnv.REDIS_URL+ ? "cargo run --release (redis store)"+ : "cargo run --release"+ )}\n`);- const prefix = color(pc.bold("geo | "));+ const child = execa(file, args, {+ cwd,+ env: {+ ...appEnv,+ ...extraEnv+ },+ reject: false,+ stdin: "ignore",+ detached: true+ });+const pipe = (stream: NodeJS.ReadableStream | null,sink: NodeJS.WriteStreamdiff --git a/packages/dev/src/services/portless.ts b/packages/dev/src/services/portless.tsindex 378f520e35..789f9e37fa 100644--- a/packages/dev/src/services/portless.ts+++ b/packages/dev/src/services/portless.ts@@ -420,7 +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: withPrefix("assembler", branchPrefix), port: ports.PORT_ASSEMBLER },{ name: STABLE_OAUTH_ALIAS, port: ports.PORT_API }];}diff --git a/packages/dev/src/ui.ts b/packages/dev/src/ui.tsindex 6ca4aac70b..dfb26b81f5 100644--- a/packages/dev/src/ui.ts+++ b/packages/dev/src/ui.ts@@ -167,13 +167,13 @@ export function summaryLines(url("inngest", ports.PORT_INNGEST),branchPrefix ? ports.PORT_INNGEST : undefined),- ...(apps.includes("geometry")+ ...(apps.includes("assembler")? [row(pc.yellow,- "Geometry",- url("geometry", ports.PORT_GEOMETRY),- branchPrefix ? ports.PORT_GEOMETRY : undefined+ "Assembler",+ url("assembler", ports.PORT_ASSEMBLER),+ branchPrefix ? ports.PORT_ASSEMBLER : undefined)]: []),diff --git a/packages/dev/src/worktree.ts b/packages/dev/src/worktree.tsindex cdac29514c..0083b28c58 100644--- a/packages/dev/src/worktree.ts+++ b/packages/dev/src/worktree.ts@@ -23,7 +23,7 @@ export const PORT_NAMES = ["PORT_INNGEST","PORT_ERP","PORT_MES",- "PORT_GEOMETRY"+ "PORT_ASSEMBLER"] as const;type PortName = (typeof PORT_NAMES)[number];diff --git a/packages/env/src/index.ts b/packages/env/src/index.tsindex 2f1b5ad4ae..7af0581f79 100644--- a/packages/env/src/index.ts+++ b/packages/env/src/index.ts@@ -195,10 +195,10 @@ export const MES_URL =getEnv("MES_URL", { isRequired: false, isSecret: false }) ??"https://mes.carbon.ms";-export const GEOMETRY_SERVICE_URL = getEnv("GEOMETRY_SERVICE_URL", {+export const ASSEMBLER_SERVICE_URL = getEnv("ASSEMBLER_SERVICE_URL", {isRequired: false});-export const GEOMETRY_SERVICE_API_KEY = getEnv("GEOMETRY_SERVICE_API_KEY", {+export const ASSEMBLER_SERVICE_API_KEY = getEnv("ASSEMBLER_SERVICE_API_KEY", {isRequired: false,isSecret: true});diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts b/packages/jobs/src/inngest/functions/tasks/assembly-convert.tsindex 598d824fdb..0d0ff53bfc 100644--- a/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts+++ b/packages/jobs/src/inngest/functions/tasks/assembly-convert.ts@@ -1,9 +1,16 @@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 { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";+import { NonRetriableError } from "inngest";import { inngest } from "../../client";const SIGNED_URL_EXPIRY = 60 * 60; // seconds+// Conversion is synchronous on the service — the request stays open for the+// whole run. A generous cap turns a wedged convert into a fast Inngest retry+// instead of a hung step.+const CONVERT_TIMEOUT_MS = 5 * 60 * 1000;+// Bounded backoff when the service 429s (all slots busy), honoring Retry-After.+const BUSY_RETRIES = 4;/*** Converts an uploaded CAD model (STEP) into web artifacts via the geometry@@ -42,7 +49,7 @@ export const assemblyConvertFunction = inngest.createFunction(}},{ event: "carbon/assembly-convert" },- async ({ event, step }) => {+ async ({ event, step, logger }) => {const { modelUploadId, companyId, userId } = event.data;const job = await step.run("queue", async () => {@@ -90,8 +97,8 @@ export const assemblyConvertFunction = inngest.createFunction(await step.run("convert", async () => {const client = getCarbonServiceRole();- if (!GEOMETRY_SERVICE_URL) {- throw new Error("GEOMETRY_SERVICE_URL is not configured");+ if (!ASSEMBLER_SERVICE_URL) {+ throw new Error("ASSEMBLER_SERVICE_URL is not configured");}const glbPath = `${companyId}/models/${modelUploadId}/${job.id}/model.glb`;@@ -104,6 +111,21 @@ export const assemblyConvertFunction = inngest.createFunction(throw new Error(`Failed to sign source URL: ${source.error.message}`);}+ // Content identity for the geometry service's result cache: with a+ // contentHash a repeat convert of unchanged bytes is served without+ // re-downloading the source. etag is content-derived; size disambiguates+ // multipart etags. Best-effort — omitted on any failure.+ let contentHash: string | undefined;+ try {+ const info = await client.storage.from("private").info(job.modelPath);+ const etag = info.data?.etag?.replaceAll('"', "");+ if (!info.error && etag) {+ contentHash = `${etag}-${info.data?.size ?? 0}`;+ }+ } catch {+ // optimization only+ }+// 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([@@ -118,27 +140,64 @@ export const assemblyConvertFunction = inngest.createFunction(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}` }- : {})+ const requestBody = JSON.stringify({+ jobId: job.id,+ source: {+ url: source.data.signedUrl,+ format: "step",+ ...(contentHash ? { contentHash } : {})},- body: JSON.stringify({- jobId: job.id,- source: {- url: source.data.signedUrl,- format: "step"- },- outputs: {- glb: { url: glbUpload.data.signedUrl },- graph: { url: graphUpload.data.signedUrl }- }- })+ outputs: {+ glb: { url: glbUpload.data.signedUrl },+ graph: { url: graphUpload.data.signedUrl }+ }});+ let response: Response;+ // Bounded 429 backoff honoring Retry-After — the service sheds load with+ // BUSY when its conversion slots are full.+ for (let attempt = 0; ; attempt++) {+ try {+ response = await fetch(`${ASSEMBLER_SERVICE_URL}/convert`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ ...(ASSEMBLER_SERVICE_API_KEY+ ? { Authorization: `Bearer ${ASSEMBLER_SERVICE_API_KEY}` }+ : {})+ },+ body: requestBody,+ signal: AbortSignal.timeout(CONVERT_TIMEOUT_MS)+ });+ } catch (e) {+ const err = e as Error;+ // A timeout may be transient (the service was briefly saturated) — let+ // Inngest retry it. Genuine unreachability (down, DNS, TLS) is+ // permanent, so fail fast → onFailure releases the model + job rows now+ // instead of after the retry backoff.+ if (err.name === "TimeoutError" || err.name === "AbortError") {+ throw new Error(+ `Geometry service timed out after ${CONVERT_TIMEOUT_MS}ms`+ );+ }+ throw new NonRetriableError(+ `Geometry service unreachable: ${err.message}`+ );+ }+ if (response.status === 429 && attempt < BUSY_RETRIES) {+ const retryAfter = Number(response.headers.get("retry-after")) || 15;+ const waitMs = Math.min(retryAfter * 1000 * (attempt + 1), 120_000);+ logger.warn("geometry /convert busy (429); backing off", {+ modelUploadId,+ attempt,+ waitMs+ });+ await new Promise((resolve) => setTimeout(resolve, waitMs));+ continue;+ }+ break;+ }+const result = (await response.json().catch(() => null)) as {ok: boolean;componentCount?: number;@@ -147,7 +206,9 @@ export const assemblyConvertFunction = inngest.createFunction(} | null;if (!response.ok || !result?.ok) {- throw new Error(+ // Non-429 errors are an outage (5xx) or a permanent rejection (4xx):+ // retrying holds the job in Processing for nothing — fail fast.+ throw new NonRetriableError(result?.error ?? `Geometry service returned ${response.status}`);}diff --git a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts b/packages/jobs/src/inngest/functions/tasks/assembly-plan.tsindex 09698d90f5..9aa51da4af 100644--- a/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts+++ b/packages/jobs/src/inngest/functions/tasks/assembly-plan.ts@@ -1,39 +1,65 @@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 { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";import type { AssemblyPlan } from "@carbon/viewer/steps";+import { NonRetriableError } from "inngest";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 SIGNED_URL_EXPIRY = 60 * 60; // seconds — the source (read) URL only.+// Every geometry HTTP call is short (a submit), 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;+// Bounded backoff when the service 429s a submit (all slots busy) — honors+// Retry-After so Inngest's own retries don't hammer the semaphore.+const BUSY_RETRIES = 4;+// This function holds its run for the whole plan (it long-polls to completion),+// so the global concurrency limit caps concurrent long-running plans+// cluster-wide. Keep it aligned with the service's ASSEMBLER_MAX_CONCURRENCY+// (default 2) so Inngest queues surplus plans instead of 429-storming.+const PLAN_CONCURRENCY = 2;+// Long-poll: GET /plan/{id}?wait=N holds the request open until the plan+// finishes (or N elapses), so completion is near-immediate and a whole plan+// costs a handful of checkpointed steps, not ~180 short polls. The client+// timeout must exceed the server hold.+const LONG_POLL_WAIT_S = 25;+const LONG_POLL_TIMEOUT_MS = (LONG_POLL_WAIT_S + 10) * 1000;+// Floor between polls. When the service actually holds the request for ~25s this+// is negligible; when a poll returns immediately (a service without ?wait+// support, a 404, or a network blip) this is what stops the loop from hammering+// Inngest with back-to-back re-invocations.+const POLL_GAP = "3s";+// Total wall-clock budget before giving up, bounded by time (not a fixed poll+// count) so it holds whether the service long-polls or returns immediately.+const MAX_PLAN_WAIT_MS = 40 * 60 * 1000;-const authHeaders: Record<string, string> = GEOMETRY_SERVICE_API_KEY- ? { Authorization: `Bearer ${GEOMETRY_SERVICE_API_KEY}` }+const authHeaders: Record<string, string> = ASSEMBLER_SERVICE_API_KEY+ ? { Authorization: `Bearer ${ASSEMBLER_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).+ * collision-free insertion motion per part plus an assembly sequence, stored as+ * plan.json next to the model artifacts. See+ * .ai/specs/2026-07-04-animated-work-instructions-contracts.md (POST /plan, GET /plan).+ *+ * One durable function owns the whole lifecycle: submit → long-poll GET /plan+ * until the service finishes → flip the job row. Each poll carries a freshly+ * minted signed upload URL (X-Plan-Upload-Url); the service PUTs plan.json to it+ * (late-mint offload) and stores only a {status, planPath, stats} pointer in its+ * Redis-backed store, so a restart still answers the poll (no 404-on-restart+ * loss). Long-poll (rather than short-poll or a pushed completion event) keeps+ * the whole flow inside this run with no dependency on service→Inngest events.*/export const assemblyPlanFunction = inngest.createFunction({id: "assembly-plan",retries: 2,- concurrency: [{ limit: 4 }, { key: "event.data.companyId", limit: 1 }],+ concurrency: [+ { limit: PLAN_CONCURRENCY },+ { key: "event.data.companyId", limit: 1 }+ ],onFailure: async ({ event }) => {const { modelUploadId } = event.data.event.data;const client = getCarbonServiceRole();@@ -53,9 +79,15 @@ export const assemblyPlanFunction = inngest.createFunction(}},{ event: "carbon/assembly-plan" },- async ({ event, step }) => {- const { modelUploadId, companyId, userId, reMotionFor, planJobId } =- event.data;+ async ({ event, step, logger }) => {+ const {+ modelUploadId,+ companyId,+ userId,+ reMotionFor,+ planJobId,+ reDetectUnits+ } = event.data;const job = await step.run("queue", async () => {const client = getCarbonServiceRole();@@ -119,16 +151,39 @@ export const assemblyPlanFunction = inngest.createFunction(};});- if (!GEOMETRY_SERVICE_URL) {- throw new Error("GEOMETRY_SERVICE_URL is not configured");+ if (!ASSEMBLER_SERVICE_URL) {+ throw new Error("ASSEMBLER_SERVICE_URL is not configured");}- const geometryUrl = GEOMETRY_SERVICE_URL;+ const geometryUrl = ASSEMBLER_SERVICE_URL;++ // Where plan.json lands. The service PUTs it here itself (offload) via a+ // signed upload URL minted fresh on each poll (below); this run just records+ // the pointer the service reports back.+ const planPath = `${companyId}/models/${modelUploadId}/${job.id}/plan.json`;++ const failJob = async (label: string, error: string) => {+ await step.run(label, async () => {+ const client = getCarbonServiceRole();+ await client+ .from("assemblyPlanJob")+ .update({+ status: "Failed",+ error,+ updatedAt: new Date().toISOString()+ })+ .eq("id", job.id)+ .eq("companyId", companyId)+ .eq("status", "Processing");+ });+ logger.warn("plan failed", { jobId: job.id, error });+ return { jobId: job.id, status: "Failed" as const, error };+ };// 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.+ // send the user-authored "plan as one component" overrides as units — the+ // planner auto-detects PCB detail swarms from geometry on its own.const sequence = reMotionFor? await step.run("derive-sequence", async () => {const client = getCarbonServiceRole();@@ -147,18 +202,17 @@ export const assemblyPlanFunction = inngest.createFunction(const units =sequence != null? []- : await step.run("derive-units", () =>+ : await step.run("load-authored-units", () =>loadPlanUnits({modelUploadId,companyId,- graphPath: job.graphPath+ excludeAuto: reDetectUnits}));// 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.+ // 202 immediately; we then poll GET /plan below. A fresh signed source URL+ // is minted per submit so retries don't reuse an expired one.const submitPlan = async () => {const client = getCarbonServiceRole();@@ -169,134 +223,245 @@ export const assemblyPlanFunction = inngest.createFunction(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 body = JSON.stringify({+ jobId: job.id,+ source: { url: source.data.signedUrl, format: "step" },+ // No upload URL here — it's minted fresh on each poll (late-mint) so the+ // token is only seconds old when the service PUTs plan.json. The service+ // reads planPath (for the completion pointer) and modelUploadId (to scope+ // its content-hash result cache) out of meta.+ meta: {+ companyId,+ userId,+ modelUploadId,+ reMotionFor: reMotionFor ?? null,+ graphPath: job.graphPath ?? null,+ planPath+ },+ ...(sequence != null+ ? { options: { sequence } }+ : units.length > 0+ ? { options: { units } }+ : {})});- 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);+ // Bounded 429 backoff honoring Retry-After: the service sheds load with+ // BUSY when its slots are full; hammering it via instant retries only+ // extends the outage.+ for (let attempt = 0; ; attempt++) {+ let response: Response;+ try {+ response = await fetch(`${geometryUrl}/plan`, {+ method: "POST",+ headers: { "Content-Type": "application/json", ...authHeaders },+ body,+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)+ });+ } catch (e) {+ const err = e as Error;+ // A timeout may be transient (the service was briefly saturated) — let+ // Inngest retry it. Genuine unreachability (down, DNS, TLS) is+ // permanent, so fail fast → onFailure releases the job row now instead+ // of after the retry backoff.+ if (err.name === "TimeoutError" || err.name === "AbortError") {+ throw new Error(+ `Geometry service timed out after ${REQUEST_TIMEOUT_MS}ms`+ );+ }+ throw new NonRetriableError(+ `Geometry service unreachable: ${err.message}`+ );+ }- // 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);+ if (response.status === 429 && attempt < BUSY_RETRIES) {+ const retryAfter = Number(response.headers.get("retry-after")) || 15;+ const waitMs = Math.min(retryAfter * 1000 * (attempt + 1), 120_000);+ logger.warn("geometry /plan busy (429); backing off", {+ jobId: job.id,+ attempt,+ waitMs+ });+ await new Promise((resolve) => setTimeout(resolve, waitMs));+ continue;+ }- 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 {+ const result = (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}`+ if (!response.ok || !result?.ok) {+ // Non-429 errors are an outage (5xx) or a permanent rejection (4xx):+ // retrying holds the job in Processing for nothing — fail fast.+ throw new NonRetriableError(+ result?.error ?? `Geometry service returned ${response.status}`);}- return body;- });+ logger.info("plan submitted to geometry service", { jobId: job.id });+ return { ok: true };+ }+ };- if (status.status === "missing") {- if (resubmits >= PLAN_MAX_RESUBMITS) {- throw new Error(- "The geometry service repeatedly lost the plan job (restarting?)"+ await step.run("submit", submitPlan);++ // Long-poll GET /plan?wait until the service finishes. Each request holds+ // open server-side until the plan lands (or ~25s elapses), so completion is+ // near-immediate and each is a checkpointed step (a worker restart resumes+ // the loop). The service offloaded plan.json to storage, so "done" carries+ // only a { planPath, stats } pointer — not the plan body. A legacy service+ // that ignored outputs.plan.url still returns the plan inline; handle both.+ let resolvedPlanPath: string | null = null;+ let inlinePlan: AssemblyPlan | null = null;+ let stats: Json = null;+ let finished = false;+ // Bound by elapsed time, not a fixed poll count: the loop must behave whether+ // the service long-polls (few iterations) or returns immediately (many).+ const planStartedAt = await step.run("plan-poll-start", () => Date.now());+ let i = 0;+ while (Date.now() - planStartedAt < MAX_PLAN_WAIT_MS) {+ const poll = await step.run(`poll-${i}`, async () => {+ // Mint a fresh upload URL for THIS poll (late-mint). The service holds+ // the finished plan until a poll carries a URL, then PUTs plan.json with+ // this seconds-old token. Best-effort: a poll without it just keeps the+ // service waiting for the next one.+ const client = getCarbonServiceRole();+ const upload = await client.storage+ .from("private")+ .createSignedUploadUrl(planPath, { upsert: true });+ const headers: Record<string, string> = {+ ...authHeaders,+ ...(upload.data ? { "X-Plan-Upload-Url": upload.data.signedUrl } : {})+ };+ let response: Response;+ try {+ response = await fetch(+ `${geometryUrl}/plan/${job.id}?wait=${LONG_POLL_WAIT_S}`,+ {+ headers,+ signal: AbortSignal.timeout(LONG_POLL_TIMEOUT_MS)+ });+ } catch {+ // A dropped/timed-out hold (service restart mid-hold, brief network+ // blip) is transient with the Redis-backed store — treat as "still+ // waiting" and long-poll again rather than failing the run.+ return { status: "pending" as const };}- 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");+ // 404 with the Redis store is rare (only a genuinely unknown/expired+ // job); treat as transient within the wall-clock window.+ if (response.status === 404) return { status: "pending" as const };+ const bodyJson = (await response.json().catch(() => null)) as {+ status?: string;+ planPath?: string;+ plan?: AssemblyPlan;+ stats?: Json;+ error?: string;+ } | null;+ if (!response.ok || !bodyJson) {+ throw new Error(`GET /plan returned ${response.status}`);}- plan = status.plan;- stats = (status.stats ?? null) as Json;+ if (bodyJson.status === "done") {+ return {+ status: "done" as const,+ planPath: bodyJson.planPath ?? null,+ plan: bodyJson.plan ?? null,+ stats: bodyJson.stats ?? null+ };+ }+ if (bodyJson.status === "error") {+ return {+ status: "error" as const,+ error: bodyJson.error ?? "Motion planning failed"+ };+ }+ return { status: "pending" as const };+ });++ if (poll.status === "done") {+ resolvedPlanPath = poll.planPath ?? planPath;+ inlinePlan = poll.plan;+ stats = poll.stats;+ finished = true;break;}- if (status.status === "error") {- throw new Error(status.error ?? "Motion planning failed");+ if (poll.status === "error") {+ return failJob("mark-failed", poll.error);}+ await step.sleep(`gap-${i}`, POLL_GAP);+ i++;}- if (plan == null) {- throw new Error("Motion planning did not finish in time");+ if (!finished) {+ return failJob(+ "mark-failed",+ "Planner did not finish in the expected time"+ );}- const planData = plan;+ const donePlanPath = resolvedPlanPath ?? planPath;+ // Persist: flip the row to the pointer the service reported. A legacy+ // service returned the plan inline instead of offloading — upload it here in+ // that case. Guarded by status=Processing so a cancel/racing-retry no-ops.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}`);+ if (inlinePlan) {+ const upload = await client.storage+ .from("private")+ .upload(donePlanPath, JSON.stringify(inlinePlan), {+ contentType: "application/json",+ upsert: true+ });+ if (upload.error) {+ throw new Error(+ `Failed to upload plan.json: ${upload.error.message}`+ );+ }}-await client.from("assemblyPlanJob").update({status: "Success",- planPath,+ planPath: donePlanPath,stats,updatedAt: new Date().toISOString()})- .eq("id", job.id);+ .eq("id", job.id)+ .eq("companyId", companyId)+ .eq("status", "Processing");});- // Re-motion: the plan preserved the step order — update each step's motion- // in place (Done steps kept, order/titles/typed fields untouched).+ // Re-motion: preserve step order, refresh each step's motion from the new+ // plan (Done steps kept, titles/typed fields untouched). The plan lives in+ // storage now (offloaded), so download it unless the legacy inline path+ // already has it in memory.if (reMotionFor) {await step.run("update-step-motions", async () => {const client = getCarbonServiceRole();+ let plan = inlinePlan;+ if (!plan) {+ const download = await client.storage+ .from("private")+ .download(donePlanPath);+ if (download.error || !download.data) {+ throw new Error(+ `Failed to download plan.json for re-motion: ${download.error?.message ?? "not found"}`+ );+ }+ plan = JSON.parse(await download.data.text()) as AssemblyPlan;+ }await updateAssemblyStepMotionsFromPlan(client, {assemblyInstructionId: reMotionFor,- plan: planData as unknown as AssemblyPlan,- graphPath: job.graphPath,+ plan,+ graphPath: job.graphPath ?? null,companyId,userId});});}++ logger.info("plan finalized", {+ jobId: job.id,+ reMotion: Boolean(reMotionFor)+ });+ return { jobId: job.id, status: "Success" as const };});diff --git a/packages/jobs/src/inngest/functions/tasks/match-units.test.ts b/packages/jobs/src/inngest/functions/tasks/match-units.test.tsdeleted file mode 100644index 9645dd5964..0000000000--- a/packages/jobs/src/inngest/functions/tasks/match-units.test.ts+++ /dev/null@@ -1,40 +0,0 @@-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.tsdeleted file mode 100644index e23d01486b..0000000000--- a/packages/jobs/src/inngest/functions/tasks/match-units.ts+++ /dev/null@@ -1,86 +0,0 @@-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.tsindex 399a5d334f..68566bc8ab 100644--- a/packages/jobs/src/inngest/functions/tasks/plan-units.ts+++ b/packages/jobs/src/inngest/functions/tasks/plan-units.ts@@ -1,222 +1,52 @@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.+ * Loads the user-authored "plan as one component" overrides (`assemblyUnit`+ * rows, edited from the BOM tree UI) as the planner's `options.units`.*- * Only multi-leaf units are returned; a single-leaf unit is just a normal component.+ * That's the only unit source on this side: the planner itself auto-detects+ * detail swarms (a populated PCB's hundreds of tiny components on a board)+ * from pure geometry — see `detect_swarm_units` in `crates/planner` — so no+ * BOM walk or LLM component→BOM assignment happens here anymore.+ *+ * Best-effort: any failure returns `[]` and the planner plans every leaf+ * (plus whatever it auto-detects). Only multi-leaf units are sent; a+ * single-leaf unit is just a normal component.*/export async function loadPlanUnits(args: {modelUploadId: string;companyId: string;- graphPath: string | null;+ /**+ * Fresh regenerate: omit auto-detected swarm units (`sourceGroupId` set) so the+ * planner re-detects from geometry instead of merging the frozen grouping. The+ * rows stay in the DB (swapped later at step generation) — only THIS run skips+ * them. User-authored units (`sourceGroupId` null) are always sent.+ */+ excludeAuto?: boolean;}): Promise<PlanUnit[]> {- const { modelUploadId, companyId, graphPath } = args;- if (!graphPath) return [];-+ const { modelUploadId, companyId, excludeAuto } = args;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+ let query = 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- });+ .eq("modelUploadId", modelUploadId)+ .eq("companyId", companyId);+ if (excludeAuto) query = query.is("sourceGroupId", null);+ const authored = await query;- return units- .filter((unit) => unit.nodeIds.length > 1)+ return (authored.data ?? [])+ .filter((unit) => (unit.componentNodeIds ?? []).length > 1).map((unit) => ({id: unit.id,name: unit.name,- nodeIds: unit.nodeIds+ nodeIds: unit.componentNodeIds ?? []}));} 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.tsindex 2b0e993a32..65a95fd6a3 100644Binary files a/packages/jobs/src/inngest/functions/tasks/update-step-motions.ts and b/packages/jobs/src/inngest/functions/tasks/update-step-motions.ts differdiff --git a/packages/lib/src/events.ts b/packages/lib/src/events.tsindex e62873b4e3..0e8092cd25 100644--- a/packages/lib/src/events.ts+++ b/packages/lib/src/events.ts@@ -88,6 +88,13 @@ export type Events = {// 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;+ // Fresh regenerate: re-detect groups from scratch. When set, the worker+ // sends only USER-authored units to the planner (auto-detected swarm units+ // are excluded) so detection re-runs — WITHOUT deleting the materialized+ // `assemblyUnit` rows up front. The rows are swapped atomically when the+ // new plan's steps are generated, so a failed/late generate leaves the old+ // grouped state intact instead of stranding the model ungrouped.+ reDetectUnits?: boolean;// 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'sdiff --git a/packages/utils/src/assembly-units.test.ts b/packages/utils/src/assembly-units.test.tsindex d90dda8d18..6158fa54dd 100644--- a/packages/utils/src/assembly-units.test.ts+++ b/packages/utils/src/assembly-units.test.ts@@ -1,209 +1,33 @@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")+import { nameSimilarity, tokenizeName } from "./assembly-units";++describe("tokenizeName", () => {+ it("lowercases and splits on punctuation, keeping dots", () => {+ expect([...tokenizeName("Flanged Screw, M4x10")].sort()).toEqual([+ "flanged",+ "m4x10",+ "screw"]);- 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}`)- )+ expect([...tokenizeName("R_0402_1.5k")].sort()).toEqual([+ "0402",+ "1.5k",+ "r"]);- 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"))+describe("nameSimilarity", () => {+ it("scores identical names 1 and disjoint names 0", () => {+ expect(nameSimilarity("Seal Electronics Box", "Seal Electronics Box")).toBe(+ 1);- 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);+ expect(nameSimilarity("Bracket", "Washer")).toBe(0);+ expect(nameSimilarity("", "Washer")).toBe(0);});- 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");+ it("scores partial token overlap between CAD and BOM names", () => {+ const score = nameSimilarity("Seal Electronics Box", "Electronics Box Lid");+ expect(score).toBeGreaterThan(0.4);+ expect(score).toBeLessThan(1);});});diff --git a/packages/utils/src/assembly-units.ts b/packages/utils/src/assembly-units.tsindex 52859325ef..b744f4c235 100644--- a/packages/utils/src/assembly-units.ts+++ b/packages/utils/src/assembly-units.ts@@ -1,43 +1,14 @@/**- * 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.+ * Component-name similarity for BOM auto-matching ("Match BOM" — pairing a CAD+ * geometry group with a BOM item by name, see `autoMatchAssemblyComponents`).*- * 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.+ * Unit GROUPING no longer lives here: the geometry planner auto-detects detail+ * swarms (a populated PCB's hundreds of tiny components on a board) from pure+ * geometry — see `detect_swarm_units` in `crates/planner` — and user-authored+ * "plan as one component" overrides ride `assemblyUnit` rows straight to the+ * planner's `options.units`.*/-/** 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(@@ -57,218 +28,3 @@ export function nameSimilarity(a: string, b: string): number {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/viewer/package.json b/packages/viewer/package.jsonindex 98a10a2900..4a7cd505db 100644--- a/packages/viewer/package.json+++ b/packages/viewer/package.json@@ -4,6 +4,7 @@"@react-three/drei": "9.122.0","@react-three/fiber": "8.18.0","three": "0.163.0",+ "three-mesh-bvh": "0.7.8","three-stdlib": "2.36.1"},"devDependencies": {diff --git a/packages/viewer/src/AssemblyPlayer.tsx b/packages/viewer/src/AssemblyPlayer.tsxindex 32c82e61b1..450a82d8f2 100644--- a/packages/viewer/src/AssemblyPlayer.tsx+++ b/packages/viewer/src/AssemblyPlayer.tsx@@ -8,28 +8,36 @@ import {useRef,useState} from "react";+import type { BufferGeometry } from "three";import {AnimationMixer,Box3,Color,LoopOnce,type Material,- type Mesh,+ Mesh,type MeshBasicMaterial,MeshStandardMaterial,type Object3D,PerspectiveCamera,Vector3} from "three";+import {+ acceleratedRaycast,+ computeBoundsTree,+ disposeBoundsTree,+ SAH+} from "three-mesh-bvh";import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";import { AssemblyViewer } from "./AssemblyViewer";+import { fitFraming } from "./camera";import { describeStep, type NamedUnit } from "./describe";import { indexAssemblyGraph } from "./graph";import { MotionPathEditor } from "./MotionPathEditor";import {buildStepClip,displayMotionForStep,- exaggerateMotion,+ naturalizeMotion,stepTimelineSeconds} from "./motion";import type {@@ -58,6 +66,12 @@ export type AssemblyPlayerProps = {steps: AssemblyStep[];activeStepIndex: number;onStepChange?: (index: number) => void;+ /**+ * Bumped by the host to preview (play) the active step from its start. In the+ * editor, selecting a step just shows it seated; a double-click bumps this to+ * animate the insertion. Ignored on its initial value.+ */+ playStepNonce?: number;/** 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) */@@ -70,6 +84,13 @@ export type AssemblyPlayerProps = {highlightedNodeIds?: string[];/** Components hidden from the viewer entirely (fixtures, reference geometry) */hiddenNodeIds?: string[];+ /**+ * Isolate/focus set. When non-empty, ONLY these components render — everything+ * else is hidden so the user can inspect the selection in isolation. Empty =+ * no isolation. Cleared automatically when playback starts (the build-up needs+ * every part).+ */+ focusedNodeIds?: string[];/** Disables component selection (MES playback) */readOnly?: boolean;/**@@ -82,6 +103,9 @@ export type AssemblyPlayerProps = {onMotionChange?: (stepId: string, motion: Motion) => void;/** Initial render mode for future-step components */defaultFutureMode?: FutureComponentsMode;+ /** Picking components to add to a step: ghost every not-yet-installed part so+ * un-animated parts are visible and clickable (x-ray). */+ componentPickerActive?: boolean;/*** 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@@ -135,14 +159,17 @@ export const AssemblyPlayer = forwardRef<steps,activeStepIndex,onStepChange,+ playStepNonce,onSelectComponents,onGraphLoaded,highlightedNodeIds,hiddenNodeIds,+ focusedNodeIds,readOnly = false,editMotion,onMotionChange,defaultFutureMode = "ghost",+ componentPickerActive = false,autoPlay = true,units,suppressFallbackMotions = false,@@ -156,10 +183,18 @@ export const AssemblyPlayer = forwardRef<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`).+ // player starts paused: selecting a step shows it seated, and it only animates+ // when Play (or a step double-click) is pressed (`continuous` for the former).const [isPlaying, setIsPlaying] = useState(autoPlay);const [continuous, setContinuous] = useState(autoPlay);+ // "auto": each step frames the camera toward the action. Grabbing the+ // controls DURING playback switches to "free" — the user keeps their view+ // across steps until they click the floating badge to hand control back.+ // Paused orbiting doesn't change modes (per-step framing already yields to+ // the framing-key guard there).+ const [cameraMode, setCameraMode] = useState<"auto" | "free">("auto");+ // Stable identity — the scene re-subscribes its controls listener otherwise.+ const handleFreeCamera = useCallback(() => setCameraMode("free"), []);const [futureMode, setFutureMode] =useState<FutureComponentsMode>(defaultFutureMode);// Live marquee rectangle while box-selecting (drawn as a DOM overlay).@@ -212,18 +247,13 @@ export const AssemblyPlayer = forwardRef<? describeStep(activeStep, graphIndex, units): null;+ // Selecting a step no longer auto-plays it (that surprised users). The clip+ // effect (in AssemblyScene) snaps the newly-selected step to its SEATED pose+ // so it reads as "this step, done"; a double-click on the step (playStepNonce)+ // animates the insertion. autoPlay mode is unaffected — the sequence runs itself.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]);+ }, [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@@ -305,7 +335,7 @@ export const AssemblyPlayer = forwardRef<maxBox[1] - minBox[1],maxBox[2] - minBox[2]);- const motion = exaggerateMotion(+ const motion = naturalizeMotion(baseMotion,componentDiagonal,assemblyDiagonal@@ -352,18 +382,29 @@ export const AssemblyPlayer = forwardRef<}, []);const goToStep = useCallback(- (index: number) => {+ (index: number, opts?: { play?: boolean }) => {if (index < 0 || index >= stepCount) return;- seekRef.current = 0;- playheadRef.current = startTimes[index] ?? 0;- setDisplayTime(startTimes[index] ?? 0);+ if (opts?.play) {+ // Playing into the step — start at its beginning so the insertion animates.+ seekRef.current = 0;+ playheadRef.current = startTimes[index] ?? 0;+ setDisplayTime(startTimes[index] ?? 0);+ } else {+ // Just viewing the step (prev/next) — show it COMPLETED, parts seated and+ // visible, matching a single-click on the step row. Leaving the seek null+ // lets the clip effect snap to the step's end pose.+ seekRef.current = null;+ const end = (startTimes[index] ?? 0) + (segments[index] ?? 0);+ playheadRef.current = end;+ setDisplayTime(end);+ }if (index === activeStepIndex) {setSeekVersion((version) => version + 1);} else {onStepChange?.(index);}},- [onStepChange, stepCount, startTimes, activeStepIndex]+ [onStepChange, stepCount, startTimes, segments, activeStepIndex]);const handleStepFinished = useCallback(() => {@@ -371,7 +412,7 @@ export const AssemblyPlayer = forwardRef<// single-step play (from selecting a step) stops here, paused at the seated// pose.if (continuous && clampedIndex < stepCount - 1) {- goToStep(clampedIndex + 1);+ goToStep(clampedIndex + 1, { play: true });} else {setIsPlaying(false);setContinuous(false);@@ -400,6 +441,19 @@ export const AssemblyPlayer = forwardRef<[totalSeconds, stepCount, startTimes, clampedIndex, onStepChange]);+ // Double-click a step → preview it: restart the active step from its start and+ // play just that one (not a continuous run-through). Skips the initial nonce+ // value and the motion-path editor.+ const playStepNonceRef = useRef(playStepNonce);+ useEffect(() => {+ if (playStepNonce === playStepNonceRef.current) return;+ playStepNonceRef.current = playStepNonce;+ if (isEditingMotionRef.current || stepCount === 0) return;+ onScrub(startTimes[clampedIndex] ?? 0); // seek to the step's start+ setContinuous(false);+ setIsPlaying(true);+ }, [playStepNonce, clampedIndex, stepCount, startTimes, onScrub]);+return (<div className={cn("flex h-full w-full flex-col", className)}><div className="relative min-h-0 flex-1">@@ -415,6 +469,7 @@ export const AssemblyPlayer = forwardRef<futureMode={futureMode}highlightedNodeIds={highlightedNodeIds}hiddenNodeIds={hiddenNodeIds}+ focusedNodeIds={isPlaying ? undefined : focusedNodeIds}readOnly={readOnly}onSelectComponents={onSelectComponents}editMotion={editMotion ?? null}@@ -430,9 +485,37 @@ export const AssemblyPlayer = forwardRef<seekVersion={seekVersion}onStepFinished={handleStepFinished}onBoxRect={setBoxRect}+ cameraMode={cameraMode}+ onFreeCamera={handleFreeCamera}+ componentPickerActive={componentPickerActive}/>)}</AssemblyViewer>+ {cameraMode === "free" && (+ <button+ type="button"+ className={cn(+ "absolute bottom-3 left-1/2 z-10 flex -translate-x-1/2 items-center gap-1.5 rounded-full border border-border bg-background/80 py-1 pr-3 pl-2 backdrop-blur",+ "text-xs font-medium text-muted-foreground hover:text-foreground"+ )}+ onClick={() => setCameraMode("auto")}+ >+ <svg+ className="size-3.5"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden+ >+ <circle cx="12" cy="12" r="3" />+ <path d="M12 2v3M12 19v3M2 12h3M19 12h3" />+ </svg>+ Free camera — click for auto+ </button>+ )}{boxRect && (<divaria-hidden@@ -509,6 +592,9 @@ export const AssemblyPlayer = forwardRef<setContinuous(false);return;}+ // Clear any component selection so it doesn't stay tinted red over+ // the playback.+ onSelectComponents?.([]);// Play = run on through the rest of the steps.const nextStart =startTimes[clampedIndex + 1] ?? Number.POSITIVE_INFINITY;@@ -521,7 +607,7 @@ export const AssemblyPlayer = forwardRef<} 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);+ goToStep(clampedIndex + 1, { play: true });} else {// Mid-step or a fresh step → (re)play it from the current position.setSeekVersion((version) => version + 1);@@ -539,32 +625,15 @@ export const AssemblyPlayer = forwardRef<><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>+ <TimelineScrubber+ segments={segments}+ startTimes={startTimes}+ totalSeconds={totalSeconds}+ displayTime={displayTime}+ activeStepIndex={clampedIndex}+ stepCount={stepCount}+ onScrub={onScrub}+ /><span className="whitespace-nowrap text-xs tabular-nums text-muted-foreground">{stepCount > 0? `${formatTime(Math.min(displayTime, totalSeconds))} / ${formatTime(totalSeconds)}`@@ -631,6 +700,11 @@ type MaterialOverrides = {fade?: Material | Material[];};+// Scratch vectors for the camera-transition useFrame — reused every frame so+// the transition allocates nothing.+const SCRATCH_CURRENT_OFFSET = new Vector3();+const SCRATCH_DESIRED_OFFSET = new Vector3();+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@@ -638,6 +712,81 @@ const HIGHLIGHT_COLOR = 0x3b82f6;const SELECTED_COLOR = 0xef4444;const EXTERNAL_COLOR = 0xef4444;const GHOST_OPACITY = 0.3;++type BvhGeometry = BufferGeometry & {+ computeBoundsTree?: typeof computeBoundsTree;+ disposeBoundsTree?: typeof disposeBoundsTree;+ boundsTree?: unknown;+};++/** Meshes to BVH per idle slice — each build is sub-ms, so a small batch keeps+ * every frame well under budget. */+const BVH_BUILD_BATCH = 24;++/**+ * Progressively accelerates raycasting on the scene's meshes by building a+ * three-mesh-bvh bounds tree per geometry, a small batch at a time on browser+ * idle. Spreading the ~250k-triangle build across idle slices keeps the model+ * interactive the instant it renders (raycasts fall back to linear until each+ * mesh's tree lands) without the single main-thread hitch a synchronous build+ * causes — and without the geometry-neutering flicker a web-worker builder+ * would cause on a visible model. Trees are disposed and raycast restored when+ * the scene changes or the player unmounts.+ */+function useProgressiveBvh(scene: Object3D) {+ const raycaster = useThree((state) => state.raycaster);+ useEffect(() => {+ raycaster.firstHitOnly = false;+ const meshes: Mesh[] = [];+ scene.traverse((object) => {+ const mesh = object as Mesh;+ const geom = mesh.geometry as BvhGeometry | undefined;+ if (mesh.isMesh && geom && !geom.boundsTree) meshes.push(mesh);+ });++ let cancelled = false;+ let handle: number | undefined;+ let index = 0;+ const built: Mesh[] = [];+ const idle: (cb: () => void) => number =+ typeof requestIdleCallback === "function"+ ? (cb) => requestIdleCallback(cb)+ : (cb) => window.setTimeout(cb, 0);+ const cancelIdle: (id: number) => void =+ typeof cancelIdleCallback === "function"+ ? cancelIdleCallback+ : window.clearTimeout;++ const step = () => {+ if (cancelled) return;+ const end = Math.min(index + BVH_BUILD_BATCH, meshes.length);+ for (; index < end; index++) {+ const mesh = meshes[index];+ if (!mesh) continue;+ const geom = mesh.geometry as BvhGeometry;+ if (geom.boundsTree) continue;+ geom.computeBoundsTree = computeBoundsTree;+ geom.disposeBoundsTree = disposeBoundsTree;+ geom.computeBoundsTree({ strategy: SAH });+ mesh.raycast = acceleratedRaycast;+ built.push(mesh);+ }+ if (index < meshes.length) handle = idle(step);+ };+ handle = idle(step);++ return () => {+ cancelled = true;+ if (handle !== undefined) cancelIdle(handle);+ delete raycaster.firstHitOnly;+ for (const mesh of built) {+ const geom = mesh.geometry as BvhGeometry;+ if (geom.boundsTree) geom.disposeBoundsTree?.();+ mesh.raycast = Mesh.prototype.raycast;+ }+ };+ }, [scene, raycaster]);+}/** Seconds a flagged step's components take to fade in at the seated pose */const FADE_SECONDS = 1.2;@@ -650,6 +799,7 @@ function AssemblyScene({futureMode,highlightedNodeIds,hiddenNodeIds,+ focusedNodeIds,readOnly,onSelectComponents,editMotion,@@ -664,7 +814,10 @@ function AssemblyScene({seekRef,seekVersion,onStepFinished,- onBoxRect+ onBoxRect,+ cameraMode,+ onFreeCamera,+ componentPickerActive}: {scene: Object3D;nodesById: Map<string, Object3D>;@@ -674,6 +827,7 @@ function AssemblyScene({futureMode: FutureComponentsMode;highlightedNodeIds?: string[];hiddenNodeIds?: string[];+ focusedNodeIds?: string[];readOnly: boolean;onSelectComponents?: (nodeIds: string[]) => void;/** Active-step motion draft to edit (null = play normally) */@@ -703,6 +857,13 @@ function AssemblyScene({onStepFinished?: () => void;/** Live marquee rectangle (canvas-local px) while box-selecting; null clears */onBoxRect?: (rect: BoxRect | null) => void;+ /** "free" suppresses per-step camera framing (user owns the view) */+ cameraMode: "auto" | "free";+ /** The user grabbed the controls during playback — switch to free mode */+ onFreeCamera: () => void;+ /** Picking components to add to a step — ghost every not-yet-installed part so+ * un-animated parts are visible and clickable */+ componentPickerActive: boolean;}) {const camera = useThree((state) => state.camera);const controls = useThree(@@ -710,6 +871,57 @@ function AssemblyScene({) as unknown as OrbitControlsImpl | null;const gl = useThree((state) => state.gl);+ // Accelerate raycasting (hover/click picking) with per-geometry BVHs, built+ // progressively on idle so a dense model never hitches the main thread.+ useProgressiveBvh(scene);++ // Fit the perspective near/far planes to the model. A static 0.1 → 100000+ // range is a 1e6 depth ratio: the buffer spends almost all its precision+ // right in front of `near`, so coplanar CAD faces (touching solids, a boss+ // flush on a plate) z-fight into a tearing moiré at model distance. Sizing+ // the range to the assembly diagonal collapses the ratio to ~1e4 and keeps+ // those faces stable, while still leaving room to zoom close and orbit out.+ useEffect(() => {+ if (!(camera instanceof PerspectiveCamera)) return;+ const box = new Box3().setFromObject(scene);+ if (box.isEmpty()) return;+ const diag = box.getSize(new Vector3()).length();+ if (!(diag > 0)) return;+ camera.near = Math.max(diag / 500, 0.01);+ camera.far = diag * 20;+ camera.updateProjectionMatrix();+ }, [camera, scene]);++ // Break coincident-face z-fighting. A multi-body STEP split turns each solid+ // into its own mesh; a part seated flush on a plate (a bolt head on its face)+ // shares that face's exact plane, so the two meshes sit at IDENTICAL depth and+ // the GPU can't pick a winner — the face tears at every camera distance (no+ // depth-precision trick resolves an exact tie). Give each distinct material a+ // unique polygon offset so one always wins at a coincidence. Coincident parts+ // are near-always different parts with different materials (the bolt vs the+ // plate), so per-material differentiates them with no per-mesh cloning; we+ // just tag the loaded glTF materials in place. The offset is a few depth-buffer+ // units — far below any real (sub-mm) gap — so separated faces are untouched.+ useEffect(() => {+ const tagged = new Set<Material>();+ let offset = -1;+ scene.traverse((object) => {+ const mesh = object as Mesh;+ if (!mesh.isMesh) return;+ const materials = Array.isArray(mesh.material)+ ? mesh.material+ : [mesh.material];+ for (const material of materials) {+ if (tagged.has(material)) continue;+ tagged.add(material);+ material.polygonOffset = true;+ material.polygonOffsetFactor = -1;+ material.polygonOffsetUnits = offset;+ offset -= 1;+ }+ });+ }, [scene]);+const activeStep = steps[activeStepIndex] ?? null;const isEditingActive = Boolean(editMotion && activeStep && editMotion.stepId === activeStep.id@@ -738,11 +950,36 @@ function AssemblyScene({[highlightedNodeIds]);+ const focusedSet = useMemo(+ () => new Set(focusedNodeIds ?? []),+ [focusedNodeIds]+ );const hiddenSet = useMemo(() => new Set(hiddenNodeIds ?? []),[hiddenNodeIds]);+ // Component picking is only meaningful in the editor (a selection callback,+ // not read-only) — the drill affordance is gated on it so pure playback stays+ // untouched.+ const pickingEnabled = !readOnly && !!onSelectComponents;+ // Alt-hover x-ray drill: the occluders in front of the pointer (ghosted so+ // you can see through the box/lid) and the innermost part they reveal (the+ // click target). A ref mirrors the target so the high-frequency pointer-move+ // only re-renders when the drilled part actually changes.+ const [drill, setDrillState] = useState<{+ ghostIds: string[];+ target: string;+ } | null>(null);+ const drillTargetRef = useRef<string | null>(null);+ // True while the camera is being orbited — drill raycasts are skipped then.+ const orbitingRef = useRef(false);+ const clearDrill = useCallback(() => {+ if (drillTargetRef.current === null) return;+ drillTargetRef.current = null;+ setDrillState(null);+ }, []);+/** nodeId → index of the first step that installs it */const stepIndexByNode = useMemo(() => {const map = new Map<string, number>();@@ -808,17 +1045,28 @@ function AssemblyScene({// 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;+ // Component-picker mode overrides both: every not-yet-installed part ghosts+ // (x-ray) so the user can see AND click the parts they want to add — a+ // "hidden" future part is invisible and unpickable.+ const effectiveFutureMode: FutureComponentsMode = componentPickerActive+ ? "ghost"+ : isPlaying+ ? "hidden"+ : futureMode;for (const [nodeId, stepIndex] of stepIndexByNode) {const node = nodesById.get(nodeId);if (!node) continue;- applyVisual(- node,- visualForComponent(stepIndex, activeStepIndex, effectiveFutureMode)+ const visual = visualForComponent(+ stepIndex,+ activeStepIndex,+ effectiveFutureMode);+ // The active step's blue tint is a "what's animating now" cue — only+ // apply it during playback. Statically selecting/seating a step leaves+ // its parts their real color (the step list + timeline show which is+ // current).+ applyVisual(node, visual === "active" && !isPlaying ? "solid" : visual);}// Components no step installs are never "already there": they get the same@@ -840,8 +1088,11 @@ function AssemblyScene({}// External (BOM) highlight: emissive tint, forced visible even when the- // component's step would hide it ("show me all the M8 bolts")+ // component's step would hide it ("show me all the M8 bolts"). Skipped for+ // focused nodes — isolating a part shows it in its REAL color; the isolate+ // itself is the cue, no tint.for (const nodeId of highlightedSet) {+ if (focusedSet.has(nodeId)) continue;const node = nodesById.get(nodeId);if (!node) continue;node.visible = true;@@ -853,6 +1104,29 @@ function AssemblyScene({});}+ // Isolate/focus: when a focus set is active, ONLY the focused components+ // render — everything else hides so the selection can be inspected alone.+ // Keep the focused node's ANCESTORS visible too: three.js visibility is+ // inherited, and every glTF node (including the root wrapper and assembly+ // groups) carries a nodeId, so blindly hiding non-focused nodes would hide+ // the focused leaf's parents and blank the whole model. Applied before the+ // explicit-hide pass so a focused-but-manually-hidden component still hides.+ if (focusedSet.size > 0) {+ const keep = new Set<Object3D>();+ for (const nodeId of focusedSet) {+ const node = nodesById.get(nodeId);+ if (!node) continue;+ for (let a: Object3D | null = node; a; a = a.parent) keep.add(a);+ node.traverse((descendant) => keep.add(descendant));+ }+ // Only touch nodeId-stamped nodes — the reset above restores exactly these+ // to visible, so meshes (which inherit) never get stranded hidden. Ancestor+ // nodes stay in `keep`, so a focused leaf's parents don't blank it out.+ for (const node of nodesById.values()) {+ node.visible = keep.has(node);+ }+ }+// Explicitly hidden components (fixtures/reference geometry) always hide,// even when highlightedfor (const nodeId of hiddenSet) {@@ -866,6 +1140,7 @@ function AssemblyScene({// material here — regardless of whether it was picked in the viewer or the// Components panel.for (const nodeId of highlightedSet) {+ if (focusedSet.has(nodeId)) continue; // isolated part keeps its real colorconst node = nodesById.get(nodeId);if (!node || !node.visible) continue;node.traverse((object) => {@@ -874,6 +1149,23 @@ function AssemblyScene({mesh.material = getOverride(mesh, overrides, "selected");});}++ // Alt-hover x-ray drill: ghost the occluders in front of the pointer so the+ // innermost part they hide (the click target) shows through. Applied last so+ // it wins even over a selected occluder — you're deliberately looking past+ // it. The target keeps its real material (it's the solid thing behind glass).+ if (drill) {+ for (const nodeId of drill.ghostIds) {+ const node = nodesById.get(nodeId);+ if (!node?.visible) continue;+ node.traverse((object) => {+ if (!(object as Mesh).isMesh) return;+ const mesh = object as Mesh;+ mesh.material = getOverride(mesh, overrides, "ghost");+ mesh.renderOrder = 1;+ });+ }+ }}, [nodesById,stepIndexByNode,@@ -882,8 +1174,11 @@ function AssemblyScene({activeStepIndex,futureMode,isPlaying,+ componentPickerActive,highlightedSet,- hiddenSet+ hiddenSet,+ focusedSet,+ drill]);// --- Animation -----------------------------------------------------------@@ -892,13 +1187,37 @@ function AssemblyScene({const actionRef = useRef<ReturnType<AnimationMixer["clipAction"]> | null>(null);+ // Live mirror so the step-keyed clip effect can tell "static selection" (snap+ // seated) from "playing" without listing isPlaying as a dep.+ const isPlayingRef = useRef(isPlaying);+ isPlayingRef.current = isPlaying;/** 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+ // The clip effect is keyed on a CONTENT signature of the active step, not the+ // `steps` array identity — a loader revalidation (5s poll, realtime) hands+ // down a new-but-equivalent array, and re-running the effect on it would tear+ // down and restart an in-flight animation from t=0 plus rebuild the clip.+ // Mirrors the per-step camera effect's framingKey guard. The body reads the+ // live values through refs so the signature is the only re-run trigger.+ const stepsLiveRef = useRef(steps);+ stepsLiveRef.current = steps;+ const startTimesLiveRef = useRef(startTimes);+ startTimesLiveRef.current = startTimes;+ const clipKey = activeStep+ ? [+ activeStepIndex,+ activeStep.id,+ JSON.stringify(activeStep.motion),+ activeStep.componentNodeIds.join(","),+ isEditingActive+ ].join("|")+ : `none|${activeStepIndex}`;++ // biome-ignore lint/correctness/useExhaustiveDependencies: clipKey is the content signature that keys the rebuild — a revalidation with an equivalent steps array must not re-run this effectuseEffect(() => {- const step = steps[activeStepIndex];+ const step = stepsLiveRef.current[activeStepIndex];// Consume any pending seek; otherwise the step starts at 0const seek = seekRef.current;@@ -906,13 +1225,14 @@ function AssemblyScene({localElapsedRef.current = seek ?? 0;finishedRef.current = false;playheadRef.current =- (startTimes[activeStepIndex] ?? 0) + localElapsedRef.current;+ (startTimesLiveRef.current[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;+ if (isEditingActive) return;const clip = buildStepClip(step, nodesById);if (!clip) return;@@ -934,6 +1254,15 @@ function AssemblyScene({if (seek !== null) {action.time = Math.min(seek, clip.duration);mixer.update(0);+ } else if (!isPlayingRef.current) {+ // Static selection (no play): show the step COMPLETED — the component+ // seated, not flown-out at t=0. A double-click seeks back to 0 and plays.+ action.time = clip.duration;+ mixer.update(0);+ localElapsedRef.current = clip.duration;+ finishedRef.current = true;+ playheadRef.current =+ (startTimesLiveRef.current[activeStepIndex] ?? 0) + clip.duration;}actionRef.current = action;@@ -946,19 +1275,36 @@ function AssemblyScene({node.quaternion.copy(quaternion);}};- // seekVersion re-applies a seek within the same step}, [mixer,nodesById,- steps,+ clipKey,activeStepIndex,- seekVersion,+ isEditingActive,seekRef,- playheadRef,- startTimes,- editMotion+ playheadRef]);+ // Same-step scrub: apply the pending seek to the LIVE action instead of+ // re-running the clip effect — a timeline drag fires many times per second,+ // and each effect re-run would stop/uncache/rebuild the whole clip when only+ // `action.time` changes.+ // biome-ignore lint/correctness/useExhaustiveDependencies: seekVersion is the trigger for re-applying a same-step seek+ useEffect(() => {+ const seek = seekRef.current;+ if (seek === null) return;+ seekRef.current = null;+ localElapsedRef.current = seek;+ finishedRef.current = false;+ playheadRef.current =+ (startTimesLiveRef.current[activeStepIndex] ?? 0) + seek;+ const action = actionRef.current;+ if (action) {+ action.time = Math.min(seek, action.getClip().duration);+ mixer.update(0);+ }+ }, [seekVersion, activeStepIndex, mixer, seekRef, playheadRef]);+useEffect(() => {if (actionRef.current) actionRef.current.paused = !isPlaying;}, [isPlaying]);@@ -1146,12 +1492,32 @@ function AssemblyScene({useEffect(() => {if (!controls) return;- const cancel = () => {+ const onStart = () => {desiredPoseRef.current = null;+ // Orbiting is not picking — suppress hover raycasts (and drop the tint)+ // while the camera is being dragged, the moment it feels choppiest.+ orbitingRef.current = true;+ clearDrill();+ // Grabbing the view mid-playback means the user wants to keep it — stop+ // re-framing on every step until they opt back into auto via the badge.+ if (isPlaying) onFreeCamera();+ };+ const onEnd = () => {+ orbitingRef.current = false;+ };+ controls.addEventListener("start", onStart);+ controls.addEventListener("end", onEnd);+ return () => {+ controls.removeEventListener("start", onStart);+ controls.removeEventListener("end", onEnd);};- controls.addEventListener("start", cancel);- return () => controls.removeEventListener("start", cancel);- }, [controls]);+ }, [controls, isPlaying, onFreeCamera, clearDrill]);++ // Returning to auto must re-frame the CURRENT step even when its framing key+ // hasn't changed — the user panned away and asked for the staged view back.+ useEffect(() => {+ if (cameraMode === "auto") lastFramedKeyRef.current = null;+ }, [cameraMode]);// Transition by orbiting around the target — the view direction rotates// and the distance eases, so the model never leaves the frame the way a@@ -1163,8 +1529,12 @@ function AssemblyScene({controls.target.lerp(desired.target, alpha);- const currentOffset = camera.position.clone().sub(controls.target);- const desiredOffset = desired.position.clone().sub(desired.target);+ const currentOffset = SCRATCH_CURRENT_OFFSET.copy(camera.position).sub(+ controls.target+ );+ const desiredOffset = SCRATCH_DESIRED_OFFSET.copy(desired.position).sub(+ desired.target+ );const currentDistance = Math.max(currentOffset.length(), 1e-3);const desiredDistance = Math.max(desiredOffset.length(), 1e-3);@@ -1200,6 +1570,8 @@ function AssemblyScene({useEffect(() => {const step = steps[activeStepIndex];if (!step || !controls) return;+ // Free mode: the user owns the view — no per-step framing at all.+ if (cameraMode === "free") 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@@ -1217,7 +1589,8 @@ function AssemblyScene({if (framingKey === lastFramedKeyRef.current) return;lastFramedKeyRef.current = framingKey;- if (step.camera) {+ // Manual "Set view" pose — applied verbatim, fov included.+ if (step.camera && !("source" in step.camera)) {desiredPoseRef.current = {position: new Vector3(...step.camera.position),target: new Vector3(...step.camera.target)@@ -1229,6 +1602,15 @@ function AssemblyScene({return;}+ // Planner-baked view direction: chosen at plan time with sight lines+ // against the real triangles of everything installed earlier — the AABB+ // scoring below can't tell a hollow container's open top from its wall.+ // Target, distance, and the frustum fit still happen live.+ const planDirection =+ step.camera && "source" in step.camera+ ? new Vector3(...step.camera.direction).normalize()+ : null;+if (step.componentNodeIds.length === 0) return;const assemblyBox = getAssemblyBox();@@ -1252,93 +1634,153 @@ function AssemblyScene({// Aim mostly at the assembly (context) with a nudge toward the componentconst target = center.clone().lerp(componentCenter, 0.3);- // Where the action happens: the seated pose and the travel midpoint+ // Where the action happens: the seated body (corners, so a mostly-hidden+ // part scores worse than a clear one) plus the full travel — start,+ // midpoint, and seat.const motionDirection = insertionDirection(step.motion);- const lookPoints = [componentCenter];const startOffset = insertionStartOffset(step.motion);+ const boxCorner = (box: Box3, i: number, offset: Vector3 | null) => {+ const corner = new Vector3(+ i & 1 ? box.max.x : box.min.x,+ i & 2 ? box.max.y : box.min.y,+ i & 4 ? box.max.z : box.min.z+ );+ return offset ? corner.add(offset) : corner;+ };+ const lookPoints = [componentCenter];+ for (let i = 0; i < 8; i++) {+ lookPoints.push(boxCorner(componentBox, i, null));+ }if (startOffset) {lookPoints.push(componentCenter.clone().addScaledVector(startOffset, 0.5));+ lookPoints.push(componentCenter.clone().add(startOffset));}- // 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();+ let bestDirection: Vector3;+ if (planDirection && planDirection.lengthSq() > 1e-6) {+ bestDirection = planDirection;+ } else {+ // Live fallback (manual/edited steps, plans without directions):+ // AABB-scored candidates. Coarse — it can't see through hollow+ // geometry — which is exactly why generated steps carry a baked+ // direction instead.+ 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+ });+ }- 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()- );+ // Candidate view directions: 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.+ 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();- 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;- }+ const currentDirection = camera.position+ .clone()+ .sub(controls.target)+ .normalize();+ const candidates: Vector3[] = [];+ if (currentDirection.lengthSq() > 1e-6) candidates.push(currentDirection);+ // Third, steeper ring: in dense machines the only clear sight line to a+ // buried part is often from high above.+ for (const elevation of [0.3, 0.55, 0.8]) {+ 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()+ );}}- // 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;++ 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;+ }}}+ // Guarantee the action is entirely in frame: pan the target (and only+ // grow the distance when the action genuinely can't fit) so the seated+ // body plus its travel-start copy sit inside the frustum.+ let right = new Vector3().crossVectors(up, bestDirection);+ if (right.lengthSq() < 1e-6) right = new Vector3(1, 0, 0);+ right.normalize();+ const trueUp = new Vector3().crossVectors(bestDirection, right).normalize();+ const actionPoints: Vector3[] = [];+ for (let i = 0; i < 8; i++) {+ actionPoints.push(boxCorner(componentBox, i, null));+ if (startOffset)+ actionPoints.push(boxCorner(componentBox, i, startOffset));+ }+ const rel = new Vector3();+ const camPoints: Vec3[] = actionPoints.map((point) => {+ rel.copy(point).sub(target);+ return [rel.dot(right), rel.dot(trueUp), rel.dot(bestDirection)];+ });+ const aspect =+ camera instanceof PerspectiveCamera && camera.aspect > 0+ ? camera.aspect+ : 16 / 9;+ const tanHalfV = Math.tan(((fov / 2) * Math.PI) / 180);+ const fit = fitFraming(+ camPoints,+ tanHalfV * aspect,+ tanHalfV,+ 0.85,+ distance+ );+ const framedTarget = target+ .clone()+ .addScaledVector(right, fit.pan[0])+ .addScaledVector(trueUp, fit.pan[1]);+desiredPoseRef.current = {- position: target.clone().addScaledVector(bestDirection, distance),- target+ position: framedTarget+ .clone()+ .addScaledVector(bestDirection, fit.distance),+ target: framedTarget};}, [steps,@@ -1350,7 +1792,8 @@ function AssemblyScene({leafBounds,hiddenSet,stepIndexByNode,- futureMode+ futureMode,+ cameraMode]);// --- Selection -------------------------------------------------------------@@ -1363,7 +1806,13 @@ function AssemblyScene({// 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);+ // Alt+click drills: select the INNERMOST part on the ray (through any+ // box/lid), matching the x-ray reveal shown on Alt-hover.+ const stack = visibleNodeStack(clickEvent.intersections);+ const nodeId =+ clickEvent.nativeEvent.altKey && stack.length >= 2+ ? (stack[stack.length - 1] ?? null)+ : 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@@ -1382,6 +1831,60 @@ function AssemblyScene({[readOnly, onSelectComponents, highlightedSet]);+ const handlePointerMove = useCallback(+ (moveEvent: ThreeEvent<PointerEvent>) => {+ // Skip the raycast entirely while playing or orbiting — the two moments+ // the view is busiest. Drilling only happens with Alt held.+ if (+ !pickingEnabled ||+ isPlaying ||+ orbitingRef.current ||+ !moveEvent.nativeEvent.altKey+ ) {+ clearDrill();+ return;+ }+ const stack = visibleNodeStack(moveEvent.intersections);+ // Nothing to drill through — the front part IS the target, so no reveal.+ if (stack.length < 2) {+ clearDrill();+ return;+ }+ const target = stack[stack.length - 1] ?? null;+ if (!target || drillTargetRef.current === target) return;+ drillTargetRef.current = target;+ setDrillState({ ghostIds: stack.slice(0, -1), target });+ },+ [pickingEnabled, isPlaying, clearDrill]+ );++ const handlePointerOut = useCallback(() => clearDrill(), [clearDrill]);++ // Drop any stale drill when picking turns off (leaving edit mode) or playback+ // starts.+ useEffect(() => {+ if (!pickingEnabled || isPlaying) clearDrill();+ }, [pickingEnabled, isPlaying, clearDrill]);++ // Releasing Alt (even without moving) ends the drill promptly.+ useEffect(() => {+ if (!pickingEnabled) return;+ const onKeyUp = (event: KeyboardEvent) => {+ if (event.key === "Alt") clearDrill();+ };+ window.addEventListener("keyup", onKeyUp);+ return () => window.removeEventListener("keyup", onKeyUp);+ }, [pickingEnabled, clearDrill]);++ // Pointer cursor signals a live drill target. document.body owns the cursor+ // because the r3f canvas fills the pane.+ useEffect(() => {+ document.body.style.cursor = drill ? "pointer" : "";+ return () => {+ document.body.style.cursor = "";+ };+ }, [drill]);+// 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);@@ -1435,7 +1938,10 @@ function AssemblyScene({active: false,startX: 0,startY: 0,- moved: false+ moved: false,+ // Canvas rect captured once per drag — the canvas can't move mid-drag,+ // and getBoundingClientRect per pointermove forces layout.+ rect: null as DOMRect | null};const localX = (event: PointerEvent, rect: DOMRect) =>event.clientX - rect.left;@@ -1459,6 +1965,7 @@ function AssemblyScene({const rect = env.gl.domElement.getBoundingClientRect();if (env.controls) env.controls.enabled = false; // suppress orbit for the boxdrag.active = true;+ drag.rect = rect;drag.startX = localX(event, rect);drag.startY = localY(event, rect);drag.moved = false;@@ -1473,7 +1980,7 @@ function AssemblyScene({const onMove = (event: PointerEvent) => {if (!drag.active) return;const env = boxEnvRef.current;- const rect = env.gl.domElement.getBoundingClientRect();+ const rect = drag.rect ?? env.gl.domElement.getBoundingClientRect();const x = localX(event, rect);const y = localY(event, rect);const width = Math.abs(x - drag.startX);@@ -1495,7 +2002,7 @@ function AssemblyScene({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 rect = drag.rect ?? env.gl.domElement.getBoundingClientRect();const endX = localX(event, rect);const endY = localY(event, rect);const minX = Math.min(drag.startX, endX);@@ -1545,6 +2052,8 @@ function AssemblyScene({object={scene}onClick={handleClick}onPointerMissed={handlePointerMissed}+ onPointerMove={handlePointerMove}+ onPointerOut={handlePointerOut}/>{isEditingActive && editMotion && onMotionChange && seatedCentroid && (<MotionPathEditor@@ -1651,6 +2160,84 @@ function formatTime(seconds: number): string {return `${minutes}:${String(remainder).padStart(2, "0")}`;}+/**+ * Chapter-style timeline: one segment per step (width ∝ its duration), the+ * played portion of each filled, the active step lifted, and a handle at the+ * playhead. A full-bleed transparent range input rides on top for pointer+ * scrubbing and keyboard control (←/→), so the custom visual stays purely+ * presentational.+ */+function TimelineScrubber({+ segments,+ startTimes,+ totalSeconds,+ displayTime,+ activeStepIndex,+ stepCount,+ onScrub+}: {+ segments: number[];+ startTimes: number[];+ totalSeconds: number;+ displayTime: number;+ activeStepIndex: number;+ stepCount: number;+ onScrub: (seconds: number) => void;+}) {+ const clamped = Math.min(Math.max(displayTime, 0), totalSeconds);+ const playheadPct = totalSeconds > 0 ? (clamped / totalSeconds) * 100 : 0;+ const disabled = stepCount === 0;++ return (+ <div className="group relative flex h-5 min-w-0 flex-1 items-center">+ <div className="flex h-1.5 w-full gap-0.5">+ {(segments.length > 0 ? segments : [1]).map((duration, index) => {+ const start = startTimes[index] ?? 0;+ const fill =+ duration > 0+ ? Math.min(Math.max((clamped - start) / duration, 0), 1)+ : clamped >= start+ ? 1+ : 0;+ return (+ <div+ key={`${start}-${index}`}+ className={cn(+ "relative h-full overflow-hidden rounded-full bg-muted-foreground/25 transition-colors",+ index === activeStepIndex && "bg-muted-foreground/40"+ )}+ style={{ flexGrow: Math.max(duration, 0.001) }}+ >+ <div+ className="absolute inset-0 origin-left rounded-full bg-primary"+ style={{ transform: `scaleX(${fill})` }}+ />+ </div>+ );+ })}+ </div>+ {!disabled && (+ <div+ aria-hidden="true"+ className="pointer-events-none absolute top-1/2 size-3 -translate-x-1/2 -translate-y-1/2 scale-50 rounded-full bg-white shadow-[0_1px_3px_rgba(0,0,0,0.5)] transition-transform group-hover:scale-100"+ style={{ left: `${playheadPct}%` }}+ />+ )}+ <input+ type="range"+ aria-label="Timeline"+ className="absolute inset-0 h-full w-full cursor-pointer opacity-0 disabled:cursor-default"+ min={0}+ max={Math.max(totalSeconds, 0.01)}+ step={0.05}+ value={clamped}+ disabled={disabled}+ onChange={(changeEvent) => onScrub(Number(changeEvent.target.value))}+ />+ </div>+ );+}+/** 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 {@@ -1700,6 +2287,27 @@ function findVisibleNodeId(return null;}+/**+ * Distinct rendered component ids the pointer ray passes through, front to back.+ * A part is one node, so the ray entering and exiting the same box yields that+ * box once — the LAST entry is the innermost content, the drill-select target.+ */+function visibleNodeStack(+ intersections: readonly { object: Object3D }[]+): string[] {+ const stack: string[] = [];+ const seen = new Set<string>();+ for (const intersection of intersections) {+ if (!isRendered(intersection.object)) continue;+ const nodeId = findNodeId(intersection.object);+ if (nodeId && !seen.has(nodeId)) {+ seen.add(nodeId);+ stack.push(nodeId);+ }+ }+ return stack;+}+function getOverride(mesh: Mesh,cache: Map<Mesh, MaterialOverrides>,diff --git a/packages/viewer/src/AssemblyViewer.tsx b/packages/viewer/src/AssemblyViewer.tsxindex e2853337d7..3eedfb072d 100644--- a/packages/viewer/src/AssemblyViewer.tsx+++ b/packages/viewer/src/AssemblyViewer.tsx@@ -34,6 +34,10 @@ export function AssemblyViewer({><Canvasgl={{ antialias: true, alpha: true }}+ // Cap the render resolution: a 3x-retina panel otherwise renders ~9x the+ // pixels, which is the main fill-rate cost when orbiting a dense model.+ // 2x keeps edges crisp without paying for the top DPR tier.+ dpr={[1, 2]}// 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 facesdiff --git a/packages/viewer/src/camera.test.ts b/packages/viewer/src/camera.test.tsindex 040633ef50..8609dc34c4 100644--- a/packages/viewer/src/camera.test.ts+++ b/packages/viewer/src/camera.test.ts@@ -1,161 +1,89 @@import { describe, expect, it } from "vitest";-import { computeStepCameraPose, computeStepCameras } from "./camera";-import { indexAssemblyGraph } from "./graph";-import type { AssemblyGraph, AssemblyGraphNode, Motion, Vec3 } from "./types";+import { fitFraming } from "./camera";+import type { 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" };+describe("fitFraming", () => {+ const tanH = Math.tan((30 * Math.PI) / 180); // wide-ish frustum for readable numbers+ const tanV = Math.tan((22.5 * Math.PI) / 180);+ const margin = 0.85;-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;+ /** Every point inside the margin frustum for the fitted pan/distance? */+ function contained(+ points: Vec3[],+ fit: { pan: [number, number]; distance: number }+ ): boolean {+ return points.every(([x, y, v]) => {+ const depth = fit.distance - v;+ return (+ depth > 0 &&+ Math.abs(x - fit.pan[0]) <= margin * tanH * depth + 1e-9 &&+ Math.abs(y - fit.pan[1]) <= margin * tanV * depth + 1e-9+ );+ });}- 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("keeps a centered action untouched", () => {+ const points: Vec3[] = [+ [-5, -5, 0],+ [5, 5, 0]+ ];+ const fit = fitFraming(points, tanH, tanV, margin, 100);+ expect(fit.pan).toEqual([0, 0]);+ expect(fit.distance).toBe(100);+ expect(contained(points, fit)).toBe(true);});- it("returns null for degenerate geometry", () => {- expect(computeStepCameraPose(index, ["missing"], NONE, [])).toBeNull();+ it("pans minimally toward an off-center action instead of zooming", () => {+ // Far right of the frustum at distance 100: half-width = .85*tanH*100 ≈ 49+ const points: Vec3[] = [+ [60, 0, 0],+ [70, 0, 0]+ ];+ const fit = fitFraming(points, tanH, tanV, margin, 100);+ expect(fit.distance).toBe(100); // no zoom — pan suffices+ expect(fit.pan[0]).toBeGreaterThan(0);+ expect(contained(points, fit)).toBe(true);+ // Minimal: the nearest constraint edge, not the action center+ expect(fit.pan[0]).toBeCloseTo(70 - margin * tanH * 100, 5);});-});--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("grows the distance only when the action cannot fit", () => {+ // Spread wider than the frustum can hold at the standing distance+ // (needs ~306 units of eye distance; fits under the 4× cap)+ const points: Vec3[] = [+ [-150, 0, 0],+ [150, 0, 0]+ ];+ const fit = fitFraming(points, tanH, tanV, margin, 100);+ expect(fit.distance).toBeGreaterThan(100);+ expect(contained(points, fit)).toBe(true);});- 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("caps the zoom-out at 4× the standing distance", () => {+ // Impossible spread — capping preserves context instead of zooming to a dot+ const points: Vec3[] = [+ [-1000, 0, 0],+ [1000, 0, 0]+ ];+ const fit = fitFraming(points, tanH, tanV, margin, 100);+ expect(fit.distance).toBe(400);});- 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("accounts for point depth (closer points need more room)", () => {+ // Same lateral offset, but one point sits far toward the eye where the+ // frustum is narrower+ const points: Vec3[] = [+ [40, 0, 60],+ [40, 0, 0]+ ];+ const fit = fitFraming(points, tanH, tanV, margin, 100);+ expect(contained(points, fit)).toBe(true);});- 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]);+ it("never returns a point behind the eye", () => {+ const points: Vec3[] = [[0, 0, 150]]; // beyond the standing distance+ const fit = fitFraming(points, tanH, tanV, margin, 100);+ expect(fit.distance).toBeGreaterThan(150);+ expect(contained(points, fit)).toBe(true);});});diff --git a/packages/viewer/src/camera.ts b/packages/viewer/src/camera.tsindex 4b256db58c..513dee0c70 100644--- a/packages/viewer/src/camera.ts+++ b/packages/viewer/src/camera.ts@@ -1,283 +1,72 @@-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];+import type { Vec3 } from "./types";++// Plain-array math so this stays importable server-side without pulling+// three.js into the bundle. The per-step view DIRECTION is baked by the Rust+// planner (mesh-precise sight lines, plan.json `viewDirection`); this module+// is the live half of that split — fitting the frame at the real viewport+// aspect once a direction is chosen (AssemblyPlayer's camera effect).++export type FramingFit = {+ /** Target shift along the camera's [right, up] axes (world units) */+ pan: [number, number];+ /** Eye distance from the (shifted) target */+ distance: number;};-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).+ * Minimal view-plane pan — and, only when the action genuinely can't fit,+ * a grown eye distance — that puts every point inside the camera frustum+ * with `margin` of the half-frustum usable (0.85 leaves a 15% border).+ *+ * Points are in CAMERA coordinates relative to the target: [right, up, view]+ * where `view` points from the target toward the eye. A point at [x, y, v]+ * sits at eye depth (distance − v) and is horizontally contained iff+ * |x − panX| ≤ margin · tanHalfH · (distance − v); the pan interval is the+ * intersection of those constraints, per axis, and the smallest |pan| inside+ * it wins. Distance never shrinks below `standingDistance` — the per-step+ * zoom stays steady.*/-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;+export function fitFraming(+ points: readonly Vec3[],+ tanHalfH: number,+ tanHalfV: number,+ margin: number,+ standingDistance: number+): FramingFit {+ if (points.length === 0) return { pan: [0, 0], distance: standingDistance };+ const maxDistance = standingDistance * 4;+ // Smallest shift inside [lo, hi]; interval midpoint when it's empty+ const pick = (lo: number, hi: number): number =>+ lo <= hi ? Math.min(Math.max(0, lo), hi) : (lo + hi) / 2;+ let distance = standingDistance;+ for (;;) {+ let loX = Number.NEGATIVE_INFINITY;+ let hiX = Number.POSITIVE_INFINITY;+ let loY = Number.NEGATIVE_INFINITY;+ let hiY = Number.POSITIVE_INFINITY;+ let allInFront = true;+ for (const [x, y, v] of points) {+ const depth = distance - v;+ if (depth <= 1e-6) {+ allInFront = false;+ break;}+ const hx = margin * tanHalfH * depth;+ const hy = margin * tanHalfV * depth;+ loX = Math.max(loX, x - hx);+ hiX = Math.min(hiX, x + hx);+ loY = Math.max(loY, y - hy);+ hiY = Math.min(hiY, y + hy);}- // Prefer travel running across the screen, not into it- if (motionDirection) {- score += 4 * Math.max(0, Math.abs(dot(candidate, motionDirection)) - 0.6);+ if (allInFront && loX <= hiX && loY <= hiY) {+ return { pan: [pick(loX, hiX), pick(loY, hiY)], distance };}- if (score < bestScore) {- bestScore = score;- bestDirection = candidate;+ if (distance >= maxDistance) {+ // Give up growing: best-effort pan (midpoints of the empty intervals)+ return allInFront+ ? { pan: [pick(loX, hiX), pick(loY, hiY)], distance }+ : { pan: [0, 0], distance };}+ distance = Math.min(distance * 1.2, maxDistance);}-- 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/index.ts b/packages/viewer/src/index.tsindex d2e3c870b5..8b8caadbe2 100644--- a/packages/viewer/src/index.ts+++ b/packages/viewer/src/index.ts@@ -5,7 +5,7 @@ export {type FutureComponentsMode} from "./AssemblyPlayer";export { AssemblyViewer, type AssemblyViewerProps } from "./AssemblyViewer";-export { computeStepCameraPose, computeStepCameras } from "./camera";+export { type FramingFit, fitFraming } from "./camera";export { describeStep, type NamedUnit } from "./describe";export { synthesizeFallbackMotion } from "./fallback";export {@@ -17,12 +17,12 @@ export {export {buildStepClip,displayMotionForStep,- exaggerateMotion,type MotionKeyframeOptions,type MotionKeyframes,motionDuration,motionToKeyframes,motionTravelDistance,+ naturalizeMotion,type Pose,type StepClipOptions,stepTimelineSeconds@@ -31,10 +31,12 @@ export {type AssemblyPlan,type AssemblyPlanComponent,type AssemblyStepGroup,+ assignStepPhases,buildAssemblyStepGroups,CURRENT_PLAN_VERSION,type PlannedMotion,- planMotionForComponents+ planMotionForComponents,+ type StepPhase} from "./plan";export type {AssemblyGraph,@@ -48,6 +50,7 @@ export type {Motion,NoneMotion,PathMotion,+ PlanViewHint,Quat,Vec3} from "./types";diff --git a/packages/viewer/src/motion.test.ts b/packages/viewer/src/motion.test.tsindex 627ec77092..90f12f53e8 100644--- a/packages/viewer/src/motion.test.ts+++ b/packages/viewer/src/motion.test.ts@@ -12,13 +12,14 @@ import {buildStepClip,DEFAULT_WAYPOINT_DISTANCE,displayMotionForStep,- exaggerateMotion,type MotionKeyframes,motionDuration,motionToKeyframes,motionToWaypoints,motionTravelDistance,+ naturalizeMotion,type Pose,+ resampleEased,waypointsToMotion} from "./motion";import type { AssemblyStep, Motion, Vec3 } from "./types";@@ -478,32 +479,118 @@ describe("buildStepClip", () => {});});-describe("exaggerateMotion", () => {+describe("resampleEased", () => {+ const straight: MotionKeyframes = {+ times: [0, 2],+ positions: [0, 0, 0, 0, 0, 100],+ quaternions: [0, 0, 0, 1, 0, 0, 0, 1]+ };++ it("preserves both endpoints and the total duration exactly", () => {+ const eased = resampleEased(straight);+ expectVectorClose(positionAt(eased, 0), [0, 0, 0]);+ expectVectorClose(positionAt(eased, lastIndex(eased)), [0, 0, 100]);+ expect(eased.times[0]).toBe(0);+ expect(eased.times[eased.times.length - 1]).toBeCloseTo(2);+ expectMonotonicTimes(eased);+ });++ it("accelerates off the start and decelerates into the seat", () => {+ const eased = resampleEased(straight);+ // 21 samples → index 5 is u=0.25 (time 0.5), index 15 is u=0.75 (time 1.5)+ expect(eased.times.length).toBe(21);+ const early = positionAt(eased, 5)[2] ?? Number.NaN;+ const late = positionAt(eased, 15)[2] ?? Number.NaN;+ // slow start: quarter of the way in time, far less than a quarter of the way+ expect(early).toBeLessThan(10); // easeInOutCubic(0.25)=0.0625 → ~6.25+ // gentle settle: three quarters through time, most of the distance covered+ expect(late).toBeGreaterThan(90); // easeInOutCubic(0.75)=0.9375 → ~93.75+ // symmetric ease keeps the midpoint at the midpoint+ expect(positionAt(eased, 10)[2] ?? Number.NaN).toBeCloseTo(50);+ });++ it("leaves a degenerate path unchanged", () => {+ const single: MotionKeyframes = {+ times: [0],+ positions: [1, 2, 3],+ quaternions: [0, 0, 0, 1]+ };+ expect(resampleEased(single)).toBe(single);+ const zero: MotionKeyframes = {+ times: [0, 0],+ positions: [0, 0, 0, 0, 0, 0],+ quaternions: [0, 0, 0, 1, 0, 0, 0, 1]+ };+ expect(resampleEased(zero)).toBe(zero);+ });+});++describe("naturalizeMotion", () => {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", () => {+ it("floors 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);+ const result = naturalizeMotion(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("caps a long travel to a few of the part's own body-lengths", () => {+ // 20mm part flying in 500mm → ceiling 3*20 + 5 = 65+ const long = { ...lift, distance: 500 };+ const result = naturalizeMotion(long, 20, 1000);+ if (result.type === "linear") {+ expect(result.distance).toBe(65);+ } else {+ throw new Error("expected linear motion");+ }});- it("leaves already-long travels unchanged", () => {- const long = { ...lift, distance: 200 };- expect(exaggerateMotion(long, 20, 1000)).toBe(long);+ it("caps a large part at the assembly-wide ceiling, not the raw travel", () => {+ // 400mm part (not small), 2000mm travel. Per-part ceiling is 3*400+5=1205,+ // but the assembly cap 0.35*1000=350 governs — nothing flies in from+ // further than a third of the whole assembly, however large the part.+ const long = { ...lift, distance: 2000 };+ const result = naturalizeMotion(long, 400, 1000);+ if (result.type === "linear") {+ expect(result.distance).toBe(350);+ } else {+ throw new Error("expected linear motion");+ }});- it("scales L segments proportionally", () => {+ it("keeps a large flat part's drop within the assembly (seal fly-out)", () => {+ // The SA BCU seal: 166mm diagonal, 288mm L-travel, 196mm assembly. Without+ // the assembly cap its ceiling is 3*166+5=503, so 288mm passed through and+ // it flew in from 1.5x the whole assembly.+ const seal: Motion = {+ type: "L",+ segments: [+ { direction: [1, 0, 0], distance: 122 },+ { direction: [0, 0, -1], distance: 166 }+ ]+ };+ const result = naturalizeMotion(seal, 166, 196);+ if (result.type !== "L") throw new Error("expected L motion");+ const total = result.segments.reduce(+ (sum, s) => sum + Math.abs(s.distance),+ 0+ );+ expect(total).toBeCloseTo(196 * 0.35, 1); // ~68.6mm, a natural drop+ });++ it("leaves an in-band travel unchanged", () => {+ const inBand = { ...lift, distance: 55 }; // within [50, 65] for a 20mm part+ expect(naturalizeMotion(inBand, 20, 1000)).toBe(inBand);+ });++ it("floors then scales L segments proportionally", () => {const motion: Motion = {type: "L",segments: [@@ -511,7 +598,7 @@ describe("exaggerateMotion", () => {{ direction: [0, 0, -1], distance: 4 }]};- const result = exaggerateMotion(motion, 20, 1000);+ const result = naturalizeMotion(motion, 20, 1000); // total 10 → floor 50if (result.type === "L") {const total = result.segments.reduce((sum, s) => sum + s.distance, 0);expect(total).toBeCloseTo(50);@@ -523,9 +610,29 @@ describe("exaggerateMotion", () => {}});- it("does not exaggerate none motions", () => {+ it("caps an over-long L total to the ceiling", () => {+ const motion: Motion = {+ type: "L",+ segments: [+ { direction: [1, 0, 0], distance: 180 },+ { direction: [0, 0, -1], distance: 120 }+ ]+ };+ const result = naturalizeMotion(motion, 20, 1000); // total 300 → ceiling 65+ if (result.type === "L") {+ const total = result.segments.reduce((sum, s) => sum + s.distance, 0);+ expect(total).toBeCloseTo(65);+ expect(+ result.segments[0]!.distance / result.segments[1]!.distance+ ).toBeCloseTo(180 / 120);+ } else {+ throw new Error("expected L motion");+ }+ });++ it("does not touch none motions", () => {const none = { type: "none" } as const;- expect(exaggerateMotion(none, 20, 1000)).toBe(none);+ expect(naturalizeMotion(none, 20, 1000)).toBe(none);});});diff --git a/packages/viewer/src/motion.ts b/packages/viewer/src/motion.tsindex 0882fd457f..41b96e63e7 100644--- a/packages/viewer/src/motion.ts+++ b/packages/viewer/src/motion.ts@@ -153,36 +153,73 @@ export function displayMotionForStep(const SMALL_COMPONENT_FRACTION = 0.15;/** Small components travel at least this many times their own size. */const SMALL_COMPONENT_TRAVEL_FACTOR = 2.5;+/** No component travels more than this many times its own size, +margin. */+const NATURAL_TRAVEL_FACTOR = 3;+/** Additive slack (mm) on the travel ceiling so a seat still fully clears. */+const NATURAL_TRAVEL_MARGIN_MM = 5;+/**+ * Hard ceiling as a fraction of the whole assembly: nothing animates in from+ * further than this, however large the part. A big FLAT part (a gasket, a lid)+ * has a huge diagonal but should still just drop a short way onto its seat —+ * the per-part `NATURAL_TRAVEL_FACTOR × diagonal` ceiling is meaningless for it+ * (3× a 166 mm seal = 500 mm), so its planner collision path (an L-shaped+ * detour around the box, ~1.5× the assembly) reads as flying in from off-screen.+ */+const ASSEMBLY_TRAVEL_FRACTION = 0.35;/**- * 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.+ * Shapes a component's insertion travel into a natural band for playback so it+ * neither pops (too short) nor flies in from across the assembly (too long).+ *+ * Display-only: the stored plan keeps the geometric (collision-minimum) travel;+ * this only shortens/lengthens where the part *starts* its animated approach.+ * Safe because playback hides future-step parts and a part seats against the+ * already-placed parts below/beside it, not along its short approach.+ *+ * - Ceiling (all parts): `d · NATURAL_TRAVEL_FACTOR + margin` — a long+ * collision path (slider, deep mate, a graze past a distant neighbor) is+ * trimmed to a few of the part's own body-lengths.+ * - Floor (small parts only, < SMALL_COMPONENT_FRACTION of the assembly): keeps+ * bolts/washers/pins traveling `d · SMALL_COMPONENT_TRAVEL_FACTOR` so they+ * still read at assembly scale.+ *+ * Returns the motion unchanged when it's non-translating or already in band.*/-export function exaggerateMotion(+export function naturalizeMotion(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;+ const isSmall =+ componentDiagonal < assemblyDiagonal * SMALL_COMPONENT_FRACTION;+ const floor = isSmall ? componentDiagonal * SMALL_COMPONENT_TRAVEL_FACTOR : 0;+ // Per-part ceiling, then the assembly-wide cap; never below the floor so a+ // borderline-small part keeps its readable minimum travel.+ const ceiling = Math.max(+ floor,+ Math.min(+ componentDiagonal * NATURAL_TRAVEL_FACTOR + NATURAL_TRAVEL_MARGIN_MM,+ assemblyDiagonal * ASSEMBLY_TRAVEL_FRACTION+ )+ );+ const clamp = (t: number) => Math.min(Math.max(t, floor), ceiling);switch (motion.type) {case "linear": {- if (motion.distance >= minTravel) return motion;- return { ...motion, distance: minTravel };+ const distance = clamp(motion.distance);+ return distance === motion.distance ? motion : { ...motion, distance };}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;+ if (total <= 0) return motion;+ const target = clamp(total);+ if (target === total) return motion;+ const scale = target / total;return {...motion,segments: motion.segments.map((segment) => ({@@ -201,6 +238,57 @@ export function exaggerateMotion(* world pose is `basePose`. The last keyframe always equals `basePose`.* Returns `null` for `none` motions.*/+/** Sub-samples per motion when re-timing a straight path through ease-in-out. */+const EASE_SAMPLES = 20;++/** Ease-in-out cubic: slow start, quick middle, gentle settle. */+function easeInOutCubic(t: number): number {+ return t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;+}++/**+ * Re-times a piecewise-linear keyframe path through an ease-in-out velocity+ * profile so an insertion accelerates off the start and decelerates into its+ * seat instead of moving at constant speed. Preserves the geometric path and+ * both endpoints exactly (only WHEN the part is at each point changes); total+ * duration is unchanged. Playback-only — the stored motion and the editable+ * waypoints keep the raw path.+ */+export function resampleEased(kf: MotionKeyframes): MotionKeyframes {+ const n = kf.times.length;+ const total = kf.times[n - 1] ?? 0;+ if (n < 2 || total <= 0) return kf;++ const times: number[] = [];+ const positions: number[] = [];+ const quaternions: number[] = [];+ const a = new Vector3();+ const b = new Vector3();+ const qa = new Quaternion();+ const qb = new Quaternion();++ for (let j = 0; j <= EASE_SAMPLES; j++) {+ const u = j / EASE_SAMPLES;+ const s = easeInOutCubic(u) * total; // eased sample point along the path+ let i = 0;+ while (i < n - 1 && (kf.times[i + 1] ?? total) < s) i++;+ const t0 = kf.times[i] ?? 0;+ const t1 = kf.times[i + 1] ?? total;+ const span = t1 - t0;+ const f = span > 1e-9 ? (s - t0) / span : 0;+ a.fromArray(kf.positions, i * 3);+ b.fromArray(kf.positions, (i + 1) * 3);+ a.lerp(b, f);+ qa.fromArray(kf.quaternions, i * 4);+ qb.fromArray(kf.quaternions, (i + 1) * 4);+ qa.slerp(qb, f);+ times.push(u * total);+ positions.push(a.x, a.y, a.z);+ quaternions.push(qa.x, qa.y, qa.z, qa.w);+ }+ return { times, positions, quaternions };+}+export function motionToKeyframes(motion: Motion,basePose: Pose,@@ -399,7 +487,7 @@ export function buildStepClip(const worldScale = new Vector3();node.matrixWorld.decompose(worldPosition, worldQuaternion, worldScale);- const keyframes = motionToKeyframes(+ const rawKeyframes = motionToKeyframes(step.motion,{position: worldPosition.toArray() as Vec3,@@ -407,7 +495,14 @@ export function buildStepClip(},{ ...options, duration });- if (!keyframes) continue;+ if (!rawKeyframes) continue;+ // Ease the straight insertion approaches (accelerate off the start, settle+ // into the seat). Helix threads at a constant rate (mechanically correct)+ // and paths carry their own timing, so leave those raw.+ const keyframes =+ step.motion.type === "linear" || step.motion.type === "L"+ ? resampleEased(rawKeyframes)+ : rawKeyframes;const parentWorldInverse = node.parent? node.parent.matrixWorld.clone().invert()diff --git a/packages/viewer/src/plan.test.ts b/packages/viewer/src/plan.test.tsindex d64ec99ed2..fdcb4bd384 100644--- a/packages/viewer/src/plan.test.ts+++ b/packages/viewer/src/plan.test.ts@@ -449,3 +449,53 @@ describe("corridor-aware simultaneous steps", () => {expect(groups).toHaveLength(4);});});++describe("buildAssemblyStepGroups floater fold", () => {+ const push: Motion = { type: "linear", direction: [0, 0, -1], distance: 20 };+ // base placed first; "arm" is precedence-forced before "clip" (the neighbor+ // that attaches to it), so it lands detached; "tail" then attaches to clip.+ const foldPlan: AssemblyPlan = {+ version: 3,+ unit: "mm",+ sequence: ["base", "arm", "clip", "tail"],+ components: {+ base: { motion: { type: "none" } },+ arm: { motion: push, confidence: "high" },+ clip: { motion: push, confidence: "high" },+ tail: { motion: push, confidence: "high" }+ },+ contacts: {+ base: ["tail"],+ arm: ["clip"],+ clip: ["arm", "tail"],+ tail: ["clip", "base"]+ },+ warnings: []+ };+ const foldGraph = indexAssemblyGraph(+ graphOf([+ graphLeaf("base", { min: [-50, -50, 0], max: [50, 50, 10] }, "h-base"),+ graphLeaf("arm", { min: [-40, -40, 10], max: [-30, -30, 30] }, "h-arm"),+ graphLeaf("clip", { min: [-32, -32, 10], max: [-22, -22, 30] }, "h-clip"),+ graphLeaf("tail", { min: [10, 10, 10], max: [20, 20, 30] }, "h-tail")+ ])+ );++ it("folds a detached part into the next step that attaches to it", () => {+ const groups = buildAssemblyStepGroups(foldPlan, foldGraph);+ // base, [arm+clip], tail — the orphan arm rides one step with its neighbor+ expect(groups.map((g) => g.componentNodeIds)).toEqual([+ ["base"],+ ["arm", "clip"],+ ["tail"]+ ]);+ });++ it("leaves the sequence untouched when the plan has no contacts", () => {+ const groups = buildAssemblyStepGroups(+ { ...foldPlan, contacts: undefined },+ foldGraph+ );+ expect(groups).toHaveLength(4);+ });+});diff --git a/packages/viewer/src/plan.ts b/packages/viewer/src/plan.tsindex 2efdf8715e..d1948db421 100644--- a/packages/viewer/src/plan.ts+++ b/packages/viewer/src/plan.ts@@ -24,6 +24,25 @@ export type AssemblyPlanComponent = {groupId?: string;/** v2: rigidly merged into this component (rides its step) */mergedInto?: string;+ /**+ * The part's center of mass falls outside the support polygon of the parts+ * placed below it — it will tip and likely needs a fixture or a second hand.+ * Diagnostic only.+ */+ needsSupport?: boolean;+ /**+ * Build wave: longest-path level in the precedence DAG. Components sharing a+ * wave have no ordering constraint and can be assembled in parallel. Absent+ * for cycle-affected parts.+ */+ wave?: number;+ /**+ * Mesh-precise camera direction (unit vector, target→eye) baked by the+ * planner: sight lines against the real triangles of everything installed+ * earlier. The viewer applies it with live framing (target, distance,+ * frustum fit at the real aspect). Optional: absent on older plans.+ */+ viewDirection?: [number, number, number];};/**@@ -46,8 +65,20 @@ export type AssemblyPlan = {*/groups?: Record<string,- { componentNodeIds: string[]; motion: Motion; name?: string }+ {+ componentNodeIds: string[];+ motion: Motion;+ name?: string;+ viewDirection?: [number, number, number];+ }>;+ /**+ * v3: planned-body contact graph (body node_id → touching bodies), keyed in+ * the pre-expansion body space — a member maps to its body via+ * `components[member].groupId ?? member`. Powers floater-into-neighbor step+ * folding in {@link buildAssemblyStepGroups}. Optional: absent on older plans.+ */+ contacts?: Record<string, string[]>;warnings: string[];};@@ -83,6 +114,9 @@ export function planMotionForComponents(return { motion: first.motion, confidence: first.confidence ?? "low" };}+ // Full stringify (not motionKey) — agreement must account for distance and+ // helix/path params, which motionKey drops. This is a cold plan-gen path, so+ // the per-entry allocation is not worth trading correctness for.const firstKey = JSON.stringify(first.motion);const allAgree =entries.length === componentNodeIds.length &&@@ -109,6 +143,15 @@ function isMotion(value: unknown): value is Motion {);}+/**+ * A subassembly phase a step belongs to. `null` = the main phase (built seated+ * at final coordinates). A non-null phase is a cluster that builds staged off to+ * the side and flies into the main body at its `join` step. `id` is stable+ * within a plan; `join` is true on exactly the one step that attaches the+ * cluster to the main body.+ */+export type StepPhase = { id: string; name: string; join: boolean };+export type AssemblyStepGroup = {componentNodeIds: string[];motion: Motion;@@ -119,8 +162,27 @@ export type AssemblyStepGroup = {* the components in at their seated pose.*/blockedBy: string[];+ /**+ * Any member's center of mass falls outside the support polygon of the parts+ * below it — the step may need a fixture or a second hand (diagnostic).+ */+ needsSupport: boolean;+ /**+ * Build wave: steps sharing a wave have no ordering constraint between them+ * (parallel-buildable). Members of one step share a wave; absent (undefined)+ * for cycle-affected parts.+ */+ wave?: number;/** v3: the pre-grouped unit's name (e.g. "PCB Assembly"), for the step title. */name?: string;+ /** Planner-baked camera direction for this step (see AssemblyPlanComponent). */+ viewDirection?: [number, number, number];+ /**+ * Subassembly phase, derived from the plan's `contacts` graph (see+ * {@link assignStepPhases}). `null` for the main phase or when the plan has no+ * `contacts`.+ */+ phase?: StepPhase | null;};function motionKey(motion: Motion): string {@@ -230,6 +292,8 @@ export function buildAssemblyStepGroups(const component = plan.components[nodeId];if (component?.mergedInto) continue; // defensive: hosts carry their mergesconst blockedBy = component?.blockedBy ?? [];+ const needsSupport = component?.needsSupport === true;+ const wave = component?.wave;const flagged = blockedBy.length > 0 || component?.verified === false;const motion: Motion = flagged? { type: "none" }@@ -270,6 +334,7 @@ export function buildAssemblyStepGroups(previous.blockedBy.push(blocker);}}+ if (needsSupport) previous.needsSupport = true;// Identical components can sit at different depths: animate the longestif (motion.type === "linear" && previous.motion.type === "linear") {previous.motion = {@@ -284,9 +349,17 @@ export function buildAssemblyStepGroups(motion,confidence,blockedBy: [...blockedBy],+ needsSupport,+ wave,name: component?.groupId? plan.groups?.[component.groupId]?.name: undefined,+ // Group steps take the group's baked direction; merged-identical steps+ // keep the first entry's (later same-key entries never overwrite)+ viewDirection: component?.groupId+ ? (plan.groups?.[component.groupId]?.viewDirection ??+ component?.viewDirection)+ : component?.viewDirection,key,corridors: corridor ? [corridor] : []});@@ -314,5 +387,224 @@ export function buildAssemblyStepGroups(}}- return groups.map(({ key: _key, corridors: _corridors, ...group }) => group);+ // Floater fold: a part whose insertion path is blocked by a later neighbor is+ // placed BEFORE that neighbor (collision precedence), so for one step it sits+ // detached — a floating island. When the very next step is exactly the+ // neighbor that attaches to it, fold the two into one step: they install as a+ // rigid pair animating along the detached part's (open-space) approach, so it+ // never renders alone. Uses the planner's body-level contact graph; skipped on+ // older plans that predate `contacts`.+ const contacts = plan.contacts;+ if (contacts) {+ const bodyKey = (nodeId: string): string => {+ const component = plan.components[nodeId];+ return component?.mergedInto ?? component?.groupId ?? nodeId;+ };+ const bodiesOf = (group: WorkingGroup): string[] => {+ const bodies = new Set<string>();+ for (const nodeId of group.componentNodeIds) bodies.add(bodyKey(nodeId));+ return [...bodies];+ };+ const touchesAny = (bodies: string[], target: Set<string>): boolean =>+ bodies.some((body) =>+ (contacts[body] ?? []).some((neighbor) => target.has(neighbor))+ );++ const folded: WorkingGroup[] = [];+ const present = new Set<string>();+ let index = 0;+ while (index < groups.length) {+ const group = groups[index];+ if (!group) {+ index++;+ continue;+ }+ // The first placed group is the base — seated, never a floater.+ if (folded.length > 0) {+ const bodies = bodiesOf(group);+ const detached = !touchesAny(bodies, present);+ const next = groups[index + 1];+ if (detached && next && touchesAny(bodiesOf(next), new Set(bodies))) {+ group.componentNodeIds.push(...next.componentNodeIds);+ for (const blocker of next.blockedBy) {+ if (!group.blockedBy.includes(blocker))+ group.blockedBy.push(blocker);+ }+ if (next.confidence === "low") group.confidence = "low";+ for (const body of bodies) present.add(body);+ for (const body of bodiesOf(next)) present.add(body);+ folded.push(group);+ index += 2;+ continue;+ }+ }+ for (const body of bodiesOf(group)) present.add(body);+ folded.push(group);+ index++;+ }+ groups.length = 0;+ groups.push(...folded);+ }++ const stripped = groups.map(+ ({ key: _key, corridors: _corridors, ...group }) => group+ );+ const phases = assignStepPhases(stripped, plan, graphIndex);+ for (let index = 0; index < stripped.length; index++) {+ const group = stripped[index];+ if (group) group.phase = phases[index] ?? null;+ }+ return stripped;+}++/** A staged subassembly cluster being built up before it joins the main body. */+type PhaseIsland = {+ /** Group indices belonging to this cluster, in order. */+ groups: number[];+ /** Group index that attaches this cluster to the main body, or null if it never does. */+ join: number | null;+ /** Cluster name (largest-volume member of its seed group). */+ name: string;+};++/**+ * Partition the step groups into subassembly phases from the plan's body-level+ * `contacts` graph. Replays the sequence tracking which bodies are connected to+ * the main body (the first group's cluster) versus building up in a detached+ * cluster off to the side. A group that touches nothing placed starts a new+ * staged cluster; a group that first bridges a staged cluster to the main body+ * is that cluster's `join` step; staged clusters that touch each other before+ * joining merge into one phase. Groups on (or joined into) the main body get+ * `null`. Deterministic; returns `null` for every group when the plan has no+ * `contacts` (older plans).+ */+export function assignStepPhases(+ groups: readonly Pick<AssemblyStepGroup, "componentNodeIds">[],+ plan: AssemblyPlan,+ graphIndex: AssemblyGraphIndex | null+): (StepPhase | null)[] {+ const result: (StepPhase | null)[] = groups.map(() => null);+ const contacts = plan.contacts;+ if (!contacts || groups.length === 0) return result;++ const bodyKey = (nodeId: string): string => {+ const component = plan.components[nodeId];+ return component?.mergedInto ?? component?.groupId ?? nodeId;+ };+ const bodiesOf = (index: number): string[] => {+ const bodies = new Set<string>();+ for (const nodeId of groups[index]?.componentNodeIds ?? []) {+ bodies.add(bodyKey(nodeId));+ }+ return [...bodies];+ };+ const seedName = (index: number): string => {+ let best: string | null = null;+ let bestVolume = -1;+ if (graphIndex) {+ for (const nodeId of groups[index]?.componentNodeIds ?? []) {+ const node = graphIndex.nodesById.get(nodeId);+ const volume = node?.volume ?? 0;+ if (node?.name && volume >= bestVolume) {+ best = node.name;+ bestVolume = volume;+ }+ }+ }+ return best ?? "Subassembly";+ };++ const baseBodies = new Set<string>();+ const bodyIsland = new Map<string, PhaseIsland>();+ const islandOfGroup: (PhaseIsland | null)[] = groups.map(() => null);++ const touchesBase = (bodies: string[]): boolean =>+ bodies.some((body) =>+ (contacts[body] ?? []).some((neighbor) => baseBodies.has(neighbor))+ );+ const touchedIslands = (bodies: string[]): PhaseIsland[] => {+ const seen = new Set<PhaseIsland>();+ for (const body of bodies) {+ for (const neighbor of contacts[body] ?? []) {+ const island = bodyIsland.get(neighbor);+ if (island) seen.add(island);+ }+ }+ return [...seen];+ };+ const earliest = (islands: PhaseIsland[]): PhaseIsland =>+ islands.reduce((a, b) => (a.groups[0]! <= b.groups[0]! ? a : b));++ for (let index = 0; index < groups.length; index++) {+ const bodies = bodiesOf(index);+ if (index === 0) {+ for (const body of bodies) baseBodies.add(body);+ continue;+ }+ const onBase = touchesBase(bodies);+ const islands = touchedIslands(bodies);++ if (!onBase && islands.length === 0) {+ const island: PhaseIsland = {+ groups: [index],+ join: null,+ name: seedName(index)+ };+ islandOfGroup[index] = island;+ for (const body of bodies) bodyIsland.set(body, island);+ continue;+ }++ if (onBase) {+ if (islands.length > 0) {+ // Join step: bridges staged cluster(s) into the main body.+ const primary = earliest(islands);+ primary.join = index;+ islandOfGroup[index] = primary;+ for (const island of islands) {+ for (const [body, owner] of bodyIsland) {+ if (owner === island) {+ bodyIsland.delete(body);+ baseBodies.add(body);+ }+ }+ }+ }+ for (const body of bodies) baseBodies.add(body);+ continue;+ }++ // Touches only staged cluster(s) — merge them and extend.+ const primary = earliest(islands);+ for (const island of islands) {+ if (island === primary) continue;+ for (const groupIndex of island.groups) {+ islandOfGroup[groupIndex] = primary;+ primary.groups.push(groupIndex);+ }+ for (const [body, owner] of bodyIsland) {+ if (owner === island) bodyIsland.set(body, primary);+ }+ }+ primary.groups.push(index);+ islandOfGroup[index] = primary;+ for (const body of bodies) bodyIsland.set(body, primary);+ }++ // Assign stable ids by first-appearance order (also the staging lane order).+ const order = new Map<PhaseIsland, number>();+ for (let index = 0; index < groups.length; index++) {+ const island = islandOfGroup[index];+ if (island && !order.has(island)) order.set(island, order.size);+ }+ for (let index = 0; index < groups.length; index++) {+ const island = islandOfGroup[index];+ if (!island) continue;+ result[index] = {+ id: `p${order.get(island)}`,+ name: island.name,+ join: island.join === index+ };+ }+ return result;}diff --git a/packages/viewer/src/steps.ts b/packages/viewer/src/steps.tsindex b4e0f9b266..8f4be4ee3f 100644--- a/packages/viewer/src/steps.ts+++ b/packages/viewer/src/steps.ts@@ -4,9 +4,18 @@* three.js/react rendering deps that the package barrel (index.ts) re-exports.*/import { indexAssemblyGraph } from "./graph";-import { buildAssemblyStepGroups, CURRENT_PLAN_VERSION } from "./plan";+import {+ assignStepPhases,+ buildAssemblyStepGroups,+ CURRENT_PLAN_VERSION+} from "./plan";-export { buildAssemblyStepGroups, CURRENT_PLAN_VERSION, indexAssemblyGraph };+export {+ assignStepPhases,+ buildAssemblyStepGroups,+ CURRENT_PLAN_VERSION,+ indexAssemblyGraph+};export type { AssemblyGraphIndex } from "./graph";-export type { AssemblyPlan, AssemblyStepGroup } from "./plan";+export type { AssemblyPlan, AssemblyStepGroup, StepPhase } from "./plan";export type { AssemblyGraph } from "./types";diff --git a/packages/viewer/src/types.ts b/packages/viewer/src/types.tsindex 892e3c0a23..ce4254cf1e 100644--- a/packages/viewer/src/types.ts+++ b/packages/viewer/src/types.ts@@ -71,6 +71,18 @@ export type CameraPose = {fov: number;};+/**+ * Planner-baked camera hint: a mesh-precise view DIRECTION (target→eye, unit)+ * chosen with sight lines against the real triangles of everything installed+ * earlier. The viewer supplies the rest live — target, standing distance, and+ * frustum fit at the actual viewport aspect. Distinct from a manual+ * {@link CameraPose}, which is applied verbatim.+ */+export type PlanViewHint = {+ source: "plan";+ direction: Vec3;+};+/** Fastener callout for a step. All fields optional. */export type Fastener = {spec?: string;@@ -86,7 +98,7 @@ export type AssemblyStep = {/** Components installed in this step (stable nodeIds from glTF extras/graph.json) */componentNodeIds: string[];motion: Motion;- camera: CameraPose | null;+ camera: CameraPose | PlanViewHint | null;fastener: Fastener | null;/** Optional authored override for the step's timeline length (seconds) */durationSeconds?: number | null;@@ -96,6 +108,13 @@ export type AssemblyStep = {* motion — a fabricated path would animate straight through geometry.*/flagged?: boolean;+ /**+ * Subassembly phase this step belongs to (baked at step generation from the+ * plan's contact graph). `null`/absent = the main phase, built seated. A+ * non-null phase builds staged off to the side and flies into the main body+ * at its `join` step. See `@carbon/viewer` staging.+ */+ phase?: { id: string; name: string; join: boolean } | null;};/** One node of the assembly tree in graph.json. */diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2d626272a1..771bf34cc3 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -301,7 +301,7 @@ importers:version: 1.40.0'@react-router/remix-routes-option-adapter':specifier: 'catalog:'- version: 7.15.1(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])+ version: 7.15.1(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])cookie:specifier: 'catalog:'version: 1.1.1@@ -338,7 +338,7 @@ importers:version: 5.9.4([email protected])([email protected])'@react-router/dev':specifier: 'catalog:'- version: 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@types/aws-lambda':specifier: 8.10.152version: 8.10.152@@ -389,7 +389,7 @@ importers:version: 5.8.3vite-plugin-babel-macros:specifier: 'catalog:'- version: 1.0.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 1.0.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))optionalDependencies:'@rollup/rollup-linux-x64-gnu':specifier: 4.60.1@@ -685,7 +685,7 @@ importers:version: 3.4.5([email protected])([email protected])'@react-router/remix-routes-option-adapter':specifier: 'catalog:'- version: 7.15.1(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])+ version: 7.15.1(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])'@react-router/serve':specifier: 'catalog:'version: 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])@@ -730,7 +730,7 @@ importers:version: 1.6.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])'@vercel/react-router':specifier: 'catalog:'- version: 1.2.6(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])+ version: 1.2.6(@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])'@visx/responsive':specifier: 2.17.0version: 2.17.0([email protected])@@ -962,16 +962,16 @@ importers:version: 5.9.4(@lingui/[email protected]([email protected])([email protected]))([email protected])([email protected])'@lingui/vite-plugin':specifier: 'catalog:'- version: 5.9.4([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 5.9.4([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@react-router/dev':specifier: 'catalog:'- version: 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ version: 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])'@tailwindcss/typography':specifier: 'catalog:'version: 0.5.19([email protected])'@tailwindcss/vite':specifier: 'catalog:'- version: 4.3.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.3.0([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))'@types/d3':specifier: 7.4.3version: 7.4.3@@ -1031,13 +1031,13 @@ importers:version: 5.8.3vite:specifier: 'catalog:'- version: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ version: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vite-plugin-babel-macros:specifier: 'catalog:'- version: 1.0.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 1.0.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))vitest:specifier: 'catalog:'- version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))apps/mes:dependencies:@@ -3467,6 +3467,9 @@ importers:three:specifier: 0.163.0version: 0.163.0+ three-mesh-bvh:+ specifier: 0.7.8+ version: 0.7.8([email protected])three-stdlib:specifier: 2.36.1version: 2.36.1([email protected])@@ -16961,7 +16964,7 @@ snapshots:'@babel/traverse': 7.29.0'@babel/types': 7.29.0convert-source-map: 2.0.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])gensync: 1.0.0-beta.2json5: 2.2.3semver: 7.7.4@@ -16981,7 +16984,7 @@ snapshots:'@babel/types': 7.29.0'@jridgewell/remapping': 2.3.5convert-source-map: 2.0.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])gensync: 1.0.0-beta.2json5: 2.2.3semver: 7.7.4@@ -17151,7 +17154,7 @@ snapshots:'@babel/parser': 7.29.2'@babel/template': 7.28.6'@babel/types': 7.29.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])globals: 11.12.0transitivePeerDependencies:- supports-color@@ -17164,7 +17167,7 @@ snapshots:'@babel/parser': 7.29.2'@babel/template': 7.28.6'@babel/types': 7.29.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-color@@ -18212,16 +18215,6 @@ snapshots:transitivePeerDependencies:- typescript- '@lingui/[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@lingui/cli': 5.9.4([email protected])([email protected])- '@lingui/conf': 5.9.4([email protected])- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- transitivePeerDependencies:- - babel-plugin-macros- - supports-color- - typescript-'@lingui/[email protected]([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@lingui/cli': 5.9.4([email protected])([email protected])@@ -18583,7 +18576,7 @@ snapshots:dependencies:'@oclif/core': 4.11.7ansis: 3.17.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])npm: 11.17.0npm-package-arg: 11.0.3npm-run-path: 5.3.0@@ -21896,7 +21889,7 @@ snapshots:'@react-pdf/primitives': 4.2.0'@react-pdf/stylesheet': 6.1.4- '@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':+ '@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:'@babel/core': 7.29.0'@babel/generator': 7.29.1@@ -21926,7 +21919,7 @@ snapshots:semver: 7.7.4tinyglobby: 0.2.17valibot: 1.3.1([email protected])- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])optionalDependencies:'@react-router/serve': 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])@@ -21946,56 +21939,6 @@ snapshots:- tsx- yaml- '@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':- 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- '@react-router/node': 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])- '@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])- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- optionalDependencies:- '@react-router/serve': 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])- typescript: 5.8.3- transitivePeerDependencies:- - '@types/node'- - babel-plugin-macros- - jiti- - less- - lightningcss- - sass- - sass-embedded- - stylus- - sugarss- - supports-color- - terser- - tsx- - yaml-'@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])':dependencies:'@babel/core': 7.29.0@@ -22068,15 +22011,9 @@ snapshots:optionalDependencies:typescript: 5.8.3- '@react-router/[email protected](@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])':- dependencies:- '@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])- optionalDependencies:- typescript: 5.8.3-- '@react-router/[email protected](@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])':+ '@react-router/[email protected](@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])':dependencies:- '@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])+ '@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])optionalDependencies:typescript: 5.8.3@@ -23366,13 +23303,6 @@ snapshots:postcss-selector-parser: 6.0.10tailwindcss: 4.3.0- '@tailwindcss/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@tailwindcss/node': 4.3.0- '@tailwindcss/oxide': 4.3.0- tailwindcss: 4.3.0- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])-'@tailwindcss/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@tailwindcss/node': 4.3.0@@ -24240,16 +24170,6 @@ snapshots:'@vercel/[email protected]': {}- '@vercel/[email protected](@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])':- dependencies:- '@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])- '@react-router/node': 7.15.1([email protected]([email protected]([email protected]))([email protected]))([email protected])- '@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-'@vercel/[email protected](@react-router/[email protected](patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])':dependencies:'@react-router/dev': 7.15.1(patch_hash=77f56df34c4642159bb889b71903a3953827448e994174779d32db487727da95)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected])@@ -24388,14 +24308,6 @@ snapshots:optionalDependencies:vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':- dependencies:- '@vitest/spy': 4.1.6- estree-walker: 3.0.3- magic-string: 0.30.21- optionalDependencies:- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])-'@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))':dependencies:'@vitest/spy': 4.1.6@@ -24865,7 +24777,7 @@ snapshots:dependencies:bytes: 3.1.2content-type: 1.0.5- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])http-errors: 2.0.1iconv-lite: 0.7.2on-finished: 2.4.1@@ -25741,7 +25653,7 @@ snapshots:dependencies:'@socket.io/component-emitter': 3.1.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])engine.io-parser: 5.2.3ws: 8.21.0xmlhttprequest-ssl: 2.1.2@@ -25761,7 +25673,7 @@ snapshots:base64id: 2.0.0cookie: 0.7.2cors: 2.8.6- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])engine.io-parser: 5.2.3ws: 8.21.0transitivePeerDependencies:@@ -26178,7 +26090,7 @@ snapshots:content-type: 1.0.5cookie: 0.7.2cookie-signature: 1.2.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])depd: 2.0.0encodeurl: 2.0.0escape-html: 1.0.3@@ -26307,7 +26219,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])encodeurl: 2.0.0escape-html: 1.0.3on-finished: 2.4.1@@ -26873,14 +26785,14 @@ snapshots:dependencies:agent-base: 7.1.4- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-colordependencies:agent-base: 9.0.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-color@@ -26993,7 +26905,7 @@ snapshots:canonicalize: 1.0.8chalk: 4.1.2cross-fetch: 4.1.0([email protected])- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])hash.js: 1.1.7json-stringify-safe: 5.0.1ms: 2.1.3@@ -27031,7 +26943,7 @@ snapshots:canonicalize: 1.0.8chalk: 4.1.2cross-fetch: 4.1.0([email protected])- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])hash.js: 1.1.7json-stringify-safe: 5.0.1ms: 2.1.3@@ -27093,7 +27005,7 @@ snapshots:dependencies:'@ioredis/commands': 1.5.1cluster-key-slot: 1.1.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])denque: 2.1.0lodash.defaults: 4.2.0lodash.isarguments: 3.1.0@@ -28191,7 +28103,7 @@ snapshots:dependencies:'@types/debug': 4.1.13- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])decode-named-character-reference: 1.3.0devlop: 1.1.0micromark-core-commonmark: 2.0.3@@ -29773,7 +29685,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])module-details-from-path: 1.0.4resolve: 1.22.11transitivePeerDependencies:@@ -29781,7 +29693,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])module-details-from-path: 1.0.4transitivePeerDependencies:- supports-color@@ -29892,7 +29804,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])depd: 2.0.0is-promise: 4.0.0parseurl: 1.3.3@@ -30000,7 +29912,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])encodeurl: 2.0.0escape-html: 1.0.3etag: 1.8.1@@ -30207,7 +30119,7 @@ snapshots:dependencies:- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])ws: 8.21.0transitivePeerDependencies:- bufferutil@@ -30228,7 +30140,7 @@ snapshots:dependencies:'@socket.io/component-emitter': 3.1.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])transitivePeerDependencies:- supports-color@@ -30237,7 +30149,7 @@ snapshots:accepts: 1.3.8base64id: 2.0.0cors: 2.8.6- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])engine.io: 6.6.9socket.io-adapter: 2.5.8socket.io-parser: 4.2.6@@ -30698,7 +30610,7 @@ snapshots:dependencies:callsites: 3.1.0- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])is-observable: 2.1.0observable-fns: 0.6.1optionalDependencies:@@ -30844,7 +30756,7 @@ snapshots:cac: 6.7.14chokidar: 4.0.3consola: 3.4.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])esbuild: 0.27.7fix-dts-default-cjs-exports: 1.0.1joycon: 3.1.1@@ -30872,7 +30784,7 @@ snapshots:cac: 6.7.14chokidar: 4.0.3consola: 3.4.2- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])esbuild: 0.27.7fix-dts-default-cjs-exports: 1.0.1joycon: 3.1.1@@ -31157,7 +31069,7 @@ snapshots:[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:cac: 6.7.14- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])es-module-lexer: 1.7.0pathe: 2.0.3vite: 7.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -31178,7 +31090,7 @@ snapshots:[email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:cac: 6.7.14- debug: 4.4.3([email protected])+ debug: 4.4.3([email protected])es-module-lexer: 1.7.0pathe: 2.0.3vite: 7.3.2(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])@@ -31196,25 +31108,14 @@ snapshots:- tsx- yaml- [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):+ [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):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.5babel-plugin-macros: 3.1.0- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- transitivePeerDependencies:- - supports-color-- [email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):- 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- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])+ vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])transitivePeerDependencies:- supports-color@@ -31312,7 +31213,7 @@ snapshots:tsx: 4.21.0yaml: 2.8.3- [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:lightningcss: 1.32.0picomatch: 4.0.4@@ -31321,14 +31222,14 @@ snapshots:tinyglobby: 0.2.17optionalDependencies:'@types/node': 24.12.2- esbuild: 0.28.0+ esbuild: 0.27.7fsevents: 2.3.3jiti: 2.7.0terser: 5.48.0tsx: 4.21.0yaml: 2.8.3- [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):+ [email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]):dependencies:lightningcss: 1.32.0picomatch: 4.0.4@@ -31336,8 +31237,8 @@ snapshots:rolldown: 1.0.0-rc.17tinyglobby: 0.2.17optionalDependencies:- '@types/node': 26.1.0- esbuild: 0.27.7+ '@types/node': 24.12.2+ esbuild: 0.28.0fsevents: 2.3.3jiti: 2.7.0terser: 5.48.0@@ -31488,34 +31389,6 @@ snapshots:transitivePeerDependencies:- msw- [email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):- dependencies:- '@vitest/expect': 4.1.6- '@vitest/mocker': 4.1.6([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))- '@vitest/pretty-format': 4.1.6- '@vitest/runner': 4.1.6- '@vitest/snapshot': 4.1.6- '@vitest/spy': 4.1.6- '@vitest/utils': 4.1.6- es-module-lexer: 2.0.0- expect-type: 1.3.0- magic-string: 0.30.21- obug: 2.1.1- pathe: 2.0.3- picomatch: 4.0.4- std-env: 4.0.0- tinybench: 2.9.0- tinyexec: 1.2.4- tinyglobby: 0.2.17- tinyrainbow: 3.1.0- vite: 8.0.10(@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- why-is-node-running: 2.3.0- optionalDependencies:- '@opentelemetry/api': 1.9.0- '@types/node': 26.1.0- transitivePeerDependencies:- - msw-[email protected](@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:'@vitest/expect': 4.1.6diff --git a/services/geometry/.gitignore b/services/geometry/.gitignoredeleted file mode 100644index 20f968f344..0000000000--- a/services/geometry/.gitignore+++ /dev/null@@ -1,7 +0,0 @@-.venv/-__pycache__/-*.pyc-*.egg-info/-.pytest_cache/-build/-dist/diff --git a/services/geometry/Dockerfile b/services/geometry/Dockerfiledeleted file mode 100644index 87de9ba33b..0000000000--- a/services/geometry/Dockerfile+++ /dev/null@@ -1,32 +0,0 @@-# 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.mddeleted file mode 100644index 77f741dc33..0000000000--- a/services/geometry/README.md+++ /dev/null@@ -1,90 +0,0 @@-# 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__.pydeleted file mode 100644index 3dc1f76bc6..0000000000--- a/services/geometry/app/__init__.py+++ /dev/null@@ -1 +0,0 @@-__version__ = "0.1.0"diff --git a/services/geometry/app/auth.py b/services/geometry/app/auth.pydeleted file mode 100644index 0a6e5bfa7f..0000000000--- a/services/geometry/app/auth.py+++ /dev/null@@ -1,23 +0,0 @@-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.pydeleted file mode 100644index 2902adc1ad..0000000000--- a/services/geometry/app/config.py+++ /dev/null@@ -1,51 +0,0 @@-"""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.pydeleted file mode 100644index 2ecc628641..0000000000--- a/services/geometry/app/convert.py+++ /dev/null@@ -1,594 +0,0 @@-"""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.pydeleted file mode 100644index bd2c584fdc..0000000000--- a/services/geometry/app/errors.py+++ /dev/null@@ -1,18 +0,0 @@-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_codediff --git a/services/geometry/app/glb.py b/services/geometry/app/glb.pydeleted file mode 100644index b35d90eb01..0000000000--- a/services/geometry/app/glb.py+++ /dev/null@@ -1,180 +0,0 @@-"""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.pydeleted file mode 100644index b91bc4b013..0000000000--- a/services/geometry/app/main.py+++ /dev/null@@ -1,354 +0,0 @@-"""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 excdiff --git a/services/geometry/app/optimize.py b/services/geometry/app/optimize.pydeleted file mode 100644index 110b08ce17..0000000000--- a/services/geometry/app/optimize.py+++ /dev/null@@ -1,41 +0,0 @@-"""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 Truediff --git a/services/geometry/app/plan.py b/services/geometry/app/plan.pydeleted file mode 100644index c03e090fae..0000000000--- a/services/geometry/app/plan.py+++ /dev/null@@ -1,4103 +0,0 @@-"""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.pydeleted file mode 100644index 459b9159b8..0000000000--- a/services/geometry/app/schemas.py+++ /dev/null@@ -1,145 +0,0 @@-"""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: strdiff --git a/services/geometry/pyproject.toml b/services/geometry/pyproject.tomldeleted file mode 100644index f60227a64e..0000000000--- a/services/geometry/pyproject.toml+++ /dev/null@@ -1,31 +0,0 @@-[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.pydeleted file mode 100644index 21ba64944e..0000000000--- a/services/geometry/tests/conftest.py+++ /dev/null@@ -1,54 +0,0 @@-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/services/geometry/tests/fixtures/__init__.py b/services/geometry/tests/fixtures/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/services/geometry/tests/fixtures/make_fixtures.py b/services/geometry/tests/fixtures/make_fixtures.pydeleted file mode 100644index 703f2e24b7..0000000000--- a/services/geometry/tests/fixtures/make_fixtures.py+++ /dev/null@@ -1,133 +0,0 @@-"""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.pydeleted file mode 100644index d905a0a228..0000000000--- a/services/geometry/tests/test_api.py+++ /dev/null@@ -1,65 +0,0 @@-"""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.pydeleted file mode 100644index c6a84f0bfd..0000000000--- a/services/geometry/tests/test_convert.py+++ /dev/null@@ -1,159 +0,0 @@-"""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_idsdiff --git a/services/geometry/tests/test_endpoint.py b/services/geometry/tests/test_endpoint.pydeleted file mode 100644index 1083a991f6..0000000000--- a/services/geometry/tests/test_endpoint.py+++ /dev/null@@ -1,141 +0,0 @@-"""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 == 401diff --git a/services/geometry/tests/test_limits.py b/services/geometry/tests/test_limits.pydeleted file mode 100644index 4d9c6eb29c..0000000000--- a/services/geometry/tests/test_limits.py+++ /dev/null@@ -1,90 +0,0 @@-"""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.pydeleted file mode 100644index 1eb1ff1ae5..0000000000--- a/services/geometry/tests/test_optimize.py+++ /dev/null@@ -1,48 +0,0 @@-"""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 Falsediff --git a/services/geometry/tests/test_plan.py b/services/geometry/tests/test_plan.pydeleted file mode 100644index d5d09d7e19..0000000000--- a/services/geometry/tests/test_plan.py+++ /dev/null@@ -1,1505 +0,0 @@-"""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