六足拼装

This commit is contained in:
lxp
2026-10-16 17:54:43 +08:00
parent d7bad75558
commit 3a0a3c388c
32 changed files with 2571 additions and 127 deletions
+1 -1
View File
@@ -72,7 +72,7 @@ Spring Boot 不自动读取 `.env`,需要通过 shell 导入。默认 profile
先选定最符合需求的唯一躯干,再沿接口逐层选件。interfaceType 优先确定目标类型,缺失/无效时从 child 的 LINK_ 后解析现有类别;双方 frames[].child 严格一致才连接,name 不参与匹配。每个数组元素独立占用,同款组件可复用为多个实例;明确 quantity 优先,省略时填满所需类型的可匹配接口,单次最多24个实例。汇总和替代均按实例处理。
后端只返回实例及接口下标的连接关系,不再计算装配矩阵;原始 urdfInfo 保留,由前端决定摆放。组件类型统一使用[完整12类大写编码](cadworld-api/docs/api.md#36-角色映射),足部为 LEG_L/LEG_R;旧小写及 pedal_l/pedal_r 兼容输入。默认模板不变,不新增 leg_0 或四足/六足模板。历史结果通过新消息重新生成,无需数据库迁移。
后端只返回实例及接口下标的连接关系,不再计算装配矩阵;原始 urdfInfo 保留,由前端决定摆放。组件类型统一使用[完整16类大写编码](cadworld-api/docs/api.md#36-角色映射),足部为 LEG_L/LEG_R/LEG_0;旧小写及 pedal_l/pedal_r 兼容输入。默认人形按实际接口选择 L/R/0,臂、手、足、脚各合计至少两个;六足需求使用 hexapod 模板,只要求躯干和 LEG/FOOT 各至少六个实例。接口仍为 0 接 0、L 接 L、R 接 R;其他未配置形态保留差异。历史结果通过新消息重新生成,无需数据库迁移。
## 上传与接口
+52 -17
View File
@@ -92,7 +92,7 @@ X-Request-Id: frontend-match-001
| `requirements` | string[] | 否 | 最多 32 个关键词,每个非空且最多 128 字符;省略/null 表示无关键词要求 |
| `requiredParts` | string[] | 是 | 非空,最多 24 项;中英文别名归一化后去重,组件类型去重但支持同类型多个实例;未列出躯干时自动补入唯一 `TORSO_0` |
| `robotRequirements` | object | 否 | 整机条件,字段见下表 |
| `partRequirements` | object[] | 否 | 最多 12 项;每项对应一个角色的条件,字段见下表 |
| `partRequirements` | object[] | 否 | 最多 16 项;每项对应一个角色的条件,字段见下表 |
`userInput` 中写出的条件不会自动生效,前端必须同时提供相应结构化字段。例如“质量不超过 10kg”需要传 `massKg: 10` 和 `operators.massKg: "lte"`。
@@ -149,23 +149,29 @@ X-Request-Id: frontend-match-001
| 腰_0 | WAIST_0 |
| 左臂 | ARM_L |
| 右臂 | ARM_R |
| 不分左右的臂 | ARM_0 |
| 左手 | HAND_L |
| 右手 | HAND_R |
| 不分左右的手 | HAND_0 |
| 左足(腿部) | LEG_L |
| 右足(腿部) | LEG_R |
| 不分左右的足(腿部) | LEG_0 |
| 左脚 | FOOT_L |
| 右脚 | FOOT_R |
| 不分左右的脚 | FOOT_0 |
| 尾_0 | TAIL_0 |
以上12类为完整组件类型,公开响应统一使用大写标准编码。输入兼容英文大小写和原有中文别名;旧 `pedal_l/pedal_r` 兼容为 `LEG_L/LEG_R`。左右侧、足与脚独立,不互相替代。
以上16类为完整组件类型,公开响应统一使用大写标准编码。输入兼容英文大小写和原有中文别名;旧 `pedal_l/pedal_r` 兼容为 `LEG_L/LEG_R`。左右侧、足与脚独立,不互相替代。
`LINK_ARM_0`、`LINK_HAND_0`、`LINK_LEG_0`、`LINK_FOOT_0` 均为独立接口编码:0 只接 0,L 只接 L,R 只接 R,且原始 child 区分大小写。中性类型不作为左右接口的通配符。
组件库分类及 URDF `interfaceType` 均按上述类型识别,候选查询兼容已有大小写分类和旧足部编码;`interfaceType` 缺失时也可从 `LINK_LEG_L/LINK_LEG_R` 等 child 识别目标类型。原始 `urdfInfo` 保持不变,连接仍要求双方 `frames[].child` 区分大小写完全一致。实例编码同步使用大写类别,例如 `LEG_L:1`。
### 3.7 匹配结果的业务约定
先按角色查询未删除组件,再评价参数、材质和关键词。默认同义词包括跑步/奔跑/跑动/running、机器人/robot、双足/两足/biped/bipedal、铝合金/aluminum alloy/aluminium alloy。材质采用同义词归一化后的等值匹配,功能、形状和大小采用扩展后的包含匹配。名称、分类、功能、说明、材质、形状和大小参与关键词评价。
先按角色查询未删除组件,再评价参数、材质和关键词。默认同义词包括跑步/奔跑/跑动/running、机器人/robot、双足/两足/biped/bipedal、六足/六足机器人/六腿/六条腿/hexapod/hexapod robot、铝合金/aluminum alloy/aluminium alloy。材质采用同义词归一化后的等值匹配,功能、形状和大小采用扩展后的包含匹配。名称、分类、功能、说明、材质、形状和大小参与关键词评价;例如“六足机器人”可以命中说明“六足蜘蛛机器人躯干”。
先选定需求评分最高的一个躯干:按躯干自身条件的未满足数量、数值差距、功能文本和关键词相关性评价;需求评分相同时优先所需接口覆盖,最后按编码稳定排序。整机自由度、质量总量在选定躯干后的组合中评价,不直接作为躯干单件目标。
先选定需求评分最高的一个躯干:按躯干自身条件的未满足数量、数值差距、功能文本和关键词相关性评价。关键词先比较命中的不同需求数量,再比较字段权重,避免名称中的泛称“机器人”压过说明中的“六足”等具体要求;需求评分相同时优先所需接口覆盖,最后按编码稳定排序。整机自由度、质量总量在选定躯干后的组合中评价,不直接作为躯干单件目标。组合在既有完整性、参数和整体关键词评分相同后,继续比较各实例的关键词相关性,使带有六足说明的足部候选优先于无相关说明的同接口候选。
默认方案始终只有一个躯干且以 `TORSO_0` 为根,未列出躯干时自动补入。后续只沿这个躯干的接口路径匹配其他部件,在固定躯干下优先覆盖所需部件,再评价整机条件。选中的躯干不会因为另一个躯干能接更多部件而自动替换。参数与材质可降级,角色和连接规则始终保持匹配;不自动加入其他未要求的中间连接件。
@@ -179,6 +185,8 @@ X-Request-Id: frontend-match-001
## 4. 匹配结果
响应新增 `missingPartGroups`,每项为 `{family, categories, reason, expectedQuantity, actualQuantity, missingQuantity}`。它用于 AI 默认人形的部位合计缺口,例如 ARM 组允许 `ARM_L/ARM_R/ARM_0`、期望2个、实际1个、缺少1个;具体类别缺口仍放 `missingParts`。任一类缺口存在时为 `PARTIAL`,没有组件仍为 `NO_MATCH`。直接结构化请求不启用模板分组,`missingPartGroups` 返回 `[]`,也不接受 `templatePartGroups` 入参。
### 4.1 `data` 字段
| 字段 | 类型 | 内容 |
@@ -192,13 +200,14 @@ X-Request-Id: frontend-match-001
| `unmetRequirements` | object[] | 未满足的整机或部件条件,字段见 4.7 |
| `unmatchedKeywords` | string[] | 没有任何选中组件元数据命中的关键词 |
| `missingParts` | object[] | 未加入组合的角色和原因,字段见 4.7 |
| `missingPartGroups` | object[] | 后端模板部位合计缺口;直接结构化请求为 `[]` |
| `searchLimited` | boolean | 搜索是否达到候选/搜索限制;true 时仍可展示当前方案,但不代表已找到最优方案或证明组件库无解 |
| status | 含义 |
| --- | --- |
| `MATCHED` | 所需角色完整,所有提供条件和关键词均满足 |
| `FALLBACK` | 角色完整,部分条件或关键词不满足 |
| `PARTIAL` | 返回连通部分,存在缺失角色;也可能有参数不满足 |
| `PARTIAL` | 返回连通部分,存在缺失角色或模板部位合计数量不足;也可能有参数不满足 |
| `NO_MATCH` | 没有可用装配候选,parts和connections为空;HTTP仍为200 |
`searchLimited` 与 `status` 独立,例如 `MATCHED` 也可能同时返回 `searchLimited=true`。数组无内容时返回 `[]`。`parts` 的顺序不保证与请求一致,前端使用 `category` 和 `componentCode` 定位组件。
@@ -463,7 +472,8 @@ X-Request-Id: frontend-match-001
"unmetRequirements": [],
"unmatchedKeywords": [],
"missingParts": [],
"searchLimited": false
"searchLimited": false,
"missingPartGroups": []
}
}
```
@@ -569,24 +579,47 @@ X-Request-Id: frontend-match-001
{
"status": "FALLBACK",
"rootCategory": "TORSO_0",
"totals": {"degreesOfFreedom": 4, "massKg": 3.2, "knownMassKg": 3.2, "massComplete": true},
"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": "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": "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"
"scope": "ROBOT",
"category": null,
"field": "functionDescription",
"operator": "contains",
"expected": "跑步",
"actual": null,
"reason": "NO_TEXT_MATCH"
}
],
"unmatchedKeywords": ["跑步"],
"unmatchedKeywords": [
"跑步"
],
"missingParts": [],
"searchLimited": false
"searchLimited": false,
"missingPartGroups": []
}
```
@@ -625,7 +658,8 @@ X-Request-Id: frontend-match-001
"missingQuantity": 1
}
],
"searchLimited": false
"searchLimited": false,
"missingPartGroups": []
}
```
@@ -681,7 +715,8 @@ X-Request-Id: frontend-match-001
"missingQuantity": 1
}
],
"searchLimited": false
"searchLimited": false,
"missingPartGroups": []
}
}
```
+5 -3
View File
@@ -1,6 +1,6 @@
# 需求解析后端接入与部署
已按 `/Users/edy/Downloads/robot-demand-parser-v1` 的 README、backend-handoff、protocol,以及 `index.mjs` / `mechanical-rules.mjs` 移植 Java 程序校验。自动拼装输出版本为 `multimodal-v1.4-component-types`,目录版本为 `2026-10-16-component-types`。原始来源作为参考保留,当前提示词与 Java 规则已调整为无追问的自动生成流程。来源文件夹保持不变,运行时不依赖 Node、React 或前端解析脚本。
已按 `/Users/edy/Downloads/robot-demand-parser-v1` 的 README、backend-handoff、protocol,以及 `index.mjs` / `mechanical-rules.mjs` 移植 Java 程序校验。自动拼装输出版本为 `multimodal-v1.5-neutral-components`,目录版本为 `2026-10-16-hexapod-template`。原始来源作为参考保留,当前提示词与 Java 规则已调整为无追问的自动生成流程。来源文件夹保持不变,运行时不依赖 Node、React 或前端解析脚本。
业务标准化另外落实躯干优先规则:整机必须且只能有一个躯干,解析时可自动补入基础躯干;明确排除躯干时保留排除项并返回无匹配方案,不追问或偷偷补入。匹配先固定最符合需求的躯干,再搜索与其连通的其他组件。
@@ -64,7 +64,7 @@ java -jar cadworld-api/target/cadworld-api-0.0.1-SNAPSHOT.jar
组件组合仍为 MySQL + 同义词词典 + Java 有界搜索。候选查询只扫描同时具有非空 `step_object_key` 和 `urdf_main_object_key` 的组件,只有 STEP 的组件不参与默认方案或替代候选;新增时可先仅上传 STEP,再通过管理端修改补齐 URDF 和元数据。先按躯干单件硬要求、数值差距、偏好及功能/关键词相关性固定唯一躯干;评分相同后比较所需接口覆盖及编码。整机自由度和质量在后续组合求和评价。固定躯干后优先覆盖所需角色;在同等覆盖下,硬要求差距优先于偏好。先搜索其他部件硬条件满足的候选,再提供明确说明的降级结果,两轮共用同一个躯干;不以整机总量或覆盖率更换根。
没有可用躯干时返回无匹配结果,不再尝试其他角色为根。同一组件编码可生成多个独立实例,躯干仍固定一个,中英文类别别名先归一化。除作为基础部件自动补入的躯干外,不补入其他未要求的中间连接件;明确部位数量投影到 partRequirements.quantity(1–24);省略时先覆盖所需类型,再填充其可匹配剩余接口。实例标识、接口占用、替代和参数汇总均以实例为单位,不能按类别或组件编码去重。本次不增加类别或四足/六足模板。躯干替代项只用于替换当前唯一躯干。
没有可用躯干时返回无匹配结果,不再尝试其他角色为根。同一组件编码可生成多个独立实例,躯干仍固定一个,中英文类别别名先归一化。除作为基础部件自动补入的躯干外,不补入其他未要求的中间连接件;明确部位数量投影到 partRequirements.quantity(1–24);省略时先覆盖所需类型,再填充其可匹配剩余接口。实例标识、接口占用、替代和参数汇总均以实例为单位,不能按类别或组件编码去重。组件类型仍为16类,新增 hexapod 六足模板,未配置的其他形态继续保留差异。躯干替代项只用于替换当前唯一躯干。
`complete/partial/no_match` 描述需求匹配,`assembly.ready/blocked` 只描述是否有可展示组合和已生成的逻辑连接关系。缺件通过 `missingParts` 和 `partial` 提示,不进入 `assembly.issues`;缺件、性能不足或未验证能力不要求先接受降级,`degradationAcceptanceRequired` 固定为 false,因此 `partial` 可同时返回 `assembly.ready` 并直接显示已有有效组合。只有没有可用躯干/组件时才没有可展示组合;安装基准、位姿、活动关节和资源清单问题只返回提示,不阻塞已有组合。仅有有效躯干时可以显示躯干,连接数组为空。
@@ -72,7 +72,9 @@ java -jar cadworld-api/target/cadworld-api-0.0.1-SNAPSHOT.jar
## 接口数据与实例
已有 category 和默认模板保持不变。接口以合法 interfaceType 确定要查找的 category,缺失或无效时从 child 的 LINK_ 后解析已有类型编码/别名;无法确定类型时不从此接口向外扩展。目标类型必须属于需求,候选还须具有严格相同(区分大小写)的 child。frame 的 name、kind、type、坐标和安装基准不参与连接资格判断。
组件类型扩展为16类,新增 ARM_0/HAND_0/LEG_0/FOOT_0。默认人形使用臂、手、足、脚四组各至少两个实例的要求,根据实际接口选择 L/R/0。明确六足需求使用 hexapod 模板,只要求躯干及 LEG/FOOT 各至少六个实例,不沿用人形部位要求。接口以合法 interfaceType 确定要查找的 category,缺失或无效时从 child 的 LINK_ 后解析已有类型编码/别名;无法确定类型时不从此接口向外扩展。目标类型必须属于需求,候选还须具有严格相同(区分大小写)的 child。frame 的 name、kind、type、坐标和安装基准不参与连接资格判断。
四类中性接口均严格按 0 接 0、L 接 L、R 接 R 处理。默认模板的候选类型通过后端生成的 `result.request.templatePartGroups` 扩展,具体类别和分组合计缺口分别返回 `missingParts`、`missingPartGroups`。部署时同步读取 `multimodal-v1.5-neutral-components`;消息请求参数不变,无需数据库迁移,原始 URDF 与历史方案均不回写。
```json
{
+57 -11
View File
@@ -2,7 +2,7 @@
服务地址默认 `http://127.0.0.1:8991`。本流程接收用户文字、图片,自动理解需求、选件并校验装配,完成响应直接包含机器人方案。无需追问、确认或接受降级后才能显示。所有 JSON 接口和 SSE 事件数据沿用 `{code, message, data, requestId}`。
本文已按当前后端代码核对(2026-10-16),新生成结果的 `result.analysis.schemaVersion` 为 `multimodal-v1.4-component-types`。新方案的类别和实例编码使用[完整12类大写编码](api.md#36-角色映射),足部使用 `LEG_L/LEG_R`;旧小写及 `pedal_l/pedal_r` 仅作为兼容输入,原始 URDF 数据保持不变。本次对接变化如下:
本文已按当前后端代码核对(2026-10-16),新生成结果的 `result.analysis.schemaVersion` 为 `multimodal-v1.5-neutral-components`。新方案的类别和实例编码使用[完整16类大写编码](api.md#36-角色映射),足部使用 `LEG_L/LEG_R/LEG_0`;旧小写及 `pedal_l/pedal_r` 仅作为兼容输入,原始 URDF 数据保持不变。本次对接变化如下:
| 位置 | 当前约定 |
| --- | --- |
@@ -12,6 +12,8 @@
| `data.match.assembly.connections[]` | 双方实例编码、共同 `interfaceChild` 和双方原始 frames 下标;不再返回摆放矩阵及连接中的 xyz/rpy |
| `data.match.alternatives[]` | 按目标 `instanceId` 分组,切换时只替换该实例 |
| `data.match.missingParts[]` | 包含期望、实际、缺少数量;缺件时仍可展示已有连通组合 |
| `data.result.request.templatePartGroups[]` | 默认人形的四组部位合计要求,由后端生成 |
| `data.match.missingPartGroups[]` | 模板部位合计缺口;不会将同组未选类别逐一报为缺件 |
历史快照不会自动升级,联调新协议时请使用新的 `messageId` 生成结果。
@@ -221,7 +223,8 @@ async function sendMessage(conversationId, message, onEvent, signal) {
},
"quantity": 1
}
]
],
"templatePartGroups": []
},
"analysis": {
"summary": "右臂扭矩至少20N·m",
@@ -273,7 +276,7 @@ async function sendMessage(conversationId, message, onEvent, signal) {
"warnings": [
"整机拼装固定一个躯干,已补入TORSO_0作为基础组件。"
],
"catalogVersion": "2026-10-16-component-types",
"catalogVersion": "2026-10-16-hexapod-template",
"observations": [
{
"id": "e1",
@@ -320,7 +323,7 @@ async function sendMessage(conversationId, message, onEvent, signal) {
]
}
],
"schemaVersion": "multimodal-v1.4-component-types",
"schemaVersion": "multimodal-v1.5-neutral-components",
"canSubmit": true,
"status": "ready",
"defaultTemplate": ""
@@ -539,7 +542,8 @@ async function sendMessage(conversationId, message, onEvent, signal) {
"items": [],
"instanceId": "DM-33333333333333333333333333333333:ARM_R:1"
}
]
],
"missingPartGroups": []
}
},
"requestId": "frontend-demand-001"
@@ -552,9 +556,11 @@ async function sendMessage(conversationId, message, onEvent, signal) {
| `canSubmit` | 旧客户端兼容字段,新流程 `ready` 时为 true;无需展示确认按钮,不代表所有要求达标 |
| `questions` | 新生成结果固定为 `[]`,不发起追问 |
| `warnings` | 来源、推断或能力承载方面的说明,供核对 |
| `result.request` | 规范化五字段需求;未提供的约束不会补成 0 |
| `result.request` | 规范化需求及后端生成的 templatePartGroups;未提供的约束不会补成 0 |
| `result.request.partRequirements[].quantity` | 部位实例数量,整数 1–24;省略/null 表示按可匹配接口填充,躯干固定一个;第 5 节给出多实例示例 |
| `result.analysis.schemaVersion` | 新生成结果为 `multimodal-v1.4-component-types`;旧快照可能仍为旧协议 |
| `result.request.templatePartGroups` | 后端生成的模板要求数组,每项为 `{family, categories, minimumQuantity}`;不作为消息或结构化匹配入参 |
| `match.missingPartGroups` | 部位合计缺口,每项含 `family`、`categories`、`reason`、`expectedQuantity`、`actualQuantity`、`missingQuantity`;有缺口时为 `partial` |
| `result.analysis.schemaVersion` | 新生成结果为 `multimodal-v1.5-neutral-components`;旧快照可能仍为旧协议 |
| `result.analysis.intentItems` | 逐项需求,`must` 硬要求、`prefer` 偏好、`context` 参考;用于结果说明和逐项核对 |
| `result.analysis.defaultTemplate` | 没有可匹配类型或部位时使用的默认模板编码,目前为 `biped`;没有采用默认模板时为空字符串 |
| `match` | 已保存的完整机器人方案,包含组件资源、装配连接、缺件和逐项校验;处理未完成或已失效时为空 |
@@ -591,7 +597,7 @@ async function sendMessage(conversationId, message, onEvent, signal) {
整机结果始终以 `TORSO_0` 为根,默认方案中的躯干只有一个。用户未单独提出躯干时,后端在规范化的 `requiredParts` 中补入 `TORSO_0` 并返回说明;原始对话和提取的用户条目保持其来源。明确要求“不要躯干”时保留排除项,返回 `no_match`、`missingParts.reason=EXCLUDED_TORSO`,不会偷偷补入躯干;同款组件支持多个独立实例,躯干始终固定一个。
躯干先按自身硬条件、数值差距、偏好、整机功能文本与关键词相关性排序;这些条件相同后优先选择能接更多所需角色的接口集合,最后按编码稳定排序。整机自由度和质量目标在后续组合阶段评价,不直接当作躯干单件的数值要求。
躯干先按自身硬条件、数值差距、偏好、整机功能文本与关键词相关性排序。关键词先比较命中的不同需求数量,再比较字段权重,因此说明中匹配六足需求的躯干不会被只命中泛称“机器人”的普通躯干压过;这些条件相同后优先选择能接更多所需角色的接口集合,最后按编码稳定排序。整机自由度和质量目标在后续组合阶段评价,不直接当作躯干单件的数值要求。
选定躯干后不因其他躯干能多接几件或更接近整机总量而自动换根。其他组件须能通过现有接口路径连接到这个躯干;例如右手通过右臂连接,允许沿链匹配,但不自动补入未要求的中间连接件。达标搜索和降级搜索沿用同一个躯干。缺件时返回该躯干及可连接的部分方案;无可用躯干时返回 `no_match`,不会用头部或手臂代替根。
@@ -631,7 +637,8 @@ async function sendMessage(conversationId, message, onEvent, signal) {
}
],
"issues": []
}
},
"missingPartGroups": []
}
```
@@ -787,6 +794,44 @@ async function sendMessage(conversationId, message, onEvent, signal) {
| `resources[]` | object[] | 每项包含 `relativePath`、`url`、`version`、`expiresAt`,供前端加载 URDF 和 mesh |
| `resourceIssues[]` | object[] | 当前组件的资源清单提示,每项含 `code`、`category`、`componentCode`、`message` |
### 六足模板
目录支持 `biped`(默认人形/双足)和 `hexapod`(六足)。明确说“拼一个六足机器人”时选择 `hexapod`,不会回退到双足模板。六足模板只必需一个 `TORSO_0`,并生成 LEG、FOOT 两组各至少6个实例的要求;L/R/0 由实际接口决定,不强制分成左右各三,也不默认添加头、腰、臂、手或尾。未说明形态的需求仍沿用默认双足模板。
六足/六足机器人/hexapod 等同义词会参与名称与说明匹配。例如说明“六足蜘蛛机器人躯干”可命中“六足机器人”,随后沿该躯干的六个足部接口分别生成实例;相同 child 的三个左足接口和三个右足接口各自独立占用。六足分组使用现有 `templatePartGroups`、`missingPartGroups` 结构,没有新增消息参数。目录版本为 `2026-10-16-hexapod-template`,历史方案须通过新的 `messageId` 重新生成。
名称或说明中的六足标注用于候选相关性;六足模板与接口连接不证明行走速度、载荷或稳定性达标,这类要求继续单独核对。
### 默认人形与中性组件
默认人形的 `requiredParts` 为 `TORSO_0/HEAD_0/WAIST_0`,其余部位由 `templatePartGroups` 表达。四组均允许同一部位的 L/R/0,`minimumQuantity=2`;不会把所有候选类别都当成必须各装一个。
```json
{
"requiredParts": ["TORSO_0", "HEAD_0", "WAIST_0"],
"templatePartGroups": [
{"family": "ARM", "categories": ["ARM_L", "ARM_R", "ARM_0"], "minimumQuantity": 2},
{"family": "HAND", "categories": ["HAND_L", "HAND_R", "HAND_0"], "minimumQuantity": 2},
{"family": "LEG", "categories": ["LEG_L", "LEG_R", "LEG_0"], "minimumQuantity": 2},
{"family": "FOOT", "categories": ["FOOT_L", "FOOT_R", "FOOT_0"], "minimumQuantity": 2}
]
}
```
以上是后端规范化结果的摘录,不能直接提交到消息接口或结构化匹配接口。单部位未说明左右时,AI 默认推断为 `_0`;明确左右则保留 L/R。物理接口继续严格匹配:`LINK_ARM_0` 只接 `LINK_ARM_0`,不能接 `LINK_ARM_L/R`,手、足、脚同理。
两个 `ARM_0` 实例或一个 `ARM_L` 加一个 `ARM_0` 实例均可满足 ARM 组;同款组件实例独立计数。接口不足时,例如只有一个可连接的臂,缺口如下,方案状态为 `partial`:
```json
{
"missingPartGroups": [
{"family": "ARM", "categories": ["ARM_L", "ARM_R", "ARM_0"], "reason": "NO_COMPATIBLE_CONNECTION", "expectedQuantity": 2, "actualQuantity": 1, "missingQuantity": 1}
]
}
```
明确类别和参数要求仍单独生效,同一实例可同时计入具体类别与所属组,但总质量和自由度只累计一次。`partRequirements[].quantity` 限制该具体类别的数量;模板不能突破这个限制,有冲突时保留组缺口。明确排除项从组候选中移除,整个部位被排除时移除该默认组。自动增补仍受参数条件和24实例上限约束,默认不加入尾部。
### 数量入参与多实例返回示例
消息接口的数量仍用自然语言提交:
@@ -808,7 +853,7 @@ async function sendMessage(conversationId, message, onEvent, signal) {
}
```
`quantity` 为 1–24 的 JSON 整数;省略或为 null 表示先覆盖各个所需类型,再填满这些类型的可匹配剩余接口。自动填充以可验证的硬要求为前提,不为多装组件而破坏本可满足的整机质量或自由度条件;明确数量不足或硬条件无法满足时保留差异。每个物理接口只能连接一个实例;同 child 的多个 frames 元素是不同接口,不合并。本次沿用已有 category 和模板,不新增 leg_0 或四足/六足模板。
`quantity` 为 1–24 的 JSON 整数;省略或为 null 表示先覆盖各个所需类型,再填满这些类型的可匹配剩余接口。自动填充以可验证的硬要求为前提,不为多装组件而破坏本可满足的整机质量或自由度条件;明确数量不足或硬条件无法满足时保留差异。每个物理接口只能连接一个实例;同 child 的多个 frames 元素是不同接口,不合并。新增 ARM_0/HAND_0/LEG_0/FOOT_0 后,默认人形以部位分组要求各至少两个实例,具体类型按严格接口连接选择;六足另使用 hexapod 模板的 LEG/FOOT 各至少六个实例要求。
双足模板直接使用 `LEG_L/LEG_R`。只要腰部与腿部的原始接口 child 分别严格匹配 `LINK_LEG_L`、`LINK_LEG_R`,就能沿腰部连接双腿;公开 `component.category` 返回 `LEG_L/LEG_R`,原始 `urdfInfo` 不变。旧 `pedal_l/pedal_r` 兼容输入会归一化为 `LEG_L/LEG_R`。部署类型统一修复后,旧方案需要发送新的 `messageId` 重新生成。
@@ -915,7 +960,8 @@ async function sendMessage(conversationId, message, onEvent, signal) {
],
"issues": []
},
"missingParts": []
"missingParts": [],
"missingPartGroups": []
}
```
@@ -0,0 +1,31 @@
package com.linkerbot.cadworld.api;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.InputStream;
import org.springframework.jdbc.core.JdbcTemplate;
import static org.assertj.core.api.Assertions.assertThat;
final class ComponentFixtureSupport {
private ComponentFixtureSupport() { }
static void loadHexapodLibrary(JdbcTemplate jdbc, ObjectMapper json) throws Exception {
try (InputStream stream = ComponentFixtureSupport.class.getResourceAsStream("/fixtures/hexapod-library-components.json")) {
assertThat(stream).isNotNull();
for (JsonNode row : json.readTree(stream)) {
jdbc.update("""
INSERT INTO component (component_code,component_name,category,description,material,mass_kg,
degrees_of_freedom,function_description,shape,size,torque_nm,bom_list,urdf_info,
step_object_key,urdf_prefix,urdf_main_object_key,urdf_files,version)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
""", row.path("component_code").asText(), row.path("component_name").asText(), row.path("category").asText(),
row.path("description").asText(), row.path("material").asText(), row.path("mass_kg").decimalValue(),
row.path("degrees_of_freedom").asInt(), row.path("function_description").asText(), row.path("shape").asText(),
row.path("size").asText(), row.path("torque_nm").decimalValue(), row.path("bom_list").toString(), row.path("urdf_info").toString(),
row.path("step_object_key").asText(), row.path("urdf_prefix").asText(), row.path("urdf_main_object_key").asText(),
row.path("urdf_files").toString(), row.path("version").asLong());
}
}
}
}
@@ -269,6 +269,131 @@ class DemandFlowApiTest {
assertThat(generatedMatch(session, generated.path("analysisId").asText(), 1)).isEqualTo(match);
}
@ParameterizedTest
@ValueSource(strings = {"neutral", "sided", "mixed"})
void defaultHumanoidUsesAvailableStrictInterfacesAndCountsFamilies(String mode) throws Exception {
humanoidComponents(mode);
defaultHumanoidModel();
JsonNode generated = submit(create(), "m-default-" + mode, "拼个人形机器人", List.of());
JsonNode match = generated.path("match");
assertThat(match.path("status").asText()).isEqualTo("complete");
assertThat(match.path("components")).hasSize(11);
assertThat(match.path("missingParts")).isEmpty();
assertThat(match.path("missingPartGroups")).isEmpty();
assertThat(generated.path("result").path("request").path("requiredParts"))
.isEqualTo(json.valueToTree(List.of("TORSO_0", "HEAD_0", "WAIST_0")));
assertThat(generated.path("result").path("request").path("templatePartGroups")).hasSize(4);
assertThat(match.path("totals").path("degreesOfFreedom").asInt()).isEqualTo(11);
assertThat(match.path("totals").path("massKg").decimalValue()).isEqualByComparingTo("11");
assertThat(match.path("assembly").path("connections")).hasSize(10);
for (JsonNode edge : match.path("assembly").path("connections")) {
JsonNode parent = selection(match, edge.path("parentInstanceId").asText());
JsonNode child = selection(match, edge.path("childInstanceId").asText());
String parentChild = parent.path("component").path("urdfInfo").path("frames").get(edge.path("parentFrameIndex").asInt()).path("child").asText();
String childChild = child.path("component").path("urdfInfo").path("frames").get(edge.path("childFrameIndex").asInt()).path("child").asText();
assertThat(parentChild).isEqualTo(childChild).isEqualTo(edge.path("interfaceChild").asText());
}
for (String family : List.of("ARM", "HAND", "LEG", "FOOT")) {
long actual = java.util.stream.StreamSupport.stream(match.path("components").spliterator(), false)
.filter((JsonNode part) -> part.path("component").path("category").asText().startsWith(family + "_")).count();
assertThat(actual).isEqualTo(2);
}
}
@Test void insufficientNeutralPortsReportGroupShortagesAndExplicitExclusionsAreRespected() throws Exception {
humanoidComponents("neutral");
ObjectNode torso = (ObjectNode) json.readTree(jdbc.queryForObject("SELECT urdf_info FROM component WHERE component_code='CW-TORSO_0'", String.class));
// frames[0] 为头,frames[1] 为腰,末尾两个 ARM_0 是不同安装口。
torso.withArray("frames").remove(3);
jdbc.update("UPDATE component SET urdf_info=? WHERE component_code='CW-TORSO_0'", torso.toString());
defaultHumanoidModel();
JsonNode first = submit(create(), "m-short", "拼个人形机器人", List.of()).path("match");
assertThat(first.path("status").asText()).isEqualTo("partial");
assertThat(first.path("missingParts")).isEmpty();
assertThat(first.path("missingPartGroups").findValuesAsText("family")).containsExactly("ARM", "HAND");
for (JsonNode group : first.path("missingPartGroups")) {
assertThat(group.path("expectedQuantity").asInt()).isEqualTo(2);
assertThat(group.path("actualQuantity").asInt()).isEqualTo(1);
assertThat(group.path("missingQuantity").asInt()).isEqualTo(1);
}
humanoidComponents("neutral");
doAnswer(invocation -> {
ObjectNode raw = humanoidRaw(invocation.getArgument(0));
for (String role : List.of("HAND_L", "HAND_R", "HAND_0")) raw.withArray("excludedCategories").addObject()
.put("category", role).putArray("evidenceIds").add("e1");
intent(raw, "exclusion", "手", "不要手");
return raw;
}).when(model).analyze(anyList());
JsonNode excluded = submit(create(), "m-excluded", "拼个人形机器人,不要手", List.of());
assertThat(excluded.path("match").path("components")).hasSize(9);
assertThat(excluded.path("match").path("components").findValuesAsText("category")).noneMatch((String role) -> role.startsWith("HAND_"));
assertThat(excluded.path("result").path("request").path("templatePartGroups").findValuesAsText("family")).doesNotContain("HAND");
assertThat(excluded.path("match").path("missingPartGroups")).isEmpty();
assertThat(excluded.path("match").path("requirementChecks").get(0).path("status").asText()).isEqualTo("satisfied");
}
@Test void unspecifiedSingleArmUsesNeutralTypeAndExplicitQuantity() throws Exception {
assemblyComponent("TORSO_0", "ARM_0", "ARM_0");
assemblyComponent("ARM_0");
doAnswer(invocation -> {
ObjectNode raw = raw(invocation.getArgument(0));
for (String field : List.of("constraints", "intentItems", "partCategories", "robotTypes")) raw.putArray(field);
raw.withArray("partCategories").addObject().put("category", "ARM_0").put("source", "inferred")
.put("reason", "未指定左右,默认不分左右的臂").putArray("evidenceIds").add("e1");
intent(raw, "quantity", "手臂", "一个手臂");
return raw;
}).when(model).analyze(anyList());
JsonNode generated = submit(create(), "m-single", "拼一个手臂", List.of());
assertThat(generated.path("result").path("request").path("partRequirements").get(0).path("category").asText()).isEqualTo("ARM_0");
assertThat(generated.path("result").path("request").path("partRequirements").get(0).path("quantity").asInt()).isEqualTo(1);
assertThat(generated.path("result").path("request").path("templatePartGroups")).isEmpty();
assertThat(generated.path("match").path("components")).hasSize(2);
assertThat(generated.path("match").path("requirementChecks").get(0).path("status").asText()).isEqualTo("satisfied");
}
@Test void hexapodDemandUsesProvidedSpiderTorsoAndSixIndependentLegAndFootInstances() throws Exception {
ComponentFixtureSupport.loadHexapodLibrary(jdbc, json);
doAnswer(invocation -> {
ObjectNode raw = raw(invocation.getArgument(0));
raw.put("summary", "组装六足机器人");
for (String field : List.of("constraints", "intentItems", "partCategories", "robotTypes", "keywords")) raw.putArray(field);
raw.withArray("robotTypes").addObject().put("type", "hexapod").put("source", "explicit")
.put("reason", "用户明确要求六足机器人").putArray("evidenceIds").add("e1");
for (String term : List.of("六足机器人", "机器人")) raw.withArray("keywords").addObject()
.put("term", term).put("source", "explicit").put("reason", "用户需求").put("negated", false).putArray("evidenceIds").add("e1");
return raw;
}).when(model).analyze(anyList());
Session session = create();
JsonNode generated = submit(session, "m-hexapod", "拼一个六足机器人", List.of());
JsonNode match = generated.path("match");
assertThat(match.path("status").asText()).isEqualTo("complete");
assertThat(match.path("components")).hasSize(13);
assertThat(match.path("components").get(0).path("component").path("componentCode").asText()).isEqualTo("CW-H6FQ6HHJ4KRENJY7");
assertThat(match.path("missingParts")).isEmpty();
assertThat(match.path("missingPartGroups")).isEmpty();
assertThat(match.path("unmatchedKeywords")).isEmpty();
Map<String, Integer> counts = new java.util.LinkedHashMap<>();
for (JsonNode part : match.path("components")) counts.merge(part.path("component").path("componentCode").asText(), 1, Integer::sum);
assertThat(counts).containsExactlyInAnyOrderEntriesOf(Map.of("CW-H6FQ6HHJ4KRENJY7", 1, "CW-KNARPS5W8TARSP7C", 3,
"CW-X0JZQ6E03EMTSD48", 3, "CW-QVMWMYD1VVA4JEF4", 6));
assertThat(match.path("assembly").path("status").asText()).isEqualTo("ready");
assertThat(match.path("assembly").path("connections")).hasSize(12);
java.util.Set<Integer> torsoPorts = new java.util.HashSet<>();
for (JsonNode edge : match.path("assembly").path("connections")) {
JsonNode parent = selection(match, edge.path("parentInstanceId").asText());
JsonNode child = selection(match, edge.path("childInstanceId").asText());
String parentChild = parent.path("component").path("urdfInfo").path("frames").get(edge.path("parentFrameIndex").asInt()).path("child").asText();
String childChild = child.path("component").path("urdfInfo").path("frames").get(edge.path("childFrameIndex").asInt()).path("child").asText();
assertThat(parentChild).isEqualTo(childChild).isEqualTo(edge.path("interfaceChild").asText());
if ("TORSO_0".equals(parent.path("component").path("category").asText())) torsoPorts.add(edge.path("parentFrameIndex").asInt());
}
assertThat(torsoPorts).hasSize(6);
assertThat(generated.path("result").path("request").path("requiredParts")).isEqualTo(json.valueToTree(List.of("TORSO_0")));
assertThat(generated.path("result").path("analysis").path("defaultTemplate").asText()).isEmpty();
assertThat(generated.path("warnings").toString()).doesNotContain("默认双足");
assertThat(generatedMatch(session, generated.path("analysisId").asText(), 1)).isEqualTo(match);
}
@Test void explicitlyExcludedTorsoIsNotSilentlyAddedByStructuredMatching() throws Exception {
components(true, 20);
doAnswer(invocation -> {
@@ -821,6 +946,52 @@ class DemandFlowApiTest {
raw.withArray("intentItems").addObject().put("id", "r" + (raw.path("intentItems").size() + 1)).put("dimension", dimension).put("subject", subject)
.put("requirement", requirement).put("priority", "must").put("source", "explicit").putArray("evidenceIds").add("e1");
}
private JsonNode selection(JsonNode match, String instanceId) {
for (JsonNode selection : match.path("components")) if (instanceId.equals(selection.path("instanceId").asText())) return selection;
throw new AssertionError("缺少实例 " + instanceId);
}
private ObjectNode humanoidRaw(List<DemandMessage> history) {
ObjectNode raw = raw(history);
for (String field : List.of("constraints", "intentItems", "partCategories", "robotTypes")) raw.putArray(field);
raw.withArray("robotTypes").addObject().put("type", "biped").put("source", "explicit")
.put("reason", "用户要求人形").putArray("evidenceIds").add("e1");
return raw;
}
private void defaultHumanoidModel() throws Exception {
doAnswer(invocation -> humanoidRaw(invocation.getArgument(0))).when(model).analyze(anyList());
}
private void humanoidComponents(String mode) {
jdbc.update("DELETE FROM component");
String first = "neutral".equals(mode) ? "0" : "L";
String second = "sided".equals(mode) ? "R" : "0";
assemblyComponent("TORSO_0", "HEAD_0", "WAIST_0", "ARM_" + first, "ARM_" + second);
assemblyComponent("HEAD_0");
assemblyComponent("WAIST_0", "LEG_" + first, "LEG_" + second);
for (String side : new java.util.LinkedHashSet<>(List.of(first, second))) {
assemblyComponent("ARM_" + side, "HAND_" + side);
assemblyComponent("HAND_" + side);
assemblyComponent("LEG_" + side, "FOOT_" + side);
assemblyComponent("FOOT_" + side);
}
}
private void assemblyComponent(String category, String... outgoing) {
String code = "CW-" + category;
String root = "TORSO_0".equals(category) ? "BASE" : "LINK_" + category;
save(code, category, 1, "1", 20, root, true);
ObjectNode info = json.createObjectNode().put("rootLink", root).put("robotName", code);
info.putArray("frames");
for (String port : outgoing) {
ObjectNode frame = info.withArray("frames").addObject().put("name", "LINK_" + port).put("child", "LINK_" + port)
.put("interfaceType", port).put("parent", root).put("type", "fixed").put("kind", "joint").put("originExplicit", true);
frame.putArray("xyz").add(0).add(0).add(0); frame.putArray("rpy").add(0).add(0).add(0);
}
if (!"TORSO_0".equals(category)) {
ObjectNode frame = info.withArray("frames").addObject().put("name", "__root_interface__").put("child", root)
.put("interfaceType", category).put("kind", "interface").put("isRoot", true);
frame.putArray("xyz").add(0).add(0).add(0); frame.putArray("rpy").add(0).add(0).add(0);
}
jdbc.update("UPDATE component SET urdf_info=? WHERE component_code=?", info.toString(), code);
}
private void components(boolean mount, int torque) {
save("CW-TORSO", "TORSO_0", 0, "2", 0, "BASE", true);
save("CW-ARM", "ARM_R", 4, "1", torque, "ARM_ROOT", mount);
@@ -113,17 +113,17 @@ class MatchingApiTest {
@ParameterizedTest
@ValueSource(booleans = {true, false})
void mapsEveryRoleAndDeduplicatesAliasesWithoutSwappingFeetOrSides(boolean standardCategories) throws Exception {
List<String> english = List.of("HEAD_0", "WAIST_0", "ARM_L", "ARM_R", "HAND_L", "HAND_R",
"LEG_L", "LEG_R", "FOOT_L", "FOOT_R", "TAIL_0");
List<String> chinese = List.of("头_0", "腰_0", "臂_l", "臂_r", "手_l", "手_r", "足_l", "足_r", "脚_l", "脚_r", "尾_0");
List<String> english = List.of("HEAD_0", "WAIST_0", "ARM_L", "ARM_R", "ARM_0", "HAND_L", "HAND_R", "HAND_0",
"LEG_L", "LEG_R", "LEG_0", "FOOT_L", "FOOT_R", "FOOT_0", "TAIL_0");
List<String> chinese = List.of("头_0", "腰_0", "臂_l", "臂_r", "臂_0", "手_l", "手_r", "手_0", "足_l", "足_r", "足_0", "脚_l", "脚_r", "脚_0", "尾_0");
save("CW-TORSO", standardCategories ? "TORSO_0" : "躯干_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), standardCategories ? english.get(index) : chinese.get(index), 1, "1", "0", "");
List<String> required = new ArrayList<>(chinese);
required.addAll(List.of("躯干_0", "torso_0", "arm_l", "pedal_l", "PEDAL_R"));
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(result.path("parts").size()).isEqualTo(16);
assertThat(result.path("connections").size()).isEqualTo(15);
assertThat(part(result, "LEG_L").path("componentCode").asText()).isEqualTo("CW-LEG_L");
assertThat(part(result, "FOOT_L").path("componentCode").asText()).isEqualTo("CW-FOOT_L");
}
@@ -711,6 +711,102 @@ class MatchingApiTest {
}
}
@ParameterizedTest
@ValueSource(strings = {"ARM", "HAND", "LEG", "FOOT"})
void neutralAndSidedInterfacesRequireIdenticalChildren(String family) throws Exception {
for (String parentSide : List.of("0", "L", "R")) {
for (String childSide : List.of("0", "L", "R")) {
jdbc.update("DELETE FROM component");
String parentRole = family + "_" + parentSide;
String childRole = family + "_" + childSide;
com.fasterxml.jackson.databind.node.ObjectNode info = (com.fasterxml.jackson.databind.node.ObjectNode) metadata("BASE", parentRole);
// 每类同时覆盖 interfaceType 和 child 回退识别。
((com.fasterxml.jackson.databind.node.ObjectNode) info.path("frames").get(0)).remove("interfaceType");
save("CW-T", "TORSO_0", 0, "1", "0", "", info, json.readTree("[]"));
save("CW-C", childRole, 1, "1", "0", "");
JsonNode result = match(request(childRole));
assertThat(result.path("parts")).as(parentRole + " -> " + childRole).hasSize(parentSide.equals(childSide) ? 2 : 1);
if (parentSide.equals(childSide)) {
assertThat(result.path("connections").get(0).path("interfaceChild").asText()).isEqualTo("LINK_" + parentRole);
}
}
}
}
@Test void groupedSelectionRespectsWholeRobotTotalsAndExplicitCategoryQuantity() throws Exception {
save("CW-T", "TORSO_0", 0, "1", "0", "", metadata("BASE", "ARM_0", "ARM_0", "ARM_0", "ARM_0"), json.readTree("[]"));
save("CW-A", "ARM_0", 1, "1", "20", "");
save("CW-B", "ARM_0", 1, "1", "25", "");
List<com.linkerbot.cadworld.dto.matching.TemplatePartGroup> groups = List.of(
new com.linkerbot.cadworld.dto.matching.TemplatePartGroup("ARM", List.of("ARM_L", "ARM_R", "ARM_0"), 2));
Map<String, Object> body = new LinkedHashMap<>(request("TORSO_0"));
body.put("robotRequirements", Map.of("degreesOfFreedom", 3, "massKg", 4));
RobotMatchResponse result = context.getBean(RobotMatchingService.class).matchConfirmed(json.convertValue(body, RobotMatchRequest.class), java.util.Set.of(), groups);
assertThat(result.parts()).hasSize(4);
assertThat(result.missingParts()).isEmpty();
assertThat(result.missingPartGroups()).isEmpty();
assertThat(result.unmetRequirements()).isEmpty();
assertThat(result.totals().degreesOfFreedom()).isEqualTo(3);
assertThat(result.totals().massKg()).isEqualByComparingTo("4");
assertThat(result.alternatives().stream().filter((RobotMatchResponse.Alternatives group) -> "ARM_0".equals(group.category())))
.allSatisfy((RobotMatchResponse.Alternatives group) -> assertThat(group.items()).hasSize(1));
body.put("requiredParts", List.of("ARM_0"));
body.remove("robotRequirements");
body.put("partRequirements", List.of(Map.of("category", "ARM_0", "quantity", 1)));
result = context.getBean(RobotMatchingService.class).matchConfirmed(json.convertValue(body, RobotMatchRequest.class), java.util.Set.of(), groups);
assertThat(result.parts()).hasSize(2);
assertThat(result.missingParts()).isEmpty();
assertThat(result.missingPartGroups()).singleElement().satisfies((RobotMatchResponse.MissingPartGroup group) -> {
assertThat(group.family()).isEqualTo("ARM");
assertThat(group.actualQuantity()).isEqualTo(1);
assertThat(group.missingQuantity()).isEqualTo(1);
});
assertThat(result.status()).isEqualTo("PARTIAL");
}
@Test void groupedTorsoCoverageHonorsQuantityCapsAndHardPartConditions() throws Exception {
save("CW-A", "TORSO_0", 0, "1", "0", "", metadata("BASE_A", "ARM_0", "ARM_0", "ARM_0"), json.readTree("[]"));
save("CW-B", "TORSO_0", 0, "1", "0", "", metadata("BASE_B", "ARM_0", "ARM_R"), json.readTree("[]"));
save("CW-NEUTRAL", "ARM_0", 1, "1", "20", "钢");
save("CW-RIGHT", "ARM_R", 1, "1", "20", "钢");
save("CW-WRONG", "ARM_0", 1, "1", "5", "铝合金");
Map<String, Object> body = new LinkedHashMap<>(request("ARM_0"));
body.put("partRequirements", List.of(Map.of("category", "ARM_0", "quantity", 1, "material", "钢", "torqueNm", 20)));
List<com.linkerbot.cadworld.dto.matching.TemplatePartGroup> groups = List.of(
new com.linkerbot.cadworld.dto.matching.TemplatePartGroup("ARM", List.of("ARM_L", "ARM_R", "ARM_0"), 2));
RobotMatchResponse result = context.getBean(RobotMatchingService.class).matchConfirmed(json.convertValue(body, RobotMatchRequest.class), java.util.Set.of(), groups);
assertThat(result.parts()).hasSize(3);
assertThat(result.parts().get(0).componentCode()).isEqualTo("CW-B");
assertThat(result.parts()).extracting(com.linkerbot.cadworld.dto.matching.PublicComponentResponse::componentCode)
.contains("CW-NEUTRAL", "CW-RIGHT").doesNotContain("CW-WRONG");
assertThat(result.missingPartGroups()).isEmpty();
assertThat(result.unmetRequirements()).isEmpty();
}
@Test void acceptsPartRequirementsForAllSixteenTypesAndRejectsPublicTemplateGroups() throws Exception {
List<String> codes = java.util.Arrays.stream(com.linkerbot.cadworld.service.matching.ComponentRole.values())
.map(com.linkerbot.cadworld.service.matching.ComponentRole::code).toList();
Map<String, Object> body = new LinkedHashMap<>();
body.put("requiredParts", codes);
body.put("partRequirements", codes.stream().map((String code) -> Map.of("category", code, "material", "钢")).toList());
assertThat(match(body).path("status").asText()).isEqualTo("NO_MATCH");
body.put("templatePartGroups", List.of());
mvc.perform(post("/api/robot-matches").contentType(MediaType.APPLICATION_JSON).content(json.writeValueAsBytes(body)))
.andExpect(status().isUnprocessableEntity());
}
@ParameterizedTest
@ValueSource(strings = {"六足机器人", "六足", "hexapod robot"})
void hexapodDescriptionMatchesMoreRequirementsThanGenericRobotName(String term) throws Exception {
ComponentFixtureSupport.loadHexapodLibrary(jdbc, json);
// 仅保留 description 中的六足标注,验证说明本身足以影响选件。
jdbc.update("UPDATE component SET component_name='躯干_0_专用机身' WHERE component_code='CW-H6FQ6HHJ4KRENJY7'");
JsonNode result = match(Map.of("requiredParts", List.of("TORSO_0"), "requirements", List.of(term, "机器人")));
assertThat(part(result, "TORSO_0").path("componentCode").asText()).isEqualTo("CW-H6FQ6HHJ4KRENJY7");
assertThat(result.path("unmatchedKeywords")).isEmpty();
assertThat(part(result, "TORSO_0").path("description").asText()).isEqualTo("六足蜘蛛机器人躯干");
}
private Map<String, Object> request(String... roles) { return Map.of("requiredParts", List.of(roles)); }
private JsonNode match(Map<String, Object> body) throws Exception {
File diff suppressed because it is too large Load Diff
@@ -12,7 +12,7 @@ public record RobotMatchRequest(
@Size(max = 32) List<@NotBlank @Size(max = 128) String> requirements,
@NotEmpty @Size(max = 24) List<@NotBlank @Size(max = 64) String> requiredParts,
@Valid RobotRequirements robotRequirements,
@Size(max = 12) List<@NotNull @Valid PartRequirements> partRequirements) {
@Size(max = 16) List<@NotNull @Valid PartRequirements> partRequirements) {
@Override
public String toString() {
return "RobotMatchRequest[requiredPartCount=" + (requiredParts == null ? 0 : requiredParts.size())
@@ -7,7 +7,15 @@ public record RobotMatchResponse(
String status, String rootCategory, List<PublicComponentResponse> parts,
List<Connection> connections, List<Alternatives> alternatives, Totals totals,
List<UnmetRequirement> unmetRequirements, List<String> unmatchedKeywords,
List<MissingPart> missingParts, boolean searchLimited) {
List<MissingPart> missingParts, List<MissingPartGroup> missingPartGroups, boolean searchLimited) {
public RobotMatchResponse(String status, String rootCategory, List<PublicComponentResponse> parts,
List<Connection> connections, List<Alternatives> alternatives, Totals totals,
List<UnmetRequirement> unmetRequirements, List<String> unmatchedKeywords,
List<MissingPart> missingParts, boolean searchLimited) {
this(status, rootCategory, parts, connections, alternatives, totals, unmetRequirements, unmatchedKeywords,
missingParts, List.of(), searchLimited);
}
public record Connection(String parentCategory, String parentComponentCode, String parentLink,
String frameName, String childCategory, String childComponentCode,
@@ -23,6 +31,9 @@ public record RobotMatchResponse(
public MissingPart(String category, String reason) { this(category, reason, 1, 0, 1); }
}
public record MissingPartGroup(String family, List<String> categories, String reason,
int expectedQuantity, int actualQuantity, int missingQuantity) { }
public record Alternatives(String category, String instanceId, List<Replacement> items) { }
public record Replacement(PublicComponentResponse component, List<Connection> connections, Totals totals,
@@ -0,0 +1,6 @@
package com.linkerbot.cadworld.dto.matching;
import java.util.List;
/** 后端模板生成的同部位数量要求,不作为消息或结构化匹配的请求参数。 */
public record TemplatePartGroup(String family, List<String> categories, int minimumQuantity) { }
@@ -25,6 +25,7 @@ public record MatchingProperties(
groups.put("跑步", List.of("奔跑", "跑动", "running"));
groups.put("机器人", List.of("robot"));
groups.put("双足", List.of("两足", "biped", "bipedal"));
groups.put("六足", List.of("六足机器人", "六腿", "六条腿", "hexapod", "hexapodal", "hexapod robot"));
groups.put("铝合金", List.of("aluminum alloy", "aluminium alloy"));
if (synonyms != null) {
synonyms.forEach((String key, List<String> values) -> groups.put(key, List.copyOf(values)));
@@ -12,6 +12,7 @@ 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.dto.matching.RobotRequirements;
import com.linkerbot.cadworld.dto.matching.TemplatePartGroup;
import com.linkerbot.cadworld.entity.Component;
import com.linkerbot.cadworld.mapper.ComponentMapper;
import com.linkerbot.cadworld.service.impl.ObjectStorageUrlResolver;
@@ -52,7 +53,7 @@ public final class DemandMatchService {
response = new RobotMatchResponse("NO_MATCH", null, List.of(), List.of(), List.of(),
new RobotMatchResponse.Totals(0, null, BigDecimal.ZERO, false), List.of(), List.of(), missing, false);
} else {
response = matching.matchConfirmed(project(analysis.result()), requirements.softFields(analysis.result()));
response = matching.matchConfirmed(project(analysis.result()), requirements.softFields(analysis.result()), templateGroups(analysis.result()));
}
ObjectNode result = build(matchId, analysis, response);
log.info("需求自动选件与装配校验完成 requestId={} analysisId={} revision={} matchId={} selectedCount={} missingCount={} unmetCount={} status={} assemblyStatus={} assemblyIssueCodes={} durationMs={}",
@@ -69,7 +70,7 @@ public final class DemandMatchService {
ArrayNode checks = requirements.check(analysis.result(), response);
boolean unmet = hardUnmet(analysis.result(), response.unmetRequirements());
for (JsonNode check : checks) unmet |= "must".equals(check.path("priority").asText()) && !"satisfied".equals(check.path("status").asText());
String status = response.parts().isEmpty() ? "no_match" : !response.missingParts().isEmpty() || unmet ? "partial" : "complete";
String status = response.parts().isEmpty() ? "no_match" : !response.missingParts().isEmpty() || !response.missingPartGroups().isEmpty() || unmet ? "partial" : "complete";
ObjectNode result = json.createObjectNode().put("analysisId", analysis.analysisId()).put("revision", analysis.revision()).put("matchId", matchId)
.put("status", status).put("rootCategory", response.rootCategory()).put("searchLimited", response.searchLimited())
.put("degradationAcceptanceRequired", false).put("degradationAccepted", false);
@@ -77,6 +78,7 @@ public final class DemandMatchService {
result.set("unmetRequirements", json.valueToTree(response.unmetRequirements()));
result.set("unmatchedKeywords", json.valueToTree(response.unmatchedKeywords()));
result.set("missingParts", json.valueToTree(response.missingParts()));
result.set("missingPartGroups", json.valueToTree(response.missingPartGroups()));
result.set("requirementChecks", checks);
ArrayNode components = result.putArray("components");
for (PublicComponentResponse part : response.parts()) components.add(component(matchId, part));
@@ -87,7 +89,7 @@ public final class DemandMatchService {
for (RobotMatchResponse.Replacement replacement : group.items()) {
List<PublicComponentResponse> replacedParts = response.parts().stream().map((PublicComponentResponse part) -> part.instanceId().equals(group.instanceId()) ? replacement.component() : part).toList();
RobotMatchResponse replaced = new RobotMatchResponse(response.status(), response.rootCategory(), replacedParts, replacement.connections(), List.of(),
replacement.totals(), replacement.unmetRequirements(), replacement.unmatchedKeywords(), response.missingParts(), response.searchLimited());
replacement.totals(), replacement.unmetRequirements(), replacement.unmatchedKeywords(), response.missingParts(), response.missingPartGroups(), response.searchLimited());
ArrayNode replacementChecks = requirements.check(analysis.result(), replaced);
ObjectNode item = items.addObject();
item.set("component", json.valueToTree(replacement.component().withInstanceId(null)));
@@ -155,6 +157,17 @@ public final class DemandMatchService {
return true;
}
private List<TemplatePartGroup> templateGroups(JsonNode saved) {
try {
List<TemplatePartGroup> groups = new ArrayList<>();
for (JsonNode group : saved.path("request").path("templatePartGroups")) groups.add(json.treeToValue(group, TemplatePartGroup.class));
return List.copyOf(groups);
} catch (Exception exception) {
log.warn("模板部位分组读取失败 requestId={} exceptionType={}", RequestIdHolder.get(), exception.getClass().getSimpleName());
throw new BizException(409, "DEMAND_UNSUPPORTED_REQUEST", "已保存需求包含无效部位分组,请重新生成方案");
}
}
private RobotMatchRequest project(JsonNode saved) {
try {
JsonNode request = saved.path("request");
@@ -27,12 +27,13 @@ final class DemandMechanicalNormalizer {
LinkedHashSet<String> warnings = new LinkedHashSet<>(texts(raw.path("warnings")));
ArrayNode unmodeled = raw.withArray("unmodeled").deepCopy();
LinkedHashSet<String> categories = new LinkedHashSet<>();
Map<String, JsonNode> templateGroups = new LinkedHashMap<>();
Set<String> excluded = new LinkedHashSet<>();
for (JsonNode item : raw.path("excludedCategories")) excluded.add(item.path("category").asText());
if (excluded.contains("TORSO_0")) warnings.add("已保留排除躯干的要求;现有装配规则必须以躯干为根,因此无法形成整机。");
for (JsonNode type : raw.path("robotTypes")) {
JsonNode template = template(type.path("type").asText());
categories.addAll(texts(template.path("parts")));
expandTemplate(template, categories, templateGroups);
String keyword = template.path("keyword").asText();
boolean present = false;
for (JsonNode item : raw.path("keywords")) present |= keyword.equals(item.path("term").asText());
@@ -43,7 +44,9 @@ final class DemandMechanicalNormalizer {
}
}
for (JsonNode item : raw.path("partCategories")) {
categories.add(item.path("category").asText());
String category = item.path("category").asText();
boolean templateChoice = templateGroups.values().stream().anyMatch((JsonNode group) -> texts(group.path("categories")).contains(category));
if (!templateChoice || "explicit".equals(item.path("source").asText())) categories.add(category);
}
Map<String, List<ObjectNode>> groups = new LinkedHashMap<>();
for (JsonNode input : raw.path("constraints")) {
@@ -101,7 +104,7 @@ final class DemandMechanicalNormalizer {
defaultTemplate = catalog.path("defaultTemplate").asText();
if (!defaultTemplate.isBlank()) {
JsonNode fallback = template(defaultTemplate);
categories.addAll(texts(fallback.path("parts")));
expandTemplate(fallback, categories, templateGroups);
warnings.add("未指定可匹配的机器人类型或部位,按默认" + fallback.path("label").asText() + "生成参考方案。");
}
}
@@ -118,6 +121,15 @@ final class DemandMechanicalNormalizer {
if (required.isEmpty()) warnings.add("当前需求没有可选部位,将返回无匹配结果。");
request.set("robotRequirements", robot);
request.set("partRequirements", json.valueToTree(parts.values()));
ArrayNode groupRequirements = request.putArray("templatePartGroups");
for (JsonNode group : templateGroups.values()) {
List<String> allowed = texts(group.path("categories")).stream().filter((String category) -> !excluded.contains(category)).toList();
// 明确排除整个部位时,模板不再要求补齐该部位。
if (allowed.isEmpty()) continue;
ObjectNode requirement = groupRequirements.addObject().put("family", group.path("family").asText())
.put("minimumQuantity", group.path("minimumQuantity").asInt());
requirement.set("categories", json.valueToTree(allowed));
}
ObjectNode analysis = raw.deepCopy();
analysis.set("unmodeled", unmodeled);
analysis.putArray("questions");
@@ -184,6 +196,11 @@ final class DemandMechanicalNormalizer {
return new Condition(null, combined, "eq");
}
private void expandTemplate(JsonNode template, Set<String> categories, Map<String, JsonNode> groups) {
categories.addAll(texts(template.path("parts")));
for (JsonNode group : template.path("partGroups")) groups.putIfAbsent(group.path("family").asText(), group);
}
private JsonNode template(String id) {
for (JsonNode template : catalog.path("templates")) if (id.equals(template.path("id").asText())) return template;
throw DemandRules.invalid("robotTypes");
@@ -138,7 +138,7 @@ public final class DemandNormalizer {
for (JsonNode item : raw.path("keywords")) keywordEvidence.addObject().put("term", item.path("term").asText()).set("evidenceIds", item.get("evidenceIds"));
warnings.addAll(DemandMechanicalNormalizer.texts(analysis.path("warnings")));
analysis.set("warnings", json.valueToTree(warnings));
analysis.put("schemaVersion", "multimodal-v1.4-component-types");
analysis.put("schemaVersion", "multimodal-v1.5-neutral-components");
analysis.putArray("questions");
analysis.put("canSubmit", true).put("status", "ready");
return result;
@@ -22,6 +22,8 @@ public final class DemandRequirementChecker {
Map.entry("ARM_R", List.of("ARM_R", "右臂")), Map.entry("HAND_L", List.of("HAND_L", "左手")),
Map.entry("HAND_R", List.of("HAND_R", "右手")), Map.entry("LEG_L", List.of("LEG_L", "PEDAL_L", "左足", "左腿")),
Map.entry("LEG_R", List.of("LEG_R", "PEDAL_R", "右足", "右腿")), Map.entry("FOOT_L", List.of("FOOT_L", "左脚")),
Map.entry("ARM_0", List.of("ARM_0", "臂_0")), Map.entry("HAND_0", List.of("HAND_0", "手_0")),
Map.entry("LEG_0", List.of("LEG_0", "足_0")), Map.entry("FOOT_0", List.of("FOOT_0", "脚_0")),
Map.entry("FOOT_R", List.of("FOOT_R", "右脚")), Map.entry("TAIL_0", List.of("TAIL_0", "尾")));
private final ObjectMapper json;
private final MatchTextService text;
@@ -73,7 +75,7 @@ public final class DemandRequirementChecker {
if (expected != null && quantitySupported(intent)) {
long actual = roles.isEmpty() ? match.parts().isEmpty() ? 0 : 1 : match.parts().stream().filter((PublicComponentResponse part) -> roles.contains(part.category())).count();
check.put("expected", expected).put("actual", actual);
if (roles.isEmpty() && !match.missingParts().isEmpty()) check.put("reason", "尚未形成完整整机,无法验证整机数量");
if (roles.isEmpty() && (!match.missingParts().isEmpty() || !match.missingPartGroups().isEmpty())) check.put("reason", "尚未形成完整整机,无法验证整机数量");
else check.put("status", actual == expected ? "satisfied" : "unmet").put("reason", actual == expected ? "所选组件实例数量满足条件" : "组件实例数量不足");
}
continue;
@@ -139,7 +141,7 @@ public final class DemandRequirementChecker {
if (allMapped) {
if (roles.size() > 1) { check.set("actual", actualByRole); check.set("expected", expectedByRole); }
if (unknown) check.put("status", "unverified").put("reason", "组件缺失或参数未填写,无法验证该要求");
else if (roles.isEmpty() && !match.missingParts().isEmpty()) check.put("status", "unverified").put("reason", "所需组件尚未齐全,无法验证整机总量");
else if (roles.isEmpty() && (!match.missingParts().isEmpty() || !match.missingPartGroups().isEmpty())) check.put("status", "unverified").put("reason", "所需组件尚未齐全,无法验证整机总量");
else check.put("status", allSatisfied ? "satisfied" : "unmet").put("reason", allSatisfied ? "所选组件的登记参数满足该条件" : "所选组件或汇总参数不满足该条件");
}
}
@@ -190,9 +192,27 @@ public final class DemandRequirementChecker {
Set<String> roles = new LinkedHashSet<>();
for (Map.Entry<String, List<String>> entry : ROLE_WORDS.entrySet()) for (String word : entry.getValue()) if (value.contains(word)) roles.add(entry.getKey());
if (subject.contains("双臂") || subject.contains("两臂")) { roles.add("ARM_L"); roles.add("ARM_R"); }
// 无左右证据的单部位按中性类型处理;显式代码和左右词优先。
boolean exclusion = requirement.matches(".*(?:不配备|不要|禁止|不包含).*" );
if (exclusion || !subject.matches(".*(?:整机|整体|全机|机器人).*")) {
String partSubject = exclusion && subject.matches(".*(?:整机|整体|全机|机器人).*") ? requirement : subject;
for (String phrase : partSubject.split("[、,,和与及\\s]+")) {
String noun = phrase.replaceAll("(?:不分左右|通用|组件|部件|数量|数目|不配备|不要|禁止|不包含|[一二两三四五六七八九十0-9个只条的部])", "");
if (List.of("手臂", "臂", "胳膊").contains(noun)) inferNeutral(roles, "ARM", exclusion);
if ("手".equals(noun)) inferNeutral(roles, "HAND", exclusion);
if (List.of("足", "腿").contains(noun)) inferNeutral(roles, "LEG", exclusion);
if ("脚".equals(noun)) inferNeutral(roles, "FOOT", exclusion);
}
}
return roles.stream().sorted().toList();
}
private static void inferNeutral(Set<String> roles, String family, boolean exclusion) {
if (roles.stream().anyMatch((String role) -> role.startsWith(family + "_"))) return;
if (exclusion) { roles.add(family + "_L"); roles.add(family + "_R"); }
roles.add(family + "_0");
}
static boolean quantitySupported(JsonNode intent) {
Integer expected = quantity(intent);
if (expected == null || expected < 1 || expected > 24) return false;
@@ -25,6 +25,8 @@ public class AssemblySearchEngine {
.thenComparingInt((ScoredState state) -> state.evaluation().preferredUnmetCount())
.thenComparing((ScoredState state) -> state.evaluation().preferredDeviation())
.thenComparing(Comparator.comparingInt((ScoredState state) -> state.evaluation().keywordScore()).reversed())
.thenComparing(Comparator.comparingInt(ScoredState::localKeywordCoverage).reversed())
.thenComparing(Comparator.comparingInt(ScoredState::localKeywordScore).reversed())
.thenComparing((ScoredState state) -> state.state().parts().values().stream()
.map(MatchingCandidate::code).collect(java.util.stream.Collectors.joining("\u0000")))
.thenComparing(ScoredState::key);
@@ -64,8 +66,7 @@ public class AssemblySearchEngine {
if (depth > frontierDepth) continue;
for (AssemblyMetadata.Port port : parent.getValue().metadata().ports()) {
if (port.role() == null || !request.canAdd(port.role(), state.count(port.role())) || state.portUsed(parent.getKey(), port.index())) continue;
if (coverMinimum && state.count(port.role()) >= request.minimum(port.role())) continue;
if (coverTypes && state.count(port.role()) > 0) continue;
if (coverMinimum && !request.needed(port.role(), state, coverTypes)) continue;
for (CandidatePool.Attachment target : pool.targets(port.role(), port.child())) {
frontierDepth = Math.min(frontierDepth, depth);
if (state.parts().size() >= AssemblyState.MAX_INSTANCES) { limited = true; continue; }
@@ -90,17 +91,19 @@ public class AssemblySearchEngine {
ScoredState score(AssemblyState state, NormalizedMatchRequest request, Map<ComponentRole, RequirementEvaluator.PoolSummary> summaries) {
RequirementEvaluator.Evaluation evaluation = evaluator.evaluate(state, request);
int missing = request.roles().stream().mapToInt((ComponentRole role) -> Math.max(0, request.minimum(role) - state.count(role))).sum();
int missingTypes = (int) request.roles().stream().filter((ComponentRole role) -> state.count(role) == 0).count();
return new ScoredState(state, evaluation, evaluator.estimate(state, evaluation, summaries, request), state.key(), missing, missingTypes);
int missing = request.missingMinimum(state);
int missingTypes = request.missingTypes(state);
int localCoverage = state.parts().values().stream().mapToInt((MatchingCandidate candidate) -> candidate.assessment().keywordCoverage()).sum();
int localScore = state.parts().values().stream().mapToInt((MatchingCandidate candidate) -> java.util.Arrays.stream(candidate.assessment().keywordScores()).sum()).sum();
return new ScoredState(state, evaluation, evaluator.estimate(state, evaluation, summaries, request), state.key(), missing, missingTypes,
localCoverage, localScore);
}
private boolean hasMinimumAttachment(AssemblyState state, CandidatePool.Result pool, NormalizedMatchRequest request, boolean uncoveredOnly) {
for (Map.Entry<String, MatchingCandidate> parent : state.parts().entrySet()) {
for (AssemblyMetadata.Port port : parent.getValue().metadata().ports()) {
if (port.role() == null || !request.canAdd(port.role(), state.count(port.role()))
|| state.count(port.role()) >= request.minimum(port.role()) || state.portUsed(parent.getKey(), port.index())) continue;
if (uncoveredOnly && state.count(port.role()) > 0) continue;
|| !request.needed(port.role(), state, uncoveredOnly) || state.portUsed(parent.getKey(), port.index())) continue;
if (!pool.targets(port.role(), port.child()).isEmpty()) return true;
}
}
@@ -108,6 +111,7 @@ public class AssemblySearchEngine {
}
record ScoredState(AssemblyState state, RequirementEvaluator.Evaluation evaluation,
RequirementEvaluator.Estimate estimate, String key, int missingMinimum, int missingTypes) { }
RequirementEvaluator.Estimate estimate, String key, int missingMinimum, int missingTypes,
int localKeywordCoverage, int localKeywordScore) { }
record Result(ScoredState best, boolean limited, int expansions) { }
}
@@ -35,6 +35,7 @@ final class CandidatePool {
.thenComparingInt((MatchingCandidate candidate) -> candidate.assessment().preferredUnmetCount())
.thenComparing((MatchingCandidate candidate) -> candidate.assessment().preferredDeviation())
.thenComparing((MatchingCandidate candidate) -> !candidate.assessment().robotFunctionMatched())
.thenComparing(Comparator.comparingInt((MatchingCandidate candidate) -> candidate.assessment().keywordCoverage()).reversed())
.thenComparing(Comparator.comparingInt((MatchingCandidate candidate) ->
java.util.Arrays.stream(candidate.assessment().keywordScores()).sum()).reversed());
this.demandOrder = demandScore
@@ -67,11 +68,19 @@ final class CandidatePool {
private int compatibleCoverage(MatchingCandidate candidate, Result pool) {
int covered = 0;
Map<ComponentRole, Integer> availablePorts = new EnumMap<>(ComponentRole.class);
for (ComponentRole role : request.roles()) {
if (role == ComponentRole.TORSO) continue;
long ports = candidate.metadata().ports().stream().filter((AssemblyMetadata.Port port) -> port.role() == role
&& !pool.targets(role, port.child()).isEmpty()).count();
covered += (int) Math.min(request.minimum(role), ports);
availablePorts.put(role, (int) Math.min(ports, request.quantity(role) == null ? AssemblyState.MAX_INSTANCES : request.quantity(role)));
}
for (NormalizedMatchRequest.PartGroup group : request.groups()) {
int available = group.roles().stream().mapToInt((ComponentRole role) -> availablePorts.getOrDefault(role, 0)).sum();
int explicit = group.roles().stream().mapToInt((ComponentRole role) ->
Math.min(request.minimum(role), availablePorts.getOrDefault(role, 0))).sum();
covered += Math.max(0, Math.min(group.minimumQuantity(), available) - explicit);
}
return covered;
}
@@ -9,9 +9,10 @@ import java.util.stream.Stream;
public enum ComponentRole {
TORSO("TORSO_0", "躯干_0"), HEAD("HEAD_0", "头_0"), WAIST("WAIST_0", "腰_0"),
ARM_L("ARM_L", "臂_l"), ARM_R("ARM_R", "臂_r"), HAND_L("HAND_L", "手_l"), HAND_R("HAND_R", "手_r"),
LEG_L("LEG_L", "足_l", "pedal_l"), LEG_R("LEG_R", "足_r", "pedal_r"),
FOOT_L("FOOT_L", "脚_l"), FOOT_R("FOOT_R", "脚_r"), TAIL("TAIL_0", "尾_0");
ARM_L("ARM_L", "臂_l"), ARM_R("ARM_R", "臂_r"), ARM_0("ARM_0", "臂_0"),
HAND_L("HAND_L", "手_l"), HAND_R("HAND_R", "手_r"), HAND_0("HAND_0", "手_0"),
LEG_L("LEG_L", "足_l", "pedal_l"), LEG_R("LEG_R", "足_r", "pedal_r"), LEG_0("LEG_0", "足_0"),
FOOT_L("FOOT_L", "脚_l"), FOOT_R("FOOT_R", "脚_r"), FOOT_0("FOOT_0", "脚_0"), TAIL("TAIL_0", "尾_0");
private final String code;
private final List<String> aliases;
@@ -4,6 +4,8 @@ import com.linkerbot.cadworld.common.exception.BizException;
import com.linkerbot.cadworld.dto.matching.PartRequirements;
import com.linkerbot.cadworld.dto.matching.RobotMatchRequest;
import com.linkerbot.cadworld.dto.matching.RobotRequirements;
import com.linkerbot.cadworld.dto.matching.TemplatePartGroup;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.LinkedHashMap;
@@ -14,19 +16,37 @@ import java.util.Map;
import java.util.Set;
record NormalizedMatchRequest(List<ComponentRole> roles, List<String> keywords,
RobotRequirements robot, Map<ComponentRole, PartRequirements> parts, Set<String> softFields) {
RobotRequirements robot, Map<ComponentRole, PartRequirements> parts, Set<String> softFields,
Set<ComponentRole> requiredRoles, List<PartGroup> groups) {
static NormalizedMatchRequest from(RobotMatchRequest request) {
return from(request, Set.of());
}
static NormalizedMatchRequest from(RobotMatchRequest request, Set<String> softFields) {
return from(request, softFields, List.of());
}
static NormalizedMatchRequest from(RobotMatchRequest request, Set<String> softFields, List<TemplatePartGroup> templateGroups) {
if (request.requiredParts() == null || request.requiredParts().isEmpty()) {
throw invalid("requiredParts不能为空");
}
Set<ComponentRole> required = new LinkedHashSet<>();
required.add(ComponentRole.TORSO);
request.requiredParts().stream().map(ComponentRole::require).forEach(required::add);
List<ComponentRole> roles = required.stream().sorted(Comparator.comparingInt(ComponentRole::ordinal)).toList();
Set<ComponentRole> available = new LinkedHashSet<>(required);
List<PartGroup> groups = new ArrayList<>();
Set<String> families = new LinkedHashSet<>();
for (TemplatePartGroup group : templateGroups) {
if (group == null || group.family() == null || !Set.of("ARM", "HAND", "LEG", "FOOT").contains(group.family()) || !families.add(group.family())
|| group.minimumQuantity() < 1 || group.minimumQuantity() > 24 || group.categories() == null || group.categories().isEmpty()) {
throw invalid("模板部位分组无效");
}
List<ComponentRole> members = group.categories().stream().map(ComponentRole::require).distinct().toList();
if (members.stream().anyMatch((ComponentRole role) -> !role.code().startsWith(group.family() + "_"))) throw invalid("模板分组包含其他部位");
groups.add(new PartGroup(group.family(), members, group.minimumQuantity()));
available.addAll(members);
}
List<ComponentRole> roles = available.stream().sorted(Comparator.comparingInt(ComponentRole::ordinal)).toList();
RobotRequirements supplied = request.robotRequirements();
RobotRequirements robot = supplied == null ? new RobotRequirements(null, null, null, Map.of())
: new RobotRequirements(supplied.degreesOfFreedom(), supplied.massKg(), text(supplied.functionDescription()),
@@ -34,7 +54,7 @@ record NormalizedMatchRequest(List<ComponentRole> roles, List<String> keywords,
Map<ComponentRole, PartRequirements> parts = new EnumMap<>(ComponentRole.class);
for (PartRequirements part : request.partRequirements() == null ? List.<PartRequirements>of() : request.partRequirements()) {
ComponentRole role = ComponentRole.require(part.category());
if (!roles.contains(role)) throw invalid("部件条件的category必须包含在requiredParts中");
if (!required.contains(role)) throw invalid("部件条件的category必须包含在requiredParts中");
if (parts.containsKey(role)) throw invalid("同一组件角色不得重复定义部件条件");
if (part.quantity() != null && (part.quantity() < 1 || part.quantity() > 24)) throw invalid("组件数量必须为1至24的整数");
parts.put(role, new PartRequirements(role.code(), text(part.material()), part.degreesOfFreedom(),
@@ -46,19 +66,50 @@ record NormalizedMatchRequest(List<ComponentRole> roles, List<String> keywords,
for (String keyword : request.requirements() == null ? List.<String>of() : request.requirements()) {
if (!text(keyword).isEmpty()) keywords.add(text(keyword));
}
return new NormalizedMatchRequest(roles, List.copyOf(keywords), robot, Map.copyOf(parts), Set.copyOf(softFields));
return new NormalizedMatchRequest(roles, List.copyOf(keywords), robot, Map.copyOf(parts), Set.copyOf(softFields),
Set.copyOf(required), List.copyOf(groups));
}
boolean preferred(String category, String field) { return softFields.contains((category == null ? "robot" : category) + ":" + field); }
Integer quantity(ComponentRole role) { return parts.containsKey(role) ? parts.get(role).quantity() : null; }
int minimum(ComponentRole role) { return quantity(role) == null ? 1 : quantity(role); }
int minimum(ComponentRole role) { return quantity(role) == null ? requiredRoles.contains(role) ? 1 : 0 : quantity(role); }
int deficit(ComponentRole role, AssemblyState state) { return Math.max(0, minimum(role) - state.count(role)); }
/** 明确类别的待补实例也会计入所属组,不把同一需求重复累加。 */
int additionalMinimum(PartGroup group, AssemblyState state) {
return Math.max(0, group.minimumQuantity() - group.actual(state)
- group.roles().stream().mapToInt((ComponentRole role) -> deficit(role, state)).sum());
}
int missingMinimum(AssemblyState state) {
return roles.stream().mapToInt((ComponentRole role) -> deficit(role, state)).sum()
+ groups.stream().mapToInt((PartGroup group) -> additionalMinimum(group, state)).sum();
}
int missingTypes(AssemblyState state) {
int missing = (int) requiredRoles.stream().filter((ComponentRole role) -> state.count(role) == 0).count();
return missing + (int) groups.stream().filter((PartGroup group) -> group.actual(state) == 0
&& group.roles().stream().noneMatch(requiredRoles::contains)).count();
}
boolean needed(ComponentRole role, AssemblyState state, boolean uncoveredOnly) {
if (deficit(role, state) > 0 && (!uncoveredOnly || state.count(role) == 0)) return true;
return groups.stream().anyMatch((PartGroup group) -> group.roles().contains(role)
&& group.actual(state) < group.minimumQuantity() && (!uncoveredOnly || group.actual(state) == 0));
}
boolean canAdd(ComponentRole role, int current) {
return role != ComponentRole.TORSO && roles.contains(role) && (quantity(role) == null || current < quantity(role));
}
record PartGroup(String family, List<ComponentRole> roles, int minimumQuantity) {
int actual(AssemblyState state) { return roles.stream().mapToInt(state::count).sum(); }
List<String> categories() { return roles.stream().map(ComponentRole::code).toList(); }
}
private static Map<String, Object> numericValues(Integer degrees, java.math.BigDecimal mass, java.math.BigDecimal torque) {
Map<String, Object> values = new LinkedHashMap<>();
values.put("degreesOfFreedom", degrees);
@@ -131,12 +131,31 @@ public class RequirementEvaluator {
maximumDegrees = maximumDegrees.add(summary.maximumDegrees().multiply(BigDecimal.valueOf(remainingMax)));
minimumMass = minimumMass.add(summary.minimumMass().multiply(BigDecimal.valueOf(remainingMin)));
maximumMass = maximumMass.add(summary.maximumMass().multiply(BigDecimal.valueOf(remainingMax)));
massKnown &= summary.hasKnownMass();
if (remainingMin > 0) massKnown &= summary.hasKnownMass();
functionMatched |= summary.functionMatched();
unmet += summary.minimumUnmet() * remainingMin;
deviation = deviation.add(summary.minimumDeviation().multiply(BigDecimal.valueOf(remainingMin)));
mergeScores(scores, summary.keywordScores());
}
// 分组只补上明确类别以外的最低数量,不能把 L/R/0 各算一份必选件。
for (NormalizedMatchRequest.PartGroup group : request.groups()) {
int remaining = request.additionalMinimum(group, state);
if (remaining == 0) continue;
List<PoolSummary> choices = new ArrayList<>();
for (ComponentRole role : group.roles()) {
if ((possible & role.bit()) == 0 || !summaries.containsKey(role)) continue;
Integer quantity = request.quantity(role);
if (quantity != null && quantity - state.count(role) - request.deficit(role, state) <= 0) continue;
choices.add(summaries.get(role));
}
if (choices.isEmpty()) continue;
BigDecimal count = BigDecimal.valueOf(remaining);
minimumDegrees = minimumDegrees.add(choices.stream().map(PoolSummary::minimumDegrees).min(BigDecimal::compareTo).orElseThrow().multiply(count));
minimumMass = minimumMass.add(choices.stream().map(PoolSummary::minimumMass).min(BigDecimal::compareTo).orElseThrow().multiply(count));
massKnown &= choices.stream().anyMatch(PoolSummary::hasKnownMass);
unmet += choices.stream().mapToInt(PoolSummary::minimumUnmet).min().orElseThrow() * remaining;
deviation = deviation.add(choices.stream().map(PoolSummary::minimumDeviation).min(BigDecimal::compareTo).orElseThrow().multiply(count));
}
RobotRequirements robot = request.robot();
BigDecimal degreesGap = intervalGap(robot.degreesOfFreedom() == null ? null : decimal(robot.degreesOfFreedom()), minimumDegrees, maximumDegrees,
robot.operators().getOrDefault("degreesOfFreedom", "eq"));
@@ -260,7 +279,9 @@ public class RequirementEvaluator {
}
private record Penalties(int hardCount, int preferredCount, BigDecimal hardDeviation, BigDecimal preferredDeviation) { }
record LocalAssessment(List<UnmetRequirement> unmet, BigDecimal deviation, int[] keywordScores, boolean robotFunctionMatched,
int hardUnmetCount, int preferredUnmetCount, BigDecimal preferredDeviation) { }
int hardUnmetCount, int preferredUnmetCount, BigDecimal preferredDeviation) {
int keywordCoverage() { return (int) java.util.Arrays.stream(keywordScores).filter((int score) -> score > 0).count(); }
}
record Evaluation(Totals totals, List<UnmetRequirement> unmet, List<String> unmatched, BigDecimal deviation, int keywordScore,
int hardUnmetCount, int preferredUnmetCount, BigDecimal preferredDeviation) { }
record Estimate(int possibleParts, int unmet, BigDecimal deviation, int keywordScore) { }
@@ -7,6 +7,8 @@ import com.linkerbot.cadworld.dto.matching.RobotMatchRequest;
import com.linkerbot.cadworld.dto.matching.RobotMatchResponse;
import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.Alternatives;
import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.MissingPart;
import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.MissingPartGroup;
import com.linkerbot.cadworld.dto.matching.TemplatePartGroup;
import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.Replacement;
import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.Totals;
import java.math.BigDecimal;
@@ -48,16 +50,26 @@ public class RobotMatchingService {
return matchInternal(input, true, softFields);
}
@Transactional(readOnly = true)
public RobotMatchResponse matchConfirmed(RobotMatchRequest input, Set<String> softFields, List<TemplatePartGroup> groups) {
return matchInternal(input, true, softFields, groups);
}
private RobotMatchResponse matchInternal(RobotMatchRequest input, boolean strictFirst, Set<String> softFields) {
return matchInternal(input, strictFirst, softFields, List.of());
}
private RobotMatchResponse matchInternal(RobotMatchRequest input, boolean strictFirst, Set<String> softFields, List<TemplatePartGroup> groups) {
long started = System.nanoTime();
NormalizedMatchRequest request = NormalizedMatchRequest.from(input, softFields);
NormalizedMatchRequest request = NormalizedMatchRequest.from(input, softFields, groups);
CandidatePool collector = new CandidatePool(request, evaluator, properties);
components.scan(request.roles(), collector::accept);
CandidatePool.Result pool = collector.finish();
MatchingCandidate torso = collector.torso(pool);
log.info("躯干选择完成 requestId={} candidateCount={} componentCode={} hardUnmetCount={} preferredUnmetCount={}",
log.info("躯干选择完成 requestId={} candidateCount={} componentCode={} hardUnmetCount={} preferredUnmetCount={} keywordCoverage={} keywordCount={}",
RequestIdHolder.get(), pool.eligible().get(ComponentRole.TORSO), torso == null ? null : torso.code(),
torso == null ? null : torso.assessment().hardUnmetCount(), torso == null ? null : torso.assessment().preferredUnmetCount());
torso == null ? null : torso.assessment().hardUnmetCount(), torso == null ? null : torso.assessment().preferredUnmetCount(),
torso == null ? 0 : torso.assessment().keywordCoverage(), request.keywords().size());
AssemblySearchEngine.Result result;
if (strictFirst) {
Map<ComponentRole, List<MatchingCandidate>> strictCandidates = new EnumMap<>(ComponentRole.class);
@@ -75,6 +87,13 @@ public class RobotMatchingService {
}
} else result = search.search(pool, request, properties.maxStateExpansions(), torso);
RobotMatchResponse response = response(request, pool, result);
if (!request.groups().isEmpty()) {
AssemblySearchEngine.ScoredState selected = result.best();
List<String> groupCounts = request.groups().stream().map((NormalizedMatchRequest.PartGroup group) ->
group.family() + ":" + (selected == null ? 0 : group.actual(selected.state())) + "/" + group.minimumQuantity()).toList();
log.info("模板部位分组选件完成 requestId={} groupCounts={} missingGroupCount={}",
RequestIdHolder.get(), groupCounts, response.missingPartGroups().size());
}
if (pool.invalidMetadata() > 0 || pool.invalidPorts() > 0) {
log.warn("组件装配元数据异常 requestId={} invalidComponentCount={} invalidPortCount={} componentCodeSamples={}",
RequestIdHolder.get(), pool.invalidMetadata(), pool.invalidPorts(), collector.invalidCodeSamples());
@@ -95,9 +114,10 @@ public class RobotMatchingService {
private RobotMatchResponse response(NormalizedMatchRequest request, CandidatePool.Result pool, AssemblySearchEngine.Result result) {
List<MissingPart> missing = missing(request, pool, result);
List<MissingPartGroup> missingGroups = missingGroups(request, pool, result);
if (result.best() == null) {
return new RobotMatchResponse("NO_MATCH", null, List.of(), List.of(), List.of(),
new Totals(0, null, BigDecimal.ZERO, false), List.of(), request.keywords(), missing, result.limited());
new Totals(0, null, BigDecimal.ZERO, false), List.of(), request.keywords(), missing, missingGroups, result.limited());
}
AssemblyState selected = result.best().state();
RequirementEvaluator.Evaluation evaluation = result.best().evaluation();
@@ -112,9 +132,9 @@ public class RobotMatchingService {
alternatives.forEach((String instance, List<ReplacementState> items) -> publicAlternatives.add(new Alternatives(selected.parts().get(instance).role().code(), instance,
items.stream().map((ReplacementState item) -> new Replacement(publicComponents.get(item.candidate().code()).withInstanceId(instance),
item.state().connections(), item.evaluation().totals(), item.evaluation().unmet(), item.evaluation().unmatched())).toList())));
String status = !missing.isEmpty() ? "PARTIAL" : !evaluation.unmet().isEmpty() || !evaluation.unmatched().isEmpty() ? "FALLBACK" : "MATCHED";
String status = !missing.isEmpty() || !missingGroups.isEmpty() ? "PARTIAL" : !evaluation.unmet().isEmpty() || !evaluation.unmatched().isEmpty() ? "FALLBACK" : "MATCHED";
return new RobotMatchResponse(status, selected.root().code(), parts, selected.connections(), List.copyOf(publicAlternatives),
evaluation.totals(), evaluation.unmet(), evaluation.unmatched(), missing, result.limited());
evaluation.totals(), evaluation.unmet(), evaluation.unmatched(), missing, missingGroups, result.limited());
}
private Map<String, List<ReplacementState>> replacements(AssemblyState selected, CandidatePool.Result pool,
@@ -153,4 +173,17 @@ public class RobotMatchingService {
}
private record ReplacementState(MatchingCandidate candidate, AssemblyState state, RequirementEvaluator.Evaluation evaluation) { }
private List<MissingPartGroup> missingGroups(NormalizedMatchRequest request, CandidatePool.Result pool, AssemblySearchEngine.Result result) {
List<MissingPartGroup> missing = new ArrayList<>();
for (NormalizedMatchRequest.PartGroup group : request.groups()) {
int actual = result.best() == null ? 0 : group.actual(result.best().state());
if (actual >= group.minimumQuantity()) continue;
String reason = group.roles().stream().allMatch((ComponentRole role) -> pool.observed().getOrDefault(role, 0) == 0)
? "NO_COMPONENT" : pool.candidates().get(ComponentRole.TORSO).isEmpty() ? "NO_TORSO"
: result.limited() ? "SEARCH_LIMIT" : "NO_COMPATIBLE_CONNECTION";
missing.add(new MissingPartGroup(group.family(), group.categories(), reason, group.minimumQuantity(), actual, group.minimumQuantity() - actual));
}
return List.copyOf(missing);
}
}
@@ -210,7 +210,8 @@
"type": {
"type": "string",
"enum": [
"biped"
"biped",
"hexapod"
]
},
"source": {
@@ -252,12 +253,16 @@
"WAIST_0",
"ARM_L",
"ARM_R",
"ARM_0",
"HAND_L",
"HAND_R",
"HAND_0",
"LEG_L",
"LEG_R",
"LEG_0",
"FOOT_L",
"FOOT_R",
"FOOT_0",
"TAIL_0"
]
},
@@ -300,12 +305,16 @@
"WAIST_0",
"ARM_L",
"ARM_R",
"ARM_0",
"HAND_L",
"HAND_R",
"HAND_0",
"LEG_L",
"LEG_R",
"LEG_0",
"FOOT_L",
"FOOT_R",
"FOOT_0",
"TAIL_0"
]
},
@@ -346,12 +355,16 @@
"WAIST_0",
"ARM_L",
"ARM_R",
"ARM_0",
"HAND_L",
"HAND_R",
"HAND_0",
"LEG_L",
"LEG_R",
"LEG_0",
"FOOT_L",
"FOOT_R",
"FOOT_0",
"TAIL_0"
]
}
@@ -1,5 +1,5 @@
{
"version": "2026-10-16-component-types",
"version": "2026-10-16-hexapod-template",
"defaultTemplate": "biped",
"categories": [
"TORSO_0",
@@ -7,12 +7,16 @@
"WAIST_0",
"ARM_L",
"ARM_R",
"ARM_0",
"HAND_L",
"HAND_R",
"HAND_0",
"LEG_L",
"LEG_R",
"LEG_0",
"FOOT_L",
"FOOT_R",
"FOOT_0",
"TAIL_0"
],
"templates": [
@@ -22,17 +26,75 @@
"parts": [
"TORSO_0",
"HEAD_0",
"WAIST_0",
"ARM_L",
"ARM_R",
"HAND_L",
"HAND_R",
"LEG_L",
"LEG_R",
"FOOT_L",
"FOOT_R"
"WAIST_0"
],
"keyword": "双足"
"keyword": "双足",
"partGroups": [
{
"family": "ARM",
"categories": [
"ARM_L",
"ARM_R",
"ARM_0"
],
"minimumQuantity": 2
},
{
"family": "HAND",
"categories": [
"HAND_L",
"HAND_R",
"HAND_0"
],
"minimumQuantity": 2
},
{
"family": "LEG",
"categories": [
"LEG_L",
"LEG_R",
"LEG_0"
],
"minimumQuantity": 2
},
{
"family": "FOOT",
"categories": [
"FOOT_L",
"FOOT_R",
"FOOT_0"
],
"minimumQuantity": 2
}
]
},
{
"id": "hexapod",
"label": "六足机器人候选",
"parts": [
"TORSO_0"
],
"keyword": "六足",
"partGroups": [
{
"family": "LEG",
"categories": [
"LEG_L",
"LEG_R",
"LEG_0"
],
"minimumQuantity": 6
},
{
"family": "FOOT",
"categories": [
"FOOT_L",
"FOOT_R",
"FOOT_0"
],
"minimumQuantity": 6
}
]
}
]
}
@@ -16,9 +16,9 @@
三、类型与部位
11. 配置目录:{{CATALOG_JSON}}。robotTypes 只使用目录中的模板 id;程序展开 requiredParts,你不输出该字段。能辨认形态时选对应模板,图片推断标 inferred。未指定形态时 robotTypes=[],后端使用默认模板并说明。目录不代表库存齐全或能力达标。
12. 未配置的四足、轮式、履带、鸟形等保留为 unmodeled,不谎称双足能够满足;后端可返回默认参考方案并保留差异。“仿生鸟类”保留机器人、仿生、鸟类等关键词,可将双足作为 inferred 候选;飞行能力保留为未验证,企鹅、鸵鸟或明确不飞行时不推断飞行。
13. 类别仅限以下12个大写编码:TORSO_0 躯干、HEAD_0 头、WAIST_0 腰、ARM_L 左臂、ARM_R 右臂、HAND_L 左手、HAND_R 右手、LEG_L 左足、LEG_R 右足、FOOT_L 左脚、FOOT_R 右脚、TAIL_0 尾。0 不分左右,L/R 是机械左右,足和脚不同;腿部对应 LEG_L/LEG_R,不输出 pedal 类别。双臂明确展开两侧;单侧部件未说明左右时按右侧生成 inferred 参考部位,并在 reason 中说明默认选择,不伪装成用户明确要求。
14. 明确排除的部件放 excludedCategories,不作为正向包含。仅凭草图没画出某部件不能当作排除。翅膀、轮子、旋翼、电池、传感器、爪等目录外部件放 unmodeled,不造类别或把手臂当翅膀。现有部位支持同款组件的多个独立实例;明确数量写入quantity维度intentItems,并以part范围、field=quantity、operator=eq写入constraints,value保留原始数量,支持1至24。跨多个部位的合计数量仅保留intentItems,不平均分配。数量缺失时不要补1;后端按需求类型和实际可用接口填充。整机固定一个躯干。不要新增目录外类别或四足、六足模板。
12. 六足/六腿/hexapod 选择 hexapod 模板,不得标为不支持或回退为双足。六足基本构型由躯干、六个足部和六个脚部候选组成,具体左右或中性类型由后端按实际接口选择,不默认添加人形的头、腰、臂、手或尾。未配置的四足、轮式、履带、鸟形等保留为 unmodeled,不谎称双足能够满足;后端可返回默认参考方案并保留差异。“仿生鸟类”保留机器人、仿生、鸟类等关键词,可将双足作为 inferred 候选;飞行能力保留为未验证,企鹅、鸵鸟或明确不飞行时不推断飞行。
13. 类别仅限以下16个大写编码:TORSO_0 躯干、HEAD_0 头、WAIST_0 腰、ARM_L 左臂、ARM_R 右臂、ARM_0 不分左右的臂、HAND_L 左手、HAND_R 右手、HAND_0 不分左右的手、LEG_L 左足、LEG_R 右足、LEG_0 不分左右的足、FOOT_L 左脚、FOOT_R 右脚、FOOT_0 不分左右的脚、TAIL_0 尾。0 不分左右,L/R 是机械左右,足和脚不同,不输出 pedal 类别。单部位未说明左右时选择对应 _0 并标为 inferred,reason 说明默认选择,不伪装成用户明确指定类型。明确左或右时保留 L/R;明确双臂展开 ARM_L/ARM_R;“两个不分左右的臂”使用 ARM_0、quantity=2。人形的默认类型组合由后端按实际接口选取,不要自行把全部16类列为必需部件。
14. 明确排除的部件放 excludedCategories,未指定左右且排除整个臂、手、足或脚时,展开排除该部位的 L/R/0 三类,不作为正向包含。仅凭草图没画出某部件不能当作排除。翅膀、轮子、旋翼、电池、传感器、爪等目录外部件放 unmodeled,不造类别或把手臂当翅膀。现有部位支持同款组件的多个独立实例;明确数量写入quantity维度intentItems,并以part范围、field=quantity、operator=eq写入constraints,value保留原始数量,支持1至24。跨多个部位的合计数量仅保留intentItems,不平均分配。数量缺失时不要补1;后端按需求类型和实际可用接口填充。整机固定一个躯干。不要新增目录外类别或目录中未配置的模板;templatePartGroups 由后端生成,不自行输出。
15. 解析器不生成安装接口、坐标、旋转、父子关系或配对方案。真实连接来自后端组件数据:interfaceType优先决定目标部位,双方frames.child严格一致才能连接;同child的多个接口独立处理,后端只返回实例连接关系,摆放由前端处理。不要从草图像素生成3D位置。
四、机械条件
@@ -30,6 +30,7 @@
例子:
“我要双足跑步机器人,整体20自由度,质量不超过10kg,躯干用铝合金,右臂扭矩至少20N·m”:biped explicit;整机 DOF eq20、质量 lte10kg、跑步需求;TORSO_0 材料铝合金、ARM_R 扭矩 gte20N·m,questions=[]。跑步的真实能力仍需后端证据验证。
“拼一个六足机器人”:robotTypes=[hexapod explicit];keywords 至少保留“六足”和“机器人”;不输出双足,不把六足基本构型放入 unmodeled,不自行指定左右各三,真实数量由模板分组和接口确定。跑步速度、载荷等能力仍须单独保留证据和未验证项。
“给我拼一个机器人”:keywords 保留机器人,robotTypes/partCategories/constraints 为空,交给后端默认模板,questions=[]。
草图双腿且 OCR“20”不清:可用 biped inferred;不清的 20 留作参考,不写硬 DOF,questions=[]。
文字 8kg 与图片 10kg 且无覆盖说明:保留两条约束和冲突,不选择一侧,questions=[]。明确“改为不超过8kg”时只保留当前 8kg 条件。
@@ -35,8 +35,8 @@ class DemandNormalizerTest {
assertThat(actual.analysis().path("status").asText()).isEqualTo("ready");
assertThat(actual.analysis().path("canSubmit").asBoolean()).isTrue();
assertThat(actual.analysis().path("questions")).isEmpty();
assertThat(actual.analysis().path("schemaVersion").asText()).isEqualTo("multimodal-v1.4-component-types");
assertThat(actual.analysis().path("catalogVersion").asText()).isEqualTo("2026-10-16-component-types");
assertThat(actual.analysis().path("schemaVersion").asText()).isEqualTo("multimodal-v1.5-neutral-components");
assertThat(actual.analysis().path("catalogVersion").asText()).isEqualTo("2026-10-16-hexapod-template");
}
@Test void normalizesLegacyCategoriesInPartsConstraintsAndExclusionsWithoutChangingEvidence() {
@@ -151,7 +151,7 @@ class DemandNormalizerTest {
assertThat(result.analysis().path("defaultTemplate").asText()).isEqualTo("biped");
assertThat(result.analysis().path("robotTypes")).isEmpty();
assertThat(result.analysis().path("warnings").toString()).contains("默认");
assertThat(result.request().path("requiredParts")).hasSize(11);
assertThat(result.request().path("requiredParts")).hasSize(3);
assertThat(result.request().path("robotRequirements")).isEmpty();
assertThat(result.request().path("partRequirements")).isEmpty();
}
@@ -161,11 +161,11 @@ class DemandNormalizerTest {
ObjectNode raw = minimal(text);
raw.putArray("robotTypes");
((ObjectNode) raw.path("keywords").get(0)).put("term", "手臂");
raw.withArray("partCategories").addObject().put("category", "ARM_R").put("source", "inferred")
.put("reason", "未指定左右,默认右臂候选").putArray("evidenceIds").add("e1");
raw.withArray("partCategories").addObject().put("category", "ARM_0").put("source", "inferred")
.put("reason", "未指定左右,默认不分左右的臂候选").putArray("evidenceIds").add("e1");
DemandResult result = normalizer.normalize(raw, text(text));
assertThat(result.request().path("requiredParts").get(0).asText()).isEqualTo("TORSO_0");
assertThat(result.request().path("requiredParts").get(1).asText()).isEqualTo("ARM_R");
assertThat(result.request().path("requiredParts").get(1).asText()).isEqualTo("ARM_0");
assertThat(result.request().path("requiredParts")).hasSize(2);
assertThat(result.analysis().path("partCategories").get(0).path("source").asText()).isEqualTo("inferred");
assertThat(result.analysis().path("questions")).isEmpty();
@@ -238,6 +238,55 @@ class DemandNormalizerTest {
assertThat(result.request().path("partRequirements").get(0).path("quantity").asInt()).isEqualTo(4);
}
@ParameterizedTest
@org.junit.jupiter.params.provider.CsvSource({"手臂,ARM_0", "手,HAND_0", "腿,LEG_0", "脚,FOOT_0"})
void unspecifiedSideQuantitiesUseNeutralTypes(String subject, String category) {
String input = "一个" + subject;
ObjectNode raw = minimal(input);
raw.putArray("robotTypes");
raw.withArray("partCategories").addObject().put("category", category).put("source", "inferred")
.put("reason", "未指定左右,默认不分左右").putArray("evidenceIds").add("e1");
raw.withArray("intentItems").addObject().put("id", "quantity").put("dimension", "quantity").put("subject", subject)
.put("requirement", input).put("priority", "must").put("source", "explicit").putArray("evidenceIds").add("e1");
DemandResult result = normalizer.normalize(raw, text(input));
assertThat(result.request().path("requiredParts")).isEqualTo(json.valueToTree(List.of("TORSO_0", category)));
assertThat(result.request().path("partRequirements").get(0).path("category").asText()).isEqualTo(category);
assertThat(result.request().path("partRequirements").get(0).path("quantity").asInt()).isEqualTo(1);
assertThat(result.request().path("templatePartGroups")).isEmpty();
}
@Test void inferredTemplateSidesDoNotForceAllConcreteCategories() {
ObjectNode raw = minimal("拼个人形机器人");
for (String role : List.of("ARM_L", "ARM_R", "LEG_L", "LEG_R")) raw.withArray("partCategories").addObject()
.put("category", role).put("source", "inferred").put("reason", "模板参考部位").putArray("evidenceIds").add("e1");
DemandResult result = normalizer.normalize(raw, text("拼个人形机器人"));
assertThat(result.request().path("requiredParts")).isEqualTo(json.valueToTree(List.of("TORSO_0", "HEAD_0", "WAIST_0")));
assertThat(result.request().path("templatePartGroups")).hasSize(4);
assertThat(DemandRequirementChecker.roles("双足机器人", "一个机器人")).isEmpty();
assertThat(DemandRequirementChecker.roles("右臂", "扭矩足够大")).containsExactly("ARM_R");
assertThat(DemandRequirementChecker.roles("手腕", "一个手腕")).isEmpty();
assertThat(DemandRequirementChecker.roles("脚轮", "一个脚轮")).isEmpty();
}
@Test void hexapodTemplateRequiresSixLegsWithoutHumanPartsAndPreservesCapabilityGaps() {
String input = "拼一个六足机器人,载荷10kg";
ObjectNode raw = minimal(input);
((ObjectNode) raw.path("robotTypes").get(0)).put("type", "hexapod");
((ObjectNode) raw.path("keywords").get(0)).put("term", "六足机器人");
raw.withArray("unmodeled").addObject().put("text", "载荷10kg").put("reason", "载荷尚无可验证字段")
.putArray("evidenceIds").add("e1");
DemandResult result = normalizer.normalize(raw, text(input));
assertThat(result.request().path("requiredParts")).isEqualTo(json.valueToTree(List.of("TORSO_0")));
assertThat(result.request().path("templatePartGroups")).hasSize(2);
assertThat(result.request().path("templatePartGroups").findValuesAsText("family")).containsExactly("LEG", "FOOT");
for (JsonNode group : result.request().path("templatePartGroups")) assertThat(group.path("minimumQuantity").asInt()).isEqualTo(6);
assertThat(result.analysis().path("robotTypes").get(0).path("type").asText()).isEqualTo("hexapod");
assertThat(result.analysis().path("defaultTemplate").asText()).isEmpty();
assertThat(result.analysis().path("unmodeled").get(0).path("text").asText()).isEqualTo("载荷10kg");
assertThat(result.analysis().path("warnings").toString()).doesNotContain("默认双足");
assertThat(result.request().path("partRequirements")).isEmpty();
}
private JsonNode fixture(String name) throws Exception {
try (InputStream stream = getClass().getResourceAsStream("/robot-demand/" + name + ".json")) { return json.readTree(stream); }
}
@@ -0,0 +1,43 @@
package com.linkerbot.cadworld.service.matching;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.cadworld.service.demand.DemandRules;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.assertj.core.api.Assertions.assertThat;
class ComponentRoleTest {
@Test void catalogAndModelSchemaUseExactlyTheSixteenComponentTypes() throws Exception {
List<String> codes = List.of("TORSO_0", "HEAD_0", "WAIST_0", "ARM_L", "ARM_R", "ARM_0", "HAND_L", "HAND_R", "HAND_0",
"LEG_L", "LEG_R", "LEG_0", "FOOT_L", "FOOT_R", "FOOT_0", "TAIL_0");
ObjectMapper json = new ObjectMapper();
DemandRules rules = new DemandRules(json);
assertThat(Arrays.stream(ComponentRole.values()).map(ComponentRole::code).toList()).containsExactlyElementsOf(codes);
JsonNode expected = json.valueToTree(codes);
assertThat(rules.catalog().path("categories")).isEqualTo(expected);
for (String field : List.of("partCategories", "excludedCategories")) {
assertThat(rules.schema().path("properties").path(field).path("items").path("properties").path("category").path("enum")).isEqualTo(expected);
}
assertThat(rules.schema().path("properties").path("constraints").path("items").path("properties").path("categories").path("items").path("enum")).isEqualTo(expected);
assertThat(rules.catalog().path("templates").get(0).path("parts")).isEqualTo(json.valueToTree(List.of("TORSO_0", "HEAD_0", "WAIST_0")));
assertThat(rules.catalog().path("templates").get(0).path("partGroups")).hasSize(4);
List<String> templates = new java.util.ArrayList<>();
for (JsonNode template : rules.catalog().path("templates")) templates.add(template.path("id").asText());
assertThat(rules.schema().path("properties").path("robotTypes").path("items").path("properties").path("type").path("enum"))
.isEqualTo(json.valueToTree(templates));
assertThat(ComponentRole.find("LEG_0").orElseThrow().code()).isEqualTo("LEG_0");
}
@ParameterizedTest
@CsvSource({"TORSO_0,TORSO_0", "head_0,HEAD_0", "Waist_0,WAIST_0", "臂_L,ARM_L", "arm_r,ARM_R",
"hand_l,HAND_L", "手_R,HAND_R", "leg_l,LEG_L", "LEG_R,LEG_R", "pedal_l,LEG_L", "PEDAL_R,LEG_R",
"foot_l,FOOT_L", "脚_R,FOOT_R", "tail_0,TAIL_0", "arm_0,ARM_0", "手_0,HAND_0", "leg_0,LEG_0", "foot_0,FOOT_0"})
void acceptsLegacyAliasesAndKeepsSidesAndFeetDistinct(String alias, String code) {
assertThat(ComponentRole.find(alias).orElseThrow().code()).isEqualTo(code);
}
}
@@ -38,6 +38,9 @@ class MatchingConfigurationTest {
assertThat(text.matches("用于抓取", "夹持")).isTrue();
assertThat(text.matches("机器人", "ROBOT")).isTrue();
assertThat(text.equivalent(" ALUMINIUM ALLOY ", "铝合金")).isTrue();
assertThat(text.matches("六足蜘蛛机器人躯干", "六足机器人")).isTrue();
assertThat(text.matches("六足蜘蛛机器人左足", "hexapod robot")).isTrue();
assertThat(text.matches("通用人形机器人", "六足机器人")).isFalse();
}
@Test
@@ -475,6 +475,44 @@
"torqueNm": "gte"
}
}
],
"templatePartGroups": [
{
"family": "ARM",
"categories": [
"ARM_L",
"ARM_R",
"ARM_0"
],
"minimumQuantity": 2
},
{
"family": "HAND",
"categories": [
"HAND_L",
"HAND_R",
"HAND_0"
],
"minimumQuantity": 2
},
{
"family": "LEG",
"categories": [
"LEG_L",
"LEG_R",
"LEG_0"
],
"minimumQuantity": 2
},
{
"family": "FOOT",
"categories": [
"FOOT_L",
"FOOT_R",
"FOOT_0"
],
"minimumQuantity": 2
}
]
},
"analysis": {
@@ -663,7 +701,7 @@
"warnings": [
"部分二维来源框格式不可靠,已省略定位框,请查看整张原图核对。"
],
"catalogVersion": "2026-10-16-component-types",
"catalogVersion": "2026-10-16-hexapod-template",
"status": "needs_clarification",
"canSubmit": false,
"observations": [
@@ -896,7 +934,7 @@
]
}
],
"schemaVersion": "multimodal-v1.4-component-types"
"schemaVersion": "multimodal-v1.5-neutral-components"
}
}
}
@@ -399,14 +399,7 @@
"TORSO_0",
"HEAD_0",
"WAIST_0",
"ARM_L",
"ARM_R",
"HAND_L",
"HAND_R",
"LEG_L",
"LEG_R",
"FOOT_L",
"FOOT_R"
"ARM_R"
],
"robotRequirements": {
"degreesOfFreedom": 20,
@@ -425,6 +418,44 @@
"torqueNm": "gte"
}
}
],
"templatePartGroups": [
{
"family": "ARM",
"categories": [
"ARM_L",
"ARM_R",
"ARM_0"
],
"minimumQuantity": 2
},
{
"family": "HAND",
"categories": [
"HAND_L",
"HAND_R",
"HAND_0"
],
"minimumQuantity": 2
},
{
"family": "LEG",
"categories": [
"LEG_L",
"LEG_R",
"LEG_0"
],
"minimumQuantity": 2
},
{
"family": "FOOT",
"categories": [
"FOOT_L",
"FOOT_R",
"FOOT_0"
],
"minimumQuantity": 2
}
]
},
"analysis": {
@@ -613,7 +644,7 @@
"warnings": [
"部分二维来源框格式不可靠,已省略定位框,请查看整张原图核对。"
],
"catalogVersion": "2026-10-16-component-types",
"catalogVersion": "2026-10-16-hexapod-template",
"status": "ready",
"canSubmit": true,
"observations": [
@@ -803,7 +834,7 @@
]
}
],
"schemaVersion": "multimodal-v1.4-component-types"
"schemaVersion": "multimodal-v1.5-neutral-components"
}
}
}
@@ -422,14 +422,7 @@
"TORSO_0",
"HEAD_0",
"WAIST_0",
"ARM_L",
"ARM_R",
"HAND_L",
"HAND_R",
"LEG_L",
"LEG_R",
"FOOT_L",
"FOOT_R"
"ARM_R"
],
"robotRequirements": {
"degreesOfFreedom": 20,
@@ -451,6 +444,44 @@
"torqueNm": "gte"
}
}
],
"templatePartGroups": [
{
"family": "ARM",
"categories": [
"ARM_L",
"ARM_R",
"ARM_0"
],
"minimumQuantity": 2
},
{
"family": "HAND",
"categories": [
"HAND_L",
"HAND_R",
"HAND_0"
],
"minimumQuantity": 2
},
{
"family": "LEG",
"categories": [
"LEG_L",
"LEG_R",
"LEG_0"
],
"minimumQuantity": 2
},
{
"family": "FOOT",
"categories": [
"FOOT_L",
"FOOT_R",
"FOOT_0"
],
"minimumQuantity": 2
}
]
},
"analysis": {
@@ -639,7 +670,7 @@
"warnings": [
"部分二维来源框格式不可靠,已省略定位框,请查看整张原图核对。"
],
"catalogVersion": "2026-10-16-component-types",
"catalogVersion": "2026-10-16-hexapod-template",
"status": "ready",
"canSubmit": true,
"observations": [
@@ -852,7 +883,7 @@
]
}
],
"schemaVersion": "multimodal-v1.4-component-types"
"schemaVersion": "multimodal-v1.5-neutral-components"
}
}
}
@@ -188,18 +188,48 @@
"requiredParts": [
"TORSO_0",
"HEAD_0",
"WAIST_0",
"ARM_L",
"ARM_R",
"HAND_L",
"HAND_R",
"LEG_L",
"LEG_R",
"FOOT_L",
"FOOT_R"
"WAIST_0"
],
"robotRequirements": {},
"partRequirements": []
"partRequirements": [],
"templatePartGroups": [
{
"family": "ARM",
"categories": [
"ARM_L",
"ARM_R",
"ARM_0"
],
"minimumQuantity": 2
},
{
"family": "HAND",
"categories": [
"HAND_L",
"HAND_R",
"HAND_0"
],
"minimumQuantity": 2
},
{
"family": "LEG",
"categories": [
"LEG_L",
"LEG_R",
"LEG_0"
],
"minimumQuantity": 2
},
{
"family": "FOOT",
"categories": [
"FOOT_L",
"FOOT_R",
"FOOT_0"
],
"minimumQuantity": 2
}
]
},
"analysis": {
"summary": "用户上传火柴人风格双足人形机器人简笔草图,无附带文字说明,草图呈现包含圆形头部、方形躯干、双侧折线手臂、双侧带平底足的双腿的人形结构,可匹配现有双足机器人候选模板。",
@@ -312,7 +342,7 @@
"warnings": [
"机器人类型含推断,仅用于兼容候选,不能视为用户确认或全部功能满足。"
],
"catalogVersion": "2026-10-16-component-types",
"catalogVersion": "2026-10-16-hexapod-template",
"status": "ready",
"canSubmit": true,
"observations": [
@@ -380,7 +410,7 @@
]
}
],
"schemaVersion": "multimodal-v1.4-component-types"
"schemaVersion": "multimodal-v1.5-neutral-components"
}
}
}