diff --git a/cadworld-api/docs/demand-integration.md b/cadworld-api/docs/demand-integration.md index d204670..d18f8a8 100644 --- a/cadworld-api/docs/demand-integration.md +++ b/cadworld-api/docs/demand-integration.md @@ -1,6 +1,6 @@ # 需求解析后端接入与部署 -已按 `/Users/edy/Downloads/robot-demand-parser-v1` 的 README、backend-handoff、protocol,以及 `index.mjs` / `mechanical-rules.mjs` 移植 Java 程序校验。自动拼装输出版本为 `multimodal-v1.6-component-replacement`,目录版本为 `2026-10-16-hexapod-template`。原始来源作为参考保留,当前提示词与 Java 规则已调整为无追问的自动生成流程。来源文件夹保持不变,运行时不依赖 Node、React 或前端解析脚本。 +已按 `/Users/edy/Downloads/robot-demand-parser-v1` 的 README、backend-handoff、protocol,以及 `index.mjs` / `mechanical-rules.mjs` 移植 Java 程序校验。自动拼装输出版本为 `multimodal-v1.6-component-replacement`,目录版本为 `2026-10-27-hexapod-connectors`。原始来源作为参考保留,当前提示词与 Java 规则已调整为无追问的自动生成流程。来源文件夹保持不变,运行时不依赖 Node、React 或前端解析脚本。 业务标准化另外落实躯干优先规则:整机必须且只能有一个躯干,解析时可自动补入基础躯干;明确排除躯干时保留排除项并返回无匹配方案,不追问或偷偷补入。匹配先固定最符合需求的躯干,再搜索与其连通的其他组件。 diff --git a/cadworld-api/docs/robot-demand-api.md b/cadworld-api/docs/robot-demand-api.md index 60ca980..18295ca 100644 --- a/cadworld-api/docs/robot-demand-api.md +++ b/cadworld-api/docs/robot-demand-api.md @@ -279,7 +279,7 @@ async function sendMessage(token, conversationId, message, onEvent, signal) { "warnings": [ "整机拼装固定一个躯干,已补入TORSO_0作为基础组件。" ], - "catalogVersion": "2026-10-16-hexapod-template", + "catalogVersion": "2026-10-27-hexapod-connectors", "observations": [ { "id": "e1", @@ -562,6 +562,7 @@ async function sendMessage(token, conversationId, message, onEvent, signal) { | `result.request` | 规范化需求及后端生成的 templatePartGroups;未提供的约束不会补成 0 | | `result.request.partRequirements[].quantity` | 部位实例数量,整数 1–24;省略/null 表示按可匹配接口填充,躯干固定一个;第 5 节给出多实例示例 | | `result.request.templatePartGroups` | 后端生成的模板要求数组,每项为 `{family, categories, minimumQuantity}`;不作为消息或结构化匹配入参 | +| `result.request.optionalParts` | 模板允许按需使用的连接部位编码;无可选连接件时省略,不作为消息或结构化匹配入参 | | `match.missingPartGroups` | 部位合计缺口,每项含 `family`、`categories`、`reason`、`expectedQuantity`、`actualQuantity`、`missingQuantity`;有缺口时为 `partial` | | `result.analysis.schemaVersion` | 新生成结果为 `multimodal-v1.6-component-replacement`;旧快照可能仍为旧协议 | | `result.analysis.intentItems` | 逐项需求,`must` 硬要求、`prefer` 偏好、`context` 参考;用于结果说明和逐项核对 | @@ -604,7 +605,7 @@ async function sendMessage(token, conversationId, message, onEvent, signal) { 躯干先按自身硬条件、数值差距、偏好、整机功能文本与关键词相关性排序。关键词先比较命中的不同需求数量,再比较字段权重,因此说明中匹配六足需求的躯干不会被只命中泛称“机器人”的普通躯干压过;这些条件相同后优先选择能接更多所需角色的接口集合,最后按编码稳定排序。整机自由度和质量目标在后续组合阶段评价,不直接当作躯干单件的数值要求。 -选定躯干后不因其他躯干能多接几件或更接近整机总量而自动换根。其他组件须能通过现有接口路径连接到这个躯干;例如右手通过右臂连接,允许沿链匹配,但不自动补入未要求的中间连接件。达标搜索和降级搜索沿用同一个躯干。缺件时返回该躯干及可连接的部分方案;无可用躯干时返回 `no_match`,不会用头部或手臂代替根。 +选定躯干后不因其他躯干能多接几件或更接近整机总量而自动换根。其他组件须能通过现有接口路径连接到这个躯干;例如右手通过右臂连接,允许沿链匹配。模板可通过后端生成的 `request.optionalParts` 允许必要的连接部件,例如六足腰部;仅在连接件具有可连接缺少部位的其他接口时使用,同类可选连接件最多一个,并遵守明确排除项。目录未允许的部位仍不自动补入。达标搜索和降级搜索沿用同一个躯干。缺件时返回该躯干及可连接的部分方案;无可用躯干时返回 `no_match`,不会用头部或手臂代替根。 ### 缺件时展示已有组合 @@ -842,12 +843,14 @@ async function sendMessage(token, conversationId, message, onEvent, signal) { ### 六足模板 -目录支持 `biped`(默认人形/双足)和 `hexapod`(六足)。明确说“拼一个六足机器人”时选择 `hexapod`,不会回退到双足模板。六足模板只必需一个 `TORSO_0`,并生成 LEG、FOOT 两组各至少6个实例的要求;L/R/0 由实际接口决定,不强制分成左右各三,也不默认添加头、腰、臂、手或尾。未说明形态的需求仍沿用默认双足模板。 +目录支持 `biped`(默认人形/双足)和 `hexapod`(六足)。明确说“拼一个六足机器人”时选择 `hexapod`,不会回退到双足模板。六足模板只必需一个 `TORSO_0`,并生成 LEG、FOOT 两组各至少6个实例的要求;L/R/0 由实际接口决定,不强制分成左右各三。`request.optionalParts=["WAIST_0"]` 允许按需连接具有六个足接口的腰部,不要求所有六足方案都装腰部,不默认添加头、臂、手或尾。该字段由后端生成,不作为消息或结构化匹配入参。未说明形态的需求仍沿用默认双足模板。 -六足/六足机器人/hexapod 等同义词会参与名称与说明匹配。例如说明“六足蜘蛛机器人躯干”可命中“六足机器人”,随后沿该躯干的六个足部接口分别生成实例;相同 child 的三个左足接口和三个右足接口各自独立占用。六足分组使用现有 `templatePartGroups`、`missingPartGroups` 结构,没有新增消息参数。目录版本为 `2026-10-16-hexapod-template`,历史方案须通过新的 `messageId` 重新生成。 +六足/六足机器人/hexapod 等同义词会参与名称与说明匹配。例如说明“六足蜘蛛机器人躯干”可命中“六足机器人”,随后沿该躯干的六个足部接口分别生成实例;相同 child 的三个左足接口和三个右足接口各自独立占用。六足分组使用现有 `templatePartGroups`、`missingPartGroups` 结构,没有新增消息参数。目录版本为 `2026-10-27-hexapod-connectors`,历史方案须通过新的 `messageId` 重新生成。 名称或说明中的六足标注用于候选相关性;六足模板与接口连接不证明行走速度、载荷或稳定性达标,这类要求继续单独核对。 +“六足构型”这类整机构型条目按实际连接的 LEG、FOOT 数量及模板缺件情况校验,`requirementChecks.field=templatePartGroups`,不要求组件另填同名的 `shape`。“1台/一台/一个机器人”的单台数量可验证;只有形成完整所需组合后才标记满足,尚有缺件时保留未验证。多台整机仍不支持,不会把整机数量分摊到每个部件,也不要求组件备注包含“数量1台”。 + ### 默认人形与中性组件 默认人形的 `requiredParts` 为 `TORSO_0/HEAD_0/WAIST_0`,其余部位由 `templatePartGroups` 表达。四组均允许同一部位的 L/R/0,`minimumQuantity=2`;不会把所有候选类别都当成必须各装一个。 diff --git a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/ComponentFixtureSupport.java b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/ComponentFixtureSupport.java index af9554e..60341f4 100644 --- a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/ComponentFixtureSupport.java +++ b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/ComponentFixtureSupport.java @@ -11,7 +11,11 @@ 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")) { + loadLibrary(jdbc, json, "hexapod-library-components.json"); + } + + static void loadLibrary(JdbcTemplate jdbc, ObjectMapper json, String name) throws Exception { + try (InputStream stream = ComponentFixtureSupport.class.getResourceAsStream("/fixtures/" + name)) { assertThat(stream).isNotNull(); for (JsonNode row : json.readTree(stream)) { jdbc.update(""" diff --git a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/DemandFlowApiTest.java b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/DemandFlowApiTest.java index b659cde..ba61259 100644 --- a/cadworld-api/src/test/java/com/linkerbot/cadworld/api/DemandFlowApiTest.java +++ b/cadworld-api/src/test/java/com/linkerbot/cadworld/api/DemandFlowApiTest.java @@ -509,6 +509,80 @@ class DemandFlowApiTest { assertThat(generatedMatch(session, generated.path("analysisId").asText(), 1)).isEqualTo(match); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void hexapodDemandConnectsSixLegsThroughOptionalWaistAndChecksWholeRobotIntent(boolean excludeWaist) throws Exception { + ComponentFixtureSupport.loadLibrary(jdbc, json, "hexapod-waist-components.json"); + doAnswer(invocation -> { + ObjectNode raw = hexapodRaw(invocation.getArgument(0)); + if (excludeWaist) raw.withArray("excludedCategories").addObject().put("category", "WAIST_0").putArray("evidenceIds").add("e1"); + return raw; + }).when(model).analyze(anyList()); + Session session = create(); + JsonNode generated = submit(session, "m-hexapod-waist", "拼一个六足机器人" + (excludeWaist ? ",不要腰部" : ""), List.of()); + JsonNode match = generated.path("match"); + assertThat(generated.path("result").path("analysis").path("unmodeled")).isEmpty(); + assertThat(generated.path("warnings").toString()).doesNotContain("数量要求超出", "组件数量只支持"); + assertThat(match.path("assembly").path("status").asText()).isEqualTo("ready"); + if (excludeWaist) { + assertThat(match.path("status").asText()).isEqualTo("partial"); + assertThat(match.path("components")).hasSize(1); + assertThat(match.path("missingPartGroups")).hasSize(2); + assertThat(match.path("requirementChecks").get(0).path("status").asText()).isEqualTo("unmet"); + assertThat(match.path("requirementChecks").get(1).path("status").asText()).isEqualTo("unverified"); + } else { + assertThat(match.path("status").asText()).isEqualTo("complete"); + assertThat(match.path("components")).hasSize(14); + assertThat(match.path("missingPartGroups")).isEmpty(); + assertThat(match.path("unmatchedKeywords")).isEmpty(); + assertThat(match.path("requirementChecks").findValuesAsText("status")).containsExactly("satisfied", "satisfied"); + assertThat(match.path("assembly").path("connections")).hasSize(13); + Map 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-FS081NP1VD45Z7NJ", 1, "CW-3JB52HZTFYTPZ1F0", 1, + "CW-3Z2XH5K45D4K8JPP", 6, "CW-GFQGN4DVNT5Q79FW", 6)); + assertThat(generated.path("result").path("request").path("optionalParts")).isEqualTo(json.valueToTree(List.of("WAIST_0"))); + } + assertThat(generatedMatch(session, generated.path("analysisId").asText(), 1)).isEqualTo(match); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void optionalWaistIsOmittedWhenItCannotHelpOrAllLegsAttachDirectly(boolean directLegPorts) throws Exception { + ComponentFixtureSupport.loadLibrary(jdbc, json, "hexapod-waist-components.json"); + if (directLegPorts) { + jdbc.update("DELETE FROM component WHERE category='TORSO_0'"); + assemblyComponent("TORSO_0", "WAIST_0", "LEG_0", "LEG_0", "LEG_0", "LEG_0", "LEG_0", "LEG_0"); + } else { + ObjectNode waist = json.createObjectNode().put("rootLink", "LINK_WAIST_0"); + waist.putArray("frames").addObject().put("name", "__root_interface__").put("child", "LINK_WAIST_0").put("interfaceType", "WAIST_0"); + jdbc.update("UPDATE component SET urdf_info=? WHERE category='WAIST_0'", waist.toString()); + } + doAnswer(invocation -> hexapodRaw(invocation.getArgument(0))).when(model).analyze(anyList()); + JsonNode match = submit(create(), "m-optional-waist", "拼一个六足机器人", List.of()).path("match"); + assertThat(match.path("components").findValuesAsText("category")).doesNotContain("WAIST_0"); + assertThat(match.path("components")).hasSize(directLegPorts ? 13 : 1); + assertThat(match.path("status").asText()).isEqualTo(directLegPorts ? "complete" : "partial"); + } + + @Test void hexapodWaistReplacementPreservesConnectorPermissionAndExistingLegInstances() throws Exception { + ComponentFixtureSupport.loadLibrary(jdbc, json, "hexapod-waist-components.json"); + doAnswer(invocation -> hexapodRaw(invocation.getArgument(0))).when(model).analyze(anyList()); + Session session = create(); + JsonNode initial = submit(session, "m-hexapod", "拼一个六足机器人", List.of()).path("match"); + duplicate("CW-3JB52HZTFYTPZ1F0", "CW-WAIST-ALTERNATIVE", "六足腰部备选"); + replacementModel("WAIST", "all"); + JsonNode replaced = submit(session, "m-replace-waist", "换个腰部", List.of()); + JsonNode match = replaced.path("match"); + assertThat(match.path("status").asText()).isEqualTo("complete"); + assertThat(match.path("change").path("status").asText()).isEqualTo("applied"); + assertThat(replaced.path("result").path("request").path("optionalParts")).isEqualTo(json.valueToTree(List.of("WAIST_0"))); + Map expected = codesByRole(initial); + expected.put("WAIST_0:1", "CW-WAIST-ALTERNATIVE"); + assertThat(codesByRole(match)).isEqualTo(expected); + assertThat(match.path("assembly").path("connections")).hasSize(13); + } + @Test void explicitlyExcludedTorsoIsNotSilentlyAddedByStructuredMatching() throws Exception { components(true, 20); doAnswer(invocation -> { @@ -713,7 +787,7 @@ class DemandFlowApiTest { jdbc.update("UPDATE component SET status='DISABLED' WHERE component_code='CW-ARM'"); return response; }).when(matching).matchConfirmed(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.anySet(), - org.mockito.ArgumentMatchers.anyList(), org.mockito.ArgumentMatchers.anySet()); + org.mockito.ArgumentMatchers.anyList(), org.mockito.ArgumentMatchers.anySet(), org.mockito.ArgumentMatchers.anySet()); Session session = create(); MvcResult pending = message(session, "m-disabled-during-match", TEXT, List.of()); pending.getAsyncResult(5000); @@ -1555,6 +1629,18 @@ class DemandFlowApiTest { for (JsonNode selection : match.path("components")) if (instanceId.equals(selection.path("instanceId").asText())) return selection; throw new AssertionError("缺少实例 " + instanceId); } + private ObjectNode hexapodRaw(List history) { + ObjectNode raw = raw(history); + 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("六足", "机器人", "数量1台")) raw.withArray("keywords").addObject() + .put("term", term).put("source", "explicit").put("reason", "用户需求").put("negated", false).putArray("evidenceIds").add("e1"); + intent(raw, "form", "整机", "六足构型"); + intent(raw, "quantity", "整机", "1台"); + constraint(raw, "robot", "quantity", "1", "eq", null); + return raw; + } private ObjectNode humanoidRaw(List history) { ObjectNode raw = raw(history); for (String field : List.of("constraints", "intentItems", "partCategories", "robotTypes")) raw.putArray(field); diff --git a/cadworld-api/src/test/resources/fixtures/hexapod-waist-components.json b/cadworld-api/src/test/resources/fixtures/hexapod-waist-components.json new file mode 100644 index 0000000..5af9d8d --- /dev/null +++ b/cadworld-api/src/test/resources/fixtures/hexapod-waist-components.json @@ -0,0 +1,584 @@ +[ + { + "component_code": "CW-GFQGN4DVNT5Q79FW", + "component_name": "脚_0_六足脚1", + "category": "FOOT_0", + "description": "六足机器人脚", + "material": "", + "mass_kg": 0.0, + "degrees_of_freedom": 1, + "function_description": "", + "shape": "", + "size": "", + "torque_nm": 0.0, + "bom_list": [], + "urdf_info": { + "frames": [ + { + "rpy": [ + 0, + 0, + 0 + ], + "xyz": [ + 0, + 0, + 0 + ], + "kind": "interface", + "name": "__root_interface__", + "child": "LINK_FOOT_0", + "isRoot": true, + "limits": {}, + "parent": null, + "synthetic": true, + "interfaceName": "LINK_FOOT_0", + "interfaceType": "FOOT_0", + "originExplicit": false + } + ], + "rootLink": "LINK_FOOT_0", + "robotName": "脚_0_六足脚1" + }, + "step_object_key": "components/CW-GFQGN4DVNT5Q79FW/model.step", + "urdf_prefix": "components/CW-GFQGN4DVNT5Q79FW/urdf/", + "urdf_main_object_key": "components/CW-GFQGN4DVNT5Q79FW/urdf/robot.urdf", + "urdf_files": [ + { + "relativePath": "robot.urdf", + "sizeBytes": 1 + } + ], + "version": 1 + }, + { + "component_code": "CW-8ZDENK5SQW1APH2S", + "component_name": "头_0_六足头1", + "category": "HEAD_0", + "description": "六足机器人头", + "material": "", + "mass_kg": 0.0, + "degrees_of_freedom": 1, + "function_description": "", + "shape": "", + "size": "", + "torque_nm": 0.0, + "bom_list": [], + "urdf_info": { + "frames": [ + { + "rpy": [ + 0, + 0, + 0 + ], + "xyz": [ + 0, + 0, + 0 + ], + "kind": "interface", + "name": "__root_interface__", + "child": "LINK_WAIST_0", + "isRoot": true, + "limits": {}, + "parent": null, + "synthetic": true, + "interfaceName": "LINK_WAIST_0", + "interfaceType": "WAIST_0", + "originExplicit": false + } + ], + "rootLink": "LINK_WAIST_0", + "robotName": "头_0_六足头1" + }, + "step_object_key": "components/CW-8ZDENK5SQW1APH2S/model.step", + "urdf_prefix": "components/CW-8ZDENK5SQW1APH2S/urdf/", + "urdf_main_object_key": "components/CW-8ZDENK5SQW1APH2S/urdf/robot.urdf", + "urdf_files": [ + { + "relativePath": "robot.urdf", + "sizeBytes": 1 + } + ], + "version": 1 + }, + { + "component_code": "CW-3Z2XH5K45D4K8JPP", + "component_name": "足_0_虫足3DOF摆动", + "category": "LEG_0", + "description": "六足机器人足", + "material": "", + "mass_kg": 0.0, + "degrees_of_freedom": 1, + "function_description": "", + "shape": "", + "size": "", + "torque_nm": 0.0, + "bom_list": [], + "urdf_info": { + "frames": [ + { + "rpy": [ + 1.5707963267949, + 1.5707963267949, + 0 + ], + "xyz": [ + 0.0445, + 0, + 0 + ], + "axis": [ + 0, + 0, + -1 + ], + "kind": "joint", + "name": "J_1_Link", + "type": "revolute", + "child": "1_Link", + "limits": { + "lower": -1.57, + "upper": 0.785, + "effort": 0, + "velocity": 0 + }, + "parent": "LINK_LEG_0", + "interfaceName": null, + "interfaceType": null, + "originExplicit": true + }, + { + "rpy": [ + 0, + 0, + 0 + ], + "xyz": [ + 0.0395979797464467, + 0.0395979797464466, + 0 + ], + "axis": [ + 0, + 0, + -1 + ], + "kind": "joint", + "name": "J_2_Link", + "type": "revolute", + "child": "2_Link", + "limits": { + "lower": -0.785, + "upper": 1.57, + "effort": 0, + "velocity": 0 + }, + "parent": "1_Link", + "interfaceName": null, + "interfaceType": null, + "originExplicit": true + }, + { + "rpy": [ + 0, + 0, + 3.14159265358979 + ], + "xyz": [ + -0.0395979797464466, + 0.0395979797464467, + 0 + ], + "axis": [ + 0, + 0, + 1 + ], + "kind": "joint", + "name": "J_LINK_FOOT_0", + "type": "continuous", + "child": "LINK_FOOT_0", + "limits": {}, + "parent": "2_Link", + "interfaceName": "LINK_FOOT_0", + "interfaceType": "FOOT_0", + "originExplicit": true + }, + { + "rpy": [ + 0, + 0, + 0 + ], + "xyz": [ + 0, + 0, + 0 + ], + "kind": "interface", + "name": "__root_interface__", + "child": "LINK_LEG_0", + "isRoot": true, + "limits": {}, + "parent": null, + "synthetic": true, + "interfaceName": "LINK_LEG_0", + "interfaceType": "LEG_0", + "originExplicit": false + } + ], + "rootLink": "LINK_LEG_0", + "robotName": "足_0_虫足3DOF摆动" + }, + "step_object_key": "components/CW-3Z2XH5K45D4K8JPP/model.step", + "urdf_prefix": "components/CW-3Z2XH5K45D4K8JPP/urdf/", + "urdf_main_object_key": "components/CW-3Z2XH5K45D4K8JPP/urdf/robot.urdf", + "urdf_files": [ + { + "relativePath": "robot.urdf", + "sizeBytes": 1 + } + ], + "version": 1 + }, + { + "component_code": "CW-FS081NP1VD45Z7NJ", + "component_name": "躯干_0_直筒披肩机器人", + "category": "TORSO_0", + "description": "", + "material": "", + "mass_kg": 0.0, + "degrees_of_freedom": 1, + "function_description": "", + "shape": "", + "size": "", + "torque_nm": 0.0, + "bom_list": [], + "urdf_info": { + "frames": [ + { + "rpy": [ + 0, + 0, + 0 + ], + "xyz": [ + 0.0018067, + 0, + 0.0935 + ], + "axis": [ + 0, + 0, + -1 + ], + "kind": "joint", + "name": "J1", + "type": "continuous", + "child": "LINK_HEAD_0", + "limits": {}, + "parent": "LINK_WAIST_0", + "interfaceName": "LINK_HEAD_0", + "interfaceType": "HEAD_0", + "originExplicit": true + }, + { + "rpy": [ + -1.5708, + 1.5708, + 0 + ], + "xyz": [ + 0.0018067, + 0.0505, + 0.0675 + ], + "axis": [ + 0, + 0, + -1 + ], + "kind": "joint", + "name": "J2", + "type": "continuous", + "child": "LINK_ARM_L", + "limits": {}, + "parent": "LINK_WAIST_0", + "interfaceName": "LINK_ARM_L", + "interfaceType": "ARM_L", + "originExplicit": true + }, + { + "rpy": [ + 1.5707963267949, + 1.5707963267949, + 0 + ], + "xyz": [ + 0.00180667202154026, + -0.0505, + 0.0675 + ], + "axis": [ + 0, + 0, + -1 + ], + "kind": "joint", + "name": "J3", + "type": "continuous", + "child": "LINK_ARM_R", + "limits": {}, + "parent": "LINK_WAIST_0", + "interfaceName": "LINK_ARM_R", + "interfaceType": "ARM_R", + "originExplicit": true + }, + { + "rpy": [ + 0, + 0, + 0 + ], + "xyz": [ + 0, + 0, + 0 + ], + "kind": "interface", + "name": "__root_interface__", + "child": "LINK_WAIST_0", + "isRoot": true, + "limits": {}, + "parent": null, + "synthetic": true, + "interfaceName": "LINK_WAIST_0", + "interfaceType": "WAIST_0", + "originExplicit": false + } + ], + "rootLink": "LINK_WAIST_0", + "robotName": "躯干_0_直筒披肩机器人" + }, + "step_object_key": "components/CW-FS081NP1VD45Z7NJ/model.step", + "urdf_prefix": "components/CW-FS081NP1VD45Z7NJ/urdf/", + "urdf_main_object_key": "components/CW-FS081NP1VD45Z7NJ/urdf/robot.urdf", + "urdf_files": [ + { + "relativePath": "robot.urdf", + "sizeBytes": 1 + } + ], + "version": 5 + }, + { + "component_code": "CW-3JB52HZTFYTPZ1F0", + "component_name": "腰_0_六足腰2", + "category": "WAIST_0", + "description": "六足机器人腰部", + "material": "", + "mass_kg": 0.0, + "degrees_of_freedom": 1, + "function_description": "", + "shape": "", + "size": "", + "torque_nm": 0.0, + "bom_list": [], + "urdf_info": { + "frames": [ + { + "rpy": [ + 3.14159265358979, + 0, + -1.5707963267949 + ], + "xyz": [ + 0, + -0.0845000000000002, + -0.027 + ], + "axis": [ + 0, + 0, + 1 + ], + "kind": "joint", + "name": "J_LINK#1_LEG_0", + "type": "continuous", + "child": "LINK_LEG_0", + "limits": {}, + "parent": "LINK_WAIST_0", + "interfaceName": "LINK_LEG_0", + "interfaceType": "LEG_0", + "originExplicit": true + }, + { + "rpy": [ + 3.14159265358979, + 0, + -2.61799387799148 + ], + "xyz": [ + -0.0731791466197846, + -0.0422500000000013, + -0.027 + ], + "axis": [ + 0, + 0, + 1 + ], + "kind": "joint", + "name": "J_LINK#2_LEG_0", + "type": "continuous", + "child": "LINK_LEG_0", + "limits": {}, + "parent": "LINK_WAIST_0", + "interfaceName": "LINK_LEG_0", + "interfaceType": "LEG_0", + "originExplicit": true + }, + { + "rpy": [ + 3.14159265358979, + 0, + 2.61799387799151 + ], + "xyz": [ + -0.0731791466197859, + 0.0422499999999991, + -0.027 + ], + "axis": [ + 0, + 0, + 1 + ], + "kind": "joint", + "name": "J_LINK#3_LEG_0", + "type": "continuous", + "child": "LINK_LEG_0", + "limits": {}, + "parent": "LINK_WAIST_0", + "interfaceName": "LINK_LEG_0", + "interfaceType": "LEG_0", + "originExplicit": true + }, + { + "rpy": [ + 3.14159265358979, + 0, + 1.5707963267949 + ], + "xyz": [ + 0, + 0.0845000000000002, + -0.027 + ], + "axis": [ + 0, + 0, + 1 + ], + "kind": "joint", + "name": "J_LINK#4_LEG_0", + "type": "continuous", + "child": "LINK_LEG_0", + "limits": {}, + "parent": "LINK_WAIST_0", + "interfaceName": "LINK_LEG_0", + "interfaceType": "LEG_0", + "originExplicit": true + }, + { + "rpy": [ + -3.14159265358979, + 0, + 0.523598775598312 + ], + "xyz": [ + 0.0731791466197847, + 0.0422500000000008, + -0.027 + ], + "axis": [ + 0, + 0, + 1 + ], + "kind": "joint", + "name": "J_LINK#5_LEG_0", + "type": "continuous", + "child": "LINK_LEG_0", + "limits": {}, + "parent": "LINK_WAIST_0", + "interfaceName": "LINK_LEG_0", + "interfaceType": "LEG_0", + "originExplicit": true + }, + { + "rpy": [ + -3.14159265358979, + 0, + -0.523598775598288 + ], + "xyz": [ + 0.0731791466197853, + -0.0422499999999998, + -0.027 + ], + "axis": [ + 0, + 0, + 1 + ], + "kind": "joint", + "name": "J_LINK#6_LEG_0", + "type": "continuous", + "child": "LINK_LEG_0", + "limits": {}, + "parent": "LINK_WAIST_0", + "interfaceName": "LINK_LEG_0", + "interfaceType": "LEG_0", + "originExplicit": true + }, + { + "rpy": [ + 0, + 0, + 0 + ], + "xyz": [ + 0, + 0, + 0 + ], + "kind": "interface", + "name": "__root_interface__", + "child": "LINK_WAIST_0", + "isRoot": true, + "limits": {}, + "parent": null, + "synthetic": true, + "interfaceName": "LINK_WAIST_0", + "interfaceType": "WAIST_0", + "originExplicit": false + } + ], + "rootLink": "LINK_WAIST_0", + "robotName": "腰_0_六足腰2" + }, + "step_object_key": "components/CW-3JB52HZTFYTPZ1F0/model.step", + "urdf_prefix": "components/CW-3JB52HZTFYTPZ1F0/urdf/", + "urdf_main_object_key": "components/CW-3JB52HZTFYTPZ1F0/urdf/robot.urdf", + "urdf_files": [ + { + "relativePath": "robot.urdf", + "sizeBytes": 1 + } + ], + "version": 1 + } +] diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMatchService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMatchService.java index fb3d011..44a9414 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMatchService.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMatchService.java @@ -73,7 +73,7 @@ public final class DemandMatchService { private RobotMatchingService.ReplacementRequirements replacementRequirements(JsonNode saved) { Set excluded = new LinkedHashSet<>(); for (JsonNode item : saved.path("analysis").path("excludedCategories")) excluded.add(item.path("category").asText()); - return new RobotMatchingService.ReplacementRequirements(project(saved), requirements.softFields(saved), templateGroups(saved), Set.copyOf(excluded)); + return new RobotMatchingService.ReplacementRequirements(project(saved), requirements.softFields(saved), templateGroups(saved), Set.copyOf(excluded), optionalCategories(saved)); } private boolean acceptableChecks(JsonNode revised, RobotMatchResponse response, DemandRepository.Baseline baseline) { @@ -170,7 +170,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()), templateGroups(analysis.result()), excludedCategories); + response = matching.matchConfirmed(project(analysis.result()), requirements.softFields(analysis.result()), templateGroups(analysis.result()), excludedCategories, optionalCategories(analysis.result())); } ObjectNode result = build(matchId, analysis, response); log.info("需求自动选件与装配校验完成 requestId={} analysisId={} revision={} matchId={} selectedCount={} missingCount={} unmetCount={} status={} assemblyStatus={} assemblyIssueCodes={} durationMs={}", @@ -290,6 +290,10 @@ public final class DemandMatchService { } } + private Set optionalCategories(JsonNode saved) { + return Set.copyOf(DemandMechanicalNormalizer.texts(saved.path("request").path("optionalParts"))); + } + private RobotMatchRequest project(JsonNode saved) { try { JsonNode request = saved.path("request"); @@ -299,7 +303,11 @@ public final class DemandMatchService { List parts = new ArrayList<>(); for (JsonNode part : request.path("partRequirements")) parts.add(json.treeToValue(part, PartRequirements.class)); List keywords = new ArrayList<>(); - for (JsonNode keyword : saved.path("analysis").path("keywords")) if (!keyword.path("negated").asBoolean() && !keyword.path("term").asText().isBlank()) keywords.add(keyword.path("term").asText()); + for (JsonNode keyword : saved.path("analysis").path("keywords")) { + String term = keyword.path("term").asText(); + // 单台整机数量由结构化检查验证,不要求零件备注再包含“数量1台”。 + if (!keyword.path("negated").asBoolean() && !term.isBlank() && !term.matches("(?:数量)?[1一]台")) keywords.add(term); + } return new RobotMatchRequest(null, keywords.stream().distinct().toList(), DemandMechanicalNormalizer.texts(request.path("requiredParts")), json.treeToValue(robot, RobotRequirements.class), List.copyOf(parts)); } catch (Exception exception) { throw new BizException(409, "DEMAND_UNSUPPORTED_REQUEST", "已保存需求包含暂不支持的字段,请重新生成方案"); } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMechanicalNormalizer.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMechanicalNormalizer.java index f75b9e4..bb99654 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMechanicalNormalizer.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandMechanicalNormalizer.java @@ -27,6 +27,7 @@ final class DemandMechanicalNormalizer { LinkedHashSet warnings = new LinkedHashSet<>(texts(raw.path("warnings"))); ArrayNode unmodeled = raw.withArray("unmodeled").deepCopy(); LinkedHashSet categories = new LinkedHashSet<>(); + LinkedHashSet optional = new LinkedHashSet<>(); Map templateGroups = new LinkedHashMap<>(); Set excluded = new LinkedHashSet<>(); for (JsonNode item : raw.path("excludedCategories")) excluded.add(item.path("category").asText()); @@ -34,6 +35,7 @@ final class DemandMechanicalNormalizer { for (JsonNode type : raw.path("robotTypes")) { JsonNode template = template(type.path("type").asText()); expandTemplate(template, categories, templateGroups); + optional.addAll(texts(template.path("optionalParts"))); String keyword = template.path("keyword").asText(); boolean present = false; for (JsonNode item : raw.path("keywords")) present |= keyword.equals(item.path("term").asText()); @@ -78,10 +80,15 @@ final class DemandMechanicalNormalizer { String field = rows.get(0).path("field").asText(); String target = rows.get(0).path("target").asText(); try { - if ("quantity".equals(field) && ("robot".equals(target) || rows.stream().anyMatch((ObjectNode row) -> !"eq".equals(row.path("operator").asText())))) { + if ("quantity".equals(field) && rows.stream().anyMatch((ObjectNode row) -> !"eq".equals(row.path("operator").asText()))) { throw new IllegalArgumentException("组件数量只支持明确部位的等值要求"); } Condition condition = NUMERIC.contains(field) ? number(field, rows, numericSources) : text(field, rows); + if ("quantity".equals(field) && "robot".equals(target)) { + if (condition.number().compareTo(BigDecimal.ONE) != 0) throw new IllegalArgumentException("当前只支持生成1台整机"); + // 一次生成固定一台整机,不把整机数量投影为每个组件的数量。 + continue; + } ObjectNode container = "robot".equals(target) ? robot : parts.computeIfAbsent(target, (String key) -> json.createObjectNode().put("category", key)); if (condition.number() != null) { @@ -105,6 +112,7 @@ final class DemandMechanicalNormalizer { if (!defaultTemplate.isBlank()) { JsonNode fallback = template(defaultTemplate); expandTemplate(fallback, categories, templateGroups); + optional.addAll(texts(fallback.path("optionalParts"))); warnings.add("未指定可匹配的机器人类型或部位,按默认" + fallback.path("label").asText() + "生成参考方案。"); } } @@ -118,6 +126,9 @@ final class DemandMechanicalNormalizer { boolean defaultTorsoAdded = !categories.isEmpty() && !categories.contains("TORSO_0") && !excluded.contains("TORSO_0"); if (!categories.isEmpty() && !excluded.contains("TORSO_0")) categories.add("TORSO_0"); for (JsonNode category : catalog.path("categories")) if (categories.contains(category.asText()) && !excluded.contains(category.asText())) required.add(category); + optional.removeAll(categories); + optional.removeAll(excluded); + if (!optional.isEmpty()) request.set("optionalParts", json.valueToTree(optional)); if (required.isEmpty()) warnings.add("当前需求没有可选部位,将返回无匹配结果。"); request.set("robotRequirements", robot); request.set("partRequirements", json.valueToTree(parts.values())); diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNumberParser.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNumberParser.java index a47a771..01783f8 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNumberParser.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandNumberParser.java @@ -29,7 +29,7 @@ public final class DemandNumberParser { if (!match.matches()) throw new IllegalArgumentException("数值格式不明确"); String unit = match.group(2).toLowerCase(Locale.ROOT).replaceAll("\\s", ""); String factor = "quantity".equals(field) - ? List.of("", "个", "件", "条", "只", "套", "支").contains(unit) ? "1" : null + ? List.of("", "个", "件", "条", "只", "套", "支", "台").contains(unit) ? "1" : null : "degreesOfFreedom".equals(field) ? List.of("", "dof", "自由度", "个自由度").contains(unit) ? "1" : null : "massKg".equals(field) ? MASS.get(unit) : TORQUE.get(unit); @@ -102,7 +102,7 @@ public final class DemandNumberParser { } private static String units(String field) { return switch (field) { - case "quantity" -> "(?:个|件|条|只|套|支)"; + case "quantity" -> "(?:个|件|条|只|套|支|台)"; case "massKg" -> "(?:千克|公斤|kg|克|g|吨|t|斤)"; case "torqueNm" -> "(?:N\\s*[·.*]?\\s*(?:cm|m)|牛顿·?米|牛·?米)"; default -> "(?:个?自由度|dof)?"; diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandRequirementChecker.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandRequirementChecker.java index b992fc7..d1ed4f6 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandRequirementChecker.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/demand/DemandRequirementChecker.java @@ -87,6 +87,7 @@ public final class DemandRequirementChecker { } continue; } + if (checkHexapodForm(intent, request, analysis, match, assemblyRoles, check)) continue; if ("exclusion".equals(intent.path("dimension").asText()) && !roles.isEmpty()) { Set excluded = new LinkedHashSet<>(); for (JsonNode item : analysis.path("excludedCategories")) excluded.add(item.path("category").asText()); @@ -180,6 +181,36 @@ public final class DemandRequirementChecker { return checks; } + /** 模板构型由实际连接的部位数量验证,不依赖 shape 或 description 中是否登记了相同文字。 */ + private boolean checkHexapodForm(JsonNode intent, JsonNode request, JsonNode analysis, RobotMatchResponse match, + Map assemblyRoles, ObjectNode check) { + if (!"form".equals(intent.path("dimension").asText()) + || !intent.path("subject").asText().matches(".*(?:整机|整体|全机|机器人).*")) return false; + String requirement = intent.path("requirement").asText().replaceAll("\\s+", "").toLowerCase(Locale.ROOT); + if (!requirement.matches("(?:采用|使用)?(?:六足|六腿|hexapod)(?:机器人)?(?:构型|结构|形态)?")) return false; + boolean hexapod = false; + for (JsonNode type : analysis.path("robotTypes")) hexapod |= "hexapod".equals(type.path("type").asText()); + if (!hexapod) return false; + ObjectNode expected = json.createObjectNode(); + ObjectNode actual = json.createObjectNode(); + for (JsonNode group : request.path("templatePartGroups")) { + String family = group.path("family").asText(); + List categories = DemandMechanicalNormalizer.texts(group.path("categories")); + long count = match.parts().stream().filter((PublicComponentResponse part) -> + categories.contains(assemblyRoles.getOrDefault(part.instanceId(), part.category()))).count(); + expected.put(family, group.path("minimumQuantity").asInt()); + actual.put(family, count); + } + if (expected.path("LEG").asInt() != 6 || expected.path("FOOT").asInt() != 6) return false; + boolean satisfied = actual.path("LEG").asInt() >= 6 && actual.path("FOOT").asInt() >= 6 + && !match.parts().isEmpty() && match.missingParts().isEmpty() && match.missingPartGroups().isEmpty(); + check.put("field", "templatePartGroups").put("status", satisfied ? "satisfied" : "unmet") + .put("reason", satisfied ? "所选组件的连接及部位数量符合六足模板" : "尚未连接齐六足模板所需的部位"); + check.set("expected", expected); + check.set("actual", actual); + return true; + } + static String field(JsonNode intent) { String value = intent.path("requirement").asText(); if (value.matches(".*(?:自由度|DOF|dof).*")) return "degreesOfFreedom"; @@ -230,7 +261,7 @@ public final class DemandRequirementChecker { static Integer quantity(JsonNode intent) { String numberPattern = "(?= AssemblyState.MAX_INSTANCES) { limited = true; continue; } @@ -119,6 +120,19 @@ public class AssemblySearchEngine { return false; } + /** 可选腰部等连接件必须能从未占用的另一接口接到缺少的部位,避免为凑数量添加无关组件。 */ + private boolean connectsMissingPart(CandidatePool.Attachment connector, AssemblyState state, CandidatePool.Result pool, NormalizedMatchRequest request) { + for (AssemblyMetadata.Port port : connector.candidate().metadata().ports()) { + if (port.index() == connector.port().index() || !request.allowsPort(port)) continue; + for (CandidatePool.Attachment target : pool.targets(port.role(), port.child())) { + ComponentRole role = target.candidate().role(); + if (request.needed(role, state, false) && request.canAdd(role, state.count(role)) + && InterfaceCompatibility.canAttach(port, target.candidate(), target.port())) return true; + } + } + return false; + } + record ScoredState(AssemblyState state, RequirementEvaluator.Evaluation evaluation, RequirementEvaluator.Estimate estimate, String key, int missingMinimum, int missingTypes, int localKeywordCoverage, int localKeywordScore) { } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/CandidatePool.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/CandidatePool.java index 26a0d19..d637a12 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/CandidatePool.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/CandidatePool.java @@ -135,7 +135,7 @@ final class CandidatePool { request.allowsPort(port) && pool.targets(port.role(), port.child()).stream().anyMatch((Attachment target) -> target.candidate().role() == role && InterfaceCompatibility.canAttach(port, target.candidate(), target.port()))) .map(AssemblyMetadata.Port::index).toList(); - int quantity = minimumOnly ? request.minimum(role) + int quantity = request.optional(role) ? 1 : minimumOnly ? request.minimum(role) : request.quantity(role) == null ? AssemblyState.MAX_INSTANCES : request.quantity(role); for (int index = 0; index < Math.min(quantity, ports.size()); index++) slots.add(ports); } diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/NormalizedMatchRequest.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/NormalizedMatchRequest.java index 2df78c4..ec13b96 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/NormalizedMatchRequest.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/NormalizedMatchRequest.java @@ -32,6 +32,11 @@ record NormalizedMatchRequest(List roles, List keywords, static NormalizedMatchRequest from(RobotMatchRequest request, Set softFields, List templateGroups, Set excludedRoles) { + return from(request, softFields, templateGroups, excludedRoles, Set.of()); + } + + static NormalizedMatchRequest from(RobotMatchRequest request, Set softFields, List templateGroups, + Set excludedRoles, Set optionalCategories) { if (request.requiredParts() == null || request.requiredParts().isEmpty()) { throw invalid("requiredParts不能为空"); } @@ -39,6 +44,7 @@ record NormalizedMatchRequest(List roles, List keywords, required.add(ComponentRole.TORSO); request.requiredParts().stream().map(ComponentRole::require).filter((ComponentRole role) -> !excludedRoles.contains(role)).forEach(required::add); Set available = new LinkedHashSet<>(required); + optionalCategories.stream().map(ComponentRole::require).filter((ComponentRole role) -> !excludedRoles.contains(role)).forEach(available::add); List groups = new ArrayList<>(); Set families = new LinkedHashSet<>(); for (TemplatePartGroup group : templateGroups) { @@ -120,7 +126,12 @@ record NormalizedMatchRequest(List roles, List keywords, } boolean canAdd(ComponentRole role, int current) { - return role != ComponentRole.TORSO && roles.contains(role) && (quantity(role) == null || current < quantity(role)); + return role != ComponentRole.TORSO && roles.contains(role) && (!optional(role) || current == 0) + && (quantity(role) == null || current < quantity(role)); + } + + boolean optional(ComponentRole role) { + return roles.contains(role) && !requiredRoles.contains(role) && groups.stream().noneMatch((PartGroup group) -> group.roles().contains(role)); } record PartGroup(String family, List roles, int minimumQuantity) { diff --git a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RobotMatchingService.java b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RobotMatchingService.java index 1004124..cf4ca2c 100644 --- a/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RobotMatchingService.java +++ b/cadworld-service/src/main/java/com/linkerbot/cadworld/service/matching/RobotMatchingService.java @@ -37,7 +37,7 @@ public class RobotMatchingService { private final MatchingProperties properties; public record ReplacementRequirements(RobotMatchRequest request, Set softFields, - List groups, Set excludedCategories) { } + List groups, Set excludedCategories, Set optionalCategories) { } public record ReplacementOutcome(RobotMatchResponse response, String reasonCode) { } @Transactional(readOnly = true) @@ -93,7 +93,7 @@ public class RobotMatchingService { private NormalizedMatchRequest normalize(ReplacementRequirements requirements) { Set excluded = requirements.excludedCategories().stream().map(ComponentRole::require).collect(java.util.stream.Collectors.toSet()); - return NormalizedMatchRequest.from(requirements.request(), requirements.softFields(), requirements.groups(), excluded); + return NormalizedMatchRequest.from(requirements.request(), requirements.softFields(), requirements.groups(), excluded, requirements.optionalCategories()); } private RobotMatchResponse checkResponse(AssemblyState state, NormalizedMatchRequest request, CandidatePool.Result pool) { @@ -148,8 +148,21 @@ public class RobotMatchingService { private RobotMatchResponse matchInternal(RobotMatchRequest input, boolean strictFirst, Set softFields, List groups, Set excluded) { + return matchInternal(input, strictFirst, softFields, groups, excluded, Set.of()); + } + + /** 模板允许的可选部件只用于补齐真实接口路径,不成为必须安装的部位。 */ + @Transactional(readOnly = true) + public RobotMatchResponse matchConfirmed(RobotMatchRequest input, Set softFields, List groups, + Set excludedCategories, Set optionalCategories) { + Set excluded = excludedCategories.stream().map(ComponentRole::require).collect(java.util.stream.Collectors.toUnmodifiableSet()); + return matchInternal(input, true, softFields, groups, excluded, optionalCategories); + } + + private RobotMatchResponse matchInternal(RobotMatchRequest input, boolean strictFirst, Set softFields, List groups, + Set excluded, Set optionalCategories) { long started = System.nanoTime(); - NormalizedMatchRequest request = NormalizedMatchRequest.from(input, softFields, groups, excluded); + NormalizedMatchRequest request = NormalizedMatchRequest.from(input, softFields, groups, excluded, optionalCategories); CandidatePool collector = new CandidatePool(request, evaluator, properties); components.scan(request.scanRoles(), collector::accept); CandidatePool.Result pool = collector.finish(); @@ -203,6 +216,12 @@ public class RobotMatchingService { RequestIdHolder.get(), request.roles().size(), pool.scanned(), response.parts().size(), neutralConnections, response.status(), response.unmetRequirements().size(), response.missingParts().size(), result.limited(), result.expansions(), (System.nanoTime() - started) / 1_000_000); + if (!optionalCategories.isEmpty()) { + List selectedConnectors = selected == null ? List.of() : selected.parts().values().stream() + .filter((MatchingCandidate candidate) -> request.optional(candidate.role())).map(MatchingCandidate::code).toList(); + log.info("模板可选连接件匹配完成 requestId={} optionalCategories={} selectedComponentCodes={}", + RequestIdHolder.get(), optionalCategories, selectedConnectors); + } return response; } diff --git a/cadworld-service/src/main/resources/robot-demand/part-catalog.json b/cadworld-service/src/main/resources/robot-demand/part-catalog.json index 8bcea72..c8903fe 100644 --- a/cadworld-service/src/main/resources/robot-demand/part-catalog.json +++ b/cadworld-service/src/main/resources/robot-demand/part-catalog.json @@ -1,5 +1,5 @@ { - "version": "2026-10-16-hexapod-template", + "version": "2026-10-27-hexapod-connectors", "defaultTemplate": "biped", "categories": [ "TORSO_0", @@ -74,6 +74,9 @@ "parts": [ "TORSO_0" ], + "optionalParts": [ + "WAIST_0" + ], "keyword": "六足", "partGroups": [ { diff --git a/cadworld-service/src/main/resources/robot-demand/system-prompt.txt b/cadworld-service/src/main/resources/robot-demand/system-prompt.txt index 0505760..36843d9 100644 --- a/cadworld-service/src/main/resources/robot-demand/system-prompt.txt +++ b/cadworld-service/src/main/resources/robot-demand/system-prompt.txt @@ -21,13 +21,13 @@ 三、类型与部位 11. 配置目录:{{CATALOG_JSON}}。robotTypes 只使用目录中的模板 id;程序展开 requiredParts,你不输出该字段。能辨认形态时选对应模板,图片推断标 inferred。未指定形态时 robotTypes=[],后端使用默认模板并说明。目录不代表库存齐全或能力达标。 -12. 六足/六腿/hexapod 选择 hexapod 模板,不得标为不支持或回退为双足。六足基本构型由躯干、六个足部和六个脚部候选组成,具体左右或中性类型由后端按实际接口选择,不默认添加人形的头、腰、臂、手或尾。未配置的四足、轮式、履带、鸟形等保留为 unmodeled,不谎称双足能够满足;后端可返回默认参考方案并保留差异。“仿生鸟类”保留机器人、仿生、鸟类等关键词,可将双足作为 inferred 候选;飞行能力保留为未验证,企鹅、鸵鸟或明确不飞行时不推断飞行。 +12. 六足/六腿/hexapod 选择 hexapod 模板,不得标为不支持或回退为双足。六足基本构型由躯干、六个足部和六个脚部候选组成,具体左右或中性类型由后端按实际接口选择。后端可按目录 optionalParts 使用腰部作为连接件,不将腰部列为必须安装,也不默认添加人形的头、臂、手或尾。optionalParts 由后端生成,不自行输出。未配置的四足、轮式、履带、鸟形等保留为 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非空且相等时可连接;ARM/HAND/LEG/FOOT的父L/R接口也可安装同部位0接口组件,父0只接0,L/R不能互接,其他字符保持原有大小写匹配。0组件可承担指定侧需求,真实组件类别与本次装配角色分别保留;同child的多个接口独立处理,后端只返回实例连接关系,摆放由前端处理。不要从草图像素生成3D位置。 四、机械条件 -16. 只使用 componentName、degreesOfFreedom、material、functionDescription、shape、size、torqueNm、massKg、description、quantity。quantity只用于明确部位数量且operator=eq。scope=robot 整机、part 指定部件、unspecified 对象未明确;categories 仅 part 使用。整体 20 自由度不能给每个部件 20;双臂总质量 2kg 不能给每臂 2kg,组合约束保留为 unmodeled。不把“机器人”当作用户指定名称。 +16. 只使用 componentName、degreesOfFreedom、material、functionDescription、shape、size、torqueNm、massKg、description、quantity。quantity约束只用于明确部位数量且operator=eq。“1台机器人”作为整机数量 intentItems 保留,由后端单台生成规则验证,不写成部件数量或 constraints;多台整机数量仍须保留,不能宣称单台满足。scope=robot 整机、part 指定部件、unspecified 对象未明确;categories 仅 part 使用。整体 20 自由度不能给每个部件 20;双臂总质量 2kg 不能给每臂 2kg,组合约束保留为 unmodeled。不把“机器人”当作用户指定名称。 17. 质量、扭矩、自由度的 value 保留原数字和单位,例如“二十”“500克”“20N·m”“200N·cm”,由后端换算。缺单位时保留原文和缺口,不默认 kg/N·m,也不提问。明确 0 保留,未知值省略。size 保留完整尺寸与单位,不凭图片猜尺寸或材质牌号。 18. operator=eq/lte/gte/lt/gt/neq/range,range 的 value/upperValue 分别为上下界,其他 upperValue=""。同字段多条件分别保留,矛盾也保留;无法投影的严格比较、范围、排除属性由后端保留为未验证项,不擅自放宽或丢弃原要求。 19. “最好/尽量/大概/偏好/轻一点/小一点”保留为偏好,不能提升为硬数值。硬 constraints 只来自明确文字或清晰 OCR。图片推断和不清晰信息不能标 must 或成为硬数值。 diff --git a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandNormalizerTest.java b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandNormalizerTest.java index 767b101..3f24f7b 100644 --- a/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandNormalizerTest.java +++ b/cadworld-service/src/test/java/com/linkerbot/cadworld/service/demand/DemandNormalizerTest.java @@ -36,7 +36,7 @@ class DemandNormalizerTest { assertThat(actual.analysis().path("canSubmit").asBoolean()).isTrue(); assertThat(actual.analysis().path("questions")).isEmpty(); assertThat(actual.analysis().path("schemaVersion").asText()).isEqualTo("multimodal-v1.6-component-replacement"); - assertThat(actual.analysis().path("catalogVersion").asText()).isEqualTo("2026-10-16-hexapod-template"); + assertThat(actual.analysis().path("catalogVersion").asText()).isEqualTo("2026-10-27-hexapod-connectors"); } @Test void normalizesLegacyCategoriesInPartsConstraintsAndExclusionsWithoutChangingEvidence() { @@ -287,6 +287,37 @@ class DemandNormalizerTest { assertThat(result.request().path("partRequirements")).isEmpty(); } + @ParameterizedTest + @ValueSource(strings = {"1台", "一台", "一个"}) + void wholeRobotSingleQuantityIsValidatedWithoutBecomingAPartConstraint(String quantity) { + String input = "拼" + quantity + "六足机器人"; + ObjectNode raw = minimal(input); + ((ObjectNode) raw.path("robotTypes").get(0)).put("type", "hexapod"); + raw.withArray("intentItems").addObject().put("id", "q1").put("dimension", "quantity").put("subject", "整机") + .put("requirement", quantity).put("priority", "must").put("source", "explicit").putArray("evidenceIds").add("e1"); + constraint(raw, "robot", "quantity", "1", "eq", null, "e1"); + DemandResult result = normalizer.normalize(raw, text(input)); + assertThat(result.request().path("robotRequirements")).isEmpty(); + assertThat(result.request().path("partRequirements")).isEmpty(); + assertThat(result.request().path("optionalParts")).isEqualTo(json.valueToTree(List.of("WAIST_0"))); + assertThat(result.analysis().path("unmodeled")).isEmpty(); + assertThat(result.analysis().path("warnings").toString()).doesNotContain("数量要求超出", "组件数量只支持"); + assertThat(DemandRequirementChecker.quantitySupported(result.analysis().path("intentItems").get(0))).isTrue(); + } + + @Test void multipleWholeRobotsRemainUnsupportedAndDoNotChangePartQuantities() { + String input = "拼两台六足机器人"; + ObjectNode raw = minimal(input); + ((ObjectNode) raw.path("robotTypes").get(0)).put("type", "hexapod"); + raw.withArray("intentItems").addObject().put("id", "q1").put("dimension", "quantity").put("subject", "整机") + .put("requirement", "两台").put("priority", "must").put("source", "explicit").putArray("evidenceIds").add("e1"); + constraint(raw, "robot", "quantity", "2", "eq", null, "e1"); + DemandResult result = normalizer.normalize(raw, text(input)); + assertThat(result.request().path("partRequirements")).isEmpty(); + assertThat(result.analysis().path("unmodeled").get(0).path("reason").asText()).isEqualTo("当前只支持生成1台整机"); + assertThat(DemandRequirementChecker.quantitySupported(result.analysis().path("intentItems").get(0))).isFalse(); + } + @Test void replacementEvidenceCannotExpandAnExplicitSideOrComeFromAnEarlierMessage() { String text = "换个左臂"; ObjectNode raw = minimal(text);