feat: enforce AI page recipe gate

This commit is contained in:
2026-06-17 12:33:09 +08:00
parent e55072598e
commit fcc5719bc6
12 changed files with 414 additions and 11 deletions

View File

@@ -104,7 +104,7 @@ curl -X POST http://localhost:8093/api/ai/features/auto-develop \
1. 创建 `AiTask`。 1. 创建 `AiTask`。
2. 生成 `ENTITY`、`PAGE_SCHEMA`、`SERVICEFLOW`、`MENU`、`TEST` 草稿。`PAGE_SCHEMA` 2. 生成 `ENTITY`、`PAGE_SCHEMA`、`SERVICEFLOW`、`MENU`、`TEST` 草稿。`PAGE_SCHEMA`
先生成 EIP4 PageBlueprint,再由平台编译器输出 amis schema;草稿 metadata 保留 blueprint 证据。 先生成 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`。 4. 生成待人审 `AiChangeSet`。
5. 生成 release plan。 5. 生成 release plan。
6. 本地 apply:实体走本机 `/api/meta/entity`,页面/服务流写本地库;如果本地最小库缺少 `sys_menu`,菜单发布标记为 `SKIPPED`,不阻断本地 gate,部署包仍保留菜单 SQL 供线上人审。 6. 本地 apply:实体走本机 `/api/meta/entity`,页面/服务流写本地库;如果本地最小库缺少 `sys_menu`,菜单发布标记为 `SKIPPED`,不阻断本地 gate,部署包仍保留菜单 SQL 供线上人审。

View File

@@ -23,6 +23,11 @@ AI 自动开发链路中的 `PAGE_SCHEMA` 草稿仍然保存编译后的 amis sc
- `pageBlueprintVersion` - `pageBlueprintVersion`
- `pageBlueprint` - `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 ## Recipe: maintenance-crud-v1
适用范围: 适用范围:
@@ -73,10 +78,16 @@ AI 自动开发链路中的 `PAGE_SCHEMA` 草稿仍然保存编译后的 amis sc
这些类型必须作为新的 recipe 增量加入,不能让 Agent 直接绕过 blueprint 生成最终 amis JSON。 这些类型必须作为新的 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。 1. 增加 `master-detail-v1`、`tree-crud-v1`、`approval-task-v1` recipe。
2. 增加 `master-detail-v1`、`tree-crud-v1`、`approval-task-v1` recipe。 2. 让设计器 overlay 保存也能记录对应 blueprint 或 template 来源。
3. 让设计器 overlay 保存也能记录对应 blueprint 或 template 来源。 3. 在功能包中导出 blueprint,线上部署包继续导出编译后的 amis schema。
4. 在功能包中导出 blueprint,线上部署包继续导出编译后的 amis schema。 4. Playwright E2E 从 recipe 反推出应验证的 UI 行为。
5. Playwright E2E 从 recipe 反推出应验证的 UI 行为。

View File

@@ -61,6 +61,10 @@ import com.eip4.platform.metadata.schema.PageComponentRegistry;
import com.eip4.platform.metadata.schema.TypedPageSchemaIssue; import com.eip4.platform.metadata.schema.TypedPageSchemaIssue;
import com.eip4.platform.metadata.schema.TypedPageSchemaReport; import com.eip4.platform.metadata.schema.TypedPageSchemaReport;
import com.eip4.platform.metadata.schema.TypedPageSchemaValidator; 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.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
@@ -86,6 +90,7 @@ public class AiAgentService {
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final AiToolRegistry toolRegistry; private final AiToolRegistry toolRegistry;
private final TypedPageSchemaValidator typedSchemaValidator; private final TypedPageSchemaValidator typedSchemaValidator;
private final PageRecipeValidator pageRecipeValidator;
private static volatile SchemaGate sharedSchemaGate; private static volatile SchemaGate sharedSchemaGate;
private volatile SchemaGate schemaGate; private volatile SchemaGate schemaGate;
@@ -122,6 +127,7 @@ public class AiAgentService {
this.typedSchemaValidator = typedSchemaValidator == null this.typedSchemaValidator = typedSchemaValidator == null
? new TypedPageSchemaValidator(objectMapper, PageComponentRegistry.defaults()) ? new TypedPageSchemaValidator(objectMapper, PageComponentRegistry.defaults())
: typedSchemaValidator; : typedSchemaValidator;
this.pageRecipeValidator = new PageRecipeValidator(objectMapper, PageRecipeRegistry.defaults());
} }
public AiTask createTask(String objective) { public AiTask createTask(String objective) {
@@ -154,7 +160,8 @@ public class AiAgentService {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "payload 不能为空"); throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "payload 不能为空");
} }
List<AiGateResult> gates = validateDraft(artifactType, target, payload); Map<String, Object> safeMetadata = metadata == null ? Map.of() : metadata;
List<AiGateResult> gates = validateDraft(artifactType, target, payload, safeMetadata);
AiDraft draft = new AiDraft( AiDraft draft = new AiDraft(
"aid-" + UUID.randomUUID(), "aid-" + UUID.randomUUID(),
taskId, taskId,
@@ -163,7 +170,7 @@ public class AiAgentService {
payload, payload,
System.currentTimeMillis(), System.currentTimeMillis(),
gates, gates,
metadata == null ? Map.of() : Map.copyOf(metadata)); Map.copyOf(safeMetadata));
store.saveDraft(draft); store.saveDraft(draft);
audit(taskId, "draft.saved", "agent", Map.of( audit(taskId, "draft.saved", "agent", Map.of(
"draftId", draft.id(), "draftId", draft.id(),
@@ -781,6 +788,49 @@ public class AiAgentService {
return new AiGateResult("typed-page-schema", report.valid(), typedMessages(report)); return new AiGateResult("typed-page-schema", report.valid(), typedMessages(report));
} }
private AiGateResult validatePageRecipeGate(String targetId, JsonNode schema, Map<String, Object> 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<String> 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) { private TypedPageSchemaReport validateTypedPageSchema(JsonNode schema) {
try { try {
return typedSchemaValidator.validate(schema == null ? "null" : objectMapper.writeValueAsString(schema)); return typedSchemaValidator.validate(schema == null ? "null" : objectMapper.writeValueAsString(schema));
@@ -800,13 +850,15 @@ public class AiAgentService {
return issue.path() + " " + issue.code() + ": " + issue.message(); return issue.path() + " " + issue.code() + ": " + issue.message();
} }
private List<AiGateResult> validateDraft(AiArtifactType type, String targetId, JsonNode payload) { private List<AiGateResult> validateDraft(AiArtifactType type, String targetId, JsonNode payload,
Map<String, Object> metadata) {
List<AiGateResult> gates = new ArrayList<>(); List<AiGateResult> gates = new ArrayList<>();
gates.add(requiredFieldsGate(type, targetId, payload)); gates.add(requiredFieldsGate(type, targetId, payload));
switch (type) { switch (type) {
case PAGE_SCHEMA -> { case PAGE_SCHEMA -> {
gates.add(validateSchemaGate(payload)); gates.add(validateSchemaGate(payload));
gates.add(validateTypedPageSchemaGate(payload)); gates.add(validateTypedPageSchemaGate(payload));
gates.add(validatePageRecipeGate(targetId, payload, metadata));
} }
case ENTITY -> gates.add(validateEntityGate(payload)); case ENTITY -> gates.add(validateEntityGate(payload));
case SERVICEFLOW -> gates.add(validateServiceFlowGate(payload)); case SERVICEFLOW -> gates.add(validateServiceFlowGate(payload));

View File

@@ -1,6 +1,7 @@
package com.eip4.platform.ai.service; package com.eip4.platform.ai.service;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -251,7 +252,7 @@ public class DeterministicAiAgentRepairExecutor implements AiAgentRepairExecutor
AiArtifactType.PAGE_SCHEMA, AiArtifactType.PAGE_SCHEMA,
draft.targetId(), draft.targetId(),
copy, copy,
Map.of( repairMetadata(draft,
"source", "deterministic-agent-repair", "source", "deterministic-agent-repair",
"repairActionId", action.id(), "repairActionId", action.id(),
"supersedesDraftId", draft.id()))); "supersedesDraftId", draft.id())));
@@ -318,4 +319,15 @@ public class DeterministicAiAgentRepairExecutor implements AiAgentRepairExecutor
Object value = action.details() == null ? null : action.details().get(key); Object value = action.details() == null ? null : action.details().get(key);
return value == null ? "" : String.valueOf(value); return value == null ? "" : String.valueOf(value);
} }
private static Map<String, Object> repairMetadata(AiDraft draft, Object... entries) {
Map<String, Object> 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);
}
} }

View File

@@ -43,6 +43,7 @@ fieldMappings:
datetime: input-datetime datetime: input-datetime
boolean: switch boolean: switch
gates: gates:
- page-recipe
- typed-page-schema - typed-page-schema
- amis-schema - amis-schema
- local-smoke - local-smoke

View File

@@ -21,6 +21,7 @@ import com.eip4.platform.ai.model.AiRepairDraftPatch;
import com.eip4.platform.ai.store.InMemoryAiAgentStore; import com.eip4.platform.ai.store.InMemoryAiAgentStore;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
class AiAgentServiceTest { class AiAgentServiceTest {
@@ -123,6 +124,10 @@ class AiAgentServiceTest {
assertEquals(5, result.drafts().size()); assertEquals(5, result.drafts().size());
assertTrue(result.drafts().stream().allMatch(d -> d.passed()), "自动生成草稿必须全部过基础门禁"); 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("READY_FOR_REVIEW", result.changeSet().status());
assertEquals(5, result.changeSet().draftIds().size()); assertEquals(5, result.changeSet().draftIds().size());
assertEquals(5, service.listDrafts(result.task().id()).size()); assertEquals(5, service.listDrafts(result.task().id()).size());
@@ -170,6 +175,25 @@ class AiAgentServiceTest {
assertEquals(1, service.listRevisions(result.task().id()).size()); 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 @Test
@DisplayName("一键自动开发会串联草稿生成、本地应用、smoke 和部署包") @DisplayName("一键自动开发会串联草稿生成、本地应用、smoke 和部署包")
void autoDevelopFeatureRunsFullPipeline() { void autoDevelopFeatureRunsFullPipeline() {

View File

@@ -164,9 +164,21 @@ public final class PageBlueprintCompiler {
required(blueprint.entityName(), "entityName"); required(blueprint.entityName(), "entityName");
required(blueprint.primaryKey(), "primaryKey"); required(blueprint.primaryKey(), "primaryKey");
required(blueprint.displayField(), "displayField"); required(blueprint.displayField(), "displayField");
if (blueprint.fields().isEmpty()) { if (blueprint.fields() == null || blueprint.fields().isEmpty()) {
throw new IllegalArgumentException("fields must not be empty"); 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) { if (blueprint.pageSize() < 1 || blueprint.pageSize() > 200) {
throw new IllegalArgumentException("pageSize must be between 1 and 200"); throw new IllegalArgumentException("pageSize must be between 1 and 200");
} }

View File

@@ -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<String, String> fieldMappings,
List<String> 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);
}
}

View File

@@ -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<String, PageRecipeDefinition> recipes;
public PageRecipeRegistry(List<PageRecipeDefinition> definitions) {
Map<String, PageRecipeDefinition> ordered = new LinkedHashMap<>();
for (PageRecipeDefinition definition : definitions == null ? List.<PageRecipeDefinition>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<PageRecipeDefinition> 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"));
}
}

View File

@@ -0,0 +1,14 @@
package com.eip4.platform.metadata.schema.blueprint;
import java.util.List;
public record PageRecipeValidationReport(
String recipe,
boolean valid,
List<String> messages) {
public PageRecipeValidationReport {
recipe = recipe == null ? "" : recipe;
messages = List.copyOf(messages == null ? List.of() : messages);
}
}

View File

@@ -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<String> 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<String> 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<Map.Entry<String, JsonNode>> fields = expected.fields();
while (fields.hasNext()) {
Map.Entry<String, JsonNode> 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<String> 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;
}
}

View File

@@ -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);
}
}