diff --git a/cadworld-adminapi/docs/admin-api.md b/cadworld-adminapi/docs/admin-api.md
index 3c4d82c..2323ef9 100644
--- a/cadworld-adminapi/docs/admin-api.md
+++ b/cadworld-adminapi/docs/admin-api.md
@@ -2,6 +2,8 @@
后台保留组件库、用户管理、操作日志三个模块。以下路径以 `/admin-api` 为前缀,默认服务地址 `http://127.0.0.1:8992`。
+用户端匹配与拼装接口由独立的 `cadworld-api` 服务提供,默认端口8991,详见[用户端 API 文档](../../cadworld-api/docs/api.md)。用户端默认组件、替代候选和详情同时返回 `bomList`、`urdfInfo`,通过编码访问组件,模型直接使用公开OSS/CDN地址。
+
## 1. 通用约定
JSON 请求设置 `Content-Type: application/json`。当前没有登录认证,操作人来自 `APP_ADMIN_OPERATOR_ID / APP_ADMIN_OPERATOR_NAME`,默认 `0 / TEST_OPERATOR`。上传令牌与该操作人绑定。
diff --git a/cadworld-api/docs/api.md b/cadworld-api/docs/api.md
new file mode 100644
index 0000000..6a133db
--- /dev/null
+++ b/cadworld-api/docs/api.md
@@ -0,0 +1,640 @@
+# 用户端组件匹配与拼装 API(前端联调文档)
+
+本文说明前端如何提交拼装需求、展示匹配结果、切换替代组件及加载模型。示例编码和模型域名仅用于说明,实际结果取决于组件库。
+
+## 1. 接口总览
+
+本地默认服务地址:`http://127.0.0.1:8991`。线上地址由部署环境提供。
+
+| 方法 | 路径 | 用途 |
+| --- | --- | --- |
+| POST | `/api/robot-matches` | 按需求匹配组件,返回默认拼装方案和兼容替代组件 |
+| GET | `/api/components/{componentCode}` | 按组件编码获取详情,包括 BOM、URDF 信息和模型地址 |
+
+当前两个接口无需登录凭证。组件使用 `componentCode` 标识,不返回数据库 ID。模型通过响应中的公开 OSS/CDN 地址加载。
+
+## 2. 请求与通用返回
+
+POST 请求头:
+
+```http
+Content-Type: application/json
+X-Request-Id: frontend-match-001
+```
+
+`X-Request-Id` 可选,用于联调排查;省略时后端生成。响应头和响应体均返回请求编号。
+
+```json
+{
+ "code": "OK",
+ "message": "success",
+ "data": {},
+ "requestId": "frontend-match-001"
+}
+```
+
+| 字段 | 类型 | 说明 |
+| --- | --- | --- |
+| `code` | string | `OK` 表示接口执行成功;其他值为错误编码 |
+| `message` | string | 成功时为 `success`,失败时为错误说明 |
+| `data` | object / null | 成功时为接口数据,失败时为 null |
+| `requestId` | string | 请求编号,反馈问题时一并提供 |
+
+**HTTP 200 和 `code=OK` 表示请求执行成功,拼装是否达标需要继续检查 `data.status`。** 没有匹配组件时也返回 HTTP 200;请求参数错误返回 422,详情组件不存在或已删除返回 404,数据库不可用返回 503。
+
+## 3. 匹配接口
+
+`POST /api/robot-matches`
+
+### 3.1 请求示例
+
+只指定所需角色即可匹配:
+
+```json
+{
+ "requiredParts": ["torso_0", "arm_r"]
+}
+```
+
+包含关键词、整机条件和部件条件的请求:
+
+```json
+{
+ "userInput": "我要一个双足跑步机器人,整体20自由度,质量不超过10kg,躯干用铝合金,右臂扭矩至少20N·m",
+ "requirements": ["双足", "机器人", "跑步"],
+ "requiredParts": [
+ "torso_0", "head_0", "waist_0", "arm_l", "arm_r", "hand_l", "hand_r",
+ "pedal_l", "pedal_r", "foot_l", "foot_r"
+ ],
+ "robotRequirements": {
+ "degreesOfFreedom": 20,
+ "functionDescription": "跑步",
+ "massKg": 10,
+ "operators": {"massKg": "lte"}
+ },
+ "partRequirements": [
+ {"category": "torso_0", "material": "铝合金"},
+ {"category": "arm_r", "torqueNm": 20, "operators": {"torqueNm": "gte"}}
+ ]
+}
+```
+
+### 3.2 顶层入参
+
+| 字段 | 类型 | 必填 | 说明 |
+| --- | --- | --- | --- |
+| `userInput` | string | 否 | 最多 4000 字符,仅作上下文;后端不解析、不存储,也不覆盖结构化条件 |
+| `requirements` | string[] | 否 | 最多 32 个关键词,每个非空且最多 128 字符;省略/null 表示无关键词要求 |
+| `requiredParts` | string[] | 是 | 非空,最多 24 项;中英文别名归一化后去重,每个角色只选一个实例 |
+| `robotRequirements` | object | 否 | 整机条件,字段见下表 |
+| `partRequirements` | object[] | 否 | 最多 12 项;每项对应一个角色的条件,字段见下表 |
+
+`userInput` 中写出的条件不会自动生效,前端必须同时提供相应结构化字段。例如“质量不超过 10kg”需要传 `massKg: 10` 和 `operators.massKg: "lte"`。
+
+### 3.3 整机条件 `robotRequirements`
+
+所有字段均可选。
+
+| 字段 | 类型 | 说明 |
+| --- | --- | --- |
+| `degreesOfFreedom` | integer | 标称总自由度,非负整数 |
+| `massKg` | number | 整机质量目标,单位 kg,非负 |
+| `functionDescription` | string | 整机功能要求,最多 512 字符,例如“跑步” |
+| `operators` | object | 数值比较方式,只支持已提供的 `degreesOfFreedom`、`massKg` |
+
+### 3.4 部件条件 `partRequirements[]`
+
+| 字段 | 类型 | 必填 | 说明 |
+| --- | --- | --- | --- |
+| `category` | string | 是 | 组件角色,必须包含在 `requiredParts` 中;同一角色不能重复定义条件 |
+| `material` | string | 否 | 材质,最多 128 字符,例如“铝合金” |
+| `degreesOfFreedom` | integer | 否 | 该部件自由度,非负整数 |
+| `massKg` | number | 否 | 该部件质量目标,单位 kg,非负 |
+| `torqueNm` | number | 否 | 该部件扭矩目标,单位 N·m,非负 |
+| `functionDescription` | string | 否 | 功能要求,最多 512 字符 |
+| `shape` | string | 否 | 形状要求,最多 128 字符 |
+| `size` | string | 否 | 大小描述要求,最多 128 字符,例如“中型”;不是数值尺寸比较 |
+| `operators` | object | 否 | 数值比较方式,只支持已提供的 `degreesOfFreedom`、`massKg`、`torqueNm` |
+
+### 3.5 数值、空值与运算符
+
+可选条件省略或传 null 表示不约束该字段。字符串裁剪首尾空白,空字符串也表示不约束。显式传 `0` 表示要求数值为 0,与不传条件不同。
+
+自由度只接受 0 至 2147483647 的 JSON 整数;`1.0`、`"1"`、布尔值和越界值均不合法。质量与扭矩使用 JSON 数值,最多 12 位整数、6 位小数。
+
+| 运算符 | 含义 | 示例 |
+| --- | --- | --- |
+| `eq` | 等于,省略时的默认值 | `degreesOfFreedom: 20` 表示总自由度等于 20 |
+| `gte` | 大于或等于 | `torqueNm: 20` 配合 `operators.torqueNm: "gte"` 表示至少 20 N·m |
+| `lte` | 小于或等于 | `massKg: 10` 配合 `operators.massKg: "lte"` 表示不超过 10 kg |
+
+`operators` 不能对应未提供目标值的字段,也不能用于文本字段。未知请求字段、非法角色、重复部件条件、负数和非法运算符均返回 HTTP 422。
+
+材质按同义词归一化后的等值匹配;功能、形状、大小按文本包含关系匹配。这些条件都可能因找不到合适组件而放宽,实际差异见 `unmetRequirements`。
+
+### 3.6 角色映射
+
+| 中文类型 | 标准编码 |
+| --- | --- |
+| 躯干_0 | torso_0 |
+| 头_0 | head_0 |
+| 腰_0 | waist_0 |
+| 臂_l、臂_r | arm_l、arm_r |
+| 手_l、手_r | hand_l、hand_r |
+| 足_l、足_r | pedal_l、pedal_r |
+| 脚_l、脚_r | foot_l、foot_r |
+| 尾_0 | tail_0 |
+
+输入接受中英文别名和英文大小写,响应返回标准编码。左右侧独立;`pedal` 对应足,`foot` 对应脚。
+
+### 3.7 匹配结果的业务约定
+
+先按角色查询未删除组件,再评价参数、材质和关键词。默认同义词包括跑步/奔跑/跑动/running、机器人/robot、双足/两足/biped/bipedal、铝合金/aluminum alloy/aluminium alloy。材质采用同义词归一化后的等值匹配,功能、形状和大小采用扩展后的包含匹配。名称、分类、功能、说明、材质、形状和大小参与关键词评价。
+
+优先返回能够覆盖更多所需部件的方案,再尽量满足参数、材质和关键词。参数与材质可以放宽,角色和连接规则始终保持匹配。不自动加入 `requiredParts` 之外的中间连接件。
+
+有可用的所需躯干时优先以躯干为根;否则尝试其他所需角色。无法覆盖所有角色时返回可拼的连通部分,至少保留一个可用根组件。单个组件没有安装端口时仍可作为根或叶节点。
+
+整机自由度和质量按选中组件字段求和,**不重复累加BOM,不从URDF再次计算**。质量为0视为未填写;只要一个组件质量未知,`totals.massKg=null`、`massComplete=false`,已知部分保存在 `knownMassKg`。不能据此宣布满足质量上限。功能命中表示元数据相关,不代表动力学验证。
+
+拼装候选必须有 URDF 主文件,且 `urdfInfo` 是包含非空 `rootLink` 和 `frames` 数组的对象。父帧的 `interfaceType` 对应子角色,连接到子组件的 `rootLink`。结果为无环连通组合,每个端口最多使用一次。异常端口会被忽略,前端应使用返回的 `connections` 完成拼装。
+
+`bomList` 和 `urdfInfo` 始终作为原始 JSON 返回,保留嵌套内容;详情里的 `urdfInfo` 也可能是其他对象或数组。接口匹配只评价元数据和连接类型,不验证机械承载或运动性能。
+
+## 4. 匹配结果
+
+### 4.1 `data` 字段
+
+| 字段 | 类型 | 内容 |
+| --- | --- | --- |
+| `status` | string | 匹配状态,见下表 |
+| `rootCategory` | string / null | 根角色;无结果时为 null |
+| `parts` | object[] | 默认选中组件,字段见 4.2 |
+| `connections` | object[] | 默认方案的整套父子连接,字段见 4.4 |
+| `alternatives` | object[] | 每个已选角色一个分组,每组最多 5 个兼容替代组件,字段见 4.5 |
+| `totals` | object | 默认方案的整机汇总,字段见 4.6 |
+| `unmetRequirements` | object[] | 未满足的整机或部件条件,字段见 4.7 |
+| `unmatchedKeywords` | string[] | 没有任何选中组件元数据命中的关键词 |
+| `missingParts` | object[] | 未加入组合的角色和原因,字段见 4.7 |
+| `searchLimited` | boolean | 搜索是否达到候选/搜索限制;true 时仍可展示当前方案,但不代表已找到最优方案或证明组件库无解 |
+
+| status | 含义 |
+| --- | --- |
+| `MATCHED` | 所需角色完整,所有提供条件和关键词均满足 |
+| `FALLBACK` | 角色完整,部分条件或关键词不满足 |
+| `PARTIAL` | 返回连通部分,存在缺失角色;也可能有参数不满足 |
+| `NO_MATCH` | 没有可用装配候选,parts和connections为空;HTTP仍为200 |
+
+`searchLimited` 与 `status` 独立,例如 `MATCHED` 也可能同时返回 `searchLimited=true`。数组无内容时返回 `[]`。`parts` 的顺序不保证与请求一致,前端使用 `category` 和 `componentCode` 定位组件。
+
+### 4.2 公开组件字段
+
+`parts[]`、`alternatives[].items[].component` 和详情接口的 `data` 使用同一结构。
+
+| 字段 | 类型 | 说明 |
+| --- | --- | --- |
+| `componentCode` | string | 组件唯一编码,用于获取详情和区分组件 |
+| `componentName` | string | 组件名称 |
+| `category` | string | 组件角色;匹配结果使用标准英文编码 |
+| `description` | string | 组件说明 |
+| `material` | string | 材质 |
+| `massKg` | number | 组件质量,单位 kg;0 表示未填写 |
+| `degreesOfFreedom` | integer | 组件标称自由度 |
+| `functionDescription` | string | 功能描述 |
+| `shape` | string | 形状描述 |
+| `size` | string | 大小描述 |
+| `torqueNm` | number | 扭矩,单位 N·m |
+| `bomList` | object / array | 原始 BOM JSON,内部结构由组件数据决定;允许 `{}`、`[]` 和嵌套内容 |
+| `urdfInfo` | object / array | 原始 URDF 信息 JSON,保留完整 frames、axis、limits 等;匹配结果中为带 `rootLink`、`frames` 的对象 |
+| `version` | integer | 组件数据版本号 |
+| `stepUrl` | string | 公开 STEP 文件地址;没有文件时为空字符串 |
+| `urdfUrl` | string | 公开 URDF 主文件地址;详情没有文件时为空字符串 |
+
+两个 JSON 字段均直接作为对象或数组使用,无需再执行 `JSON.parse`。组件未填写的描述字段可能为空字符串。响应不包含数据库 ID、独立 OSS 对象键、目录前缀、内部文件清单或上传令牌。
+
+### 4.3 完整成功响应示例
+
+以下响应对应 3.1 的最小请求 `{"requiredParts":["torso_0","arm_r"]}`,不是包含 11 个角色的整机请求。组件库提供了躯干、默认右臂和一个兼容的替代右臂。
+
+```json
+{
+ "code": "OK", "message": "success", "requestId": "example-request",
+ "data": {
+ "status": "MATCHED", "rootCategory": "torso_0",
+ "parts": [
+ {
+ "componentCode": "CW-00000000000000000000000000000001",
+ "componentName": "铝合金躯干", "category": "torso_0", "description": "机器人躯干",
+ "material": "铝合金", "massKg": 2, "degreesOfFreedom": 0,
+ "functionDescription": "支撑", "shape": "宽躯干", "size": "中型", "torqueNm": 0,
+ "bomList": {"items": [{"code": "BOLT-M4", "quantity": 4}]},
+ "urdfInfo": {
+ "robotName": "torso", "rootLink": "BASE",
+ "frames": [{
+ "name": "J1", "kind": "joint", "type": "fixed", "parent": "BASE",
+ "child": "LINK_arm_r", "interfaceType": "arm_r", "originExplicit": true,
+ "xyz": [-0.1, 0.01, 0], "rpy": [0, -1.5707963267949, 0],
+ "axis": [0, 0, 0], "limits": {}
+ }]
+ },
+ "version": 1,
+ "stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/step/batch/model.STEP",
+ "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/urdf/batch/robot.urdf"
+ },
+ {
+ "componentCode": "CW-00000000000000000000000000000002",
+ "componentName": "右臂", "category": "arm_r", "description": "机器人右臂",
+ "material": "铝合金", "massKg": 1, "degreesOfFreedom": 4,
+ "functionDescription": "摆臂", "shape": "", "size": "", "torqueNm": 20,
+ "bomList": [{"code": "ACTUATOR", "quantity": 4}],
+ "urdfInfo": {"robotName": "arm", "rootLink": "ARM_BASE", "frames": []},
+ "version": 1,
+ "stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000002/step/batch/model.STEP",
+ "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000002/urdf/batch/robot.urdf"
+ }
+ ],
+ "connections": [{
+ "parentCategory": "torso_0", "parentComponentCode": "CW-00000000000000000000000000000001",
+ "parentLink": "BASE", "frameName": "J1", "childCategory": "arm_r",
+ "childComponentCode": "CW-00000000000000000000000000000002", "childRootLink": "ARM_BASE",
+ "xyz": [-0.1, 0.01, 0], "rpy": [0, -1.5707963267949, 0]
+ }],
+ "alternatives": [
+ {"category": "torso_0", "items": []},
+ {
+ "category": "arm_r",
+ "items": [
+ {
+ "component": {
+ "componentCode": "CW-00000000000000000000000000000003",
+ "componentName": "高扭矩右臂", "category": "arm_r", "description": "机器人右臂",
+ "material": "铝合金", "massKg": 1.2, "degreesOfFreedom": 4,
+ "functionDescription": "摆臂", "shape": "", "size": "", "torqueNm": 25,
+ "bomList": [{"code": "ACTUATOR-25", "quantity": 4, "spec": {"torqueNm": 25}}],
+ "urdfInfo": {"robotName": "arm_v2", "rootLink": "ARM_V2_BASE", "frames": []},
+ "version": 1,
+ "stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000003/step/batch/model.STEP",
+ "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000003/urdf/batch/robot.urdf"
+ },
+ "connections": [{
+ "parentCategory": "torso_0", "parentComponentCode": "CW-00000000000000000000000000000001",
+ "parentLink": "BASE", "frameName": "J1", "childCategory": "arm_r",
+ "childComponentCode": "CW-00000000000000000000000000000003", "childRootLink": "ARM_V2_BASE",
+ "xyz": [-0.1, 0.01, 0], "rpy": [0, -1.5707963267949, 0]
+ }],
+ "totals": {"degreesOfFreedom": 4, "massKg": 3.2, "knownMassKg": 3.2, "massComplete": true},
+ "unmetRequirements": [],
+ "unmatchedKeywords": []
+ }
+ ]
+ }
+ ],
+ "totals": {"degreesOfFreedom": 4, "massKg": 3, "knownMassKg": 3, "massComplete": true},
+ "unmetRequirements": [], "unmatchedKeywords": [], "missingParts": [], "searchLimited": false
+ }
+}
+```
+
+### 4.4 连接字段 `connections[]`
+
+| 字段 | 类型 | 说明 |
+| --- | --- | --- |
+| `parentCategory` | string | 父组件角色 |
+| `parentComponentCode` | string | 父组件编码 |
+| `parentLink` | string | 父组件模型内部的连接基准 link |
+| `frameName` | string | 父组件用于安装的帧名称 |
+| `childCategory` | string | 子组件角色 |
+| `childComponentCode` | string | 子组件编码 |
+| `childRootLink` | string | 子组件模型根 link |
+| `xyz` | number[3] | 相对于父 `parentLink` 的平移 `[x,y,z]`,单位米 |
+| `rpy` | number[3] | 相对于父 `parentLink` 的旋转 `[roll,pitch,yaw]`,单位弧度 |
+
+位姿不是世界坐标。示例中将右臂的 `ARM_BASE` 对齐到躯干 `BASE` 下的给定位姿。不同组件的 link 名称可能相同,应在对应组件实例内查找。
+
+### 4.5 替代候选 `alternatives[]`
+
+| 字段 | 类型 | 说明 |
+| --- | --- | --- |
+| `category` | string | 当前可替换的角色 |
+| `items` | object[] | 0 至 5 个兼容替代项,空数组表示没有提供替代组件 |
+| `items[].component` | object | 替代组件的完整公开数据,包括 BOM 和 URDF 信息 |
+| `items[].connections` | object[] | 替换后的**整套**连接,不只是该部件的局部连接 |
+| `items[].totals` | object | 替换后的整机汇总 |
+| `items[].unmetRequirements` | object[] | 替换后的未满足条件 |
+| `items[].unmatchedKeywords` | string[] | 替换后的未命中关键词 |
+
+替代组件兼容当前父组件和全部当前子组件,保持当前父子拓扑;仍可能不满足用户的材质、数值或文本要求。替换父组件时连接位姿可能改变,替换子组件时根 link 可能改变。
+
+前端选择一个替代项后,应按角色替换 `parts` 中的组件,并整体采用该项的 `connections`、`totals`、`unmetRequirements` 和 `unmatchedKeywords`。上例替换右臂后,编码变为 `CW-00000000000000000000000000000003`,根 link 变为 `ARM_V2_BASE`,整机质量变为 3.2 kg。
+
+替代项没有独立 `status`,可根据当前 `missingParts` 和替代项的未满足条件/关键词重新展示状态。这些替代项针对本次默认方案计算;多个角色的替代项不能直接任意组合。重新请求会生成新的默认方案,当前接口没有锁定已选编码或校验多部件替换的入参。
+
+### 4.6 汇总 `totals`
+
+| 字段 | 类型 | 说明 |
+| --- | --- | --- |
+| `degreesOfFreedom` | integer | 所选组件标称自由度之和 |
+| `massKg` | number / null | 全部已选组件质量已知时的总质量;有未知质量时为 null |
+| `knownMassKg` | number | 仅已知质量部分的合计 |
+| `massComplete` | boolean | 是否所有已选组件质量均已填写;无组件时为 false |
+
+`PARTIAL` 的汇总只覆盖已返回的组件。`massComplete=true` 表示这些组件的质量已知,不表示所需角色齐全。不要把组件 `massKg=0` 或汇总 `massKg=null` 展示成真实的零质量。
+
+### 4.7 未满足条件和缺件
+
+`unmetRequirements[]` 字段:
+
+| 字段 | 类型 | 说明 |
+| --- | --- | --- |
+| `scope` | string | `PART` 表示部件条件,`ROBOT` 表示整机条件 |
+| `category` | string / null | 部件标准角色;整机条件为 null |
+| `field` | string | 未满足的请求字段,如 `torqueNm`、`massKg`、`material` |
+| `operator` | string | 数值为 `eq/gte/lte`,材质为 `eq`,功能/形状/大小为 `contains` |
+| `expected` | number / string | 用户要求的目标值 |
+| `actual` | number / string / null | 实际值;未知质量或未命中的整机功能可为 null |
+| `reason` | string | 原因,见下表 |
+
+| `unmetRequirements.reason` | 展示含义 |
+| --- | --- |
+| `VALUE_MISMATCH` | 数值不满足目标 |
+| `UNKNOWN_MASS` | 质量未填写,无法确认是否满足质量要求 |
+| `NO_TEXT_MATCH` | 材质、功能、形状或大小未命中 |
+
+`missingParts[]` 每项包含 `category`(缺失角色)和 `reason`(原因):
+
+| `missingParts.reason` | 展示含义 |
+| --- | --- |
+| `NO_COMPONENT` | 组件库没有该角色的可用组件 |
+| `INVALID_ASSEMBLY_METADATA` | 有该角色的组件,但 URDF 文件或拼装信息不完整 |
+| `NO_COMPATIBLE_CONNECTION` | 有候选组件,但未找到与当前组合兼容的连接 |
+| `SEARCH_LIMIT` | 达到搜索限制,本次未找到可加入的组件 |
+
+### 4.8 降级示例:`FALLBACK`
+
+请求要求能跑步、质量不超过 2 kg、右臂扭矩至少 30 N·m:
+
+```json
+{
+ "requirements": ["跑步"],
+ "requiredParts": ["torso_0", "arm_r"],
+ "robotRequirements": {
+ "massKg": 2,
+ "functionDescription": "跑步",
+ "operators": {"massKg": "lte"}
+ },
+ "partRequirements": [
+ {"category": "arm_r", "torqueNm": 30, "operators": {"torqueNm": "gte"}}
+ ]
+}
+```
+
+例如找到可拼装的完整组合,但合计 3.2 kg、右臂扭矩 25 N·m,且未命中跑步功能。HTTP 200、`code=OK`,下面仅展示 **`data` 的状态字段片段**;实际响应仍包含完整 `parts`、`connections` 和 `alternatives`:
+
+```json
+{
+ "status": "FALLBACK",
+ "rootCategory": "torso_0",
+ "totals": {"degreesOfFreedom": 4, "massKg": 3.2, "knownMassKg": 3.2, "massComplete": true},
+ "unmetRequirements": [
+ {
+ "scope": "PART", "category": "arm_r", "field": "torqueNm", "operator": "gte",
+ "expected": 30, "actual": 25, "reason": "VALUE_MISMATCH"
+ },
+ {
+ "scope": "ROBOT", "category": null, "field": "massKg", "operator": "lte",
+ "expected": 2, "actual": 3.2, "reason": "VALUE_MISMATCH"
+ },
+ {
+ "scope": "ROBOT", "category": null, "field": "functionDescription", "operator": "contains",
+ "expected": "跑步", "actual": null, "reason": "NO_TEXT_MATCH"
+ }
+ ],
+ "unmatchedKeywords": ["跑步"],
+ "missingParts": [],
+ "searchLimited": false
+}
+```
+
+前端可以展示模型,同时提示“已提供可拼装方案,部分要求未满足”,并列出质量、扭矩和功能差异。
+
+### 4.9 缺件示例:`PARTIAL`
+
+请求:
+
+```json
+{
+ "requiredParts": ["torso_0", "head_0", "arm_r"]
+}
+```
+
+例如仅返回躯干和右臂的连通组合,组件库没有头部。HTTP 200、`code=OK`,以下为 **`data` 的状态字段片段**,实际响应的 `parts` 包含这两个组件:
+
+```json
+{
+ "status": "PARTIAL",
+ "rootCategory": "torso_0",
+ "totals": {"degreesOfFreedom": 4, "massKg": 3, "knownMassKg": 3, "massComplete": true},
+ "unmetRequirements": [],
+ "unmatchedKeywords": [],
+ "missingParts": [{"category": "head_0", "reason": "NO_COMPONENT"}],
+ "searchLimited": false
+}
+```
+
+前端展示已返回的组件,并提示缺失头部;不能把这份汇总作为完整整机数据。
+
+### 4.10 无可用组件示例:`NO_MATCH`
+
+请求:
+
+```json
+{
+ "requirements": ["跑步"],
+ "requiredParts": ["torso_0", "arm_r"]
+}
+```
+
+例如这两个角色都没有可用组件,返回 HTTP 200。**完整响应**:
+
+```json
+{
+ "code": "OK",
+ "message": "success",
+ "requestId": "frontend-match-004",
+ "data": {
+ "status": "NO_MATCH",
+ "rootCategory": null,
+ "parts": [],
+ "connections": [],
+ "alternatives": [],
+ "totals": {"degreesOfFreedom": 0, "massKg": null, "knownMassKg": 0, "massComplete": false},
+ "unmetRequirements": [],
+ "unmatchedKeywords": ["跑步"],
+ "missingParts": [
+ {"category": "torso_0", "reason": "NO_COMPONENT"},
+ {"category": "arm_r", "reason": "NO_COMPONENT"}
+ ],
+ "searchLimited": false
+ }
+}
+```
+
+前端展示“暂无可拼装组件”,结合 `missingParts` 提示原因。数据库故障属于接口错误,会返回 HTTP 503,不会返回此状态。
+
+## 5. 组件详情
+
+`GET /api/components/{componentCode}`,无请求体。
+
+| 路径参数 | 类型 | 必填 | 说明 |
+| --- | --- | --- | --- |
+| `componentCode` | string | 是 | 组件编码,非空且最多 64 字符;使用匹配结果中的编码 |
+
+请求示例:
+
+```http
+GET /api/components/CW-00000000000000000000000000000001
+X-Request-Id: frontend-detail-001
+```
+
+HTTP 200,完整响应示例:
+
+```json
+{
+ "code": "OK",
+ "message": "success",
+ "requestId": "frontend-detail-001",
+ "data": {
+ "componentCode": "CW-00000000000000000000000000000001",
+ "componentName": "铝合金躯干",
+ "category": "torso_0",
+ "description": "机器人躯干",
+ "material": "铝合金",
+ "massKg": 2,
+ "degreesOfFreedom": 0,
+ "functionDescription": "支撑",
+ "shape": "宽躯干",
+ "size": "中型",
+ "torqueNm": 0,
+ "bomList": {
+ "items": [{"code": "BOLT-M4", "quantity": 4}]
+ },
+ "urdfInfo": {
+ "robotName": "torso",
+ "rootLink": "BASE",
+ "frames": [
+ {
+ "name": "J1",
+ "kind": "joint",
+ "type": "fixed",
+ "parent": "BASE",
+ "child": "LINK_arm_r",
+ "interfaceType": "arm_r",
+ "originExplicit": true,
+ "xyz": [-0.1, 0.01, 0],
+ "rpy": [0, -1.5707963267949, 0],
+ "axis": [0, 0, 0],
+ "limits": {}
+ }
+ ]
+ },
+ "version": 1,
+ "stepUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/step/batch/model.STEP",
+ "urdfUrl": "https://models.example.com/cadworld/components/CW-00000000000000000000000000000001/urdf/batch/robot.urdf"
+ }
+}
+```
+
+返回字段见 4.2。详情可能返回不满足拼装要求的原始 `urdfInfo`,查看详情不表示该组件一定可以参与匹配。
+
+## 6. 错误响应
+
+| HTTP 状态 | `code` | 常见原因 |
+| --- | --- | --- |
+| 422 | `INVALID_REQUEST` | 必填项缺失、JSON 类型错误、未知字段、超长文本、负数、自由度小数或数值越界 |
+| 422 | `INVALID_MATCH_REQUEST` | 不支持的角色、部件条件不属于所需角色、重复角色条件、非法运算符 |
+| 404 | `COMPONENT_NOT_FOUND` | 详情编码不存在或组件已删除 |
+| 503 | `DATABASE_UNAVAILABLE` | 数据库暂不可用 |
+| 500 | `INTERNAL_ERROR` | 服务内部异常 |
+
+### 6.1 非法角色:HTTP 422
+
+请求 `POST /api/robot-matches`:
+
+```json
+{
+ "requiredParts": ["unknown_part"]
+}
+```
+
+响应:
+
+```json
+{
+ "code": "INVALID_MATCH_REQUEST",
+ "message": "不支持的组件角色",
+ "data": null,
+ "requestId": "frontend-invalid-001"
+}
+```
+
+### 6.2 自由度类型错误:HTTP 422
+
+请求中的自由度使用了字符串:
+
+```json
+{
+ "requiredParts": ["arm_r"],
+ "robotRequirements": {"degreesOfFreedom": "20"}
+}
+```
+
+响应:
+
+```json
+{
+ "code": "INVALID_REQUEST",
+ "message": "请求体格式不合法,请检查字段类型和JSON结构",
+ "data": null,
+ "requestId": "frontend-invalid-002"
+}
+```
+
+### 6.3 组件不存在:HTTP 404
+
+请求 `GET /api/components/CW-NOT-FOUND`,响应:
+
+```json
+{
+ "code": "COMPONENT_NOT_FOUND",
+ "message": "组件不存在",
+ "data": null,
+ "requestId": "frontend-detail-002"
+}
+```
+
+### 6.4 数据库不可用:HTTP 503
+
+```json
+{
+ "code": "DATABASE_UNAVAILABLE",
+ "message": "数据库暂不可用,请检查数据库连接配置后重试",
+ "data": null,
+ "requestId": "frontend-match-005"
+}
+```
+
+错误时按 HTTP 状态和 `code` 判断,`message` 用于提示,不作为固定业务分支条件。排查时提供 `requestId`。
+
+## 7. 前端拼装与模型加载
+
+1. 提交结构化匹配条件,读取 `data.status`;`FALLBACK`、`PARTIAL` 仍可以展示已有模型,同时展示未满足条件和缺件。
+2. 使用 `parts[].urdfUrl` 加载 URDF,用 `componentCode` 区分模型实例;需要 STEP 文件时使用 `stepUrl`。空地址不发起文件请求。
+3. 从 `rootCategory` 对应模型开始,按 `connections` 组装。在父组件实例内部查找 `parentLink`,将子 `childRootLink` 对齐到给定局部 `xyz/rpy`。不要假设连接数组已经按装配顺序排列。
+4. BOM 展示读取 `bomList`;关节、轴、限位等读取原始 `urdfInfo` 或已加载模型。不要重复累加 BOM 的质量和自由度。
+5. 选择替代组件后,按 4.5 同时更新组件、连接、汇总及未满足项。
+
+模型资源由前端直接请求公开 OSS/CDN 地址,无需拼接 `/api/components/{componentCode}/assets/...` 路径,也不需要给模型地址附加管理员凭证。资源域名需允许前端源跨域读取 URDF 及 meshes,联调时由部署人员配置 OSS/CDN 的 GET/HEAD CORS。
+
+URDF 相对 mesh 路径以主文件目录解析,保留服务器返回的完整目录。若文件使用 `package://`,前端 URDF 加载器需要配置对应 package 路径映射。STEP 格式解析和模型展示由前端加载器负责。
+
+组件资源替换后应使用最新响应中的 URL。组件已删除时详情返回 404,但已有公开资源地址不保证立即失效;不要仅凭模型地址可访问就判断组件仍可使用。
diff --git a/cadworld-api/pom.xml b/cadworld-api/pom.xml
index a28ffa1..4b65a13 100644
--- a/cadworld-api/pom.xml
+++ b/cadworld-api/pom.xml
@@ -14,4 +14,31 @@
cadworld-api
jar
cadworld-api
+
+
+
+ com.linkerbot
+ cadworld-service
+ ${project.version}
+
+
+ com.mysql
+ mysql-connector-j
+ runtime
+
+
+ com.h2database
+ h2
+ test
+
+
+
+
+
+
+ org.springframework.boot
+ spring-boot-maven-plugin
+
+
+
diff --git a/cadworld-api/src/main/java/com/linkerbot/cadworld/api/ApiApplication.java b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/ApiApplication.java
new file mode 100644
index 0000000..dcd28d4
--- /dev/null
+++ b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/ApiApplication.java
@@ -0,0 +1,25 @@
+package com.linkerbot.cadworld.api;
+
+import com.linkerbot.cadworld.config.MatchingProperties;
+import com.linkerbot.cadworld.config.MybatisPlusConfig;
+import com.linkerbot.cadworld.config.StorageProperties;
+import com.linkerbot.cadworld.mapper.ComponentMapper;
+import com.linkerbot.cadworld.service.impl.ObjectStorageUrlResolver;
+import org.mybatis.spring.annotation.MapperScan;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Import;
+
+@SpringBootApplication(scanBasePackages = {
+ "com.linkerbot.cadworld.api", "com.linkerbot.cadworld.common",
+ "com.linkerbot.cadworld.service.matching"
+})
+@EnableConfigurationProperties({StorageProperties.class, MatchingProperties.class})
+@Import({MybatisPlusConfig.class, ObjectStorageUrlResolver.class})
+@MapperScan(basePackageClasses = ComponentMapper.class)
+public class ApiApplication {
+ public static void main(String[] args) {
+ SpringApplication.run(ApiApplication.class, args);
+ }
+}
diff --git a/cadworld-api/src/main/java/com/linkerbot/cadworld/api/controller/ComponentMatchingController.java b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/controller/ComponentMatchingController.java
new file mode 100644
index 0000000..0f08e71
--- /dev/null
+++ b/cadworld-api/src/main/java/com/linkerbot/cadworld/api/controller/ComponentMatchingController.java
@@ -0,0 +1,38 @@
+package com.linkerbot.cadworld.api.controller;
+
+import com.linkerbot.cadworld.common.api.ApiResponse;
+import com.linkerbot.cadworld.dto.matching.PublicComponentResponse;
+import com.linkerbot.cadworld.dto.matching.RobotMatchRequest;
+import com.linkerbot.cadworld.dto.matching.RobotMatchResponse;
+import com.linkerbot.cadworld.service.matching.PublicComponentQueryService;
+import com.linkerbot.cadworld.service.matching.RobotMatchingService;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.Size;
+import lombok.RequiredArgsConstructor;
+import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/api")
+@Validated
+@RequiredArgsConstructor
+public class ComponentMatchingController {
+ private final RobotMatchingService matching;
+ private final PublicComponentQueryService components;
+
+ @PostMapping("/robot-matches")
+ public ApiResponse match(@Valid @RequestBody RobotMatchRequest request) {
+ return ApiResponse.success(matching.match(request));
+ }
+
+ @GetMapping("/components/{componentCode}")
+ public ApiResponse detail(@PathVariable @NotBlank @Size(max = 64) String componentCode) {
+ return ApiResponse.success(components.get(componentCode));
+ }
+}
diff --git a/cadworld-api/src/main/resources/application-prod.yml b/cadworld-api/src/main/resources/application-prod.yml
new file mode 100644
index 0000000..27c8660
--- /dev/null
+++ b/cadworld-api/src/main/resources/application-prod.yml
@@ -0,0 +1,21 @@
+spring:
+ datasource:
+ url: ${APP_DB_URL}
+ username: ${APP_DB_USERNAME}
+ password: ${APP_DB_PASSWORD}
+ driver-class-name: com.mysql.cj.jdbc.Driver
+ hikari:
+ pool-name: CadworldApiHikariCP
+ minimum-idle: 1
+ maximum-pool-size: 20
+ connection-timeout: 5000
+
+app:
+ storage:
+ root-prefix: ${OSS_ROOT_PREFIX:cadworld}
+ # 生产环境必须配置公开 OSS/CDN 域名,供前端直接加载模型。
+ public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL}
+
+logging:
+ level:
+ com.linkerbot.cadworld: INFO
diff --git a/cadworld-api/src/main/resources/application-test.yml b/cadworld-api/src/main/resources/application-test.yml
new file mode 100644
index 0000000..db48b74
--- /dev/null
+++ b/cadworld-api/src/main/resources/application-test.yml
@@ -0,0 +1,20 @@
+spring:
+ datasource:
+ # 优先使用与管理端一致的 APP_DB_*,兼容原有 DB_* 环境变量。
+ url: ${APP_DB_URL:${DB_URL:jdbc:mysql://127.0.0.1:3306/cadworld?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai}}
+ username: ${APP_DB_USERNAME:${DB_USERNAME:}}
+ password: ${APP_DB_PASSWORD:${DB_PASSWORD:}}
+ driver-class-name: com.mysql.cj.jdbc.Driver
+ hikari:
+ pool-name: CadworldApiHikariCP
+ minimum-idle: 1
+ maximum-pool-size: 10
+ connection-timeout: 5000
+
+app:
+ storage:
+ root-prefix: ${OSS_ROOT_PREFIX:cadworld_dev}
+
+logging:
+ level:
+ com.linkerbot.cadworld: DEBUG
diff --git a/cadworld-api/src/main/resources/application.yml b/cadworld-api/src/main/resources/application.yml
new file mode 100644
index 0000000..4d2cf51
--- /dev/null
+++ b/cadworld-api/src/main/resources/application.yml
@@ -0,0 +1,34 @@
+spring:
+ application:
+ name: cadworld-api
+ profiles:
+ default: test
+ sql:
+ init:
+ mode: never
+ jackson:
+ deserialization:
+ fail-on-unknown-properties: true
+server:
+ port: ${SERVER_PORT:8991}
+logging:
+ level:
+ root: INFO
+ # 测试环境开启项目 DEBUG 时,仍不输出 SQL 参数或完整请求内容。
+ com.linkerbot.cadworld.mapper: INFO
+ org.springframework.web: INFO
+mybatis-plus:
+ configuration:
+ map-underscore-to-camel-case: true
+app:
+ storage:
+ # 配置公开 OSS/CDN 域名,不能填管理端下载代理地址;对象键已包含环境根目录。
+ public-base-url: ${APP_STORAGE_PUBLIC_BASE_URL:}
+ matching:
+ candidates-per-role: 50
+ preferred-candidates-per-role: 30
+ beam-width: 128
+ max-state-expansions: 50000
+ # 可追加或覆盖同义词组,例如:
+ # synonyms:
+ # "[跑步]": [奔跑, 跑动, running]
diff --git a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingApiTest.java b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingApiTest.java
new file mode 100644
index 0000000..1f6f451
--- /dev/null
+++ b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/MatchingApiTest.java
@@ -0,0 +1,505 @@
+package com.linkerbot.cadworld.api;
+
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.read.ListAppender;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.linkerbot.cadworld.config.MatchingProperties;
+import com.linkerbot.cadworld.dto.matching.RobotMatchRequest;
+import com.linkerbot.cadworld.dto.matching.RobotMatchResponse;
+import com.linkerbot.cadworld.service.AdminOperatorProvider;
+import com.linkerbot.cadworld.service.client.ObjectStorageClient;
+import com.linkerbot.cadworld.service.matching.AssemblySearchEngine;
+import com.linkerbot.cadworld.service.matching.PublicComponentQueryService;
+import com.linkerbot.cadworld.service.matching.RequirementEvaluator;
+import com.linkerbot.cadworld.service.matching.RobotMatchingService;
+import com.linkerbot.cadworld.service.support.ComponentUploadSessionTokenProvider;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.context.ApplicationContext;
+import org.springframework.http.MediaType;
+import org.springframework.jdbc.core.JdbcTemplate;
+import org.springframework.test.web.servlet.MockMvc;
+import org.springframework.test.web.servlet.MvcResult;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
+
+@SpringBootTest(classes = ApiApplication.class, properties = {
+ "spring.datasource.url=jdbc:h2:mem:matching;MODE=MySQL;DB_CLOSE_DELAY=-1",
+ "spring.datasource.driver-class-name=org.h2.Driver", "spring.datasource.username=sa",
+ "spring.datasource.password=", "spring.sql.init.mode=never",
+ "app.storage.public-base-url=https://models.example.test", "logging.file.path=target/test-logs"
+})
+@AutoConfigureMockMvc
+class MatchingApiTest {
+ @Autowired private MockMvc mvc;
+ @Autowired private ObjectMapper json;
+ @Autowired private JdbcTemplate jdbc;
+ @Autowired private ApplicationContext context;
+ @Autowired private PublicComponentQueryService components;
+ @Autowired private RequirementEvaluator evaluator;
+
+ @BeforeEach
+ void prepare() {
+ String product = jdbc.execute((org.springframework.jdbc.core.ConnectionCallback)
+ connection -> connection.getMetaData().getDatabaseProductName());
+ assertThat(product).isEqualTo("H2");
+ jdbc.execute("""
+ CREATE TABLE IF NOT EXISTS component (
+ id BIGINT AUTO_INCREMENT PRIMARY KEY,
+ component_code VARCHAR(64) NOT NULL DEFAULT '' UNIQUE,
+ component_name VARCHAR(128) NOT NULL DEFAULT '', category VARCHAR(64) NOT NULL DEFAULT '',
+ description CLOB NOT NULL DEFAULT '', material VARCHAR(128) NOT NULL DEFAULT '',
+ mass_kg DECIMAL(18,6) NOT NULL DEFAULT 0, degrees_of_freedom INT NOT NULL DEFAULT 0,
+ function_description VARCHAR(512) NOT NULL DEFAULT '', shape VARCHAR(128) NOT NULL DEFAULT '',
+ size VARCHAR(128) NOT NULL DEFAULT '', torque_nm DECIMAL(18,6) NOT NULL DEFAULT 0,
+ bom_list CLOB NOT NULL, urdf_info CLOB NOT NULL,
+ basic_fields CLOB NOT NULL DEFAULT '[]', parameter_fields CLOB NOT NULL DEFAULT '[]',
+ step_object_key VARCHAR(512) NOT NULL DEFAULT '', urdf_prefix VARCHAR(512) NOT NULL DEFAULT '',
+ urdf_main_object_key VARCHAR(512) NOT NULL DEFAULT '', urdf_files CLOB NOT NULL DEFAULT '[]',
+ version BIGINT NOT NULL DEFAULT 1, deleted TINYINT NOT NULL DEFAULT 0,
+ created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP)
+ """);
+ jdbc.update("DELETE FROM component");
+ }
+
+ @Test
+ void startsWithoutAdminOrOssBeansAndOnlyExposesUserRoutes() throws Exception {
+ assertThat(context.getBeansOfType(AdminOperatorProvider.class)).isEmpty();
+ assertThat(context.getBeansOfType(ComponentUploadSessionTokenProvider.class)).isEmpty();
+ assertThat(context.getBeansOfType(ObjectStorageClient.class)).isEmpty();
+ mvc.perform(get("/admin-api/components")).andExpect(status().isNotFound());
+ mvc.perform(get("/api/components/CW-NO/assets/1/step")).andExpect(status().isNotFound());
+ JsonNode empty = match(request("torso_0"));
+ assertThat(empty.path("status").asText()).isEqualTo("NO_MATCH");
+ assertThat(empty.path("parts")).isEmpty();
+ assertThat(empty.path("missingParts").get(0).path("reason").asText()).isEqualTo("NO_COMPONENT");
+ }
+
+ @Test
+ void mapsEveryRoleAndDeduplicatesAliasesWithoutSwappingFeetOrSides() throws Exception {
+ List english = List.of("head_0", "waist_0", "arm_l", "arm_r", "hand_l", "hand_r",
+ "pedal_l", "pedal_r", "foot_l", "foot_r", "tail_0");
+ List chinese = List.of("头_0", "腰_0", "臂_l", "臂_r", "手_l", "手_r", "足_l", "足_r", "脚_l", "脚_r", "尾_0");
+ save("CW-TORSO", "躯干_0", 0, "1", "0", "", metadata("ROOT", english.toArray(String[]::new)), json.readTree("[]"));
+ for (int index = 0; index < english.size(); index++) save("CW-" + english.get(index), chinese.get(index), 1, "1", "0", "");
+ List required = new ArrayList<>(chinese);
+ required.addAll(List.of("躯干_0", "torso_0", "ARM_L"));
+ JsonNode result = match(Map.of("requiredParts", required));
+ assertThat(result.path("status").asText()).isEqualTo("MATCHED");
+ assertThat(result.path("parts").size()).isEqualTo(12);
+ assertThat(result.path("connections").size()).isEqualTo(11);
+ assertThat(part(result, "pedal_l").path("componentCode").asText()).isEqualTo("CW-pedal_l");
+ assertThat(part(result, "foot_l").path("componentCode").asText()).isEqualTo("CW-foot_l");
+ }
+
+ @Test
+ void returnsOriginalNestedJsonInSelectedAlternativeAndDetailWithEncodedDirectUrls() throws Exception {
+ JsonNode original = metadata("BASE", "arm_r");
+ JsonNode bom = json.readTree("{\"items\":[{\"code\":\"bolt\",\"qty\":4,\"details\":{\"material\":\"steel\"}}]}");
+ save("CW-A", "torso_0", 0, "1", "0", "", original, bom);
+ JsonNode alternativeBom = json.readTree("[{\"code\":\"plate\",\"children\":[{\"qty\":2}]}]");
+ JsonNode alternativeInfo = metadata("OTHER_BASE", "arm_r");
+ save("CW-B", "躯干_0", 0, "2", "0", "", alternativeInfo, alternativeBom);
+ save("CW-ARM", "臂_r", 4, "1", "20", "");
+ jdbc.update("UPDATE component SET step_object_key=?,urdf_main_object_key=? WHERE component_code=?",
+ "cadworld_dev/components/CW-A/step/batch/模型 one.STEP",
+ "cadworld_dev/components/CW-A/urdf/batch/L20/机器人.urdf", "CW-A");
+ JsonNode result = match(request("torso_0", "arm_r"));
+ JsonNode selected = part(result, "torso_0");
+ assertThat(selected.get("bomList")).isEqualTo(bom);
+ assertThat(selected.get("urdfInfo")).isEqualTo(original);
+ assertThat(selected.path("stepUrl").asText()).startsWith("https://models.example.test/cadworld_dev/")
+ .endsWith("%E6%A8%A1%E5%9E%8B%20one.STEP");
+ assertThat(selected.path("urdfUrl").asText()).contains("/urdf/batch/L20/").endsWith("%E6%9C%BA%E5%99%A8%E4%BA%BA.urdf");
+ JsonNode replacement = alternatives(result, "torso_0").get(0).path("component");
+ assertThat(replacement.get("bomList")).isEqualTo(alternativeBom);
+ assertThat(replacement.get("urdfInfo")).isEqualTo(alternativeInfo);
+ assertPublic(selected);
+ assertPublic(replacement);
+ MvcResult detail = mvc.perform(get("/api/components/CW-A").header("X-Request-Id", "matching-detail"))
+ .andExpect(status().isOk()).andExpect(jsonPath("$.requestId").value("matching-detail")).andReturn();
+ JsonNode publicDetail = json.readTree(detail.getResponse().getContentAsString()).path("data");
+ assertThat(publicDetail).isEqualTo(selected);
+ assertPublic(publicDetail);
+ Long id = jdbc.queryForObject("SELECT id FROM component WHERE component_code='CW-A'", Long.class);
+ mvc.perform(get("/api/components/" + id)).andExpect(status().isNotFound());
+ }
+
+ @Test
+ void publicDetailAlsoPreservesJsonArraysThatAreNotAssemblyMetadata() throws Exception {
+ JsonNode info = json.readTree("[{\"robotName\":\"legacy\"}]");
+ save("CW-LEGACY", "torso_0", 0, "1", "0", "", info, json.readTree("{}"));
+ MvcResult detail = mvc.perform(get("/api/components/CW-LEGACY")).andExpect(status().isOk()).andReturn();
+ assertThat(json.readTree(detail.getResponse().getContentAsString()).path("data").get("urdfInfo")).isEqualTo(info);
+ JsonNode result = match(request("torso_0"));
+ assertThat(result.path("status").asText()).isEqualTo("NO_MATCH");
+ assertThat(result.path("missingParts").get(0).path("reason").asText()).isEqualTo("INVALID_ASSEMBLY_METADATA");
+ }
+
+ @Test
+ void structuredRequirementsAndSynonymsDetermineExactMatchNotUserInput() throws Exception {
+ save("CW-T", "torso_0", 0, "2", "0", "aluminium alloy", metadata("BASE", "arm_r"), json.readTree("[]"));
+ save("CW-R", "arm_r", 20, "3", "20", "steel");
+ jdbc.update("UPDATE component SET component_name='双足机器人',function_description='用于奔跑',shape='双足' ");
+ Map body = new LinkedHashMap<>(request("torso_0", "arm_r"));
+ body.put("userInput", "这里写100自由度和质量1kg也不能覆盖结构化条件");
+ body.put("requirements", List.of("running", "robot", "biped"));
+ body.put("robotRequirements", Map.of("degreesOfFreedom", 20, "massKg", 10, "functionDescription", "跑步", "operators", Map.of("massKg", "lte")));
+ body.put("partRequirements", List.of(Map.of("category", "躯干_0", "material", " 铝合金 "),
+ Map.of("category", "arm_r", "torqueNm", 20, "operators", Map.of("torqueNm", "gte"))));
+ JsonNode result = match(body);
+ assertThat(result.path("status").asText()).isEqualTo("MATCHED");
+ assertThat(result.path("totals").path("degreesOfFreedom").asInt()).isEqualTo(20);
+ assertThat(result.path("totals").path("massKg").decimalValue()).isEqualByComparingTo("5");
+ assertThat(result.path("unmetRequirements")).isEmpty();
+ assertThat(result.path("unmatchedKeywords")).isEmpty();
+ }
+
+ @Test
+ void completeConnectedAssemblyWinsOverSmallerAssemblyThatMeetsParameters() throws Exception {
+ save("CW-EXACT-LEAF", "torso_0", 20, "1", "0", "铝合金");
+ save("CW-FALLBACK-T", "torso_0", 0, "8", "0", "steel", metadata("BASE", "arm_r"), json.readTree("[]"));
+ save("CW-FALLBACK-R", "arm_r", 4, "5", "10", "steel");
+ Map body = new LinkedHashMap<>(request("torso_0", "arm_r"));
+ body.put("robotRequirements", Map.of("degreesOfFreedom", 20, "massKg", 10, "operators", Map.of("massKg", "lte")));
+ body.put("partRequirements", List.of(Map.of("category", "torso_0", "material", "铝合金"),
+ Map.of("category", "arm_r", "torqueNm", 20, "operators", Map.of("torqueNm", "gte"))));
+ JsonNode result = match(body);
+ assertThat(result.path("status").asText()).isEqualTo("FALLBACK");
+ assertThat(result.path("parts").size()).isEqualTo(2);
+ assertThat(part(result, "torso_0").path("componentCode").asText()).isEqualTo("CW-FALLBACK-T");
+ assertThat(result.path("unmetRequirements").size()).isEqualTo(4);
+ }
+
+ @Test
+ void searchesGlobalDegreeCombinationInsteadOfChoosingEveryPartIndependently() throws Exception {
+ save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_l", "arm_r"), json.readTree("[]"));
+ save("CW-L5", "arm_l", 5, "1", "0", "");
+ save("CW-L8", "arm_l", 8, "1", "0", "");
+ save("CW-R7", "arm_r", 7, "1", "0", "");
+ save("CW-R12", "arm_r", 12, "1", "0", "");
+ Map body = new LinkedHashMap<>(request("torso_0", "arm_l", "arm_r"));
+ body.put("robotRequirements", Map.of("degreesOfFreedom", 20));
+ JsonNode result = match(body);
+ assertThat(result.path("status").asText()).isEqualTo("MATCHED");
+ assertThat(part(result, "arm_l").path("componentCode").asText()).isEqualTo("CW-L8");
+ assertThat(part(result, "arm_r").path("componentCode").asText()).isEqualTo("CW-R12");
+ assertThat(result.path("totals").path("degreesOfFreedom").asInt()).isEqualTo(20);
+ }
+
+ @Test
+ void followsChainsWithoutAssumingRequestedRoleOrderAndNeverCreatesCycles() throws Exception {
+ save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r"), json.readTree("[]"));
+ save("CW-R", "arm_r", 3, "1", "0", "", metadata("RIGHT", "head_0", "hand_r", "torso_0"), json.readTree("[]"));
+ save("CW-H", "head_0", 0, "1", "0", "");
+ save("CW-HAND", "hand_r", 2, "1", "0", "");
+ JsonNode result = match(request("head_0", "hand_r", "torso_0", "arm_r"));
+ assertThat(result.path("status").asText()).isEqualTo("MATCHED");
+ assertThat(result.path("connections").size()).isEqualTo(3);
+ for (JsonNode connection : result.path("connections")) {
+ assertThat(connection.path("childCategory").asText()).isNotEqualTo("torso_0");
+ }
+ }
+
+ @Test
+ void doesNotAddUnrequestedConnectorsAndKeepsLeftRightIndependent() throws Exception {
+ save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_l", "arm_r"), json.readTree("[]"));
+ save("CW-L", "arm_l", 1, "1", "0", "", metadata("LEFT", "hand_l"), json.readTree("[]"));
+ save("CW-HAND", "hand_l", 1, "1", "0", "");
+ JsonNode result = match(request("torso_0", "hand_l", "arm_r"));
+ assertThat(result.path("status").asText()).isEqualTo("PARTIAL");
+ assertThat(result.path("parts").size()).isEqualTo(1);
+ assertThat(result.path("missingParts").size()).isEqualTo(2);
+ assertThat(result.path("missingParts").toString()).contains("NO_COMPONENT", "NO_COMPATIBLE_CONNECTION");
+ }
+
+ @Test
+ void missingTorsoUsesRootWithMostReachableRequestedParts() throws Exception {
+ save("CW-HEAD", "head_0", 0, "1", "0", "");
+ save("CW-R", "arm_r", 3, "1", "0", "", metadata("RIGHT", "hand_r"), json.readTree("[]"));
+ save("CW-HAND", "hand_r", 2, "1", "0", "");
+ JsonNode result = match(request("torso_0", "head_0", "arm_r", "hand_r"));
+ assertThat(result.path("status").asText()).isEqualTo("PARTIAL");
+ assertThat(result.path("rootCategory").asText()).isEqualTo("arm_r");
+ assertThat(result.path("parts").size()).isEqualTo(2);
+ }
+
+ @Test
+ void unknownMassDoesNotPretendToMeetMassLimit() throws Exception {
+ save("CW-T", "torso_0", 0, "0", "0", "", metadata("BASE", "arm_r"), json.readTree("[]"));
+ save("CW-R", "arm_r", 4, "2", "0", "");
+ Map body = new LinkedHashMap<>(request("torso_0", "arm_r"));
+ body.put("robotRequirements", Map.of("massKg", 10, "operators", Map.of("massKg", "lte")));
+ body.put("partRequirements", List.of(Map.of("category", "torso_0", "massKg", 1, "operators", Map.of("massKg", "lte"))));
+ JsonNode result = match(body);
+ assertThat(result.path("status").asText()).isEqualTo("FALLBACK");
+ assertThat(result.path("totals").path("massKg").isNull()).isTrue();
+ assertThat(result.path("totals").path("knownMassKg").decimalValue()).isEqualByComparingTo("2");
+ assertThat(result.path("totals").path("massComplete").asBoolean()).isFalse();
+ assertThat(result.path("unmetRequirements").size()).isEqualTo(2);
+ for (JsonNode unmet : result.path("unmetRequirements")) assertThat(unmet.path("reason").asText()).isEqualTo("UNKNOWN_MASS");
+ }
+
+ @Test
+ void alternativesKeepChildrenRecomputePosesRootsAndGlobalConstraints() throws Exception {
+ JsonNode first = metadata("BASE_A", "arm_r");
+ JsonNode second = metadata("BASE_B", "arm_r");
+ ((com.fasterxml.jackson.databind.node.ObjectNode) second.path("frames").get(0))
+ .set("xyz", json.readTree("[2,3,4]"));
+ save("CW-A", "torso_0", 5, "1", "0", "", first, json.readTree("[]"));
+ save("CW-B", "torso_0", 9, "3", "0", "", second, json.readTree("{\"replacement\":true}"));
+ save("CW-BAD", "torso_0", 5, "1", "0", "");
+ save("CW-R", "arm_r", 1, "1", "0", "", metadata("ROOT_R"), json.readTree("[]"));
+ save("CW-R2", "arm_r", 1, "1", "0", "", metadata("NEW_ROOT_R"), json.readTree("[]"));
+ Map body = new LinkedHashMap<>(request("torso_0", "arm_r"));
+ body.put("robotRequirements", Map.of("degreesOfFreedom", 6, "massKg", 3, "operators", Map.of("massKg", "lte")));
+ JsonNode result = match(body);
+ assertThat(part(result, "torso_0").path("componentCode").asText()).isEqualTo("CW-A");
+ JsonNode torsoItems = alternatives(result, "torso_0");
+ assertThat(torsoItems.size()).isEqualTo(1);
+ JsonNode replacement = torsoItems.get(0);
+ assertThat(replacement.path("component").path("componentCode").asText()).isEqualTo("CW-B");
+ assertThat(replacement.path("connections").get(0).path("xyz")).isEqualTo(json.readTree("[2,3,4]"));
+ assertThat(replacement.path("connections").get(0).path("parentLink").asText()).isEqualTo("BASE_B");
+ assertThat(replacement.path("totals").path("massKg").decimalValue()).isEqualByComparingTo("4");
+ assertThat(replacement.path("unmetRequirements").size()).isEqualTo(2);
+ assertThat(alternatives(result, "arm_r").get(0).path("connections").get(0).path("childRootLink").asText()).isEqualTo("NEW_ROOT_R");
+ }
+
+ @Test
+ void ignoresInvalidAndDuplicatePortsWithoutChangingReturnedMetadata() throws Exception {
+ JsonNode metadata = json.readTree("""
+ {"rootLink":"BASE","frames":[
+ {"name":"duplicate","kind":"joint","type":"fixed","parent":"BASE","child":"A","interfaceType":"arm_r","xyz":[0,0,0],"rpy":[0,0,0]},
+ {"name":"duplicate","kind":"joint","type":"fixed","parent":"BASE","child":"B","interfaceType":"arm_r","xyz":[0,0,0],"rpy":[0,0,0]},
+ {"name":"bad_pose","kind":"joint","type":"fixed","parent":"BASE","child":"C","interfaceType":"head_0","xyz":[0,0],"rpy":[0,0,0]},
+ {"name":"implicit","kind":"joint","type":"fixed","parent":"BASE","child":"D","interfaceType":"hand_r","originExplicit":false}
+ ]}
+ """);
+ save("CW-T", "torso_0", 0, "1", "0", "", metadata, json.readTree("[]"));
+ save("CW-R", "arm_r", 1, "1", "0", "");
+ save("CW-H", "hand_r", 1, "1", "0", "");
+ JsonNode result = match(request("torso_0", "arm_r", "hand_r"));
+ assertThat(result.path("parts").size()).isEqualTo(2);
+ assertThat(result.path("connections").get(0).path("xyz")).isEqualTo(json.readTree("[0,0,0]"));
+ assertThat(part(result, "torso_0").get("urdfInfo")).isEqualTo(metadata);
+ }
+
+ @Test
+ void logicDeletedComponentsDisappearAndResourceReplacementChangesDirectUrl() throws Exception {
+ save("CW-T", "torso_0", 0, "1", "0", "");
+ String firstUrl = components.get("CW-T").urdfUrl();
+ jdbc.update("UPDATE component SET version=2,urdf_main_object_key='cadworld/components/CW-T/urdf/new-batch/robot.urdf' WHERE component_code='CW-T'");
+ assertThat(components.get("CW-T").urdfUrl()).isNotEqualTo(firstUrl).contains("/new-batch/");
+ jdbc.update("UPDATE component SET deleted=1 WHERE component_code='CW-T'");
+ mvc.perform(get("/api/components/CW-T")).andExpect(status().isNotFound());
+ assertThat(match(request("torso_0")).path("status").asText()).isEqualTo("NO_MATCH");
+ }
+
+ @Test
+ void stableResultsAndAlternativesAreCappedAtFive() throws Exception {
+ for (int index = 9; index >= 0; index--) save("CW-" + index, "torso_0", 0, "1", "0", "");
+ JsonNode first = match(request("torso_0"));
+ JsonNode second = match(request("torso_0"));
+ assertThat(first).isEqualTo(second);
+ assertThat(first.path("parts").get(0).path("componentCode").asText()).isEqualTo("CW-0");
+ assertThat(alternatives(first, "torso_0").size()).isEqualTo(5);
+ }
+
+ @Test
+ void boundedSearchReturnsBestKnownConnectedResultAndMarksLimit() throws Exception {
+ save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_l", "arm_r", "head_0"), json.readTree("[]"));
+ save("CW-L", "arm_l", 1, "1", "0", "");
+ save("CW-R", "arm_r", 1, "1", "0", "");
+ save("CW-H", "head_0", 1, "1", "0", "");
+ MatchingProperties tiny = new MatchingProperties(50, 30, 128, 1, Map.of());
+ RobotMatchingService service = new RobotMatchingService(components, evaluator, new AssemblySearchEngine(tiny, evaluator), tiny);
+ RobotMatchResponse result = service.match(json.convertValue(request("torso_0", "arm_l", "arm_r", "head_0"), RobotMatchRequest.class));
+ assertThat(result.searchLimited()).isTrue();
+ assertThat(result.status()).isEqualTo("PARTIAL");
+ assertThat(result.parts()).hasSize(2);
+ assertThat(result.connections()).hasSize(1);
+ assertThat(result.missingParts()).allMatch((RobotMatchResponse.MissingPart missing) -> missing.reason().equals("SEARCH_LIMIT"));
+ }
+
+ @Test
+ void candidateTruncationIsReportedRatherThanClaimingAnExactOptimum() throws Exception {
+ save("CW-A", "torso_0", 1, "1", "0", "");
+ save("CW-B", "torso_0", 2, "1", "0", "");
+ MatchingProperties tiny = new MatchingProperties(1, 1, 128, 50000, Map.of());
+ RobotMatchingService service = new RobotMatchingService(components, evaluator, new AssemblySearchEngine(tiny, evaluator), tiny);
+ RobotMatchResponse result = service.match(json.convertValue(request("torso_0"), RobotMatchRequest.class));
+ assertThat(result.parts()).hasSize(1);
+ assertThat(result.searchLimited()).isTrue();
+ }
+
+ @Test
+ void scansPastFirstDatabasePageAndKeepsAConnectorOutsidePreferredCandidates() throws Exception {
+ for (int index = 0; index < 205; index++) {
+ save(String.format(java.util.Locale.ROOT, "CW-P%03d", index), "torso_0", 0, "1", "0", "");
+ }
+ save("CW-Z-CONNECTOR", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r"), json.readTree("[]"));
+ save("CW-ARM", "arm_r", 1, "1", "0", "");
+ JsonNode result = match(request("torso_0", "arm_r"));
+ assertThat(result.path("status").asText()).isEqualTo("MATCHED");
+ assertThat(result.path("searchLimited").asBoolean()).isTrue();
+ assertThat(part(result, "torso_0").path("componentCode").asText()).isEqualTo("CW-Z-CONNECTOR");
+ }
+
+ @Test
+ void keepsNumericExtremesOutsidePreferredCandidatesForGlobalGoals() throws Exception {
+ save("CW-T", "torso_0", 0, "1", "0", "", metadata("BASE", "arm_r"), json.readTree("[]"));
+ for (int index = 0; index < 60; index++) {
+ save(String.format(java.util.Locale.ROOT, "CW-P%03d", index), "arm_r", 1, "1", "0", "");
+ }
+ save("CW-Z-EXTREME", "arm_r", 20, "1", "0", "");
+ Map body = new LinkedHashMap<>(request("torso_0", "arm_r"));
+ body.put("robotRequirements", Map.of("degreesOfFreedom", 20));
+ JsonNode result = match(body);
+ assertThat(result.path("status").asText()).isEqualTo("MATCHED");
+ assertThat(result.path("searchLimited").asBoolean()).isTrue();
+ assertThat(part(result, "arm_r").path("componentCode").asText()).isEqualTo("CW-Z-EXTREME");
+ }
+
+ @Test
+ void defaultsNumericComparisonToEqualityAndUsesGteLteWithoutRounding() throws Exception {
+ save("CW-R", "arm_r", 5, "1.000001", "20.000001", "");
+ Map body = new LinkedHashMap<>(request("arm_r"));
+ body.put("robotRequirements", Map.of("degreesOfFreedom", 4, "operators", Map.of("degreesOfFreedom", "gte")));
+ body.put("partRequirements", List.of(Map.of("category", "arm_r", "torqueNm", new BigDecimal("20.000001"),
+ "massKg", new BigDecimal("1.000001"), "operators", Map.of("massKg", "lte"))));
+ assertThat(match(body).path("status").asText()).isEqualTo("MATCHED");
+ body.put("partRequirements", List.of(Map.of("category", "arm_r", "torqueNm", 20)));
+ JsonNode fallback = match(body);
+ assertThat(fallback.path("status").asText()).isEqualTo("FALLBACK");
+ assertThat(fallback.path("unmetRequirements").get(0).path("operator").asText()).isEqualTo("eq");
+ assertThat(fallback.path("unmetRequirements").get(0).path("actual").decimalValue()).isEqualByComparingTo("20.000001");
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"-1", "1.5", "1.0", "\"1\"", "true", "2147483648"})
+ void rejectsInvalidDegreesBeforeSearching(String value) throws Exception {
+ mvc.perform(post("/api/robot-matches").contentType(MediaType.APPLICATION_JSON)
+ .content("{\"requiredParts\":[\"arm_r\"],\"robotRequirements\":{\"degreesOfFreedom\":" + value + "}}"))
+ .andExpect(status().isUnprocessableEntity());
+ }
+
+ @ParameterizedTest
+ @ValueSource(strings = {"-1", "20.0000001", "1000000000000", "\"bad\""})
+ void rejectsInvalidTorqueBeforeSearching(String value) throws Exception {
+ mvc.perform(post("/api/robot-matches").contentType(MediaType.APPLICATION_JSON)
+ .content("{\"requiredParts\":[\"arm_r\"],\"partRequirements\":[{\"category\":\"arm_r\",\"torqueNm\":" + value + "}]}"))
+ .andExpect(status().isUnprocessableEntity());
+ }
+
+ @Test
+ void acceptsNumericBoundariesAndRejectsAmbiguousOrUnsupportedRequirements() throws Exception {
+ match(Map.of("requiredParts", List.of("arm_r"), "robotRequirements", Map.of("degreesOfFreedom", 2147483647),
+ "partRequirements", List.of(Map.of("category", "arm_r", "torqueNm", new BigDecimal("999999999999.999999")))));
+ List