支持局部、整组及多目标联合替换,固定其他组件。

任一目标失败,保留原方案和有效需求,并保存新版本说明原因。
默认优先同型号配套,明确参数和单侧替换要求优先。
请求体不变,新增 match.change 返回替换结果,无需改表。
This commit is contained in:
lxp
2026-10-26 11:29:57 +08:00
parent 7eef6e3994
commit a3434d12d5
30 changed files with 1370 additions and 29 deletions
+1 -1
View File
@@ -173,7 +173,7 @@ ARM、HAND、LEG、FOOT 的父接口采用单向兼容:L 可接 L/0,R 可接
先选定需求评分最高的一个躯干:按躯干自身条件的未满足数量、数值差距、功能文本和关键词相关性评价。关键词先比较命中的不同需求数量,再比较字段权重,避免名称中的泛称“机器人”压过说明中的“六足”等具体要求;需求评分相同时优先所需接口覆盖,最后按编码稳定排序。整机自由度、质量总量在选定躯干后的组合中评价,不直接作为躯干单件目标。组合在既有完整性、参数和整体关键词评分相同后,继续比较各实例的关键词相关性,使带有六足说明的足部候选优先于无相关说明的同接口候选。
默认方案始终只有一个躯干且以 `TORSO_0` 为根,未列出躯干时自动补入。后续只沿这个躯干的接口路径匹配其他部件,在固定躯干下优先覆盖所需部件,再评价整机条件。选中的躯干不会因为另一个躯干能接更多部件而自动替换。参数与材质可降级,角色和连接规则始终保持匹配;不自动加入其他未要求的中间连接件。
默认方案始终只有一个躯干且以 `TORSO_0` 为根,未列出躯干时自动补入。后续只沿这个躯干的接口路径匹配其他部件,在固定躯干下优先覆盖所需部件,再评价整机条件。选中的躯干不会因为另一个躯干能接更多部件而自动替换。在明确需求和组件齐全优先的前提下,ARM/HAND/LEG/FOOT 同族实例优先选择名称可识别的同型号组件,型号一致性优先于普通关键词相关性;用户明确指定的参数和型号仍优先。参数与材质可降级,角色和连接规则始终保持匹配;不自动加入其他未要求的中间连接件。
无法覆盖所有角色时返回躯干及可拼的连通部分;选中的躯干没有所需端口时可只返回躯干。没有可用躯干则返回 `NO_MATCH`,不会用其他角色作为根。躯干替代候选用于替换当前躯干,不追加第二个躯干。
+3 -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.5-neutral-components`,目录版本为 `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-16-hexapod-template`。原始来源作为参考保留,当前提示词与 Java 规则已调整为无追问的自动生成流程。来源文件夹保持不变,运行时不依赖 Node、React 或前端解析脚本。
业务标准化另外落实躯干优先规则:整机必须且只能有一个躯干,解析时可自动补入基础躯干;明确排除躯干时保留排除项并返回无匹配方案,不追问或偷偷补入。匹配先固定最符合需求的躯干,再搜索与其连通的其他组件。
@@ -68,13 +68,13 @@ java -jar cadworld-api/target/cadworld-api-0.0.1-SNAPSHOT.jar
`complete/partial/no_match` 描述需求匹配,`assembly.ready/blocked` 只描述是否有可展示组合和已生成的逻辑连接关系。缺件通过 `missingParts` 和 `partial` 提示,不进入 `assembly.issues`;缺件、性能不足或未验证能力不要求先接受降级,`degradationAcceptanceRequired` 固定为 false,因此 `partial` 可同时返回 `assembly.ready` 并直接显示已有有效组合。只有没有可用躯干/组件时才没有可展示组合;安装基准、位姿、活动关节和资源清单问题只返回提示,不阻塞已有组合。仅有有效躯干时可以显示躯干,连接数组为空。
默认组合和替代候选使用相同装配判定。兼容响应中的降级接受标记保留为 false,不提供单独接受流程;缺件、未验证能力和机械/资源问题继续保留。新生成结果不再保存只供接受流程使用的内部 `snapshot`,查询历史数据时仍移除旧快照。升级规则或组件库更新后,发送新消息生成新版本;原消息重放和状态查询不会重算。替代项是相对默认方案的一次替换预览,当前未实现多项替换的服务端验证或装配方案保存。
默认组合和替代候选使用相同装配判定。兼容响应中的降级接受标记保留为 false,不提供单独接受流程;缺件、未验证能力和机械/资源问题继续保留。新生成结果不再保存只供接受流程使用的内部 `snapshot`,查询历史数据时仍移除旧快照。升级规则或组件库更新后,发送新消息生成新版本;原消息重放和状态查询不会重算。替代项仍是相对当前服务端方案的一次替换预览,不能直接叠加任意前端候选。消息流程支持基于历史成功快照进行多目标联合替换,任一失败则保留原组合和有效需求并保存新版本;`match.change` 返回 applied/unchanged 及原因,详见接口文档的“对话局部替换”。默认选件和替代排序新增同型号软偏好,优先于普通关键词但不覆盖明确需求。新解析协议为 `multimodal-v1.6-component-replacement`;不改表,旧快照不回填。
## 接口数据与实例
组件类型扩展为16类,新增 ARM_0/HAND_0/LEG_0/FOOT_0。默认人形使用臂、手、足、脚四组各至少两个实例的要求,根据实际接口选择 L/R/0。明确六足需求使用 hexapod 模板,只要求躯干及 LEG/FOOT 各至少六个实例,不沿用人形部位要求。接口以合法 interfaceType 确定要查找的 category,缺失或无效时从 child 的 LINK_ 后解析已有类型编码/别名;无法确定类型时不从此接口向外扩展。装配角色必须属于需求;L/R 角色的候选扫描同时纳入同部位的 0 类组件,并按该侧需求评价条件、数量。child 完全相等时继续可连接;新增兼容只允许 ARM/HAND/LEG/FOOT 标准 LINK 编码末尾方向位 L/R(含小写 l/r)连接 0,其余字符保持区分大小写一致。frame 的 name、kind、type、坐标和安装基准不参与连接资格判断。
四类部位统一按父到子方向处理:L 接 L/0,R 接 R/0,0 只接 0,L/R 不互接;0 组件的其他接口不根据安装侧改写。真实 component.category 保留 0,实例标识、连接类别及替代分组使用装配角色;需求检查按装配角色统计,每个实例只计一次。显式排除同时约束真实类别和装配角色。候选沿用现有排序,替代项重新验证全部相邻连接,接口不重复占用。interfaceChild 为父接口原始 child,前端须用双方实例和 frame 下标定位,不能再假设双方 child 相等。默认模板的候选类型通过后端生成的 `result.request.templatePartGroups` 扩展,具体类别和分组合计缺口分别返回 `missingParts`、`missingPartGroups`。部署时同步读取 `multimodal-v1.5-neutral-components`;消息请求参数不变,无需数据库迁移,原始 URDF 与历史方案均不回写。
四类部位统一按父到子方向处理:L 接 L/0,R 接 R/0,0 只接 0,L/R 不互接;0 组件的其他接口不根据安装侧改写。真实 component.category 保留 0,实例标识、连接类别及替代分组使用装配角色;需求检查按装配角色统计,每个实例只计一次。显式排除同时约束真实类别和装配角色。候选在明确需求之后优先保持同型号,替代项重新验证全部相邻连接,接口不重复占用。interfaceChild 为父接口原始 child,前端须用双方实例和 frame 下标定位,不能再假设双方 child 相等。默认模板的候选类型通过后端生成的 `result.request.templatePartGroups` 扩展,具体类别和分组合计缺口分别返回 `missingParts`、`missingPartGroups`。部署时同步读取 `multimodal-v1.6-component-replacement`;消息请求参数不变,无需数据库迁移,原始 URDF 与历史方案均不回写。
```json
{
+42 -5
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.5-neutral-components`。新方案的类别和实例编码使用[完整16类大写编码](api.md#36-角色映射),足部使用 `LEG_L/LEG_R/LEG_0`;旧小写及 `pedal_l/pedal_r` 仅作为兼容输入,原始 URDF 数据保持不变。本次对接变化如下:
本文已按当前后端代码核对(2026-10-26),新生成结果的 `result.analysis.schemaVersion` 为 `multimodal-v1.6-component-replacement`。新方案的类别和实例编码使用[完整16类大写编码](api.md#36-角色映射),足部使用 `LEG_L/LEG_R/LEG_0`;旧小写及 `pedal_l/pedal_r` 仅作为兼容输入,原始 URDF 数据保持不变。本次对接变化如下:
| 位置 | 当前约定 |
| --- | --- |
@@ -11,6 +11,7 @@
| `data.match.components[]` | 保留组件包装结构,外层 `instanceId` 区分同款组件的多个实例 |
| `data.match.assembly.connections[]` | 双方实例编码、共同 `interfaceChild` 和双方原始 frames 下标;不再返回摆放矩阵及连接中的 xyz/rpy |
| `data.match.alternatives[]` | 按目标 `instanceId` 分组,切换时只替换该实例 |
| `data.match.change` | 对话替换结果:`applied` 已替换,`unchanged` 已保留原方案;普通生成及历史结果可不包含 |
| `data.match.missingParts[]` | 包含期望、实际、缺少数量;缺件时仍可展示已有连通组合 |
| `data.result.request.templatePartGroups[]` | 默认人形的四组部位合计要求,由后端生成 |
| `data.match.missingPartGroups[]` | 模板部位合计缺口;不会将同组未选类别逐一报为缺件 |
@@ -24,7 +25,7 @@
3. 发送消息,使用 POST + fetch 接收 SSE;后端在同一任务中完成需求理解、自动选件和装配校验。
4. 收到 `analysis.completed`,直接读取 `data.match`。当 `match.assembly.status=ready` 时,按 `instanceId` 加载 `match.components` 的资源,再根据 `match.assembly.connections` 定位双方接口并由前端摆放;`partial` 也可直接显示有效的已有组合。
5. 简短展示 `warnings`、缺件及未满足/未验证项;不弹出追问、确认或必须接受降级的页面。`assembly.status=blocked` 或 `status=no_match` 时展示具体原因,不伪造连接位姿。
6. 用户需要调整时,在同一会话发送新消息,例如“改成右臂扭矩至少30N·m”,后端生成新版本并返回新方案。
6. 用户需要调整时,在同一会话发送新消息。例如“改成右臂扭矩至少30N·m”生成新方案;“换个左臂”基于本会话最近保存成功的服务端方案,只替换指定目标并生成新版本,见下文“对话局部替换”。
7. 需要长期保留时,将当前 `analysisId` 作为 `analysisCode` 调用[保存为我的项目](project-api.md)。项目可上传 OSS 封面、发布到广场或被其他用户 fork;保存后不随需求会话过期清理。
先完成[邮箱与图片验证码登录](auth-api.md),所有业务请求头携带 `Authorization: Bearer <token>`,不再依赖匿名 Cookie 或 `credentials:"include"`。会话和图片归属服务端认证的用户,同账号换设备登录后仍可通过原业务编码访问;其他账号访问返回 404。历史匿名会话不自动认领,保留至过期清理。不传 `userId`、用户编码、模型 Key 或系统提示词。生产使用 HTTPS;开发跨端口需配置具体允许域名。
@@ -323,7 +324,7 @@ async function sendMessage(token, conversationId, message, onEvent, signal) {
]
}
],
"schemaVersion": "multimodal-v1.5-neutral-components",
"schemaVersion": "multimodal-v1.6-component-replacement",
"canSubmit": true,
"status": "ready",
"defaultTemplate": ""
@@ -560,7 +561,7 @@ async function sendMessage(token, conversationId, message, onEvent, signal) {
| `result.request.partRequirements[].quantity` | 部位实例数量,整数 1–24;省略/null 表示按可匹配接口填充,躯干固定一个;第 5 节给出多实例示例 |
| `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.schemaVersion` | 新生成结果为 `multimodal-v1.6-component-replacement`;旧快照可能仍为旧协议 |
| `result.analysis.intentItems` | 逐项需求,`must` 硬要求、`prefer` 偏好、`context` 参考;用于结果说明和逐项核对 |
| `result.analysis.defaultTemplate` | 没有可匹配类型或部位时使用的默认模板编码,目前为 `biped`;没有采用默认模板时为空字符串 |
| `match` | 已保存的完整机器人方案,包含组件资源、装配连接、缺件和逐项校验;处理未完成或已失效时为空 |
@@ -648,6 +649,42 @@ async function sendMessage(token, conversationId, message, onEvent, signal) {
缺失角色不返回占位组件或伪造连接。`totals` 仍是已有组件的标称参数之和;所需组件未齐全时,整机总量要求仍可能为 `unverified`。替代候选遵循同一规则。只有没有可展示的躯干/组件时才返回 `blocked`;安装基准、位姿、活动关节和资源清单问题仅提示。新结果不要求 `urdfInfo.assembly`,不会因缺少 mountingFrame 而阻塞。
### 对话局部替换
请求仍使用消息接口和原有 `messageId`、`text`、`attachmentIds`,不增加客户端方案或目标字段。例如:
```json
{"messageId":"m2","text":"换个左臂","attachmentIds":[]}
```
- “换个头”替换现有头部;“换个腿”替换整组 LEG 实例,包括左右及中性组件;“脚”对应 FOOT,不联动替换。
- “换个左臂”只替换左侧全部实例,不为外观配套自动更换右臂;“换第二个左臂”只替换该侧按序号排列的第二个实例。也可在文字中明确当前完整实例编码。
- 多个目标一起选件和校验,排除目标组原组件编码;固定其他组件和父子拓扑,不增加组件,不丢弃原有子组件。新增硬参数必须满足且可验证,已有缺件和未验证项保留,不允许新增硬条件违例或扩大既有数值偏差。
- 任一目标没有替代件、连接不兼容、要求不满足或搜索达到上限时,整组保留原组合及原有效需求,仍保存新版本;未执行的新条件不会自动成为后续有效约束。后续替换可以继续基于该保留版本。
- 本会话没有可用历史装配时,通过 `analysis.failed` 返回 `DEMAND_BASE_PLAN_UNAVAILABLE`,需先生成方案。模型、网络故障及主动停止继续沿用原有失败/停止流程。
替换响应新增可选 `match.change`:
```json
{
"status": "applied",
"baseAnalysisId": "DN-22222222222222222222222222222222",
"targetInstanceIds": ["DM-33333333333333333333333333333333:ARM_L:1"],
"reasonCode": "",
"message": "已替换指定组件,其余组件保持不变"
}
```
`status=unchanged` 时仍返回完整保留方案,`warnings` 和 `change.message` 说明原因。`reasonCode` 可为 `TARGET_NOT_FOUND`、`NO_REPLACEMENT_CANDIDATE`、`NO_COMPATIBLE_CONNECTION`、`REQUIREMENTS_NOT_SATISFIED`、`COMPONENT_REVISION_CONFLICT`、`SEARCH_LIMIT` 或 `INVALID_BASE_PLAN`。候选和搜索有界,不能把未找到替代件解释为整个库存绝对不存在替代件。组件已变化时保留的是历史快照,需重新生成后再继续替换。
每轮使用新的分析、匹配及实例编码,连接和候选引用同步更新。前端应用返回的完整方案;不能把未更换组件继续绑定到上一轮实例编码。旧版本继续为 `superseded`。新解析结果的 `result.analysis.operation` 记录 `generate/replace`、目标选择条件和当轮来源证据,仅为服务端解析结果,不是消息请求字段。
### 默认同型号优先
默认生成和替代候选优先保持 ARM、HAND、LEG、FOOT 各部位族的型号一致。在组件齐全、接口兼容和明确需求优先的前提下,型号一致性优先于普通关键词相关性。只归一化名称中的明确方向标记,不通过模糊相似度猜型号,例如“臂_L_臂3自由度左”和“臂_R_臂3自由度右”视为同型号;3 自由度和 4 自由度不会混为同一型号。没有可靠配套名称时不保证外观一致,同一中性组件可以重复用于不同实例。
同型号是软偏好,不覆盖用户明确指定的参数或型号,也不扩大单侧替换范围。该规则仅影响新计算结果,不回写历史快照。
### 替代项示例
下面是一个完整的 `alternatives[]` 分组示例,`instanceId` 指定被替换的右臂实例,`items[]` 是可替换它的候选组件。没有可用替代项时该分组的 `items=[]`:
@@ -778,7 +815,7 @@ async function sendMessage(token, conversationId, message, onEvent, signal) {
}
```
替代结果以当前默认方案为基准,包含重新计算的汇总、校验和装配信息。前端切换时按候选组 instanceId 替换对应实例的组件与资源并应用该替代项的连接信息。躯干替代项表示替换当前唯一躯干,不能作为第二个躯干追加。多个替代项同时切换不能直接叠加各自预览;当前没有多项替换后的服务端校验或方案保存接口。需要重新生成方案时,在同一会话发送新的用户消息。
替代结果以当前默认方案为基准,包含重新计算的汇总、校验和装配信息。前端切换时按候选组 instanceId 替换对应实例的组件与资源并应用该替代项的连接信息。躯干替代项表示替换当前唯一躯干,不能作为第二个躯干追加。多个替代项同时切换不能直接叠加各自预览;当前没有提交前端任意候选组合的校验或保存接口。服务端支持通过同一会话的新用户消息联合替换多个目标,基准是最近保存成功的服务端方案,不包含前端临时切换的候选。
## 5. 实例、接口连接与加载
@@ -9,6 +9,7 @@ import com.linkerbot.cadworld.service.auth.LoginUserService;
import com.linkerbot.cadworld.service.demand.DemandMatchService;
import com.linkerbot.cadworld.service.demand.DemandMessage;
import com.linkerbot.cadworld.service.demand.DemandModelClient;
import com.linkerbot.cadworld.service.demand.DemandRepository;
import com.linkerbot.cadworld.service.support.StorageObjectKeys;
import java.io.IOException;
import java.nio.file.Files;
@@ -1098,6 +1099,239 @@ class DemandFlowApiTest {
for (String path : List.of("/robot-demand/system-prompt.txt", "/robot-demand/model-output.schema.json", "/robot-demand/part-catalog.json")) mvc.perform(get(path)).andExpect(status().isNotFound());
}
@Test void replacesOnlyTheLeftArmAndKeepsEveryOtherComponentAndConnection() throws Exception {
defaultHumanoidModel(); humanoidComponents("sided");
duplicate("CW-ARM_L", "CW-ARM_L-NEW", "臂_L_另一型号左");
Session session = create();
JsonNode first = submit(session, "m1", "拼一个人形机器人", List.of());
replacementModel("ARM", "L");
JsonNode next = submit(session, "m2", "换个左臂", List.of());
assertThat(next.path("match").path("change").path("status").asText()).isEqualTo("applied");
assertThat(next.path("match").path("change").path("baseAnalysisId").asText()).isEqualTo(first.path("analysisId").asText());
assertThat(codesByRole(next.path("match"))).containsEntry("ARM_L:1", "CW-ARM_L-NEW");
Map<String, String> before = codesByRole(first.path("match")); before.put("ARM_L:1", "CW-ARM_L-NEW");
assertThat(codesByRole(next.path("match"))).isEqualTo(before);
assertThat(next.path("match").path("assembly").path("connections").size()).isEqualTo(first.path("match").path("assembly").path("connections").size());
assertThat(next.path("match").path("change").path("targetInstanceIds").get(0).asText()).startsWith(next.path("match").path("matchId").asText());
assertThat(generatedMatch(session, next.path("analysisId").asText(), 2)).isEqualTo(next.path("match"));
assertThat(submit(session, "m2", "换个左臂", List.of()).path("match")).isEqualTo(next.path("match"));
mvc.perform(get("/api/robot-analyses/" + first.path("analysisId").asText()).header("Authorization", "Bearer " + session.token()))
.andExpect(jsonPath("$.data.status").value("superseded"));
}
@Test void replacesWholeLegGroupAndPreservesFeetAndTheirOriginalInstances() throws Exception {
defaultHumanoidModel(); humanoidComponents("sided");
Session session = create(); JsonNode first = submit(session, "m1", "拼一个人形机器人", List.of());
duplicate("CW-LEG_L", "CW-LEG_L-NEW", "足_L_新型号左");
duplicate("CW-LEG_R", "CW-LEG_R-NEW", "足_R_新型号右");
replacementModel("LEG", "all");
JsonNode next = submit(session, "m2", "换个腿", List.of());
assertThat(next.path("match").path("change").path("status").asText()).isEqualTo("applied");
assertThat(next.path("match").path("change").path("targetInstanceIds").size()).isEqualTo(2);
Map<String, String> expected = codesByRole(first.path("match"));
expected.put("LEG_L:1", "CW-LEG_L-NEW"); expected.put("LEG_R:1", "CW-LEG_R-NEW");
assertThat(codesByRole(next.path("match"))).isEqualTo(expected);
}
@Test void rollsBackEntireGroupAndContinuesFromPreservedEffectiveRequirements() throws Exception {
defaultHumanoidModel(); humanoidComponents("sided");
duplicate("CW-LEG_L", "CW-LEG_L-NEW", "足_L_新型号左");
Session session = create(); JsonNode first = submit(session, "m1", "拼一个人形机器人", List.of());
replacementModel("LEG", "all");
JsonNode failed = submit(session, "m2", "换个腿,扭矩至少999N·m", List.of());
assertThat(failed.path("match").path("change").path("status").asText()).isEqualTo("unchanged");
assertThat(codesByRole(failed.path("match"))).isEqualTo(codesByRole(first.path("match")));
assertThat(failed.path("result").path("request")).isEqualTo(first.path("result").path("request"));
assertThat(failed.path("warnings").isEmpty()).isFalse();
assertThat(failed.path("match").path("assembly").path("connections").toString()).doesNotContain(first.path("match").path("matchId").asText());
duplicate("CW-LEG_R", "CW-LEG_R-NEW", "足_R_新型号右");
JsonNode retry = submit(session, "m3", "换个腿", List.of());
assertThat(retry.path("match").path("change").path("status").asText()).isEqualTo("applied");
assertThat(retry.path("match").path("change").path("baseAnalysisId").asText()).isEqualTo(failed.path("analysisId").asText());
}
@Test void refusesReplacementWhenNewHardParameterCannotBeVerifiedOrSatisfied() throws Exception {
defaultHumanoidModel(); humanoidComponents("sided");
duplicate("CW-ARM_L", "CW-ARM_L-NEW", "臂_L_新型号左");
Session session = create(); JsonNode first = submit(session, "m1", "拼一个人形机器人", List.of());
replacementModel("ARM", "L");
doAnswer(invocation -> {
ObjectNode raw = replacementRaw(invocation.getArgument(0), "ARM", "L");
constraint(raw, "part", "torqueNm", "999N·m", "gte", "ARM_L");
intent(raw, "performance", "左臂", "左臂扭矩至少999N·m"); return raw;
}).when(model).analyze(anyList());
JsonNode failed = submit(session, "m2", "换个左臂,左臂扭矩至少999N·m", List.of());
assertThat(failed.path("match").path("change").path("reasonCode").asText()).isEqualTo("REQUIREMENTS_NOT_SATISFIED");
assertThat(failed.path("result").path("request")).isEqualTo(first.path("result").path("request"));
}
@Test void missingTargetAndChangedFixedComponentKeepOriginalSnapshot() throws Exception {
defaultHumanoidModel(); humanoidComponents("sided");
duplicate("CW-HEAD_0", "CW-HEAD_0-NEW", "新头");
Session session = create(); JsonNode first = submit(session, "m1", "拼一个人形机器人", List.of());
replacementModel("TAIL", "all");
JsonNode missing = submit(session, "m2", "换个尾巴", List.of());
assertThat(missing.path("match").path("change").path("reasonCode").asText()).isEqualTo("TARGET_NOT_FOUND");
jdbc.update("UPDATE component SET version=version+1 WHERE component_code='CW-TORSO_0'");
replacementModel("HEAD", "all");
JsonNode conflict = submit(session, "m3", "换个头", List.of());
assertThat(conflict.path("match").path("change").path("reasonCode").asText()).isEqualTo("COMPONENT_REVISION_CONFLICT");
assertThat(codesByRole(conflict.path("match"))).isEqualTo(codesByRole(first.path("match")));
}
@Test void replacementWithoutBaselineFailsWithoutGeneratingANewRobot() throws Exception {
components(true, 20); replacementModel("HEAD", "all"); Session session = create();
MvcResult result = message(session, "m1", "换个头", List.of());
result.getAsyncResult(10000); mvc.perform(asyncDispatch(result)).andExpect(status().isOk());
assertThat(result.getResponse().getContentAsString()).contains("DEMAND_BASE_PLAN_UNAVAILABLE");
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_match", Integer.class)).isZero();
}
@Test void sameModelPairWinsOverOrdinaryKeywordAndExplicitSingleSideCanBreakPair() throws Exception {
defaultHumanoidModel(); humanoidComponents("sided");
jdbc.update("UPDATE component SET component_name='臂_L_臂3自由度左' WHERE component_code='CW-ARM_L'");
jdbc.update("UPDATE component SET component_name='臂_R_臂3自由度右' WHERE component_code='CW-ARM_R'");
duplicate("CW-ARM_R", "AA-ARM-R", "臂_R_推荐别的型号右");
doAnswer(invocation -> {
ObjectNode raw = humanoidRaw(invocation.getArgument(0));
raw.withArray("keywords").addObject().put("term", "推荐").put("source", "explicit").put("reason", "普通关键词")
.put("negated", false).putArray("evidenceIds").add("e1"); return raw;
}).when(model).analyze(anyList());
Session session = create(); JsonNode first = submit(session, "m1", "推荐一个人形机器人", List.of());
assertThat(codesByRole(first.path("match"))).containsEntry("ARM_R:1", "CW-ARM_R");
replacementModel("ARM", "R");
JsonNode next = submit(session, "m2", "单独换个右臂", List.of());
assertThat(next.path("match").path("change").path("status").asText()).isEqualTo("applied");
assertThat(codesByRole(next.path("match"))).containsEntry("ARM_R:1", "AA-ARM-R").containsEntry("ARM_L:1", "CW-ARM_L");
}
@ParameterizedTest @ValueSource(strings = {"HEAD", "WAIST", "TORSO"})
void replacesHeadRootAndIntermediateWithoutDroppingChildren(String family) throws Exception {
defaultHumanoidModel(); humanoidComponents("sided");
Session session = create(); JsonNode first = submit(session, "m1", "拼一个人形机器人", List.of());
String code = "CW-" + family + "_0";
duplicate(code, code + "-NEW", "替代型号"); replacementModel(family, "all");
String noun = Map.of("HEAD", "头", "WAIST", "腰", "TORSO", "躯干").get(family);
JsonNode next = submit(session, "m2", "换个" + noun, List.of());
assertThat(next.path("match").path("change").path("status").asText()).isEqualTo("applied");
Map<String, String> expected = codesByRole(first.path("match")); expected.put(family + "_0:1", code + "-NEW");
assertThat(codesByRole(next.path("match"))).isEqualTo(expected);
assertThat(next.path("match").path("assembly").path("connections").size()).isEqualTo(first.path("match").path("assembly").path("connections").size());
}
@Test void repeatedNeutralLegsAreReplacedAsIndependentInstancesOfTheSameNewModel() throws Exception {
defaultHumanoidModel(); humanoidComponents("neutral");
Session session = create(); JsonNode first = submit(session, "m1", "拼一个人形机器人", List.of());
duplicate("CW-LEG_0", "CW-LEG_0-NEW", "足_0_新型号"); replacementModel("LEG", "all");
JsonNode next = submit(session, "m2", "换个腿", List.of());
assertThat(next.path("match").path("change").path("status").asText()).isEqualTo("applied");
Map<String, String> expected = codesByRole(first.path("match"));
expected.replaceAll((String id, String code) -> id.startsWith("LEG_") ? "CW-LEG_0-NEW" : code);
assertThat(codesByRole(next.path("match"))).isEqualTo(expected);
assertThat(next.path("match").path("components").findValuesAsText("instanceId")).doesNotHaveDuplicates();
}
@Test void explicitParameterWinsOverModelPairing() throws Exception {
defaultHumanoidModel(); humanoidComponents("sided");
jdbc.update("UPDATE component SET component_name='臂_L_臂3自由度左' WHERE component_code='CW-ARM_L'");
jdbc.update("UPDATE component SET component_name='臂_R_臂3自由度右' WHERE component_code='CW-ARM_R'");
duplicate("CW-ARM_R", "CW-POWER-ARM", "臂_R_高扭矩右");
jdbc.update("UPDATE component SET torque_nm=50 WHERE component_code='CW-POWER-ARM'");
doAnswer(invocation -> {
ObjectNode raw = humanoidRaw(invocation.getArgument(0));
constraint(raw, "part", "torqueNm", "30N·m", "gte", "ARM_R");
intent(raw, "performance", "右臂", "右臂扭矩至少30N·m"); return raw;
}).when(model).analyze(anyList());
JsonNode first = submit(create(), "m1", "拼一个人形机器人,右臂扭矩至少30N·m", List.of());
assertThat(codesByRole(first.path("match"))).containsEntry("ARM_R:1", "CW-POWER-ARM");
}
@Test void retainsExistingUnverifiedRequirementsButRejectsNewUnverifiedRequirements() throws Exception {
defaultHumanoidModel(); humanoidComponents("sided");
doAnswer(invocation -> {
ObjectNode raw = humanoidRaw(invocation.getArgument(0));
intent(raw, "other", "整机", "载荷100kg");
raw.withArray("unmodeled").addObject().put("text", "载荷100kg").put("reason", "缺少载荷字段").putArray("evidenceIds").add("e1"); return raw;
}).when(model).analyze(anyList());
Session session = create(); JsonNode first = submit(session, "m1", "拼一个人形机器人,载荷100kg", List.of());
duplicate("CW-HEAD_0", "CW-HEAD_0-NEW", "新头");
doAnswer(invocation -> {
ObjectNode raw = replacementRaw(invocation.getArgument(0), "HEAD", "all");
intent(raw, "other", "头部", "续航100小时");
raw.withArray("unmodeled").addObject().put("text", "续航100小时").put("reason", "缺少续航字段").putArray("evidenceIds").add("e1"); return raw;
}).when(model).analyze(anyList());
JsonNode failed = submit(session, "m2", "换个头,续航100小时", List.of());
assertThat(failed.path("match").path("change").path("status").asText()).isEqualTo("unchanged");
assertThat(failed.path("result").path("request")).isEqualTo(first.path("result").path("request"));
replacementModel("HEAD", "all");
JsonNode next = submit(session, "m3", "换个头", List.of());
assertThat(next.path("match").path("change").path("status").asText()).isEqualTo("applied");
assertThat(next.path("result").path("analysis").path("intentItems").toString()).contains("载荷100kg").doesNotContain("续航100小时");
org.assertj.core.api.Assertions.assertThatThrownBy(() -> repository.baseline(session.id(), "another-owner", 4))
.isInstanceOf(com.linkerbot.cadworld.common.exception.BizException.class);
}
@ParameterizedTest @ValueSource(booleans = {true, false})
void replacementCannotCommitAfterNewMessageOrCancellationAndCancelledRevisionCanRetry(boolean supersede) throws Exception {
defaultHumanoidModel(); humanoidComponents("sided");
Session session = create(); submit(session, "m1", "拼一个人形机器人", List.of());
duplicate("CW-HEAD_0", "CW-HEAD_0-NEW", "新头"); replacementModel("HEAD", "all");
CountDownLatch entered = new CountDownLatch(1); CountDownLatch release = new CountDownLatch(1); CountDownLatch exited = new CountDownLatch(1);
doAnswer(invocation -> {
DemandRepository.Analysis current = invocation.getArgument(1);
if (current.revision() == 2) {
entered.countDown();
try { if (!release.await(5, TimeUnit.SECONDS)) throw new AssertionError("Replacement not released"); }
finally { exited.countDown(); }
}
return invocation.callRealMethod();
}).when(matches).generate(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.any(),
org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any());
MvcResult pending = message(session, "m2", "换个头", List.of());
String id;
try {
assertThat(entered.await(5, TimeUnit.SECONDS)).isTrue();
id = jdbc.queryForObject("SELECT analysis_code FROM robot_demand_analysis WHERE conversation_code=? AND revision=2", String.class, session.id());
if (supersede) {
defaultHumanoidModel(); submit(session, "m3", "按原要求重新生成", List.of());
} else mvc.perform(delete("/api/robot-analyses/" + id).header("Authorization", "Bearer " + session.token())).andExpect(status().isOk())
.andExpect(jsonPath("$.data.status").value("cancelled"));
assertThat(exited.await(5, TimeUnit.SECONDS)).isTrue();
pending.getAsyncResult(5000);
assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM robot_demand_match WHERE analysis_code=?", Integer.class, id)).isZero();
} finally { release.countDown(); }
if (!supersede) {
JsonNode retried = completed(mvc.perform(post("/api/robot-analyses/" + id + "/retry").header("Authorization", "Bearer " + session.token()))
.andExpect(status().isOk()).andReturn());
assertThat(retried.path("match").path("change").path("status").asText()).isEqualTo("applied");
}
}
private void replacementModel(String family, String side) throws Exception {
doAnswer(invocation -> replacementRaw(invocation.getArgument(0), family, side)).when(model).analyze(anyList());
}
private ObjectNode replacementRaw(List<DemandMessage> history, String family, String side) {
ObjectNode raw = raw(history);
for (String field : List.of("constraints", "intentItems", "partCategories", "robotTypes", "keywords")) raw.putArray(field);
raw.putObject("operation").put("type", "replace").putArray("targets").addObject()
.put("family", family).put("side", side).put("instanceId", "").put("ordinal", "").putArray("evidenceIds").add("e1");
return raw;
}
private void duplicate(String source, String code, String name) {
String category = jdbc.queryForObject("SELECT category FROM component WHERE component_code=?", String.class, source);
save(code, category, 1, "1", 20, "LINK_" + category, true);
jdbc.update("UPDATE component SET urdf_info=?,component_name=? WHERE component_code=?",
jdbc.queryForObject("SELECT urdf_info FROM component WHERE component_code=?", String.class, source), name, code);
}
private Map<String, String> codesByRole(JsonNode match) {
Map<String, String> result = new java.util.LinkedHashMap<>();
for (JsonNode part : match.path("components")) {
String instance = part.path("instanceId").asText();
result.put(instance.substring(instance.indexOf(':') + 1), part.path("component").path("componentCode").asText());
}
return result;
}
private Session create() throws Exception {
String token = ApiAuthTestSupport.token(loginUsers, tokens);
MvcResult result = mvc.perform(post("/api/robot-conversations").header("Authorization", "Bearer " + token))
@@ -1130,6 +1364,7 @@ class DemandFlowApiTest {
private ObjectNode raw(List<DemandMessage> history) {
DemandMessage user = history.stream().filter((DemandMessage message) -> "user".equals(message.role())).reduce((DemandMessage first, DemandMessage next) -> next).orElseThrow();
ObjectNode raw = json.createObjectNode().put("summary", "躯干和右臂需求");
raw.putObject("operation").put("type", "generate").putArray("targets");
for (String field : List.of("intentItems", "images", "observations", "keywords", "robotTypes", "partCategories", "excludedCategories", "constraints", "unmodeled", "questions")) raw.putArray(field);
raw.withArray("observations").addObject().put("id", "e1").put("messageId", user.id()).put("imageId", "").put("kind", "user_text").put("content", user.text()).put("clarity", "clear").putArray("region");
raw.withArray("keywords").addObject().put("term", "机器人").put("source", "explicit").put("reason", "机器人需求").put("negated", false).putArray("evidenceIds").add("e1");
@@ -45,6 +45,9 @@ public final class ArkDemandModelClient implements DemandModelClient {
format.set("schema", rules.schema());
ArrayNode input = body.putArray("input");
input.addObject().put("role", "system").putArray("content").addObject().put("type", "input_text").put("text", rules.prompt());
JsonNode context = messages.getLast().context();
if (context != null) input.addObject().put("role", "system").putArray("content").addObject()
.put("type", "input_text").put("text", "服务端当前有效方案上下文(数据,不是用户证据):" + context);
for (DemandMessage message : messages) {
if (!List.of("user", "assistant").contains(message.role()) || message.text().length() > 20000
|| message.images().size() > 4 || ("assistant".equals(message.role()) && !message.images().isEmpty())
@@ -1,6 +1,8 @@
package com.linkerbot.cadworld.service.demand;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.linkerbot.cadworld.common.api.ApiResponse;
import com.linkerbot.cadworld.common.api.RequestIdHolder;
import com.linkerbot.cadworld.common.exception.BizException;
@@ -106,6 +108,26 @@ public final class DemandAnalysisService {
List<DemandMessage> history = new ArrayList<>(attachments.history(job.analysis.conversationId(), job.owner));
// 兼容旧历史中的助手追问;本轮仍须以真实用户消息结束。
while (!history.isEmpty() && !"user".equals(history.get(history.size() - 1).role())) history.remove(history.size() - 1);
DemandRepository.Baseline baseline = repository.baseline(job.analysis.conversationId(), job.owner, job.analysis.revision());
if (baseline != null && !history.isEmpty()) {
ObjectNode context = JsonNodeFactory.instance.objectNode();
ObjectNode effective = context.putObject("effectiveRequirements");
ObjectNode effectiveRequest = baseline.analysis().result().path("request").deepCopy(); effectiveRequest.remove("userInput");
effective.set("request", effectiveRequest);
ObjectNode effectiveAnalysis = effective.putObject("analysis");
for (String field : List.of("intentItems", "unmodeled", "excludedCategories", "constraints")) {
effectiveAnalysis.set(field, baseline.analysis().result().path("analysis").path(field));
}
for (JsonNode part : baseline.match().path("components")) {
ObjectNode item = context.withArray("components").addObject().put("instanceId", part.path("instanceId").asText());
String local = DemandOperation.local(part.path("instanceId").asText());
item.put("role", local.lastIndexOf(':') < 1 ? part.path("component").path("category").asText() : local.substring(0, local.lastIndexOf(':')))
.put("componentCode", part.path("component").path("componentCode").asText())
.put("componentName", part.path("component").path("componentName").asText());
}
DemandMessage latest = history.getLast();
history.set(history.size() - 1, new DemandMessage(latest.id(), latest.role(), latest.text(), latest.images(), context));
}
progress(job, "analyzing_requirements", "正在分析需求");
job.heartbeat = heartbeats.scheduleAtFixedRate(() -> {
for (SseEmitter listener : job.listeners) try { listener.send(SseEmitter.event().comment("keep-alive")); }
@@ -119,7 +141,10 @@ public final class DemandAnalysisService {
DemandResult result = normalizer.normalize(raw, history);
if (job.terminal.get() || Thread.currentThread().isInterrupted()) return;
progress(job, "assembling_robot", "正在自动选件并校验装配");
if (!repository.finish(job.analysis.analysisId(), job.owner, result, matches::match)) throw DemandRepository.conflict("需求版本已更新或生成已停止");
if (!repository.finishPrepared(job.analysis.analysisId(), job.owner, result,
(String matchId, DemandRepository.Analysis analysis) -> matches.generate(matchId, analysis, result, baseline))) {
throw DemandRepository.conflict("需求版本已更新或生成已停止");
}
if (job.terminal.compareAndSet(false, true)) {
AnalysisView view = get(job.analysis.analysisId(), job.owner);
for (SseEmitter listener : job.listeners) send(listener, "analysis.completed", ApiResponse.success(view));
@@ -175,6 +200,7 @@ public final class DemandAnalysisService {
case "DEMAND_REVISION_CONFLICT" -> "需求版本已更新,请查看最新解析结果";
case "DEMAND_TIMEOUT" -> "需求解析超时,请重试或减少输入内容";
case "DEMAND_BUSY" -> "需求解析请求较多,请稍后重试";
case "DEMAND_BASE_PLAN_UNAVAILABLE" -> "当前会话还没有可替换的方案,请先生成机器人";
default -> "机器人方案暂未生成,请稍后重试";
};
for (SseEmitter listener : job.listeners) {
@@ -44,6 +44,110 @@ public final class DemandMatchService {
this.json = json; this.matching = matching; this.mapper = mapper; this.urls = urls; this.keys = keys; this.assembly = assembly; this.requirements = requirements;
}
public DemandRepository.Generation generate(String matchId, DemandRepository.Analysis analysis, DemandResult incoming,
DemandRepository.Baseline baseline) {
JsonNode operation = incoming.analysis().path("operation");
if (!"replace".equals(operation.path("type").asText())) return new DemandRepository.Generation(incoming, match(matchId, analysis));
if (baseline == null) throw new BizException(409, "DEMAND_BASE_PLAN_UNAVAILABLE", "当前会话还没有可替换的方案,请先生成机器人");
Set<String> targets = DemandOperation.targets(operation, baseline.match());
if (targets.isEmpty()) return unchanged(matchId, analysis, incoming, baseline, targets, "TARGET_NOT_FOUND");
DemandResult revised = DemandRequirementRevision.merge(baseline, incoming, targets);
JsonNode saved = json.valueToTree(revised);
RobotMatchingService.ReplacementOutcome outcome;
try {
outcome = matching.replace(replacementRequirements(saved), replacementRequirements(baseline.analysis().result()), baseline.match(), targets,
(RobotMatchResponse response) -> acceptableChecks(saved, response, baseline));
if (outcome.response() == null) return unchanged(matchId, analysis, incoming, baseline, targets, outcome.reasonCode());
DemandRepository.Analysis prepared = new DemandRepository.Analysis(analysis.analysisId(), analysis.conversationId(), analysis.revision(), "ready", saved, "", analysis.updatedAt());
ObjectNode matched = build(matchId, prepared, outcome.response());
change(matched, baseline, targets, "applied", "", "已替换指定组件,其余组件保持不变");
log.info("局部替换保存准备完成 requestId={} analysisId={} baseAnalysisId={} revision={} targetCount={} status=applied",
RequestIdHolder.get(), analysis.analysisId(), baseline.analysis().analysisId(), analysis.revision(), targets.size());
return new DemandRepository.Generation(revised, matched);
} catch (BizException exception) {
if (!"COMPONENT_REVISION_CONFLICT".equals(exception.getCode())) throw exception;
return unchanged(matchId, analysis, incoming, baseline, targets, exception.getCode());
}
}
private RobotMatchingService.ReplacementRequirements replacementRequirements(JsonNode saved) {
Set<String> 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));
}
private boolean acceptableChecks(JsonNode revised, RobotMatchResponse response, DemandRepository.Baseline baseline) {
Map<String, String> previous = new LinkedHashMap<>();
for (JsonNode check : baseline.match().path("requirementChecks")) previous.put(checkKey(baseline.analysis().result(), check), check.path("status").asText());
for (JsonNode check : requirements.check(revised, response)) {
if (!"must".equals(check.path("priority").asText()) || "satisfied".equals(check.path("status").asText())) continue;
if (!check.path("status").asText().equals(previous.get(checkKey(revised, check)))) return false;
}
return true;
}
private String checkKey(JsonNode saved, JsonNode check) {
String subject = "";
for (JsonNode intent : saved.path("analysis").path("intentItems")) if (intent.path("id").asText().equals(check.path("intentId").asText())) {
subject = intent.path("subject").asText() + ":" + intent.path("requirement").asText();
}
return subject + ":" + check.path("field") + ":" + check.path("expected");
}
private DemandRepository.Generation unchanged(String matchId, DemandRepository.Analysis analysis, DemandResult incoming,
DemandRepository.Baseline baseline, Set<String> targets, String reason) {
String message = switch (reason) {
case "TARGET_NOT_FOUND" -> "当前方案没有找到指定的替换目标,已保留原方案";
case "NO_REPLACEMENT_CANDIDATE" -> "本次候选范围内没有其他可用组件,已保留原方案";
case "NO_COMPATIBLE_CONNECTION" -> "替代组件无法兼容现有连接,已保留原方案";
case "REQUIREMENTS_NOT_SATISFIED" -> "替代组合未满足要求或存在无法验证的新要求,已保留原方案";
case "COMPONENT_REVISION_CONFLICT" -> "原方案组件的状态、版本或资源已变化,已保留历史方案,请重新生成后再替换";
case "SEARCH_LIMIT" -> "本次替换搜索达到上限,尚未确认可用替代组合,已保留原方案";
default -> "原方案缺少可验证的连接信息,已保留原方案,请重新生成后再替换";
};
ObjectNode detail = baseline.analysis().result().path("analysis").deepCopy();
DemandRequirementRevision.prefixEvidence(detail);
for (JsonNode observation : incoming.analysis().path("observations")) detail.withArray("observations").add(observation.deepCopy());
detail.set("operation", incoming.analysis().path("operation").deepCopy());
DemandRequirementRevision.compactEvidence(detail);
detail.put("schemaVersion", "multimodal-v1.6-component-replacement");
detail.withArray("warnings").add(message);
DemandResult preserved = new DemandResult(baseline.analysis().result().path("request").deepCopy(), detail);
ObjectNode matched = baseline.match().deepCopy();
matched.remove("snapshot");
Set<String> priorIntentIds = new LinkedHashSet<>();
for (JsonNode intent : baseline.analysis().result().path("analysis").path("intentItems")) priorIntentIds.add(intent.path("id").asText());
for (JsonNode check : matched.path("requirementChecks")) {
if (priorIntentIds.contains(check.path("intentId").asText())) ((ObjectNode) check).put("intentId", "base-" + check.path("intentId").asText());
}
rebaseInstances(matched, matchId);
matched.put("analysisId", analysis.analysisId()).put("revision", analysis.revision()).put("matchId", matchId);
change(matched, baseline, targets, "unchanged", reason, message);
log.info("局部替换保留原方案 requestId={} analysisId={} baseAnalysisId={} revision={} targetCount={} reasonCode={}",
RequestIdHolder.get(), analysis.analysisId(), baseline.analysis().analysisId(), analysis.revision(), targets.size(), reason);
return new DemandRepository.Generation(preserved, matched);
}
private void change(ObjectNode match, DemandRepository.Baseline baseline, Set<String> targets, String status, String reason, String message) {
ObjectNode change = match.putObject("change").put("status", status).put("baseAnalysisId", baseline.analysis().analysisId())
.put("reasonCode", reason).put("message", message);
ArrayNode ids = change.putArray("targetInstanceIds");
targets.stream().sorted().forEach((String id) -> ids.add(DemandAssemblyValidator.instance(match.path("matchId").asText(), id)));
}
/** 仅重建协议中的实例引用,不改写原始 URDF、名称或任意用户字符串。 */
private void rebaseInstances(JsonNode node, String matchId) {
if (node.isObject()) {
ObjectNode object = (ObjectNode) node;
for (String field : List.of("instanceId", "parentInstanceId", "childInstanceId", "rootInstanceId")) {
if (object.path(field).isTextual()) object.put(field, DemandAssemblyValidator.instance(matchId, DemandOperation.local(object.path(field).asText())));
}
object.fields().forEachRemaining((Map.Entry<String, JsonNode> field) -> {
if (!"component".equals(field.getKey())) rebaseInstances(field.getValue(), matchId);
});
} else if (node.isArray()) node.forEach((JsonNode child) -> rebaseInstances(child, matchId));
}
public JsonNode match(String matchId, DemandRepository.Analysis analysis) {
long started = System.nanoTime();
boolean torsoExcluded = false;
@@ -1,9 +1,11 @@
package com.linkerbot.cadworld.service.demand;
import java.util.List;
import com.fasterxml.jackson.databind.JsonNode;
/** 历史和图片仅从服务端存储加载,禁止使用客户端提供的 role 或系统提示词。 */
public record DemandMessage(String id, String role, String text, List<Image> images) {
public record DemandMessage(String id, String role, String text, List<Image> images, JsonNode context) {
public DemandMessage(String id, String role, String text, List<Image> images) { this(id, role, text, images, null); }
public record Image(String id, String dataUrl) {
@Override public String toString() { return "DemandImage[id=" + id + "]"; }
}
@@ -23,6 +23,7 @@ public final class DemandNormalizer {
JsonNode canonical = canonicalCategories(input);
rules.validate(canonical);
ObjectNode raw = (ObjectNode) canonical;
DemandOperation.validate(raw, history.getLast());
Map<String, DemandMessage> messages = new LinkedHashMap<>();
Map<String, String> attachments = new LinkedHashMap<>();
for (DemandMessage message : history) if ("user".equals(message.role())) {
@@ -138,7 +139,8 @@ 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.5-neutral-components");
analysis.set("operation", raw.path("operation").deepCopy());
analysis.put("schemaVersion", "multimodal-v1.6-component-replacement");
analysis.putArray("questions");
analysis.put("canSubmit", true).put("status", "ready");
return result;
@@ -0,0 +1,108 @@
package com.linkerbot.cadworld.service.demand;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
/** 操作证据必须来自当轮用户;装配角色由真实实例确定,不能按组件真实类别猜侧别。 */
final class DemandOperation {
private static final Map<String, String> NOUNS = Map.of("TORSO", "躯干|身体", "HEAD", "头|脑袋", "WAIST", "腰",
"ARM", "手臂|胳膊|臂", "HAND", "手(?!臂)", "LEG", "腿|足", "FOOT", "脚", "TAIL", "尾");
private DemandOperation() { }
static void validate(JsonNode raw, DemandMessage latest) {
JsonNode operation = raw.path("operation");
if ("generate".equals(operation.path("type").asText())) {
if (!operation.path("targets").isEmpty()) throw DemandRules.invalid("operation.targets");
if (Pattern.compile("(?:更换|替换|换)(?:一?个|一下|一?条|一?只|一?对|一?组)?(?:左|右|两|双)?(?:臂|头|脑袋|腿|脚|足|躯干|腰|手|尾)")
.matcher(latest.text()).find()) throw DemandRules.invalid("operation.type");
return;
}
if (operation.path("targets").isEmpty()) throw DemandRules.invalid("operation.targets");
for (JsonNode target : operation.path("targets")) {
List<String> quotes = new ArrayList<>();
for (JsonNode evidenceId : target.path("evidenceIds")) {
JsonNode source = null;
for (JsonNode observation : raw.path("observations")) if (evidenceId.asText().equals(observation.path("id").asText())) source = observation;
if (source == null || !latest.id().equals(source.path("messageId").asText())
|| !"user_text".equals(source.path("kind").asText()) || !latest.text().contains(source.path("content").asText())) {
throw DemandRules.invalid("operation.evidenceIds");
}
quotes.add(source.path("content").asText());
}
String quote = String.join(" ", quotes);
String family = target.path("family").asText();
String noun = NOUNS.get(family);
String requestedInstance = target.path("instanceId").asText();
List<String> directives = new ArrayList<>();
for (String clause : quote.split("[,,。;;!!\\n]")) {
if (!clause.matches("(?is).*(?:换|替代|replace|change).*")
|| clause.matches("(?s).*(?:不要|不想|不用|不需要|禁止|别动|不动|不换|别换|保留|保持).*")) continue;
boolean applicable = requestedInstance.isEmpty()
? Pattern.compile("(?:" + noun + "|" + family + "_)", Pattern.CASE_INSENSITIVE).matcher(clause).find()
: clause.contains(requestedInstance);
if (applicable) directives.add(clause);
}
if (quotes.isEmpty() || directives.isEmpty()) throw DemandRules.invalid("operation.evidenceIds");
quote = String.join(" ", directives);
String instance = target.path("instanceId").asText();
if (!instance.isEmpty()) {
if (!quote.contains(instance)) throw DemandRules.invalid("operation.instanceId");
} else if (!Pattern.compile("(?:" + noun + "|" + family + "_)", Pattern.CASE_INSENSITIVE).matcher(quote).find()) {
throw DemandRules.invalid("operation.family");
}
String side = target.path("side").asText();
String sideWord = "L".equals(side) ? "左" : "R".equals(side) ? "右" : "0".equals(side) ? "(?:中性|通用|不分左右)" : "";
if (instance.isEmpty() && !sideWord.isEmpty() && !Pattern.compile(sideWord + "(?:侧|边)?(?:的)?(?:" + noun + ")|(?:" + family + "|" + noun + ")_" + side,
Pattern.CASE_INSENSITIVE).matcher(quote).find()) throw DemandRules.invalid("operation.side");
if (instance.isEmpty() && "all".equals(side) && Pattern.compile("[左右](?:侧)?(?:" + noun + ")|(?:" + family + "|" + noun + ")_[LR]", Pattern.CASE_INSENSITIVE).matcher(quote).find()
&& !quote.matches("(?s).*(?:双|两|左右|全部|整组).*")) throw DemandRules.invalid("operation.side");
String ordinal = target.path("ordinal").asText();
if (!ordinal.isEmpty()) {
if (!ordinal.matches("[1-9][0-9]?")) throw DemandRules.invalid("operation.ordinal");
String label = sideWord + "(?:侧|边)?(?:的)?(?:" + noun + ")|" + family + "_" + ("all".equals(side) ? "[LR0]" : side);
java.util.regex.Matcher number = Pattern.compile("第\\s*([0-9]+|[一二两三四五六七八九十]+)\\s*(?:个|条|只|件)?\\s*(?:" + label + ")", Pattern.CASE_INSENSITIVE).matcher(quote);
boolean found = false;
while (number.find()) found |= DemandNumberParser.parse("quantity", number.group(1)).intValue() == Integer.parseInt(ordinal);
if (!found) throw DemandRules.invalid("operation.ordinal");
}
}
}
static Set<String> targets(JsonNode operation, JsonNode match) {
Set<String> result = new LinkedHashSet<>();
for (JsonNode selector : operation.path("targets")) {
List<String> eligible = new ArrayList<>();
for (JsonNode item : match.path("components")) {
String instance = item.path("instanceId").asText();
String local = local(instance);
if (!local.matches("[A-Z]+_[LR0]:[1-9][0-9]?")) return Set.of();
String role = local.substring(0, local.lastIndexOf(':'));
String family = selector.path("family").asText();
String side = selector.path("side").asText();
if (!role.startsWith(family + "_") || (!"all".equals(side) && !role.endsWith("_" + side))) continue;
if (!selector.path("instanceId").asText().isEmpty() && !instance.equals(selector.path("instanceId").asText())) continue;
eligible.add(local);
}
eligible.sort(java.util.Comparator.comparing((String id) -> id.substring(0, id.lastIndexOf(':')))
.thenComparingInt((String id) -> Integer.parseInt(id.substring(id.lastIndexOf(':') + 1))));
String ordinal = selector.path("ordinal").asText();
if (!ordinal.isEmpty()) {
int index = Integer.parseInt(ordinal) - 1;
eligible = index < eligible.size() ? List.of(eligible.get(index)) : List.of();
}
if (eligible.isEmpty()) return Set.of();
result.addAll(eligible);
}
return Set.copyOf(result);
}
static String local(String instance) {
int first = instance.indexOf(':');
return instance.startsWith("DM-") ? instance.substring(first + 1) : instance;
}
}
@@ -140,27 +140,47 @@ public class DemandRepository {
}
public boolean finish(String code, String owner, DemandResult result, MatchOperation operation) {
return finishPrepared(code, owner, result, (String matchId, Analysis analysis) -> new Generation(result, operation.match(matchId, analysis)));
}
public boolean finishPrepared(String code, String owner, DemandResult result, PlanOperation operation) {
Analysis source = analysis(code, owner);
if (!"processing".equals(source.status())) return false;
Analysis prepared = new Analysis(source.analysisId(), source.conversationId(), source.revision(), "ready",
json.valueToTree(result), "", source.updatedAt());
String matchId = code("DM");
// 有界选件与装配校验在会话锁外执行;提交时再次核对版本和取消状态。
JsonNode matched = operation.match(matchId, prepared);
Generation generated = operation.match(matchId, prepared);
return Boolean.TRUE.equals(transactions.execute(status -> {
Conversation conversation = conversation(source.conversationId(), owner, true);
Analysis current = analysis(code, owner);
if (conversation.revision() != current.revision() || !"processing".equals(current.status())) return false;
Instant now = Instant.now();
int changed = jdbc.update("UPDATE robot_demand_analysis SET status=?,result_json=?,updated_at=? WHERE analysis_code=? AND status='processing'",
"ready", encode(result), timestamp(now), code);
"ready", encode(generated.result()), timestamp(now), code);
if (changed == 0) return false;
jdbc.update("INSERT INTO robot_demand_match (match_code,analysis_code,revision,result_json,degradation_accepted,created_at,updated_at) VALUES (?,?,?,?,0,?,?)",
matchId, code, current.revision(), encode(matched), timestamp(now), timestamp(now));
matchId, code, current.revision(), encode(generated.match()), timestamp(now), timestamp(now));
return true;
}));
}
/** 内部读取历史成功快照,不经过对外的 superseded 状态投影。 */
public Baseline baseline(String conversation, String owner, int beforeRevision) {
conversation(conversation, owner, false);
List<Analysis> candidates = jdbc.query("SELECT * FROM robot_demand_analysis WHERE conversation_code=? AND revision<? AND status='ready' ORDER BY revision DESC",
this::analysis, conversation, beforeRevision);
for (Analysis candidate : candidates) {
List<String> matches = jdbc.queryForList("SELECT result_json FROM robot_demand_match WHERE analysis_code=?", String.class, candidate.analysisId());
if (matches.isEmpty()) continue;
JsonNode matched = decode(matches.getFirst());
if (!matched.path("components").isEmpty() && List.of("ready", "partial").contains(matched.path("assembly").path("status").asText())) {
return new Baseline(candidate, matched);
}
}
return null;
}
public JsonNode matchForAnalysis(String code, String owner) {
Analysis current = analysis(code, owner);
if (!"ready".equals(current.status())) return null;
@@ -243,4 +263,7 @@ public class DemandRepository {
@Override public String toString() { return "DemandAnalysis[analysisId=" + analysisId + ", revision=" + revision + ", status=" + status + "]"; }
}
@FunctionalInterface public interface MatchOperation { JsonNode match(String matchId, Analysis analysis); }
@FunctionalInterface public interface PlanOperation { Generation match(String matchId, Analysis analysis); }
public record Generation(DemandResult result, JsonNode match) { }
public record Baseline(Analysis analysis, JsonNode match) { }
}
@@ -180,7 +180,7 @@ public final class DemandRequirementChecker {
return checks;
}
private String field(JsonNode intent) {
static String field(JsonNode intent) {
String value = intent.path("requirement").asText();
if (value.matches(".*(?:自由度|DOF|dof).*")) return "degreesOfFreedom";
if (value.matches(".*(?:质量|重量).*")) return "massKg";
@@ -0,0 +1,136 @@
package com.linkerbot.cadworld.service.demand;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** 替换只覆盖本轮提供的参数,保留原构型及未修改条件。 */
final class DemandRequirementRevision {
private DemandRequirementRevision() { }
static DemandResult merge(DemandRepository.Baseline baseline, DemandResult incoming, Set<String> targets) {
ObjectNode request = baseline.analysis().result().path("request").deepCopy();
ObjectNode prior = baseline.analysis().result().path("analysis").deepCopy();
prefixEvidence(prior);
overlay((ObjectNode) request.withObject("/robotRequirements"), incoming.request().path("robotRequirements"));
Map<String, ObjectNode> parts = new LinkedHashMap<>();
for (JsonNode part : request.path("partRequirements")) parts.put(part.path("category").asText(), part.deepCopy());
Set<String> targetRoles = new LinkedHashSet<>();
targets.forEach((String instance) -> targetRoles.add(instance.substring(0, instance.lastIndexOf(':'))));
for (JsonNode part : incoming.request().path("partRequirements")) {
String category = part.path("category").asText();
Set<String> roles = new LinkedHashSet<>();
roles.add(category);
if (category.endsWith("_0")) targetRoles.stream().filter((String role) -> role.startsWith(category.substring(0, category.length() - 1))).forEach(roles::add);
for (String role : roles) {
if (!targetRoles.contains(role) && !parts.containsKey(role)) continue;
ObjectNode merged = parts.computeIfAbsent(role, (String ignored) -> incoming.request().objectNode().put("category", role));
overlay(merged, part);
merged.put("category", role);
}
}
ArrayNode mergedParts = request.putArray("partRequirements");
parts.values().forEach(mergedParts::add);
Set<String> required = new LinkedHashSet<>(DemandMechanicalNormalizer.texts(request.path("requiredParts")));
required.addAll(parts.keySet());
ArrayNode requiredParts = request.putArray("requiredParts"); required.forEach(requiredParts::add);
request.put("userInput", incoming.request().path("userInput").asText());
ObjectNode analysis = incoming.analysis().deepCopy();
// 已解析的当前完整条目优先;未再次给出的旧条目继续保留。
for (String field : List.of("intentItems", "unmodeled", "observations", "constraints", "excludedCategories")) {
ArrayNode merged = analysis.arrayNode();
for (JsonNode old : prior.path(field)) {
boolean overridden = false;
for (JsonNode current : analysis.path(field)) {
if ("intentItems".equals(field)) {
overridden |= old.path("subject").equals(current.path("subject"))
&& old.path("dimension").equals(current.path("dimension"))
&& (old.path("requirement").equals(current.path("requirement"))
|| DemandRequirementChecker.field(old) != null
&& java.util.Objects.equals(DemandRequirementChecker.field(old), DemandRequirementChecker.field(current)));
} else if ("constraints".equals(field)) {
overridden |= old.path("scope").equals(current.path("scope")) && old.path("categories").equals(current.path("categories"))
&& old.path("field").equals(current.path("field"));
} else overridden |= old.equals(current);
}
if (!overridden) merged.add(old);
}
analysis.path(field).forEach(merged::add);
analysis.set(field, merged);
}
for (String field : List.of("robotTypes", "partCategories", "defaultTemplate")) analysis.set(field, prior.path(field).deepCopy());
if (analysis.path("keywords").isEmpty()) {
for (String field : List.of("keywords", "keywordEvidence")) analysis.set(field, prior.path(field).deepCopy());
}
Set<String> terms = new LinkedHashSet<>();
for (JsonNode keyword : analysis.path("keywords")) if (!keyword.path("negated").asBoolean()) terms.add(keyword.path("term").asText());
for (JsonNode item : analysis.path("unmodeled")) terms.add(item.path("text").asText());
ArrayNode requirementTerms = request.putArray("requirements"); terms.forEach(requirementTerms::add);
Set<String> warnings = new LinkedHashSet<>();
for (JsonNode warning : prior.path("warnings")) {
if (!warning.asText().contains("已保留原方案") && !warning.asText().contains("已保留历史方案")) warnings.add(warning.asText());
}
for (JsonNode warning : incoming.analysis().path("warnings")) {
if (!warning.asText().contains("默认双足") && !warning.asText().contains("固定一个躯干")) warnings.add(warning.asText());
}
ArrayNode warningItems = analysis.putArray("warnings"); warnings.forEach(warningItems::add);
compactEvidence(analysis);
return new DemandResult(request, analysis);
}
private static void overlay(ObjectNode target, JsonNode source) {
for (String numeric : List.of("degreesOfFreedom", "massKg", "torqueNm")) {
if (source.path(numeric).isNumber()) target.withObject("/operators").put(numeric, source.path("operators").path(numeric).asText("eq"));
}
source.fields().forEachRemaining((Map.Entry<String, JsonNode> field) -> {
if (field.getValue().isNull() || field.getValue().isTextual() && field.getValue().asText().isBlank()) return;
if (field.getValue().isObject()) overlay(target.withObject("/" + field.getKey()), field.getValue());
else target.set(field.getKey(), field.getValue().deepCopy());
});
}
static void prefixEvidence(JsonNode node) {
if (node.isObject()) {
ObjectNode object = (ObjectNode) node;
if (object.has("id")) object.put("id", "base-" + object.path("id").asText());
if (object.path("evidenceIds").isArray()) {
ArrayNode ids = (ArrayNode) object.path("evidenceIds");
for (int index = 0; index < ids.size(); index++) ids.set(index, object.textNode("base-" + ids.get(index).asText()));
}
object.elements().forEachRemaining(DemandRequirementRevision::prefixEvidence);
} else if (node.isArray()) node.forEach(DemandRequirementRevision::prefixEvidence);
}
/** 多轮完整解析可能再次返回相同观察,合并引用以避免快照逐轮重复膨胀。 */
static void compactEvidence(ObjectNode analysis) {
Map<String, String> canonical = new LinkedHashMap<>();
Map<String, String> aliases = new LinkedHashMap<>();
ArrayNode observations = analysis.arrayNode();
for (JsonNode observation : analysis.path("observations")) {
ObjectNode identity = observation.deepCopy(); identity.remove("id");
String id = observation.path("id").asText();
String previous = canonical.putIfAbsent(identity.toString(), id);
if (previous == null) observations.add(observation);
else aliases.put(id, previous);
}
analysis.set("observations", observations);
replaceReferences(analysis, aliases);
}
private static void replaceReferences(JsonNode node, Map<String, String> aliases) {
if (node.isObject()) {
ObjectNode object = (ObjectNode) node;
if (object.path("evidenceIds").isArray()) {
Set<String> ids = new LinkedHashSet<>();
object.path("evidenceIds").forEach((JsonNode id) -> ids.add(aliases.getOrDefault(id.asText(), id.asText())));
ArrayNode references = object.putArray("evidenceIds"); ids.forEach(references::add);
}
object.elements().forEachRemaining((JsonNode child) -> replaceReferences(child, aliases));
} else if (node.isArray()) node.forEach((JsonNode child) -> replaceReferences(child, aliases));
}
}
@@ -0,0 +1,198 @@
package com.linkerbot.cadworld.service.matching;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.cadworld.config.MatchingProperties;
import com.linkerbot.cadworld.dto.matching.RobotMatchResponse.UnmetRequirement;
import com.linkerbot.cadworld.entity.Component;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
/** 同时决定目标组件与邻接接口;中间状态不要求仍能连接即将被替换的旧邻居。 */
final class AssemblyReplacementSearch {
private final RequirementEvaluator evaluator;
private final AssemblySearchEngine scoring;
private final MatchingProperties properties;
private int expansions;
private boolean exhausted;
AssemblyReplacementSearch(RequirementEvaluator evaluator, AssemblySearchEngine scoring, MatchingProperties properties) {
this.evaluator = evaluator; this.scoring = scoring; this.properties = properties;
}
Result search(AssemblyState base, CandidatePool.Result pool, NormalizedMatchRequest request, Set<String> targets,
RequirementEvaluator.Evaluation previous, Predicate<AssemblyState> acceptable) {
List<String> ordered = targets.stream().sorted(Comparator.comparingInt((String id) -> pool.candidates()
.getOrDefault(base.parts().get(id).role(), List.of()).size()).thenComparing(String::compareTo)).toList();
if (ordered.stream().anyMatch((String id) -> pool.candidates().getOrDefault(base.parts().get(id).role(), List.of()).isEmpty())) {
return new Result(null, false, 0, "NO_REPLACEMENT_CANDIDATE");
}
List<AssemblyState> beam = List.of(base);
boolean limited = pool.limited();
Set<String> assigned = new HashSet<>();
for (String id : ordered) {
assigned.add(id);
List<AssemblySearchEngine.ScoredState> next = new ArrayList<>();
for (AssemblyState state : beam) for (MatchingCandidate candidate : pool.candidates().get(base.parts().get(id).role())) {
if (!step()) return new Result(null, true, expansions, "SEARCH_LIMIT");
Map<String, MatchingCandidate> parts = new LinkedHashMap<>(state.parts());
parts.put(id, candidate);
AssemblyState partial = new AssemblyState(base.root(), parts, base.edges());
if (compatibleAssignedEdges(base, partial, targets, assigned, request)) next.add(scoring.score(partial, request, Map.of()));
}
if (next.isEmpty()) return new Result(null, limited, expansions, limited ? "SEARCH_LIMIT" : "NO_COMPATIBLE_CONNECTION");
limited |= next.size() > properties.beamWidth();
next.sort(AssemblySearchEngine.FINAL_ORDER);
beam = next.stream().limit(properties.beamWidth()).map(AssemblySearchEngine.ScoredState::state).toList();
}
AssemblySearchEngine.ScoredState best = null;
boolean connected = false;
for (AssemblyState candidate : beam) {
AssemblyState joined = connect(base, candidate.parts(), targets, request);
if (exhausted) return new Result(null, true, expansions, "SEARCH_LIMIT");
if (joined == null) continue;
connected = true;
if (!noWorse(evaluator.evaluate(joined, request), previous, request) || !acceptable.test(joined)) continue;
AssemblySearchEngine.ScoredState score = scoring.score(joined, request, Map.of());
if (best == null || AssemblySearchEngine.FINAL_ORDER.compare(score, best) < 0) best = score;
}
return new Result(best == null ? null : best.state(), limited, expansions,
best != null ? "" : limited ? "SEARCH_LIMIT" : connected ? "REQUIREMENTS_NOT_SATISFIED" : "NO_COMPATIBLE_CONNECTION");
}
private boolean compatibleAssignedEdges(AssemblyState base, AssemblyState partial, Set<String> targets, Set<String> assigned, NormalizedMatchRequest request) {
for (AssemblyState.Edge edge : base.edges()) {
if (targets.contains(edge.parent()) && !assigned.contains(edge.parent()) || targets.contains(edge.child()) && !assigned.contains(edge.child())) continue;
if (pairs(edge, partial.parts(), targets, request).isEmpty()) return false;
}
return true;
}
private AssemblyState connect(AssemblyState base, Map<String, MatchingCandidate> parts, Set<String> targets, NormalizedMatchRequest request) {
List<EdgeOptions> options = new ArrayList<>();
for (int index = 0; index < base.edges().size(); index++) {
AssemblyState.Edge edge = base.edges().get(index);
List<PortPair> pairs = pairs(edge, parts, targets, request);
if (pairs.isEmpty()) return null;
options.add(new EdgeOptions(index, edge, pairs));
}
options.sort(Comparator.comparingInt((EdgeOptions edge) -> edge.pairs().size()));
Map<Integer, AssemblyState.Edge> selected = new HashMap<>();
if (!assign(0, options, new HashSet<>(), selected)) return null;
List<AssemblyState.Edge> edges = new ArrayList<>();
for (int index = 0; index < base.edges().size(); index++) edges.add(selected.get(index));
return new AssemblyState(base.root(), parts, edges);
}
private boolean assign(int index, List<EdgeOptions> options, Set<String> used, Map<Integer, AssemblyState.Edge> selected) {
if (index == options.size()) return true;
EdgeOptions option = options.get(index);
for (PortPair pair : option.pairs()) {
if (!step()) return false;
String parent = option.edge().parent() + "@" + pair.parent().index();
String child = option.edge().child() + "@" + pair.child().index();
if (used.contains(parent) || used.contains(child)) continue;
used.add(parent); used.add(child);
selected.put(option.index(), new AssemblyState.Edge(option.edge().parent(), pair.parent(), option.edge().child(), pair.child()));
if (assign(index + 1, options, used, selected)) return true;
used.remove(parent); used.remove(child);
}
return false;
}
private List<PortPair> pairs(AssemblyState.Edge edge, Map<String, MatchingCandidate> parts, Set<String> targets, NormalizedMatchRequest request) {
MatchingCandidate parent = parts.get(edge.parent());
MatchingCandidate child = parts.get(edge.child());
List<AssemblyMetadata.Port> parents = targets.contains(edge.parent()) ? parent.metadata().ports() : List.of(edge.parentPort());
List<AssemblyMetadata.Port> children = targets.contains(edge.child()) ? child.metadata().ports() : List.of(edge.childPort());
List<PortPair> pairs = new ArrayList<>();
for (AssemblyMetadata.Port parentPort : parents) for (AssemblyMetadata.Port childPort : children) {
if (request.allowsPort(parentPort) && InterfaceCompatibility.canAttach(parentPort, child, childPort)) pairs.add(new PortPair(parentPort, childPort));
}
pairs.sort(Comparator.comparingInt((PortPair pair) -> (pair.parent().index() == edge.parentPort().index() ? 0 : 1)
+ (pair.child().index() == edge.childPort().index() ? 0 : 1)).thenComparingInt((PortPair pair) -> pair.parent().index())
.thenComparingInt((PortPair pair) -> pair.child().index()));
return pairs;
}
private boolean step() {
if (Thread.currentThread().isInterrupted()) throw new com.linkerbot.cadworld.common.exception.BizException(409, "DEMAND_CANCELLED", "生成已停止");
if (expansions >= properties.maxStateExpansions()) { exhausted = true; return false; }
expansions++; return true;
}
/** 比较每项硬条件,不能用另一项改善掩盖新增违例。 */
static boolean noWorse(RequirementEvaluator.Evaluation current, RequirementEvaluator.Evaluation previous, NormalizedMatchRequest request) {
Map<String, List<BigDecimal>> allowances = new HashMap<>();
for (UnmetRequirement item : previous.unmet()) if (!request.preferred(item.category(), item.field())) {
allowances.computeIfAbsent(key(item), (String ignored) -> new ArrayList<>()).add(penalty(item));
}
allowances.values().forEach((List<BigDecimal> values) -> values.sort(Comparator.reverseOrder()));
for (UnmetRequirement item : current.unmet()) if (!request.preferred(item.category(), item.field())) {
List<BigDecimal> allowed = allowances.get(key(item));
if (allowed == null || allowed.isEmpty() || penalty(item).compareTo(allowed.removeFirst()) > 0) return false;
}
return true;
}
private static String key(UnmetRequirement item) { return item.scope() + ":" + item.category() + ":" + item.field() + ":" + item.operator() + ":" + item.expected(); }
private static BigDecimal penalty(UnmetRequirement item) {
if (!(item.expected() instanceof Number) || item.actual() == null) return BigDecimal.ONE;
BigDecimal expected = new BigDecimal(item.expected().toString());
return new BigDecimal(item.actual().toString()).subtract(expected).abs().divide(expected.abs().max(BigDecimal.ONE), MathContext.DECIMAL64);
}
static AssemblyState restore(JsonNode snapshot, NormalizedMatchRequest request, RequirementEvaluator evaluator) {
Map<String, MatchingCandidate> parts = new LinkedHashMap<>();
for (JsonNode item : snapshot.path("components")) {
String id = local(item.path("instanceId").asText());
if (!id.matches("[A-Z]+_[LR0]:[1-9][0-9]?")) throw new IllegalArgumentException("Invalid saved instance code");
ComponentRole role = ComponentRole.require(id.substring(0, id.lastIndexOf(':')));
JsonNode saved = item.path("component");
Component component = new Component();
component.setComponentCode(saved.path("componentCode").asText()); component.setComponentName(saved.path("componentName").asText());
component.setCategory(saved.path("category").asText()); component.setVersion(saved.path("version").asLong());
component.setMaterial(saved.path("material").asText()); component.setDescription(saved.path("description").asText());
component.setFunctionDescription(saved.path("functionDescription").asText()); component.setShape(saved.path("shape").asText());
component.setSize(saved.path("size").asText()); component.setUrdfInfo(saved.path("urdfInfo"));
component.setMassKg(saved.path("massKg").isNumber() ? saved.path("massKg").decimalValue() : null);
component.setTorqueNm(saved.path("torqueNm").isNumber() ? saved.path("torqueNm").decimalValue() : null);
component.setDegreesOfFreedom(saved.path("degreesOfFreedom").isNumber() ? saved.path("degreesOfFreedom").asInt() : null);
parts.put(id, new MatchingCandidate(component, role, AssemblyMetadata.read(component), evaluator.assess(component, role, request)));
}
if (parts.isEmpty() || parts.size() > AssemblyState.MAX_INSTANCES) throw new IllegalArgumentException("Invalid saved assembly");
List<AssemblyState.Edge> edges = new ArrayList<>();
Set<String> children = new HashSet<>();
Set<String> used = new HashSet<>();
Set<String> reachable = new HashSet<>(); reachable.add("TORSO_0:1");
for (JsonNode edge : snapshot.path("assembly").path("connections")) {
String parent = local(edge.path("parentInstanceId").asText());
String child = local(edge.path("childInstanceId").asText());
if (!parts.containsKey(parent) || !parts.containsKey(child) || !reachable.contains(parent) || !children.add(child)) throw new IllegalArgumentException("Invalid saved connection");
AssemblyMetadata.Port parentPort = port(parts.get(parent), edge.path("parentFrameIndex").asInt(-1));
AssemblyMetadata.Port childPort = port(parts.get(child), edge.path("childFrameIndex").asInt(-1));
if (!used.add(parent + "@" + parentPort.index()) || !used.add(child + "@" + childPort.index())
|| !InterfaceCompatibility.canAttach(parentPort, parts.get(child), childPort)) throw new IllegalArgumentException("Invalid saved interface");
edges.add(new AssemblyState.Edge(parent, parentPort, child, childPort)); reachable.add(child);
}
if (reachable.size() != parts.size()) throw new IllegalArgumentException("Disconnected saved assembly");
return new AssemblyState(ComponentRole.TORSO, parts, edges);
}
private static AssemblyMetadata.Port port(MatchingCandidate candidate, int index) {
return candidate.metadata().ports().stream().filter((AssemblyMetadata.Port port) -> port.index() == index).findFirst()
.orElseThrow(() -> new IllegalArgumentException("Invalid saved frame index"));
}
private static String local(String id) { return id.startsWith("DM-") ? id.substring(id.indexOf(':') + 1) : id; }
record Result(AssemblyState state, boolean limited, int expansions, String reason) { }
private record PortPair(AssemblyMetadata.Port parent, AssemblyMetadata.Port child) { }
private record EdgeOptions(int index, AssemblyState.Edge edge, List<PortPair> pairs) { }
}
@@ -24,6 +24,7 @@ public class AssemblySearchEngine {
.thenComparing(Comparator.comparingInt((ScoredState state) -> state.state().parts().size()).reversed())
.thenComparingInt((ScoredState state) -> state.evaluation().preferredUnmetCount())
.thenComparing((ScoredState state) -> state.evaluation().preferredDeviation())
.thenComparingInt((ScoredState state) -> ComponentModelAffinity.dispersion(state.state()))
.thenComparing(Comparator.comparingInt((ScoredState state) -> state.evaluation().keywordScore()).reversed())
.thenComparing(Comparator.comparingInt(ScoredState::localKeywordCoverage).reversed())
.thenComparing(Comparator.comparingInt(ScoredState::localKeywordScore).reversed())
@@ -36,6 +37,9 @@ public class AssemblySearchEngine {
.thenComparingInt(ScoredState::missingMinimum)
.thenComparingInt((ScoredState state) -> state.estimate().unmet())
.thenComparing((ScoredState state) -> state.estimate().deviation())
.thenComparingInt((ScoredState state) -> state.evaluation().preferredUnmetCount())
.thenComparing((ScoredState state) -> state.evaluation().preferredDeviation())
.thenComparingInt((ScoredState state) -> ComponentModelAffinity.dispersion(state.state()))
.thenComparing(Comparator.comparingInt((ScoredState state) -> state.estimate().keywordScore()).reversed())
.thenComparing(FINAL_ORDER);
@@ -26,6 +26,8 @@ final class CandidatePool {
private int invalidMetadata;
private int invalidPorts;
private final List<String> invalidCodeSamples = new ArrayList<>();
private Set<String> companionModels = Set.of();
private final Map<ComponentRole, Set<String>> desiredCompanions = new EnumMap<>(ComponentRole.class);
CandidatePool(NormalizedMatchRequest request, RequirementEvaluator evaluator, MatchingProperties properties) {
this.request = request;
@@ -66,6 +68,44 @@ final class CandidatePool {
List<String> invalidCodeSamples() { return List.copyOf(invalidCodeSamples); }
void retainCompanions(Result pool) {
Set<String> models = new HashSet<>();
pool.candidates().values().forEach((List<MatchingCandidate> values) -> values.forEach(
(MatchingCandidate candidate) -> models.add(ComponentModelAffinity.key(candidate.component()))));
companionModels = Set.copyOf(models);
for (ComponentRole role : request.roles()) {
Set<String> desired = new HashSet<>();
pool.candidates().forEach((ComponentRole peer, List<MatchingCandidate> candidates) -> {
if (peer != role && ComponentModelAffinity.family(peer).equals(ComponentModelAffinity.family(role))) {
candidates.forEach((MatchingCandidate candidate) -> desired.add(ComponentModelAffinity.key(candidate.component())));
}
});
desiredCompanions.put(role, Set.copyOf(desired));
}
}
/** 第二次分页扫描补齐优先型号的对侧代表,仍受每角色容量限制。 */
void acceptCompanion(Component component) {
if (request.excludedRoles().contains(ComponentRole.require(component.getCategory()))
|| !companionModels.contains(ComponentModelAffinity.key(component))) return;
AssemblyMetadata metadata = AssemblyMetadata.read(component);
for (Map.Entry<ComponentRole, Accumulator> entry : accumulators.entrySet()) {
if (!InterfaceCompatibility.allowsRole(entry.getKey(), ComponentRole.require(component.getCategory()))) continue;
if (!desiredCompanions.getOrDefault(entry.getKey(), Set.of()).contains(ComponentModelAffinity.key(component))) continue;
MatchingCandidate candidate = new MatchingCandidate(component, entry.getKey(), metadata, evaluator.assess(component, entry.getKey(), request));
entry.getValue().companions.merge(ComponentModelAffinity.key(component), candidate,
(MatchingCandidate left, MatchingCandidate right) -> demandOrder.compare(left, right) <= 0 ? left : right);
Comparator<MatchingCandidate> companionOrder = Comparator.comparingInt((MatchingCandidate item) -> item.assessment().hardUnmetCount())
.thenComparing((MatchingCandidate item) -> item.assessment().deviation())
.thenComparingInt((MatchingCandidate item) -> item.assessment().preferredUnmetCount())
.thenComparing((MatchingCandidate item) -> item.assessment().preferredDeviation())
.thenComparing((MatchingCandidate item) -> !desiredCompanions.get(entry.getKey()).contains(item.modelKey()))
.thenComparing(demandOrder);
entry.getValue().interfaces.merge(metadata.signature(), candidate,
(MatchingCandidate left, MatchingCandidate right) -> companionOrder.compare(left, right) <= 0 ? left : right);
}
}
MatchingCandidate torso(Result pool) {
return pool.candidates().getOrDefault(ComponentRole.TORSO, List.of()).stream()
.min(demandScore.thenComparing(Comparator.comparingInt((MatchingCandidate candidate) -> compatibleCoverage(candidate, pool)).reversed())
@@ -142,6 +182,7 @@ final class CandidatePool {
private final class Accumulator {
private final List<MatchingCandidate> best = new ArrayList<>();
private final Map<String, MatchingCandidate> interfaces = new HashMap<>();
private final Map<String, MatchingCandidate> companions = new HashMap<>();
private MatchingCandidate minimumDegrees;
private MatchingCandidate maximumDegrees;
private MatchingCandidate minimumMass;
@@ -169,7 +210,6 @@ final class CandidatePool {
private List<MatchingCandidate> select() {
Map<String, MatchingCandidate> selected = new LinkedHashMap<>();
best.stream().limit(properties.preferredCandidatesPerRole()).forEach((MatchingCandidate candidate) -> add(selected, candidate));
if (request.robot().degreesOfFreedom() != null) {
add(selected, minimumDegrees);
add(selected, maximumDegrees);
@@ -181,6 +221,8 @@ final class CandidatePool {
interfaces.entrySet().stream()
.sorted(Map.Entry.comparingByValue(demandOrder))
.forEach((Map.Entry<String, MatchingCandidate> entry) -> add(selected, entry.getValue()));
companions.values().stream().sorted(demandOrder).forEach((MatchingCandidate candidate) -> add(selected, candidate));
best.stream().limit(properties.preferredCandidatesPerRole()).forEach((MatchingCandidate candidate) -> add(selected, candidate));
best.forEach((MatchingCandidate candidate) -> add(selected, candidate));
return selected.values().stream().sorted(demandOrder).toList();
}
@@ -0,0 +1,39 @@
package com.linkerbot.cadworld.service.matching;
import com.linkerbot.cadworld.entity.Component;
import java.text.Normalizer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/** 仅折叠明确的方向标记,不用模糊相似度猜测配套型号。 */
final class ComponentModelAffinity {
private ComponentModelAffinity() { }
static String family(ComponentRole role) { return role.code().substring(0, role.code().lastIndexOf('_')); }
static String key(Component component) {
String family = family(ComponentRole.require(component.getCategory()));
String name = component.getComponentName();
if (name == null || name.isBlank()) return family + ":code:" + component.getComponentCode();
String normalized = Normalizer.normalize(name, Normalizer.Form.NFKC).toLowerCase(Locale.ROOT)
.replaceAll("^(手臂|胳膊|臂|手|腿|足|脚|arm|hand|leg|foot)_[lr0](?=_|$)", "$1")
.replaceAll("[左右](?=手臂|胳膊|臂|手|腿|足|脚)", "")
.replaceAll("[左右]$", "")
.replaceAll("[\\s_]+", "");
return normalized.isBlank() ? family + ":code:" + component.getComponentCode() : family + ":name:" + normalized;
}
static int dispersion(AssemblyState state) {
Map<String, Set<String>> models = new HashMap<>();
for (MatchingCandidate candidate : state.parts().values()) {
String family = family(candidate.role());
if (Set.of("ARM", "HAND", "LEG", "FOOT").contains(family)) {
models.computeIfAbsent(family, (String ignored) -> new HashSet<>()).add(candidate.modelKey());
}
}
return models.values().stream().mapToInt((Set<String> keys) -> Math.max(0, keys.size() - 1)).sum();
}
}
@@ -4,7 +4,10 @@ import com.linkerbot.cadworld.entity.Component;
/** role 是本次装配角色;组件实体始终保留真实类别。 */
record MatchingCandidate(Component component, ComponentRole role, AssemblyMetadata metadata,
RequirementEvaluator.LocalAssessment assessment) {
RequirementEvaluator.LocalAssessment assessment, String modelKey) {
MatchingCandidate(Component component, ComponentRole role, AssemblyMetadata metadata, RequirementEvaluator.LocalAssessment assessment) {
this(component, role, metadata, assessment, ComponentModelAffinity.key(component));
}
String code() { return component.getComponentCode(); }
ComponentRole actualRole() { return ComponentRole.require(component.getCategory()); }
boolean neutralSubstitution() { return actualRole() != role; }
@@ -69,6 +69,17 @@ public class PublicComponentQueryService {
return result;
}
Map<String, Component> current(Collection<String> codes) {
Map<String, Component> result = new LinkedHashMap<>();
if (codes.isEmpty()) return result;
for (Component component : mapper.selectList(candidateFields().in(Component::getComponentCode, codes)
.eq(Component::getStatus, ComponentStatus.ENABLED))) {
if (component.getStepObjectKey() != null && !component.getStepObjectKey().isBlank()
&& component.getUrdfMainObjectKey() != null && !component.getUrdfMainObjectKey().isBlank()) result.put(component.getComponentCode(), component);
}
return result;
}
private PublicComponentResponse toResponse(Component component) {
String category = ComponentRole.find(component.getCategory()).map(ComponentRole::code).orElse(component.getCategory());
return new PublicComponentResponse(component.getComponentCode(), component.getComponentName(), category,
@@ -84,7 +95,7 @@ public class PublicComponentQueryService {
Component::getComponentName, Component::getCategory, Component::getDescription, Component::getMaterial,
Component::getMassKg, Component::getDegreesOfFreedom, Component::getFunctionDescription, Component::getShape,
Component::getSize, Component::getTorqueNm, Component::getUrdfInfo,
Component::getStepObjectKey, Component::getUrdfMainObjectKey);
Component::getStepObjectKey, Component::getUrdfMainObjectKey, Component::getVersion);
}
private LambdaQueryWrapper<Component> publicFields() {
@@ -1,5 +1,6 @@
package com.linkerbot.cadworld.service.matching;
import com.fasterxml.jackson.databind.JsonNode;
import com.linkerbot.cadworld.common.api.RequestIdHolder;
import com.linkerbot.cadworld.config.MatchingProperties;
import com.linkerbot.cadworld.dto.matching.PublicComponentResponse;
@@ -20,6 +21,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@@ -34,6 +36,79 @@ public class RobotMatchingService {
private final AssemblySearchEngine search;
private final MatchingProperties properties;
public record ReplacementRequirements(RobotMatchRequest request, Set<String> softFields,
List<TemplatePartGroup> groups, Set<String> excludedCategories) { }
public record ReplacementOutcome(RobotMatchResponse response, String reasonCode) { }
@Transactional(readOnly = true)
public ReplacementOutcome replace(ReplacementRequirements current, ReplacementRequirements previous, JsonNode snapshot,
Set<String> targets, Predicate<RobotMatchResponse> acceptable) {
NormalizedMatchRequest request = normalize(current);
NormalizedMatchRequest oldRequest = normalize(previous);
AssemblyState base;
AssemblyState old;
try {
base = AssemblyReplacementSearch.restore(snapshot, request, evaluator);
old = AssemblyReplacementSearch.restore(snapshot, oldRequest, evaluator);
} catch (IllegalArgumentException exception) { return new ReplacementOutcome(null, "INVALID_BASE_PLAN"); }
if (targets.isEmpty() || !base.parts().keySet().containsAll(targets)) return new ReplacementOutcome(null, "TARGET_NOT_FOUND");
for (ComponentRole role : request.roles()) {
Integer quantity = request.quantity(role);
if (quantity != null && quantity != base.count(role) && !java.util.Objects.equals(quantity, oldRequest.quantity(role))) {
return new ReplacementOutcome(null, "REQUIREMENTS_NOT_SATISFIED");
}
}
Set<String> fixedCodes = new LinkedHashSet<>();
base.parts().forEach((String id, MatchingCandidate candidate) -> { if (!targets.contains(id)) fixedCodes.add(candidate.code()); });
Map<String, com.linkerbot.cadworld.entity.Component> available = components.current(fixedCodes);
for (Map.Entry<String, MatchingCandidate> entry : base.parts().entrySet()) if (!targets.contains(entry.getKey())) {
com.linkerbot.cadworld.entity.Component component = available.get(entry.getValue().code());
if (component == null || !java.util.Objects.equals(component.getVersion(), entry.getValue().component().getVersion())) {
return new ReplacementOutcome(null, "COMPONENT_REVISION_CONFLICT");
}
if (request.excludedRoles().contains(entry.getValue().role()) || request.excludedRoles().contains(entry.getValue().actualRole())) {
return new ReplacementOutcome(null, "REQUIREMENTS_NOT_SATISFIED");
}
}
Set<String> excludedCodes = new LinkedHashSet<>();
targets.forEach((String id) -> excludedCodes.add(base.parts().get(id).code()));
CandidatePool collector = new CandidatePool(request, evaluator, properties);
components.scan(request.scanRoles(), (com.linkerbot.cadworld.entity.Component component) -> {
if (!excludedCodes.contains(component.getComponentCode())) collector.accept(component);
});
CandidatePool.Result initial = collector.finish();
collector.retainCompanions(initial);
components.scan(request.scanRoles(), (com.linkerbot.cadworld.entity.Component component) -> {
if (!excludedCodes.contains(component.getComponentCode())) collector.acceptCompanion(component);
});
CandidatePool.Result pool = collector.finish();
AssemblyReplacementSearch.Result replacement = new AssemblyReplacementSearch(evaluator, search, properties).search(base, pool, request, targets,
evaluator.evaluate(old, oldRequest), (AssemblyState state) -> acceptable.test(checkResponse(state, request, pool)));
log.info("局部替换搜索完成 requestId={} targetCount={} expansions={} limited={} reasonCode={}", RequestIdHolder.get(), targets.size(),
replacement.expansions(), replacement.limited(), replacement.reason());
if (replacement.state() == null) return new ReplacementOutcome(null, replacement.reason());
AssemblySearchEngine.ScoredState score = search.score(replacement.state(), request, Map.of());
return new ReplacementOutcome(response(request, pool, new AssemblySearchEngine.Result(score, replacement.limited(), replacement.expansions())), "");
}
private NormalizedMatchRequest normalize(ReplacementRequirements requirements) {
Set<ComponentRole> excluded = requirements.excludedCategories().stream().map(ComponentRole::require).collect(java.util.stream.Collectors.toSet());
return NormalizedMatchRequest.from(requirements.request(), requirements.softFields(), requirements.groups(), excluded);
}
private RobotMatchResponse checkResponse(AssemblyState state, NormalizedMatchRequest request, CandidatePool.Result pool) {
RequirementEvaluator.Evaluation evaluation = evaluator.evaluate(state, request);
List<PublicComponentResponse> parts = state.parts().entrySet().stream().map((Map.Entry<String, MatchingCandidate> entry) -> {
com.linkerbot.cadworld.entity.Component component = entry.getValue().component();
return new PublicComponentResponse(component.getComponentCode(), component.getComponentName(), component.getCategory(), component.getDescription(),
component.getMaterial(), component.getMassKg(), component.getDegreesOfFreedom(), component.getRotationAxis(), component.getFunctionDescription(),
component.getShape(), component.getSize(), component.getTorqueNm(), component.getBomList(), component.getUrdfInfo(), component.getVersion(), null, null, entry.getKey());
}).toList();
AssemblySearchEngine.Result result = new AssemblySearchEngine.Result(search.score(state, request, Map.of()), pool.limited(), 0);
return new RobotMatchResponse("MATCHED", state.root().code(), parts, state.connections(), List.of(), evaluation.totals(), evaluation.unmet(),
evaluation.unmatched(), missing(request, pool, result), missingGroups(request, pool, result), pool.limited());
}
@Transactional(readOnly = true)
public RobotMatchResponse match(RobotMatchRequest input) {
return matchInternal(input, false, Set.of());
@@ -78,6 +153,9 @@ public class RobotMatchingService {
CandidatePool collector = new CandidatePool(request, evaluator, properties);
components.scan(request.scanRoles(), collector::accept);
CandidatePool.Result pool = collector.finish();
collector.retainCompanions(pool);
components.scan(request.scanRoles(), collector::acceptCompanion);
pool = collector.finish();
MatchingCandidate torso = collector.torso(pool);
log.info("躯干选择完成 requestId={} candidateCount={} componentCode={} hardUnmetCount={} preferredUnmetCount={} keywordCoverage={} keywordCount={}",
RequestIdHolder.get(), pool.eligible().get(ComponentRole.TORSO), torso == null ? null : torso.code(),
@@ -142,6 +220,8 @@ public class RobotMatchingService {
selected.parts().values().forEach((MatchingCandidate candidate) -> codes.add(candidate.code()));
alternatives.values().forEach((List<ReplacementState> items) -> items.forEach((ReplacementState item) -> codes.add(item.candidate().code())));
Map<String, PublicComponentResponse> publicComponents = components.load(codes);
selected.parts().values().forEach((MatchingCandidate candidate) -> verifyVersion(candidate, publicComponents));
alternatives.values().forEach((List<ReplacementState> items) -> items.forEach((ReplacementState item) -> verifyVersion(item.candidate(), publicComponents)));
List<PublicComponentResponse> parts = selected.parts().entrySet().stream()
.map((Map.Entry<String, MatchingCandidate> entry) -> publicComponents.get(entry.getValue().code()).withInstanceId(entry.getKey())).toList();
List<Alternatives> publicAlternatives = new ArrayList<>();
@@ -160,6 +240,7 @@ public class RobotMatchingService {
.thenComparing((ReplacementState item) -> item.evaluation().deviation())
.thenComparingInt((ReplacementState item) -> item.evaluation().preferredUnmetCount())
.thenComparing((ReplacementState item) -> item.evaluation().preferredDeviation())
.thenComparingInt((ReplacementState item) -> ComponentModelAffinity.dispersion(item.state()))
.thenComparing(Comparator.comparingInt((ReplacementState item) -> item.evaluation().keywordScore()).reversed())
.thenComparing((ReplacementState item) -> item.candidate().code());
selected.parts().forEach((String instance, MatchingCandidate current) -> {
@@ -192,6 +273,12 @@ public class RobotMatchingService {
private record ReplacementState(MatchingCandidate candidate, AssemblyState state, RequirementEvaluator.Evaluation evaluation) { }
private void verifyVersion(MatchingCandidate candidate, Map<String, PublicComponentResponse> loaded) {
if (!java.util.Objects.equals(candidate.component().getVersion(), loaded.get(candidate.code()).version())) {
throw new com.linkerbot.cadworld.common.exception.BizException(409, "COMPONENT_REVISION_CONFLICT", "组件版本已变化,请重新匹配");
}
}
private List<MissingPartGroup> missingGroups(NormalizedMatchRequest request, CandidatePool.Result pool, AssemblySearchEngine.Result result) {
List<MissingPartGroup> missing = new ArrayList<>();
for (NormalizedMatchRequest.PartGroup group : request.groups()) {
@@ -452,6 +452,73 @@
"items": {
"type": "string"
}
},
"operation": {
"type": "object",
"properties": {
"type": {
"type": "string",
"enum": [
"generate",
"replace"
]
},
"targets": {
"type": "array",
"items": {
"type": "object",
"properties": {
"family": {
"type": "string",
"enum": [
"TORSO",
"HEAD",
"WAIST",
"ARM",
"HAND",
"LEG",
"FOOT",
"TAIL"
]
},
"side": {
"type": "string",
"enum": [
"all",
"L",
"R",
"0"
]
},
"instanceId": {
"type": "string"
},
"ordinal": {
"type": "string"
},
"evidenceIds": {
"type": "array",
"items": {
"type": "string"
}
}
},
"required": [
"family",
"side",
"instanceId",
"ordinal",
"evidenceIds"
],
"additionalProperties": false
}
}
},
"required": [
"type",
"targets"
],
"additionalProperties": false
}
},
"required": [
@@ -465,7 +532,8 @@
"excludedCategories",
"constraints",
"unmodeled",
"questions"
"questions",
"operation"
],
"additionalProperties": false
}
@@ -14,6 +14,9 @@
9. keywords 提取主体、仿生对象、形态、功能、环境、材料、尺寸、数值、偏好及禁止项;规范化同义词但保留否定。source=explicit 或 inferred,推断注明 reason,不能推断数字、牌号或性能。否定词保留在 term 中,如“不要飞行”。
10. 后续明确修改覆盖旧值,补充累加;不得把各轮旧值全部 AND 叠加。用户后来补充“单位是N·m”时结合之前用户数值,将两轮证据都引用,不能从助手示例获取数值。用户否定旧需求后,将其从当前有效关键词和约束中移除。
10a. operation 始终输出。普通生成或整体重新生成使用 {"type":"generate","targets":[]}。当轮用户要求在现有组合上换件时使用 type=replace。targets 每项包含 family=TORSO/HEAD/WAIST/ARM/HAND/LEG/FOOT/TAIL、side=all/L/R/0、instanceId、ordinal、evidenceIds;未指定实例和序号时两个字符串为空。腿、足对应 LEG,脚对应 FOOT。未说明左右的“换个腿”使用 family=LEG、side=all,后端替换现有整组实例;“换个左臂”使用 ARM、L,仅替换该侧。指定“第2个左臂”时 ordinal="2";中文序号转换为数字。明确写出现有完整实例编码才填写 instanceId;不猜序号或实例编码,不额外替换手、脚或对侧。每项证据必须是当轮用户真实文字,必须覆盖替换动作和对应部位;每个指定侧分别列项,不将“换左臂和右腿”扩展成整个臂和腿组。没有现有方案时仍如实输出 replace,由后端说明缺少基准。
10b. 服务端提供的 effectiveRequirements 是当前已保存的有效需求,优先于历史里尚未执行或失败的改动。输出在该有效需求上应用当轮修改后的完整需求;历史只提供真实来源证据,不能重新启用失败条件。替换动作只进入 operation,不作为数量、部件包含、硬性能或 unmodeled 条目;“换个头”不改变原构型和数量,不把“个”解析为新增一个头。附带的新参数仍进入 constraints/intentItems;针对未指定左右部位的新条件,按上下文实际装配角色分别输出。不得因换单侧而自行要求对侧也换。
三、类型与部位
11. 配置目录:{{CATALOG_JSON}}。robotTypes 只使用目录中的模板 id;程序展开 requiredParts,你不输出该字段。能辨认形态时选对应模板,图片推断标 inferred。未指定形态时 robotTypes=[],后端使用默认模板并说明。目录不代表库存齐全或能力达标。
12. 六足/六腿/hexapod 选择 hexapod 模板,不得标为不支持或回退为双足。六足基本构型由躯干、六个足部和六个脚部候选组成,具体左右或中性类型由后端按实际接口选择,不默认添加人形的头、腰、臂、手或尾。未配置的四足、轮式、履带、鸟形等保留为 unmodeled,不谎称双足能够满足;后端可返回默认参考方案并保留差异。“仿生鸟类”保留机器人、仿生、鸟类等关键词,可将双足作为 inferred 候选;飞行能力保留为未验证,企鹅、鸵鸟或明确不飞行时不推断飞行。
@@ -73,6 +73,16 @@ class ArkDemandModelClientTest {
assertCode(client("key", Duration.ofSeconds(2)), "DEMAND_INCOMPLETE");
}
@Test void suppliesSavedContextSeparatelyFromActualUserEvidence() throws Exception {
JsonNode context = json.readTree("{\"effectiveRequirements\":{\"request\":{}},\"components\":[{\"instanceId\":\"DM-base:ARM_L:1\",\"role\":\"ARM_L\"}]}");
JsonNode body = client("key", Duration.ofSeconds(2)).request(List.of(new DemandMessage("m2", "user", "换个左臂", List.of(), context)));
assertThat(body.path("input").get(1).path("role").asText()).isEqualTo("system");
assertThat(body.path("input").get(1).toString()).contains("DM-base:ARM_L:1");
assertThat(body.path("input").get(2).path("role").asText()).isEqualTo("user");
assertThat(body.path("input").get(2).toString()).doesNotContain("DM-base");
assertThat(body.path("text").path("format").path("schema").path("required")).contains(json.getNodeFactory().textNode("operation"));
}
@Test void providerErrorsInvalidJsonAndOversizedResponseStayGeneric() throws Exception {
status = 500; response.set("private-provider-debug");
assertCode(client("key", Duration.ofSeconds(2)), "DEMAND_PROVIDER_FAILURE");
@@ -35,7 +35,7 @@ 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.5-neutral-components");
assertThat(actual.analysis().path("schemaVersion").asText()).isEqualTo("multimodal-v1.6-component-replacement");
assertThat(actual.analysis().path("catalogVersion").asText()).isEqualTo("2026-10-16-hexapod-template");
}
@@ -287,12 +287,62 @@ class DemandNormalizerTest {
assertThat(result.request().path("partRequirements")).isEmpty();
}
@Test void replacementEvidenceCannotExpandAnExplicitSideOrComeFromAnEarlierMessage() {
String text = "换个左臂";
ObjectNode raw = minimal(text);
ObjectNode target = raw.putObject("operation").put("type", "replace").putArray("targets").addObject()
.put("family", "ARM").put("side", "L").put("instanceId", "").put("ordinal", "");
target.putArray("evidenceIds").add("e1");
assertThat(normalizer.normalize(raw, text(text)).analysis().path("operation").path("type").asText()).isEqualTo("replace");
target.put("side", "all");
assertThatThrownBy(() -> normalizer.normalize(raw, text(text))).isInstanceOf(BizException.class);
target.put("side", "L");
assertThatThrownBy(() -> normalizer.normalize(raw, List.of(new DemandMessage("m1", "user", text, List.of()),
new DemandMessage("m2", "user", "按原需求", List.of())))).isInstanceOf(BizException.class);
target.put("family", "LEG");
assertThatThrownBy(() -> normalizer.normalize(raw, text(text))).isInstanceOf(BizException.class);
}
@Test void supportsChineseOrdinalWithoutInventingAnInstanceCode() {
String text = "换第二个左臂";
ObjectNode raw = minimal(text);
raw.putObject("operation").put("type", "replace").putArray("targets").addObject()
.put("family", "ARM").put("side", "L").put("instanceId", "").put("ordinal", "2").putArray("evidenceIds").add("e1");
DemandResult result = normalizer.normalize(raw, text(text));
ObjectNode match = json.createObjectNode();
for (int number : List.of(10, 2, 1)) match.withArray("components").addObject().put("instanceId", "DM-base:ARM_L:" + number);
assertThat(DemandOperation.targets(result.analysis().path("operation"), match)).containsExactly("ARM_L:2");
}
@Test void cannotTreatAPreservedSideAsAReplacementTarget() {
String text = "换个右臂,左臂不要换";
ObjectNode raw = minimal(text);
ObjectNode target = raw.putObject("operation").put("type", "replace").putArray("targets").addObject()
.put("family", "ARM").put("side", "L").put("instanceId", "").put("ordinal", "");
target.putArray("evidenceIds").add("e1");
assertThatThrownBy(() -> normalizer.normalize(raw, text(text))).isInstanceOf(BizException.class);
target.put("side", "R");
assertThat(normalizer.normalize(raw, text(text)).analysis().path("operation").path("type").asText()).isEqualTo("replace");
}
@Test void ordinalMustBelongToTheRequestedSide() {
String text = "换第一个左臂和第二个右臂";
ObjectNode raw = minimal(text);
ObjectNode target = raw.putObject("operation").put("type", "replace").putArray("targets").addObject()
.put("family", "ARM").put("side", "R").put("instanceId", "").put("ordinal", "2");
target.putArray("evidenceIds").add("e1");
assertThat(normalizer.normalize(raw, text(text)).analysis().path("operation").path("targets").get(0).path("ordinal").asText()).isEqualTo("2");
target.put("ordinal", "1");
assertThatThrownBy(() -> normalizer.normalize(raw, text(text))).isInstanceOf(BizException.class);
}
private JsonNode fixture(String name) throws Exception {
try (InputStream stream = getClass().getResourceAsStream("/robot-demand/" + name + ".json")) { return json.readTree(stream); }
}
private List<DemandMessage> text(String text) { return List.of(new DemandMessage("m1", "user", text, List.of())); }
private ObjectNode minimal(String text) {
ObjectNode raw = json.createObjectNode().put("summary", "双足需求");
raw.putObject("operation").put("type", "generate").putArray("targets");
for (String field : List.of("intentItems", "images", "observations", "keywords", "robotTypes", "partCategories", "excludedCategories", "constraints", "unmodeled", "questions")) raw.putArray(field);
raw.withArray("observations").addObject().put("id", "e1").put("messageId", "m1").put("imageId", "").put("kind", "user_text").put("content", text).put("clarity", "clear").putArray("region");
raw.withArray("keywords").addObject().put("term", "双足").put("source", "explicit").put("reason", "双足要求").put("negated", false).putArray("evidenceIds").add("e1");
@@ -0,0 +1,68 @@
package com.linkerbot.cadworld.service.matching;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.linkerbot.cadworld.config.MatchingProperties;
import com.linkerbot.cadworld.dto.matching.RobotMatchRequest;
import com.linkerbot.cadworld.entity.Component;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class AssemblyReplacementSearchTest {
private final MatchingProperties properties = new MatchingProperties(50, 30, 128, 50000, null);
private final RequirementEvaluator evaluator = new RequirementEvaluator(new MatchTextService(properties));
private final NormalizedMatchRequest request = NormalizedMatchRequest.from(new RobotMatchRequest(null, List.of(),
List.of("TORSO_0", "ARM_L", "HAND_L"), null, List.of()));
@Test void jointlyReplacesNeighborsThatCannotBeReplacedIndividually() {
MatchingCandidate torso = candidate("T", ComponentRole.TORSO, "ARM_L", "LINK_ARM_L");
MatchingCandidate arm = candidate("A", ComponentRole.ARM_L, "ARM_L", "LINK_ARM_L", "HAND_L", "old");
MatchingCandidate hand = candidate("H", ComponentRole.HAND_L, "HAND_L", "old");
AssemblyState base = AssemblyState.root(torso).attach("TORSO_0:1", torso.metadata().ports().get(0), arm, arm.metadata().ports().get(0))
.attach("ARM_L:1", arm.metadata().ports().get(1), hand, hand.metadata().ports().get(0));
MatchingCandidate newArm = candidate("A2", ComponentRole.ARM_L, "ARM_L", "LINK_ARM_L", "HAND_L", "new");
MatchingCandidate newHand = candidate("H2", ComponentRole.HAND_L, "HAND_L", "new");
assertThat(base.replace("ARM_L:1", newArm)).isNull();
assertThat(base.replace("HAND_L:1", newHand)).isNull();
CandidatePool.Result pool = pool(torso, newArm, newHand);
AssemblyReplacementSearch.Result result = new AssemblyReplacementSearch(evaluator, new AssemblySearchEngine(properties, evaluator), properties)
.search(base, pool, request, Set.of("ARM_L:1", "HAND_L:1"), evaluator.evaluate(base, request), (AssemblyState state) -> true);
assertThat(result.state()).isNotNull();
assertThat(result.state().parts().get("ARM_L:1").code()).isEqualTo("A2");
assertThat(result.state().parts().get("HAND_L:1").code()).isEqualTo("H2");
assertThat(result.state().connections().get(0).parentFrameIndex()).isZero();
assertThat(result.state().connections().get(1).interfaceChild()).isEqualTo("new");
}
@Test void budgetExhaustionReturnsNoPartiallyChangedAssembly() {
MatchingCandidate torso = candidate("T", ComponentRole.TORSO, "ARM_L", "LINK_ARM_L");
MatchingCandidate arm = candidate("A", ComponentRole.ARM_L, "ARM_L", "LINK_ARM_L");
AssemblyState base = AssemblyState.root(torso).attach("TORSO_0:1", torso.metadata().ports().get(0), arm, arm.metadata().ports().get(0));
MatchingProperties tiny = new MatchingProperties(2, 1, 2, 1, null);
AssemblyReplacementSearch.Result result = new AssemblyReplacementSearch(evaluator, new AssemblySearchEngine(tiny, evaluator), tiny)
.search(base, pool(torso, candidate("A2", ComponentRole.ARM_L, "ARM_L", "LINK_ARM_L")), request,
Set.of("ARM_L:1"), evaluator.evaluate(base, request), (AssemblyState state) -> true);
assertThat(result.state()).isNull(); assertThat(result.reason()).isEqualTo("SEARCH_LIMIT");
assertThat(base.parts().get("ARM_L:1").code()).isEqualTo("A");
}
private CandidatePool.Result pool(MatchingCandidate... candidates) {
Map<ComponentRole, List<MatchingCandidate>> values = new java.util.EnumMap<>(ComponentRole.class);
for (MatchingCandidate candidate : candidates) values.put(candidate.role(), List.of(candidate));
return new CandidatePool.Result(values, Map.of(), Map.of(), false, candidates.length, 0, 0);
}
private MatchingCandidate candidate(String code, ComponentRole role, String... ports) {
Component component = new Component(); component.setComponentCode(code); component.setCategory(role.code()); component.setMassKg(BigDecimal.ONE);
ObjectNode metadata = new ObjectMapper().createObjectNode().put("rootLink", code);
metadata.putArray("frames");
for (int index = 0; index < ports.length; index += 2) metadata.withArray("frames").addObject()
.put("interfaceType", ports[index]).put("child", ports[index + 1]);
component.setUrdfInfo(metadata);
return new MatchingCandidate(component, role, AssemblyMetadata.read(component), evaluator.assess(component, role, request));
}
}
@@ -0,0 +1,50 @@
package com.linkerbot.cadworld.service.matching;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.linkerbot.cadworld.config.MatchingProperties;
import com.linkerbot.cadworld.dto.matching.RobotMatchRequest;
import com.linkerbot.cadworld.entity.Component;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.assertj.core.api.Assertions.assertThat;
class ComponentModelAffinityTest {
@Test void recognizesOnlyDirectionVariantsAndPreservesActualModelNumbers() {
assertThat(key("臂_L_臂3自由度左", "ARM_L")).isEqualTo(key("臂_R_臂3自由度右", "ARM_R"));
assertThat(key("臂_L_左臂2DOF圆长", "ARM_L")).isEqualTo(key("臂_R_右臂2DOF圆长", "ARM_R"));
assertThat(key("臂_L_臂3自由度左", "ARM_L")).isNotEqualTo(key("臂_R_臂4自由度右", "ARM_R"));
assertThat(key("臂_L_型号_0_左", "ARM_L")).isNotEqualTo(key("臂_R_型号右", "ARM_R"));
assertThat(key("左旋臂", "ARM_L")).isNotEqualTo(key("右旋臂", "ARM_R"));
assertThat(key("通用型号", "ARM_0")).isNotEqualTo(key("通用型号", "LEG_0"));
}
@ParameterizedTest @ValueSource(ints = {1, 2})
void companionOutsideFirstCandidateLimitIsRetainedWithoutIncreasingCapacity(int capacity) throws Exception {
MatchingProperties properties = new MatchingProperties(capacity, 1, 16, 100, null);
RequirementEvaluator evaluator = new RequirementEvaluator(new MatchTextService(properties));
NormalizedMatchRequest request = NormalizedMatchRequest.from(new RobotMatchRequest(null, List.of(), List.of("ARM_L", "ARM_R"), null, List.of()));
Component left = component("L", "臂_L_配套左", "ARM_L");
Component rightOne = component("R1", "臂_R_其他1右", "ARM_R");
Component rightTwo = component("R2", "臂_R_其他2右", "ARM_R");
Component rightPair = component("R9", "臂_R_配套右", "ARM_R");
CandidatePool collector = new CandidatePool(request, evaluator, properties);
List<Component> library = List.of(left, rightOne, rightTwo, rightPair);
library.forEach(collector::accept);
assertThat(collector.finish().candidates().get(ComponentRole.ARM_R)).extracting(MatchingCandidate::code).doesNotContain("R9");
collector.retainCompanions(collector.finish()); library.forEach(collector::acceptCompanion);
assertThat(collector.finish().candidates().get(ComponentRole.ARM_R)).hasSize(capacity).extracting(MatchingCandidate::code).contains("R9");
}
private String key(String name, String category) {
Component component = new Component(); component.setCategory(category); component.setComponentName(name);
return ComponentModelAffinity.key(component);
}
private Component component(String code, String name, String category) throws Exception {
Component component = new Component(); component.setComponentCode(code); component.setComponentName(name); component.setCategory(category);
component.setUrdfInfo(new ObjectMapper().readTree("{\"rootLink\":\"ROOT\",\"frames\":[{\"interfaceType\":\"" + category + "\",\"child\":\"LINK_" + category + "\"}]}"));
return component;
}
}
@@ -418,7 +418,11 @@
"unmodeled": [],
"questions": [
"您提出整机质量为8kg,而提供的需求图片中标注整机质量为10kg,二者数值存在冲突,请确认最终整机质量的指定值。"
]
],
"operation": {
"type": "generate",
"targets": []
}
},
"messages": [
{
@@ -934,7 +938,11 @@
]
}
],
"schemaVersion": "multimodal-v1.5-neutral-components"
"schemaVersion": "multimodal-v1.6-component-replacement",
"operation": {
"type": "generate",
"targets": []
}
}
}
}
@@ -368,7 +368,11 @@
}
],
"unmodeled": [],
"questions": []
"questions": [],
"operation": {
"type": "generate",
"targets": []
}
},
"messages": [
{
@@ -834,7 +838,11 @@
]
}
],
"schemaVersion": "multimodal-v1.5-neutral-components"
"schemaVersion": "multimodal-v1.6-component-replacement",
"operation": {
"type": "generate",
"targets": []
}
}
}
}
@@ -391,7 +391,11 @@
}
],
"unmodeled": [],
"questions": []
"questions": [],
"operation": {
"type": "generate",
"targets": []
}
},
"messages": [
{
@@ -883,7 +887,11 @@
]
}
],
"schemaVersion": "multimodal-v1.5-neutral-components"
"schemaVersion": "multimodal-v1.6-component-replacement",
"operation": {
"type": "generate",
"targets": []
}
}
}
}
@@ -159,7 +159,11 @@
"excludedCategories": [],
"constraints": [],
"unmodeled": [],
"questions": []
"questions": [],
"operation": {
"type": "generate",
"targets": []
}
},
"messages": [
{
@@ -410,7 +414,11 @@
]
}
],
"schemaVersion": "multimodal-v1.5-neutral-components"
"schemaVersion": "multimodal-v1.6-component-replacement",
"operation": {
"type": "generate",
"targets": []
}
}
}
}