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.
PMI in the STEP viewer — implementation plan
Spec: .ai/specs/2026-10-26-step-pmi-viewer.md
Research: .ai/research/step-pmi-viewer.md
Closest sibling: the optimize thumbnail (a second ingest output of model-optimize)
Branch: tokyo
Progress
- Task 1: Add
read_pmiand the AP242 fixture writer toocct-bridge - Task 2: Build
pmi.jsoninconverter, with tests - Task 3: Write the
pmioutput from theoptimizeaction - Task 4: Add
modelUpload.pmiPath - Task 5: Request, persist and back up
pmiPathin@carbon/jobs - Task 6: Return
pmiPathfrom the artifacts routes - Task 7: Add the
pmi.tscontract and formatter to@carbon/viewer, with tests - Task 8: Draw the PMI layer and the PMI panel
- Task 9: Pass
pmiUrlfrom the ERP and MES hosts - Task 10: Verify end to end
Deviations during the build
CODE_VERSIONstays at 4. Onlyplanreads the result-pointer cache, so a bump would only throw away cached results.- The
pmi.jsonpath is unique per run, after the self-review found a race between two runs of one model. - Task 4 ran against a throwaway database restored from a sibling worktree's schema (same 1,238 migrations), because the shared Redis pool was full and
crbncould not start this worktree's stack. - Task 2 step 15 changed: OCCT reads none of NIST STC 06's 12 views (it stops at the first camera with no draughting model). The test asserts STC 06's PMI only; CTC 01 (1 view) and CTC 05 (2 views) carry the view tests.
- Task 10 ran the browser check on a throwaway Vite page that mounts the real
ModelPreview, for the same reason.
Dependencies
- Task 2 needs Task 1. Task 3 needs Task 2.
- Task 5 needs Task 4. Task 6 needs Task 4.
- Task 8 needs Task 7. Task 9 needs Tasks 6 and 8.
- Tasks 1–3 (Rust) and Tasks 4–8 (TypeScript) are independent of each other.
Build environment
The host has no Rust toolchain and no OCCT. Run every cargo command in the dev container:
docker run --rm -v "$PWD":/repo -v carbon-target:/target -v carbon-cargo:/usr/local/cargo/registry \
-v "$PWD/.context/pmi-fixtures":/fixtures carbon-rust-dev <cargo command>
The image carbon-rust-dev is built from .context/dev/Dockerfile (OCCT carbon-occt:8.0.0-p1, FCL, Draco, Rust 1.99). NIST fixtures are in .context/pmi-fixtures/ (not committed).
Task 1: Add read_pmi and the AP242 fixture writer to occt-bridge
Depends on: none Files:
- Modify:
crates/occt-bridge/src/lib.rs— new shared structs and two functions in the cxx bridge - Modify:
crates/occt-bridge/src/occt.h— declarations - Create:
crates/occt-bridge/src/pmi.cc— the PMI walk - Modify:
crates/occt-bridge/build.rs— compilepmi.cc - Copy from (precedent):
read_xbf,doc_to_tree,write_test_stepincrates/occt-bridge/src/occt.cc;XDEDRAW_GDTs.cxxin.context/occt-srcfor the getters
Steps:
- Add these shared structs to the bridge:
PmiTree { ok, error, items: Vec<PmiRaw>, faces: Vec<PmiMesh>, edges: Vec<PmiPolyline>, views: Vec<PmiViewRaw> }. PmiRawholds:kind(0 dimension, 1 tolerance, 2 datum, 3 note),type_name,name, the number fields, the string-list fields,lines: Vec<PmiPolyline>,mesh: PmiMesh, plane and text point (withhas_*flags),faces: Vec<u32>,edges: Vec<u32>,datum_refs: Vec<String>,datum_ref_modifiers: Vec<String>.PmiViewRawholdsname,direction[3],up[3],projection(0 none, 1 parallel, 2 central),items: Vec<u32>.- Declare
fn read_pmi(path: &str, angular_deflection: f64) -> PmiTree;andfn write_test_pmi_step(path: &str) -> bool;. - In
read_pmi, open the file as.xbfwhen it starts withBINFILE, else as STEP with the same reader setup asread_step_to_doc. - If
DimTolToolhas no dimension, tolerance or datum labels andViewToolhas no view labels, returnok=truewith empty lists. - Walk the free shapes and their components once. Record the first world
TopLoc_Locationof every product label. - For each GD&T label, read the object once with
GetObject(). Read the referenced shapes withGetRefShapeLabel. - Find the owner part:
refL.Father()whenIsSubShape(refL), elserefL. Use the owner's first world location; identity when unknown. - Discretize presentation edges with
BRepAdaptor_CurveandGCPnts_TangentialDeflection. Read presentation faces withBRep_Tool::Triangulation. - Mesh each referenced face once with
BRepMesh_IncrementalMesh, then read its triangulation. Store it once infacesand index it. - Discretize each referenced edge into
edges, once per edge. - Transform every point, normal and direction by the owner location.
- Map every OCCT enum to a stable lower camel case string in a
switch(for exampleLocation_LinearDistance→linearDistance). - Store the dimension's lower tolerance as a negative number.
- For tolerances, read datum references with
GetDatumWithObjectOfTolerLabels, in datumGetPositionorder. - For views, read
XCAFView_ObjectViewDirection,UpDirectionandType, and mapGetRefGDTLabelto item indices. - Wrap the walk in
try { } catch (Standard_Failure&) { }. On a throw, returnok=falsewith the message. - In
write_test_pmi_step, build a 100×50×20 mm box in a new XCAF document. - Add one linear distance dimension (two opposite faces, 100 mm, +0.1 / −0.05), with a presentation of two edges.
- Add one flatness tolerance (value 0.05) on the top face, referencing datum A.
- Add datum A on the bottom face.
- Write the document with
STEPCAFControl_Writerandwrite.step.schema5 (AP242).
Verify:
docker run --rm -v "$PWD":/repo -v carbon-target:/target -v carbon-cargo:/usr/local/cargo/registry carbon-rust-dev cargo build -p occt-bridge --release
# Expected: "Finished `release` profile"
If the OCCT writer does not write the semantic GD&T, STOP and report — do not improvise.
Out of scope: read_step, read_xbf, tessellate, Builder — their output must not change.
Task 2: Build pmi.json in converter, with tests
Depends on: Task 1 Files:
- Create:
crates/converter/src/pmi.rs - Modify:
crates/converter/src/lib.rs—pub mod pmi; - Create:
crates/converter/tests/pmi.rs - Copy from (precedent):
crates/converter/src/graph.rs(serde emit),crates/converter/tests/multibody_split.rs(hermetic fixture test)
Steps:
- Define the serde types of
pmi.jsonversion 1 inpmi.rs, exactly as the spec'sPmiDocument. Use#[serde(rename_all = "camelCase")]. - Add
pub fn extract_pmi(path: &str, source_unit: Option<&str>) -> Result<Option<PmiDocument>, String>. - Return
Ok(None)when the tree has no items and no views. - Give ids in document order per kind:
d1…,t1…,a1…,n1…. - Merge datums with the same name. Keep the first copy with lines or a mesh. Point every view at the kept id.
- Round every coordinate to 4 decimals (0.1 µm).
- Add
pub fn to_json(doc: &PmiDocument) -> Result<Vec<u8>, String>with the 16 MB cap. - If the JSON is over the cap, empty
facesand retry once. If it is still over, return an error. - In
tests/pmi.rs, write the fixture withwrite_test_pmi_step. Assert 1 dimension, 1 tolerance and 1 datum. - Assert the dimension's values (100, 0.1, −0.05) and that it references 2 faces with triangles.
- Assert that the tolerance lists datum
A. - Write the fixture to
.xbfwithstep_to_xbf. Assert thatextract_pmion the.xbfgives the same JSON. - Add
nist_fixturestests that skip unlessPMI_FIXTURESis set. - For CTC 01: assert at least 20 items, each with lines or a mesh.
- For STC 06: assert 12 views.
- For CTC 01: assert that the PMI bounding box overlaps the bounding box of
convert_step_head(...).graph's root.
Verify:
docker run --rm -v "$PWD":/repo -v carbon-target:/target -v carbon-cargo:/usr/local/cargo/registry -v "$PWD/.context/pmi-fixtures":/fixtures -e PMI_FIXTURES=/fixtures carbon-rust-dev cargo test -p converter --release
# Expected: every test result "ok", including the pmi tests
If the NIST counts differ from the spec, update the spec's acceptance criteria with the real counts. Explain why in the run record.
Out of scope: graph.rs, glb.rs, nodeid.rs.
Task 3: Write the pmi output from the optimize action
Depends on: Task 2 Files:
- Modify:
apps/assembler/src/actions/optimize.rs—PmiOut,run_ingest,spawn - Modify:
apps/assembler/src/request.rs— parsepmi: { path }inoptimize_ingest - Modify:
apps/assembler/AGENTS.md— document thepmioutput - Copy from (precedent):
ThumbnailOutand thethumbnailoutput inoptimize.rs
Steps:
- Add
pub pmi: Option<Option<String>>toOptimizeReq(outerSome= asked for, inner = path). - In
run_ingest, after a successful optimize, callconverter::pmi::extract_pmioningest.load_path. - Pass the source unit from
converter::graph::detect_source_unit_byteswhen the source is STEP. - If the call fails, push
pmi: <message>intooutcome.warnings. Never fail the job. - If a document exists, add output
pmi(application/json) andresult.outputs.pmi = { path, bytes, items, views }.
Verify:
docker run --rm -v "$PWD":/repo -v carbon-target:/target -v carbon-cargo:/usr/local/cargo/registry carbon-rust-dev cargo test -p assembler --release
# Expected: every test result "ok"
Out of scope: the convert, plan, compact and thumbnail actions.
Task 4: Add modelUpload.pmiPath
Depends on: none Files:
- Create:
packages/database/supabase/migrations/<timestamp>_model-pmi-artifact.sql(viapnpm db:migrate:new model-pmi-artifact) - Modify (generated):
packages/database/src/types.ts,packages/database/src/swagger-docs-schema.ts - Copy from (precedent):
packages/database/supabase/migrations/20260714120000_model-optimize-artifact.sql
Steps:
- Run
pnpm db:migrate:new model-pmi-artifact. - Write the SQL: a comment and
ALTER TABLE "modelUpload" ADD COLUMN IF NOT EXISTS "pmiPath" TEXT;. - Run
pnpm db:migrate. - Run
pnpm run generate:types.
Verify:
grep -c '"pmiPath"' packages/database/src/types.ts
# Expected: 3 or more (Row, Insert, Update)
If the local database is down, add the column to types.ts by hand in Row, Insert and Update, in the same place as optimizedModelPath. Record that in the run record.
Out of scope: RLS (the table keeps its policies).
Task 5: Request, persist and back up pmiPath in @carbon/jobs
Depends on: Task 4 Files:
- Modify:
packages/jobs/src/inngest/functions/tasks/model-optimize.ts - Modify:
packages/jobs/src/inngest/functions/tasks/model-rows.ts—pmiPathin the row type and the select - Modify:
packages/jobs/src/inngest/functions/tasks/company-backup.ts—STORAGE_PATH_COLUMNS - Modify:
packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts—MODEL_UPLOAD_PATH_COLUMNS - Copy from (precedent): the
thumbnailpath, mint and persist inmodel-optimize.ts
Steps:
- Set
pmiPath = ${companyId}/models/${modelUploadId}/pmi-${run}.json(unique per run, like the thumbnail). - Send
pmi: { path: pmiPath }in the body. - Sign a
pmiupload URL in the company bucket. - Add
pmi?: { bytes?: number }toIngestOutputs. - In
persist, setpmiPath: outputs.pmi ? pmiPath : null. - If the row held a different
pmiPath, remove that object (best effort, log a warning on failure). - Add
"pmiPath"toSTORAGE_PATH_COLUMNSand toMODEL_UPLOAD_PATH_COLUMNS.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/jobs && pnpm --filter @carbon/jobs test -- company-backup.closure
# Expected: typecheck passes; the closure tests pass
Out of scope: assembly-convert.ts, model-compact.ts.
Task 6: Return pmiPath from the artifacts routes
Depends on: Task 4 Files:
- Modify:
apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts - Modify:
apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts - Modify:
packages/viewer/src/useOptimizedModel.ts—pmiPath?: string | nullinModelArtifacts
Steps:
- Add
pmiPathto theselectin both routes. - Return
pmiPath: model.data?.pmiPath ?? null. - Add the optional
pmiPathfield toModelArtifactswith a doc comment.
Verify:
pnpm exec turbo run typecheck --filter=erp --filter=mes
# Expected: both pass
Task 7: Add the pmi.ts contract and formatter to @carbon/viewer, with tests
Depends on: none Files:
- Create:
packages/viewer/src/pmi.ts - Create:
packages/viewer/src/pmi.test.ts - Copy from (precedent):
packages/viewer/src/graph.tsandgraph.test.ts
Steps:
- Export the TypeScript types of the spec's
PmiDocument. They must matchcrates/converter/src/pmi.rsfield for field. - Export
parsePmiDocument(json: unknown): PmiDocument | null. It returns null for a wrongversionor a wrong shape. - Export
formatPmiItem(item, unit: "mm" | "in", sourceUnit): { label: string; symbol: string | null; title: string }. - Format dimensions: prefix (⌀, R, S⌀, SR), the nominal, then
±t,+u/−l, limitsu/l, or the fit class. - Format angles in degrees with
°, never converted. - Format tolerances as a frame: the characteristic symbol, the zone (
⌀for a diameter zone), Ⓜ/Ⓛ, then the datum letters. - Use the file's decimals only when the display unit is the source unit. Else use 3 decimals for mm and 4 for in, trimming zeros.
- Export
groupPmiItems(doc)(Dimensions, Tolerances, Datums, Notes) andvisibleItemIds(doc, viewId | null). - Write tests: parse a good and a bad document, and each format rule above, in mm and in.
Verify:
pnpm --filter @carbon/viewer test -- pmi
# Expected: all pmi tests pass
Task 8: Draw the PMI layer and the PMI panel
Depends on: Task 7 Files:
- Create:
packages/viewer/src/PmiLayer.tsx - Modify:
packages/viewer/src/ModelCanvas.tsx—pmi,pmiStateprops; renderPmiLayerinModelScene; camera focus - Modify:
packages/viewer/src/ModelPreview.tsx—pmiUrlprop, load, shared unit state,PmiPanel - Copy from (precedent):
ModelMetricsPanel,UnitToggleandRowinModelPreview.tsx;frameBoxinModelCanvas.tsx
Steps:
- In
PmiLayer, merge each item'slinesinto oneLineSegmentsper item. - Draw a mesh for each item's
mesh. - Color unselected items with the theme foreground. Color the selected item blue (
0x3b82f6), withdepthTest: falseand a highrenderOrder. - Draw the selected item's faces as a blue transparent mesh with
polygonOffset. - Draw the selected item's edges as blue lines.
- For items with no lines and no mesh, draw a drei
Htmllabel attextPosition, else at the center of its faces. Cap the labels at 200. - In
ModelCanvas, add afocusrequest. For an item, look along the plane normal and fit the item's and its faces' box. - For a view, use the view's
directionandup, then fit the view's items' box. - Reuse
frameBoxwith a given direction and up vector. - In
ModelPreview, fetchpmiUrlonce (fetch+parsePmiDocumentin auseEffect). - Lift the unit state out of
ModelMetricsPanel. Start it at the PMIsourceUnitwhen it ismmorin, elseimperial. - Add
PmiPanelunder the Measurements panel. It holds the eye toggle, a view select (when views exist) and the grouped list. - Make a click on an item select it, and a second click clear it.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/viewer && pnpm --filter @carbon/viewer test
# Expected: typecheck passes; all viewer tests pass
Out of scope: AssemblyPlayer.tsx, RawModelCanvas.
Task 9: Pass pmiUrl from the ERP and MES hosts
Depends on: Tasks 6 and 8 Files:
- Modify:
apps/erp/app/components/CadModel.tsx - Modify:
apps/mes/app/components/JobOperation/JobOperation.tsx - Modify:
apps/mes/app/components/AssemblyView.tsx— only whereModelPreviewgetsoptimizedUrlfromartifacts - Copy from (precedent): the
optimizedUrlprop inCadModel.tsx(with the?v=cache-buster)
Steps:
- Pass
pmiUrl={artifacts?.pmiPath ? getPrivateUrl(artifacts.pmiPath) : null}. The path is unique per run, so it needs no cache-buster. - Do the same in each MES host that reads
artifacts.
Verify:
pnpm exec turbo run typecheck --filter=erp --filter=mes && pnpm exec biome check packages/viewer apps/erp/app/components/CadModel.tsx apps/mes/app/components
# Expected: both typechecks pass; Biome reports no errors
Task 10: Verify end to end
Depends on: Tasks 1–9 Steps:
- Run all Rust tests (Task 2 command, plus
cargo test -p assembler). - Run
pnpm --filter @carbon/viewer testand the scoped typechecks. - If a local stack with the assembler runs, upload
nist_ctc_01_asme1_ap242-e1.stpto a part. - Open the PMI panel. Pick a position tolerance. Take a screenshot to
.context/. - If no stack with the assembler runs, record "browser test skipped" and the reason in the run record.
Verify:
# Expected: every command above passes; the screenshot shows the PMI panel and a highlighted face