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.
SolidWorks PDM Integration — implementation plan
Spec: .ai/specs/2026-08-04-solidworks-pdm-integration.md Research: .ai/research/solidworks-pdm-integration.md Branch: solidworks-pdm-integration-spec
Read the spec first. The whole build is precedent-driven: almost every task clones an Onshape file and applies enumerated deltas. Where a task rests on an assumption about the PDM Web API, an escape hatch says so — STOP and report rather than improvising, because no live vault is available for verification.
Progress
- Task 1: Seed the
solidworks-pdmintegration catalog row (migration) - Task 2: Build
SolidWorksPdmClient+ factory in@carbon/ee - Task 3: Add the normalized BOM row validator (
lib/data.ts) - Task 4: Register the integration (config, registry, server hooks)
- Task 5: Add path helpers
- Task 6: Picker API routes (files / configurations / bom)
- Task 7: Add
type: "solidworks-pdm"to thesyncedge function - Task 8: Manual BOM sync route (POST)
- Task 9:
SolidWorksPdmSyncUI + BoMExplorer mount + status icon - Task 10: Event + trigger wiring for release sync
- Task 11: Matching/normalization helpers + unit tests
- Task 12: Attach helper (documents, models, thumbnails)
- Task 13:
solidworks-pdm-file-syncInngest job - Task 14:
solidworks-pdm-release-polljob + cron fan-out - Task 15: Backfill API route
- Task 16: Webhook receiver route
- Task 17: Docs page (conditional on existing Onshape docs)
- Task 18: Fixture playbook + browser verification
Dependencies
- Task 1 is independent (run first; everything else can proceed without it locally, but the settings UI needs the row to activate).
- Tasks 2–3 are independent of each other; Task 4 needs Task 2. Task 5 is independent.
- Tasks 6, 8 need Tasks 2, 5. Task 7 is independent (edge function only). Task 8 also needs Task 7.
- Task 9 needs Tasks 5, 6, 8.
- Task 10 is independent. Tasks 11–12 need Task 2. Task 13 needs Tasks 10–12. Task 14 needs Tasks 10, 13. Tasks 15–16 need Tasks 10, 14 (they trigger the poll event).
- Tasks 6, 7, 10, 11 can run as parallel subagents once Task 2 lands.
- Tasks 17–18 last.
Task 1: Seed the solidworks-pdm integration catalog row (migration)
Depends on: none Files:
- Create:
packages/database/supabase/migrations/{timestamp}_solidworks-pdm-integration.sql(via the command below — never hand-pick the timestamp) - Copy from (precedent):
packages/database/supabase/migrations/20250410120243_onshape-integration.sqlandpackages/database/supabase/migrations/20260703165330_onshape-asset-sync-jsonschema.sql
Steps:
- Run
pnpm db:migrate:new solidworks-pdm-integration. - Fill the generated file with exactly (the
integrationtable has onlyid+jsonschemasince20241006185904_integration-refactor.sql):
INSERT INTO "integration" ("id", "jsonschema")
VALUES (
'solidworks-pdm',
'{
"type": "object",
"properties": {
"baseUrl": { "type": "string" },
"vaultName": { "type": "string" },
"username": { "type": "string" },
"password": { "type": "string" },
"releasedStateName": { "type": "string" },
"partNumberVariable": { "type": "string" },
"revisionVariable": { "type": "string" },
"assetSyncEnabled": { "type": "boolean" },
"webApiVersion": { "type": "string" },
"searchCapability": { "type": "string", "enum": ["state-search", "folder-sweep"] },
"lastReleaseSyncAt": { "type": "string" }
},
"required": ["baseUrl", "vaultName", "username", "password"]
}'::json
)
ON CONFLICT ("id") DO UPDATE SET "jsonschema" = EXCLUDED."jsonschema";
- Run
pnpm db:migrateto apply it to the local stack. - Run
pnpm run generate:types.
Verify:
pnpm db:migrate
# Expected: output lists {timestamp}_solidworks-pdm-integration.sql as applied, no errors
psql postgresql://postgres:postgres@localhost:54322/postgres -c "select id from integration where id='solidworks-pdm';"
# Expected: one row: solidworks-pdm
# (If the local DB is not on 54322, find the port with `docker ps` — do NOT rebuild the DB.)
git status --porcelain packages/database/src
# Expected: empty or whitespace-only — a seed row changes no generated types
Out of scope: any new table, any change to companyIntegration, externalIntegrationMapping, or the verify_integration trigger.
Task 2: Build SolidWorksPdmClient + factory in @carbon/ee
Depends on: none Files:
- Create:
packages/ee/src/solidworks-pdm/lib/client.ts - Modify:
packages/ee/package.json— add a./solidworks-pdmsubpath export ONLY IF the existing exports map lists./onshapeexplicitly (mirror that entry); if exports are wildcarded, no change - Copy from (precedent):
packages/ee/src/onshape/lib/client.ts(axios client class + error types +getOnshapeClientfactory at line ~591)
Steps:
- Read the entire Onshape client first. Clone its structure: an axios instance, typed methods,
OnshapeApiError-style error classes, a size-capped streaming download, and a factory that loadscompanyIntegrationand returns{ client, error }without throwing. - Implement
SolidWorksPdmClientwith constructor{ baseUrl, vaultName, username, password }. All URLs are${baseUrl}/api/...with the vault name in the path. Auth model (differs from Onshape): no token is passed in — the client lazily callsPOST /api/{vaultName}/authenticatewith{ Username, Password }, storesJwtStringin memory, sendsAuthorization: Bearer <jwt>on every call, and on a 401 response re-authenticates once and retries the request once (then surfaces the error). - Methods (paths from the research file §7; response types as minimal TS interfaces — define only fields we consume):
getWebApiVersion(): GET /api/version/webapigetVaultInfo(): GET /api/{v}/infosearch(criteria): POST /api/{v}/search— returns[{ Id, Type }](Type: 0=Folder, 1=File)getFilesInfo(fileIds): POST /api/{v}/files/info(bulk)getFileConfigurations(fileId, version): GET /api/{v}/files/{fileId}/{version}/configurationsgetActiveConfig(fileId, version): GET /api/{v}/files/{fileId}/{version}/ActiveConfig— returns the active configuration id/namegetFileVariables(fileId, version): GET /api/{v}/files/{fileId}/{version}/variables— returnsConfigInfo[]({ ConfigurationName, ConfigurationId, Models: [{ VarName, VarValue }] })getBomInfo(fileId): GET /api/{v}/files/{fileId}/bominfogetComputedBom(bomTypeId, fileId, version, folderId, configId): GET /api/{v}/bom/{bomTypeId}/{fileId}/{version}/{folderId}/computed?configId=&latest=truebrowseFolder(folderId): GET /api/{v}/folders/{folderId}/browsegetThumbnail(fileId, version, folderId, { maxBytes })—GET /api/{v}/files/{fileId}/{version}/thumbnails?folderId=; the API replies with a redirectLocation; follow it and return bytes + content type, enforcing the samemaxBytescap asdownloadFileToTempwhile reading (abort and throwSolidWorksPdmAssetTooLargeErroronce the cap is exceeded — the thumbnail is buffered in memory, so an uncapped response is a memory hazard)downloadFileToTemp(fileId, version, folderId, { maxBytes })—GET /api/{v}/files/{fileId}/{version}/download, streamed to a temp file with the same byte-cap behavior as Onshape'sdownloadExternalDataToFile(throwSolidWorksPdmAssetTooLargeErrorpast the cap)registerWebhook(url, events)/getWebhooks()/deleteWebhook(id)—POST|GET /api/{v}/configuration/hooks/url(2025+; callers treat failures as non-fatal)
- Error classes:
SolidWorksPdmApiError(status + message + url) andSolidWorksPdmAssetTooLargeError, mirroring the Onshape pair. - Factory
getSolidWorksPdmClient(client: SupabaseClient<Database>, companyId: string): readcompanyIntegrationrowid = "solidworks-pdm", requireactive, requiremetadata.baseUrl/vaultName/username/password(flat keys), return{ client, error: null }or{ client: null, error: string }. No token persistence back to the DB (unlike Onshape's refresh flow — PDM JWTs are re-fetched, not refreshed).
Verify:
pnpm exec turbo run typecheck --filter=@carbon/ee
# Expected: exit 0, no new errors
Out of scope: retries beyond the single 401 re-auth (Inngest owns retry policy); any write endpoint (check-in, state change, datacard save); caching tokens in Redis or the DB.
Task 3: Add the normalized BOM row validator (lib/data.ts)
Depends on: none Files:
- Create:
packages/ee/src/solidworks-pdm/lib/data.ts - Copy from (precedent):
packages/ee/src/onshape/lib/data.ts(onShapeDataValidator)
Steps:
- Read the Onshape validator to match its style and the field set the
syncedge function consumes. - Export
solidWorksPdmDataValidator— a zod schema for one normalized BOM row:{ partNumber: string, description: string optional default "", revision: string optional default "", quantity: number, unitOfMeasure: string optional, level: number, fileId: string, configId: string optional, folderId: string optional }— plustype SolidWorksPdmBomRow = z.infer<...>. Match the Onshape validator's conventions for optionality/coercion exactly where fields overlap (partNumber, description, quantity).
Verify:
pnpm exec turbo run typecheck --filter=@carbon/ee
# Expected: exit 0
Out of scope: parsing raw PDM API responses here (that normalization lives in the Task 6 BOM loader).
Task 4: Register the integration (config, registry, server hooks)
Depends on: Task 2 Files:
- Create:
packages/ee/src/solidworks-pdm/config.tsx - Create:
packages/ee/src/solidworks-pdm/hooks.server.ts - Modify:
packages/ee/src/index.ts— addSolidWorksPdmto theintegrationsarray + barrel exports - Modify:
packages/ee/src/hooks.server.ts— add thesolidworks-pdmentry to theserverHooksmap - Copy from (precedent):
packages/ee/src/onshape/config.tsx,packages/ee/src/onshape/hooks.server.ts
Steps:
config.tsx:defineIntegrationwithid: "solidworks-pdm",name: "SolidWorks PDM",category: "CAD"(same literal as Onshape's),active: true(no env-var gate — credentials are per-company), an inline SVGLogocomponent (simple "PDM" wordmark in currentColor; do not fetch brand assets),descriptionstating: PDM Professional only, requires the customer's PDM Web API server reachable over HTTPS, and one dedicated vault service account.images: [].settings(withsettingGroupsConnectionandRelease sync— copy the group mechanics from any integration usinggroup, e.g. grepsettingGroupsinpackages/ee/src):baseUrl(text, required),vaultName(text, required),username(text, required),password(password, required),releasedStateName(text, default"Released"),partNumberVariable(text, default"Number"),revisionVariable(text, default"Revision"),assetSyncEnabled(switch, default false).schema: zod object with all eight fields;baseUrlmust parse as URL and behttps:unless hostname islocalhost/127.0.0.1;assetSyncEnableduses the samez.preprocessstring→boolean trick as Onshape's schema. Also.passthrough()so system-written keys (webApiVersion,searchCapability,lastReleaseSyncAt) survive validation — check how the settings action atapps/erp/app/routes/x+/settings+/integrations.$id.tsxmerges metadata before deciding whether passthrough is needed, and mirror whichever integration already preserves extra keys (Onshape'sonshapeCompanyIdproves the merge path exists).actions:[{ id: "backfill", label: "Backfill released assets", description: <one sentence>, endpoint: "/api/integrations/solidworks-pdm/backfill", enabledWhenSetting: "assetSyncEnabled" }].- No
oauth, noonClientInstall. solidworks-pdm/hooks.server.ts: exportsolidWorksPdmOnInstall(authenticate +getVaultInfo; on failure return/throw the same error shape Onshape's install path surfaces viaintegration-errors.ts; on success writemetadata.webApiVersionviaupsertCompanyIntegration-style update, then ifassetSyncEnabledand version ≥ 2025 best-effortregisterWebhookfor the post-ChangeState event pointing at${origin}/api/webhook/solidworks-pdm/${companyId}— wrap in try/catch, log, continue),solidWorksPdmOnUninstall(best-effortdeleteWebhook),solidWorksPdmOnHealthcheck(authenticate + vault info; return the exact healthcheck result shape used by Onshape'sonHealthcheck— read it inpackages/ee/src/onshape/hooks.server.tsfirst).- Wire all three into the
serverHooksmap inpackages/ee/src/hooks.server.ts; addexport { Logo as SolidWorksPdmLogo, SolidWorksPdm } from "./solidworks-pdm/config"topackages/ee/src/index.tsand appendSolidWorksPdmto theintegrationsarray.
If the settings action's metadata merge turns out to REPLACE rather than merge (contradicting the Onshape playbook's step 3), STOP and report — do not improvise a merge in the config.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/ee --filter=erp
# Expected: exit 0 for both
Out of scope: the backfill/webhook routes themselves (Tasks 15–16); translations of setting labels (the check-and-commit gate's /translate pass handles .po fill).
Task 5: Add path helpers
Depends on: none Files:
- Modify:
apps/erp/app/utils/path.ts— add API path helpers - Copy from (precedent): the
onShapeDocuments/onShapeVersions/onShapeElements/onShapeBom/onShapeSyncentries in the same file
Steps:
- Next to the Onshape entries, add:
solidWorksPdmFiles→/api/integrations/solidworks-pdm/files,solidWorksPdmConfigurations(fileId)→/api/integrations/solidworks-pdm/files/${fileId}/configurations,solidWorksPdmBom(fileId)→/api/integrations/solidworks-pdm/files/${fileId}/bom,solidWorksPdmSync→/api/integrations/solidworks-pdm/sync,solidWorksPdmBackfill→/api/integrations/solidworks-pdm/backfill. Match the exact naming/casing style of the neighboring Onshape helpers.
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
Out of scope: none.
Task 6: Picker API routes (files / configurations / bom)
Depends on: Tasks 2, 5 Files:
- Create:
apps/erp/app/routes/api+/integrations.solidworks-pdm.files.ts - Create:
apps/erp/app/routes/api+/integrations.solidworks-pdm.files.$fileId.configurations.ts - Create:
apps/erp/app/routes/api+/integrations.solidworks-pdm.files.$fileId.bom.ts - Copy from (precedent):
apps/erp/app/routes/api+/integrations.onshape.documents.ts(list loader shape +requirePermissionsscope — copy the scope verbatim),...d.$did.v.$vid.elements.ts(param loader),...d.$did.v.$vid.e.$eid.bom.ts(BOM loader)
Steps:
files.ts(GET loader):requirePermissionswith the same scope asintegrations.onshape.documents.ts; read?q=search text;getSolidWorksPdmClient; callsearchwith a filename criteria built fromq. Search returns only[{ Id, Type }]— so take at most the first 200 file-type ids, hydrate them via one bulkgetFilesInfocall, filter to extensions.sldasm/.sldprt(case-insensitive), and return at most 50 results as{ files: [{ id, name, folderId, version }] }. Return plain objects (neverResponse.json). Emptyq→ return{ files: [] }without calling the API.configurations.ts(GET loader): same scope; paramsfileId, queryversionandfolderId(pass through from the file pick); callgetFileConfigurations; return{ configurations: [{ id, name }] }.bom.ts(GET loader): same scope; paramsfileId, queryversion,folderId,configId; callgetBomInfothengetComputedBomwithlatest=true; normalize here: read the integration metadata'spartNumberVariable/revisionVariable, locate the matching entries in the BOMColumns[]by name (case-insensitive), and flatten the recursive row tree intoSolidWorksPdmBomRow[](Task 3 type) withlevel= tree depth andquantityfrom the BOM quantity column. The normalizer is strict — it throws rather than degrading (a later validator cannot repair a wrong column pick or a mis-flattened tree): zero OR more than one column matchingpartNumberVariable→ throw naming the columns found; configured revision column missing → throw; any quantity that is not a finite number ≥ 0 → throw with the row's part number; any child row whose depth is not parent depth + 1 → throw. The loader catches and returns the message as a form-level error so the picker shows it and Sync is never enabled with malformed rows. Return{ rows }.
Escape hatch: the exact JSON field names of the computed-BOM response (Columns, row tree nesting) are documented only loosely (research §7). Write the normalizer as a small pure function normalizeComputedBom(raw, { partNumberVariable, revisionVariable }) exported from the route file's sibling packages/ee/src/solidworks-pdm/lib/bom.ts so Task 11 can unit-test it against a hand-written fixture; if the real response shape can't be inferred from the research file, STOP and report rather than guessing silently — the fixture then documents the assumed shape for live-vault validation.
Verify:
pnpm exec turbo run typecheck --filter=erp --filter=@carbon/ee
# Expected: exit 0
Out of scope: UI; writing mappings; folder browsing UI (search-only picker in v1).
Task 7: Add type: "solidworks-pdm" to the sync edge function
Depends on: none Files:
- Modify:
packages/database/supabase/functions/sync/index.ts— new discriminated-union variant + handler - Copy from (precedent): the existing
type: "onshape"variant in the same file (union at line ~25, handler below)
Steps:
- Before editing, record the baseline own-file error count:
cd packages/database/supabase/functions && deno check sync/index.ts 2>&1 | grep -c "sync/index.ts"(lesson: this tree is not deno-check-clean; gate on the delta). - Read the whole
onshapehandler. Add az.object({ type: z.literal("solidworks-pdm"), companyId, userId, itemId, rows: <inline zod matching SolidWorksPdmBomRow — duplicate the shape here; Deno functions must not import from packages/ee>, source: z.object({ fileId, configId: optional, folderId: optional }) })variant topayloadValidator. - Implement the handler by extracting/reusing the Onshape handler's tree-building core (items/parts/make-method creation from leveled rows). The normalized rows already carry
partNumber/description/revision/quantity/level, so the handler maps them into the same internal structure the Onshape BOM rows produce. WriteexternalIntegrationMappingrows: integration"solidworks-pdm"on the root item with metadata{ fileId, configId, folderId }, and"solidworksPdmData"per created/updated item with the raw row as metadata — mirroring how the Onshape handler writes"onshape"/"onshapeData"(find those exact writes in the file and copy their column usage, includingcompanyIdand audit fields). - If the Onshape tree-building core is too entangled with Onshape-specific row fields to reuse without behavior risk, duplicate it into a clearly-named function for the new variant instead of refactoring the shared path — preserving Onshape behavior outranks DRY here.
Verify:
cd packages/database/supabase/functions && deno check sync/index.ts 2>&1 | grep -c "sync/index.ts"
# Expected: count <= the baseline recorded in step 1 (no new own-file errors)
Out of scope: changes to the onshape variant's behavior; config.toml (the sync function is already registered).
Task 8: Manual BOM sync route (POST)
Depends on: Tasks 5, 7 Files:
- Create:
apps/erp/app/routes/api+/integrations.solidworks-pdm.sync.ts - Copy from (precedent):
apps/erp/app/routes/api+/integrations.onshape.sync.ts(copy itsrequirePermissionsscope, its edge-function invocation viaclient.functions.invoke("sync", ...), and its mapping upsert verbatim, adjusting names)
Steps:
- Clone the Onshape sync action: validate the posted body (
itemId,rowspersolidWorksPdmDataValidator,source: { fileId, configId?, folderId? }), invoke thesyncedge function withtype: "solidworks-pdm", and upsert the rootexternalIntegrationMappingrow exactly the way the Onshape route does (same table columns,lastSyncedAtupdate included).
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
Out of scope: none.
Task 9: SolidWorksPdmSync UI + BoMExplorer mount + status icon
Depends on: Tasks 5, 6, 8 Files:
- Create:
apps/erp/app/components/SolidWorksPdmSync.tsx - Modify:
apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx— mount besideOnshapeSync(line ~160) - Modify:
apps/erp/app/components/Icons.tsx— addSolidWorksPdmStatus - Copy from (precedent):
apps/erp/app/components/OnshapeSync.tsx(the whole component: fetchers, comboboxes, BOM preview tree, Sync/Save buttons, saved-selection +lastSyncedAtread fromexternalIntegrationMapping);OnshapeStatusinIcons.tsx
Steps:
- Clone
OnshapeSync.tsx→SolidWorksPdmSync.tsxwith these deltas: the three-level Document→Version→Element pickers become two levels — a debounced file search input + results combobox (GETpath.to.api.solidWorksPdmFiles?q=) and a configuration combobox (GET...solidWorksPdmConfigurations(fileId)?version=&folderId=); "Fetch" loads the normalized BOM (GET...solidWorksPdmBom(fileId)?...&configId=); the preview tree renderspartNumber/description/quantity/revisionbylevel; "Sync" POSTs topath.to.api.solidWorksPdmSync. Keep the saved-mapping read/write behavior (integration id"solidworks-pdm"). - In
BoMExplorer.tsx, find how theOnshapeSyncmount is gated on the Onshape integration being active, and add the equivalentSolidWorksPdmSyncmount gated onsolidworks-pdm— both may render if both integrations are active. SolidWorksPdmStatusinIcons.tsx: cloneOnshapeStatus. Field sources (these are the only producers that persist them):stateNamefrom the"solidworks-pdm-release-model"/"-drawing"mapping metadata (written by Task 13 step 5),revisionfrom thesolidworksPdmDatamapping metadata. No release mapping yet → render revision only. A plain text badge is sufficient (no state-color mapping in v1).
Verify:
pnpm exec turbo run typecheck --filter=erp && pnpm run lint
# Expected: both exit 0
Out of scope: MES; any redesign of the BOM explorer; per-configuration multi-item sync.
Task 10: Event + trigger wiring for release sync
Depends on: none Files:
- Modify:
packages/lib/src/events.ts— addcarbon/solidworks-pdm-release-pollandcarbon/solidworks-pdm-file-syncschemas (Onshape precedents at lines ~514 and ~526) - Modify:
packages/lib/src/trigger.ts— add both totaskToEvent - Copy from (precedent): the
carbon/onshape-backfill+carbon/onshape-revision-syncentries in both files
Steps:
carbon/solidworks-pdm-release-pollpayload:{ companyId: string, mode: "incremental" | "backfill" }.carbon/solidworks-pdm-file-syncpayload:{ companyId: string, fileId: string, version: number, folderId: string, fileName: string, messageId: string }(messageId=${companyId}:${fileId}:${version}, used for idempotency like Onshape's).- Mirror the zod style and the
taskToEventkey naming of the Onshape entries exactly.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/lib --filter=@carbon/jobs
# Expected: exit 0
Out of scope: the jobs themselves.
Task 11: Matching/normalization helpers + unit tests
Depends on: Task 2 (types), Task 6 (normalizeComputedBom lives in packages/ee/src/solidworks-pdm/lib/bom.ts)
Files:
- Create:
packages/jobs/src/inngest/functions/integrations/solidworks-pdm-matching.ts - Create:
packages/jobs/src/inngest/functions/integrations/solidworks-pdm-matching.test.ts - Copy from (precedent):
packages/jobs/src/inngest/functions/integrations/onshape-matching.ts+onshape-matching.test.ts(reusereleaseKey,sharedNumberSuffix,escapeLikePattern— import them if exported, otherwise re-export/copy with attribution comment)
Steps:
- Pure functions:
extractCardValues(configInfos, activeConfigId, { partNumberVariable, revisionVariable })→ selects theConfigInfowhoseConfigurationId === activeConfigId(the id fromgetActiveConfig), falling back per-variable to the@tab entry when absent (input = theConfigInfo[]shape from Task 2);releaseMatchKey(partNumber, revision)→ delegates to the OnshapereleaseKeyconvention;colocatedCandidateNames(fileName)→ forx.sldprt/x.sldasmreturns["x.step", "x.stp"], forx.slddrwreturns["x.pdf"], case-insensitive, else[];classifyPdmFile(fileName)→"model" | "drawing" | "other";releaseMappingIntegration(fileClass)→"solidworks-pdm-release-model" | "solidworks-pdm-release-drawing". - Tests (vitest, mirror the Onshape test file's structure): active-config selection by id, per-variable
@fallback, and unknownactiveConfigId→ full@fallback; empty part number → no match key; drawing shared-suffix matching via the reusedsharedNumberSuffix;colocatedCandidateNamesfor all three extensions + uppercase variants;classifyPdmFileedge cases (.SLDASM, no extension).normalizeComputedBomfixture tests: a valid fixture (hand-write the raw computed-BOM JSON, documenting the assumed API shape per Task 6's escape hatch) asserting flattened rows/levels/quantities, plus rejection cases — zero part-number column matches, two ambiguous matches, a non-finite/negative quantity, and a child row skipping a level — each asserting a thrown error.
Verify:
pnpm --filter @carbon/jobs test -- solidworks-pdm-matching
# Expected: all new tests pass
pnpm exec turbo run typecheck --filter=@carbon/jobs
# Expected: exit 0 (noUncheckedIndexedAccess: use optional chaining on indexed access in tests)
Out of scope: network calls; DB access.
Task 12: Attach helper (documents, models, thumbnails)
Depends on: Task 2 Files:
- Create:
packages/jobs/src/inngest/functions/integrations/solidworks-pdm-attach.ts - Copy from (precedent):
packages/jobs/src/inngest/functions/integrations/onshape-attach.ts(the Carbon-side storage upload,documentrow creation,modelUploadrow creation + item linkage, thumbnail storage — copy the column usage and storage paths verbatim, changing only thesourceDocumentlabel to"SolidWorks PDM"and path segments from onshape to solidworks-pdm)
Steps:
- Read
onshape-attach.tsend-to-end first. Export the same operation set it provides (attach model file →modelUpload+ item link; attach PDF →documentlinked to the item; store thumbnail →modelUpload.thumbnailPath), taking already-downloaded temp file paths/bytes as input so this module stays PDM-API-free. - Filename sanitization: reuse whatever sanitizer
onshape-attach.tsuses (lesson: storage keys from raw filenames break silently — never interpolate raw names).
Verify:
pnpm exec turbo run typecheck --filter=@carbon/jobs
# Expected: exit 0
Out of scope: matching logic (Task 11); deciding WHAT to attach (Task 13).
Task 13: solidworks-pdm-file-sync Inngest job
Depends on: Tasks 10, 11, 12 Files:
- Create:
packages/jobs/src/inngest/functions/integrations/solidworks-pdm-file-sync.ts - Modify:
packages/jobs/src/inngest/functions/integrations/index.ts— export it - Modify:
packages/jobs/src/inngest/index.ts— register it (Onshape registrations at lines ~118–119) - Copy from (precedent):
packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.ts(function options, payload parse, enabled-check,withRateLimitRetrywrapper,model-optimize/model-thumbnailfan-out) andonshape-sync-element.ts(per-asset orchestration)
Steps:
inngest.createFunction({ id: "solidworks-pdm-file-sync", retries: 3, idempotency: "event.data.messageId", concurrency: { key: "event.data.fileId", limit: 1 } }, { event: "carbon/solidworks-pdm-file-sync" }, ...).- Body: parse payload →
getCarbonServiceRole()→ check integration active +assetSyncEnabled(clone theisOnshapeAssetSyncEnabledhelper pattern asisSolidWorksPdmAssetSyncEnabled, readingcompanyIntegrationmetadata) →getSolidWorksPdmClient→getActiveConfigthengetFileVariables→extractCardValues(configInfos, activeConfigId, …)→releaseMatchKey; no key or no matching item (item.readableIdWithRevisionlookup — copy the exact matching query fromonshape-sync-element.ts, includingescapeLikePatternusage and the drawing shared-suffix path for.slddrw) → return{ skipped: true, reason }. - Idempotency, keyed per file class: look up
externalIntegrationMappingwith integrationreleaseMappingIntegration(classifyPdmFile(fileName))("solidworks-pdm-release-model"for.sldprt/.sldasm,"-drawing"for.slddrw), entityType"item", entityId = matched item id, companyId. If the recorded metadataversion >= payload.version, return{ skipped: true, reason: "up-to-date" }— the>=guard blocks both replays and an out-of-order poll overwriting newer release state with older. The two class-specific integration values mean a released part and its drawing (same item) keep separate rows and never clobber each other. - By
classifyPdmFile: model →browseFolder(folderId), find firstcolocatedCandidateNameshit,downloadFileToTempit, attach via Task 12,step.sendEvent("model-optimize", ...)exactly likeonshape-revision-sync.ts; fetchgetThumbnail, store via Task 12, else fall back tocarbon/model-thumbnail. Drawing → co-located PDF → attach as document.other→ skip. - Upsert the class-specific
"solidworks-pdm-release-*"mapping row (metadata{ fileId, version, configId, fileName, stateName: <the metadata's releasedStateName> },lastSyncedAt: now,companyId, audit fields — copy column usage from whereveronshape-sync-element.ts/the sync route writes mappings).stateNameis whatSolidWorksPdmStatus(Task 9) renders; this upsert happens ONLY after the attaches succeed — the poll's dedupe depends on that ordering.
Verify:
pnpm exec turbo run typecheck --filter=@carbon/jobs && pnpm --filter @carbon/jobs test
# Expected: exit 0; existing + Task 11 tests pass
Out of scope: creating items; syncing files not in the released state (the poll already filtered).
Task 14: solidworks-pdm-release-poll job + cron fan-out
Depends on: Tasks 10, 13 Files:
- Create:
packages/jobs/src/inngest/functions/integrations/solidworks-pdm-release-poll.ts(poll function + cron function in one file) - Modify:
packages/jobs/src/inngest/functions/integrations/index.ts+packages/jobs/src/inngest/index.ts— export/register both - Copy from (precedent):
packages/jobs/src/inngest/functions/integrations/onshape-backfill.ts(retries 10, per-company concurrency, cursor loop) andpackages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts(cron iterating activecompanyIntegrationrows)
Steps:
Cron function
solidworks-pdm-release-cron:{ cron: "*/30 * * * *" }; selectcompanyIntegrationwhereid = 'solidworks-pdm'andactive = true; filter rows wheremetadata.assetSyncEnabled === true;step.sendEventonecarbon/solidworks-pdm-release-poll(mode: "incremental") per company. Zero rows → return early (log, like the exchange-rates function).Poll function:
{ id: "solidworks-pdm-release-poll", retries: 10, concurrency: { key: "event.data.companyId", limit: 1 } }, eventcarbon/solidworks-pdm-release-poll. Body:- Load integration metadata. There is no date cursor — dedupe is mapping-based (below), so
mode: "incremental"andmode: "backfill"run the same sweep;modeis kept for logging only. - Candidate discovery, honoring
metadata.searchCapability— default is"folder-sweep":- unset or
"folder-sweep": recursivelybrowseFolderfrom the vault root, bulkgetFilesInfoper folder batch, filter current state =releasedStateName. "state-search"(used ONLY when metadata explicitly says so — set by hand after live-vault validation, never inferred at runtime): callclient.searchwith workflow-state-name criteria, then cross-check each result's current-state field from bulkgetFilesInfo; any mismatch → log, ignore the mismatching rows, and proceed with the verified subset. Never auto-flip the flag in either direction: an undocumented search syntax returning silently-empty results must not be able to make releases invisible.
- unset or
- Dedupe: drop candidates whose class-specific
"solidworks-pdm-release-*"mapping row (Task 13 step 3 lookup, matched by fileId in metadata) already recordsversion >= candidate.version. Because Task 13 writes that row only after successful attaches, a failed file-sync automatically re-qualifies next sweep. - Fan out one
carbon/solidworks-pdm-file-syncper remaining candidate viastep.sendEvent(batched). - After the sweep completes, write
metadata.lastReleaseSyncAt = sweepStartIso(merge-update the metadata JSON — never replace it wholesale). This field is informational (shown in settings) — it is NOT read by discovery.
Escape hatch: the search criteria body format is undocumented. Implement
state-searchbehind a small request-builder function with the assumed format in one place; if the assumption can't be expressed from the research file, shipfolder-sweeponly and report the gap — do not invent criteria syntax silently.- Load integration metadata. There is no date cursor — dedupe is mapping-based (below), so
Verify:
pnpm exec turbo run typecheck --filter=@carbon/jobs && pnpm --filter @carbon/jobs test
# Expected: exit 0; tests pass
Out of scope: attaching assets (Task 13); webhook/backfill triggers (Tasks 15–16).
Task 15: Backfill API route
Depends on: Tasks 10, 14 Files:
- Create:
apps/erp/app/routes/api+/integrations.solidworks-pdm.backfill.ts - Copy from (precedent):
apps/erp/app/routes/api+/integrations.onshape.backfill.ts(copyrequirePermissionsscope, theassetSyncEnabledgate returning 400 with a message, and thetrigger(...)call verbatim, adjusting names)
Steps:
- Clone with deltas: gate message references SolidWorks PDM; trigger
carbon/solidworks-pdm-release-pollwith{ companyId, mode: "backfill" }; success body{ success: true, message: "SolidWorks PDM asset backfill started" }(plain object return).
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
Out of scope: none.
Task 16: Webhook receiver route
Depends on: Tasks 10, 14 Files:
- Create:
apps/erp/app/routes/api+/webhook.solidworks-pdm.$companyId.ts - Copy from (precedent):
apps/erp/app/routes/api+/webhook.onshape.$companyId.ts(public action shape, active-integration +assetSyncEnabledchecks, 400 "Integration not configured" for unknown company, zod envelope, 200 acks)
Steps:
- Clone with deltas: the zod envelope is lenient —
z.object({ EventType: z.union([z.string(), z.number()]).optional(), VaultName: z.string().optional() }).passthrough(); any POST that parses as JSON on an active, asset-sync-enabled company triggerscarbon/solidworks-pdm-release-poll{ companyId, mode: "incremental" }and returns{ success: true }. Non-JSON body → 400. Unknown/inactive company → 400 "Integration not configured". Never read file ids or state names from the payload (unsigned source — spec Risks).
Verify:
pnpm exec turbo run typecheck --filter=erp
# Expected: exit 0
Out of scope: signature verification (PDM doesn't sign); rate limiting beyond what the route framework provides.
Task 17: Docs page (conditional on existing Onshape docs)
Depends on: Tasks 1–16 (documents the finished behavior) Files:
- Possibly create: a sibling of the Onshape page under
docs/content/(exact path determined in step 1)
Steps:
- Run
grep -ril onshape docs/content | head. - If it returns one or more pages: invoke the
carbon-docsskill and author a SolidWorks PDM page as a sibling (same directory, same frontmatter shape), covering: prerequisites (PDM Professional, Web API server exposed over HTTPS, dedicated service-account seat, release-time convert tasks producing co-located STEP/PDF), the settings fields, what syncs (both features), and what is out of scope (PDM Standard, writes to vault, per-configuration items). Ground every claim in the implemented code, not this plan. - If it returns nothing: there is no CAD-integration docs surface yet — skip page creation and record "no docs surface for integrations; follow-up" in the PR body. Do not invent a new docs section in this task.
Verify:
pnpm --filter docs build
# Expected: exit 0 (only if a page was created; otherwise N/A — state which branch was taken)
Out of scope: glossary changes; API reference (codegen).
Task 18: Fixture playbook + browser verification
Depends on: Tasks 1–16 Files:
- Create:
.ai/playbooks/solidworks-pdm.md - Copy from (precedent):
.ai/playbooks/onshape-asset-sync.md(fixture SQL, gating checks, selector notes)
Steps:
- Boot the stack with plain
crbn up(portless). Login per the/authskill. - Write the playbook mirroring the Onshape one, with the PDM fixture:
insert into "companyIntegration" (id,"companyId",active,metadata,"updatedAt","updatedBy")
values ('solidworks-pdm','<companyId>',true,
'{"baseUrl":"https://localhost:9999","vaultName":"Fixture","username":"fixture","password":"FIXTURE_FAKE","releasedStateName":"Released","partNumberVariable":"Number","revisionVariable":"Revision","assetSyncEnabled":false}'::json,
now(),'<userId>')
on conflict (id,"companyId") do update set active=excluded.active, metadata=excluded.metadata, "updatedAt"=now();
- Verify with agent-browser (submit RVF forms via
requestSubmit, per the known agent-browser gotcha):/x/settings/integrationsshows the SolidWorks PDM card./x/settings/integrations/solidworks-pdmrenders Connection + Release sync groups; the backfill action appears only afterassetSyncEnabledis toggled on and saved; saving preservesusername/passwordin metadata (SQL check).POST /api/integrations/solidworks-pdm/backfillfrom the authenticated session: 200 when enabled, 400 when disabled.curl POST /api/webhook/solidworks-pdm/<companyId>with{"EventType":8}: 200{"success":true}; with an unknown companyId: 400.- Item BOM explorer shows the SolidWorks PDM sync widget while the fixture row is active (the pickers will error against the fake baseUrl — expected; capture with the
/errorskill and note it).
- Cleanup SQL (delete the fixture row, keyed on the FIXTURE password) goes in the playbook.
- Record in the run notes: live-vault sync (Tasks 13–14 end-to-end against real PDM) is environment-gated, not verified — the PR must say so explicitly.
Verify:
ls .ai/playbooks/solidworks-pdm.md
# Expected: file exists; all playbook steps above executed with screenshots for the settings page and BOM explorer widget
Out of scope: live PDM vault testing; performance testing of vault sweeps.