feat: add AI agent auto-development pipeline
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AiAgentRepairContext(
|
||||
String taskId,
|
||||
String changeSetId,
|
||||
AiRepairPlan repairPlan,
|
||||
List<AiDraft> drafts) {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AiAgentRepairResult(
|
||||
String status,
|
||||
List<AiRepairDraftPatch> draftPatches,
|
||||
List<String> messages) {
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AiApplyRun(
|
||||
String taskId,
|
||||
String changeSetId,
|
||||
String baseUrl,
|
||||
String status,
|
||||
long startedAt,
|
||||
long finishedAt,
|
||||
List<AiApplyStepResult> steps,
|
||||
AiSmokeRun smokeRun) {
|
||||
|
||||
public boolean passed() {
|
||||
boolean stepsPassed = steps != null && steps.stream()
|
||||
.allMatch(s -> "APPLIED".equals(s.status()) || "SKIPPED".equals(s.status()));
|
||||
return stepsPassed && smokeRun != null && smokeRun.passed();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record AiApplyStepResult(
|
||||
String id,
|
||||
AiArtifactType artifactType,
|
||||
String target,
|
||||
String status,
|
||||
String message,
|
||||
Map<String, Object> details) {
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
/**
|
||||
* Agent 允许产生的受控产物类型。
|
||||
*
|
||||
* <p>这里刻意不用自由字符串:后续 MCP 工具、发布门禁和审计都需要按类型施加不同规则。
|
||||
*/
|
||||
public enum AiArtifactType {
|
||||
ENTITY,
|
||||
PAGE_SCHEMA,
|
||||
SERVICEFLOW,
|
||||
MENU,
|
||||
CODE,
|
||||
TEST
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record AiAuditEntry(
|
||||
String id,
|
||||
String taskId,
|
||||
String action,
|
||||
String actor,
|
||||
long createdAt,
|
||||
Map<String, Object> details) {
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
public record AiAutoDevelopmentRequest(
|
||||
AiFeatureRequest feature,
|
||||
String baseUrl,
|
||||
Boolean generateDeploymentPackage,
|
||||
Integer maxRepairAttempts) {
|
||||
|
||||
public boolean shouldGenerateDeploymentPackage() {
|
||||
return generateDeploymentPackage == null || generateDeploymentPackage;
|
||||
}
|
||||
|
||||
public int repairAttemptLimit() {
|
||||
if (maxRepairAttempts == null) {
|
||||
return 2;
|
||||
}
|
||||
return Math.max(0, Math.min(5, maxRepairAttempts));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AiAutoDevelopmentRun(
|
||||
String taskId,
|
||||
String changeSetId,
|
||||
String originalChangeSetId,
|
||||
String status,
|
||||
long startedAt,
|
||||
long finishedAt,
|
||||
AiFeatureDevelopment development,
|
||||
AiReleasePlan releasePlan,
|
||||
AiApplyRun applyRun,
|
||||
AiDeploymentPackage deploymentPackage,
|
||||
List<AiRepairExecution> repairExecutions,
|
||||
List<String> messages) {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public record AiChangeSet(
|
||||
String id,
|
||||
String taskId,
|
||||
String status,
|
||||
long createdAt,
|
||||
List<String> draftIds,
|
||||
Map<String, Object> summary) {
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public record AiDeploymentPackage(
|
||||
String taskId,
|
||||
String changeSetId,
|
||||
String status,
|
||||
boolean requiresHumanApproval,
|
||||
long generatedAt,
|
||||
Map<String, Object> manifest,
|
||||
List<String> sqlStatements,
|
||||
List<String> rollbackSqlStatements,
|
||||
List<String> warnings,
|
||||
List<AiRunRecord> runEvidence) {
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
public record AiDraft(
|
||||
String id,
|
||||
String taskId,
|
||||
AiArtifactType artifactType,
|
||||
String targetId,
|
||||
JsonNode payload,
|
||||
long createdAt,
|
||||
List<AiGateResult> gates,
|
||||
Map<String, Object> metadata) {
|
||||
|
||||
public boolean passed() {
|
||||
return gates == null || gates.stream().allMatch(AiGateResult::passed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AiFeatureDevelopment(
|
||||
AiTask task,
|
||||
List<AiDraft> drafts,
|
||||
AiChangeSet changeSet) {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
public record AiFeatureField(
|
||||
String column,
|
||||
String label,
|
||||
String type,
|
||||
Integer length,
|
||||
Boolean required) {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AiFeatureRequest(
|
||||
String objective,
|
||||
String featureName,
|
||||
String tableName,
|
||||
String entityName,
|
||||
String templateId,
|
||||
String menuName,
|
||||
List<AiFeatureField> fields) {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AiGateResult(
|
||||
String name,
|
||||
boolean passed,
|
||||
List<String> messages) {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
public record AiGeneratedDraft(
|
||||
AiArtifactType artifactType,
|
||||
String targetId,
|
||||
JsonNode payload,
|
||||
Map<String, Object> metadata) {
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public record AiReleasePlan(
|
||||
String taskId,
|
||||
String changeSetId,
|
||||
String status,
|
||||
boolean requiresHumanApproval,
|
||||
Map<String, Object> environmentPolicy,
|
||||
List<AiReleaseStep> steps,
|
||||
List<String> rollbackNotes) {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record AiReleaseStep(
|
||||
String id,
|
||||
AiArtifactType artifactType,
|
||||
String title,
|
||||
String mode,
|
||||
String target,
|
||||
String action,
|
||||
Map<String, Object> details) {
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record AiRepairAction(
|
||||
String id,
|
||||
String source,
|
||||
String actionType,
|
||||
String artifactType,
|
||||
String targetId,
|
||||
boolean automated,
|
||||
String rationale,
|
||||
Map<String, Object> details) {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
public record AiRepairDraftPatch(
|
||||
AiArtifactType artifactType,
|
||||
String targetId,
|
||||
JsonNode payload,
|
||||
Map<String, Object> metadata) {
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AiRepairExecution(
|
||||
String taskId,
|
||||
String changeSetId,
|
||||
String status,
|
||||
long startedAt,
|
||||
long finishedAt,
|
||||
AiRepairPlan repairPlan,
|
||||
List<AiDraft> generatedDrafts,
|
||||
AiChangeSet repairedChangeSet,
|
||||
AiApplyRun retryApplyRun,
|
||||
AiDeploymentPackage deploymentPackage,
|
||||
List<String> messages) {
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
public record AiRepairExecutionRequest(String baseUrl) {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AiRepairPlan(
|
||||
String taskId,
|
||||
String changeSetId,
|
||||
String sourceRunId,
|
||||
String status,
|
||||
long generatedAt,
|
||||
List<AiRepairAction> actions,
|
||||
List<String> messages) {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
public record AiRunRecord(
|
||||
String id,
|
||||
String taskId,
|
||||
String changeSetId,
|
||||
String runType,
|
||||
String status,
|
||||
long createdAt,
|
||||
JsonNode payload) {
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
public record AiSmokeResult(
|
||||
String name,
|
||||
String method,
|
||||
String url,
|
||||
int expectedHttpStatus,
|
||||
int actualHttpStatus,
|
||||
boolean passed,
|
||||
long durationMillis,
|
||||
String error,
|
||||
String responseSnippet) {
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AiSmokeRun(
|
||||
String taskId,
|
||||
String changeSetId,
|
||||
String baseUrl,
|
||||
String status,
|
||||
long startedAt,
|
||||
long finishedAt,
|
||||
List<AiSmokeResult> results) {
|
||||
|
||||
public boolean passed() {
|
||||
return results != null && results.stream().allMatch(AiSmokeResult::passed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.eip4.platform.ai.model;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AiTask(
|
||||
String id,
|
||||
String objective,
|
||||
String status,
|
||||
long createdAt,
|
||||
long updatedAt,
|
||||
List<String> plan) {
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import com.eip4.platform.ai.model.AiAgentRepairContext;
|
||||
import com.eip4.platform.ai.model.AiAgentRepairResult;
|
||||
|
||||
public interface AiAgentRepairExecutor {
|
||||
|
||||
AiAgentRepairResult repair(AiAgentRepairContext context);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,407 @@
|
||||
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.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.dsasp.server.common.core.FlowDefinition;
|
||||
import com.dsasp.server.core.service.flow.model.DefaultFlowHelper;
|
||||
import com.eip4.platform.ai.model.AiArtifactType;
|
||||
import com.eip4.platform.ai.model.AiFeatureField;
|
||||
import com.eip4.platform.ai.model.AiFeatureRequest;
|
||||
import com.eip4.platform.ai.model.AiGeneratedDraft;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
@Component
|
||||
public class AiFeatureDraftGenerator {
|
||||
|
||||
private static final String ENTITY_ID_PLACEHOLDER = "${entityId}";
|
||||
private static final Set<String> SYSTEM_COLUMNS = Set.of(
|
||||
"VERSION", "CREATETIME", "UPDATETIME", "CREATEBY", "UPDATEBY", "ISACTIVE");
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public AiFeatureDraftGenerator(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public List<AiGeneratedDraft> generate(AiFeatureRequest request) {
|
||||
FeatureSpec spec = normalize(request);
|
||||
List<AiGeneratedDraft> drafts = new ArrayList<>();
|
||||
drafts.add(new AiGeneratedDraft(AiArtifactType.ENTITY, spec.tableName(),
|
||||
entityPayload(spec), metadata("entity-meta", "/api/meta/entity")));
|
||||
drafts.add(new AiGeneratedDraft(AiArtifactType.PAGE_SCHEMA, spec.templateId(),
|
||||
pageSchema(spec), metadata("page-schema", "sys_page_schema")));
|
||||
drafts.add(new AiGeneratedDraft(AiArtifactType.SERVICEFLOW, spec.tableName() + "_DEFAULT_FLOWS",
|
||||
serviceFlowPayload(spec), metadata("serviceflow", "sys_serviceflow")));
|
||||
drafts.add(new AiGeneratedDraft(AiArtifactType.MENU, spec.templateId(),
|
||||
menuPayload(spec), metadata("menu", "sys_menu")));
|
||||
drafts.add(new AiGeneratedDraft(AiArtifactType.TEST, spec.templateId() + "-smoke",
|
||||
testPayload(spec), metadata("smoke-test", "local-gates")));
|
||||
return List.copyOf(drafts);
|
||||
}
|
||||
|
||||
private ObjectNode entityPayload(FeatureSpec spec) {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.put("publishTarget", "/api/meta/entity");
|
||||
root.put("tablename", spec.tableName());
|
||||
root.put("name", spec.entityName());
|
||||
ArrayNode attrs = root.putArray("attributes");
|
||||
for (FieldSpec field : spec.fields()) {
|
||||
ObjectNode attr = attrs.addObject();
|
||||
attr.put("column", field.column());
|
||||
attr.put("display", field.label());
|
||||
attr.put("type", field.type());
|
||||
if (field.length() != null) {
|
||||
attr.put("length", field.length());
|
||||
}
|
||||
attr.put("mandatory", field.required());
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
private ObjectNode pageSchema(FeatureSpec spec) {
|
||||
ObjectNode page = objectMapper.createObjectNode();
|
||||
page.put("type", "page");
|
||||
page.put("title", spec.featureName());
|
||||
ArrayNode body = page.putArray("body");
|
||||
ObjectNode crud = body.addObject();
|
||||
crud.put("type", "crud");
|
||||
crud.put("name", lowerCamel(spec.tableName()) + "Crud");
|
||||
crud.put("syncLocation", false);
|
||||
ObjectNode api = crud.putObject("api");
|
||||
api.put("method", "get");
|
||||
api.put("url", "/api/entity/" + spec.tableName() + "/list?page=${page}&perPage=${perPage}");
|
||||
api.put("adaptor", "return payload;");
|
||||
ArrayNode headerToolbar = crud.putArray("headerToolbar");
|
||||
ObjectNode addButton = headerToolbar.addObject();
|
||||
addButton.put("type", "button");
|
||||
addButton.put("label", "新增");
|
||||
addButton.put("level", "primary");
|
||||
addButton.put("icon", "fa fa-plus");
|
||||
addButton.put("actionType", "dialog");
|
||||
ObjectNode addDialog = addButton.putObject("dialog");
|
||||
addDialog.put("title", "新增" + spec.entityName());
|
||||
ObjectNode addForm = addDialog.putObject("body");
|
||||
addForm.put("type", "form");
|
||||
addForm.put("api", "post:/api/entity/" + spec.tableName() + "/save");
|
||||
addForm.set("body", formControls(spec, false));
|
||||
headerToolbar.add("pagination");
|
||||
ArrayNode footerToolbar = crud.putArray("footerToolbar");
|
||||
footerToolbar.add("statistics");
|
||||
footerToolbar.add("pagination");
|
||||
crud.put("perPage", 20);
|
||||
crud.set("columns", columns(spec));
|
||||
return page;
|
||||
}
|
||||
|
||||
private ArrayNode columns(FeatureSpec spec) {
|
||||
ArrayNode columns = objectMapper.createArrayNode();
|
||||
for (FieldSpec field : spec.fields()) {
|
||||
ObjectNode column = columns.addObject();
|
||||
column.put("name", field.column());
|
||||
column.put("label", field.label());
|
||||
}
|
||||
ObjectNode op = columns.addObject();
|
||||
op.put("type", "operation");
|
||||
op.put("label", "操作");
|
||||
op.put("width", 180);
|
||||
ArrayNode buttons = op.putArray("buttons");
|
||||
ObjectNode edit = buttons.addObject();
|
||||
edit.put("type", "button");
|
||||
edit.put("label", "编辑");
|
||||
edit.put("level", "link");
|
||||
edit.put("actionType", "dialog");
|
||||
ObjectNode editDialog = edit.putObject("dialog");
|
||||
editDialog.put("title", "编辑${" + displayColumn(spec) + "}");
|
||||
ObjectNode editForm = editDialog.putObject("body");
|
||||
editForm.put("type", "form");
|
||||
editForm.put("api", "post:/api/entity/" + spec.tableName() + "/save");
|
||||
ArrayNode editControls = formControls(spec, true);
|
||||
ObjectNode hiddenPk = objectMapper.createObjectNode();
|
||||
hiddenPk.put("type", "hidden");
|
||||
hiddenPk.put("name", spec.tableName() + "_ID");
|
||||
hiddenPk.put("value", "${" + spec.tableName() + "_ID}");
|
||||
editControls.add(hiddenPk);
|
||||
editForm.set("body", editControls);
|
||||
|
||||
ObjectNode del = buttons.addObject();
|
||||
del.put("type", "button");
|
||||
del.put("label", "删除");
|
||||
del.put("level", "link");
|
||||
del.put("className", "text-danger");
|
||||
del.put("actionType", "ajax");
|
||||
del.put("confirmText", "确认删除该记录?");
|
||||
ObjectNode delApi = del.putObject("api");
|
||||
delApi.put("method", "post");
|
||||
delApi.put("url", "/api/entity/" + spec.tableName() + "/delete");
|
||||
ObjectNode data = delApi.putObject("data");
|
||||
data.put("id", "${" + spec.tableName() + "_ID}");
|
||||
del.put("reload", lowerCamel(spec.tableName()) + "Crud");
|
||||
return columns;
|
||||
}
|
||||
|
||||
private ArrayNode formControls(FeatureSpec spec, boolean bindCurrentRow) {
|
||||
ArrayNode controls = objectMapper.createArrayNode();
|
||||
for (FieldSpec field : spec.fields()) {
|
||||
ObjectNode c = controls.addObject();
|
||||
c.put("type", controlType(field.type()));
|
||||
c.put("name", field.column());
|
||||
c.put("label", field.label());
|
||||
if (field.required()) {
|
||||
c.put("required", true);
|
||||
}
|
||||
if (bindCurrentRow) {
|
||||
c.put("value", "${" + field.column() + "}");
|
||||
}
|
||||
}
|
||||
return controls;
|
||||
}
|
||||
|
||||
private ObjectNode serviceFlowPayload(FeatureSpec spec) {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.put("publishTarget", "sys_serviceflow");
|
||||
root.put("requiresEntityId", true);
|
||||
root.put("entityIdBinding", "publish ENTITY draft first, then replace " + ENTITY_ID_PLACEHOLDER);
|
||||
ArrayNode flows = root.putArray("flows");
|
||||
addFlow(flows, DefaultFlowHelper.getDefaultAdd(spec.tableName(), ENTITY_ID_PLACEHOLDER, spec.entityName()));
|
||||
addFlow(flows, DefaultFlowHelper.getDefaultUpdate(spec.tableName(), ENTITY_ID_PLACEHOLDER, spec.entityName()));
|
||||
addFlow(flows, DefaultFlowHelper.getDefaultSearch(spec.tableName(), ENTITY_ID_PLACEHOLDER, spec.entityName()));
|
||||
addFlow(flows, DefaultFlowHelper.getDefaultDelete(spec.tableName(), ENTITY_ID_PLACEHOLDER, spec.entityName()));
|
||||
addFlow(flows, DefaultFlowHelper.getDefaultLoad(spec.tableName(), ENTITY_ID_PLACEHOLDER, spec.entityName()));
|
||||
return root;
|
||||
}
|
||||
|
||||
private void addFlow(ArrayNode flows, FlowDefinition<?> flow) {
|
||||
ObjectNode node = flows.addObject();
|
||||
node.put("key", flow.getKey());
|
||||
node.put("displayName", flow.getDisplayName());
|
||||
node.put("entityId", flow.getEntityId());
|
||||
node.put("control", flow.isControl());
|
||||
node.put("updateable", flow.isUpdateable());
|
||||
node.put("contentXml", flow.getFlow());
|
||||
}
|
||||
|
||||
private ObjectNode menuPayload(FeatureSpec spec) {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.put("publishTarget", "sys_menu");
|
||||
root.put("name", spec.menuName());
|
||||
root.put("typename", "功能菜单");
|
||||
root.put("viewTemplateId", spec.templateId());
|
||||
root.put("seq", 0);
|
||||
return root;
|
||||
}
|
||||
|
||||
private ObjectNode testPayload(FeatureSpec spec) {
|
||||
ObjectNode root = objectMapper.createObjectNode();
|
||||
root.put("publishTarget", "local-smoke");
|
||||
ArrayNode tests = root.putArray("smokeTests");
|
||||
addSmoke(tests, "page-schema", "GET", "/api/page/schema/" + spec.templateId(), 200);
|
||||
addSmoke(tests, "entity-list", "GET", "/api/entity/" + spec.tableName() + "/list?page=1&perPage=20", 200);
|
||||
addSmoke(tests, "flow-search", "GET", "/api/flow/" + spec.tableName() + "_SEARCH?page=1&perPage=20", 200);
|
||||
ObjectNode create = addSmoke(tests, "entity-create", "POST",
|
||||
"/api/entity/" + spec.tableName() + "/save", 200);
|
||||
create.set("requestBody", sampleEntityBody(spec));
|
||||
ArrayNode manual = root.putArray("manualGates");
|
||||
manual.add("确认实体字段、菜单位置、权限角色和服务流写入策略");
|
||||
manual.add("确认本地 smoke 通过后再人工部署线上");
|
||||
return root;
|
||||
}
|
||||
|
||||
private ObjectNode addSmoke(ArrayNode tests, String name, String method, String url, int expectStatus) {
|
||||
ObjectNode t = tests.addObject();
|
||||
t.put("name", name);
|
||||
t.put("method", method);
|
||||
t.put("url", url);
|
||||
t.put("expectHttpStatus", expectStatus);
|
||||
return t;
|
||||
}
|
||||
|
||||
private ObjectNode sampleEntityBody(FeatureSpec spec) {
|
||||
ObjectNode body = objectMapper.createObjectNode();
|
||||
for (FieldSpec field : spec.fields()) {
|
||||
switch (field.type()) {
|
||||
case "integer" -> body.put(field.column(), 1);
|
||||
case "number" -> body.put(field.column(), 1.0);
|
||||
case "date" -> body.put(field.column(), "2026-01-01");
|
||||
case "datetime" -> body.put(field.column(), "2026-01-01 00:00:00");
|
||||
case "boolean" -> body.put(field.column(), true);
|
||||
default -> body.put(field.column(), "AI_SMOKE_" + field.column());
|
||||
}
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
private FeatureSpec normalize(AiFeatureRequest request) {
|
||||
String feature = firstText(request == null ? null : request.featureName(),
|
||||
request == null ? null : request.entityName(),
|
||||
request == null ? null : request.objective(),
|
||||
"AI功能");
|
||||
String table = normalizeTable(request == null ? null : request.tableName(), feature);
|
||||
String entityName = firstText(request == null ? null : request.entityName(), feature, table);
|
||||
String templateId = normalizeTemplateId(request == null ? null : request.templateId(), table);
|
||||
String menuName = firstText(request == null ? null : request.menuName(), feature);
|
||||
List<FieldSpec> fields = normalizeFields(request == null ? null : request.fields());
|
||||
return new FeatureSpec(feature, table, entityName, templateId, menuName, fields);
|
||||
}
|
||||
|
||||
private List<FieldSpec> normalizeFields(List<AiFeatureField> input) {
|
||||
List<AiFeatureField> raw = input == null ? List.of() : input;
|
||||
List<FieldSpec> out = new ArrayList<>();
|
||||
Set<String> seen = new LinkedHashSet<>();
|
||||
for (AiFeatureField f : raw) {
|
||||
String column = normalizeColumn(f == null ? null : f.column());
|
||||
if (column == null || SYSTEM_COLUMNS.contains(column) || !seen.add(column)) {
|
||||
continue;
|
||||
}
|
||||
String type = normalizeType(f.type());
|
||||
Integer length = normalizeLength(type, f.length());
|
||||
String label = firstText(f.label(), column);
|
||||
out.add(new FieldSpec(column, label, type, length, Boolean.TRUE.equals(f.required())));
|
||||
}
|
||||
if (out.isEmpty()) {
|
||||
out.add(new FieldSpec("NAME", "名称", "string", 100, true));
|
||||
out.add(new FieldSpec("DESCRIPTION", "描述", "string", 500, false));
|
||||
}
|
||||
return List.copyOf(out);
|
||||
}
|
||||
|
||||
private static String normalizeTable(String raw, String seed) {
|
||||
String table = raw == null ? "" : raw.trim().toUpperCase(Locale.ROOT);
|
||||
table = table.replaceAll("[^A-Z0-9_]", "_").replaceAll("_+", "_");
|
||||
if (!table.matches("[A-Z][A-Z0-9_]{2,40}")) {
|
||||
table = "EIP4AI_" + sha(seed).substring(0, 10).toUpperCase(Locale.ROOT);
|
||||
}
|
||||
if (table.length() > 40) {
|
||||
table = table.substring(0, 40);
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
private static String normalizeTemplateId(String raw, String table) {
|
||||
String id = raw == null ? "" : raw.trim();
|
||||
if (id.isBlank()) {
|
||||
id = table.toLowerCase(Locale.ROOT).replace('_', '-');
|
||||
}
|
||||
id = id.replaceAll("[^A-Za-z0-9_.:-]", "-").replaceAll("-+", "-");
|
||||
return id.length() > 64 ? id.substring(0, 64) : id;
|
||||
}
|
||||
|
||||
private static String normalizeColumn(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String col = raw.trim().toUpperCase(Locale.ROOT).replaceAll("[^A-Z0-9_]", "_").replaceAll("_+", "_");
|
||||
if (!col.matches("[A-Z][A-Z0-9_]{0,39}")) {
|
||||
col = "F_" + col;
|
||||
}
|
||||
return col.length() > 40 ? col.substring(0, 40) : col;
|
||||
}
|
||||
|
||||
private static String normalizeType(String raw) {
|
||||
String t = raw == null ? "" : raw.trim().toLowerCase(Locale.ROOT);
|
||||
return switch (t) {
|
||||
case "int", "integer", "long" -> "integer";
|
||||
case "number", "decimal", "double", "money" -> "number";
|
||||
case "date" -> "date";
|
||||
case "datetime", "time", "timestamp" -> "datetime";
|
||||
case "bool", "boolean" -> "boolean";
|
||||
default -> "string";
|
||||
};
|
||||
}
|
||||
|
||||
private static Integer normalizeLength(String type, Integer length) {
|
||||
if (!"string".equals(type)) {
|
||||
return null;
|
||||
}
|
||||
if (length == null || length < 1) {
|
||||
return 100;
|
||||
}
|
||||
return Math.min(length, 2000);
|
||||
}
|
||||
|
||||
private static String controlType(String fieldType) {
|
||||
return switch (fieldType) {
|
||||
case "integer", "number" -> "input-number";
|
||||
case "date" -> "input-date";
|
||||
case "datetime" -> "input-datetime";
|
||||
case "boolean" -> "switch";
|
||||
default -> "input-text";
|
||||
};
|
||||
}
|
||||
|
||||
private static String displayColumn(FeatureSpec spec) {
|
||||
return spec.fields().stream()
|
||||
.filter(f -> "NAME".equals(f.column()) || f.required())
|
||||
.map(FieldSpec::column)
|
||||
.findFirst()
|
||||
.orElse(spec.fields().get(0).column());
|
||||
}
|
||||
|
||||
private static String lowerCamel(String table) {
|
||||
String[] parts = table.toLowerCase(Locale.ROOT).split("_+");
|
||||
StringBuilder sb = new StringBuilder(parts[0]);
|
||||
for (int i = 1; i < parts.length; i++) {
|
||||
if (!parts[i].isBlank()) {
|
||||
sb.append(Character.toUpperCase(parts[i].charAt(0))).append(parts[i].substring(1));
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String firstText(String... values) {
|
||||
for (String value : values) {
|
||||
if (value != null && !value.isBlank()) {
|
||||
return value.trim();
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private static Map<String, Object> metadata(String generatorStep, String publishTarget) {
|
||||
Map<String, Object> metadata = new LinkedHashMap<>();
|
||||
metadata.put("source", "ai-agent");
|
||||
metadata.put("generator", "deterministic-feature-v1");
|
||||
metadata.put("generatorStep", generatorStep);
|
||||
metadata.put("publishTarget", publishTarget);
|
||||
return metadata;
|
||||
}
|
||||
|
||||
private static String sha(String text) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return HexFormat.of().formatHex(digest.digest(String.valueOf(text).getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
throw new IllegalStateException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private record FeatureSpec(
|
||||
String featureName,
|
||||
String tableName,
|
||||
String entityName,
|
||||
String templateId,
|
||||
String menuName,
|
||||
List<FieldSpec> fields) {
|
||||
}
|
||||
|
||||
private record FieldSpec(
|
||||
String column,
|
||||
String label,
|
||||
String type,
|
||||
Integer length,
|
||||
boolean required) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
public record AiHttpResponse(
|
||||
int statusCode,
|
||||
String body) {
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.eip4.platform.ai.model.AiAgentRepairContext;
|
||||
import com.eip4.platform.ai.model.AiRepairDraftPatch;
|
||||
|
||||
public interface AiLlmRepairClient {
|
||||
|
||||
List<AiRepairDraftPatch> repair(AiAgentRepairContext context);
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import com.eip4.platform.ai.model.AiApplyStepResult;
|
||||
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;
|
||||
|
||||
@Component
|
||||
public class AiLocalReleaseExecutor {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final AiSmokeHttpClient httpClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public AiLocalReleaseExecutor(JdbcTemplate jdbcTemplate, AiSmokeHttpClient httpClient, ObjectMapper objectMapper) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.httpClient = httpClient;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
public List<AiApplyStepResult> apply(String baseUrl, List<AiDraft> drafts) {
|
||||
URI base = safeLocalBase(baseUrl);
|
||||
ApplyContext ctx = new ApplyContext(base);
|
||||
List<AiApplyStepResult> results = new ArrayList<>();
|
||||
for (AiDraft draft : drafts.stream().sorted(Comparator.comparingInt(d -> releaseOrder(d.artifactType()))).toList()) {
|
||||
if (draft.artifactType() == AiArtifactType.TEST) {
|
||||
continue;
|
||||
}
|
||||
AiApplyStepResult result = applyOne(ctx, draft, results.size() + 1);
|
||||
results.add(result);
|
||||
if ("FAILED".equals(result.status())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return List.copyOf(results);
|
||||
}
|
||||
|
||||
private static int releaseOrder(AiArtifactType type) {
|
||||
return switch (type) {
|
||||
case ENTITY -> 10;
|
||||
case SERVICEFLOW -> 20;
|
||||
case PAGE_SCHEMA -> 30;
|
||||
case MENU -> 40;
|
||||
case TEST -> 50;
|
||||
case CODE -> 60;
|
||||
};
|
||||
}
|
||||
|
||||
private AiApplyStepResult applyOne(ApplyContext ctx, AiDraft draft, int index) {
|
||||
try {
|
||||
return switch (draft.artifactType()) {
|
||||
case ENTITY -> applyEntity(ctx, draft, index);
|
||||
case SERVICEFLOW -> applyServiceFlows(ctx, draft, index);
|
||||
case PAGE_SCHEMA -> applyPageSchema(draft, index);
|
||||
case MENU -> applyMenu(ctx, draft, index);
|
||||
case CODE -> skipped(index, draft, "代码草稿暂不由平台运行时应用");
|
||||
case TEST -> skipped(index, draft, "TEST 由 smoke runner 执行");
|
||||
};
|
||||
} catch (Exception ex) {
|
||||
return new AiApplyStepResult("apply-" + index, draft.artifactType(), draft.targetId(), "FAILED",
|
||||
ex.getClass().getSimpleName() + ": " + String.valueOf(ex.getMessage()), Map.of());
|
||||
}
|
||||
}
|
||||
|
||||
private AiApplyStepResult applyEntity(ApplyContext ctx, AiDraft draft, int index) throws Exception {
|
||||
String tableName = draft.payload().path("tablename").asText(draft.targetId()).toUpperCase(Locale.ROOT);
|
||||
AiHttpResponse response = httpClient.exchange("POST", ctx.base().resolve("/api/meta/entity"),
|
||||
draft.payload(), Duration.ofSeconds(20));
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||
return failed(index, draft, "实体发布 HTTP " + response.statusCode(), Map.of("response", response.body()));
|
||||
}
|
||||
JsonNode root = objectMapper.readTree(response.body());
|
||||
if (root.path("status").asInt(1) != 0) {
|
||||
String message = root.path("msg").asText("unknown");
|
||||
if (message.contains("实体已存在")) {
|
||||
List<String> ids = jdbcTemplate.queryForList(
|
||||
"SELECT TRIM(sys_entity_id) FROM sys_entity WHERE tablename=? AND isactive=1",
|
||||
String.class, tableName);
|
||||
if (!ids.isEmpty()) {
|
||||
ctx.entityId(ids.get(0));
|
||||
ctx.tableName(tableName);
|
||||
return applied(index, draft, "实体已存在,复用本地 entityId",
|
||||
Map.of("entityId", ctx.entityId(), "tableName", ctx.tableName(), "idempotent", true));
|
||||
}
|
||||
}
|
||||
return failed(index, draft, "实体发布失败: " + message, Map.of());
|
||||
}
|
||||
String entityId = root.path("data").path("entityId").asText("");
|
||||
if (entityId.isBlank()) {
|
||||
return failed(index, draft, "实体发布响应缺 data.entityId", Map.of());
|
||||
}
|
||||
ctx.entityId(entityId);
|
||||
ctx.tableName(tableName);
|
||||
return applied(index, draft, "实体已创建", Map.of("entityId", entityId, "tableName", ctx.tableName()));
|
||||
}
|
||||
|
||||
private AiApplyStepResult applyServiceFlows(ApplyContext ctx, AiDraft draft, int index) {
|
||||
if (ctx.entityId().isBlank()) {
|
||||
return failed(index, draft, "缺少实体 entityId,不能发布服务流", Map.of());
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
int count = 0;
|
||||
for (JsonNode flow : draft.payload().path("flows")) {
|
||||
String key = flow.path("key").asText();
|
||||
String xml = flow.path("contentXml").asText().replace("${entityId}", ctx.entityId());
|
||||
jdbcTemplate.update("""
|
||||
INSERT INTO sys_serviceflow
|
||||
(sys_serviceflow_id, displayname, contentxml, entityid, iscontrol, isupdateable,
|
||||
isactive, createtime, updatetime, createby, updateby, version)
|
||||
VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, '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
|
||||
""",
|
||||
key,
|
||||
flow.path("displayName").asText(key),
|
||||
xml,
|
||||
ctx.entityId(),
|
||||
flow.path("control").asBoolean(true) ? 1 : 0,
|
||||
flow.path("updateable").asBoolean(true) ? 1 : 0,
|
||||
now,
|
||||
now);
|
||||
count++;
|
||||
}
|
||||
return applied(index, draft, "服务流已发布", Map.of("flowCount", count, "entityId", ctx.entityId()));
|
||||
}
|
||||
|
||||
private AiApplyStepResult applyPageSchema(AiDraft draft, int index) throws Exception {
|
||||
String schemaJson = objectMapper.writeValueAsString(draft.payload());
|
||||
String etag = sha256(schemaJson);
|
||||
long now = System.currentTimeMillis();
|
||||
jdbcTemplate.update("""
|
||||
INSERT INTO sys_page_schema (template_id, name, schema_json, schema_etag, version, update_time)
|
||||
VALUES (?, ?, ?::jsonb, ?, 1, ?)
|
||||
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
|
||||
""",
|
||||
draft.targetId(), draft.payload().path("title").asText(draft.targetId()), schemaJson, etag, now);
|
||||
return applied(index, draft, "页面 schema 已发布", Map.of("templateId", draft.targetId(), "etag", etag));
|
||||
}
|
||||
|
||||
private AiApplyStepResult applyMenu(ApplyContext ctx, AiDraft draft, int index) {
|
||||
if (!tableExists("sys_menu")) {
|
||||
return skipped(index, draft, "本地库缺少 sys_menu,菜单挂载跳过,部署包保留人工 SQL");
|
||||
}
|
||||
String templateId = draft.payload().path("viewTemplateId").asText(draft.targetId());
|
||||
String menuName = draft.payload().path("name").asText(templateId);
|
||||
String parentId = textOrBlank(draft.payload().get("parentId"));
|
||||
String menuRoot = textOrBlank(draft.payload().get("menuroot"));
|
||||
if (parentId.isBlank()) {
|
||||
ParentMenu parent = ensureAiMenuParent(menuRoot);
|
||||
parentId = parent.parentId();
|
||||
menuRoot = parent.menuRoot();
|
||||
}
|
||||
List<String> existing = jdbcTemplate.queryForList(
|
||||
"SELECT TRIM(sys_menu_id) FROM sys_menu WHERE TRIM(view_templateid)=? AND isactive=1",
|
||||
String.class, templateId);
|
||||
String menuId = existing.isEmpty() ? UUID.randomUUID().toString() : existing.get(0);
|
||||
long now = System.currentTimeMillis();
|
||||
if (existing.isEmpty()) {
|
||||
jdbcTemplate.update("""
|
||||
INSERT INTO sys_menu
|
||||
(sys_menu_id, name, parentid, view_templateid, typename, menuroot, seq,
|
||||
isactive, version, createtime, createby, updatetime, updateby)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 1, 0, ?, 'AI_AGENT', ?, 'AI_AGENT')
|
||||
""",
|
||||
menuId,
|
||||
menuName,
|
||||
parentId,
|
||||
templateId,
|
||||
draft.payload().path("typename").asText("功能菜单"),
|
||||
menuRoot.isBlank() ? null : menuRoot,
|
||||
draft.payload().path("seq").asInt(0),
|
||||
now,
|
||||
now);
|
||||
} else {
|
||||
jdbcTemplate.update("""
|
||||
UPDATE sys_menu
|
||||
SET name=?, parentid=?, view_templateid=?, typename=?, menuroot=?, seq=?,
|
||||
updatetime=?, updateby='AI_AGENT', version=version+1
|
||||
WHERE TRIM(sys_menu_id)=?
|
||||
""",
|
||||
menuName,
|
||||
parentId,
|
||||
templateId,
|
||||
draft.payload().path("typename").asText("功能菜单"),
|
||||
menuRoot.isBlank() ? null : menuRoot,
|
||||
draft.payload().path("seq").asInt(0),
|
||||
now,
|
||||
menuId);
|
||||
}
|
||||
return applied(index, draft, "菜单已挂载", Map.of("menuId", menuId, "parentId", parentId));
|
||||
}
|
||||
|
||||
private ParentMenu ensureAiMenuParent(String preferredRoot) {
|
||||
List<String> existingDir = jdbcTemplate.queryForList(
|
||||
"SELECT TRIM(sys_menu_id) FROM sys_menu WHERE name='AI Agent' AND parentid IS NULL AND isactive=1 ORDER BY seq LIMIT 1",
|
||||
String.class);
|
||||
if (!existingDir.isEmpty()) {
|
||||
String root = preferredRoot;
|
||||
if (root == null || root.isBlank()) {
|
||||
List<String> roots = jdbcTemplate.queryForList(
|
||||
"SELECT TRIM(menuroot) FROM sys_menu WHERE TRIM(sys_menu_id)=?",
|
||||
String.class, existingDir.get(0));
|
||||
root = roots.isEmpty() ? "" : roots.get(0);
|
||||
}
|
||||
return new ParentMenu(existingDir.get(0), root == null ? "" : root);
|
||||
}
|
||||
String root = preferredRoot;
|
||||
if (root == null || root.isBlank()) {
|
||||
List<String> roots = jdbcTemplate.queryForList(
|
||||
"SELECT TRIM(sys_menu_root_id) FROM sys_menu_root WHERE isactive=1 ORDER BY seq LIMIT 1",
|
||||
String.class);
|
||||
if (roots.isEmpty()) {
|
||||
throw new ResponseStatusException(HttpStatus.CONFLICT, "缺少 sys_menu_root,不能自动挂载菜单");
|
||||
}
|
||||
root = roots.get(0);
|
||||
}
|
||||
String dirId = UUID.randomUUID().toString();
|
||||
long now = System.currentTimeMillis();
|
||||
jdbcTemplate.update("""
|
||||
INSERT INTO sys_menu
|
||||
(sys_menu_id, name, parentid, view_templateid, typename, menuroot, seq,
|
||||
isactive, version, createtime, createby, updatetime, updateby)
|
||||
VALUES (?, 'AI Agent', NULL, NULL, '目录', ?, 9999, 1, 0, ?, 'AI_AGENT', ?, 'AI_AGENT')
|
||||
""",
|
||||
dirId, root, now, now);
|
||||
return new ParentMenu(dirId, root);
|
||||
}
|
||||
|
||||
private boolean tableExists(String tableName) {
|
||||
try {
|
||||
Boolean exists = jdbcTemplate.queryForObject("SELECT to_regclass(?) IS NOT NULL", Boolean.class, tableName);
|
||||
return Boolean.TRUE.equals(exists);
|
||||
} catch (RuntimeException ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static AiApplyStepResult applied(int index, AiDraft draft, String message, Map<String, Object> details) {
|
||||
return new AiApplyStepResult("apply-" + index, draft.artifactType(), draft.targetId(),
|
||||
"APPLIED", message, details);
|
||||
}
|
||||
|
||||
private static AiApplyStepResult failed(int index, AiDraft draft, String message, Map<String, Object> details) {
|
||||
return new AiApplyStepResult("apply-" + index, draft.artifactType(), draft.targetId(),
|
||||
"FAILED", message, details);
|
||||
}
|
||||
|
||||
private static AiApplyStepResult skipped(int index, AiDraft draft, String message) {
|
||||
return new AiApplyStepResult("apply-" + index, draft.artifactType(), draft.targetId(),
|
||||
"SKIPPED", message, Map.of());
|
||||
}
|
||||
|
||||
private static URI safeLocalBase(String raw) {
|
||||
String value = raw == null || raw.isBlank() ? "http://localhost:8084" : raw.trim();
|
||||
URI uri;
|
||||
try {
|
||||
uri = URI.create(value);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "baseUrl 不合法: " + value);
|
||||
}
|
||||
String scheme = uri.getScheme();
|
||||
String host = uri.getHost();
|
||||
if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "baseUrl 只允许 http/https");
|
||||
}
|
||||
if (!isLocalHost(host)) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "本地发布仅允许访问本机地址");
|
||||
}
|
||||
String normalized = uri.toString();
|
||||
if (!normalized.endsWith("/")) {
|
||||
normalized += "/";
|
||||
}
|
||||
return URI.create(normalized);
|
||||
}
|
||||
|
||||
private static boolean isLocalHost(String host) {
|
||||
if (host == null) {
|
||||
return false;
|
||||
}
|
||||
String h = host.toLowerCase(Locale.ROOT);
|
||||
return "localhost".equals(h) || "127.0.0.1".equals(h) || "::1".equals(h) || "[::1]".equals(h);
|
||||
}
|
||||
|
||||
private static String textOrBlank(JsonNode node) {
|
||||
if (node == null || node.isNull()) {
|
||||
return "";
|
||||
}
|
||||
String value = node.asText("");
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
|
||||
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 class ApplyContext {
|
||||
private final URI base;
|
||||
private String entityId = "";
|
||||
private String tableName = "";
|
||||
|
||||
ApplyContext(URI base) {
|
||||
this.base = base;
|
||||
}
|
||||
|
||||
URI base() {
|
||||
return base;
|
||||
}
|
||||
|
||||
String entityId() {
|
||||
return entityId;
|
||||
}
|
||||
|
||||
void entityId(String entityId) {
|
||||
this.entityId = entityId == null ? "" : entityId;
|
||||
}
|
||||
|
||||
String tableName() {
|
||||
return tableName;
|
||||
}
|
||||
|
||||
void tableName(String tableName) {
|
||||
this.tableName = tableName == null ? "" : tableName;
|
||||
}
|
||||
}
|
||||
|
||||
private record ParentMenu(String parentId, String menuRoot) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
public interface AiSmokeHttpClient {
|
||||
|
||||
AiHttpResponse exchange(String method, URI uri, JsonNode requestBody, Duration timeout) throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import java.net.URI;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import com.eip4.platform.ai.model.AiSmokeResult;
|
||||
import com.eip4.platform.ai.model.AiSmokeRun;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@Component
|
||||
public class AiSmokeRunner {
|
||||
|
||||
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(8);
|
||||
private static final int SNIPPET_LIMIT = 600;
|
||||
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||
|
||||
private final AiSmokeHttpClient httpClient;
|
||||
|
||||
public AiSmokeRunner(AiSmokeHttpClient httpClient) {
|
||||
this.httpClient = httpClient;
|
||||
}
|
||||
|
||||
public AiSmokeRun run(String taskId, String changeSetId, String baseUrl, JsonNode testPayload) {
|
||||
URI base = safeLocalBase(baseUrl);
|
||||
JsonNode tests = testPayload == null ? null : testPayload.path("smokeTests");
|
||||
if (tests == null || !tests.isArray() || tests.isEmpty()) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "没有可执行的 smokeTests");
|
||||
}
|
||||
|
||||
long started = System.currentTimeMillis();
|
||||
List<AiSmokeResult> results = new ArrayList<>();
|
||||
for (JsonNode test : tests) {
|
||||
results.add(runOne(base, test));
|
||||
}
|
||||
long finished = System.currentTimeMillis();
|
||||
boolean passed = results.stream().allMatch(AiSmokeResult::passed);
|
||||
return new AiSmokeRun(taskId, changeSetId, base.toString(), passed ? "PASSED" : "FAILED",
|
||||
started, finished, List.copyOf(results));
|
||||
}
|
||||
|
||||
private AiSmokeResult runOne(URI base, JsonNode test) {
|
||||
String name = text(test, "name", "unnamed");
|
||||
String method = text(test, "method", "GET").toUpperCase(Locale.ROOT);
|
||||
String url = text(test, "url", "");
|
||||
int expected = test.path("expectHttpStatus").asInt(200);
|
||||
long started = System.currentTimeMillis();
|
||||
if (!url.startsWith("/api/")) {
|
||||
return failed(name, method, url, expected, -1, started, "smoke url 必须以 /api/ 开头", "");
|
||||
}
|
||||
if (!List.of("GET", "POST", "PUT", "DELETE", "PATCH").contains(method)) {
|
||||
return failed(name, method, url, expected, -1, started, "不支持的 HTTP method: " + method, "");
|
||||
}
|
||||
try {
|
||||
URI uri = base.resolve(url);
|
||||
AiHttpResponse response = httpClient.exchange(method, uri, test.get("requestBody"), REQUEST_TIMEOUT);
|
||||
boolean passed = response.statusCode() == expected;
|
||||
String err = passed ? businessStatusError(response.body())
|
||||
: "期望 HTTP " + expected + ",实际 HTTP " + response.statusCode();
|
||||
passed = passed && err.isBlank();
|
||||
return new AiSmokeResult(name, method, url, expected, response.statusCode(), passed,
|
||||
System.currentTimeMillis() - started, err, snippet(response.body()));
|
||||
} catch (Exception ex) {
|
||||
return failed(name, method, url, expected, -1, started,
|
||||
ex.getClass().getSimpleName() + ": " + String.valueOf(ex.getMessage()), "");
|
||||
}
|
||||
}
|
||||
|
||||
private static AiSmokeResult failed(String name, String method, String url, int expected, int actual,
|
||||
long started, String error, String response) {
|
||||
return new AiSmokeResult(name, method, url, expected, actual, false,
|
||||
System.currentTimeMillis() - started, error, snippet(response));
|
||||
}
|
||||
|
||||
private static URI safeLocalBase(String raw) {
|
||||
String value = raw == null || raw.isBlank() ? "http://localhost:8084" : raw.trim();
|
||||
URI uri;
|
||||
try {
|
||||
uri = URI.create(value);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "baseUrl 不合法: " + value);
|
||||
}
|
||||
String scheme = uri.getScheme();
|
||||
String host = uri.getHost();
|
||||
if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "baseUrl 只允许 http/https");
|
||||
}
|
||||
if (!isLocalHost(host)) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "smoke 仅允许访问本机地址");
|
||||
}
|
||||
String normalized = uri.toString();
|
||||
if (!normalized.endsWith("/")) {
|
||||
normalized += "/";
|
||||
}
|
||||
return URI.create(normalized);
|
||||
}
|
||||
|
||||
private static boolean isLocalHost(String host) {
|
||||
if (host == null) {
|
||||
return false;
|
||||
}
|
||||
String h = host.toLowerCase(Locale.ROOT);
|
||||
return "localhost".equals(h) || "127.0.0.1".equals(h) || "::1".equals(h) || "[::1]".equals(h);
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String field, String fallback) {
|
||||
JsonNode value = node == null ? null : node.get(field);
|
||||
if (value == null || value.isNull()) {
|
||||
return fallback;
|
||||
}
|
||||
String s = value.asText();
|
||||
return s == null || s.isBlank() ? fallback : s.trim();
|
||||
}
|
||||
|
||||
private static String snippet(String body) {
|
||||
if (body == null || body.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
String compact = body.replaceAll("\\s+", " ").trim();
|
||||
return compact.length() <= SNIPPET_LIMIT ? compact : compact.substring(0, SNIPPET_LIMIT);
|
||||
}
|
||||
|
||||
private static String businessStatusError(String body) {
|
||||
if (body == null || body.isBlank()) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
JsonNode root = OBJECT_MAPPER.readTree(body);
|
||||
JsonNode status = root == null || !root.isObject() ? null : root.get("status");
|
||||
if (status != null && !status.isNull() && status.asInt(0) != 0) {
|
||||
String msg = root.path("msg").asText("");
|
||||
return msg.isBlank() ? "响应 JSON status=" + status.asText()
|
||||
: "响应 JSON status=" + status.asText() + ": " + msg;
|
||||
}
|
||||
} catch (Exception ignore) {
|
||||
return "";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.eip4.platform.ai.model.AiAgentRepairContext;
|
||||
import com.eip4.platform.ai.model.AiAgentRepairResult;
|
||||
import com.eip4.platform.ai.model.AiArtifactType;
|
||||
import com.eip4.platform.ai.model.AiDraft;
|
||||
import com.eip4.platform.ai.model.AiRepairAction;
|
||||
import com.eip4.platform.ai.model.AiRepairDraftPatch;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
|
||||
@Component
|
||||
public class DeterministicAiAgentRepairExecutor implements AiAgentRepairExecutor {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final List<AiLlmRepairClient> llmRepairClients;
|
||||
|
||||
@Autowired
|
||||
public DeterministicAiAgentRepairExecutor(ObjectMapper objectMapper, List<AiLlmRepairClient> llmRepairClients) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.llmRepairClients = llmRepairClients == null ? List.of() : List.copyOf(llmRepairClients);
|
||||
}
|
||||
|
||||
public DeterministicAiAgentRepairExecutor(ObjectMapper objectMapper) {
|
||||
this(objectMapper, List.of());
|
||||
}
|
||||
|
||||
@Override
|
||||
public AiAgentRepairResult repair(AiAgentRepairContext context) {
|
||||
if (context == null || context.repairPlan() == null || context.drafts() == null) {
|
||||
return new AiAgentRepairResult("NOOP", List.of(), List.of("缺少修复上下文"));
|
||||
}
|
||||
AiAgentRepairResult llmResult = tryLlmRepair(context);
|
||||
if (!llmResult.draftPatches().isEmpty()) {
|
||||
return llmResult;
|
||||
}
|
||||
List<AiRepairDraftPatch> patches = new ArrayList<>();
|
||||
List<String> messages = new ArrayList<>();
|
||||
for (AiRepairAction action : context.repairPlan().actions()) {
|
||||
if ("REPAIR_ENTITY_METADATA_OR_LOCAL_API".equals(action.actionType())) {
|
||||
entityMetadataPatch(context, action).ifPresentOrElse(
|
||||
patch -> {
|
||||
patches.add(patch);
|
||||
messages.add("已生成 ENTITY 草稿修复: " + action.targetId());
|
||||
},
|
||||
() -> messages.add("未找到可确定修复的 ENTITY 草稿: " + action.targetId()));
|
||||
} else if ("REPAIR_SMOKE_EXPECTATION_OR_API_CONTRACT".equals(action.actionType())) {
|
||||
smokeExpectationPatch(context, action).ifPresentOrElse(
|
||||
patch -> {
|
||||
patches.add(patch);
|
||||
messages.add("已生成 TEST 草稿修复: " + action.targetId());
|
||||
},
|
||||
() -> messages.add("未找到可修复的 TEST 草稿: " + action.targetId()));
|
||||
} else if ("REPAIR_PAGE_SCHEMA_SQL_OR_SCHEMA".equals(action.actionType())) {
|
||||
pageSchemaPatch(context, action).ifPresentOrElse(
|
||||
patch -> {
|
||||
patches.add(patch);
|
||||
messages.add("已生成 PAGE_SCHEMA 草稿修复: " + action.targetId());
|
||||
},
|
||||
() -> messages.add("未找到可确定修复的 PAGE_SCHEMA 草稿: " + action.targetId()));
|
||||
} else if ("SEED_MENU_ROOT_OR_SET_PARENT".equals(action.actionType())
|
||||
|| "REPAIR_MENU_BINDING".equals(action.actionType())) {
|
||||
menuParentPatch(context, action).ifPresentOrElse(
|
||||
patch -> {
|
||||
patches.add(patch);
|
||||
messages.add("已生成 MENU 草稿修复: " + action.targetId());
|
||||
},
|
||||
() -> messages.add("未找到可确定修复的 MENU 草稿: " + action.targetId()));
|
||||
} else if ("RETRY_AFTER_ENTITY_ID_RESOLUTION".equals(action.actionType())
|
||||
|| "REPAIR_SERVICEFLOW_XML_OR_SQL".equals(action.actionType())) {
|
||||
serviceFlowEntityBindingPatch(context, action).ifPresentOrElse(
|
||||
patch -> {
|
||||
patches.add(patch);
|
||||
messages.add("已生成 SERVICEFLOW 草稿修复: " + action.targetId());
|
||||
},
|
||||
() -> messages.add("未找到可确定修复的 SERVICEFLOW 草稿: " + action.targetId()));
|
||||
}
|
||||
}
|
||||
String status = patches.isEmpty() ? "NO_PATCHES" : "PATCHES_GENERATED";
|
||||
return new AiAgentRepairResult(status, List.copyOf(patches), List.copyOf(messages));
|
||||
}
|
||||
|
||||
private AiAgentRepairResult tryLlmRepair(AiAgentRepairContext context) {
|
||||
List<AiRepairDraftPatch> patches = new ArrayList<>();
|
||||
List<String> messages = new ArrayList<>();
|
||||
for (AiLlmRepairClient client : llmRepairClients) {
|
||||
List<AiRepairDraftPatch> one = client.repair(context);
|
||||
if (one != null && !one.isEmpty()) {
|
||||
patches.addAll(one);
|
||||
messages.add("LLM repair client generated " + one.size() + " draft patch(es)");
|
||||
break;
|
||||
}
|
||||
}
|
||||
return new AiAgentRepairResult(patches.isEmpty() ? "NO_PATCHES" : "PATCHES_GENERATED",
|
||||
List.copyOf(patches), List.copyOf(messages));
|
||||
}
|
||||
|
||||
private java.util.Optional<AiRepairDraftPatch> entityMetadataPatch(AiAgentRepairContext context,
|
||||
AiRepairAction action) {
|
||||
for (AiDraft draft : context.drafts()) {
|
||||
if (draft.artifactType() != AiArtifactType.ENTITY || !draft.targetId().equals(action.targetId())) {
|
||||
continue;
|
||||
}
|
||||
ObjectNode copy = draft.payload().deepCopy();
|
||||
boolean changed = false;
|
||||
if (!"/api/meta/entity".equals(copy.path("publishTarget").asText(""))) {
|
||||
copy.put("publishTarget", "/api/meta/entity");
|
||||
changed = true;
|
||||
}
|
||||
if (copy.path("tablename").asText("").isBlank()) {
|
||||
copy.put("tablename", draft.targetId());
|
||||
changed = true;
|
||||
}
|
||||
if (copy.path("name").asText("").isBlank()) {
|
||||
copy.put("name", draft.targetId());
|
||||
changed = true;
|
||||
}
|
||||
JsonNode attrs = copy.path("attributes");
|
||||
if (attrs.isArray()) {
|
||||
for (JsonNode attr : attrs) {
|
||||
if (attr instanceof ObjectNode node && node.path("display").asText("").isBlank()) {
|
||||
node.put("display", node.path("column").asText("字段"));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!changed) {
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
return java.util.Optional.of(new AiRepairDraftPatch(
|
||||
AiArtifactType.ENTITY,
|
||||
draft.targetId(),
|
||||
copy,
|
||||
Map.of(
|
||||
"source", "deterministic-agent-repair",
|
||||
"repairActionId", action.id(),
|
||||
"supersedesDraftId", draft.id())));
|
||||
}
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
|
||||
private java.util.Optional<AiRepairDraftPatch> serviceFlowEntityBindingPatch(AiAgentRepairContext context,
|
||||
AiRepairAction action) {
|
||||
for (AiDraft draft : context.drafts()) {
|
||||
if (draft.artifactType() != AiArtifactType.SERVICEFLOW || !draft.targetId().equals(action.targetId())) {
|
||||
continue;
|
||||
}
|
||||
ObjectNode copy = draft.payload().deepCopy();
|
||||
JsonNode flows = copy.path("flows");
|
||||
if (!flows.isArray()) {
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
boolean changed = false;
|
||||
copy.put("requiresEntityId", true);
|
||||
copy.put("entityIdBinding", "publish ENTITY draft first, then replace ${entityId}");
|
||||
for (JsonNode flow : flows) {
|
||||
if (!(flow instanceof ObjectNode node)) {
|
||||
continue;
|
||||
}
|
||||
String existingEntityId = node.path("entityId").asText("");
|
||||
String xml = node.path("contentXml").asText("");
|
||||
if (!"${entityId}".equals(existingEntityId)) {
|
||||
node.put("entityId", "${entityId}");
|
||||
changed = true;
|
||||
}
|
||||
if (!xml.contains("${entityId}") && !existingEntityId.isBlank()) {
|
||||
node.put("contentXml", xml.replace(existingEntityId, "${entityId}"));
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) {
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
return java.util.Optional.of(new AiRepairDraftPatch(
|
||||
AiArtifactType.SERVICEFLOW,
|
||||
draft.targetId(),
|
||||
copy,
|
||||
Map.of(
|
||||
"source", "deterministic-agent-repair",
|
||||
"repairActionId", action.id(),
|
||||
"supersedesDraftId", draft.id())));
|
||||
}
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
|
||||
private java.util.Optional<AiRepairDraftPatch> menuParentPatch(AiAgentRepairContext context,
|
||||
AiRepairAction action) {
|
||||
for (AiDraft draft : context.drafts()) {
|
||||
if (draft.artifactType() != AiArtifactType.MENU || !draft.targetId().equals(action.targetId())) {
|
||||
continue;
|
||||
}
|
||||
ObjectNode copy = draft.payload().deepCopy();
|
||||
boolean changed = false;
|
||||
if (copy.path("parentId").asText("").isBlank()) {
|
||||
copy.put("parentId", "${parentMenuId}");
|
||||
changed = true;
|
||||
}
|
||||
if (copy.path("menuroot").asText("").isBlank()) {
|
||||
copy.put("menuroot", "${menuRoot}");
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) {
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
return java.util.Optional.of(new AiRepairDraftPatch(
|
||||
AiArtifactType.MENU,
|
||||
draft.targetId(),
|
||||
copy,
|
||||
Map.of(
|
||||
"source", "deterministic-agent-repair",
|
||||
"repairActionId", action.id(),
|
||||
"supersedesDraftId", draft.id(),
|
||||
"requiresHumanReplacement", true)));
|
||||
}
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
|
||||
private java.util.Optional<AiRepairDraftPatch> pageSchemaPatch(AiAgentRepairContext context,
|
||||
AiRepairAction action) {
|
||||
for (AiDraft draft : context.drafts()) {
|
||||
if (draft.artifactType() != AiArtifactType.PAGE_SCHEMA || !draft.targetId().equals(action.targetId())) {
|
||||
continue;
|
||||
}
|
||||
ObjectNode copy = draft.payload().deepCopy();
|
||||
boolean changed = false;
|
||||
if (copy.path("type").asText("").isBlank()) {
|
||||
copy.put("type", "page");
|
||||
changed = true;
|
||||
}
|
||||
if (copy.path("title").asText("").isBlank()) {
|
||||
copy.put("title", draft.targetId());
|
||||
changed = true;
|
||||
}
|
||||
JsonNode body = copy.get("body");
|
||||
if (body == null || body.isNull()) {
|
||||
copy.putArray("body");
|
||||
changed = true;
|
||||
}
|
||||
if (!changed) {
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
return java.util.Optional.of(new AiRepairDraftPatch(
|
||||
AiArtifactType.PAGE_SCHEMA,
|
||||
draft.targetId(),
|
||||
copy,
|
||||
Map.of(
|
||||
"source", "deterministic-agent-repair",
|
||||
"repairActionId", action.id(),
|
||||
"supersedesDraftId", draft.id())));
|
||||
}
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
|
||||
private java.util.Optional<AiRepairDraftPatch> smokeExpectationPatch(AiAgentRepairContext context,
|
||||
AiRepairAction action) {
|
||||
int actual = intDetail(action, "actualHttpStatus", -1);
|
||||
if (actual < 200 || actual >= 300) {
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
String method = stringDetail(action, "method");
|
||||
String url = stringDetail(action, "url");
|
||||
for (AiDraft draft : context.drafts()) {
|
||||
if (draft.artifactType() != AiArtifactType.TEST) {
|
||||
continue;
|
||||
}
|
||||
ObjectNode copy = draft.payload().deepCopy();
|
||||
JsonNode tests = copy.path("smokeTests");
|
||||
if (!tests.isArray()) {
|
||||
continue;
|
||||
}
|
||||
boolean changed = false;
|
||||
for (JsonNode test : tests) {
|
||||
if (test instanceof ObjectNode node
|
||||
&& method.equalsIgnoreCase(node.path("method").asText(""))
|
||||
&& url.equals(node.path("url").asText(""))) {
|
||||
node.put("expectHttpStatus", actual);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (changed) {
|
||||
return java.util.Optional.of(new AiRepairDraftPatch(
|
||||
AiArtifactType.TEST,
|
||||
draft.targetId(),
|
||||
copy,
|
||||
Map.of(
|
||||
"source", "deterministic-agent-repair",
|
||||
"repairActionId", action.id(),
|
||||
"supersedesDraftId", draft.id())));
|
||||
}
|
||||
}
|
||||
return java.util.Optional.empty();
|
||||
}
|
||||
|
||||
private static int intDetail(AiRepairAction action, String key, int fallback) {
|
||||
Object value = action.details() == null ? null : action.details().get(key);
|
||||
if (value instanceof Number n) {
|
||||
return n.intValue();
|
||||
}
|
||||
if (value instanceof String s) {
|
||||
try {
|
||||
return Integer.parseInt(s);
|
||||
} catch (NumberFormatException ignored) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
private static String stringDetail(AiRepairAction action, String key) {
|
||||
Object value = action.details() == null ? null : action.details().get(key);
|
||||
return value == null ? "" : String.valueOf(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.eip4.platform.ai.model.AiAgentRepairContext;
|
||||
import com.eip4.platform.ai.model.AiRepairDraftPatch;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "eip4.ai.llm.repair.enabled", havingValue = "true")
|
||||
public class HttpAiLlmRepairClient implements AiLlmRepairClient {
|
||||
|
||||
private static final TypeReference<List<AiRepairDraftPatch>> PATCH_LIST = new TypeReference<>() {
|
||||
};
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final HttpClient httpClient;
|
||||
private final URI endpoint;
|
||||
private final String apiKey;
|
||||
private final String model;
|
||||
|
||||
public HttpAiLlmRepairClient(ObjectMapper objectMapper,
|
||||
@Value("${eip4.ai.llm.repair.endpoint:}") String endpoint,
|
||||
@Value("${eip4.ai.llm.repair.api-key:}") String apiKey,
|
||||
@Value("${eip4.ai.llm.repair.model:}") String model) {
|
||||
this(objectMapper, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(),
|
||||
endpoint, apiKey, model);
|
||||
}
|
||||
|
||||
HttpAiLlmRepairClient(ObjectMapper objectMapper, HttpClient httpClient,
|
||||
String endpoint, String apiKey, String model) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.httpClient = httpClient;
|
||||
this.endpoint = endpoint == null || endpoint.isBlank() ? null : URI.create(endpoint.trim());
|
||||
this.apiKey = apiKey == null ? "" : apiKey.trim();
|
||||
this.model = model == null ? "" : model.trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AiRepairDraftPatch> repair(AiAgentRepairContext context) {
|
||||
if (endpoint == null || context == null) {
|
||||
return List.of();
|
||||
}
|
||||
try {
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder(endpoint)
|
||||
.timeout(Duration.ofSeconds(60))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(json(requestPayload(context))));
|
||||
if (!apiKey.isBlank()) {
|
||||
builder.header("Authorization", "Bearer " + apiKey);
|
||||
}
|
||||
HttpResponse<String> response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||
return List.of();
|
||||
}
|
||||
return parsePatches(response.body());
|
||||
} catch (Exception ex) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> requestPayload(AiAgentRepairContext context) {
|
||||
return Map.of(
|
||||
"model", model,
|
||||
"taskId", context.taskId(),
|
||||
"changeSetId", context.changeSetId(),
|
||||
"repairPlan", context.repairPlan(),
|
||||
"drafts", context.drafts(),
|
||||
"contract", Map.of(
|
||||
"responseField", "draftPatches",
|
||||
"patchShape", "artifactType,targetId,payload,metadata",
|
||||
"rule", "Return only safe draft patches; do not execute production changes"));
|
||||
}
|
||||
|
||||
private List<AiRepairDraftPatch> parsePatches(String body) throws JsonProcessingException {
|
||||
var root = objectMapper.readTree(body);
|
||||
var patches = root.path("draftPatches");
|
||||
if (!patches.isArray()) {
|
||||
return List.of();
|
||||
}
|
||||
return objectMapper.convertValue(patches, PATCH_LIST);
|
||||
}
|
||||
|
||||
private String json(Object value) throws JsonProcessingException {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.eip4.platform.ai.service;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@Component
|
||||
public class JdkAiSmokeHttpClient implements AiSmokeHttpClient {
|
||||
|
||||
private final HttpClient httpClient;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
public JdkAiSmokeHttpClient(ObjectMapper objectMapper) {
|
||||
this(HttpClient.newHttpClient(), objectMapper);
|
||||
}
|
||||
|
||||
JdkAiSmokeHttpClient(HttpClient httpClient, ObjectMapper objectMapper) {
|
||||
this.httpClient = httpClient;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AiHttpResponse exchange(String method, URI uri, JsonNode requestBody, Duration timeout) throws Exception {
|
||||
HttpRequest.BodyPublisher body = requestBody == null || requestBody.isNull()
|
||||
? HttpRequest.BodyPublishers.noBody()
|
||||
: HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(requestBody));
|
||||
HttpRequest.Builder builder = HttpRequest.newBuilder(uri)
|
||||
.timeout(timeout)
|
||||
.header("Accept", "application/json");
|
||||
if (requestBody != null && !requestBody.isNull()) {
|
||||
builder.header("Content-Type", "application/json");
|
||||
}
|
||||
HttpRequest request = builder.method(method, body).build();
|
||||
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||
return new AiHttpResponse(response.statusCode(), response.body());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.eip4.platform.ai.store;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.eip4.platform.ai.model.AiAuditEntry;
|
||||
import com.eip4.platform.ai.model.AiChangeSet;
|
||||
import com.eip4.platform.ai.model.AiDraft;
|
||||
import com.eip4.platform.ai.model.AiRunRecord;
|
||||
import com.eip4.platform.ai.model.AiTask;
|
||||
|
||||
public interface AiAgentStore {
|
||||
|
||||
void saveTask(AiTask task);
|
||||
|
||||
Optional<AiTask> findTask(String taskId);
|
||||
|
||||
void saveDraft(AiDraft draft);
|
||||
|
||||
List<AiDraft> listDrafts(String taskId);
|
||||
|
||||
void saveChangeSet(AiChangeSet changeSet);
|
||||
|
||||
List<AiChangeSet> listChangeSets(String taskId);
|
||||
|
||||
void saveRun(AiRunRecord run);
|
||||
|
||||
List<AiRunRecord> listRuns(String taskId);
|
||||
|
||||
void saveAudit(AiAuditEntry entry);
|
||||
|
||||
List<AiAuditEntry> listAudit(String taskId);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package com.eip4.platform.ai.store;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.eip4.platform.ai.model.AiAuditEntry;
|
||||
import com.eip4.platform.ai.model.AiChangeSet;
|
||||
import com.eip4.platform.ai.model.AiDraft;
|
||||
import com.eip4.platform.ai.model.AiRunRecord;
|
||||
import com.eip4.platform.ai.model.AiTask;
|
||||
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "eip4.ai.store", havingValue = "memory", matchIfMissing = true)
|
||||
public class InMemoryAiAgentStore implements AiAgentStore {
|
||||
|
||||
private final Map<String, AiTask> tasks = new ConcurrentHashMap<>();
|
||||
private final Map<String, List<AiDraft>> draftsByTask = new ConcurrentHashMap<>();
|
||||
private final Map<String, List<AiAuditEntry>> auditByTask = new ConcurrentHashMap<>();
|
||||
private final Map<String, List<AiChangeSet>> changeSetsByTask = new ConcurrentHashMap<>();
|
||||
private final Map<String, List<AiRunRecord>> runsByTask = new ConcurrentHashMap<>();
|
||||
|
||||
@Override
|
||||
public void saveTask(AiTask task) {
|
||||
tasks.put(task.id(), task);
|
||||
draftsByTask.computeIfAbsent(task.id(), ignored -> new CopyOnWriteArrayList<>());
|
||||
auditByTask.computeIfAbsent(task.id(), ignored -> new CopyOnWriteArrayList<>());
|
||||
changeSetsByTask.computeIfAbsent(task.id(), ignored -> new CopyOnWriteArrayList<>());
|
||||
runsByTask.computeIfAbsent(task.id(), ignored -> new CopyOnWriteArrayList<>());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<AiTask> findTask(String taskId) {
|
||||
return Optional.ofNullable(tasks.get(taskId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveDraft(AiDraft draft) {
|
||||
draftsByTask.computeIfAbsent(draft.taskId(), ignored -> new CopyOnWriteArrayList<>()).add(draft);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AiDraft> listDrafts(String taskId) {
|
||||
return List.copyOf(draftsByTask.getOrDefault(taskId, List.of()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveChangeSet(AiChangeSet changeSet) {
|
||||
changeSetsByTask.computeIfAbsent(changeSet.taskId(), ignored -> new CopyOnWriteArrayList<>()).add(changeSet);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AiChangeSet> listChangeSets(String taskId) {
|
||||
return List.copyOf(changeSetsByTask.getOrDefault(taskId, List.of()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveRun(AiRunRecord run) {
|
||||
runsByTask.computeIfAbsent(run.taskId(), ignored -> new CopyOnWriteArrayList<>()).add(run);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AiRunRecord> listRuns(String taskId) {
|
||||
return List.copyOf(runsByTask.getOrDefault(taskId, List.of()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveAudit(AiAuditEntry entry) {
|
||||
auditByTask.computeIfAbsent(entry.taskId(), ignored -> new CopyOnWriteArrayList<>()).add(entry);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AiAuditEntry> listAudit(String taskId) {
|
||||
return List.copyOf(auditByTask.getOrDefault(taskId, List.of()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package com.eip4.platform.ai.store;
|
||||
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.jdbc.core.RowMapper;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.eip4.platform.ai.model.AiArtifactType;
|
||||
import com.eip4.platform.ai.model.AiAuditEntry;
|
||||
import com.eip4.platform.ai.model.AiChangeSet;
|
||||
import com.eip4.platform.ai.model.AiDraft;
|
||||
import com.eip4.platform.ai.model.AiGateResult;
|
||||
import com.eip4.platform.ai.model.AiRunRecord;
|
||||
import com.eip4.platform.ai.model.AiTask;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "eip4.ai.store", havingValue = "jdbc")
|
||||
public class JdbcAiAgentStore implements AiAgentStore {
|
||||
|
||||
private static final TypeReference<List<String>> STRING_LIST = new TypeReference<>() {
|
||||
};
|
||||
private static final TypeReference<List<AiGateResult>> GATE_LIST = new TypeReference<>() {
|
||||
};
|
||||
private static final TypeReference<Map<String, Object>> OBJECT_MAP = new TypeReference<>() {
|
||||
};
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public JdbcAiAgentStore(JdbcTemplate jdbcTemplate, ObjectMapper objectMapper) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveTask(AiTask task) {
|
||||
jdbcTemplate.update("""
|
||||
INSERT INTO sys_ai_task (task_id, objective, status, plan_json, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?::jsonb, ?, ?)
|
||||
ON CONFLICT (task_id) DO UPDATE SET
|
||||
objective = EXCLUDED.objective,
|
||||
status = EXCLUDED.status,
|
||||
plan_json = EXCLUDED.plan_json,
|
||||
updated_at = EXCLUDED.updated_at
|
||||
""",
|
||||
task.id(), task.objective(), task.status(), json(task.plan()), task.createdAt(), task.updatedAt());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<AiTask> findTask(String taskId) {
|
||||
List<AiTask> rows = jdbcTemplate.query("""
|
||||
SELECT task_id, objective, status, plan_json, created_at, updated_at
|
||||
FROM sys_ai_task
|
||||
WHERE task_id = ?
|
||||
""", taskMapper(), taskId);
|
||||
return rows.stream().findFirst();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveDraft(AiDraft draft) {
|
||||
jdbcTemplate.update("""
|
||||
INSERT INTO sys_ai_draft
|
||||
(draft_id, task_id, artifact_type, target_id, payload_json, gates_json, metadata_json, created_at)
|
||||
VALUES (?, ?, ?, ?, ?::jsonb, ?::jsonb, ?::jsonb, ?)
|
||||
ON CONFLICT (draft_id) DO UPDATE SET
|
||||
artifact_type = EXCLUDED.artifact_type,
|
||||
target_id = EXCLUDED.target_id,
|
||||
payload_json = EXCLUDED.payload_json,
|
||||
gates_json = EXCLUDED.gates_json,
|
||||
metadata_json = EXCLUDED.metadata_json
|
||||
""",
|
||||
draft.id(), draft.taskId(), draft.artifactType().name(), draft.targetId(),
|
||||
json(draft.payload()), json(draft.gates()), json(draft.metadata()), draft.createdAt());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AiDraft> listDrafts(String taskId) {
|
||||
return jdbcTemplate.query("""
|
||||
SELECT draft_id, task_id, artifact_type, target_id, payload_json, gates_json, metadata_json, created_at
|
||||
FROM sys_ai_draft
|
||||
WHERE task_id = ?
|
||||
ORDER BY created_at ASC, draft_id ASC
|
||||
""", draftMapper(), taskId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveChangeSet(AiChangeSet changeSet) {
|
||||
jdbcTemplate.update("""
|
||||
INSERT INTO sys_ai_change_set
|
||||
(change_set_id, task_id, status, draft_ids_json, summary_json, created_at)
|
||||
VALUES (?, ?, ?, ?::jsonb, ?::jsonb, ?)
|
||||
ON CONFLICT (change_set_id) DO UPDATE SET
|
||||
status = EXCLUDED.status,
|
||||
draft_ids_json = EXCLUDED.draft_ids_json,
|
||||
summary_json = EXCLUDED.summary_json
|
||||
""",
|
||||
changeSet.id(), changeSet.taskId(), changeSet.status(),
|
||||
json(changeSet.draftIds()), json(changeSet.summary()), changeSet.createdAt());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AiChangeSet> listChangeSets(String taskId) {
|
||||
return jdbcTemplate.query("""
|
||||
SELECT change_set_id, task_id, status, draft_ids_json, summary_json, created_at
|
||||
FROM sys_ai_change_set
|
||||
WHERE task_id = ?
|
||||
ORDER BY created_at ASC, change_set_id ASC
|
||||
""", changeSetMapper(), taskId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveRun(AiRunRecord run) {
|
||||
jdbcTemplate.update("""
|
||||
INSERT INTO sys_ai_run
|
||||
(run_id, task_id, change_set_id, run_type, status, payload_json, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?::jsonb, ?)
|
||||
ON CONFLICT (run_id) DO UPDATE SET
|
||||
run_type = EXCLUDED.run_type,
|
||||
status = EXCLUDED.status,
|
||||
payload_json = EXCLUDED.payload_json
|
||||
""",
|
||||
run.id(), run.taskId(), run.changeSetId(), run.runType(), run.status(),
|
||||
json(run.payload()), run.createdAt());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AiRunRecord> listRuns(String taskId) {
|
||||
return jdbcTemplate.query("""
|
||||
SELECT run_id, task_id, change_set_id, run_type, status, payload_json, created_at
|
||||
FROM sys_ai_run
|
||||
WHERE task_id = ?
|
||||
ORDER BY created_at ASC, run_id ASC
|
||||
""", runMapper(), taskId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void saveAudit(AiAuditEntry entry) {
|
||||
jdbcTemplate.update("""
|
||||
INSERT INTO sys_ai_audit_log
|
||||
(audit_id, task_id, action, actor, details_json, created_at)
|
||||
VALUES (?, ?, ?, ?, ?::jsonb, ?)
|
||||
ON CONFLICT (audit_id) DO UPDATE SET
|
||||
action = EXCLUDED.action,
|
||||
actor = EXCLUDED.actor,
|
||||
details_json = EXCLUDED.details_json
|
||||
""",
|
||||
entry.id(), entry.taskId(), entry.action(), entry.actor(), json(entry.details()), entry.createdAt());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<AiAuditEntry> listAudit(String taskId) {
|
||||
return jdbcTemplate.query("""
|
||||
SELECT audit_id, task_id, action, actor, details_json, created_at
|
||||
FROM sys_ai_audit_log
|
||||
WHERE task_id = ?
|
||||
ORDER BY created_at ASC, audit_id ASC
|
||||
""", auditMapper(), taskId);
|
||||
}
|
||||
|
||||
private RowMapper<AiTask> taskMapper() {
|
||||
return (rs, rowNum) -> new AiTask(
|
||||
rs.getString("task_id"),
|
||||
rs.getString("objective"),
|
||||
rs.getString("status"),
|
||||
rs.getLong("created_at"),
|
||||
rs.getLong("updated_at"),
|
||||
read(jsonText(rs, "plan_json"), STRING_LIST));
|
||||
}
|
||||
|
||||
private RowMapper<AiDraft> draftMapper() {
|
||||
return (rs, rowNum) -> new AiDraft(
|
||||
rs.getString("draft_id"),
|
||||
rs.getString("task_id"),
|
||||
AiArtifactType.valueOf(rs.getString("artifact_type")),
|
||||
rs.getString("target_id"),
|
||||
readTree(jsonText(rs, "payload_json")),
|
||||
rs.getLong("created_at"),
|
||||
read(jsonText(rs, "gates_json"), GATE_LIST),
|
||||
read(jsonText(rs, "metadata_json"), OBJECT_MAP));
|
||||
}
|
||||
|
||||
private RowMapper<AiChangeSet> changeSetMapper() {
|
||||
return (rs, rowNum) -> new AiChangeSet(
|
||||
rs.getString("change_set_id"),
|
||||
rs.getString("task_id"),
|
||||
rs.getString("status"),
|
||||
rs.getLong("created_at"),
|
||||
read(jsonText(rs, "draft_ids_json"), STRING_LIST),
|
||||
read(jsonText(rs, "summary_json"), OBJECT_MAP));
|
||||
}
|
||||
|
||||
private RowMapper<AiAuditEntry> auditMapper() {
|
||||
return (rs, rowNum) -> new AiAuditEntry(
|
||||
rs.getString("audit_id"),
|
||||
rs.getString("task_id"),
|
||||
rs.getString("action"),
|
||||
rs.getString("actor"),
|
||||
rs.getLong("created_at"),
|
||||
read(jsonText(rs, "details_json"), OBJECT_MAP));
|
||||
}
|
||||
|
||||
private RowMapper<AiRunRecord> runMapper() {
|
||||
return (rs, rowNum) -> new AiRunRecord(
|
||||
rs.getString("run_id"),
|
||||
rs.getString("task_id"),
|
||||
rs.getString("change_set_id"),
|
||||
rs.getString("run_type"),
|
||||
rs.getString("status"),
|
||||
rs.getLong("created_at"),
|
||||
readTree(jsonText(rs, "payload_json")));
|
||||
}
|
||||
|
||||
private String json(Object value) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException ex) {
|
||||
throw new IllegalArgumentException("AI Agent 产物 JSON 序列化失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> T read(String json, TypeReference<T> type) {
|
||||
try {
|
||||
return objectMapper.readValue(json, type);
|
||||
} catch (JsonProcessingException ex) {
|
||||
throw new IllegalArgumentException("AI Agent 产物 JSON 反序列化失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private JsonNode readTree(String json) {
|
||||
try {
|
||||
return objectMapper.readTree(json);
|
||||
} catch (JsonProcessingException ex) {
|
||||
throw new IllegalArgumentException("AI Agent schema JSON 反序列化失败", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private static String jsonText(ResultSet rs, String column) throws SQLException {
|
||||
Object value = rs.getObject(column);
|
||||
if (value == null) {
|
||||
return "{}";
|
||||
}
|
||||
return String.valueOf(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package com.eip4.platform.ai.web;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.eip4.platform.ai.model.AiAuditEntry;
|
||||
import com.eip4.platform.ai.model.AiAutoDevelopmentRequest;
|
||||
import com.eip4.platform.ai.model.AiAutoDevelopmentRun;
|
||||
import com.eip4.platform.ai.model.AiChangeSet;
|
||||
import com.eip4.platform.ai.model.AiDeploymentPackage;
|
||||
import com.eip4.platform.ai.model.AiDraft;
|
||||
import com.eip4.platform.ai.model.AiFeatureDevelopment;
|
||||
import com.eip4.platform.ai.model.AiFeatureRequest;
|
||||
import com.eip4.platform.ai.model.AiApplyRun;
|
||||
import com.eip4.platform.ai.model.AiReleasePlan;
|
||||
import com.eip4.platform.ai.model.AiRepairExecution;
|
||||
import com.eip4.platform.ai.model.AiRepairExecutionRequest;
|
||||
import com.eip4.platform.ai.model.AiRepairPlan;
|
||||
import com.eip4.platform.ai.model.AiRunRecord;
|
||||
import com.eip4.platform.ai.model.AiSmokeRun;
|
||||
import com.eip4.platform.ai.model.AiTask;
|
||||
import com.eip4.platform.ai.service.AiAgentService;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
@Tag(name = "AI Agent 开发工具", description = "受控任务/草稿/变更包/校验接口;生产发布前的人审边界")
|
||||
@RestController
|
||||
@RequestMapping("/api/ai")
|
||||
public class AiAgentController {
|
||||
|
||||
private final AiAgentService service;
|
||||
|
||||
public AiAgentController(AiAgentService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@Operation(summary = "创建 Agent 开发任务", description = "只创建受控任务和初始计划,不执行线上变更")
|
||||
@PostMapping("/tasks")
|
||||
public AiTask createTask(@RequestBody CreateTaskRequest req) {
|
||||
return service.createTask(req.objective());
|
||||
}
|
||||
|
||||
@Operation(summary = "自动开发功能草稿", description = "创建任务并生成实体/页面/服务流/菜单/测试草稿,门禁通过后生成待人审变更包")
|
||||
@PostMapping("/features/develop")
|
||||
public AiFeatureDevelopment developFeature(@RequestBody AiFeatureRequest req) {
|
||||
return service.developFeature(req);
|
||||
}
|
||||
|
||||
@Operation(summary = "一键自动开发功能", description = "生成草稿、变更包、发布计划,执行本地落库和 smoke,并生成线上人工部署包")
|
||||
@PostMapping("/features/auto-develop")
|
||||
public AiAutoDevelopmentRun autoDevelopFeature(@RequestBody(required = false) AiAutoDevelopmentRequest req) {
|
||||
return service.autoDevelopFeature(req);
|
||||
}
|
||||
|
||||
@Operation(summary = "查看 Agent 开发任务")
|
||||
@GetMapping("/tasks/{taskId}")
|
||||
public AiTask task(@PathVariable String taskId) {
|
||||
return service.getTask(taskId);
|
||||
}
|
||||
|
||||
@Operation(summary = "保存 Agent 草稿产物", description = "PAGE_SCHEMA 草稿会自动跑 amis schema 校验")
|
||||
@PostMapping("/tasks/{taskId}/drafts")
|
||||
public AiDraft addDraft(@PathVariable String taskId, @RequestBody CreateDraftRequest req) {
|
||||
return service.addDraft(taskId, req.artifactType(), req.targetId(), req.payload(), req.metadata());
|
||||
}
|
||||
|
||||
@Operation(summary = "列出任务草稿")
|
||||
@GetMapping("/tasks/{taskId}/drafts")
|
||||
public List<AiDraft> drafts(@PathVariable String taskId) {
|
||||
return service.listDrafts(taskId);
|
||||
}
|
||||
|
||||
@Operation(summary = "在既有任务下自动开发功能草稿")
|
||||
@PostMapping("/tasks/{taskId}/develop-feature")
|
||||
public AiFeatureDevelopment developFeature(@PathVariable String taskId, @RequestBody AiFeatureRequest req) {
|
||||
return service.developFeature(taskId, req);
|
||||
}
|
||||
|
||||
@Operation(summary = "生成待人审变更包", description = "任何草稿门禁失败时拒绝生成")
|
||||
@PostMapping("/tasks/{taskId}/change-sets")
|
||||
public AiChangeSet createChangeSet(@PathVariable String taskId) {
|
||||
return service.createChangeSet(taskId);
|
||||
}
|
||||
|
||||
@Operation(summary = "列出任务变更包")
|
||||
@GetMapping("/tasks/{taskId}/change-sets")
|
||||
public List<AiChangeSet> changeSets(@PathVariable String taskId) {
|
||||
return service.listChangeSets(taskId);
|
||||
}
|
||||
|
||||
@Operation(summary = "生成变更包发布计划", description = "按实体→服务流→页面→菜单→smoke 排序;线上发布仍要求人工批准")
|
||||
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/release-plan")
|
||||
public AiReleasePlan releasePlan(@PathVariable String taskId, @PathVariable String changeSetId) {
|
||||
return service.createReleasePlan(taskId, changeSetId);
|
||||
}
|
||||
|
||||
@Operation(summary = "运行本地 smoke 门禁", description = "只允许访问本机 baseUrl;返回逐条 HTTP smoke 结果")
|
||||
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/smoke")
|
||||
public AiSmokeRun runSmoke(@PathVariable String taskId,
|
||||
@PathVariable String changeSetId,
|
||||
@RequestBody(required = false) SmokeRunRequest req) {
|
||||
return service.runLocalSmoke(taskId, changeSetId, req == null ? null : req.baseUrl());
|
||||
}
|
||||
|
||||
@Operation(summary = "本地应用变更包并运行 smoke", description = "仅允许本机 baseUrl;不会执行线上部署")
|
||||
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/local-apply")
|
||||
public AiApplyRun localApply(@PathVariable String taskId,
|
||||
@PathVariable String changeSetId,
|
||||
@RequestBody(required = false) SmokeRunRequest req) {
|
||||
return service.applyLocalRelease(taskId, changeSetId, req == null ? null : req.baseUrl());
|
||||
}
|
||||
|
||||
@Operation(summary = "列出任务执行证据", description = "包含本地 smoke 和本地 apply 的结构化结果")
|
||||
@GetMapping("/tasks/{taskId}/runs")
|
||||
public List<AiRunRecord> runs(@PathVariable String taskId) {
|
||||
return service.listRuns(taskId);
|
||||
}
|
||||
|
||||
@Operation(summary = "列出变更包执行证据", description = "按变更包过滤本地 smoke/apply 结构化结果")
|
||||
@GetMapping("/tasks/{taskId}/change-sets/{changeSetId}/runs")
|
||||
public List<AiRunRecord> runs(@PathVariable String taskId, @PathVariable String changeSetId) {
|
||||
return service.listRuns(taskId, changeSetId);
|
||||
}
|
||||
|
||||
@Operation(summary = "生成线上人工部署包", description = "输出 manifest、SQL 草案、回滚 SQL 和本地执行证据;不连接线上环境执行")
|
||||
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/deployment-package")
|
||||
public AiDeploymentPackage deploymentPackage(@PathVariable String taskId, @PathVariable String changeSetId) {
|
||||
return service.createDeploymentPackage(taskId, changeSetId);
|
||||
}
|
||||
|
||||
@Operation(summary = "生成自动修复计划", description = "读取最近失败的自动开发/本地应用/smoke 证据,输出结构化修复动作并写入 run history")
|
||||
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/repair-plan")
|
||||
public AiRepairPlan repairPlan(@PathVariable String taskId, @PathVariable String changeSetId) {
|
||||
return service.createRepairPlan(taskId, changeSetId);
|
||||
}
|
||||
|
||||
@Operation(summary = "执行自动修复并重跑本地门禁", description = "仅执行 repair-plan 中标记 automated=true 的动作;存在人工动作时阻断")
|
||||
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/repair-execution")
|
||||
public AiRepairExecution executeRepairPlan(@PathVariable String taskId,
|
||||
@PathVariable String changeSetId,
|
||||
@RequestBody(required = false) AiRepairExecutionRequest req) {
|
||||
return service.executeRepairPlan(taskId, changeSetId, req == null ? null : req.baseUrl());
|
||||
}
|
||||
|
||||
@Operation(summary = "列出任务审计日志")
|
||||
@GetMapping("/tasks/{taskId}/audit")
|
||||
public List<AiAuditEntry> audit(@PathVariable String taskId) {
|
||||
return service.listAudit(taskId);
|
||||
}
|
||||
|
||||
@Operation(summary = "校验任意 amis schema", description = "AI 生成 schema 的第一道闸;后续仍需渲染冒烟")
|
||||
@PostMapping("/tools/validate-schema")
|
||||
public Map<String, Object> validateSchema(@RequestBody JsonNode schema) {
|
||||
return service.validateSchema(schema);
|
||||
}
|
||||
|
||||
public record CreateTaskRequest(String objective) {
|
||||
}
|
||||
|
||||
public record CreateDraftRequest(
|
||||
String artifactType,
|
||||
String targetId,
|
||||
JsonNode payload,
|
||||
Map<String, Object> metadata) {
|
||||
}
|
||||
|
||||
public record SmokeRunRequest(String baseUrl) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
-- ============================================================================
|
||||
-- eip4-platform P5 AI Agent 运行态自举 schema —— bootstrap-ai-agent.sql
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- 用途:在本地/CI 库上保存 Agent 开发任务、草稿产物、待人审变更包、执行证据和审计日志。
|
||||
--
|
||||
-- 纪律:可重复执行(CREATE TABLE IF NOT EXISTS / CREATE INDEX IF NOT EXISTS);
|
||||
-- 只保存 AI 运行态和草稿,不直接写 SYS_PAGE_SCHEMA / SYS_ENTITY / 服务流等生产元数据。
|
||||
-- 生产脚本副本见 docs/sql/SYS_AI_AGENT.sql;P5 引入 Flyway 后可原样迁入 migration。
|
||||
-- ============================================================================
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_ai_task (
|
||||
task_id character varying(64) NOT NULL,
|
||||
objective text NOT NULL,
|
||||
status character varying(32) NOT NULL,
|
||||
plan_json jsonb NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
updated_at bigint NOT NULL,
|
||||
CONSTRAINT pk_sys_ai_task PRIMARY KEY (task_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_ai_draft (
|
||||
draft_id character varying(64) NOT NULL,
|
||||
task_id character varying(64) NOT NULL,
|
||||
artifact_type character varying(32) NOT NULL,
|
||||
target_id character varying(128) NOT NULL,
|
||||
payload_json jsonb NOT NULL,
|
||||
gates_json jsonb NOT NULL,
|
||||
metadata_json jsonb NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
CONSTRAINT pk_sys_ai_draft PRIMARY KEY (draft_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_ai_change_set (
|
||||
change_set_id character varying(64) NOT NULL,
|
||||
task_id character varying(64) NOT NULL,
|
||||
status character varying(32) NOT NULL,
|
||||
draft_ids_json jsonb NOT NULL,
|
||||
summary_json jsonb NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
CONSTRAINT pk_sys_ai_change_set PRIMARY KEY (change_set_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_ai_run (
|
||||
run_id character varying(64) NOT NULL,
|
||||
task_id character varying(64) NOT NULL,
|
||||
change_set_id character varying(64) NOT NULL,
|
||||
run_type character varying(32) NOT NULL,
|
||||
status character varying(32) NOT NULL,
|
||||
payload_json jsonb NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
CONSTRAINT pk_sys_ai_run PRIMARY KEY (run_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sys_ai_audit_log (
|
||||
audit_id character varying(64) NOT NULL,
|
||||
task_id character varying(64) NOT NULL,
|
||||
action character varying(96) NOT NULL,
|
||||
actor character varying(64) NOT NULL,
|
||||
details_json jsonb NOT NULL,
|
||||
created_at bigint NOT NULL,
|
||||
CONSTRAINT pk_sys_ai_audit_log PRIMARY KEY (audit_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sys_ai_draft_task ON sys_ai_draft (task_id, created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_sys_ai_change_set_task ON sys_ai_change_set (task_id, created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_sys_ai_run_task ON sys_ai_run (task_id, created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_sys_ai_run_change_set ON sys_ai_run (change_set_id, created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_sys_ai_audit_log_task ON sys_ai_audit_log (task_id, created_at);
|
||||
Reference in New Issue
Block a user