Merge feat/ai-agent-service-split: AiAgentService SRP 收窄(§10.2,抽 SQL/门禁两簇)
Some checks failed
ci / build-test-parity (push) Has been cancelled
Some checks failed
ci / build-test-parity (push) Has been cancelled
1846→1329 行(-28%):部署/回滚 SQL 簇→AiDeploymentSqlBuilder、草稿门禁电池→AiDraftGateValidator,各带黄金/直测;行为零变更(platform-ai 79 全绿),全 reactor mvn clean install 绿。AiRunStore 丢弃(持久化已在 AiAgentStore)。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,12 +1,8 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Comparator;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -14,15 +10,12 @@ import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.xml.sax.InputSource;
|
||||
|
||||
import com.eip4.platform.ai.model.AiApplyRun;
|
||||
import com.eip4.platform.ai.model.AiApplyStepResult;
|
||||
@@ -56,17 +49,12 @@ import com.eip4.platform.ai.model.AiToolAccessRequest;
|
||||
import com.eip4.platform.ai.model.AiToolDefinition;
|
||||
import com.eip4.platform.ai.model.AiEmployeeDefinition;
|
||||
import com.eip4.platform.ai.store.AiAgentStore;
|
||||
import com.eip4.platform.converter.SchemaGate;
|
||||
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.PageRecipeDefinition;
|
||||
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;
|
||||
|
||||
@@ -78,10 +66,6 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
@Service
|
||||
public class AiAgentService {
|
||||
|
||||
private static final Pattern TABLE_NAME = Pattern.compile("[A-Z][A-Z0-9_]{2,40}");
|
||||
private static final Pattern FLOW_KEY = Pattern.compile("[A-Z][A-Z0-9_]{2,80}");
|
||||
private static final Pattern COLUMN_NAME = Pattern.compile("[A-Z][A-Z0-9_]{0,39}");
|
||||
private static final Pattern HTTP_METHOD = Pattern.compile("GET|POST|PUT|DELETE|PATCH");
|
||||
|
||||
private final AiAgentStore store;
|
||||
private final AiFeatureDraftGenerator featureDraftGenerator;
|
||||
@@ -93,9 +77,11 @@ public class AiAgentService {
|
||||
private final TypedPageSchemaValidator typedSchemaValidator;
|
||||
private final PageRecipeRegistry pageRecipeRegistry;
|
||||
private final PageRecipeValidator pageRecipeValidator;
|
||||
/** 部署/回滚 SQL 生成已抽出(§10.2 SRP slice 1);本类只编排,不再内联 SQL 文本。 */
|
||||
private final AiDeploymentSqlBuilder sqlBuilder;
|
||||
/** 草稿门禁电池已抽出(§10.2 SRP slice 2);本类只编排,不再内联各类 validate*Gate 判定。 */
|
||||
private final AiDraftGateValidator gateValidator;
|
||||
|
||||
private static volatile SchemaGate sharedSchemaGate;
|
||||
private volatile SchemaGate schemaGate;
|
||||
|
||||
@Autowired
|
||||
public AiAgentService(AiAgentStore store, AiFeatureDraftGenerator featureDraftGenerator,
|
||||
@@ -131,6 +117,9 @@ public class AiAgentService {
|
||||
: typedSchemaValidator;
|
||||
this.pageRecipeRegistry = PageRecipeRegistry.defaults();
|
||||
this.pageRecipeValidator = new PageRecipeValidator(objectMapper, pageRecipeRegistry);
|
||||
this.sqlBuilder = new AiDeploymentSqlBuilder(objectMapper);
|
||||
this.gateValidator = new AiDraftGateValidator(
|
||||
objectMapper, this.typedSchemaValidator, this.pageRecipeRegistry, this.pageRecipeValidator);
|
||||
}
|
||||
|
||||
public AiTask createTask(String objective) {
|
||||
@@ -164,7 +153,7 @@ public class AiAgentService {
|
||||
}
|
||||
|
||||
Map<String, Object> safeMetadata = metadata == null ? Map.of() : metadata;
|
||||
List<AiGateResult> gates = validateDraft(artifactType, target, payload, safeMetadata);
|
||||
List<AiGateResult> gates = gateValidator.validateDraft(artifactType, target, payload, safeMetadata);
|
||||
AiDraft draft = new AiDraft(
|
||||
"aid-" + UUID.randomUUID(),
|
||||
taskId,
|
||||
@@ -515,8 +504,8 @@ public class AiAgentService {
|
||||
true,
|
||||
generatedAt,
|
||||
manifest,
|
||||
deploymentSql(drafts, entityId, menuIds, generatedAt),
|
||||
rollbackSql(drafts, generatedAt),
|
||||
sqlBuilder.deploymentSql(drafts, entityId, menuIds, generatedAt),
|
||||
sqlBuilder.rollbackSql(drafts, generatedAt),
|
||||
List.copyOf(warnings),
|
||||
List.copyOf(runs));
|
||||
audit(taskId, "deployment-package.generated", "agent", Map.of(
|
||||
@@ -742,9 +731,9 @@ public class AiAgentService {
|
||||
}
|
||||
|
||||
public Map<String, Object> validateSchema(JsonNode schema) {
|
||||
AiGateResult schemaGate = validateSchemaGate(schema);
|
||||
TypedPageSchemaReport typedReport = validateTypedPageSchema(schema);
|
||||
List<String> typedMessages = typedMessages(typedReport);
|
||||
AiGateResult schemaGate = gateValidator.validateSchemaGate(schema);
|
||||
TypedPageSchemaReport typedReport = gateValidator.validateTypedPageSchema(schema);
|
||||
List<String> typedMessages = AiDraftGateValidator.typedMessages(typedReport);
|
||||
List<String> validationErrors = new ArrayList<>();
|
||||
validationErrors.addAll(schemaGate.messages());
|
||||
validationErrors.addAll(typedMessages);
|
||||
@@ -798,342 +787,6 @@ public class AiAgentService {
|
||||
}
|
||||
}
|
||||
|
||||
private AiGateResult validateSchemaGate(JsonNode schema) {
|
||||
if (schema == null || !schema.isObject()) {
|
||||
return new AiGateResult("amis-schema", false, List.of("schema 顶层必须是 JSON object"));
|
||||
}
|
||||
List<String> errors = getSchemaGate().validate(schema);
|
||||
return new AiGateResult("amis-schema", errors.isEmpty(), errors.stream().limit(20).toList());
|
||||
}
|
||||
|
||||
private AiGateResult validateTypedPageSchemaGate(JsonNode schema) {
|
||||
TypedPageSchemaReport report = validateTypedPageSchema(schema);
|
||||
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) {
|
||||
try {
|
||||
return typedSchemaValidator.validate(schema == null ? "null" : objectMapper.writeValueAsString(schema));
|
||||
} catch (JsonProcessingException ex) {
|
||||
return typedSchemaValidator.validate("");
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> typedMessages(TypedPageSchemaReport report) {
|
||||
return report.issues().stream()
|
||||
.limit(20)
|
||||
.map(AiAgentService::typedMessage)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static String typedMessage(TypedPageSchemaIssue issue) {
|
||||
return issue.path() + " " + issue.code() + ": " + issue.message();
|
||||
}
|
||||
|
||||
private List<AiGateResult> validateDraft(AiArtifactType type, String targetId, JsonNode payload,
|
||||
Map<String, Object> metadata) {
|
||||
List<AiGateResult> 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));
|
||||
case MENU -> gates.add(validateMenuGate(payload));
|
||||
case TEST -> {
|
||||
gates.add(validateTestGate(payload));
|
||||
gates.add(validateRenderPlanGate(payload));
|
||||
}
|
||||
case CODE -> gates.add(new AiGateResult("code-review-required", true, List.of("代码草稿需后续静态检查/单测门禁")));
|
||||
}
|
||||
return List.copyOf(gates);
|
||||
}
|
||||
|
||||
private AiGateResult requiredFieldsGate(AiArtifactType type, String targetId, JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
if (targetId == null || targetId.isBlank()) {
|
||||
messages.add("targetId 不能为空");
|
||||
}
|
||||
if (payload == null || !payload.isObject()) {
|
||||
messages.add(type.name() + " payload 顶层必须是 JSON object");
|
||||
}
|
||||
return new AiGateResult("draft-required-fields", messages.isEmpty(), List.copyOf(messages));
|
||||
}
|
||||
|
||||
private AiGateResult validateEntityGate(JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
String table = payload.path("tablename").asText("");
|
||||
if (!TABLE_NAME.matcher(table).matches()) {
|
||||
messages.add("tablename 必须是 3-40 位大写字母数字下划线,且以字母开头");
|
||||
}
|
||||
if (payload.path("name").asText("").isBlank()) {
|
||||
messages.add("name 不能为空");
|
||||
}
|
||||
JsonNode attrs = payload.path("attributes");
|
||||
if (!attrs.isArray() || attrs.isEmpty()) {
|
||||
messages.add("attributes 至少需要 1 个业务字段");
|
||||
} else {
|
||||
for (JsonNode attr : attrs) {
|
||||
String col = attr.path("column").asText("");
|
||||
if (!COLUMN_NAME.matcher(col).matches()) {
|
||||
messages.add("字段 column 不合法: " + col);
|
||||
}
|
||||
String type = attr.path("type").asText("");
|
||||
if (!List.of("string", "integer", "number", "date", "datetime", "boolean").contains(type)) {
|
||||
messages.add("字段 " + col + " type 不支持: " + type);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new AiGateResult("entity-meta", messages.isEmpty(), messages.stream().limit(20).toList());
|
||||
}
|
||||
|
||||
private AiGateResult validateServiceFlowGate(JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
JsonNode flows = payload.path("flows");
|
||||
if (!flows.isArray() || flows.isEmpty()) {
|
||||
messages.add("flows 至少需要 1 个服务流定义");
|
||||
} else {
|
||||
for (JsonNode flow : flows) {
|
||||
String key = flow.path("key").asText("");
|
||||
if (!FLOW_KEY.matcher(key).matches()) {
|
||||
messages.add("服务流 key 不合法: " + key);
|
||||
}
|
||||
String xml = flow.path("contentXml").asText("");
|
||||
if (!isValidFlowXml(xml)) {
|
||||
messages.add("服务流 XML 不合法: " + key);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new AiGateResult("serviceflow-xml", messages.isEmpty(), messages.stream().limit(20).toList());
|
||||
}
|
||||
|
||||
private AiGateResult validateMenuGate(JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
if (payload.path("name").asText("").isBlank()) {
|
||||
messages.add("菜单 name 不能为空");
|
||||
}
|
||||
if (payload.path("viewTemplateId").asText("").isBlank()) {
|
||||
messages.add("菜单 viewTemplateId 不能为空");
|
||||
}
|
||||
return new AiGateResult("menu-binding", messages.isEmpty(), List.copyOf(messages));
|
||||
}
|
||||
|
||||
private AiGateResult validateTestGate(JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
JsonNode tests = payload.path("smokeTests");
|
||||
if (!tests.isArray() || tests.isEmpty()) {
|
||||
messages.add("smokeTests 至少需要 1 条");
|
||||
} else {
|
||||
for (JsonNode test : tests) {
|
||||
String method = test.path("method").asText("");
|
||||
String url = test.path("url").asText("");
|
||||
if (!HTTP_METHOD.matcher(method).matches()) {
|
||||
messages.add("smoke method 不合法: " + method);
|
||||
}
|
||||
if (!url.startsWith("/api/")) {
|
||||
messages.add("smoke url 必须以 /api/ 开头: " + url);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new AiGateResult("smoke-plan", messages.isEmpty(), messages.stream().limit(20).toList());
|
||||
}
|
||||
|
||||
private AiGateResult validateRenderPlanGate(JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
JsonNode tests = payload.path("renderTests");
|
||||
if (!tests.isArray() || tests.isEmpty()) {
|
||||
messages.add("renderTests 至少需要 1 条");
|
||||
} else {
|
||||
for (JsonNode test : tests) {
|
||||
String name = test.path("name").asText("");
|
||||
String recipe = test.path("recipe").asText("");
|
||||
String schemaUrl = test.path("schemaUrl").asText("");
|
||||
String previewUrl = test.path("previewUrl").asText("");
|
||||
String rootType = test.path("expectedRootType").asText("");
|
||||
String bodyType = test.path("expectedBodyType").asText("");
|
||||
String crudName = test.path("expectedCrudName").asText("");
|
||||
String expectedApi = test.path("expectedApi").asText("");
|
||||
JsonNode components = test.path("expectedComponents");
|
||||
JsonNode columns = test.path("expectedColumns");
|
||||
JsonNode actions = test.path("expectedActions");
|
||||
JsonNode texts = test.path("expectedTexts");
|
||||
if (name.isBlank()) {
|
||||
messages.add("render name 不能为空");
|
||||
}
|
||||
if (pageRecipeRegistry.find(recipe).isEmpty()) {
|
||||
messages.add("render recipe 未注册: " + recipe);
|
||||
}
|
||||
if (!schemaUrl.startsWith("/api/page/schema/")) {
|
||||
messages.add("render schemaUrl 必须以 /api/page/schema/ 开头: " + schemaUrl);
|
||||
}
|
||||
if (!previewUrl.startsWith("/amis.html?schema=")
|
||||
&& !previewUrl.startsWith("/amis.html?templateId=")
|
||||
&& !previewUrl.startsWith("/amis.html?schemaUrl=")) {
|
||||
messages.add("render previewUrl 必须指向可解析 schema 的 /amis.html: " + previewUrl);
|
||||
}
|
||||
if (!"page".equals(rootType)) {
|
||||
messages.add("render expectedRootType 必须是 page");
|
||||
}
|
||||
if (!"crud".equals(bodyType)) {
|
||||
messages.add("render expectedBodyType 必须是 crud");
|
||||
}
|
||||
if (crudName.isBlank()) {
|
||||
messages.add("render expectedCrudName 不能为空");
|
||||
}
|
||||
// house-style 对齐:单表维护页列表走保真层服务流 _SEARCH(/api/flow),
|
||||
// 树页仍走 /api/entity 树接口。
|
||||
if (PageBlueprint.RECIPE_TREE_CRUD.equals(recipe)) {
|
||||
if (!expectedApi.startsWith("/api/entity/") || !expectedApi.contains("/tree?")) {
|
||||
messages.add("tree-crud-v1 render expectedApi 必须是 /api/entity 树接口: " + expectedApi);
|
||||
}
|
||||
} else if (PageBlueprint.RECIPE_MAINTENANCE_CRUD.equals(recipe)) {
|
||||
if (!expectedApi.startsWith("/api/flow/") || !expectedApi.endsWith("_SEARCH")) {
|
||||
messages.add("maintenance-crud-v1 render expectedApi 必须是 /api/flow 服务流 _SEARCH 接口: "
|
||||
+ expectedApi);
|
||||
}
|
||||
} else if (!expectedApi.startsWith("/api/")) {
|
||||
messages.add("render expectedApi 必须指向 /api/: " + expectedApi);
|
||||
}
|
||||
if (!components.isArray() || components.isEmpty()) {
|
||||
messages.add("render expectedComponents 至少需要 1 项");
|
||||
} else {
|
||||
if (!arrayContainsText(components, "page")) {
|
||||
messages.add("render expectedComponents 必须包含 page");
|
||||
}
|
||||
if (!arrayContainsText(components, "crud")) {
|
||||
messages.add("render expectedComponents 必须包含 crud");
|
||||
}
|
||||
}
|
||||
if (!columns.isArray() || columns.isEmpty()) {
|
||||
messages.add("render expectedColumns 至少需要 1 项");
|
||||
} else {
|
||||
for (JsonNode column : columns) {
|
||||
if (column.path("name").asText("").isBlank()) {
|
||||
messages.add("render expectedColumns.name 不能为空");
|
||||
}
|
||||
if (column.path("label").asText("").isBlank()) {
|
||||
messages.add("render expectedColumns.label 不能为空");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!actions.isArray() || actions.isEmpty()) {
|
||||
messages.add("render expectedActions 至少需要 1 项");
|
||||
} else {
|
||||
if (!arrayContainsText(actions, "新增")
|
||||
&& !arrayContainsTextStartingWith(actions, "新增顶级")) {
|
||||
messages.add("render expectedActions 必须包含新增动作");
|
||||
}
|
||||
if (!arrayContainsText(actions, "编辑")) {
|
||||
messages.add("render expectedActions 必须包含编辑动作");
|
||||
}
|
||||
if (!arrayContainsText(actions, "删除")) {
|
||||
messages.add("render expectedActions 必须包含删除动作");
|
||||
}
|
||||
}
|
||||
if (!texts.isArray() || texts.isEmpty()) {
|
||||
messages.add("render expectedTexts 至少需要 1 项");
|
||||
}
|
||||
}
|
||||
}
|
||||
return new AiGateResult("render-plan", messages.isEmpty(), messages.stream().limit(20).toList());
|
||||
}
|
||||
|
||||
private static boolean arrayContainsText(JsonNode array, String value) {
|
||||
for (JsonNode item : array) {
|
||||
if (value.equals(item.asText(""))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean arrayContainsTextStartingWith(JsonNode array, String prefix) {
|
||||
for (JsonNode item : array) {
|
||||
if (item.asText("").startsWith(prefix)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isValidFlowXml(String xml) {
|
||||
if (xml == null || xml.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
factory.setExpandEntityReferences(false);
|
||||
var builder = factory.newDocumentBuilder();
|
||||
var doc = builder.parse(new InputSource(new java.io.StringReader(xml)));
|
||||
return "flow".equals(doc.getDocumentElement().getNodeName())
|
||||
&& doc.getElementsByTagName("input").getLength() > 0
|
||||
&& doc.getElementsByTagName("transition").getLength() > 0;
|
||||
} catch (Exception ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private SchemaGate getSchemaGate() {
|
||||
if (schemaGate == null) {
|
||||
synchronized (AiAgentService.class) {
|
||||
if (sharedSchemaGate == null) {
|
||||
sharedSchemaGate = new SchemaGate();
|
||||
}
|
||||
schemaGate = sharedSchemaGate;
|
||||
}
|
||||
}
|
||||
return schemaGate;
|
||||
}
|
||||
|
||||
private void audit(String taskId, String action, String actor, Map<String, Object> details) {
|
||||
AiAuditEntry entry = new AiAuditEntry(
|
||||
"aia-" + UUID.randomUUID(),
|
||||
@@ -1566,176 +1219,6 @@ public class AiAgentService {
|
||||
return Map.copyOf(summary);
|
||||
}
|
||||
|
||||
private List<String> deploymentSql(List<AiDraft> drafts, String entityId,
|
||||
Map<String, String> menuIdsByTarget, long generatedAt) {
|
||||
List<String> out = new ArrayList<>();
|
||||
for (AiDraft draft : drafts) {
|
||||
switch (draft.artifactType()) {
|
||||
case ENTITY -> out.add(entityDeploymentNote(draft));
|
||||
case SERVICEFLOW -> out.addAll(serviceFlowSql(draft, entityId, generatedAt));
|
||||
case PAGE_SCHEMA -> out.add(pageSchemaSql(draft, generatedAt));
|
||||
case MENU -> out.add(menuSql(draft, menuIdsByTarget.get(draft.targetId()), generatedAt));
|
||||
case TEST -> out.add("-- TEST " + draft.targetId() + ": 保留 smoke 结果作为上线审批附件,不生成生产 SQL");
|
||||
case CODE -> out.add("-- CODE " + draft.targetId() + ": 代码改动需通过代码仓库发布流程,不生成运行态 SQL");
|
||||
}
|
||||
}
|
||||
return List.copyOf(out);
|
||||
}
|
||||
|
||||
private String entityDeploymentNote(AiDraft draft) {
|
||||
return "-- ENTITY " + draft.targetId()
|
||||
+ ": 人工审批后在目标环境调用 POST /api/meta/entity,payload="
|
||||
+ json(draft.payload())
|
||||
+ ";确认返回 entityId 后替换服务流 SQL 中的 ${entityId}";
|
||||
}
|
||||
|
||||
private List<String> serviceFlowSql(AiDraft draft, String entityId, long generatedAt) {
|
||||
List<String> out = new ArrayList<>();
|
||||
String resolvedEntityId = entityId == null || entityId.isBlank() ? "${entityId}" : entityId;
|
||||
for (JsonNode flow : draft.payload().path("flows")) {
|
||||
String xml = flow.path("contentXml").asText("");
|
||||
if (!entityId.isBlank()) {
|
||||
xml = xml.replace("${entityId}", entityId);
|
||||
}
|
||||
out.add("""
|
||||
INSERT INTO sys_serviceflow
|
||||
(sys_serviceflow_id, displayname, contentxml, entityid, iscontrol, isupdateable,
|
||||
isactive, createtime, updatetime, createby, updateby, version)
|
||||
VALUES (%s, %s, %s::xml, %s, %d, %d, 1, %d, %d, 'AI_AGENT', 'AI_AGENT', 0)
|
||||
ON CONFLICT (sys_serviceflow_id) DO UPDATE SET
|
||||
displayname = EXCLUDED.displayname,
|
||||
contentxml = EXCLUDED.contentxml,
|
||||
entityid = EXCLUDED.entityid,
|
||||
iscontrol = EXCLUDED.iscontrol,
|
||||
isupdateable = EXCLUDED.isupdateable,
|
||||
updatetime = EXCLUDED.updatetime,
|
||||
updateby = EXCLUDED.updateby,
|
||||
version = sys_serviceflow.version + 1;
|
||||
""".formatted(
|
||||
sqlString(flow.path("key").asText()),
|
||||
sqlString(flow.path("displayName").asText(flow.path("key").asText())),
|
||||
sqlString(xml),
|
||||
sqlString(resolvedEntityId),
|
||||
flow.path("control").asBoolean(true) ? 1 : 0,
|
||||
flow.path("updateable").asBoolean(true) ? 1 : 0,
|
||||
generatedAt,
|
||||
generatedAt));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private String pageSchemaSql(AiDraft draft, long generatedAt) {
|
||||
String schemaJson = json(draft.payload());
|
||||
return """
|
||||
INSERT INTO sys_page_schema (template_id, name, schema_json, schema_etag, version, update_time)
|
||||
VALUES (%s, %s, %s::jsonb, %s, 1, %d)
|
||||
ON CONFLICT (template_id) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
schema_json = EXCLUDED.schema_json,
|
||||
schema_etag = EXCLUDED.schema_etag,
|
||||
version = sys_page_schema.version + 1,
|
||||
update_time = EXCLUDED.update_time;
|
||||
""".formatted(
|
||||
sqlString(draft.targetId()),
|
||||
sqlString(draft.payload().path("title").asText(draft.targetId())),
|
||||
sqlString(schemaJson),
|
||||
sqlString(sha256(schemaJson)),
|
||||
generatedAt);
|
||||
}
|
||||
|
||||
private String menuSql(AiDraft draft, String appliedMenuId, long generatedAt) {
|
||||
JsonNode payload = draft.payload();
|
||||
String menuId = appliedMenuId == null || appliedMenuId.isBlank() ? "${menuId}" : appliedMenuId;
|
||||
String parentId = payload.path("parentId").asText("");
|
||||
if (parentId.isBlank()) {
|
||||
parentId = "${parentMenuId}";
|
||||
}
|
||||
String menuRoot = payload.path("menuroot").asText("");
|
||||
if (menuRoot.isBlank()) {
|
||||
menuRoot = "${menuRoot}";
|
||||
}
|
||||
return """
|
||||
INSERT INTO sys_menu
|
||||
(sys_menu_id, name, parentid, view_templateid, typename, menuroot, seq,
|
||||
isactive, version, createtime, createby, updatetime, updateby)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %d, 1, 0, %d, 'AI_AGENT', %d, 'AI_AGENT')
|
||||
ON CONFLICT (sys_menu_id) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
parentid = EXCLUDED.parentid,
|
||||
view_templateid = EXCLUDED.view_templateid,
|
||||
typename = EXCLUDED.typename,
|
||||
menuroot = EXCLUDED.menuroot,
|
||||
seq = EXCLUDED.seq,
|
||||
isactive = 1,
|
||||
updatetime = EXCLUDED.updatetime,
|
||||
updateby = EXCLUDED.updateby,
|
||||
version = sys_menu.version + 1;
|
||||
""".formatted(
|
||||
sqlString(menuId),
|
||||
sqlString(payload.path("name").asText(draft.targetId())),
|
||||
sqlString(parentId),
|
||||
sqlString(payload.path("viewTemplateId").asText(draft.targetId())),
|
||||
sqlString(payload.path("typename").asText("功能菜单")),
|
||||
sqlString(menuRoot),
|
||||
payload.path("seq").asInt(0),
|
||||
generatedAt,
|
||||
generatedAt);
|
||||
}
|
||||
|
||||
private List<String> rollbackSql(List<AiDraft> drafts, long generatedAt) {
|
||||
List<String> out = new ArrayList<>();
|
||||
for (AiDraft draft : drafts) {
|
||||
switch (draft.artifactType()) {
|
||||
case ENTITY -> out.add("-- ENTITY " + draft.targetId()
|
||||
+ ": 人工确认后调用 DELETE /api/meta/entity/" + draft.targetId()
|
||||
+ ",并清理对应菜单/服务流/页面 schema");
|
||||
case SERVICEFLOW -> out.add(serviceFlowRollbackSql(draft));
|
||||
case PAGE_SCHEMA -> out.add("DELETE FROM sys_page_schema WHERE template_id = "
|
||||
+ sqlString(draft.targetId()) + ";");
|
||||
case MENU -> out.add("""
|
||||
UPDATE sys_menu
|
||||
SET isactive = 0, updatetime = %d, updateby = 'AI_AGENT_ROLLBACK',
|
||||
version = version + 1
|
||||
WHERE TRIM(view_templateid) = %s;
|
||||
""".formatted(generatedAt, sqlString(draft.targetId())));
|
||||
case TEST -> out.add("-- TEST " + draft.targetId() + ": 无生产数据回滚动作");
|
||||
case CODE -> out.add("-- CODE " + draft.targetId() + ": 通过代码仓库反向补丁或回滚发布单处理");
|
||||
}
|
||||
}
|
||||
return List.copyOf(out);
|
||||
}
|
||||
|
||||
private String serviceFlowRollbackSql(AiDraft draft) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
for (JsonNode flow : draft.payload().path("flows")) {
|
||||
keys.add(sqlString(flow.path("key").asText()));
|
||||
}
|
||||
return "DELETE FROM sys_serviceflow WHERE sys_serviceflow_id IN ("
|
||||
+ String.join(", ", keys) + ");";
|
||||
}
|
||||
|
||||
private String json(Object value) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException ex) {
|
||||
throw new IllegalArgumentException("AI Agent 部署包 JSON 序列化失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static String sqlString(String value) {
|
||||
String text = value == null ? "" : value;
|
||||
return "'" + text.replace("'", "''") + "'";
|
||||
}
|
||||
|
||||
private static String sha256(String text) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return HexFormat.of().formatHex(digest.digest(text.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<String> defaultPlan() {
|
||||
List<String> plan = new ArrayList<>();
|
||||
plan.add("采集需求和上下文");
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.eip4.platform.ai.model.AiDraft;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* AI Agent 部署包 / 回滚 SQL 生成器(自 {@code AiAgentService} 抽出,§10.2 SRP 收敛 slice 1)。
|
||||
*
|
||||
* <p>纯生成职责:把已过门禁的草稿({@link AiDraft})翻成人审部署包里的 SQL/备注语句与回滚语句。
|
||||
* <strong>逐字节复刻原 AiAgentService 实现,零行为变更</strong>(SQL 文本是红线「逐字节对拍」对象,
|
||||
* 由 {@code AiDeploymentSqlBuilderTest} 黄金串钉死)。所有动态值经 {@link #sqlString} 转义,
|
||||
* 时间戳/实体 id/菜单 id 由调用方({@code AiAgentService.createDeploymentPackage})解析后传入。
|
||||
*
|
||||
* <p>仍恪守红线:本类只<em>生成</em>待人工审批执行的 SQL 文本,不直接落库、不触发执行。
|
||||
*/
|
||||
public class AiDeploymentSqlBuilder {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public AiDeploymentSqlBuilder(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public List<String> deploymentSql(List<AiDraft> drafts, String entityId,
|
||||
Map<String, String> menuIdsByTarget, long generatedAt) {
|
||||
List<String> out = new ArrayList<>();
|
||||
for (AiDraft draft : drafts) {
|
||||
switch (draft.artifactType()) {
|
||||
case ENTITY -> out.add(entityDeploymentNote(draft));
|
||||
case SERVICEFLOW -> out.addAll(serviceFlowSql(draft, entityId, generatedAt));
|
||||
case PAGE_SCHEMA -> out.add(pageSchemaSql(draft, generatedAt));
|
||||
case MENU -> out.add(menuSql(draft, menuIdsByTarget.get(draft.targetId()), generatedAt));
|
||||
case TEST -> out.add("-- TEST " + draft.targetId() + ": 保留 smoke 结果作为上线审批附件,不生成生产 SQL");
|
||||
case CODE -> out.add("-- CODE " + draft.targetId() + ": 代码改动需通过代码仓库发布流程,不生成运行态 SQL");
|
||||
}
|
||||
}
|
||||
return List.copyOf(out);
|
||||
}
|
||||
|
||||
private String entityDeploymentNote(AiDraft draft) {
|
||||
return "-- ENTITY " + draft.targetId()
|
||||
+ ": 人工审批后在目标环境调用 POST /api/meta/entity,payload="
|
||||
+ json(draft.payload())
|
||||
+ ";确认返回 entityId 后替换服务流 SQL 中的 ${entityId}";
|
||||
}
|
||||
|
||||
private List<String> serviceFlowSql(AiDraft draft, String entityId, long generatedAt) {
|
||||
List<String> out = new ArrayList<>();
|
||||
String resolvedEntityId = entityId == null || entityId.isBlank() ? "${entityId}" : entityId;
|
||||
for (JsonNode flow : draft.payload().path("flows")) {
|
||||
String xml = flow.path("contentXml").asText("");
|
||||
if (!entityId.isBlank()) {
|
||||
xml = xml.replace("${entityId}", entityId);
|
||||
}
|
||||
out.add("""
|
||||
INSERT INTO sys_serviceflow
|
||||
(sys_serviceflow_id, displayname, contentxml, entityid, iscontrol, isupdateable,
|
||||
isactive, createtime, updatetime, createby, updateby, version)
|
||||
VALUES (%s, %s, %s::xml, %s, %d, %d, 1, %d, %d, 'AI_AGENT', 'AI_AGENT', 0)
|
||||
ON CONFLICT (sys_serviceflow_id) DO UPDATE SET
|
||||
displayname = EXCLUDED.displayname,
|
||||
contentxml = EXCLUDED.contentxml,
|
||||
entityid = EXCLUDED.entityid,
|
||||
iscontrol = EXCLUDED.iscontrol,
|
||||
isupdateable = EXCLUDED.isupdateable,
|
||||
updatetime = EXCLUDED.updatetime,
|
||||
updateby = EXCLUDED.updateby,
|
||||
version = sys_serviceflow.version + 1;
|
||||
""".formatted(
|
||||
sqlString(flow.path("key").asText()),
|
||||
sqlString(flow.path("displayName").asText(flow.path("key").asText())),
|
||||
sqlString(xml),
|
||||
sqlString(resolvedEntityId),
|
||||
flow.path("control").asBoolean(true) ? 1 : 0,
|
||||
flow.path("updateable").asBoolean(true) ? 1 : 0,
|
||||
generatedAt,
|
||||
generatedAt));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private String pageSchemaSql(AiDraft draft, long generatedAt) {
|
||||
String schemaJson = json(draft.payload());
|
||||
return """
|
||||
INSERT INTO sys_page_schema (template_id, name, schema_json, schema_etag, version, update_time)
|
||||
VALUES (%s, %s, %s::jsonb, %s, 1, %d)
|
||||
ON CONFLICT (template_id) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
schema_json = EXCLUDED.schema_json,
|
||||
schema_etag = EXCLUDED.schema_etag,
|
||||
version = sys_page_schema.version + 1,
|
||||
update_time = EXCLUDED.update_time;
|
||||
""".formatted(
|
||||
sqlString(draft.targetId()),
|
||||
sqlString(draft.payload().path("title").asText(draft.targetId())),
|
||||
sqlString(schemaJson),
|
||||
sqlString(sha256(schemaJson)),
|
||||
generatedAt);
|
||||
}
|
||||
|
||||
private String menuSql(AiDraft draft, String appliedMenuId, long generatedAt) {
|
||||
JsonNode payload = draft.payload();
|
||||
String menuId = appliedMenuId == null || appliedMenuId.isBlank() ? "${menuId}" : appliedMenuId;
|
||||
String parentId = payload.path("parentId").asText("");
|
||||
if (parentId.isBlank()) {
|
||||
parentId = "${parentMenuId}";
|
||||
}
|
||||
String menuRoot = payload.path("menuroot").asText("");
|
||||
if (menuRoot.isBlank()) {
|
||||
menuRoot = "${menuRoot}";
|
||||
}
|
||||
return """
|
||||
INSERT INTO sys_menu
|
||||
(sys_menu_id, name, parentid, view_templateid, typename, menuroot, seq,
|
||||
isactive, version, createtime, createby, updatetime, updateby)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %d, 1, 0, %d, 'AI_AGENT', %d, 'AI_AGENT')
|
||||
ON CONFLICT (sys_menu_id) DO UPDATE SET
|
||||
name = EXCLUDED.name,
|
||||
parentid = EXCLUDED.parentid,
|
||||
view_templateid = EXCLUDED.view_templateid,
|
||||
typename = EXCLUDED.typename,
|
||||
menuroot = EXCLUDED.menuroot,
|
||||
seq = EXCLUDED.seq,
|
||||
isactive = 1,
|
||||
updatetime = EXCLUDED.updatetime,
|
||||
updateby = EXCLUDED.updateby,
|
||||
version = sys_menu.version + 1;
|
||||
""".formatted(
|
||||
sqlString(menuId),
|
||||
sqlString(payload.path("name").asText(draft.targetId())),
|
||||
sqlString(parentId),
|
||||
sqlString(payload.path("viewTemplateId").asText(draft.targetId())),
|
||||
sqlString(payload.path("typename").asText("功能菜单")),
|
||||
sqlString(menuRoot),
|
||||
payload.path("seq").asInt(0),
|
||||
generatedAt,
|
||||
generatedAt);
|
||||
}
|
||||
|
||||
public List<String> rollbackSql(List<AiDraft> drafts, long generatedAt) {
|
||||
List<String> out = new ArrayList<>();
|
||||
for (AiDraft draft : drafts) {
|
||||
switch (draft.artifactType()) {
|
||||
case ENTITY -> out.add("-- ENTITY " + draft.targetId()
|
||||
+ ": 人工确认后调用 DELETE /api/meta/entity/" + draft.targetId()
|
||||
+ ",并清理对应菜单/服务流/页面 schema");
|
||||
case SERVICEFLOW -> out.add(serviceFlowRollbackSql(draft));
|
||||
case PAGE_SCHEMA -> out.add("DELETE FROM sys_page_schema WHERE template_id = "
|
||||
+ sqlString(draft.targetId()) + ";");
|
||||
case MENU -> out.add("""
|
||||
UPDATE sys_menu
|
||||
SET isactive = 0, updatetime = %d, updateby = 'AI_AGENT_ROLLBACK',
|
||||
version = version + 1
|
||||
WHERE TRIM(view_templateid) = %s;
|
||||
""".formatted(generatedAt, sqlString(draft.targetId())));
|
||||
case TEST -> out.add("-- TEST " + draft.targetId() + ": 无生产数据回滚动作");
|
||||
case CODE -> out.add("-- CODE " + draft.targetId() + ": 通过代码仓库反向补丁或回滚发布单处理");
|
||||
}
|
||||
}
|
||||
return List.copyOf(out);
|
||||
}
|
||||
|
||||
private String serviceFlowRollbackSql(AiDraft draft) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
for (JsonNode flow : draft.payload().path("flows")) {
|
||||
keys.add(sqlString(flow.path("key").asText()));
|
||||
}
|
||||
return "DELETE FROM sys_serviceflow WHERE sys_serviceflow_id IN ("
|
||||
+ String.join(", ", keys) + ");";
|
||||
}
|
||||
|
||||
private String json(Object value) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException ex) {
|
||||
throw new IllegalArgumentException("AI Agent 部署包 JSON 序列化失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static String sqlString(String value) {
|
||||
String text = value == null ? "" : value;
|
||||
return "'" + text.replace("'", "''") + "'";
|
||||
}
|
||||
|
||||
private static String sha256(String text) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return HexFormat.of().formatHex(digest.digest(text.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
|
||||
import org.xml.sax.InputSource;
|
||||
|
||||
import com.eip4.platform.ai.model.AiArtifactType;
|
||||
import com.eip4.platform.ai.model.AiGateResult;
|
||||
import com.eip4.platform.converter.SchemaGate;
|
||||
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;
|
||||
|
||||
/**
|
||||
* AI Agent 草稿门禁校验器(自 {@code AiAgentService} 抽出,§10.2 SRP 收敛 slice 2)。
|
||||
*
|
||||
* <p>把按 artifact 类型分发的门禁电池(必填字段 / amis-schema / typed-page-schema / page-recipe /
|
||||
* 实体元数据 / 服务流 XML / 菜单绑定 / smoke-plan / render-plan)从编排类剥离,集中在此。
|
||||
* <strong>逐方法从原 AiAgentService 搬迁、判定逻辑零变更</strong>——D3 红线(每类草稿在落库/发布前必过
|
||||
* 对应门禁、终点恒人审)焊在这些判定里,搬迁不动任何阈值/正则/分支。{@code AiAgentServiceTest} +
|
||||
* {@code AiAgentControllerTest} 的现有用例即行为安全网。
|
||||
*
|
||||
* <p>{@link SchemaGate} 的懒加载状态(进程级共享单例)随门禁一并移入本类。
|
||||
*/
|
||||
public class AiDraftGateValidator {
|
||||
|
||||
private static final Pattern TABLE_NAME = Pattern.compile("[A-Z][A-Z0-9_]{2,40}");
|
||||
private static final Pattern FLOW_KEY = Pattern.compile("[A-Z][A-Z0-9_]{2,80}");
|
||||
private static final Pattern COLUMN_NAME = Pattern.compile("[A-Z][A-Z0-9_]{0,39}");
|
||||
private static final Pattern HTTP_METHOD = Pattern.compile("GET|POST|PUT|DELETE|PATCH");
|
||||
|
||||
private static volatile SchemaGate sharedSchemaGate;
|
||||
private volatile SchemaGate schemaGate;
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final TypedPageSchemaValidator typedSchemaValidator;
|
||||
private final PageRecipeRegistry pageRecipeRegistry;
|
||||
private final PageRecipeValidator pageRecipeValidator;
|
||||
|
||||
public AiDraftGateValidator(ObjectMapper objectMapper, TypedPageSchemaValidator typedSchemaValidator,
|
||||
PageRecipeRegistry pageRecipeRegistry, PageRecipeValidator pageRecipeValidator) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.typedSchemaValidator = typedSchemaValidator;
|
||||
this.pageRecipeRegistry = pageRecipeRegistry;
|
||||
this.pageRecipeValidator = pageRecipeValidator;
|
||||
}
|
||||
|
||||
public List<AiGateResult> validateDraft(AiArtifactType type, String targetId, JsonNode payload,
|
||||
Map<String, Object> metadata) {
|
||||
List<AiGateResult> 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));
|
||||
case MENU -> gates.add(validateMenuGate(payload));
|
||||
case TEST -> {
|
||||
gates.add(validateTestGate(payload));
|
||||
gates.add(validateRenderPlanGate(payload));
|
||||
}
|
||||
case CODE -> gates.add(new AiGateResult("code-review-required", true, List.of("代码草稿需后续静态检查/单测门禁")));
|
||||
}
|
||||
return List.copyOf(gates);
|
||||
}
|
||||
|
||||
public AiGateResult validateSchemaGate(JsonNode schema) {
|
||||
if (schema == null || !schema.isObject()) {
|
||||
return new AiGateResult("amis-schema", false, List.of("schema 顶层必须是 JSON object"));
|
||||
}
|
||||
List<String> errors = getSchemaGate().validate(schema);
|
||||
return new AiGateResult("amis-schema", errors.isEmpty(), errors.stream().limit(20).toList());
|
||||
}
|
||||
|
||||
private AiGateResult validateTypedPageSchemaGate(JsonNode schema) {
|
||||
TypedPageSchemaReport report = validateTypedPageSchema(schema);
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
public TypedPageSchemaReport validateTypedPageSchema(JsonNode schema) {
|
||||
try {
|
||||
return typedSchemaValidator.validate(schema == null ? "null" : objectMapper.writeValueAsString(schema));
|
||||
} catch (JsonProcessingException ex) {
|
||||
return typedSchemaValidator.validate("");
|
||||
}
|
||||
}
|
||||
|
||||
public static List<String> typedMessages(TypedPageSchemaReport report) {
|
||||
return report.issues().stream()
|
||||
.limit(20)
|
||||
.map(AiDraftGateValidator::typedMessage)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static String typedMessage(TypedPageSchemaIssue issue) {
|
||||
return issue.path() + " " + issue.code() + ": " + issue.message();
|
||||
}
|
||||
|
||||
private AiGateResult requiredFieldsGate(AiArtifactType type, String targetId, JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
if (targetId == null || targetId.isBlank()) {
|
||||
messages.add("targetId 不能为空");
|
||||
}
|
||||
if (payload == null || !payload.isObject()) {
|
||||
messages.add(type.name() + " payload 顶层必须是 JSON object");
|
||||
}
|
||||
return new AiGateResult("draft-required-fields", messages.isEmpty(), List.copyOf(messages));
|
||||
}
|
||||
|
||||
private AiGateResult validateEntityGate(JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
String table = payload.path("tablename").asText("");
|
||||
if (!TABLE_NAME.matcher(table).matches()) {
|
||||
messages.add("tablename 必须是 3-40 位大写字母数字下划线,且以字母开头");
|
||||
}
|
||||
if (payload.path("name").asText("").isBlank()) {
|
||||
messages.add("name 不能为空");
|
||||
}
|
||||
JsonNode attrs = payload.path("attributes");
|
||||
if (!attrs.isArray() || attrs.isEmpty()) {
|
||||
messages.add("attributes 至少需要 1 个业务字段");
|
||||
} else {
|
||||
for (JsonNode attr : attrs) {
|
||||
String col = attr.path("column").asText("");
|
||||
if (!COLUMN_NAME.matcher(col).matches()) {
|
||||
messages.add("字段 column 不合法: " + col);
|
||||
}
|
||||
String type = attr.path("type").asText("");
|
||||
if (!List.of("string", "integer", "number", "date", "datetime", "boolean").contains(type)) {
|
||||
messages.add("字段 " + col + " type 不支持: " + type);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new AiGateResult("entity-meta", messages.isEmpty(), messages.stream().limit(20).toList());
|
||||
}
|
||||
|
||||
private AiGateResult validateServiceFlowGate(JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
JsonNode flows = payload.path("flows");
|
||||
if (!flows.isArray() || flows.isEmpty()) {
|
||||
messages.add("flows 至少需要 1 个服务流定义");
|
||||
} else {
|
||||
for (JsonNode flow : flows) {
|
||||
String key = flow.path("key").asText("");
|
||||
if (!FLOW_KEY.matcher(key).matches()) {
|
||||
messages.add("服务流 key 不合法: " + key);
|
||||
}
|
||||
String xml = flow.path("contentXml").asText("");
|
||||
if (!isValidFlowXml(xml)) {
|
||||
messages.add("服务流 XML 不合法: " + key);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new AiGateResult("serviceflow-xml", messages.isEmpty(), messages.stream().limit(20).toList());
|
||||
}
|
||||
|
||||
private AiGateResult validateMenuGate(JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
if (payload.path("name").asText("").isBlank()) {
|
||||
messages.add("菜单 name 不能为空");
|
||||
}
|
||||
if (payload.path("viewTemplateId").asText("").isBlank()) {
|
||||
messages.add("菜单 viewTemplateId 不能为空");
|
||||
}
|
||||
return new AiGateResult("menu-binding", messages.isEmpty(), List.copyOf(messages));
|
||||
}
|
||||
|
||||
private AiGateResult validateTestGate(JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
JsonNode tests = payload.path("smokeTests");
|
||||
if (!tests.isArray() || tests.isEmpty()) {
|
||||
messages.add("smokeTests 至少需要 1 条");
|
||||
} else {
|
||||
for (JsonNode test : tests) {
|
||||
String method = test.path("method").asText("");
|
||||
String url = test.path("url").asText("");
|
||||
if (!HTTP_METHOD.matcher(method).matches()) {
|
||||
messages.add("smoke method 不合法: " + method);
|
||||
}
|
||||
if (!url.startsWith("/api/")) {
|
||||
messages.add("smoke url 必须以 /api/ 开头: " + url);
|
||||
}
|
||||
}
|
||||
}
|
||||
return new AiGateResult("smoke-plan", messages.isEmpty(), messages.stream().limit(20).toList());
|
||||
}
|
||||
|
||||
private AiGateResult validateRenderPlanGate(JsonNode payload) {
|
||||
List<String> messages = new ArrayList<>();
|
||||
JsonNode tests = payload.path("renderTests");
|
||||
if (!tests.isArray() || tests.isEmpty()) {
|
||||
messages.add("renderTests 至少需要 1 条");
|
||||
} else {
|
||||
for (JsonNode test : tests) {
|
||||
String name = test.path("name").asText("");
|
||||
String recipe = test.path("recipe").asText("");
|
||||
String schemaUrl = test.path("schemaUrl").asText("");
|
||||
String previewUrl = test.path("previewUrl").asText("");
|
||||
String rootType = test.path("expectedRootType").asText("");
|
||||
String bodyType = test.path("expectedBodyType").asText("");
|
||||
String crudName = test.path("expectedCrudName").asText("");
|
||||
String expectedApi = test.path("expectedApi").asText("");
|
||||
JsonNode components = test.path("expectedComponents");
|
||||
JsonNode columns = test.path("expectedColumns");
|
||||
JsonNode actions = test.path("expectedActions");
|
||||
JsonNode texts = test.path("expectedTexts");
|
||||
if (name.isBlank()) {
|
||||
messages.add("render name 不能为空");
|
||||
}
|
||||
if (pageRecipeRegistry.find(recipe).isEmpty()) {
|
||||
messages.add("render recipe 未注册: " + recipe);
|
||||
}
|
||||
if (!schemaUrl.startsWith("/api/page/schema/")) {
|
||||
messages.add("render schemaUrl 必须以 /api/page/schema/ 开头: " + schemaUrl);
|
||||
}
|
||||
if (!previewUrl.startsWith("/amis.html?schema=")
|
||||
&& !previewUrl.startsWith("/amis.html?templateId=")
|
||||
&& !previewUrl.startsWith("/amis.html?schemaUrl=")) {
|
||||
messages.add("render previewUrl 必须指向可解析 schema 的 /amis.html: " + previewUrl);
|
||||
}
|
||||
if (!"page".equals(rootType)) {
|
||||
messages.add("render expectedRootType 必须是 page");
|
||||
}
|
||||
if (!"crud".equals(bodyType)) {
|
||||
messages.add("render expectedBodyType 必须是 crud");
|
||||
}
|
||||
if (crudName.isBlank()) {
|
||||
messages.add("render expectedCrudName 不能为空");
|
||||
}
|
||||
// house-style 对齐:单表维护页列表走保真层服务流 _SEARCH(/api/flow),
|
||||
// 树页仍走 /api/entity 树接口。
|
||||
if (PageBlueprint.RECIPE_TREE_CRUD.equals(recipe)) {
|
||||
if (!expectedApi.startsWith("/api/entity/") || !expectedApi.contains("/tree?")) {
|
||||
messages.add("tree-crud-v1 render expectedApi 必须是 /api/entity 树接口: " + expectedApi);
|
||||
}
|
||||
} else if (PageBlueprint.RECIPE_MAINTENANCE_CRUD.equals(recipe)) {
|
||||
if (!expectedApi.startsWith("/api/flow/") || !expectedApi.endsWith("_SEARCH")) {
|
||||
messages.add("maintenance-crud-v1 render expectedApi 必须是 /api/flow 服务流 _SEARCH 接口: "
|
||||
+ expectedApi);
|
||||
}
|
||||
} else if (!expectedApi.startsWith("/api/")) {
|
||||
messages.add("render expectedApi 必须指向 /api/: " + expectedApi);
|
||||
}
|
||||
if (!components.isArray() || components.isEmpty()) {
|
||||
messages.add("render expectedComponents 至少需要 1 项");
|
||||
} else {
|
||||
if (!arrayContainsText(components, "page")) {
|
||||
messages.add("render expectedComponents 必须包含 page");
|
||||
}
|
||||
if (!arrayContainsText(components, "crud")) {
|
||||
messages.add("render expectedComponents 必须包含 crud");
|
||||
}
|
||||
}
|
||||
if (!columns.isArray() || columns.isEmpty()) {
|
||||
messages.add("render expectedColumns 至少需要 1 项");
|
||||
} else {
|
||||
for (JsonNode column : columns) {
|
||||
if (column.path("name").asText("").isBlank()) {
|
||||
messages.add("render expectedColumns.name 不能为空");
|
||||
}
|
||||
if (column.path("label").asText("").isBlank()) {
|
||||
messages.add("render expectedColumns.label 不能为空");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!actions.isArray() || actions.isEmpty()) {
|
||||
messages.add("render expectedActions 至少需要 1 项");
|
||||
} else {
|
||||
if (!arrayContainsText(actions, "新增")
|
||||
&& !arrayContainsTextStartingWith(actions, "新增顶级")) {
|
||||
messages.add("render expectedActions 必须包含新增动作");
|
||||
}
|
||||
if (!arrayContainsText(actions, "编辑")) {
|
||||
messages.add("render expectedActions 必须包含编辑动作");
|
||||
}
|
||||
if (!arrayContainsText(actions, "删除")) {
|
||||
messages.add("render expectedActions 必须包含删除动作");
|
||||
}
|
||||
}
|
||||
if (!texts.isArray() || texts.isEmpty()) {
|
||||
messages.add("render expectedTexts 至少需要 1 项");
|
||||
}
|
||||
}
|
||||
}
|
||||
return new AiGateResult("render-plan", messages.isEmpty(), messages.stream().limit(20).toList());
|
||||
}
|
||||
|
||||
private static boolean arrayContainsText(JsonNode array, String value) {
|
||||
for (JsonNode item : array) {
|
||||
if (value.equals(item.asText(""))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean arrayContainsTextStartingWith(JsonNode array, String prefix) {
|
||||
for (JsonNode item : array) {
|
||||
if (item.asText("").startsWith(prefix)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isValidFlowXml(String xml) {
|
||||
if (xml == null || xml.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
|
||||
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
|
||||
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
|
||||
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
|
||||
factory.setExpandEntityReferences(false);
|
||||
var builder = factory.newDocumentBuilder();
|
||||
var doc = builder.parse(new InputSource(new java.io.StringReader(xml)));
|
||||
return "flow".equals(doc.getDocumentElement().getNodeName())
|
||||
&& doc.getElementsByTagName("input").getLength() > 0
|
||||
&& doc.getElementsByTagName("transition").getLength() > 0;
|
||||
} catch (Exception ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private SchemaGate getSchemaGate() {
|
||||
if (schemaGate == null) {
|
||||
synchronized (AiDraftGateValidator.class) {
|
||||
if (sharedSchemaGate == null) {
|
||||
sharedSchemaGate = new SchemaGate();
|
||||
}
|
||||
schemaGate = sharedSchemaGate;
|
||||
}
|
||||
}
|
||||
return schemaGate;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.eip4.platform.ai.model.AiArtifactType;
|
||||
import com.eip4.platform.ai.model.AiDraft;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* AiDeploymentSqlBuilder 黄金特征测试(§10.2 SRP slice 1 抽取的安全网)。
|
||||
*
|
||||
* <p>SQL 文本是红线「逐字节对拍」对象;抽取为逐字移动、字节不变。本测试钉死关键 token
|
||||
* (表名 / AI_AGENT 审计字面量 / ON CONFLICT / version+1 / ::xml·::jsonb 类型转换 /
|
||||
* 单引号转义 / ${entityId}·${menuId} 等占位符回退 / entityId 替换),防后续编辑悄悄改写运行态 SQL。
|
||||
*/
|
||||
class AiDeploymentSqlBuilderTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private final AiDeploymentSqlBuilder builder = new AiDeploymentSqlBuilder(MAPPER);
|
||||
|
||||
private AiDraft draft(AiArtifactType type, String targetId, String payloadJson) {
|
||||
try {
|
||||
JsonNode payload = MAPPER.readTree(payloadJson);
|
||||
return new AiDraft("d-" + targetId, "t1", type, targetId, payload, 0L, List.of(), Map.of());
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceFlow_含审计字面量与entityId替换与版本自增() {
|
||||
AiDraft d = draft(AiArtifactType.SERVICEFLOW, "FLOW1",
|
||||
"{\"flows\":[{\"key\":\"OA_X_ADD\",\"displayName\":\"新增\",\"contentXml\":\"<flow e='${entityId}'/>\",\"control\":true,\"updateable\":false}]}");
|
||||
List<String> sql = builder.deploymentSql(List.of(d), "ENT-9", Map.of(), 1000L);
|
||||
assertEquals(1, sql.size());
|
||||
String s = sql.get(0);
|
||||
assertTrue(s.contains("INSERT INTO sys_serviceflow"), s);
|
||||
assertTrue(s.contains("'AI_AGENT', 'AI_AGENT', 0"), "createby/updateby 审计字面量");
|
||||
assertTrue(s.contains("::xml"), "contentxml 类型转换");
|
||||
assertTrue(s.contains("version = sys_serviceflow.version + 1"), "乐观锁版本自增");
|
||||
assertTrue(s.contains("ON CONFLICT (sys_serviceflow_id) DO UPDATE SET"), s);
|
||||
// sqlString 会把 XML 里的单引号翻倍转义,故断言「占位符已消失 + 真实 entityId 出现」而非原样引号串
|
||||
assertTrue(!s.contains("${entityId}"), "${entityId} 占位符应被替换消失");
|
||||
assertTrue(s.contains("ENT-9"), "应替换为真实 entityId");
|
||||
assertTrue(s.contains("e=''ENT-9''"), "XML 内单引号经 sqlString 翻倍转义");
|
||||
assertTrue(s.contains("'OA_X_ADD'"), "flow key 进 SQL 并加引号");
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceFlow_entityId空时保留占位符() {
|
||||
AiDraft d = draft(AiArtifactType.SERVICEFLOW, "FLOW1",
|
||||
"{\"flows\":[{\"key\":\"K\",\"contentXml\":\"<f/>\"}]}");
|
||||
String s = builder.deploymentSql(List.of(d), "", Map.of(), 1L).get(0);
|
||||
assertTrue(s.contains("'${entityId}'"), "entityId 空 → SQL 保留 ${entityId} 占位符待人工替换");
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceFlow_单引号转义防注入() {
|
||||
AiDraft d = draft(AiArtifactType.SERVICEFLOW, "F",
|
||||
"{\"flows\":[{\"key\":\"a'b\",\"contentXml\":\"<f/>\"}]}");
|
||||
String s = builder.deploymentSql(List.of(d), "E", Map.of(), 1L).get(0);
|
||||
assertTrue(s.contains("'a''b'"), "单引号必须翻倍转义");
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageSchema_含jsonb与etag与版本自增() {
|
||||
AiDraft d = draft(AiArtifactType.PAGE_SCHEMA, "PG1", "{\"title\":\"页\",\"type\":\"page\"}");
|
||||
String s = builder.deploymentSql(List.of(d), null, Map.of(), 2000L).get(0);
|
||||
assertTrue(s.contains("INSERT INTO sys_page_schema"), s);
|
||||
assertTrue(s.contains("::jsonb"), "schema_json 类型转换");
|
||||
assertTrue(s.contains("'PG1'"), "template_id");
|
||||
assertTrue(s.contains("version = sys_page_schema.version + 1"), s);
|
||||
// etag = sha256(schemaJson) = 64 位十六进制
|
||||
java.util.regex.Matcher m = java.util.regex.Pattern.compile("'([0-9a-f]{64})'").matcher(s);
|
||||
assertTrue(m.find(), "应含 64 位 sha256 etag");
|
||||
}
|
||||
|
||||
@Test
|
||||
void menu_应用菜单id缺失时回退占位符() {
|
||||
AiDraft d = draft(AiArtifactType.MENU, "M1", "{\"name\":\"菜单\"}");
|
||||
String s = builder.deploymentSql(List.of(d), null, Map.of(), 3000L).get(0);
|
||||
assertTrue(s.contains("INSERT INTO sys_menu"), s);
|
||||
assertTrue(s.contains("'${menuId}'"), "menuId 未应用 → 占位符");
|
||||
assertTrue(s.contains("'${parentMenuId}'"), "parentId 空 → 占位符");
|
||||
assertTrue(s.contains("'${menuRoot}'"), "menuroot 空 → 占位符");
|
||||
assertTrue(s.contains("'AI_AGENT'"), "审计字面量");
|
||||
}
|
||||
|
||||
@Test
|
||||
void menu_应用真实菜单id() {
|
||||
AiDraft d = draft(AiArtifactType.MENU, "M1", "{\"name\":\"菜单\",\"parentId\":\"P\",\"menuroot\":\"R\"}");
|
||||
String s = builder.deploymentSql(List.of(d), null, Map.of("M1", "MENU-9"), 1L).get(0);
|
||||
assertTrue(s.contains("'MENU-9'"), "应用真实菜单 id");
|
||||
assertTrue(s.contains("'P'") && s.contains("'R'"), "真实 parentId/menuroot");
|
||||
}
|
||||
|
||||
@Test
|
||||
void entity_test_code_注释备注精确() {
|
||||
assertEquals(List.of(
|
||||
"-- ENTITY E1: 人工审批后在目标环境调用 POST /api/meta/entity,payload={\"a\":1}"
|
||||
+ ";确认返回 entityId 后替换服务流 SQL 中的 ${entityId}"),
|
||||
builder.deploymentSql(List.of(draft(AiArtifactType.ENTITY, "E1", "{\"a\":1}")), "E", Map.of(), 1L));
|
||||
assertTrue(builder.deploymentSql(List.of(draft(AiArtifactType.TEST, "T1", "{}")), "E", Map.of(), 1L)
|
||||
.get(0).startsWith("-- TEST T1:"));
|
||||
assertTrue(builder.deploymentSql(List.of(draft(AiArtifactType.CODE, "C1", "{}")), "E", Map.of(), 1L)
|
||||
.get(0).startsWith("-- CODE C1:"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rollback_各类型反向语句() {
|
||||
String flowRb = builder.rollbackSql(List.of(draft(AiArtifactType.SERVICEFLOW, "F",
|
||||
"{\"flows\":[{\"key\":\"K1\"},{\"key\":\"K2\"}]}")), 1L).get(0);
|
||||
assertEquals("DELETE FROM sys_serviceflow WHERE sys_serviceflow_id IN ('K1', 'K2');", flowRb);
|
||||
|
||||
String pageRb = builder.rollbackSql(List.of(draft(AiArtifactType.PAGE_SCHEMA, "PG1", "{}")), 1L).get(0);
|
||||
assertEquals("DELETE FROM sys_page_schema WHERE template_id = 'PG1';", pageRb);
|
||||
|
||||
String menuRb = builder.rollbackSql(List.of(draft(AiArtifactType.MENU, "M1", "{}")), 5000L).get(0);
|
||||
assertTrue(menuRb.contains("UPDATE sys_menu") && menuRb.contains("isactive = 0")
|
||||
&& menuRb.contains("'AI_AGENT_ROLLBACK'") && menuRb.contains("TRIM(view_templateid) = 'M1'"), menuRb);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.eip4.platform.ai.model.AiArtifactType;
|
||||
import com.eip4.platform.ai.model.AiGateResult;
|
||||
import com.eip4.platform.metadata.schema.PageComponentRegistry;
|
||||
import com.eip4.platform.metadata.schema.TypedPageSchemaValidator;
|
||||
import com.eip4.platform.metadata.schema.blueprint.PageRecipeRegistry;
|
||||
import com.eip4.platform.metadata.schema.blueprint.PageRecipeValidator;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
/**
|
||||
* AiDraftGateValidator 直测(§10.2 SRP slice 2 抽取的门禁簇的独立契约测试)。
|
||||
*
|
||||
* <p>门禁逐方法从 AiAgentService 搬迁、判定零变更;此处直接对验证器钉死各类草稿的关键 pass/fail 判定,
|
||||
* 与经 {@code AiAgentServiceTest.addDraft} 的传递覆盖互补。红线:每类草稿落库/发布前必过对应门禁。
|
||||
*/
|
||||
class AiDraftGateValidatorTest {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private AiDraftGateValidator validator() {
|
||||
PageRecipeRegistry registry = PageRecipeRegistry.defaults();
|
||||
return new AiDraftGateValidator(
|
||||
MAPPER,
|
||||
new TypedPageSchemaValidator(MAPPER, PageComponentRegistry.defaults()),
|
||||
registry,
|
||||
new PageRecipeValidator(MAPPER, registry));
|
||||
}
|
||||
|
||||
private JsonNode json(String s) {
|
||||
try {
|
||||
return MAPPER.readTree(s);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
private AiGateResult gate(List<AiGateResult> gates, String name) {
|
||||
return gates.stream().filter(g -> g.name().equals(name)).findFirst().orElseThrow();
|
||||
}
|
||||
|
||||
@Test
|
||||
void requiredFields_targetId空被拒() {
|
||||
List<AiGateResult> g = validator().validateDraft(AiArtifactType.ENTITY, "", json("{}"), Map.of());
|
||||
assertFalse(gate(g, "draft-required-fields").passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void entity_合法通过_非法tablename被拒() {
|
||||
String ok = "{\"tablename\":\"OA_DEMO\",\"name\":\"演示\",\"attributes\":[{\"column\":\"TITLE\",\"type\":\"string\"}]}";
|
||||
assertTrue(gate(validator().validateDraft(AiArtifactType.ENTITY, "OA_DEMO", json(ok), Map.of()),
|
||||
"entity-meta").passed());
|
||||
String bad = "{\"tablename\":\"oa demo\",\"name\":\"\",\"attributes\":[]}";
|
||||
assertFalse(gate(validator().validateDraft(AiArtifactType.ENTITY, "X", json(bad), Map.of()),
|
||||
"entity-meta").passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void serviceFlow_非法key与xml被拒() {
|
||||
String bad = "{\"flows\":[{\"key\":\"bad key\",\"contentXml\":\"<notflow/>\"}]}";
|
||||
assertFalse(gate(validator().validateDraft(AiArtifactType.SERVICEFLOW, "F", json(bad), Map.of()),
|
||||
"serviceflow-xml").passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void menu_缺name或viewTemplateId被拒() {
|
||||
assertFalse(gate(validator().validateDraft(AiArtifactType.MENU, "M", json("{\"name\":\"\"}"), Map.of()),
|
||||
"menu-binding").passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void code_恒通过() {
|
||||
assertTrue(gate(validator().validateDraft(AiArtifactType.CODE, "C", json("{}"), Map.of()),
|
||||
"code-review-required").passed());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageSchema_顶层非object的amisSchema门被拒() {
|
||||
AiGateResult r = validator().validateSchemaGate(MAPPER.createArrayNode());
|
||||
assertFalse(r.passed());
|
||||
assertEquals("amis-schema", r.name());
|
||||
}
|
||||
|
||||
@Test
|
||||
void pageRecipe_未声明recipe时跳过门() {
|
||||
// 无 pageRecipe/pageBlueprint metadata → page-recipe 门以通过(跳过)放行手工草稿
|
||||
String schema = "{\"type\":\"page\"}";
|
||||
List<AiGateResult> g = validator().validateDraft(AiArtifactType.PAGE_SCHEMA, "PG", json(schema), Map.of());
|
||||
assertTrue(gate(g, "page-recipe").passed());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user