From fcc5719bc60fd7465abdf62fe8dc351e8ad4550d Mon Sep 17 00:00:00 2001 From: zhengwr Date: Wed, 17 Jun 2026 12:33:09 +0800 Subject: [PATCH] feat: enforce AI page recipe gate --- docs/AI_AGENT_AUTO_DEVELOPMENT.md | 2 +- docs/AI_AGENT_PAGE_BLUEPRINT_CONTRACT.md | 21 ++- .../platform/ai/service/AiAgentService.java | 58 +++++++- .../DeterministicAiAgentRepairExecutor.java | 14 +- .../ai/page-recipes/maintenance-crud-v1.yaml | 1 + .../ai/service/AiAgentServiceTest.java | 24 ++++ .../blueprint/PageBlueprintCompiler.java | 14 +- .../blueprint/PageRecipeDefinition.java | 24 ++++ .../schema/blueprint/PageRecipeRegistry.java | 66 +++++++++ .../blueprint/PageRecipeValidationReport.java | 14 ++ .../schema/blueprint/PageRecipeValidator.java | 126 ++++++++++++++++++ .../blueprint/PageRecipeValidatorTest.java | 61 +++++++++ 12 files changed, 414 insertions(+), 11 deletions(-) create mode 100644 platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeDefinition.java create mode 100644 platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeRegistry.java create mode 100644 platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidationReport.java create mode 100644 platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidator.java create mode 100644 platform-metadata/src/test/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidatorTest.java diff --git a/docs/AI_AGENT_AUTO_DEVELOPMENT.md b/docs/AI_AGENT_AUTO_DEVELOPMENT.md index c81ab7b..0aaab16 100644 --- a/docs/AI_AGENT_AUTO_DEVELOPMENT.md +++ b/docs/AI_AGENT_AUTO_DEVELOPMENT.md @@ -104,7 +104,7 @@ curl -X POST http://localhost:8093/api/ai/features/auto-develop \ 1. 创建 `AiTask`。 2. 生成 `ENTITY`、`PAGE_SCHEMA`、`SERVICEFLOW`、`MENU`、`TEST` 草稿。`PAGE_SCHEMA` 先生成 EIP4 PageBlueprint,再由平台编译器输出 amis schema;草稿 metadata 保留 blueprint 证据。 -3. 对草稿执行基础门禁,包括 amis schema、typed page schema、服务流 XML、实体字段和 smoke 计划。 +3. 对草稿执行基础门禁,包括 page-recipe、amis schema、typed page schema、服务流 XML、实体字段和 smoke 计划。 4. 生成待人审 `AiChangeSet`。 5. 生成 release plan。 6. 本地 apply:实体走本机 `/api/meta/entity`,页面/服务流写本地库;如果本地最小库缺少 `sys_menu`,菜单发布标记为 `SKIPPED`,不阻断本地 gate,部署包仍保留菜单 SQL 供线上人审。 diff --git a/docs/AI_AGENT_PAGE_BLUEPRINT_CONTRACT.md b/docs/AI_AGENT_PAGE_BLUEPRINT_CONTRACT.md index 3715951..52b4717 100644 --- a/docs/AI_AGENT_PAGE_BLUEPRINT_CONTRACT.md +++ b/docs/AI_AGENT_PAGE_BLUEPRINT_CONTRACT.md @@ -23,6 +23,11 @@ AI 自动开发链路中的 `PAGE_SCHEMA` 草稿仍然保存编译后的 amis sc - `pageBlueprintVersion` - `pageBlueprint` +声明了 `pageRecipe` 的草稿必须通过 `page-recipe` 门禁。该门禁会重新解析 metadata 中的 +`pageBlueprint`,用平台注册的 recipe/compiler 重新编译,并要求草稿 payload 与编译结果一致。 +因此 Agent 不能一边声明使用标准 recipe,一边绕过 compiler 私改 amis JSON。没有声明 recipe 的 +历史/手工 `PAGE_SCHEMA` 草稿暂按自由 schema 处理,只走 amis schema 和 typed page schema。 + ## Recipe: maintenance-crud-v1 适用范围: @@ -73,10 +78,16 @@ AI 自动开发链路中的 `PAGE_SCHEMA` 草稿仍然保存编译后的 amis sc 这些类型必须作为新的 recipe 增量加入,不能让 Agent 直接绕过 blueprint 生成最终 amis JSON。 +## 已落地门禁 + +- `page-recipe`:校验 recipe 已注册、metadata 证据完整、payload 等于 blueprint 编译结果。 +- `typed-page-schema`:校验组件和 actionType 来自 EIP4 注册表。 +- `amis-schema`:校验最终 schema 符合 amis schema。 +- `local-smoke`:本地发布后访问页面、实体、服务流和新增接口。 + ## 后续演进 -1. 将 `maintenance-crud-v1.yaml` 中的规则接入 UI lint。 -2. 增加 `master-detail-v1`、`tree-crud-v1`、`approval-task-v1` recipe。 -3. 让设计器 overlay 保存也能记录对应 blueprint 或 template 来源。 -4. 在功能包中导出 blueprint,线上部署包继续导出编译后的 amis schema。 -5. Playwright E2E 从 recipe 反推出应验证的 UI 行为。 +1. 增加 `master-detail-v1`、`tree-crud-v1`、`approval-task-v1` recipe。 +2. 让设计器 overlay 保存也能记录对应 blueprint 或 template 来源。 +3. 在功能包中导出 blueprint,线上部署包继续导出编译后的 amis schema。 +4. Playwright E2E 从 recipe 反推出应验证的 UI 行为。 diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentService.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentService.java index 9b83535..ebc2933 100644 --- a/platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentService.java +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentService.java @@ -61,6 +61,10 @@ import com.eip4.platform.metadata.schema.PageComponentRegistry; import com.eip4.platform.metadata.schema.TypedPageSchemaIssue; import com.eip4.platform.metadata.schema.TypedPageSchemaReport; import com.eip4.platform.metadata.schema.TypedPageSchemaValidator; +import com.eip4.platform.metadata.schema.blueprint.PageBlueprint; +import com.eip4.platform.metadata.schema.blueprint.PageRecipeRegistry; +import com.eip4.platform.metadata.schema.blueprint.PageRecipeValidationReport; +import com.eip4.platform.metadata.schema.blueprint.PageRecipeValidator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -86,6 +90,7 @@ public class AiAgentService { private final ObjectMapper objectMapper; private final AiToolRegistry toolRegistry; private final TypedPageSchemaValidator typedSchemaValidator; + private final PageRecipeValidator pageRecipeValidator; private static volatile SchemaGate sharedSchemaGate; private volatile SchemaGate schemaGate; @@ -122,6 +127,7 @@ public class AiAgentService { this.typedSchemaValidator = typedSchemaValidator == null ? new TypedPageSchemaValidator(objectMapper, PageComponentRegistry.defaults()) : typedSchemaValidator; + this.pageRecipeValidator = new PageRecipeValidator(objectMapper, PageRecipeRegistry.defaults()); } public AiTask createTask(String objective) { @@ -154,7 +160,8 @@ public class AiAgentService { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "payload 不能为空"); } - List gates = validateDraft(artifactType, target, payload); + Map safeMetadata = metadata == null ? Map.of() : metadata; + List gates = validateDraft(artifactType, target, payload, safeMetadata); AiDraft draft = new AiDraft( "aid-" + UUID.randomUUID(), taskId, @@ -163,7 +170,7 @@ public class AiAgentService { payload, System.currentTimeMillis(), gates, - metadata == null ? Map.of() : Map.copyOf(metadata)); + Map.copyOf(safeMetadata)); store.saveDraft(draft); audit(taskId, "draft.saved", "agent", Map.of( "draftId", draft.id(), @@ -781,6 +788,49 @@ public class AiAgentService { return new AiGateResult("typed-page-schema", report.valid(), typedMessages(report)); } + private AiGateResult validatePageRecipeGate(String targetId, JsonNode schema, Map metadata) { + boolean hasRecipe = metadata.containsKey("pageRecipe"); + boolean hasBlueprint = metadata.containsKey("pageBlueprint"); + if (!hasRecipe && !hasBlueprint) { + return new AiGateResult("page-recipe", true, List.of("未声明 pageRecipe,按手工 PAGE_SCHEMA 草稿跳过 recipe 门禁")); + } + List messages = new ArrayList<>(); + Object recipeValue = metadata.get("pageRecipe"); + Object blueprintValue = metadata.get("pageBlueprint"); + Object versionValue = metadata.get("pageBlueprintVersion"); + if (!(recipeValue instanceof String recipe) || recipe.isBlank()) { + messages.add("pageRecipe metadata 不能为空"); + } + if (blueprintValue == null) { + messages.add("pageBlueprint metadata 不能为空"); + } + if (!(versionValue instanceof Number)) { + messages.add("pageBlueprintVersion metadata 必须是数字"); + } + if (!messages.isEmpty()) { + return new AiGateResult("page-recipe", false, messages); + } + try { + PageBlueprint blueprint = objectMapper.convertValue(blueprintValue, PageBlueprint.class); + if (!recipeValue.equals(blueprint.recipe())) { + messages.add("pageRecipe 与 pageBlueprint.recipe 不一致"); + } + if (!targetId.equals(blueprint.templateId())) { + messages.add("targetId 与 pageBlueprint.templateId 不一致"); + } + if (((Number) versionValue).intValue() != blueprint.schemaVersion()) { + messages.add("pageBlueprintVersion 与 pageBlueprint.schemaVersion 不一致"); + } + if (!messages.isEmpty()) { + return new AiGateResult("page-recipe", false, messages); + } + PageRecipeValidationReport report = pageRecipeValidator.validate(blueprint, schema); + return new AiGateResult("page-recipe", report.valid(), report.messages()); + } catch (IllegalArgumentException ex) { + return new AiGateResult("page-recipe", false, List.of("pageBlueprint metadata 解析失败: " + ex.getMessage())); + } + } + private TypedPageSchemaReport validateTypedPageSchema(JsonNode schema) { try { return typedSchemaValidator.validate(schema == null ? "null" : objectMapper.writeValueAsString(schema)); @@ -800,13 +850,15 @@ public class AiAgentService { return issue.path() + " " + issue.code() + ": " + issue.message(); } - private List validateDraft(AiArtifactType type, String targetId, JsonNode payload) { + private List validateDraft(AiArtifactType type, String targetId, JsonNode payload, + Map metadata) { List gates = new ArrayList<>(); gates.add(requiredFieldsGate(type, targetId, payload)); switch (type) { case PAGE_SCHEMA -> { gates.add(validateSchemaGate(payload)); gates.add(validateTypedPageSchemaGate(payload)); + gates.add(validatePageRecipeGate(targetId, payload, metadata)); } case ENTITY -> gates.add(validateEntityGate(payload)); case SERVICEFLOW -> gates.add(validateServiceFlowGate(payload)); diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/DeterministicAiAgentRepairExecutor.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/DeterministicAiAgentRepairExecutor.java index 8dd193b..d6739ce 100644 --- a/platform-ai/src/main/java/com/eip4/platform/ai/service/DeterministicAiAgentRepairExecutor.java +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/DeterministicAiAgentRepairExecutor.java @@ -1,6 +1,7 @@ package com.eip4.platform.ai.service; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -251,7 +252,7 @@ public class DeterministicAiAgentRepairExecutor implements AiAgentRepairExecutor AiArtifactType.PAGE_SCHEMA, draft.targetId(), copy, - Map.of( + repairMetadata(draft, "source", "deterministic-agent-repair", "repairActionId", action.id(), "supersedesDraftId", draft.id()))); @@ -318,4 +319,15 @@ public class DeterministicAiAgentRepairExecutor implements AiAgentRepairExecutor Object value = action.details() == null ? null : action.details().get(key); return value == null ? "" : String.valueOf(value); } + + private static Map repairMetadata(AiDraft draft, Object... entries) { + Map out = new LinkedHashMap<>(); + if (draft.metadata() != null) { + out.putAll(draft.metadata()); + } + for (int i = 0; i + 1 < entries.length; i += 2) { + out.put(String.valueOf(entries[i]), entries[i + 1]); + } + return Map.copyOf(out); + } } diff --git a/platform-ai/src/main/resources/ai/page-recipes/maintenance-crud-v1.yaml b/platform-ai/src/main/resources/ai/page-recipes/maintenance-crud-v1.yaml index 13bc47a..95ed2fe 100644 --- a/platform-ai/src/main/resources/ai/page-recipes/maintenance-crud-v1.yaml +++ b/platform-ai/src/main/resources/ai/page-recipes/maintenance-crud-v1.yaml @@ -43,6 +43,7 @@ fieldMappings: datetime: input-datetime boolean: switch gates: + - page-recipe - typed-page-schema - amis-schema - local-smoke diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/service/AiAgentServiceTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiAgentServiceTest.java index ed82d28..e0a992e 100644 --- a/platform-ai/src/test/java/com/eip4/platform/ai/service/AiAgentServiceTest.java +++ b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiAgentServiceTest.java @@ -21,6 +21,7 @@ import com.eip4.platform.ai.model.AiRepairDraftPatch; import com.eip4.platform.ai.store.InMemoryAiAgentStore; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; class AiAgentServiceTest { @@ -123,6 +124,10 @@ class AiAgentServiceTest { assertEquals(5, result.drafts().size()); assertTrue(result.drafts().stream().allMatch(d -> d.passed()), "自动生成草稿必须全部过基础门禁"); + assertTrue(result.drafts().stream() + .filter(d -> d.artifactType() == AiArtifactType.PAGE_SCHEMA) + .flatMap(d -> d.gates().stream()) + .anyMatch(g -> "page-recipe".equals(g.name()) && g.passed())); assertEquals("READY_FOR_REVIEW", result.changeSet().status()); assertEquals(5, result.changeSet().draftIds().size()); assertEquals(5, service.listDrafts(result.task().id()).size()); @@ -170,6 +175,25 @@ class AiAgentServiceTest { assertEquals(1, service.listRevisions(result.task().id()).size()); } + @Test + @DisplayName("声明 PageBlueprint 的页面草稿必须匹配 recipe 编译结果") + void pageRecipeGateRejectsTamperedSchema() { + AiAgentService service = newService(); + var generated = new AiFeatureDraftGenerator(MAPPER).generate(contractTypeFeature()).stream() + .filter(d -> d.artifactType() == AiArtifactType.PAGE_SCHEMA) + .findFirst().orElseThrow(); + ObjectNode tampered = generated.payload().deepCopy(); + tampered.put("title", "被篡改标题"); + var task = service.createTask("验证 page recipe 门禁"); + + var draft = service.addDraft(task.id(), "PAGE_SCHEMA", generated.targetId(), tampered, generated.metadata()); + + assertFalse(draft.passed()); + assertTrue(draft.gates().stream() + .anyMatch(g -> "page-recipe".equals(g.name()) && !g.passed() + && g.messages().toString().contains("$.title"))); + } + @Test @DisplayName("一键自动开发会串联草稿生成、本地应用、smoke 和部署包") void autoDevelopFeatureRunsFullPipeline() { diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageBlueprintCompiler.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageBlueprintCompiler.java index a39ee5e..a8ad36e 100644 --- a/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageBlueprintCompiler.java +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageBlueprintCompiler.java @@ -164,9 +164,21 @@ public final class PageBlueprintCompiler { required(blueprint.entityName(), "entityName"); required(blueprint.primaryKey(), "primaryKey"); required(blueprint.displayField(), "displayField"); - if (blueprint.fields().isEmpty()) { + if (blueprint.fields() == null || blueprint.fields().isEmpty()) { throw new IllegalArgumentException("fields must not be empty"); } + boolean displayFieldExists = false; + for (PageBlueprintField field : blueprint.fields()) { + required(field.name(), "field.name"); + required(field.label(), "field.label"); + required(field.type(), "field.type"); + if (field.name().equals(blueprint.displayField())) { + displayFieldExists = true; + } + } + if (!displayFieldExists) { + throw new IllegalArgumentException("displayField must match one blueprint field"); + } if (blueprint.pageSize() < 1 || blueprint.pageSize() > 200) { throw new IllegalArgumentException("pageSize must be between 1 and 200"); } diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeDefinition.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeDefinition.java new file mode 100644 index 0000000..a4b17e6 --- /dev/null +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeDefinition.java @@ -0,0 +1,24 @@ +package com.eip4.platform.metadata.schema.blueprint; + +import java.util.List; +import java.util.Map; + +public record PageRecipeDefinition( + String recipe, + int schemaVersion, + String title, + Map fieldMappings, + List gates) { + + public PageRecipeDefinition { + if (recipe == null || recipe.isBlank()) { + throw new IllegalArgumentException("recipe is required"); + } + if (schemaVersion < 1) { + throw new IllegalArgumentException("schemaVersion must be positive"); + } + title = title == null ? "" : title; + fieldMappings = Map.copyOf(fieldMappings == null ? Map.of() : fieldMappings); + gates = List.copyOf(gates == null ? List.of() : gates); + } +} diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeRegistry.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeRegistry.java new file mode 100644 index 0000000..0582ad7 --- /dev/null +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeRegistry.java @@ -0,0 +1,66 @@ +package com.eip4.platform.metadata.schema.blueprint; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public final class PageRecipeRegistry { + + private final Map recipes; + + public PageRecipeRegistry(List definitions) { + Map ordered = new LinkedHashMap<>(); + for (PageRecipeDefinition definition : definitions == null ? List.of() : definitions) { + PageRecipeDefinition previous = ordered.put(definition.recipe(), definition); + if (previous != null) { + throw new IllegalArgumentException("Duplicate page recipe: " + definition.recipe()); + } + } + this.recipes = Map.copyOf(ordered); + } + + public static PageRecipeRegistry defaults() { + return new PageRecipeRegistry(List.of(maintenanceCrud())); + } + + public Optional find(String recipe) { + if (recipe == null || recipe.isBlank()) { + return Optional.empty(); + } + return Optional.ofNullable(recipes.get(recipe)); + } + + public boolean supports(String recipe) { + return find(recipe).isPresent(); + } + + public ObjectNode compile(PageBlueprint blueprint, ObjectMapper objectMapper) { + if (!supports(blueprint == null ? null : blueprint.recipe())) { + String recipe = blueprint == null ? "" : blueprint.recipe(); + throw new IllegalArgumentException("Unsupported page recipe: " + recipe); + } + return switch (blueprint.recipe()) { + case PageBlueprint.RECIPE_MAINTENANCE_CRUD -> new PageBlueprintCompiler(objectMapper).compile(blueprint); + default -> throw new IllegalArgumentException("Unsupported page recipe: " + blueprint.recipe()); + }; + } + + private static PageRecipeDefinition maintenanceCrud() { + return new PageRecipeDefinition( + PageBlueprint.RECIPE_MAINTENANCE_CRUD, + PageBlueprint.VERSION, + "EIP4 maintenance CRUD page", + Map.of( + "string", "input-text", + "integer", "input-number", + "number", "input-number", + "date", "input-date", + "datetime", "input-datetime", + "boolean", "switch"), + List.of("page-recipe", "typed-page-schema", "amis-schema", "local-smoke", "playwright-render")); + } +} diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidationReport.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidationReport.java new file mode 100644 index 0000000..df495ce --- /dev/null +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidationReport.java @@ -0,0 +1,14 @@ +package com.eip4.platform.metadata.schema.blueprint; + +import java.util.List; + +public record PageRecipeValidationReport( + String recipe, + boolean valid, + List messages) { + + public PageRecipeValidationReport { + recipe = recipe == null ? "" : recipe; + messages = List.copyOf(messages == null ? List.of() : messages); + } +} diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidator.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidator.java new file mode 100644 index 0000000..11fd02a --- /dev/null +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidator.java @@ -0,0 +1,126 @@ +package com.eip4.platform.metadata.schema.blueprint; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public final class PageRecipeValidator { + + private final ObjectMapper objectMapper; + private final PageRecipeRegistry registry; + + public PageRecipeValidator(ObjectMapper objectMapper, PageRecipeRegistry registry) { + this.objectMapper = objectMapper; + this.registry = registry; + } + + public static PageRecipeValidator defaults() { + return new PageRecipeValidator(new ObjectMapper(), PageRecipeRegistry.defaults()); + } + + public PageRecipeValidationReport validate(PageBlueprint blueprint, JsonNode schema) { + List messages = new ArrayList<>(); + if (blueprint == null) { + return report("", List.of("pageBlueprint metadata is required when pageRecipe is declared")); + } + String recipe = blueprint.recipe(); + registry.find(recipe).ifPresentOrElse( + definition -> { + if (definition.schemaVersion() != blueprint.schemaVersion()) { + messages.add("pageBlueprintVersion 与 recipe 版本不一致: expected=" + + definition.schemaVersion() + ", actual=" + blueprint.schemaVersion()); + } + }, + () -> messages.add("未注册的 page recipe: " + recipe)); + if (schema == null || !schema.isObject()) { + messages.add("PAGE_SCHEMA payload 顶层必须是 JSON object"); + return report(recipe, messages); + } + if (messages.isEmpty()) { + try { + JsonNode expected = registry.compile(blueprint, objectMapper); + if (!expected.equals(schema)) { + String difference = firstDifference(expected, schema, "$"); + messages.add("PAGE_SCHEMA payload 与 recipe 编译结果不一致" + + (difference == null ? "" : ": " + difference)); + } + } catch (IllegalArgumentException ex) { + messages.add(ex.getMessage()); + } + } + return report(recipe, messages); + } + + private static PageRecipeValidationReport report(String recipe, List messages) { + return new PageRecipeValidationReport(recipe, messages.isEmpty(), messages.stream().limit(20).toList()); + } + + private static String firstDifference(JsonNode expected, JsonNode actual, String path) { + if (expected == null && actual == null) { + return null; + } + if (expected == null || actual == null) { + return path + " expected=" + valueSummary(expected) + ", actual=" + valueSummary(actual); + } + if (expected.isObject() && actual.isObject()) { + Iterator> fields = expected.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + JsonNode actualChild = actual.get(entry.getKey()); + if (actualChild == null) { + return child(path, entry.getKey()) + " missing"; + } + String difference = firstDifference(entry.getValue(), actualChild, child(path, entry.getKey())); + if (difference != null) { + return difference; + } + } + Iterator actualNames = actual.fieldNames(); + while (actualNames.hasNext()) { + String name = actualNames.next(); + if (!expected.has(name)) { + return child(path, name) + " unexpected=" + valueSummary(actual.get(name)); + } + } + return null; + } + if (expected.isArray() && actual.isArray()) { + if (expected.size() != actual.size()) { + return path + " array size expected=" + expected.size() + ", actual=" + actual.size(); + } + for (int i = 0; i < expected.size(); i++) { + String difference = firstDifference(expected.get(i), actual.get(i), path + "[" + i + "]"); + if (difference != null) { + return difference; + } + } + return null; + } + if (!expected.equals(actual)) { + return path + " expected=" + valueSummary(expected) + ", actual=" + valueSummary(actual); + } + return null; + } + + private static String child(String path, String field) { + if (field.matches("[A-Za-z_][A-Za-z0-9_]*")) { + return path + "." + field; + } + return path + "['" + field.replace("'", "\\'") + "']"; + } + + private static String valueSummary(JsonNode node) { + if (node == null || node.isNull()) { + return "null"; + } + String text = node.isTextual() ? node.asText() : node.toString(); + if (text.length() > 80) { + return text.substring(0, 77) + "..."; + } + return text; + } +} diff --git a/platform-metadata/src/test/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidatorTest.java b/platform-metadata/src/test/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidatorTest.java new file mode 100644 index 0000000..636c571 --- /dev/null +++ b/platform-metadata/src/test/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidatorTest.java @@ -0,0 +1,61 @@ +package com.eip4.platform.metadata.schema.blueprint; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; + +class PageRecipeValidatorTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + private final PageRecipeValidator validator = new PageRecipeValidator(MAPPER, PageRecipeRegistry.defaults()); + + @Test + @DisplayName("page recipe 校验接受 compiler 标准输出") + void acceptsCompiledRecipeOutput() { + PageBlueprint blueprint = blueprint(); + ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint); + + PageRecipeValidationReport report = validator.validate(blueprint, schema); + + assertTrue(report.valid()); + } + + @Test + @DisplayName("page recipe 校验拒绝被篡改的 schema") + void rejectsSchemaThatDiffersFromCompilerOutput() { + PageBlueprint blueprint = blueprint(); + ObjectNode schema = new PageBlueprintCompiler(MAPPER).compile(blueprint); + schema.put("title", "被篡改标题"); + + PageRecipeValidationReport report = validator.validate(blueprint, schema); + + assertFalse(report.valid()); + assertTrue(report.messages().get(0).contains("$.title")); + } + + private static PageBlueprint blueprint() { + return new PageBlueprint( + PageBlueprint.VERSION, + PageBlueprint.RECIPE_MAINTENANCE_CRUD, + "eip4ai-contract-type", + "合同类型维护", + "EIP4AI_CONTRACT_TYPE", + "合同类型", + "EIP4AI_CONTRACT_TYPE_ID", + "NAME", + List.of( + new PageBlueprintField("NAME", "名称", "string", true, true, true), + new PageBlueprintField("ENABLED", "启用", "boolean", false, true, true)), + true, + true, + true, + 20); + } +}