Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
docs(specs): SolidWorks PDM integration spec, plan, and research (#1331)
Brad Barbin9e5e27b0b09b
diff --git a/.ai/plans/2026-08-04-solidworks-pdm-integration.md b/.ai/plans/2026-08-04-solidworks-pdm-integration.mdnew file mode 100644index 0000000000..2e5fab406a--- /dev/null+++ b/.ai/plans/2026-08-04-solidworks-pdm-integration.md@@ -0,0 +1,485 @@+# 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-pdm` integration 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 the `sync` edge function+- [ ] Task 8: Manual BOM sync route (POST)+- [ ] Task 9: `SolidWorksPdmSync` UI + 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-sync` Inngest job+- [ ] Task 14: `solidworks-pdm-release-poll` job + 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.sql` and `packages/database/supabase/migrations/20260703165330_onshape-asset-sync-jsonschema.sql`++**Steps:**+1. Run `pnpm db:migrate:new solidworks-pdm-integration`.+2. Fill the generated file with exactly (the `integration` table has only `id` + `jsonschema` since `20241006185904_integration-refactor.sql`):++```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";+```++3. Run `pnpm db:migrate` to apply it to the local stack.+4. Run `pnpm run generate:types`.++**Verify:**+```bash+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-pdm` subpath export ONLY IF the existing exports map lists `./onshape` explicitly (mirror that entry); if exports are wildcarded, no change+- Copy from (precedent): `packages/ee/src/onshape/lib/client.ts` (axios client class + error types + `getOnshapeClient` factory at line ~591)++**Steps:**+1. 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 loads `companyIntegration` and returns `{ client, error }` without throwing.+2. Implement `SolidWorksPdmClient` with 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 calls `POST /api/{vaultName}/authenticate` with `{ Username, Password }`, stores `JwtString` in memory, sends `Authorization: Bearer <jwt>` on every call, and on a 401 response re-authenticates once and retries the request once (then surfaces the error).+3. Methods (paths from the research file §7; response types as minimal TS interfaces — define only fields we consume):+ - `getWebApiVersion(): GET /api/version/webapi`+ - `getVaultInfo(): GET /api/{v}/info`+ - `search(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}/configurations`+ - `getActiveConfig(fileId, version): GET /api/{v}/files/{fileId}/{version}/ActiveConfig` — returns the active configuration id/name+ - `getFileVariables(fileId, version): GET /api/{v}/files/{fileId}/{version}/variables` — returns `ConfigInfo[]` (`{ ConfigurationName, ConfigurationId, Models: [{ VarName, VarValue }] }`)+ - `getBomInfo(fileId): GET /api/{v}/files/{fileId}/bominfo`+ - `getComputedBom(bomTypeId, fileId, version, folderId, configId): GET /api/{v}/bom/{bomTypeId}/{fileId}/{version}/{folderId}/computed?configId=&latest=true`+ - `browseFolder(folderId): GET /api/{v}/folders/{folderId}/browse`+ - `getThumbnail(fileId, version, folderId, { maxBytes })` — `GET /api/{v}/files/{fileId}/{version}/thumbnails?folderId=`; the API replies with a redirect `Location`; follow it and return bytes + content type, enforcing the same `maxBytes` cap as `downloadFileToTemp` while reading (abort and throw `SolidWorksPdmAssetTooLargeError` once 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's `downloadExternalDataToFile` (throw `SolidWorksPdmAssetTooLargeError` past the cap)+ - `registerWebhook(url, events)` / `getWebhooks()` / `deleteWebhook(id)` — `POST|GET /api/{v}/configuration/hooks/url` (2025+; callers treat failures as non-fatal)+4. Error classes: `SolidWorksPdmApiError` (status + message + url) and `SolidWorksPdmAssetTooLargeError`, mirroring the Onshape pair.+5. Factory `getSolidWorksPdmClient(client: SupabaseClient<Database>, companyId: string)`: read `companyIntegration` row `id = "solidworks-pdm"`, require `active`, require `metadata.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:**+```bash+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:**+1. Read the Onshape validator to match its style and the field set the `sync` edge function consumes.+2. 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 }` — plus `type SolidWorksPdmBomRow = z.infer<...>`. Match the Onshape validator's conventions for optionality/coercion exactly where fields overlap (partNumber, description, quantity).++**Verify:**+```bash+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` — add `SolidWorksPdm` to the `integrations` array + barrel exports+- Modify: `packages/ee/src/hooks.server.ts` — add the `solidworks-pdm` entry to the `serverHooks` map+- Copy from (precedent): `packages/ee/src/onshape/config.tsx`, `packages/ee/src/onshape/hooks.server.ts`++**Steps:**+1. `config.tsx`: `defineIntegration` with `id: "solidworks-pdm"`, `name: "SolidWorks PDM"`, `category: "CAD"` (same literal as Onshape's), `active: true` (no env-var gate — credentials are per-company), an inline SVG `Logo` component (simple "PDM" wordmark in currentColor; do not fetch brand assets), `description` stating: PDM Professional only, requires the customer's PDM Web API server reachable over HTTPS, and one dedicated vault service account. `images: []`.+2. `settings` (with `settingGroups` `Connection` and `Release sync` — copy the group mechanics from any integration using `group`, e.g. grep `settingGroups` in `packages/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).+3. `schema`: zod object with all eight fields; `baseUrl` must parse as URL and be `https:` unless hostname is `localhost`/`127.0.0.1`; `assetSyncEnabled` uses the same `z.preprocess` string→boolean trick as Onshape's schema. Also `.passthrough()` so system-written keys (`webApiVersion`, `searchCapability`, `lastReleaseSyncAt`) survive validation — check how the settings action at `apps/erp/app/routes/x+/settings+/integrations.$id.tsx` merges metadata before deciding whether passthrough is needed, and mirror whichever integration already preserves extra keys (Onshape's `onshapeCompanyId` proves the merge path exists).+4. `actions`: `[{ id: "backfill", label: "Backfill released assets", description: <one sentence>, endpoint: "/api/integrations/solidworks-pdm/backfill", enabledWhenSetting: "assetSyncEnabled" }]`.+5. No `oauth`, no `onClientInstall`.+6. `solidworks-pdm/hooks.server.ts`: export `solidWorksPdmOnInstall` (authenticate + `getVaultInfo`; on failure return/throw the same error shape Onshape's install path surfaces via `integration-errors.ts`; on success write `metadata.webApiVersion` via `upsertCompanyIntegration`-style update, then if `assetSyncEnabled` and version ≥ 2025 best-effort `registerWebhook` for the post-ChangeState event pointing at `${origin}/api/webhook/solidworks-pdm/${companyId}` — wrap in try/catch, log, continue), `solidWorksPdmOnUninstall` (best-effort `deleteWebhook`), `solidWorksPdmOnHealthcheck` (authenticate + vault info; return the exact healthcheck result shape used by Onshape's `onHealthcheck` — read it in `packages/ee/src/onshape/hooks.server.ts` first).+7. Wire all three into the `serverHooks` map in `packages/ee/src/hooks.server.ts`; add `export { Logo as SolidWorksPdmLogo, SolidWorksPdm } from "./solidworks-pdm/config"` to `packages/ee/src/index.ts` and append `SolidWorksPdm` to the `integrations` array.++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:**+```bash+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`/`onShapeSync` entries in the same file++**Steps:**+1. 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:**+```bash+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 + `requirePermissions` scope — copy the scope verbatim), `...d.$did.v.$vid.elements.ts` (param loader), `...d.$did.v.$vid.e.$eid.bom.ts` (BOM loader)++**Steps:**+1. `files.ts` (GET loader): `requirePermissions` with the same scope as `integrations.onshape.documents.ts`; read `?q=` search text; `getSolidWorksPdmClient`; call `search` with a filename criteria built from `q`. Search returns only `[{ Id, Type }]` — so take at most the first **200** file-type ids, hydrate them via one bulk `getFilesInfo` call, filter to extensions `.sldasm`/`.sldprt` (case-insensitive), and return at most **50** results as `{ files: [{ id, name, folderId, version }] }`. Return plain objects (never `Response.json`). Empty `q` → return `{ files: [] }` without calling the API.+2. `configurations.ts` (GET loader): same scope; params `fileId`, query `version` and `folderId` (pass through from the file pick); call `getFileConfigurations`; return `{ configurations: [{ id, name }] }`.+3. `bom.ts` (GET loader): same scope; params `fileId`, query `version`, `folderId`, `configId`; call `getBomInfo` then `getComputedBom` with `latest=true`; **normalize here**: read the integration metadata's `partNumberVariable`/`revisionVariable`, locate the matching entries in the BOM `Columns[]` by name (case-insensitive), and flatten the recursive row tree into `SolidWorksPdmBomRow[]` (Task 3 type) with `level` = tree depth and `quantity` from 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 matching `partNumberVariable` → 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:**+```bash+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:**+1. 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).+2. Read the whole `onshape` handler. Add a `z.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 to `payloadValidator`.+3. 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. Write `externalIntegrationMapping` rows: 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, including `companyId` and audit fields).+4. 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:**+```bash+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 its `requirePermissions` scope, its edge-function invocation via `client.functions.invoke("sync", ...)`, and its mapping upsert verbatim, adjusting names)++**Steps:**+1. Clone the Onshape sync action: validate the posted body (`itemId`, `rows` per `solidWorksPdmDataValidator`, `source: { fileId, configId?, folderId? }`), invoke the `sync` edge function with `type: "solidworks-pdm"`, and upsert the root `externalIntegrationMapping` row exactly the way the Onshape route does (same table columns, `lastSyncedAt` update included).++**Verify:**+```bash+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 beside `OnshapeSync` (line ~160)+- Modify: `apps/erp/app/components/Icons.tsx` — add `SolidWorksPdmStatus`+- Copy from (precedent): `apps/erp/app/components/OnshapeSync.tsx` (the whole component: fetchers, comboboxes, BOM preview tree, Sync/Save buttons, saved-selection + `lastSyncedAt` read from `externalIntegrationMapping`); `OnshapeStatus` in `Icons.tsx`++**Steps:**+1. Clone `OnshapeSync.tsx` → `SolidWorksPdmSync.tsx` with these deltas: the three-level Document→Version→Element pickers become two levels — a debounced file **search input + results combobox** (GET `path.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 renders `partNumber`/`description`/`quantity`/`revision` by `level`; "Sync" POSTs to `path.to.api.solidWorksPdmSync`. Keep the saved-mapping read/write behavior (integration id `"solidworks-pdm"`).+2. In `BoMExplorer.tsx`, find how the `OnshapeSync` mount is gated on the Onshape integration being active, and add the equivalent `SolidWorksPdmSync` mount gated on `solidworks-pdm` — both may render if both integrations are active.+3. `SolidWorksPdmStatus` in `Icons.tsx`: clone `OnshapeStatus`. Field sources (these are the only producers that persist them): `stateName` from the `"solidworks-pdm-release-model"`/`"-drawing"` mapping metadata (written by Task 13 step 5), `revision` from the `solidworksPdmData` mapping metadata. No release mapping yet → render revision only. A plain text badge is sufficient (no state-color mapping in v1).++**Verify:**+```bash+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` — add `carbon/solidworks-pdm-release-poll` and `carbon/solidworks-pdm-file-sync` schemas (Onshape precedents at lines ~514 and ~526)+- Modify: `packages/lib/src/trigger.ts` — add both to `taskToEvent`+- Copy from (precedent): the `carbon/onshape-backfill` + `carbon/onshape-revision-sync` entries in both files++**Steps:**+1. `carbon/solidworks-pdm-release-poll` payload: `{ companyId: string, mode: "incremental" | "backfill" }`.+2. `carbon/solidworks-pdm-file-sync` payload: `{ companyId: string, fileId: string, version: number, folderId: string, fileName: string, messageId: string }` (`messageId` = `${companyId}:${fileId}:${version}`, used for idempotency like Onshape's).+3. Mirror the zod style and the `taskToEvent` key naming of the Onshape entries exactly.++**Verify:**+```bash+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` (reuse `releaseKey`, `sharedNumberSuffix`, `escapeLikePattern` — import them if exported, otherwise re-export/copy with attribution comment)++**Steps:**+1. Pure functions: `extractCardValues(configInfos, activeConfigId, { partNumberVariable, revisionVariable })` → selects the `ConfigInfo` whose `ConfigurationId === activeConfigId` (the id from `getActiveConfig`), falling back per-variable to the `@` tab entry when absent (input = the `ConfigInfo[]` shape from Task 2); `releaseMatchKey(partNumber, revision)` → delegates to the Onshape `releaseKey` convention; `colocatedCandidateNames(fileName)` → for `x.sldprt`/`x.sldasm` returns `["x.step", "x.stp"]`, for `x.slddrw` returns `["x.pdf"]`, case-insensitive, else `[]`; `classifyPdmFile(fileName)` → `"model" | "drawing" | "other"`; `releaseMappingIntegration(fileClass)` → `"solidworks-pdm-release-model" | "solidworks-pdm-release-drawing"`.+2. Tests (vitest, mirror the Onshape test file's structure): active-config selection by id, per-variable `@` fallback, and unknown `activeConfigId` → full `@` fallback; empty part number → no match key; drawing shared-suffix matching via the reused `sharedNumberSuffix`; `colocatedCandidateNames` for all three extensions + uppercase variants; `classifyPdmFile` edge cases (`.SLDASM`, no extension). `normalizeComputedBom` fixture 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:**+```bash+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, `document` row creation, `modelUpload` row creation + item linkage, thumbnail storage — copy the column usage and storage paths verbatim, changing only the `sourceDocument` label to `"SolidWorks PDM"` and path segments from onshape to solidworks-pdm)++**Steps:**+1. Read `onshape-attach.ts` end-to-end first. Export the same operation set it provides (attach model file → `modelUpload` + item link; attach PDF → `document` linked to the item; store thumbnail → `modelUpload.thumbnailPath`), taking already-downloaded temp file paths/bytes as input so this module stays PDM-API-free.+2. Filename sanitization: reuse whatever sanitizer `onshape-attach.ts` uses (lesson: storage keys from raw filenames break silently — never interpolate raw names).++**Verify:**+```bash+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, `withRateLimitRetry` wrapper, `model-optimize`/`model-thumbnail` fan-out) and `onshape-sync-element.ts` (per-asset orchestration)++**Steps:**+1. `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" }, ...)`.+2. Body: parse payload → `getCarbonServiceRole()` → check integration active + `assetSyncEnabled` (clone the `isOnshapeAssetSyncEnabled` helper pattern as `isSolidWorksPdmAssetSyncEnabled`, reading `companyIntegration` metadata) → `getSolidWorksPdmClient` → `getActiveConfig` then `getFileVariables` → `extractCardValues(configInfos, activeConfigId, …)` → `releaseMatchKey`; no key or no matching item (`item.readableIdWithRevision` lookup — copy the exact matching query from `onshape-sync-element.ts`, including `escapeLikePattern` usage and the drawing shared-suffix path for `.slddrw`) → return `{ skipped: true, reason }`.+3. Idempotency, keyed per file class: look up `externalIntegrationMapping` with integration `releaseMappingIntegration(classifyPdmFile(fileName))` (`"solidworks-pdm-release-model"` for `.sldprt`/`.sldasm`, `"-drawing"` for `.slddrw`), entityType `"item"`, entityId = matched item id, companyId. If the recorded metadata `version >= 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.+4. By `classifyPdmFile`: model → `browseFolder(folderId)`, find first `colocatedCandidateNames` hit, `downloadFileToTemp` it, attach via Task 12, `step.sendEvent("model-optimize", ...)` exactly like `onshape-revision-sync.ts`; fetch `getThumbnail`, store via Task 12, else fall back to `carbon/model-thumbnail`. Drawing → co-located PDF → attach as document. `other` → skip.+5. 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 wherever `onshape-sync-element.ts`/the sync route writes mappings). `stateName` is what `SolidWorksPdmStatus` (Task 9) renders; this upsert happens ONLY after the attaches succeed — the poll's dedupe depends on that ordering.++**Verify:**+```bash+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) and `packages/jobs/src/inngest/functions/scheduled/update-exchange-rates.ts` (cron iterating active `companyIntegration` rows)++**Steps:**+1. Cron function `solidworks-pdm-release-cron`: `{ cron: "*/30 * * * *" }`; select `companyIntegration` where `id = 'solidworks-pdm'` and `active = true`; filter rows where `metadata.assetSyncEnabled === true`; `step.sendEvent` one `carbon/solidworks-pdm-release-poll` (`mode: "incremental"`) per company. Zero rows → return early (log, like the exchange-rates function).+2. Poll function: `{ id: "solidworks-pdm-release-poll", retries: 10, concurrency: { key: "event.data.companyId", limit: 1 } }`, event `carbon/solidworks-pdm-release-poll`. Body:+ - Load integration metadata. There is **no date cursor** — dedupe is mapping-based (below), so `mode: "incremental"` and `mode: "backfill"` run the same sweep; `mode` is kept for logging only.+ - Candidate discovery, honoring `metadata.searchCapability` — **default is `"folder-sweep"`**:+ - unset or `"folder-sweep"`: recursively `browseFolder` from the vault root, bulk `getFilesInfo` per 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): call `client.search` with workflow-state-name criteria, then cross-check each result's current-state field from bulk `getFilesInfo`; 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.+ - Dedupe: drop candidates whose class-specific `"solidworks-pdm-release-*"` mapping row (Task 13 step 3 lookup, matched by fileId in metadata) already records `version >= 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-sync` per remaining candidate via `step.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-search` behind a small request-builder function with the assumed format in one place; if the assumption can't be expressed from the research file, ship `folder-sweep` only and report the gap — do not invent criteria syntax silently.++**Verify:**+```bash+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` (copy `requirePermissions` scope, the `assetSyncEnabled` gate returning 400 with a message, and the `trigger(...)` call verbatim, adjusting names)++**Steps:**+1. Clone with deltas: gate message references SolidWorks PDM; trigger `carbon/solidworks-pdm-release-poll` with `{ companyId, mode: "backfill" }`; success body `{ success: true, message: "SolidWorks PDM asset backfill started" }` (plain object return).++**Verify:**+```bash+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 + `assetSyncEnabled` checks, 400 "Integration not configured" for unknown company, zod envelope, 200 acks)++**Steps:**+1. 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 triggers `carbon/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:**+```bash+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:**+1. Run `grep -ril onshape docs/content | head`.+2. If it returns one or more pages: invoke the `carbon-docs` skill 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.+3. 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:**+```bash+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:**+1. Boot the stack with plain `crbn up` (portless). Login per the `/auth` skill.+2. Write the playbook mirroring the Onshape one, with the PDM fixture:++```sql+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();+```++3. Verify with agent-browser (submit RVF forms via `requestSubmit`, per the known agent-browser gotcha):+ - `/x/settings/integrations` shows the SolidWorks PDM card.+ - `/x/settings/integrations/solidworks-pdm` renders Connection + Release sync groups; the backfill action appears only after `assetSyncEnabled` is toggled on and saved; saving preserves `username`/`password` in metadata (SQL check).+ - `POST /api/integrations/solidworks-pdm/backfill` from 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 `/error` skill and note it).+4. Cleanup SQL (delete the fixture row, keyed on the FIXTURE password) goes in the playbook.+5. 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:**+```bash+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.diff --git a/.ai/research/solidworks-pdm-integration.md b/.ai/research/solidworks-pdm-integration.mdnew file mode 100644index 0000000000..a24a215ab3--- /dev/null+++ b/.ai/research/solidworks-pdm-integration.md@@ -0,0 +1,156 @@+# SolidWorks PDM Integration — Research++> Date: 2026-08-04+> Purpose: ground the design of a Carbon ↔ SOLIDWORKS PDM Professional integration (spec: `.ai/specs/2026-08-04-solidworks-pdm-integration.md`), modeled on the existing Onshape integration.+> Grounded in the official SOLIDWORKS help (endpoint inventory extracted directly from the 2019–2026 `pdmprowebapihelp` doc trees), vendor/VAR documentation, and competitor connector marketing.++## TL;DR++- PDM Professional has **two APIs**: the classic in-process **COM API** (`IEdmVault5`, Windows-only, needs an installed PDM client + vault view + license) and an **HTTP REST "Web API"** (IIS app, PDM Professional only, JWT auth, default port 65453). The Web API is **read/write** (check-in/out, upload, data card save, state change) — not read-only.+- The Web API server component dates to ~2018 (built for EXALEAD OnePart indexing and eDrawings mobile vault access; integrated into the PDM installer in 2019); public endpoint documentation only appeared in the help around 2021–2022. Extraction of the doc tree counts **106 endpoints in the 2024 docs and 113 in 2025/2026**.+- **PDM 2025 added webhooks** (18 pre/post events incl. `OnPostChangeState`, i.e. "file released") plus server-side "add-in hook" DLLs — but as documented, each webhook is keyed to a *Web API HTTP request*, so events appear to fire for API-mediated operations; desktop-client-originated transitions are the norm in real vaults and are traditionally captured with COM add-ins/tasks/Dispatch or DB polling. Treat webhook coverage of desktop operations as **unverified — assume not covered** until tested.+- Every production ERP connector in this market (CADLink, Genius CAD2BOM, CustomTools, OdooPLM) is an **on-prem add-in or Windows service** that hooks PDM/CAD locally and pushes to the ERP. Nobody ships a pure "cloud calls the vault" integration. CADLink specifically = CAD/PDM UI add-in + background service watching workflow state changes, pushing Item/BOM/Routing to ERP on release.+- The realistic Carbon architecture is an **outbound-only on-prem agent** (Windows service using the COM API and/or localhost Web API) pushing to Carbon's REST API on release transitions, with the customer-exposed Web API as a secondary, lower-friction-but-lower-fidelity option for 2023+ installs.++---++## 1. API options++### 1.1 Classic COM API (`IEdmVault5` et al.)++- COM-based, stateful, in-process; interfaces like `IEdmVault5` (login/vault), `IEdmFile5`, `IEdmFolder5`, `IEdmEnumeratorVariable5` (data card variables), `IEdmBomMgr`/`IEdmBomView` (BOMs), `IEdmItem*` (items). "High-performance access to metadata, folders, variables, references, and workflow information," per Blue Byte's practical guide — explicitly *not* a REST API; it's tightly integrated with the Windows processes running the PDM client. https://bluebyte.biz/solidworks/solidworkspdm/a-practical-guide-to-the-solidworks-pdm-api-in-2026/+- Requires: Windows, the PDM Professional/Standard client installed, a local vault view, and a licensed vault login. Languages: VBA, C#, VB.NET, C++, PowerShell via COM interop (Python needs COM wrappers).+- Three application patterns: **add-ins** (DLLs registered in the vault, receive events via `IEdmAddIn5::OnCmd` — check-in, state change, etc.), **tasks** (framework for conversion/scripted work executed on a designated task host machine, triggerable from workflow transitions), and **standalone desktop utilities** (batch tools). https://www.codestack.net/solidworks-pdm-api/ and https://www.codestack.net/solidworks-pdm-api/pdm-tasks/+- This is the only API surface for **PDM Standard** (Standard's API is a restricted subset; no Web API at all).++### 1.2 SOLIDWORKS PDM Web API (REST) — PDM Professional only++- An optional **"Web API server"**: an ASP.NET web app hosted in IIS on-prem, installed from the PDM installer and configured per-vault in the Administration tool. Default HTTP port **65453**. Originally built so **EXALEAD OnePart** could index vault data (that's still how the admin help frames it) and to serve eDrawings mobile vault browsing; the 2019 release integrated its installation into the main PDM server installer ("previously, you had to install the Web API server components separately" — i.e. the component predates 2019). https://help.solidworks.com/2019/english/EnterprisePDM/Admin/c_web_api_server_overview.htm , https://help.solidworks.com/2019/english/WhatsNew/c_integrated_install_webapi_server.htm , https://help.solidworks.com/2022/english/EnterprisePDM/Admin/c_administering_web_api_servers.htm+- **Auth**: `POST /api/{vaultName}/authenticate` with `{Username, Password}` (a normal PDM vault user) returns a `JwtString`; subsequent calls use `Authorization: Bearer <token>`. Official docs include Python/C# samples. https://help.solidworks.com/2023/english/api/pdmprowebapihelp/PDM%20Pro%20API_ws~r-api-%7BvaultName%7D-authenticate~o-HttpPost.html+- **Not read-only.** The endpoint inventory (section 7) includes folder create, staged file upload + check-in, check-out/undo, data card variable save, workflow state change, and delete. Reads cover files, versions, references/where-used, configurations, variables, data cards, computed/named BOMs, search, workflows, users/groups, thumbnails, download.+- **Documentation quality is poor**: auto-generated, no OpenAPI/swagger published, no documented token TTL ("there is no way to determine when the access token expires" — Blue Byte), and SOLIDWORKS support has acknowledged the docs are auto-generated. https://bluebyte.biz/pdm-api-tips/a-quickstart-guide-with-the-solidworks-pdm-web-api/+- Community example front-end consuming the REST API: https://github.com/hawkwareapps/pdm-web-example (auth + search + PNG previews).++### 1.3 Web2 server++- **Web2 is a UI, not an API**: a responsive browser client (IIS app, typically `/SOLIDWORKSPDM` site) for browsing, searching, check-in/out, state change, and eDrawings-based WebGL preview from any device. It has no documented public API; the Web API server is the programmatic sibling. https://help.solidworks.com/2021/English/EnterprisePDM/FileExplorer/c_Web2_Client.htm , https://www.javelin-tech.com/blog/2025/09/using-the-solidworks-pdm-web2-client-for-external-access/ , https://hawkridgesys.com/blog/top-6-new-enhancements-in-solidworks-pdm-2019 (WebGL eDrawings preview added to Web2 in 2019).++---++## 2. Deployment reality — how cloud talks to an on-prem vault++PDM Professional is strictly on-prem: SQL Server (vault DB) + Archive Server (file store) + SolidNetWork License server, plus optional IIS boxes for Web2/Web API. Realistic patterns:++**(a) Customer exposes the Web API server** (internet or VPN): possible — Web2/Web API are explicitly designed to be internet-faceable via IIS with HTTPS — but requires the customer's IT to stand up IIS, TLS, firewall rules (port 65453 by default), and to accept a vault-credential-holding endpoint on the edge. VARs' guidance for Web2 external access applies equally. https://www.javelin-tech.com/blog/2025/09/using-the-solidworks-pdm-web2-client-for-external-access/++**(b) On-prem connector/agent** written against the COM API (or hitting the Web API on localhost), pushing outbound to the cloud ERP's REST API. This is what the entire commercial ecosystem does:++- **CADLink (QBuild)** — the market leader for SOLIDWORKS/PDM→ERP. Architecture per QBuild: three components — (1) a CAD-side interface "to check and compare ERP data before commit to PLM check-in," (2) a PLM/PDM data-card interface to browse ERP data and link PDM documents to ERP items, and (3) a **background service that monitors PDM workflow state changes** and auto-pushes Item, BOM, and Routing to the ERP when files hit designated (release) states. Bidirectional in the sense that engineers can *view/pull* ERP item-master data (descriptions, on-hand, open orders) from inside CAD/PDM, while the authoritative sync is a push into ERP. "No additional database or server components"; 50+ CAD/PDM/PLM sources, 50+ ERPs (Epicor, Dynamics 365 BC/F&O, SyteLine, JobBOSS, NetSuite, Acumatica, Plex, Rootstock…). https://www.qbuildsoftware.com/cadlink/cadlink-plm-pdm/ , https://www.solidworks.com/partner-product/cadlink-solidworks-pdm-professional , https://www.qbuildsoftware.com/wp-content/uploads/cadlink_fact-sheet_sw_2020.pdf , https://www.acumatica.com/acumatica-marketplace/qbuild-cadlink-cad-bom-to-acumatica-sync/+- **Genius ERP CAD2BOM** — "a plugin housed within your CAD system"; one-click conversion of the CAD model into an itemized BOM in Genius, creating items/raw materials in parallel; SOLIDWORKS/Inventor/CREO/Solid Edge/Catia. Same on-prem add-in pattern. https://www.geniuserp.com/features/cad2bom-engineering/ , https://www.solidworks.com/partner-product/genius-cad2bom+- **Odoo**: **OdooPLM** (open source, OmniaSolutions) uses a client-side CAD/PDM integration talking to Odoo over XML-RPC (https://github.com/OmniaGit/odooplm); **ATR CustomTools** is a SOLIDWORKS add-in syncing item master/BOM/documents to Odoo via remote calls (https://www.atrsoft.com/customtools/news/integrate-solidworks-with-odoo-erp/). ERPNext has no notable maintained connector.+- **JobBOSS / DDI System (Inform) / most mid-market ERPs**: served via CADLink rather than first-party connectors — QBuild lists them as supported targets.+- Historical pattern identical: SolidWorks Enterprise PDM → Dynamics AX connector (B&W IRS) was an on-prem service bridging the PDM database and AX. https://www.slideshare.net/slideshow/bwirs-solid-works-enterprise-pdm-microsoft-axconnector/17193515++**(c) Third-party middleware/iPaaS** — QBuild markets iPaaS targets, and xLM Solutions and Hawkware build custom PDM web-services bridges (https://www.youtube.com/watch?v=z46dW7d5Bg0 , https://github.com/hawkwareapps/pdm-web-example), but there is no established neutral "PDM cloud gateway" product category.++Conclusion: **(b) is the industry-proven pattern**; (a) became plausible for read-mostly integration once the Web API matured (and especially with 2025 webhooks), but no major ERP connector relies on it today.++---++## 3. Data model++- **Data card variables** are the metadata system of record: per-file (and per-folder) card values stored in the vault DB. Variables (e.g. `Number`, `Description`, `Revision`, `Material`) are **two-way mapped to file custom properties** via attribute mappings (block `CustomProperty`, attribute = property name) — edit the card and the SW file property updates, and vice versa. https://help.solidworks.com/2022/english/EnterprisePDM/admin/c_mapping_variables_solidworks.htm , https://www.javelin-tech.com/blog/2025/04/solidworks-pdm-how-to-map-variables-to-file-properties-and-custom-variables/ , https://www.goengineer.com/blog/solidworks-pdm-variable-mapping-tips-and-tricks+- **Per-configuration values**: if a SOLIDWORKS file has configurations, the data card shows one tab per configuration; values can differ per config (the `@` tab holds file-level/custom-tab values). The Web API mirrors this: `GET .../files/{fileId}/{version}/variables` returns an **array of `ConfigInfo`** ({ConfigurationName, ConfigurationId, Models:[{VarId, VarName, VarValue, VarType, VersionFree,…}]}) — i.e. variables grouped by configuration; `POST .../files/{fileId}/datacard` writes the same shape. https://www.goengineer.com/blog/configuration-properties-solidworks-pdm-data-cards+- **Revision**: a workflow concept — revision counters/numbers are bumped by workflow transition actions ("Inc. revision", "Set variable"), and the displayed revision is typically both a system attribute and a card variable stamped at release. Versions (every check-in) ≠ revisions (workflow-controlled). The API exposes file versions, history, and current state; the revision string is read from the card variable/file info.+- **BOMs**: two kinds.+ - **Computed BOMs (CBOMs)** — calculated live from the CAD assembly/drawing reference structure (includes virtual components, respects SW BOM exclusions; weldment cut lists are a computed type that only refreshes on check-in). Columns are admin-configured BOM views pulling card variables/referenced properties. https://www.mlc-cad.com/solidworks-help-center/how-to-activate-a-computed-bom-in-solidworks-pdm/ , https://help.solidworks.com/2021/english/EnterprisePDM/fileexplorer/c_Referenced_Properties_in_Computed_BOMs.htm+ - **Named BOMs** — a saved snapshot of a computed BOM that becomes a vault object in its own right: editable cell-by-cell, versioned, check-in/out, workflow states. This is what customers use as the "engineering BOM of record" when it must diverge from CAD structure. https://www.javelin-tech.com/blog/2018/08/solidworks-pdm-named-bom/+ - Web API surface: `GET .../files/{fileId}/bominfo` (which BOM sheets/types exist), `GET .../bom/{bomTypeId}/{fileId}/{version}/{folderId}/computed?configId=&latest=` (returns `ComputedBOM`: `Columns[]` + a recursive `BOMRef` tree of `BOMRow`s — **per-configuration via `configId`**), `.../named`, `.../weldmentcutlist`.+- **Item mode vs file mode**: PDM Professional has an item-centric layer ("Items" + Item Explorer — item numbers aggregating CAD + docs, item BOMs) but it is legacy/niche, administered separately, still documented through 2025 yet absent from the Web API; COM has `IEdmItem*`. The overwhelming majority of vaults are **file-mode** — part number lives on the file's data card. Plan for file mode; treat items as out of scope. https://help.solidworks.com/2023/English/EnterprisePDM/Admin/c_items_admin_tool.htm , https://help.solidworks.com/2025/english/EnterprisePDM/ItemExplorer/c_Item_Explorer.htm++---++## 4. Events / webhooks++- **PDM 2025+ Web API webhooks** ("web event hooks"): register URLs per event via `POST /api/{vaultName}/configuration/hooks/url` (or by editing `vault.config.json` under the Web API site root, e.g. `c:\inetpub\wwwroot\SOLIDWORKSPDM\WebApi`). **18 events**: pre/post × AddFolder, AddFiles, GetFile (download), LockFile (checkout), UndoLockFile, Checkin, **ChangeState**, DeleteFile, DeleteFolder. Payload includes event type enum, vault name, operation parameters; **pre-events can cancel the operation** by returning HTTP 402/412; per-vault `HooksTimeout` default 15 s; logs in `c:\ProgramData\SWPDMWebAPI`. Requires the admin's "Can administrate add-ins" permission. Also new in 2025: **server-side add-in hook DLLs** (`SWPDM.Hooks.IAddInHook::OnCmd`, uploaded via `PUT /configuration/hooks/dll`, loaded in isolated AppDomains — i.e. .NET Framework). https://help.solidworks.com/2025/english/api/pdmprowebapihelp/PDMProWebAPI_Webhooks_Programming_Guide.html , https://help.solidworks.com/2026/english/api/pdmprowebapihelp/Webhooks.html+- **Critical caveat**: the official event table maps each webhook to a specific *Web API HTTP request* ("If this webhook is configured… then when this HTTP request is sent…"). The hooks provider is a Web API server component, so as documented the webhooks fire for **operations performed through the Web API** — coverage of transitions performed from the desktop PDM client (the dominant path in real vaults) is not documented and should be assumed absent pending a live test. Do not architect around these webhooks without verifying that a desktop-client "Released" transition fires `OnPostChangeState`.+- **Pre-2025 / desktop-originated events** — the mechanisms real integrations use:+ - **COM add-in event hooks** (`IEdmAddIn5::OnCmd` for post-state-change, post-check-in, etc.) — fires in the client session performing the operation; this is how CADLink-class tools and serial-number/validation add-ins work. https://www.codestack.net/solidworks-pdm-api/+ - **Workflow transition actions**: "Execute task" (run a conversion/script on the task host at release), "Execute command", set-variable, inc-revision. https://help.solidworks.com/2021/English/EnterprisePDM/FileExplorer/c_Transition_Actions.htm , https://help.solidworks.com/2022/english/EnterprisePDM/admin/t_workflow_transition_actions.htm+ - **Dispatch** (admin-configured script actions on events) and **email notifications** on transitions (SMTP — some integrations literally parse notification mail).+ - **Polling**: query the vault (search API/COM, or read-only SQL against the vault DB — common but unsupported) for files that entered a target state since the last sweep. CADLink's "background service monitors state changes" is effectively this pattern.++---++## 5. Auth & licensing++- **License types** (SolidNetWork licenses): **CAD Editor & Web** (full, CAD add-ins), **Contributor & Web** (add/modify, no CAD add-ins), **Viewer** (read-only, cannot add/modify), plus **Processor Site License (PSL)**. https://trimech.com/solidworks-pdm-license-types-what-do-i-need/ , https://www.gsc-3d.com/blog/solidworks-pdm-license-types/+- **Web2** logins consume either a "Web" license (comes with each CAD Editor/Contributor/PSL) for read-write access or a Viewer license for read-only; license pools can be partitioned with an SNL options file. https://www.javelin-tech.com/blog/2019/01/solidworks-pdm-web2-login-type-options/ , https://support.hawkridgesys.com/hc/en-us/articles/115003426891-Managing-licenses-for-PDM-and-Web2-using-an-Options-File+- **Web API**: authentication is an ordinary vault user login; Dassault does not document a separate "API license," and license consumption semantics for Web API sessions are **not clearly documented anywhere** — plan on a dedicated service account holding an appropriate seat (Viewer if read-only suffices; Contributor if the integration writes card variables/states) and validate against the customer's SNL pool. A COM-based agent likewise consumes a client license while logged in. Budget one named seat per vault for the connector and confirm with the customer's VAR.++---++## 6. File previews++- **Web API**: `GET /api/{vaultName}/files/{fileId}/{version}/thumbnails?folderId=` returns a redirect (`Location` URI) to the thumbnail image — the community example renders PNG previews of SOLIDWORKS files this way. Simplest cloud-accessible preview path. https://github.com/hawkwareapps/pdm-web-example+- **COM**: the EPDM API has a documented "Get Preview Bitmap of File" pattern for the stored preview. https://help.solidworks.com/2018/english/api/epdmapi/get_bitmap_preview_of_file_example_vbnet.htm+- **Document Manager API** (headless, no SOLIDWORKS needed, free license key from Dassault): `ISwDMConfiguration9::GetPreviewPNGBitmapBytes` extracts the embedded per-configuration preview PNG straight from the `.sldprt/.sldasm` file. Ideal for an agent that already has file bytes. https://www.codestack.net/solidworks-document-manager-api/document/get-preview/+- **eDrawings**: interactive viewing — Web2 embeds the eDrawings WebGL viewer (since 2019; eDrawings viewer embedded in desktop preview tab since 2022). https://help.solidworks.com/2022/English/WhatsNew/c_wn2022_pdm_embed_edrawing_viewer.htm+- **Convert tasks**: the standard "publish at release" pattern — a PDM Convert task on the release transition generates PDF/STEP/DXF into the vault (runs on a task host with SOLIDWORKS installed); integrations then ship the neutral file to the ERP. https://www.codestack.net/solidworks-pdm-api/pdm-tasks/built-in-tasks/customizing-solidworks-pdm-convert-task/++---++## 7. Web API endpoint inventory (extracted from the 2026 docs; 113 endpoints)++Index: https://help.solidworks.com/2026/english/api/pdmprowebapihelp/PDMProAPI_ws.html (same for [2024](https://help.solidworks.com/2024/english/api/pdmprowebapihelp/PDMProAPI_ws.html), [2022](https://help.solidworks.com/2022/English/api/pdmprowebapihelp/PDMProAPI_ws.html)). Grouped, `{v}` = vaultName:++- **Auth/version/config**: `POST api/{v}/authenticate`; `GET api/version/webapi`; `GET api/configuration/vaults?vaultName=`; `GET|POST api/configuration/fileserverroot` (2025+); `GET api/{v}`, `GET api/{v}/info`+- **Search**: `GET|POST api/{v}/search` (returns bare `[{Id, Type}]`, Type: Folder=0 | File=1 | Bom=3 — you must follow up with info calls); `POST api/{v}/searchvariables` (variable-criteria search). https://help.solidworks.com/2024/english/api/pdmprowebapihelp/PDM%20Pro%20API_ws~r-api-%7BvaultName%7D-search~o-HttpGet.html+- **Folders**: `GET folders/{folderId}`, `/info`, `/browse` (children), `/datacard`; `POST folders/info` (bulk); `PUT folders/{parentFolderId}` (create); `DELETE folders/{folderId}?destroy=`+- **Files (read)**: `POST files/info` (bulk), `POST files/infofrompath`; `GET files/{fileId}/{version}` (+`/info`, `/info-extended`), `/history`, `/moves`, `/versions`, `/transitions`, `/configurations`, `/ActiveConfig`, `/variables` (per-config card values), `/datacard`, `/references?configId=`, `/allreferences`, `/whereused?configId=&anyVersion=`, `/download`, `/thumbnails`+- **Files (write)**: `POST files/CheckOut`, `files/UndoCheckOut`, `files/buildtree/checkout`, `files/buildtree/undo`; changeset flow: `GET changeset/create` → `PUT files/{changesetId}/upload` → `PUT files/{changesetId}/finishadd` / `PUT checkin/addfiles/{changesetId}` → `GET checkin/buildtree/{changesetId}` → `PUT checkin/{changesetId}/{overrideVersion}`; `POST files/{fileId}/datacard?folderId=` (save card variables, per-configuration payload); `DELETE files/{fileId}?destroy=`; `POST delete/computetree`; `PUT api/stage/{v}/{documentId}` (staging)+- **BOM**: `GET files/{fileId}/bominfo`; `GET bom/{bomTypeId}/{fileId}/{version}/{folderId}/computed?configId=&latest=`; `.../weldmentcutlist`; `GET bom/{bomDocumentId}/{version}/{folderId}/named`+- **Workflow/state**: `GET api/{v}/workflows`, `workflows/icons`; `GET state/{documentId}/transitions` (valid transitions for a file), `GET state/{transitionId}`, `GET state/{documentId}/{folderId}/{transitionId}/references`; `POST state/transitions` (bulk query); `POST state/{transitionId}/changestate?revoke=` (execute transition), `POST state/{transitionId}/HistoryComments`, `POST state/{transitionId}/DynamicNotificationUsers`+- **Users/groups**: `GET users`, `users/all`, `users/{userId}` (+`/info`, `/Extended` GET/PUT, `/Picture` GET/PUT/DELETE); `GET groups`, `groups/all`, `groups/{groupId}` (+`/info`)+- **Notifications**: `POST notifications`, `POST notifications/markRead`, `GET notifications?all=&pageNo=&pageSize=`+- **Async progress**: `GET progress/{guid}/status`, `GET progress/{guid}/result`+- **Hooks (2025+)**: `GET|POST configuration/hooks/url` (webhooks); `GET|PUT|DELETE configuration/hooks/dll` (add-in hook DLLs)++**Version history**: component ships ~2018 (EXALEAD OnePart / eDrawings mobile), installer-integrated 2019; endpoint docs published ~2021–2022; 2024 = 106 endpoints; **2025 = 113 (webhooks + add-in hooks + fileserverroot)**; 2026 unchanged vs 2025. The API is read/write throughout its documented life; growth has been incremental (Dassault's strategic investment is in 3DEXPERIENCE, not PDM).++---++## 8. Rate limits, pagination, gotchas++- **No documented rate limits** anywhere in the Web API docs. No documented pagination on search or browse — only the notifications endpoint has `pageNo`/`pageSize`. Large vaults ⇒ chunk queries yourself (per-folder browse, targeted search criteria).+- **Search returns only object IDs + types** — expect an N+1 pattern (search → bulk `files/info` POST → per-file `variables`/`bominfo`). Use the bulk `POST files/info` endpoint where possible.+- **JWT expiry is undocumented**; handle 401 by re-authenticating. https://bluebyte.biz/pdm-api-tips/a-quickstart-guide-with-the-solidworks-pdm-web-api/+- **`folderId` is required almost everywhere** (files can live in multiple folders via shared links); resolve and cache folder IDs.+- Default deployment is **HTTP on port 65453** — TLS is the customer's IIS problem; insist on HTTPS before any internet exposure.+- Docs are auto-generated with no OpenAPI spec; response models sometimes leak ASP.NET internals (`HttpResponseMessage` wrappers, redirect results). Budget for empirical testing against a live vault; SOLIDWORKS ships Postman collections in "Getting Started" (including `HooksManagement.postman_collection.json`).+- Webhook deliveries have a 15 s default timeout and no documented retry/signing — put a queue-backed receiver in front and verify payloads by calling back into the API.+- Version skew: features vary by customer's PDM year (webhooks need 2025+; many manufacturers run N-2). Vault schema/API is stable, but pin per-customer capability flags.++---++## 9. Onshape contrast & competitor sync direction++- **Onshape** is the cloud-native counterexample: full REST API for everything plus first-class **webhooks** (notifications on events such as a release), enabling genuine event-driven cloud↔cloud ERP integration with zero customer infrastructure. https://onshape-public.github.io/docs/api-intro/ , https://www.onshape.com/en/features/integrations+- Nothing in the PDM world matches that: PDM's 2025 webhooks still require an on-prem IIS Web API server that the customer must expose, and (per §4) appear scoped to API-mediated operations. The pragmatic PDM equivalent of "webhook on release" remains an on-prem hook (add-in/task/Dispatch/polling service) that pushes outbound.+- **Competitor positioning**: all major connectors (CADLink, CAD2BOM, CustomTools, OdooPLM) market "bidirectional," but functionally it decomposes to: **ERP→engineer lookup** (browse/validate item master, descriptions, inventory from inside CAD/PDM before commit) + **CAD→ERP authoritative push of item master + BOM (+ routings) triggered manually or on release-state transition**. The ERP never writes back into CAD geometry/BOM; at most it standardizes descriptions/part numbers on the card. That release-triggered one-way push is the industry-expected behavior Carbon should replicate.++---++## Implications for Carbon++Ranked architecture options for pulling item metadata, BOMs, revisions, and previews from customer PDM Professional vaults:++**1. On-prem connector agent (recommended primary, long-term).** A small Windows service the customer installs on a vault-connected machine (or the task host): logs into the vault (COM API via a local vault view, service account with Contributor/Viewer seat), detects release transitions (PDM add-in `OnCmd` post-state hook and/or periodic state-based search sweep — CADLink's exact pattern), then pushes outbound HTTPS to Carbon's API: card variables per configuration (part number, description, revision), computed/named BOM rows, thumbnail PNG (Document Manager `GetPreviewPNGBitmapBytes` or PDM preview bitmap), and released PDF/STEP produced by the customer's existing convert tasks. Pros: works on every PDM version incl. Standard (COM), no inbound firewall changes, event-fidelity for desktop-originated releases, matches what the market already trusts. Cons: Carbon ships/maintains a Windows .NET (Framework, COM-interop) installer — a real but well-understood engineering cost.++**2. Direct-to-Web-API integration (secondary / low-friction tier).** For PDM Professional 2022+ customers willing to expose (or VPN/tunnel) the Web API server: Carbon cloud authenticates as a service vault user and polls `search`/`state` for newly released files, then reads `variables`, `bom/.../computed|named`, `thumbnails`, `download`. On 2025+, additionally register webhooks (`configuration/hooks/url`) for `OnPostChangeState` as an acceleration signal — but keep polling as ground truth until webhook coverage of desktop transitions is proven on a live vault. Pros: zero installed software. Cons: customer must run/expose an optional IIS component over HTTPS, Professional-only, undocumented token TTL/limits, N+1 read patterns, weaker eventing.++**3. Hybrid (likely end-state).** Ship option 1's agent but implement its vault access against the *localhost* Web API where available (cleaner HTTP/JSON code path, COM fallback for Standard/older versions); agent handles eventing + outbound push, Carbon cloud handles mapping/UI. This maximizes shared code with option 2.++**4. Partner/middleware route (opportunistic).** Get Carbon listed as a CADLink-supported ERP target (QBuild integrates "any ERP"; Carbon's REST API is exactly what they consume) — instantly serves customers who already own CADLink, at zero engineering cost, in exchange for margin and no control of UX.++Cross-cutting product guidance: model the sync as **CAD→ERP one-way push on release** (create/update Carbon items, revisions, and an engineering BOM as a candidate for the manufacturing BOM), with read-only ERP-side lookups surfaced back to engineering later; key on the data card part-number variable per configuration (each SW configuration is potentially a distinct item); store the PDM fileId/configId/version as the external reference for idempotent upserts; ingest previews as thumbnails plus released PDF/STEP documents; and gate scope to file-mode vaults (ignore PDM "Items").diff --git a/.ai/specs/2026-08-04-solidworks-pdm-integration.md b/.ai/specs/2026-08-04-solidworks-pdm-integration.mdnew file mode 100644index 0000000000..6c46acc8fa--- /dev/null+++ b/.ai/specs/2026-08-04-solidworks-pdm-integration.md@@ -0,0 +1,248 @@+# SolidWorks PDM Integration++> Status: draft+> Author: Claude (with Brad Barbin)+> Date: 2026-08-04+> Research: `.ai/research/solidworks-pdm-integration.md`+> Plan: `.ai/plans/2026-08-04-solidworks-pdm-integration.md`+> Precedent: the Onshape integration (`packages/ee/src/onshape/`, `packages/jobs/src/inngest/functions/integrations/onshape-*.ts`, `apps/erp/app/routes/api+/integrations.onshape.*`, `apps/erp/app/routes/api+/webhook.onshape.$companyId.ts`)++## TLDR++Add a `solidworks-pdm` integration that mirrors the Onshape integration's two features against a customer's on-prem SOLIDWORKS PDM Professional vault, reached through the **PDM Web API** (the REST server that ships with PDM Professional, IIS-hosted, JWT auth): **(A) manual BOM sync** — from the item BOM explorer, pick a vault assembly + configuration, preview its computed BOM, and sync it into a Carbon make-method tree via the existing `sync` edge function (new discriminated-union variant); **(B) release asset sync** — a polling Inngest job (cron ground truth; the PDM 2025+ webhook is only a poll-now hint) finds files that entered the customer's "Released" workflow state, matches data-card part number + revision to `item.readableIdWithRevision`, and link-only-attaches the API thumbnail, a co-located converted drawing PDF, and a co-located converted STEP model (fanning out to `carbon/model-optimize`). No new tables: config + credentials live in `companyIntegration.metadata` (validated by a new `integration` catalog jsonschema), and external references live in `externalIntegrationMapping`. Sync is strictly PDM → Carbon; Carbon never writes to the vault. An on-prem COM agent (the CADLink-style architecture) is explicitly deferred.++## Problem Statement++Carbon's only CAD integration is Onshape — cloud-native, webhook-driven. The majority of job-shop and mid-market manufacturers run SOLIDWORKS with PDM Professional on-prem. Today those customers rekey part numbers, descriptions, revisions, and BOMs from PDM into Carbon by hand, and released drawings/models never reach the Carbon item record. The industry-standard behavior (research §9: CADLink, CAD2BOM, CustomTools) is a one-way, release-triggered push of item master + BOM + released documents from CAD/PDM into the ERP — Carbon should offer the same, packaged like the Onshape integration so all the existing plumbing (integration registry, settings UI, `companyIntegration`, `externalIntegrationMapping`, Inngest asset pipeline) is reused.++Concretely, a customer releases `BRKT-1042.SLDDRW` rev C in PDM: nothing happens in Carbon. With this integration, within one poll cycle Carbon item `BRKT-1042` rev C gets the released drawing PDF attached, the STEP model becomes its viewable `modelUpload`, and the vault thumbnail becomes its preview — exactly what the Onshape release sync does for Onshape customers today.++## Proposed Solution++### Architecture++Cloud-direct: the Carbon backend (Inngest jobs + ERP loaders) talks HTTPS to the customer's PDM **Web API server** (`https://pdm.example.com:65453/api/{vaultName}/…`), authenticating as a dedicated PDM service account (`POST /api/{vaultName}/authenticate` → JWT; TTL undocumented, so every call path re-authenticates once on 401). This is the same shape as the Onshape integration — a REST client in `packages/ee`, per-company credentials in `companyIntegration.metadata` — with two deliberate differences forced by PDM's nature (research §2, §4):++1. **Credentials form instead of OAuth.** PDM has no OAuth; the settings form collects `baseUrl`, `vaultName`, `username`, `password` (the `password` field type already exists in `IntegrationSetting`). No `onClientInstall` popup, no `install.ts`/`oauth.ts` routes.+2. **Polling instead of webhooks as ground truth.** PDM webhooks exist only on 2025+, are unsigned, and are not proven to fire for desktop-client transitions (research §4). A cron-driven Inngest poll is authoritative; the webhook receiver merely triggers an immediate poll.++Supported: PDM **Professional** with the Web API server reachable from Carbon's backend over HTTPS. Unsupported in v1: PDM Standard (no Web API), on-prem agent connectivity, writes back to the vault.++### Feature A — manual BOM sync (parity with `OnshapeSync.tsx`)++In the item BOM explorer (`apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx`), when the `solidworks-pdm` integration is active, a `SolidWorksPdmSync` widget (clone of `OnshapeSync.tsx`) lets the user:++1. Search the vault for a file. `POST /api/{v}/search` returns only `[{ Id, Type }]` (research §7), so the loader hydrates the first 200 file-type ids via bulk `POST files/info`, filters to `.sldasm`/`.sldprt`, and returns at most 50 candidates. Pick one.+2. Pick a configuration (`GET files/{fileId}/{version}/configurations`, defaulting to the active configuration).+3. Fetch the **computed BOM** for that configuration at the latest checked-in version (`GET files/{fileId}/bominfo` → `GET bom/{bomTypeId}/{fileId}/{version}/{folderId}/computed?configId=`), normalized app-side into rows `{ partNumber, description, revision, quantity, unitOfMeasure, level, fileId, configId, folderId }` using the configured `partNumberVariable`/`revisionVariable` column names. The normalizer **rejects malformed responses before any sync**: exactly one case-insensitive column must match `partNumberVariable` (zero or multiple → error), the revision column must resolve, every quantity must be a finite non-negative number, and tree nesting must be consistent — a later validator cannot repair a wrong column pick or a mis-flattened tree. Preview the tree.+4. Sync: POST to `/api/integrations/solidworks-pdm/sync`, which invokes the `sync` edge function (`packages/database/supabase/functions/sync/index.ts`) with a new `type: "solidworks-pdm"` discriminated-union variant. The edge function reuses the existing tree-building logic (create/update `item` + `part`, build the `makeMethod`/`methodMaterial` tree) and writes `externalIntegrationMapping` rows: integration `"solidworks-pdm"` on the root item (`{ fileId, configId, folderId }`) and `"solidworksPdmData"` per item (raw normalized BOM row as metadata) — the same two-mapping pattern as `"onshape"`/`"onshapeData"`.++The widget stores/reads its saved file + configuration and `lastSyncedAt` from `externalIntegrationMapping`, exactly like `OnshapeSync.tsx` does.++### Feature B — release asset sync (parity with `onshape-revision-sync`/`onshape-backfill`)++Link-only: never creates items. Three triggers feed one per-company poll job, which fans out per file:++- **Cron** `solidworks-pdm-release-cron` (`{ cron: "*/30 * * * *" }`, pattern: `update-exchange-rates.ts`): iterates `companyIntegration` rows where `id = 'solidworks-pdm'`, `active = true`, and `metadata.assetSyncEnabled = true`, and sends one `carbon/solidworks-pdm-release-poll` event per company.+- **Webhook receiver** `apps/erp/app/routes/api+/webhook.solidworks-pdm.$companyId.ts` (pattern: `webhook.onshape.$companyId.ts`): accepts the PDM 2025+ `OnPostChangeState` webhook. Because payloads are unsigned, the payload is never trusted — a valid-looking event on an active, asset-sync-enabled company just triggers `carbon/solidworks-pdm-release-poll` (`mode: "incremental"`). Response contract (matches the Onshape receiver): unknown or inactive company → 400 "Integration not configured"; active + asset-sync-enabled company with a parseable JSON body → 200 (poll triggered); non-JSON body → 400.+- **Backfill action** — an `actions` entry on the integration config (`enabledWhenSetting: "assetSyncEnabled"`, pattern: Onshape's backfill) POSTs `/api/integrations/solidworks-pdm/backfill`, which triggers the poll with `mode: "backfill"` (ignores the cursor).++**Poll job** `solidworks-pdm-release-poll` (per company; concurrency key `companyId` limit 1; retries 10 like `onshape-backfill`):++1. Enumerate files **currently in** the configured released state. Default path (`metadata.searchCapability` unset or `"folder-sweep"`): recursive folder sweep (`folders/{id}/browse` + bulk `POST files/info`) filtered on current state. The search endpoint's workflow-state criteria (`"state-search"`) is an opt-in optimization used only when `metadata.searchCapability` is **explicitly** set to `"state-search"` after live-vault validation — never inferred at runtime, because its criteria syntax is undocumented and a silently-empty result would be indistinguishable from "nothing released" (research §8).+2. Dedupe against the `"solidworks-pdm-release-*"` mapping rows (written only by a *successful* file-sync, below): a candidate fans out only if no mapping already records its `{ fileId, version }`. There is **no modified-date cursor** — a release that doesn't bump the file's modified date is still caught, and a failed file-sync self-heals on the next sweep because its mapping row was never written. `metadata.lastReleaseSyncAt` is informational only (last completed sweep time), never a correctness gate.+3. For each new candidate, send `carbon/solidworks-pdm-file-sync` (concurrency key `fileId` limit 1; idempotency key `{companyId}:{fileId}:{version}`).++`mode: "backfill"` (the settings action) and `mode: "incremental"` (cron/webhook) run the same sweep — dedupe makes it idempotent; backfill exists as the manual "sweep now" trigger. This is **current-state synchronization, best-effort by design**: a file that is released and then transitions onward between sweeps is not seen (per-file transition history exists in the API but is prohibitively chatty to poll); the backfill action plus the next release of that file are the recovery paths, and the docs state this.++**File-sync job** `solidworks-pdm-file-sync` (per file; pattern: `onshape-revision-sync.ts` + `onshape-sync-element.ts` + `onshape-attach.ts`):++1. Resolve the active configuration id via `GET files/{fileId}/{version}/ActiveConfig`, then read the per-configuration data-card variables (`GET files/{fileId}/{version}/variables`) and select the `ConfigInfo` whose `ConfigurationId` matches; any variable missing there falls back to the `@` tab entry. Extract `partNumberVariable` and `revisionVariable`; the resolved `configId` is carried into the mapping metadata.+2. Match to a Carbon item on `readableIdWithRevision` using the same key convention as `onshape-matching.ts` (`releaseKey`); for drawings (`.slddrw`), also apply the shared-number-suffix heuristic (`sharedNumberSuffix`). No match → skip (logged, not an error).+3. Idempotency check, **keyed per file class** so a released part and its drawing (which match the same item) never clobber each other: integration `"solidworks-pdm-release-model"` (`.sldprt`/`.sldasm`) or `"solidworks-pdm-release-drawing"` (`.slddrw`), entityType `"item"` — the table's uniqueness is `(entityType, entityId, integration, companyId)`, so the two classes coexist as two rows. Skip when the incoming `version` is **≤** the recorded version (guards both replays and out-of-order polls overwriting newer state with older).+4. Attach (mirroring `onshape-attach.ts`):+ - `.sldprt`/`.sldasm`: co-located converted model — a file in the same folder with the same base name and `.step`/`.stp` extension (produced by the customer's PDM convert task, research §6) → download (size-capped like `downloadExternalDataToFile`) → `modelUpload` on the item → send `carbon/model-optimize`; API thumbnail (`GET files/{fileId}/{version}/thumbnails`) → `modelUpload.thumbnailPath`, with `carbon/model-thumbnail` as fallback.+ - `.slddrw`: co-located `.pdf` with the same base name → attach as item `document` (sourceDocument identifies SolidWorks PDM).+ - Native SOLIDWORKS files are **never** downloaded (Carbon can't render them; no translation API exists in PDM).+5. Upsert the class-specific `"solidworks-pdm-release-*"` mapping row with metadata `{ fileId, version, configId, fileName, stateName: releasedStateName }` plus `lastSyncedAt`/`remoteUpdatedAt` — `stateName` is what the UI status badge renders.++### Integration registration & settings++`packages/ee/src/solidworks-pdm/config.tsx` via `defineIntegration` (pattern: `onshape/config.tsx`):++- `id: "solidworks-pdm"`, `name: "SolidWorks PDM"`, `category: "CAD"`, inline SVG logo, `active: true` (no global env vars — credentials are wholly per-company, like the pre-OAuth Onshape model).+- Settings (groups **Connection** / **Release sync**):+ | name | type | required | default |+ |---|---|---|---|+ | `baseUrl` | text | yes | — (HTTPS enforced by zod; `http://` allowed only for `localhost`) |+ | `vaultName` | text | yes | — |+ | `username` | text | yes | — |+ | `password` | password | yes | — |+ | `releasedStateName` | text | no | `"Released"` |+ | `partNumberVariable` | text | no | `"Number"` |+ | `revisionVariable` | text | no | `"Revision"` |+ | `assetSyncEnabled` | switch | no | `false` |+- `actions`: the backfill button (above).+- Server hooks in `packages/ee/src/hooks.server.ts` registry:+ - `onInstall`: verify connectivity (authenticate + `GET api/{v}/info`); record `metadata.webApiVersion` (`GET api/version/webapi`); if `assetSyncEnabled` and version ≥ 2025, best-effort register the `OnPostChangeState` webhook at `/api/webhook/solidworks-pdm/{companyId}` (`POST configuration/hooks/url`) — failure logs and continues (polling covers it). Note: hook registration requires the PDM **"Can administrate add-ins"** permission on the service account, which Viewer/Contributor seats do not imply — the docs list it as an *optional* extra grant for webhook acceleration; vault data flow remains read-only PDM → Carbon regardless.+ - `onUninstall`: best-effort webhook deregistration.+ - `onHealthcheck`: authenticate + vault info (cached via the existing Redis health cache).++Metadata shape (validated by the new `integration.jsonschema` when `active = true`, enforced by the existing `verify_integration` trigger):++```jsonc+{+ "baseUrl": "https://pdm.example.com:65453",+ "vaultName": "Engineering",+ "username": "carbon-svc",+ "password": "…",+ "releasedStateName": "Released",+ "partNumberVariable": "Number",+ "revisionVariable": "Revision",+ "assetSyncEnabled": false,+ // written by the system, not the form:+ "webApiVersion": "2025", // optional+ "searchCapability": "state-search", // optional+ "lastReleaseSyncAt": "2026-08-04T12:00:00.000Z" // optional+}+```++Keys are flat (not nested under `credentials`) because the generic `IntegrationForm` writes settings fields flat into metadata; the settings action's merge-don't-replace behavior (proven by the Onshape playbook) preserves system-written keys.++### Client++`packages/ee/src/solidworks-pdm/lib/client.ts` (pattern: `onshape/lib/client.ts`): `SolidWorksPdmClient` (axios, JWT held in-memory, single re-auth retry on 401), error types `SolidWorksPdmApiError` / `SolidWorksPdmAssetTooLargeError`, and factory `getSolidWorksPdmClient(client, companyId)` reading `companyIntegration` (returns `{ client, error }`, never throws). Methods: `authenticate`, `getWebApiVersion`, `getVaultInfo`, `search`, `getFilesInfo` (bulk POST), `getFileConfigurations`, `getActiveConfig`, `getFileVariables`, `getBomInfo`, `getComputedBom`, `browseFolder`, `getThumbnail` (follows the redirect; enforces the same `maxBytes` cap as downloads since the bytes are buffered), `downloadFileToTemp` (streamed, `maxBytes` cap), `registerWebhook`/`getWebhooks`/`deleteWebhook`. Exported from the `@carbon/ee` barrel as `SolidWorksPdm` + `SolidWorksPdmLogo`, client via subpath (mirroring `@carbon/ee/onshape`).++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Connectivity | Cloud-direct to the customer-exposed PDM Web API over HTTPS | Mirrors the Onshape architecture the user asked for; zero installed software. The industry-standard on-prem COM agent (CADLink pattern, research §2) is a separate Windows-service product — deferred, and the client/matching/attach layers built here are reusable by it |+| Auth | Vault service-account username/password in `companyIntegration.metadata`; JWT fetched lazily, one re-auth retry on 401 | PDM Web API has no OAuth; token TTL is undocumented (research §1.2). Same storage pattern as every other Carbon integration's secrets |+| Release detection | Inngest cron poll every 30 min is ground truth; PDM 2025+ webhook only triggers an immediate poll | Webhooks are 2025+-only, unsigned, 15 s timeout, and unproven for desktop-originated transitions (research §4). Mapping-based dedupe + idempotent attach makes the poll safe to re-run regardless |+| Sync direction | PDM → Carbon only; Carbon never writes to the vault | Matches Onshape and the CAD→ERP release-push semantics every competitor connector implements (research §9) |+| Asset-sync matching | Data-card `partNumberVariable` + `revisionVariable` (active configuration) → `item.readableIdWithRevision`; link-only, never creates items | Exact mirror of Onshape feature B's contract (`onshape-matching.ts` `releaseKey`/`sharedNumberSuffix` reused) |+| Item creation | Only via manual BOM sync (feature A), through the existing `sync` edge function with a new union variant | Mirrors Onshape feature A; keeps privileged item/make-method creation in the one existing edge function |+| Models & drawings | Co-located convert-task outputs only (same folder + same base name: `.step`/`.stp`, `.pdf`); API thumbnail always; native SLDPRT/SLDASM/SLDDRW never downloaded | PDM has no translation API (unlike Onshape); release-time convert tasks are the universal PDM practice (research §6). Carbon's viewer/pipeline consumes STEP, not native SW |+| Configuration granularity | Active configuration only in v1 | Per-configuration item expansion (one SW file → N items) is a real PDM pattern but multiplies matching ambiguity; deferred with the mapping metadata (`configId`) already recorded to support it later |+| BOM type | Computed BOM at latest checked-in version, `configId`-scoped | Named-BOM support deferred; computed is always present and is what the `bominfo` → `computed` endpoints serve directly |+| PDM Standard | Unsupported | No Web API exists for Standard (research §1.1); only reachable via the deferred agent |+| Data model | No new tables — `integration` catalog seed row + `companyIntegration.metadata` + `externalIntegrationMapping` | The Onshape integration proves the existing plumbing suffices; keeps DB footprint to one idempotent seed migration |+| Idempotency | `externalIntegrationMapping` rows per file class (`"solidworks-pdm-release-model"` / `"-drawing"`) record last-synced `{fileId, version}` per item, with a version-≤ skip guard; mapping presence (not a date cursor) is what dedupes the poll | Makes sweeps re-runnable and self-healing (failed syncs retry next sweep), lets a part and its drawing coexist on one item, and blocks out-of-order overwrites; Onshape didn't need this (webhook-driven) but polling does |+| Heuristic 1 (multi-tenancy) | N/A — no new tables; every touched row (`companyIntegration`, `externalIntegrationMapping`, `document`, `modelUpload`) already carries `companyId` | Existing schema |+| Heuristic 2 (service shape) | `getSolidWorksPdmClient` returns `{ client, error }`; route loaders/actions use existing settings service fns (`getIntegration`, `upsertCompanyIntegration`) | Convention |+| Heuristic 3 (RLS) | N/A — no new tables | Existing policies cover all touched tables |+| Heuristic 4 (permissions) | Every new route copies the `requirePermissions` scope from its exact Onshape counterpart (settings/backfill: settings scopes; sync/pickers: parts scopes; webhook: public with per-company active-integration gate) | Onshape's scopes are the reviewed precedent |+| Heuristic 5 (forms) | Settings rendered by the generic `IntegrationForm` (ValidatedForm) from `settings[]` + zod `schema` — no custom form | Framework already does it |+| Heuristic 6 (module layout) | No new ERP module; integration code follows the per-integration directory convention in `packages/ee/src/solidworks-pdm/` | Convention (`packages/ee/src/onshape/` precedent) |+| Heuristic 7 (backward compat) | Additive only: new union variant in the `sync` edge function payload, new events, new catalog row. No existing contract changes | The `sync` function's discriminated union is designed for this |++## Data Model Changes++No new tables. One idempotent seed migration (created via `pnpm db:migrate:new solidworks-pdm-integration`, pattern: `20250410120243_onshape-integration.sql` + `20260703165330_onshape-asset-sync-jsonschema.sql`):++```sql+-- Seed the integration catalog row (idempotent; jsonschema validates metadata+-- via the existing verify_integration trigger when active = true)+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";+```++(Verified: since `20241006185904_integration-refactor.sql` the `integration` table has exactly two columns, `id` and `jsonschema` — the INSERT above matches.)++`externalIntegrationMapping` gains rows with integration values `"solidworks-pdm"`, `"solidworksPdmData"`, `"solidworks-pdm-release-model"`, `"solidworks-pdm-release-drawing"` — the column is free TEXT; no migration needed.++## API / Service Changes++New files (all patterns are the Onshape counterparts):++- `packages/ee/src/solidworks-pdm/config.tsx` — `defineIntegration` config + logo.+- `packages/ee/src/solidworks-pdm/lib/client.ts` — client + factory (see above).+- `packages/ee/src/solidworks-pdm/lib/data.ts` — `solidWorksPdmDataValidator` (zod) for normalized BOM rows.+- `packages/ee/src/solidworks-pdm/hooks.server.ts` — `onInstall`/`onUninstall`/`onHealthcheck` + webhook register/deregister helpers.+- Registry edits: `packages/ee/src/index.ts` (add to `integrations` array + barrel exports), `packages/ee/src/hooks.server.ts` (server-hooks map).+- Routes under `apps/erp/app/routes/api+/`:+ - `integrations.solidworks-pdm.files.ts` (GET: vault file search for the picker)+ - `integrations.solidworks-pdm.files.$fileId.configurations.ts` (GET)+ - `integrations.solidworks-pdm.files.$fileId.bom.ts` (GET: normalized computed BOM)+ - `integrations.solidworks-pdm.sync.ts` (POST: invoke `sync` edge fn, write mappings)+ - `integrations.solidworks-pdm.backfill.ts` (POST: admin, gated on `assetSyncEnabled`, triggers backfill)+ - `webhook.solidworks-pdm.$companyId.ts` (POST: public receiver → poll trigger)+- Edge function: `packages/database/supabase/functions/sync/index.ts` — add the `type: "solidworks-pdm"` variant to `payloadValidator` and a handler that maps normalized rows into the existing item/make-method tree builder.+- Jobs (`packages/jobs/src/inngest/functions/integrations/`): `solidworks-pdm-release-cron.ts`, `solidworks-pdm-release-poll.ts`, `solidworks-pdm-file-sync.ts`, helpers `solidworks-pdm-matching.ts` (+ `.test.ts`) and `solidworks-pdm-attach.ts`; registered in `packages/jobs/src/inngest/index.ts`.+- Events: `carbon/solidworks-pdm-release-poll` and `carbon/solidworks-pdm-file-sync` in `packages/lib/src/events.ts` + `packages/lib/src/trigger.ts` (`taskToEvent`).+- Path helpers in `apps/erp/app/utils/path.ts` (`solidWorksPdmFiles`, `solidWorksPdmConfigurations`, `solidWorksPdmBom`, `solidWorksPdmSync`, `solidWorksPdmBackfill`).++## UI Changes++- `apps/erp/app/components/SolidWorksPdmSync.tsx` — clone of `apps/erp/app/components/OnshapeSync.tsx` (file search combobox → configuration combobox → BOM preview tree → Fetch/Sync/Save buttons).+- `apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx` — mount `SolidWorksPdmSync` beside the existing `OnshapeSync` mount, each gated on its integration being active.+- Status badge: `apps/erp/app/components/Icons.tsx` gains `SolidWorksPdmStatus`, mirroring `OnshapeStatus`. Source of truth for its fields: `stateName` comes from the `"solidworks-pdm-release-*"` mapping metadata (the only producer that persists workflow state — see file-sync step 5); `revision` comes from the `solidworksPdmData` BOM-row metadata. When no release mapping exists yet, the badge shows revision only.+- Integration settings page needs **no custom UI** — the generic `IntegrationsList`/`IntegrationForm` renders the fields, groups, and backfill action from the config.++## Acceptance Criteria++- [ ] "SolidWorks PDM" appears in `/x/settings/integrations` with logo and description; Install opens the settings form with Connection + Release sync groups; submitting without `baseUrl`/`vaultName`/`username`/`password` shows field errors; an `http://` (non-localhost) `baseUrl` is rejected.+- [ ] With a fixture `companyIntegration` row (fake credentials, pattern: `.ai/playbooks/onshape-asset-sync.md`), the settings page renders all fields, the "Sync released assets" switch, and the backfill action button appears only when `assetSyncEnabled` is on; saving the form preserves `username`/`password` and system-written metadata keys (verified by SQL inspection of the merged metadata).+- [ ] `POST /api/integrations/solidworks-pdm/backfill` returns 200 and triggers the poll event when `assetSyncEnabled = true`; returns 400 when disabled.+- [ ] `POST /api/webhook/solidworks-pdm/{companyId}` returns 200 and triggers a poll for a `ChangeState`-shaped payload on an active company; returns 400 for an unknown company; never trusts payload contents (no attach happens without a poll).+- [ ] With the integration active, the SolidWorks PDM sync widget renders in the item BOM explorer; with it inactive, it does not.+- [ ] `solidworks-pdm-file-sync`, given a released `.sldprt` whose active-config part number + revision matches an item, attaches thumbnail + co-located STEP as `modelUpload` and sends `carbon/model-optimize`; a second run with the same `{fileId, version}` skips, and a run with an *older* version also skips (version-≤ guard). A released part and its drawing targeting the same item produce two coexisting mapping rows (`-model` / `-drawing`) without clobbering each other. Given a `.slddrw` with a co-located PDF, the PDF lands as an item document. No matching item → skip without error. (Proven by unit tests over the matching/attach decision logic; live-vault proof is flagged as environment-gated.)+- [ ] The BOM normalizer rejects malformed computed-BOM responses — zero or multiple part-number column matches, non-finite quantities, inconsistent nesting — with an error surfaced in the picker, and the sync edge function is never invoked with such data (unit-tested).+- [ ] `pnpm --filter @carbon/jobs test` passes with new `solidworks-pdm-matching.test.ts` covering: release-key matching, drawing shared-suffix matching, co-located-file basename convention, BOM row normalization, and idempotency skip.+- [ ] Scoped typechecks pass: `@carbon/ee`, `@carbon/jobs`, `erp`; the `sync` edge function's own-file deno errors do not increase.+- [ ] The `sync` edge function accepts a `type: "solidworks-pdm"` payload and produces the same item/make-method tree shape as an equivalent Onshape payload (unit-level or fixture-level proof).++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| Web API search may not filter by workflow state/date (docs don't say) | High | `folder-sweep` is the default and the only auto-selected path; `state-search` is opt-in per company (`searchCapability` set explicitly after live-vault validation), so an undocumented search quirk can never silently drop releases |+| Current-state polling misses a file that is released and transitions onward between sweeps | Low | Documented as best-effort current-state sync; per-file transition history is too chatty to poll; backfill + the file's next release are the recovery paths |+| No live vault available for development/verification | High | All matching/normalization/idempotency logic is pure and unit-tested; gating/settings/webhook paths verified via fixture rows (Onshape playbook pattern); live sync explicitly flagged environment-gated in the PR |+| JWT TTL undocumented | Low | Single re-auth retry on 401 built into the client |+| Customer exposes plain HTTP (PDM default is HTTP:65453) | Med | zod rejects non-HTTPS `baseUrl` (localhost exempt for dev); docs state the HTTPS requirement |+| Unsigned PDM webhooks could be spoofed | Med | Receiver treats payloads as poll-now hints only; all real data comes from authenticated API calls |+| Poll sweep cost on very large vaults (N+1: browse → info → variables, full sweep every cycle since dedupe is mapping-based) | Med | Bulk `POST files/info`, mapping dedupe keeps fan-out to new releases only, per-company concurrency 1, 30-min cadence; backfill retries 10 to ride out slowness |+| PDM license seat consumption by the service account is undocumented | Low | Documented prerequisite: one dedicated Viewer/Contributor seat; surfaced in the integration description/docs |+| Customer PDM version skew (webhooks 2025+, Web API maturity varies) | Low | `webApiVersion` capability flag; webhook registration best-effort; polling works on all Web-API-era versions |+| Plaintext service-account password in `companyIntegration.metadata` | Med | Same trust model as every existing integration's tokens (RLS-guarded settings scopes, JSON column); flagged for a future integration-wide secrets encryption pass |++## Open Questions++> All resolved autonomously per the combined spec+plan request (standing feedback: accept recommendations, document, surface for veto). Veto any of these and the affected sections revise.++- [x] **Architecture: cloud-direct Web API vs on-prem COM agent vs CADLink partnership?** Matters because it defines the supported customer set (Web API ⇒ PDM Professional 2022-ish+ with an internet-reachable IIS component) and the engineering shape. — **Autonomous:** cloud-direct Web API for v1: it mirrors the Onshape architecture (the explicit ask), needs no new product surface (no Windows installer), and its client/matching/attach layers are reusable by a future agent. The agent (research option 1/3) and a CADLink listing (option 4) are recorded as future work, not designed here.+- [x] **Scope: both Onshape-parity features, or asset sync only?** Matters for plan size. — **Autonomous:** both — "similarly to how we do the onshape integration" implies parity, and feature A reuses the existing `sync` edge function almost wholesale. The plan phases them (A before B) so either can ship alone.+- [x] **Release detection: webhook-first or poll-first, and at what cadence?** — **Autonomous:** poll-first (30-min cron), webhook as poll-now acceleration only, per the research's explicit warning that PDM 2025 webhook coverage of desktop transitions is unverified and payloads are unsigned.+- [x] **How do models/drawings reach Carbon given PDM has no translation API?** — **Autonomous:** rely on the customer's release-time convert tasks producing co-located `.step`/`.pdf` with the same base name (the universal PDM practice, research §6); sync the API thumbnail unconditionally. The convention is fixed in v1; making the location/naming configurable is future work.+- [x] **Per-configuration items: one SW file can hold N configurations with N part numbers — sync which?** — **Autonomous:** active configuration only in v1 (with `@`-tab fallback); `configId` is recorded in mappings so per-config expansion can be added without rework.+- [x] **Computed vs named BOM for feature A?** — **Autonomous:** computed only in v1 — always present, directly served by the API; named-BOM (the "BOM of record" pattern some customers use) is a documented fast-follow.+- [x] **Is PDM Standard supported?** — **Autonomous:** no — it has no Web API; only the deferred agent could serve it. Stated in the integration description.+- [x] **Where do vault credentials live?** — **Autonomous:** flat keys in `companyIntegration.metadata` validated by the catalog jsonschema — the established pattern for every integration's secrets (Onshape tokens live there today). The plaintext-at-rest concern is a pre-existing platform property, flagged in Risks rather than solved here.+- [x] **Should install auto-register the PDM webhook?** — **Autonomous:** best-effort on 2025+ vaults when asset sync is enabled (mirroring `ensureOnshapeReleaseWebhook`), non-fatal on failure since polling is authoritative.++## Changelog++- 2026-08-04: Created. Combined spec+plan request; all open questions resolved autonomously (recommendation-accepted mode) and listed above for veto. Research at `.ai/research/solidworks-pdm-integration.md`; plan at `.ai/plans/2026-08-04-solidworks-pdm-integration.md`.+- 2026-08-04: Revised per CodeRabbit review (PR #1331): poll dedupe is mapping-based (no modified-date cursor — releases without a modified-date bump are no longer missable, failed file-syncs self-heal); `folder-sweep` is the default discovery path with `state-search` strictly opt-in; release mappings split per file class (`-model`/`-drawing`) with a version-≤ skip guard; active-config resolution pinned to `GET /ActiveConfig` + `@`-tab fallback; picker hydrates search ids via bulk `files/info` with result caps; BOM normalizer must reject malformed responses pre-sync; `getThumbnail` gets the `maxBytes` cap; `SolidWorksPdmStatus` source of truth defined (`stateName` from release mappings); webhook registration privilege ("Can administrate add-ins") documented; webhook receiver response contract made explicit.