From 3b4d3dbd247782bfb73d536e0f39556cd3fe3000 Mon Sep 17 00:00:00 2001 From: zhengwr Date: Wed, 17 Jun 2026 07:32:54 +0800 Subject: [PATCH] feat: add AI agent auto-development pipeline --- README.md | 2 +- docs/AI_AGENT_AUTO_DEVELOPMENT.md | 104 ++ docs/AI_AGENT_REPAIR_CONTRACT.md | 155 ++ docs/sql/SYS_AI_AGENT.sql | 100 ++ docs/架构设计.md | 4 +- platform-ai/pom.xml | 6 + .../ai/model/AiAgentRepairContext.java | 10 + .../ai/model/AiAgentRepairResult.java | 9 + .../eip4/platform/ai/model/AiApplyRun.java | 20 + .../platform/ai/model/AiApplyStepResult.java | 12 + .../platform/ai/model/AiArtifactType.java | 15 + .../eip4/platform/ai/model/AiAuditEntry.java | 12 + .../ai/model/AiAutoDevelopmentRequest.java | 19 + .../ai/model/AiAutoDevelopmentRun.java | 18 + .../eip4/platform/ai/model/AiChangeSet.java | 13 + .../ai/model/AiDeploymentPackage.java | 17 + .../com/eip4/platform/ai/model/AiDraft.java | 21 + .../ai/model/AiFeatureDevelopment.java | 9 + .../platform/ai/model/AiFeatureField.java | 9 + .../platform/ai/model/AiFeatureRequest.java | 13 + .../eip4/platform/ai/model/AiGateResult.java | 9 + .../platform/ai/model/AiGeneratedDraft.java | 12 + .../eip4/platform/ai/model/AiReleasePlan.java | 14 + .../eip4/platform/ai/model/AiReleaseStep.java | 13 + .../platform/ai/model/AiRepairAction.java | 14 + .../platform/ai/model/AiRepairDraftPatch.java | 12 + .../platform/ai/model/AiRepairExecution.java | 17 + .../ai/model/AiRepairExecutionRequest.java | 4 + .../eip4/platform/ai/model/AiRepairPlan.java | 13 + .../eip4/platform/ai/model/AiRunRecord.java | 13 + .../eip4/platform/ai/model/AiSmokeResult.java | 13 + .../eip4/platform/ai/model/AiSmokeRun.java | 17 + .../com/eip4/platform/ai/model/AiTask.java | 12 + .../ai/service/AiAgentRepairExecutor.java | 9 + .../platform/ai/service/AiAgentService.java | 1483 +++++++++++++++++ .../ai/service/AiFeatureDraftGenerator.java | 407 +++++ .../platform/ai/service/AiHttpResponse.java | 6 + .../ai/service/AiLlmRepairClient.java | 11 + .../ai/service/AiLocalReleaseExecutor.java | 365 ++++ .../ai/service/AiSmokeHttpClient.java | 11 + .../platform/ai/service/AiSmokeRunner.java | 147 ++ .../DeterministicAiAgentRepairExecutor.java | 321 ++++ .../ai/service/HttpAiLlmRepairClient.java | 99 ++ .../ai/service/JdkAiSmokeHttpClient.java | 46 + .../eip4/platform/ai/store/AiAgentStore.java | 33 + .../ai/store/InMemoryAiAgentStore.java | 81 + .../platform/ai/store/JdbcAiAgentStore.java | 254 +++ .../platform/ai/web/AiAgentController.java | 178 ++ .../bootstrap/bootstrap-ai-agent.sql | 68 + .../ai/service/AiAgentServiceTest.java | 689 ++++++++ .../service/AiFeatureDraftGeneratorTest.java | 71 + .../service/AiLocalReleaseExecutorTest.java | 128 ++ .../ai/service/AiSmokeRunnerTest.java | 76 + .../ai/service/AiSpringWiringTest.java | 37 + .../ai/service/HttpAiLlmRepairClientTest.java | 113 ++ .../platform/ai/store/AiAgentDdlTest.java | 27 + .../ai/store/InMemoryAiAgentStoreTest.java | 52 + .../ai/store/JdbcAiAgentStoreTest.java | 121 ++ .../ai/web/AiAgentApiPipelineTest.java | 120 ++ .../ai/web/AiAgentControllerTest.java | 222 +++ .../src/main/resources/application-dev.yml | 12 + .../src/main/resources/application-local.yml | 12 + .../bootstrap/bootstrap-ai-agent.sql | 68 + .../metadata/flow/FlowNameResolver.java | Bin 12318 -> 12298 bytes .../platform/metadata/web/MetaController.java | 110 +- .../metadata/web/MetaControllerDdlTest.java | 40 + 66 files changed, 6136 insertions(+), 12 deletions(-) create mode 100644 docs/AI_AGENT_AUTO_DEVELOPMENT.md create mode 100644 docs/AI_AGENT_REPAIR_CONTRACT.md create mode 100644 docs/sql/SYS_AI_AGENT.sql create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiAgentRepairContext.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiAgentRepairResult.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiApplyRun.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiApplyStepResult.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiArtifactType.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiAuditEntry.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiAutoDevelopmentRequest.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiAutoDevelopmentRun.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiChangeSet.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiDeploymentPackage.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiDraft.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureDevelopment.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureField.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureRequest.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiGateResult.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiGeneratedDraft.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiReleasePlan.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiReleaseStep.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairAction.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairDraftPatch.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairExecution.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairExecutionRequest.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairPlan.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiRunRecord.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiSmokeResult.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiSmokeRun.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/model/AiTask.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentRepairExecutor.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentService.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/service/AiFeatureDraftGenerator.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/service/AiHttpResponse.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/service/AiLlmRepairClient.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/service/AiLocalReleaseExecutor.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/service/AiSmokeHttpClient.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/service/AiSmokeRunner.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/service/DeterministicAiAgentRepairExecutor.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/service/HttpAiLlmRepairClient.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/service/JdkAiSmokeHttpClient.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/store/AiAgentStore.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/store/InMemoryAiAgentStore.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/store/JdbcAiAgentStore.java create mode 100644 platform-ai/src/main/java/com/eip4/platform/ai/web/AiAgentController.java create mode 100644 platform-ai/src/main/resources/bootstrap/bootstrap-ai-agent.sql create mode 100644 platform-ai/src/test/java/com/eip4/platform/ai/service/AiAgentServiceTest.java create mode 100644 platform-ai/src/test/java/com/eip4/platform/ai/service/AiFeatureDraftGeneratorTest.java create mode 100644 platform-ai/src/test/java/com/eip4/platform/ai/service/AiLocalReleaseExecutorTest.java create mode 100644 platform-ai/src/test/java/com/eip4/platform/ai/service/AiSmokeRunnerTest.java create mode 100644 platform-ai/src/test/java/com/eip4/platform/ai/service/AiSpringWiringTest.java create mode 100644 platform-ai/src/test/java/com/eip4/platform/ai/service/HttpAiLlmRepairClientTest.java create mode 100644 platform-ai/src/test/java/com/eip4/platform/ai/store/AiAgentDdlTest.java create mode 100644 platform-ai/src/test/java/com/eip4/platform/ai/store/InMemoryAiAgentStoreTest.java create mode 100644 platform-ai/src/test/java/com/eip4/platform/ai/store/JdbcAiAgentStoreTest.java create mode 100644 platform-ai/src/test/java/com/eip4/platform/ai/web/AiAgentApiPipelineTest.java create mode 100644 platform-ai/src/test/java/com/eip4/platform/ai/web/AiAgentControllerTest.java create mode 100644 platform-app/src/main/resources/bootstrap/bootstrap-ai-agent.sql create mode 100644 platform-metadata/src/test/java/com/eip4/platform/metadata/web/MetaControllerDdlTest.java diff --git a/README.md b/README.md index cf16d28..9049822 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ EIP4 平台正式工程(路线 A'):双层制模块化单体——**保真层供 | platform-auth | 数据权限真实现(C2 已替换桩)+ P2 组织/权限 | | | platform-converter | 模板转换器(P4) | 可独立 CLI 跑批 | | platform-flow-gateway | P3 占位:Flowable 网关 | | -| platform-ai | P5 占位:MCP Server | | +| platform-ai | P5 AI Agent 开发底座:草稿/变更包/本地门禁/自动修复/人工部署包 | Agent 不直连线上执行生产变更 | | platform-parity | C1 对拍框架:录制/重放/RowDiff/自对拍 CLI | P1 一级交付物 | | platform-app | Boot 启动器,组装全部模块 | ArchUnit 规则在此模块测试里 | diff --git a/docs/AI_AGENT_AUTO_DEVELOPMENT.md b/docs/AI_AGENT_AUTO_DEVELOPMENT.md new file mode 100644 index 0000000..54b7dd7 --- /dev/null +++ b/docs/AI_AGENT_AUTO_DEVELOPMENT.md @@ -0,0 +1,104 @@ +# AI Agent 全自动开发运行说明 + +`platform-ai` 的自动开发入口是 `POST /api/ai/features/auto-develop`。它只在本地环境执行草稿生成、本地落库、smoke 和自动修复;线上变更只输出人工部署包,不连接线上环境执行。 + +## 本地运行配置 + +`local` 和 `dev` profile 已开启: + +```yaml +spring: + sql: + init: + mode: always + schema-locations: classpath:bootstrap/bootstrap-ai-agent.sql + +eip4: + ai: + store: jdbc +``` + +因此本地启动时会幂等创建 `sys_ai_task`、`sys_ai_draft`、`sys_ai_change_set`、`sys_ai_run`、`sys_ai_audit_log`,并用 JDBC 持久化开发证据。默认 profile 不强制写远端验证库,避免误把开发证据写到共享环境。 + +建议使用独立 worktree 做 Agent 功能开发,避免占用当前任务目录: + +```bash +git worktree add ../eip4-platform-ai-agent -b ai/agent-dev +cd ../eip4-platform-ai-agent +``` + +运行态验证要先构建依赖模块并启动重新打包后的 jar,避免 `spring-boot:run -pl platform-app` 读取本地 Maven 仓库里的旧 `platform-ai`: + +```bash +JAVA_HOME=/opt/homebrew/opt/openjdk@21 mvn -pl platform-app -am install -DskipTests +/opt/homebrew/opt/openjdk@21/bin/java -jar platform-app/target/platform-app-0.1.0-SNAPSHOT.jar --spring.profiles.active=local +``` + +## 请求示例 + +```bash +curl -X POST http://localhost:8093/api/ai/features/auto-develop \ + -H 'Content-Type: application/json' \ + -d '{ + "baseUrl": "http://localhost:8093", + "generateDeploymentPackage": true, + "maxRepairAttempts": 2, + "feature": { + "objective": "新增客户等级维护功能", + "featureName": "客户等级维护", + "tableName": "EIP4AI_CUSTOMER_LEVEL", + "entityName": "客户等级", + "templateId": "eip4ai-customer-level", + "menuName": "客户等级维护", + "fields": [ + {"column": "NAME", "label": "名称", "type": "string", "length": 100, "required": true}, + {"column": "CODE", "label": "编码", "type": "string", "length": 64, "required": true}, + {"column": "ENABLED", "label": "启用", "type": "boolean", "required": false} + ] + } + }' +``` + +`maxRepairAttempts` 可省略,默认 2;设为 0 时只跑首轮开发和本地门禁,失败后由调用方手动调用 repair 接口。 + +## 自动链路 + +1. 创建 `AiTask`。 +2. 生成 `ENTITY`、`PAGE_SCHEMA`、`SERVICEFLOW`、`MENU`、`TEST` 草稿。 +3. 对草稿执行基础门禁,包括 amis schema、服务流 XML、实体字段和 smoke 计划。 +4. 生成待人审 `AiChangeSet`。 +5. 生成 release plan。 +6. 本地 apply:实体走本机 `/api/meta/entity`,页面/服务流写本地库;如果本地最小库缺少 `sys_menu`,菜单发布标记为 `SKIPPED`,不阻断本地 gate,部署包仍保留菜单 SQL 供线上人审。 +7. 本地 smoke:只允许 `localhost`、`127.0.0.1`、`::1` baseUrl;HTTP 状态必须匹配,且 JSON 响应体存在 `status` 时必须为 0。 +8. 若失败,自动生成 repair plan 并执行修复重试。 +9. 生成线上人工部署包,包含 manifest、SQL 草案、回滚 SQL 和本地执行证据。 + +返回体中的关键字段: + +- `originalChangeSetId`: 首轮自动生成的变更包。 +- `changeSetId`: 最终用于部署包的变更包;如果修复生成了替代草稿,可能不同于 `originalChangeSetId`。 +- `repairExecutions`: 每轮自动修复证据。 +- `deploymentPackage.requiresHumanApproval`: 固定为 `true`,线上发布必须人工审批。 + +## LLM 修复 + +默认使用确定性修复规则。需要外部 LLM 参与时设置: + +```properties +EIP4_AI_LLM_REPAIR_ENABLED=true +EIP4_AI_LLM_REPAIR_ENDPOINT=http://127.0.0.1:18081/ai-agent/repair +EIP4_AI_LLM_REPAIR_API_KEY=... +EIP4_AI_LLM_REPAIR_MODEL=... +``` + +外部服务契约见 `docs/AI_AGENT_REPAIR_CONTRACT.md`。LLM 只能返回草稿补丁,不能要求平台执行生产命令。 + +## 线上边界 + +可靠路径是:本地 `auto-develop` 通过后,人工检查部署包,再由现有发布流程上线。功能上线后如果发现 bug,Agent 可以基于线上错误日志、导出的 run evidence 或人工复现结果生成新的本地任务并修复,但仍应先在本地验证,再输出人工部署包。 + +## 当前验证结论与遗留项 + +已在 `local` profile 验证完整自动开发链路:实体创建、默认服务流发布、页面 schema 发布、实体列表、默认搜索流和新增数据 smoke 均通过,最终状态为 `READY_FOR_HUMAN_REVIEW`。`local` 最小库没有菜单表,因此菜单 apply 为 `SKIPPED`,这是预期的本地边界。 + +遗留项是全局 metadata 辅助读路径仍有部分 SQL 写死 `eip3.` schema;在 `local/eip4m0` 下会出现非阻断 warning。AI 主链路已规避/修正必要路径,后续如果要让所有后台辅助解析在 `local` 最小库完全无噪声,需要单独做一次 schema 兼容清理。 diff --git a/docs/AI_AGENT_REPAIR_CONTRACT.md b/docs/AI_AGENT_REPAIR_CONTRACT.md new file mode 100644 index 0000000..34517d2 --- /dev/null +++ b/docs/AI_AGENT_REPAIR_CONTRACT.md @@ -0,0 +1,155 @@ +# AI Agent Repair LLM 接入契约 + +本文档定义 `platform-ai` 调用外部 LLM 修复服务的最小契约。该服务只负责根据失败证据生成安全草稿补丁,不直接写库、不发布线上、不访问生产环境。 + +## 启用配置 + +默认不启用外部 LLM 修复。需要显式配置: + +```properties +eip4.ai.llm.repair.enabled=true +eip4.ai.llm.repair.endpoint=http://127.0.0.1:18081/ai-agent/repair +eip4.ai.llm.repair.api-key=${AI_REPAIR_API_KEY} +eip4.ai.llm.repair.model=${AI_REPAIR_MODEL} +``` + +`api-key` 为空时不发送 `Authorization` 头;非空时使用 `Authorization: Bearer `。接口超时为 60 秒。服务返回非 2xx、响应格式非法或调用异常时,平台会忽略外部结果并回退到内置确定性修复规则。 + +## 请求格式 + +`HttpAiLlmRepairClient` 向配置的 endpoint 发送 `POST application/json`: + +```json +{ + "model": "repair-model-name", + "taskId": "ait-1", + "changeSetId": "aics-1", + "repairPlan": { + "taskId": "ait-1", + "changeSetId": "aics-1", + "sourceRunId": "run-1", + "status": "READY", + "generatedAt": 1710000000000, + "actions": [], + "messages": [] + }, + "drafts": [], + "contract": { + "responseField": "draftPatches", + "patchShape": "artifactType,targetId,payload,metadata", + "rule": "Return only safe draft patches; do not execute production changes" + } +} +``` + +字段说明: + +- `repairPlan`: 平台根据最近失败的 `AUTO_DEVELOP` / `LOCAL_APPLY` / `SMOKE` 证据生成的修复计划。 +- `drafts`: 当前任务的草稿快照,LLM 只能基于这些草稿生成替代草稿。 +- `contract`: 平台要求的响应约束,外部服务必须遵守。 + +## 响应格式 + +外部服务必须返回 JSON 对象,且补丁数组放在 `draftPatches` 字段: + +```json +{ + "draftPatches": [ + { + "artifactType": "ENTITY", + "targetId": "CUSTOMER", + "payload": { + "publishTarget": "/api/meta/entity", + "tableName": "SYS_CUSTOMER", + "entityName": "Customer", + "fields": [] + }, + "metadata": { + "source": "llm-repair", + "reason": "补齐实体发布目标" + } + } + ] +} +``` + +`artifactType` 只允许: + +- `ENTITY` +- `PAGE_SCHEMA` +- `SERVICEFLOW` +- `MENU` +- `TEST` +- `CODE` + +平台当前主要自动修复 `ENTITY`、`PAGE_SCHEMA`、`SERVICEFLOW`、`MENU`、`TEST`。`CODE` 补丁即使返回,也仍然必须经过后续门禁、人审和部署包流程。 + +## 安全边界 + +外部 LLM 服务不得执行以下操作: + +- 连接或修改线上数据库。 +- 触发线上发布、重启、脚本执行或远程 shell。 +- 绕过平台的草稿、变更包、本地 apply、smoke、部署包和人工审批流程。 +- 返回除 `draftPatches` 之外需要平台立即执行的命令。 + +平台接收补丁后的流程是: + +1. 将补丁写成新的 `AiDraft`,保留 `metadata.source` 和原因。 +2. 基于同一 `artifactType + targetId` 取最新草稿重新生成 change set。 +3. 执行本地 apply 和 smoke。 +4. 生成线上人工部署包。 +5. 线上部署仍由人工审批和发布系统执行。 + +## 示例:修复 TEST 契约 + +请求中的 `repairPlan.actions` 指出 smoke 期望状态码与实际接口不一致时,外部服务可以返回: + +```json +{ + "draftPatches": [ + { + "artifactType": "TEST", + "targetId": "customer-smoke", + "payload": { + "smokes": [ + { + "name": "打开客户列表", + "method": "GET", + "path": "/api/customer/list", + "expectedStatus": 200 + } + ] + }, + "metadata": { + "source": "llm-repair", + "reason": "同步 smoke 期望状态码" + } + } + ] +} +``` + +## 示例:修复 PAGE_SCHEMA + +页面 schema 缺少 `type`、`title` 或 `body` 时,外部服务可以返回: + +```json +{ + "draftPatches": [ + { + "artifactType": "PAGE_SCHEMA", + "targetId": "customer-page", + "payload": { + "type": "page", + "title": "客户管理", + "body": [] + }, + "metadata": { + "source": "llm-repair", + "reason": "补齐 amis 页面必填结构" + } + } + ] +} +``` diff --git a/docs/sql/SYS_AI_AGENT.sql b/docs/sql/SYS_AI_AGENT.sql new file mode 100644 index 0000000..153ad89 --- /dev/null +++ b/docs/sql/SYS_AI_AGENT.sql @@ -0,0 +1,100 @@ +-- ============================================================================ +-- 生产建表脚本:SYS_AI_AGENT(AI Agent 运行态平台表) +-- ---------------------------------------------------------------------------- +-- 归属:platform-ai(P5 Agent 开发底座)。 +-- 契约:/api/ai/tasks、/api/ai/tasks/{taskId}/drafts、change-sets、runs、audit。 +-- +-- 【Flyway 待办(P5)】 +-- 架构条款(docs/架构设计.md §「平台表管理」):SYS_* 平台表由 Flyway 管理。 +-- 本工程当前未引入 Flyway。本脚本即「生产建表脚本」,P5 引入 Flyway 时 +-- 原样改名为 V{n}__create_sys_ai_agent.sql 纳入 src/main/resources/db/migration 即可。 +-- 本地 / CI 自举副本见 platform-ai/src/main/resources/bootstrap/bootstrap-ai-agent.sql。 +-- +-- 边界:这些表只保存 AI 开发运行态和草稿。发布到 SYS_PAGE_SCHEMA / SYS_ENTITY / +-- 服务流等生产元数据必须经过独立人审门禁,不能由 Agent 接口直接落生产。 +-- ============================================================================ + +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); + +COMMENT ON TABLE sys_ai_task IS 'AI Agent 开发任务。只描述需求、状态和计划,不代表已发布功能'; +COMMENT ON TABLE sys_ai_draft IS 'AI Agent 草稿产物。payload_json 保存实体/页面/服务流/代码等草稿'; +COMMENT ON TABLE sys_ai_change_set IS 'AI Agent 待人审变更包。通过门禁后供人工确认和发布'; +COMMENT ON TABLE sys_ai_run IS 'AI Agent 本地执行证据。保存 smoke/local-apply 的结构化结果'; +COMMENT ON TABLE sys_ai_audit_log IS 'AI Agent 操作审计日志'; + +COMMENT ON COLUMN sys_ai_task.task_id IS 'Agent 任务 id'; +COMMENT ON COLUMN sys_ai_task.objective IS '用户目标或需求描述'; +COMMENT ON COLUMN sys_ai_task.status IS '任务状态,例如 DRAFTING / READY_FOR_REVIEW'; +COMMENT ON COLUMN sys_ai_task.plan_json IS 'Agent 计划步骤 JSON'; +COMMENT ON COLUMN sys_ai_task.created_at IS '创建时间 epoch 毫秒'; +COMMENT ON COLUMN sys_ai_task.updated_at IS '更新时间 epoch 毫秒'; + +COMMENT ON COLUMN sys_ai_draft.artifact_type IS '草稿类型:ENTITY / PAGE_SCHEMA / SERVICEFLOW / MENU / CODE / TEST'; +COMMENT ON COLUMN sys_ai_draft.target_id IS '目标标识,例如实体编码、templateId、服务流 id 或文件路径'; +COMMENT ON COLUMN sys_ai_draft.payload_json IS '草稿内容 JSON'; +COMMENT ON COLUMN sys_ai_draft.gates_json IS '草稿门禁结果 JSON'; +COMMENT ON COLUMN sys_ai_draft.metadata_json IS '来源、上下文、生成参数等附加信息'; + +COMMENT ON COLUMN sys_ai_change_set.draft_ids_json IS '纳入变更包的 draft_id 列表'; +COMMENT ON COLUMN sys_ai_change_set.summary_json IS '变更摘要、风险、人审要求和回滚提示'; +COMMENT ON COLUMN sys_ai_run.run_type IS '执行类型:SMOKE / LOCAL_APPLY / AUTO_DEVELOP / REPAIR_PLAN / REPAIR_EXECUTION'; +COMMENT ON COLUMN sys_ai_run.status IS '执行状态:PASSED / FAILED / APPLY_FAILED / SMOKE_FAILED 等'; +COMMENT ON COLUMN sys_ai_run.payload_json IS '执行结果 JSON,包含逐条 smoke 或 apply step 详情'; +COMMENT ON COLUMN sys_ai_audit_log.details_json IS '操作详情 JSON'; diff --git a/docs/架构设计.md b/docs/架构设计.md index f53eb9f..fd75ffe 100644 --- a/docs/架构设计.md +++ b/docs/架构设计.md @@ -18,7 +18,7 @@ eip4-platform(Maven 多模块单体) ├── platform-auth P2:组织/权限/数据权限真实现(替换 PoC 桩) ├── platform-flow-gateway Flowable REST 客户端、待办聚合、3 个 handler bean ├── platform-converter 模板转换器 + S3 脚本改写器(可独立 CLI 跑批) -├── platform-ai MCP Server、schema 双闸校验 +├── platform-ai AI Agent 开发底座、schema 双闸校验、自动修复、本地门禁和人工部署包 ├── platform-parity C1 逐行对拍框架:录制/重放/逐行 diff(P1 一级交付物,可独立 CLI 跑批) └── platform-app Spring Boot 启动器,组装上述模块 ``` @@ -118,4 +118,4 @@ eip4-platform(Maven 多模块单体) --- -**本文档维护**:随 P1 包结构落地校正;任何选型变更(尤其渲染层切换)回写第二、七节。 \ No newline at end of file +**本文档维护**:随 P1 包结构落地校正;任何选型变更(尤其渲染层切换)回写第二、七节。 diff --git a/platform-ai/pom.xml b/platform-ai/pom.xml index 5134213..ec89eb4 100644 --- a/platform-ai/pom.xml +++ b/platform-ai/pom.xml @@ -13,5 +13,11 @@ P5 占位:MCP Server、schema 双闸校验 com.eip4platform-legacy-core + com.eip4platform-converter + org.springframework.bootspring-boot-starter-web + org.springframework.bootspring-boot-starter-jdbc + org.springdocspringdoc-openapi-starter-webmvc-ui + com.fasterxml.jackson.corejackson-databind + org.springframework.bootspring-boot-starter-testtest diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAgentRepairContext.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAgentRepairContext.java new file mode 100644 index 0000000..40f997b --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAgentRepairContext.java @@ -0,0 +1,10 @@ +package com.eip4.platform.ai.model; + +import java.util.List; + +public record AiAgentRepairContext( + String taskId, + String changeSetId, + AiRepairPlan repairPlan, + List drafts) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAgentRepairResult.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAgentRepairResult.java new file mode 100644 index 0000000..4f19748 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAgentRepairResult.java @@ -0,0 +1,9 @@ +package com.eip4.platform.ai.model; + +import java.util.List; + +public record AiAgentRepairResult( + String status, + List draftPatches, + List messages) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiApplyRun.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiApplyRun.java new file mode 100644 index 0000000..c25a1a4 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiApplyRun.java @@ -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 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(); + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiApplyStepResult.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiApplyStepResult.java new file mode 100644 index 0000000..578fd13 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiApplyStepResult.java @@ -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 details) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiArtifactType.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiArtifactType.java new file mode 100644 index 0000000..02a4834 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiArtifactType.java @@ -0,0 +1,15 @@ +package com.eip4.platform.ai.model; + +/** + * Agent 允许产生的受控产物类型。 + * + *

这里刻意不用自由字符串:后续 MCP 工具、发布门禁和审计都需要按类型施加不同规则。 + */ +public enum AiArtifactType { + ENTITY, + PAGE_SCHEMA, + SERVICEFLOW, + MENU, + CODE, + TEST +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAuditEntry.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAuditEntry.java new file mode 100644 index 0000000..145e712 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAuditEntry.java @@ -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 details) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAutoDevelopmentRequest.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAutoDevelopmentRequest.java new file mode 100644 index 0000000..4093cd5 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAutoDevelopmentRequest.java @@ -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)); + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAutoDevelopmentRun.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAutoDevelopmentRun.java new file mode 100644 index 0000000..1fc9543 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiAutoDevelopmentRun.java @@ -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 repairExecutions, + List messages) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiChangeSet.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiChangeSet.java new file mode 100644 index 0000000..677ab5d --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiChangeSet.java @@ -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 draftIds, + Map summary) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiDeploymentPackage.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiDeploymentPackage.java new file mode 100644 index 0000000..f05ea4a --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiDeploymentPackage.java @@ -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 manifest, + List sqlStatements, + List rollbackSqlStatements, + List warnings, + List runEvidence) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiDraft.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiDraft.java new file mode 100644 index 0000000..f409908 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiDraft.java @@ -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 gates, + Map metadata) { + + public boolean passed() { + return gates == null || gates.stream().allMatch(AiGateResult::passed); + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureDevelopment.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureDevelopment.java new file mode 100644 index 0000000..9a03429 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureDevelopment.java @@ -0,0 +1,9 @@ +package com.eip4.platform.ai.model; + +import java.util.List; + +public record AiFeatureDevelopment( + AiTask task, + List drafts, + AiChangeSet changeSet) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureField.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureField.java new file mode 100644 index 0000000..300f80b --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureField.java @@ -0,0 +1,9 @@ +package com.eip4.platform.ai.model; + +public record AiFeatureField( + String column, + String label, + String type, + Integer length, + Boolean required) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureRequest.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureRequest.java new file mode 100644 index 0000000..f2fdc19 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiFeatureRequest.java @@ -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 fields) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiGateResult.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiGateResult.java new file mode 100644 index 0000000..10a7dfa --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiGateResult.java @@ -0,0 +1,9 @@ +package com.eip4.platform.ai.model; + +import java.util.List; + +public record AiGateResult( + String name, + boolean passed, + List messages) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiGeneratedDraft.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiGeneratedDraft.java new file mode 100644 index 0000000..7563d18 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiGeneratedDraft.java @@ -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 metadata) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiReleasePlan.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiReleasePlan.java new file mode 100644 index 0000000..6521759 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiReleasePlan.java @@ -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 environmentPolicy, + List steps, + List rollbackNotes) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiReleaseStep.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiReleaseStep.java new file mode 100644 index 0000000..e46ec86 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiReleaseStep.java @@ -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 details) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairAction.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairAction.java new file mode 100644 index 0000000..ecf9762 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairAction.java @@ -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 details) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairDraftPatch.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairDraftPatch.java new file mode 100644 index 0000000..226bf67 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairDraftPatch.java @@ -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 metadata) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairExecution.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairExecution.java new file mode 100644 index 0000000..8d8cd01 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairExecution.java @@ -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 generatedDrafts, + AiChangeSet repairedChangeSet, + AiApplyRun retryApplyRun, + AiDeploymentPackage deploymentPackage, + List messages) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairExecutionRequest.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairExecutionRequest.java new file mode 100644 index 0000000..86c095c --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairExecutionRequest.java @@ -0,0 +1,4 @@ +package com.eip4.platform.ai.model; + +public record AiRepairExecutionRequest(String baseUrl) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairPlan.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairPlan.java new file mode 100644 index 0000000..1c5e7b5 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRepairPlan.java @@ -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 actions, + List messages) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRunRecord.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRunRecord.java new file mode 100644 index 0000000..2dcbb3e --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiRunRecord.java @@ -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) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiSmokeResult.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiSmokeResult.java new file mode 100644 index 0000000..b219bbc --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiSmokeResult.java @@ -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) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiSmokeRun.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiSmokeRun.java new file mode 100644 index 0000000..6bd7f38 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiSmokeRun.java @@ -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 results) { + + public boolean passed() { + return results != null && results.stream().allMatch(AiSmokeResult::passed); + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/model/AiTask.java b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiTask.java new file mode 100644 index 0000000..6a20ea2 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/model/AiTask.java @@ -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 plan) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentRepairExecutor.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentRepairExecutor.java new file mode 100644 index 0000000..938f19e --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentRepairExecutor.java @@ -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); +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentService.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentService.java new file mode 100644 index 0000000..ec7adcb --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiAgentService.java @@ -0,0 +1,1483 @@ +package com.eip4.platform.ai.service; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.Comparator; +import java.util.HexFormat; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.regex.Pattern; + +import javax.xml.parsers.DocumentBuilderFactory; + +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.web.server.ResponseStatusException; +import org.xml.sax.InputSource; + +import com.eip4.platform.ai.model.AiApplyRun; +import com.eip4.platform.ai.model.AiApplyStepResult; +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.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.AiGateResult; +import com.eip4.platform.ai.model.AiGeneratedDraft; +import com.eip4.platform.ai.model.AiReleasePlan; +import com.eip4.platform.ai.model.AiReleaseStep; +import com.eip4.platform.ai.model.AiRepairAction; +import com.eip4.platform.ai.model.AiRepairDraftPatch; +import com.eip4.platform.ai.model.AiRepairExecution; +import com.eip4.platform.ai.model.AiRepairPlan; +import com.eip4.platform.ai.model.AiRunRecord; +import com.eip4.platform.ai.model.AiSmokeResult; +import com.eip4.platform.ai.model.AiSmokeRun; +import com.eip4.platform.ai.model.AiTask; +import com.eip4.platform.ai.store.AiAgentStore; +import com.eip4.platform.converter.SchemaGate; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * P5 Agent 开发底座:任务、草稿、变更包和门禁。 + * + *

任何接口都不直接写生产元数据;Agent 只能生成草稿和待人审变更包,发布必须走单独的人审门禁。 + */ +@Service +public class AiAgentService { + + private static final Pattern TABLE_NAME = Pattern.compile("[A-Z][A-Z0-9_]{2,40}"); + private static final Pattern FLOW_KEY = Pattern.compile("[A-Z][A-Z0-9_]{2,80}"); + private static final Pattern COLUMN_NAME = Pattern.compile("[A-Z][A-Z0-9_]{0,39}"); + private static final Pattern HTTP_METHOD = Pattern.compile("GET|POST|PUT|DELETE|PATCH"); + + private final AiAgentStore store; + private final AiFeatureDraftGenerator featureDraftGenerator; + private final AiSmokeRunner smokeRunner; + private final AiLocalReleaseExecutor localReleaseExecutor; + private final AiAgentRepairExecutor agentRepairExecutor; + private final ObjectMapper objectMapper; + + private volatile SchemaGate schemaGate; + + public AiAgentService(AiAgentStore store, AiFeatureDraftGenerator featureDraftGenerator, + AiSmokeRunner smokeRunner, AiLocalReleaseExecutor localReleaseExecutor, + AiAgentRepairExecutor agentRepairExecutor, ObjectMapper objectMapper) { + this.store = store; + this.featureDraftGenerator = featureDraftGenerator; + this.smokeRunner = smokeRunner; + this.localReleaseExecutor = localReleaseExecutor; + this.agentRepairExecutor = agentRepairExecutor; + this.objectMapper = objectMapper; + } + + public AiTask createTask(String objective) { + String text = objective == null ? "" : objective.trim(); + if (text.isEmpty()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "objective 不能为空"); + } + long now = System.currentTimeMillis(); + String id = "ait-" + UUID.randomUUID(); + AiTask task = new AiTask(id, text, "DRAFTING", now, now, defaultPlan()); + store.saveTask(task); + audit(id, "task.created", "agent", Map.of("objective", text)); + return task; + } + + public AiTask getTask(String taskId) { + return store.findTask(taskId) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "AI 任务不存在: " + taskId)); + } + + public AiDraft addDraft(String taskId, String type, String targetId, JsonNode payload, + Map metadata) { + getTask(taskId); + AiArtifactType artifactType = parseType(type); + String target = targetId == null ? "" : targetId.trim(); + if (target.isEmpty()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "targetId 不能为空"); + } + if (payload == null || payload.isNull()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "payload 不能为空"); + } + + List gates = validateDraft(artifactType, target, payload); + AiDraft draft = new AiDraft( + "aid-" + UUID.randomUUID(), + taskId, + artifactType, + target, + payload, + System.currentTimeMillis(), + gates, + metadata == null ? Map.of() : Map.copyOf(metadata)); + store.saveDraft(draft); + audit(taskId, "draft.saved", "agent", Map.of( + "draftId", draft.id(), + "artifactType", draft.artifactType().name(), + "passed", draft.passed())); + return draft; + } + + public AiFeatureDevelopment developFeature(AiFeatureRequest request) { + String objective = request == null || request.objective() == null || request.objective().isBlank() + ? "AI Agent 自动开发功能" + : request.objective(); + AiTask task = createTask(objective); + return developFeature(task.id(), request); + } + + public AiAutoDevelopmentRun autoDevelopFeature(AiAutoDevelopmentRequest request) { + AiAutoDevelopmentRequest req = request == null + ? new AiAutoDevelopmentRequest(null, null, null, null) + : request; + long started = System.currentTimeMillis(); + List messages = new ArrayList<>(); + List repairExecutions = new ArrayList<>(); + AiFeatureDevelopment development = null; + AiReleasePlan releasePlan = null; + AiApplyRun applyRun = null; + AiDeploymentPackage deploymentPackage = null; + String originalChangeSetId = ""; + String currentChangeSetId = ""; + String status = "FAILED"; + try { + development = developFeature(req.feature()); + String taskId = development.task().id(); + originalChangeSetId = development.changeSet().id(); + currentChangeSetId = originalChangeSetId; + releasePlan = createReleasePlan(taskId, currentChangeSetId); + applyRun = applyLocalRelease(taskId, currentChangeSetId, req.baseUrl()); + if (req.shouldGenerateDeploymentPackage()) { + deploymentPackage = createDeploymentPackage(taskId, currentChangeSetId); + } + status = autoDevelopmentStatus(applyRun, deploymentPackage, req.shouldGenerateDeploymentPackage()); + AutoRepairOutcome repairOutcome = runAutoRepairs(req, development, currentChangeSetId, + applyRun, deploymentPackage, messages, repairExecutions); + currentChangeSetId = repairOutcome.changeSetId(); + applyRun = repairOutcome.applyRun(); + deploymentPackage = repairOutcome.deploymentPackage(); + status = autoDevelopmentStatus(applyRun, deploymentPackage, req.shouldGenerateDeploymentPackage()); + messages.addAll(applyRunMessages(applyRun)); + if (deploymentPackage != null) { + messages.addAll(deploymentPackage.warnings()); + } + if (messages.isEmpty()) { + messages.add("自动开发、本地应用和 smoke 已完成,等待人工审批线上部署包"); + } + updateTaskStatus(taskId, status); + AiAutoDevelopmentRun run = autoRun(development, currentChangeSetId, originalChangeSetId, + releasePlan, applyRun, deploymentPackage, repairExecutions, status, started, messages); + saveRun(taskId, currentChangeSetId, "AUTO_DEVELOP", status, run); + audit(taskId, "auto-development.completed", "agent", Map.of( + "changeSetId", currentChangeSetId, + "originalChangeSetId", originalChangeSetId, + "status", status, + "repairAttempts", repairExecutions.size(), + "messageCount", messages.size())); + return run; + } catch (ResponseStatusException ex) { + messages.add(responseError(ex)); + if (development != null) { + updateTaskStatus(development.task().id(), "FAILED"); + String failedChangeSetId = currentChangeSetId.isBlank() + ? development.changeSet().id() : currentChangeSetId; + String initialChangeSetId = originalChangeSetId.isBlank() + ? development.changeSet().id() : originalChangeSetId; + AiAutoDevelopmentRun run = autoRun(development, failedChangeSetId, initialChangeSetId, + releasePlan, applyRun, deploymentPackage, repairExecutions, "FAILED", started, messages); + saveRun(development.task().id(), failedChangeSetId, "AUTO_DEVELOP", "FAILED", run); + audit(development.task().id(), "auto-development.failed", "agent", Map.of( + "changeSetId", failedChangeSetId, + "error", responseError(ex))); + return run; + } + throw ex; + } + } + + public AiFeatureDevelopment developFeature(String taskId, AiFeatureRequest request) { + AiTask task = getTask(taskId); + List generated = featureDraftGenerator.generate(request); + List drafts = new ArrayList<>(); + for (AiGeneratedDraft g : generated) { + drafts.add(addDraft(taskId, g.artifactType().name(), g.targetId(), g.payload(), g.metadata())); + } + AiChangeSet changeSet = createChangeSet(taskId); + audit(taskId, "feature.generated", "agent", Map.of( + "draftCount", drafts.size(), + "changeSetId", changeSet.id())); + return new AiFeatureDevelopment(task, List.copyOf(drafts), changeSet); + } + + public List listDrafts(String taskId) { + getTask(taskId); + return store.listDrafts(taskId); + } + + public AiChangeSet createChangeSet(String taskId) { + getTask(taskId); + List drafts = activeDrafts(taskId); + if (drafts.isEmpty()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "没有草稿,不能生成变更包"); + } + List failed = drafts.stream().filter(d -> !d.passed()).toList(); + if (!failed.isEmpty()) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "存在门禁失败草稿,不能生成变更包"); + } + + Map counts = new EnumMap<>(AiArtifactType.class); + for (AiDraft draft : drafts) { + counts.merge(draft.artifactType(), 1, Integer::sum); + } + Map summary = new LinkedHashMap<>(); + summary.put("draftCount", drafts.size()); + summary.put("artifactCounts", stringifyKeys(counts)); + summary.put("requiredHumanGate", true); + summary.put("publishPolicy", "local-only; production requires human approval"); + + AiChangeSet changeSet = new AiChangeSet( + "aics-" + UUID.randomUUID(), + taskId, + "READY_FOR_REVIEW", + System.currentTimeMillis(), + drafts.stream().map(AiDraft::id).toList(), + summary); + store.saveChangeSet(changeSet); + updateTaskStatus(taskId, "READY_FOR_REVIEW"); + audit(taskId, "change-set.created", "agent", Map.of( + "changeSetId", changeSet.id(), + "draftCount", drafts.size())); + return changeSet; + } + + public List listChangeSets(String taskId) { + getTask(taskId); + return store.listChangeSets(taskId); + } + + public AiReleasePlan createReleasePlan(String taskId, String changeSetId) { + getTask(taskId); + AiChangeSet changeSet = store.listChangeSets(taskId).stream() + .filter(cs -> cs.id().equals(changeSetId)) + .findFirst() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, + "AI 变更包不存在: " + changeSetId)); + if (!"READY_FOR_REVIEW".equals(changeSet.status())) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "变更包状态不可发布计划: " + changeSet.status()); + } + + Map draftsById = listDrafts(taskId).stream() + .collect(Collectors.toMap(AiDraft::id, Function.identity(), (a, b) -> a, LinkedHashMap::new)); + List drafts = changeSet.draftIds().stream() + .map(draftsById::get) + .filter(d -> d != null) + .sorted(Comparator.comparingInt(d -> releaseOrder(d.artifactType()))) + .toList(); + if (drafts.size() != changeSet.draftIds().size()) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "变更包引用的草稿不完整"); + } + List failed = drafts.stream().filter(d -> !d.passed()).toList(); + if (!failed.isEmpty()) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "存在门禁失败草稿,不能生成发布计划"); + } + + List steps = new ArrayList<>(); + for (AiDraft draft : drafts) { + steps.add(releaseStep(steps.size() + 1, draft)); + } + AiReleasePlan plan = new AiReleasePlan( + taskId, + changeSetId, + "READY_FOR_LOCAL_APPLY", + true, + Map.of( + "localAutoApplyAllowed", true, + "productionRequiresHumanApproval", true, + "productionPolicy", "本地开发测试通过后,人工确认发布包并线上部署"), + List.copyOf(steps), + rollbackNotes(drafts)); + audit(taskId, "release-plan.generated", "agent", Map.of( + "changeSetId", changeSetId, + "stepCount", steps.size(), + "requiresHumanApproval", true)); + return plan; + } + + public AiSmokeRun runLocalSmoke(String taskId, String changeSetId, String baseUrl) { + getTask(taskId); + AiChangeSet changeSet = findChangeSet(taskId, changeSetId); + if (!"READY_FOR_REVIEW".equals(changeSet.status())) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "变更包状态不可运行 smoke: " + changeSet.status()); + } + Map draftsById = listDrafts(taskId).stream() + .collect(Collectors.toMap(AiDraft::id, Function.identity(), (a, b) -> a, LinkedHashMap::new)); + List testDrafts = changeSet.draftIds().stream() + .map(draftsById::get) + .filter(d -> d != null && d.artifactType() == AiArtifactType.TEST) + .toList(); + if (testDrafts.isEmpty()) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "变更包没有 TEST 草稿,不能运行 smoke"); + } + + long started = System.currentTimeMillis(); + List results = new ArrayList<>(); + String actualBaseUrl = ""; + for (AiDraft draft : testDrafts) { + AiSmokeRun one = smokeRunner.run(taskId, changeSetId, baseUrl, draft.payload()); + actualBaseUrl = one.baseUrl(); + results.addAll(one.results()); + } + long finished = System.currentTimeMillis(); + boolean passed = results.stream().allMatch(AiSmokeResult::passed); + AiSmokeRun run = new AiSmokeRun(taskId, changeSetId, actualBaseUrl, + passed ? "PASSED" : "FAILED", started, finished, List.copyOf(results)); + saveRun(taskId, changeSetId, "SMOKE", run.status(), run); + audit(taskId, "smoke.run", "agent", Map.of( + "changeSetId", changeSetId, + "status", run.status(), + "passed", run.passed(), + "resultCount", results.size())); + return run; + } + + public AiApplyRun applyLocalRelease(String taskId, String changeSetId, String baseUrl) { + getTask(taskId); + AiChangeSet changeSet = findChangeSet(taskId, changeSetId); + if (!"READY_FOR_REVIEW".equals(changeSet.status())) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "变更包状态不可本地应用: " + changeSet.status()); + } + Map draftsById = listDrafts(taskId).stream() + .collect(Collectors.toMap(AiDraft::id, Function.identity(), (a, b) -> a, LinkedHashMap::new)); + List drafts = changeSet.draftIds().stream() + .map(draftsById::get) + .filter(d -> d != null) + .sorted(Comparator.comparingInt(d -> releaseOrder(d.artifactType()))) + .toList(); + if (drafts.size() != changeSet.draftIds().size()) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "变更包引用的草稿不完整"); + } + if (drafts.stream().anyMatch(d -> !d.passed())) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "存在门禁失败草稿,不能本地应用"); + } + + long started = System.currentTimeMillis(); + List steps = localReleaseExecutor.apply(baseUrl, drafts); + boolean applyPassed = steps.stream().allMatch(AiAgentService::stepPassed); + AiSmokeRun smoke = null; + if (applyPassed) { + smoke = runLocalSmoke(taskId, changeSetId, baseUrl); + } + long finished = System.currentTimeMillis(); + String status = applyPassed && smoke != null && smoke.passed() + ? "PASSED" : (applyPassed ? "SMOKE_FAILED" : "APPLY_FAILED"); + AiApplyRun run = new AiApplyRun(taskId, changeSetId, + smoke == null ? defaultBaseUrl(baseUrl) : smoke.baseUrl(), + status, started, finished, List.copyOf(steps), smoke); + saveRun(taskId, changeSetId, "LOCAL_APPLY", run.status(), run); + updateTaskStatus(taskId, run.passed() ? "LOCAL_GATE_PASSED" : "LOCAL_GATE_FAILED"); + audit(taskId, "local-apply.run", "agent", Map.of( + "changeSetId", changeSetId, + "status", run.status(), + "passed", run.passed(), + "stepCount", steps.size(), + "smokeStatus", smoke == null ? "" : smoke.status())); + return run; + } + + public List listRuns(String taskId) { + getTask(taskId); + return store.listRuns(taskId); + } + + public List listRuns(String taskId, String changeSetId) { + getTask(taskId); + findChangeSet(taskId, changeSetId); + return store.listRuns(taskId).stream() + .filter(run -> run.changeSetId().equals(changeSetId)) + .toList(); + } + + public AiDeploymentPackage createDeploymentPackage(String taskId, String changeSetId) { + getTask(taskId); + AiChangeSet changeSet = findChangeSet(taskId, changeSetId); + if (!"READY_FOR_REVIEW".equals(changeSet.status())) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "变更包状态不可生成部署包: " + changeSet.status()); + } + List drafts = draftsInChangeSet(taskId, changeSet); + if (drafts.stream().anyMatch(d -> !d.passed())) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "存在门禁失败草稿,不能生成部署包"); + } + + List runs = listRuns(taskId, changeSetId); + Optional latestApply = latestRun(runs, "LOCAL_APPLY"); + Optional latestSmoke = latestRun(runs, "SMOKE"); + boolean localApplyPassed = latestApply.filter(run -> "PASSED".equals(run.status())).isPresent(); + boolean smokePassed = latestSmoke.filter(run -> "PASSED".equals(run.status())).isPresent(); + String entityId = latestApply.map(this::extractEntityId).orElse(""); + Map menuIds = latestApply.map(this::extractMenuIdsByTarget).orElse(Map.of()); + + List warnings = new ArrayList<>(); + if (!localApplyPassed) { + warnings.add("缺少最近通过的 LOCAL_APPLY 记录,线上部署前应先完成本地自动落库和 smoke"); + } + if (!smokePassed) { + warnings.add("缺少最近通过的 SMOKE 记录,线上部署前应先补齐本地 smoke 证据"); + } + if (entityId.isBlank() && drafts.stream().anyMatch(d -> d.artifactType() == AiArtifactType.SERVICEFLOW)) { + warnings.add("未能从本地 apply 记录提取 entityId,服务流 SQL 保留 ${entityId} 占位符"); + } + if (drafts.stream().anyMatch(d -> d.artifactType() == AiArtifactType.MENU + && isPlaceholderOrBlank(d.payload().path("parentId").asText("")))) { + warnings.add("菜单草稿未指定 parentId,线上 SQL 中需人工替换 ${parentMenuId}"); + } + + long generatedAt = System.currentTimeMillis(); + Map manifest = deploymentManifest(taskId, changeSet, drafts, latestApply, latestSmoke, + entityId, generatedAt); + AiDeploymentPackage deploymentPackage = new AiDeploymentPackage( + taskId, + changeSetId, + localApplyPassed && smokePassed ? "READY_FOR_HUMAN_REVIEW" : "BLOCKED_PENDING_LOCAL_PASS", + true, + generatedAt, + manifest, + deploymentSql(drafts, entityId, menuIds, generatedAt), + rollbackSql(drafts, generatedAt), + List.copyOf(warnings), + List.copyOf(runs)); + audit(taskId, "deployment-package.generated", "agent", Map.of( + "changeSetId", changeSetId, + "status", deploymentPackage.status(), + "warningCount", warnings.size(), + "requiresHumanApproval", true)); + updateTaskStatus(taskId, deploymentPackage.status()); + return deploymentPackage; + } + + public AiRepairPlan createRepairPlan(String taskId, String changeSetId) { + getTask(taskId); + findChangeSet(taskId, changeSetId); + Optional failed = latestFailedRun(listRuns(taskId, changeSetId)); + long generatedAt = System.currentTimeMillis(); + if (failed.isEmpty()) { + AiRepairPlan plan = new AiRepairPlan(taskId, changeSetId, "", + "NO_REPAIR_NEEDED", generatedAt, List.of(), + List.of("未发现需要修复的失败运行记录")); + saveRun(taskId, changeSetId, "REPAIR_PLAN", plan.status(), plan); + audit(taskId, "repair-plan.generated", "agent", Map.of( + "changeSetId", changeSetId, + "status", plan.status(), + "actionCount", 0)); + return plan; + } + + AiRunRecord source = failed.get(); + List actions = repairActions(source); + String status = actions.isEmpty() + ? "NEEDS_HUMAN_TRIAGE" + : (actions.stream().allMatch(AiRepairAction::automated) + ? "READY_FOR_AUTO_RETRY" : "NEEDS_HUMAN_ACTION"); + List messages = new ArrayList<>(); + messages.add("基于 " + source.runType() + " " + source.id() + " 生成修复计划"); + if (actions.isEmpty()) { + messages.add("失败 payload 暂无可归类动作,需要人工补充诊断"); + } else { + messages.add("识别到 " + actions.size() + " 个修复动作"); + } + AiRepairPlan plan = new AiRepairPlan(taskId, changeSetId, source.id(), + status, generatedAt, List.copyOf(actions), List.copyOf(messages)); + saveRun(taskId, changeSetId, "REPAIR_PLAN", plan.status(), plan); + audit(taskId, "repair-plan.generated", "agent", Map.of( + "changeSetId", changeSetId, + "sourceRunId", source.id(), + "status", plan.status(), + "actionCount", actions.size())); + return plan; + } + + public AiRepairExecution executeRepairPlan(String taskId, String changeSetId, String baseUrl) { + return executeRepairPlan(taskId, changeSetId, baseUrl, true); + } + + private AiRepairExecution executeRepairPlan(String taskId, String changeSetId, String baseUrl, + boolean generateDeploymentPackage) { + getTask(taskId); + AiChangeSet originalChangeSet = findChangeSet(taskId, changeSetId); + long started = System.currentTimeMillis(); + AiRepairPlan plan = latestRepairPlan(taskId, changeSetId) + .orElseGet(() -> createRepairPlan(taskId, changeSetId)); + List messages = new ArrayList<>(); + List generatedDrafts = new ArrayList<>(); + AiChangeSet repairedChangeSet = null; + AiApplyRun retryApply = null; + AiDeploymentPackage deploymentPackage = null; + + if ("NO_REPAIR_NEEDED".equals(plan.status())) { + messages.add("没有需要执行的修复动作"); + return saveRepairExecution(taskId, changeSetId, "NO_REPAIR_NEEDED", started, + plan, List.of(), null, null, null, messages); + } + List manual = plan.actions().stream().filter(a -> !a.automated()).toList(); + if (!manual.isEmpty()) { + AiAgentRepairResult agentRepair = agentRepairExecutor.repair(new AiAgentRepairContext( + taskId, changeSetId, plan, draftsInChangeSet(taskId, originalChangeSet))); + messages.addAll(agentRepair.messages()); + if (agentRepair.draftPatches().isEmpty()) { + messages.add("修复计划包含 " + manual.size() + " 个不可自动执行动作,需要人工处理后重跑"); + return saveRepairExecution(taskId, changeSetId, "BLOCKED_MANUAL_ACTION", started, + plan, List.of(), null, null, null, messages); + } + for (AiRepairDraftPatch patch : agentRepair.draftPatches()) { + generatedDrafts.add(addDraft(taskId, patch.artifactType().name(), patch.targetId(), + patch.payload(), patch.metadata())); + } + repairedChangeSet = createChangeSet(taskId); + messages.add("Agent 执行器生成 " + generatedDrafts.size() + + " 个修复草稿,并创建新变更包 " + repairedChangeSet.id()); + retryApply = applyLocalRelease(taskId, repairedChangeSet.id(), baseUrl); + if (generateDeploymentPackage) { + deploymentPackage = createDeploymentPackage(taskId, repairedChangeSet.id()); + } + String status = retryApply.passed() + && (!generateDeploymentPackage || "READY_FOR_HUMAN_REVIEW".equals(deploymentPackage.status())) + ? "REPAIRED" : "RETRY_FAILED"; + messages.addAll(applyRunMessages(retryApply)); + if (deploymentPackage != null) { + messages.addAll(deploymentPackage.warnings()); + } + return saveRepairExecution(taskId, changeSetId, status, started, + plan, generatedDrafts, repairedChangeSet, retryApply, deploymentPackage, messages); + } + + messages.add("执行 " + plan.actions().size() + " 个自动修复动作,并重跑本地 apply/smoke"); + retryApply = applyLocalRelease(taskId, changeSetId, baseUrl); + if (generateDeploymentPackage) { + deploymentPackage = createDeploymentPackage(taskId, changeSetId); + } + String status = retryApply.passed() + && (!generateDeploymentPackage || "READY_FOR_HUMAN_REVIEW".equals(deploymentPackage.status())) + ? "REPAIRED" : "RETRY_FAILED"; + messages.addAll(applyRunMessages(retryApply)); + if (deploymentPackage != null) { + messages.addAll(deploymentPackage.warnings()); + } + if ("REPAIRED".equals(status)) { + messages.add("自动修复重试通过,已重新生成线上人工部署包"); + } + return saveRepairExecution(taskId, changeSetId, status, started, + plan, List.of(), null, retryApply, deploymentPackage, messages); + } + + public List listAudit(String taskId) { + getTask(taskId); + return store.listAudit(taskId); + } + + private AiChangeSet findChangeSet(String taskId, String changeSetId) { + return store.listChangeSets(taskId).stream() + .filter(cs -> cs.id().equals(changeSetId)) + .findFirst() + .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, + "AI 变更包不存在: " + changeSetId)); + } + + private List draftsInChangeSet(String taskId, AiChangeSet changeSet) { + Map draftsById = listDrafts(taskId).stream() + .collect(Collectors.toMap(AiDraft::id, Function.identity(), (a, b) -> a, LinkedHashMap::new)); + List drafts = changeSet.draftIds().stream() + .map(draftsById::get) + .filter(d -> d != null) + .sorted(Comparator.comparingInt(d -> releaseOrder(d.artifactType()))) + .toList(); + if (drafts.size() != changeSet.draftIds().size()) { + throw new ResponseStatusException(HttpStatus.CONFLICT, "变更包引用的草稿不完整"); + } + return drafts; + } + + private List activeDrafts(String taskId) { + Map latest = new LinkedHashMap<>(); + for (AiDraft draft : listDrafts(taskId)) { + String key = draft.artifactType().name() + "\u0000" + draft.targetId(); + AiDraft existing = latest.get(key); + if (existing == null || draft.createdAt() >= existing.createdAt()) { + latest.put(key, draft); + } + } + return latest.values().stream() + .sorted(Comparator.comparingInt(d -> releaseOrder(d.artifactType()))) + .toList(); + } + + public Map validateSchema(JsonNode schema) { + AiGateResult gate = validateSchemaGate(schema); + Map resp = new LinkedHashMap<>(); + resp.put("schemaValid", gate.passed()); + resp.put("validationErrors", gate.messages()); + return resp; + } + + private AiArtifactType parseType(String type) { + if (type == null || type.isBlank()) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "artifactType 不能为空"); + } + try { + return AiArtifactType.valueOf(type.trim().toUpperCase()); + } catch (IllegalArgumentException ex) { + throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "不支持的 artifactType: " + type); + } + } + + private AiGateResult validateSchemaGate(JsonNode schema) { + if (schema == null || !schema.isObject()) { + return new AiGateResult("amis-schema", false, List.of("schema 顶层必须是 JSON object")); + } + List errors = getSchemaGate().validate(schema); + return new AiGateResult("amis-schema", errors.isEmpty(), errors.stream().limit(20).toList()); + } + + private List validateDraft(AiArtifactType type, String targetId, JsonNode payload) { + List gates = new ArrayList<>(); + gates.add(requiredFieldsGate(type, targetId, payload)); + gates.add(switch (type) { + case ENTITY -> validateEntityGate(payload); + case PAGE_SCHEMA -> validateSchemaGate(payload); + case SERVICEFLOW -> validateServiceFlowGate(payload); + case MENU -> validateMenuGate(payload); + case TEST -> validateTestGate(payload); + case CODE -> new AiGateResult("code-review-required", true, List.of("代码草稿需后续静态检查/单测门禁")); + }); + return List.copyOf(gates); + } + + private AiGateResult requiredFieldsGate(AiArtifactType type, String targetId, JsonNode payload) { + List messages = new ArrayList<>(); + if (targetId == null || targetId.isBlank()) { + messages.add("targetId 不能为空"); + } + if (payload == null || !payload.isObject()) { + messages.add(type.name() + " payload 顶层必须是 JSON object"); + } + return new AiGateResult("draft-required-fields", messages.isEmpty(), List.copyOf(messages)); + } + + private AiGateResult validateEntityGate(JsonNode payload) { + List messages = new ArrayList<>(); + String table = payload.path("tablename").asText(""); + if (!TABLE_NAME.matcher(table).matches()) { + messages.add("tablename 必须是 3-40 位大写字母数字下划线,且以字母开头"); + } + if (payload.path("name").asText("").isBlank()) { + messages.add("name 不能为空"); + } + JsonNode attrs = payload.path("attributes"); + if (!attrs.isArray() || attrs.isEmpty()) { + messages.add("attributes 至少需要 1 个业务字段"); + } else { + for (JsonNode attr : attrs) { + String col = attr.path("column").asText(""); + if (!COLUMN_NAME.matcher(col).matches()) { + messages.add("字段 column 不合法: " + col); + } + String type = attr.path("type").asText(""); + if (!List.of("string", "integer", "number", "date", "datetime", "boolean").contains(type)) { + messages.add("字段 " + col + " type 不支持: " + type); + } + } + } + return new AiGateResult("entity-meta", messages.isEmpty(), messages.stream().limit(20).toList()); + } + + private AiGateResult validateServiceFlowGate(JsonNode payload) { + List messages = new ArrayList<>(); + JsonNode flows = payload.path("flows"); + if (!flows.isArray() || flows.isEmpty()) { + messages.add("flows 至少需要 1 个服务流定义"); + } else { + for (JsonNode flow : flows) { + String key = flow.path("key").asText(""); + if (!FLOW_KEY.matcher(key).matches()) { + messages.add("服务流 key 不合法: " + key); + } + String xml = flow.path("contentXml").asText(""); + if (!isValidFlowXml(xml)) { + messages.add("服务流 XML 不合法: " + key); + } + } + } + return new AiGateResult("serviceflow-xml", messages.isEmpty(), messages.stream().limit(20).toList()); + } + + private AiGateResult validateMenuGate(JsonNode payload) { + List messages = new ArrayList<>(); + if (payload.path("name").asText("").isBlank()) { + messages.add("菜单 name 不能为空"); + } + if (payload.path("viewTemplateId").asText("").isBlank()) { + messages.add("菜单 viewTemplateId 不能为空"); + } + return new AiGateResult("menu-binding", messages.isEmpty(), List.copyOf(messages)); + } + + private AiGateResult validateTestGate(JsonNode payload) { + List messages = new ArrayList<>(); + JsonNode tests = payload.path("smokeTests"); + if (!tests.isArray() || tests.isEmpty()) { + messages.add("smokeTests 至少需要 1 条"); + } else { + for (JsonNode test : tests) { + String method = test.path("method").asText(""); + String url = test.path("url").asText(""); + if (!HTTP_METHOD.matcher(method).matches()) { + messages.add("smoke method 不合法: " + method); + } + if (!url.startsWith("/api/")) { + messages.add("smoke url 必须以 /api/ 开头: " + url); + } + } + } + return new AiGateResult("smoke-plan", messages.isEmpty(), messages.stream().limit(20).toList()); + } + + private static boolean isValidFlowXml(String xml) { + if (xml == null || xml.isBlank()) { + return false; + } + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + factory.setExpandEntityReferences(false); + var builder = factory.newDocumentBuilder(); + var doc = builder.parse(new InputSource(new java.io.StringReader(xml))); + return "flow".equals(doc.getDocumentElement().getNodeName()) + && doc.getElementsByTagName("input").getLength() > 0 + && doc.getElementsByTagName("transition").getLength() > 0; + } catch (Exception ex) { + return false; + } + } + + private SchemaGate getSchemaGate() { + if (schemaGate == null) { + synchronized (this) { + if (schemaGate == null) { + schemaGate = new SchemaGate(); + } + } + } + return schemaGate; + } + + private void audit(String taskId, String action, String actor, Map details) { + AiAuditEntry entry = new AiAuditEntry( + "aia-" + UUID.randomUUID(), + taskId, + action, + actor, + System.currentTimeMillis(), + details == null ? Map.of() : Map.copyOf(details)); + store.saveAudit(entry); + } + + private void saveRun(String taskId, String changeSetId, String runType, String status, Object payload) { + AiRunRecord run = new AiRunRecord( + "air-" + UUID.randomUUID(), + taskId, + changeSetId, + runType, + status, + System.currentTimeMillis(), + objectMapper.valueToTree(payload)); + store.saveRun(run); + } + + private AiRepairExecution saveRepairExecution(String taskId, String changeSetId, String status, long started, + AiRepairPlan plan, List generatedDrafts, + AiChangeSet repairedChangeSet, AiApplyRun retryApply, + AiDeploymentPackage deploymentPackage, + List messages) { + AiRepairExecution execution = new AiRepairExecution( + taskId, + changeSetId, + status, + started, + System.currentTimeMillis(), + plan, + generatedDrafts == null ? List.of() : List.copyOf(generatedDrafts), + repairedChangeSet, + retryApply, + deploymentPackage, + List.copyOf(messages)); + saveRun(taskId, changeSetId, "REPAIR_EXECUTION", status, execution); + audit(taskId, "repair-execution.completed", "agent", Map.of( + "changeSetId", changeSetId, + "status", status, + "messageCount", messages.size())); + if ("REPAIRED".equals(status)) { + updateTaskStatus(taskId, deploymentPackage == null ? "LOCAL_GATE_PASSED" : deploymentPackage.status()); + } + return execution; + } + + private AiAutoDevelopmentRun autoRun(AiFeatureDevelopment development, + String changeSetId, + String originalChangeSetId, + AiReleasePlan releasePlan, + AiApplyRun applyRun, + AiDeploymentPackage deploymentPackage, + List repairExecutions, + String status, + long started, + List messages) { + return new AiAutoDevelopmentRun( + development == null ? "" : development.task().id(), + changeSetId == null ? "" : changeSetId, + originalChangeSetId == null ? "" : originalChangeSetId, + status, + started, + System.currentTimeMillis(), + development, + releasePlan, + applyRun, + deploymentPackage, + repairExecutions == null ? List.of() : List.copyOf(repairExecutions), + List.copyOf(messages)); + } + + private AutoRepairOutcome runAutoRepairs(AiAutoDevelopmentRequest req, + AiFeatureDevelopment development, + String changeSetId, + AiApplyRun applyRun, + AiDeploymentPackage deploymentPackage, + List messages, + List repairExecutions) { + String currentChangeSetId = changeSetId; + AiApplyRun currentApplyRun = applyRun; + AiDeploymentPackage currentDeploymentPackage = deploymentPackage; + int maxAttempts = req.repairAttemptLimit(); + if (development == null || maxAttempts <= 0) { + return new AutoRepairOutcome(currentChangeSetId, currentApplyRun, currentDeploymentPackage); + } + String taskId = development.task().id(); + for (int attempt = 1; attempt <= maxAttempts; attempt++) { + String currentStatus = autoDevelopmentStatus(currentApplyRun, currentDeploymentPackage, + req.shouldGenerateDeploymentPackage()); + if (successfulStatus(currentStatus)) { + break; + } + AiRepairPlan plan = createRepairPlan(taskId, currentChangeSetId); + if ("NO_REPAIR_NEEDED".equals(plan.status())) { + messages.add("自动修复第 " + attempt + " 轮停止: 未发现可修复失败证据"); + break; + } + AiRepairExecution execution = executeRepairPlan(taskId, currentChangeSetId, req.baseUrl(), + req.shouldGenerateDeploymentPackage()); + repairExecutions.add(execution); + messages.add("自动修复第 " + attempt + " 轮结果: " + execution.status()); + messages.addAll(execution.messages()); + if (execution.repairedChangeSet() != null) { + currentChangeSetId = execution.repairedChangeSet().id(); + } + if (execution.retryApplyRun() != null) { + currentApplyRun = execution.retryApplyRun(); + } + if (execution.deploymentPackage() != null) { + currentDeploymentPackage = execution.deploymentPackage(); + } + if ("REPAIRED".equals(execution.status())) { + break; + } + if (List.of("NO_REPAIR_NEEDED", "BLOCKED_MANUAL_ACTION").contains(execution.status())) { + break; + } + } + return new AutoRepairOutcome(currentChangeSetId, currentApplyRun, currentDeploymentPackage); + } + + private static String autoDevelopmentStatus(AiApplyRun applyRun, AiDeploymentPackage deploymentPackage, + boolean deploymentPackageRequested) { + if (applyRun == null || !applyRun.passed()) { + return "LOCAL_GATE_FAILED"; + } + if (!deploymentPackageRequested) { + return "LOCAL_GATE_PASSED"; + } + return deploymentPackage == null ? "FAILED" : deploymentPackage.status(); + } + + private static List applyRunMessages(AiApplyRun applyRun) { + if (applyRun == null || applyRun.passed()) { + return List.of(); + } + List messages = new ArrayList<>(); + if (applyRun.steps() != null) { + for (AiApplyStepResult step : applyRun.steps()) { + if ("FAILED".equals(step.status())) { + messages.add(step.artifactType().name() + " " + step.target() + ": " + step.message()); + } + } + } + AiSmokeRun smoke = applyRun.smokeRun(); + if (smoke != null && smoke.results() != null) { + for (AiSmokeResult result : smoke.results()) { + if (!result.passed()) { + messages.add("SMOKE " + result.name() + " " + result.method() + " " + + result.url() + ": " + result.error()); + } + } + } + if (messages.isEmpty()) { + messages.add("本地门禁失败: " + applyRun.status()); + } + return List.copyOf(messages); + } + + private record AutoRepairOutcome( + String changeSetId, + AiApplyRun applyRun, + AiDeploymentPackage deploymentPackage) { + } + + private void updateTaskStatus(String taskId, String status) { + AiTask task = getTask(taskId); + store.saveTask(new AiTask( + task.id(), + task.objective(), + status, + task.createdAt(), + System.currentTimeMillis(), + task.plan())); + } + + private static String responseError(ResponseStatusException ex) { + String reason = ex.getReason(); + if (reason == null || reason.isBlank()) { + return "HTTP " + ex.getStatusCode().value(); + } + return "HTTP " + ex.getStatusCode().value() + ": " + reason; + } + + private static boolean isPlaceholderOrBlank(String value) { + return value == null || value.isBlank() || value.contains("${"); + } + + private Optional latestRun(List runs, String runType) { + return runs.stream() + .filter(run -> runType.equals(run.runType())) + .max(Comparator.comparingLong(AiRunRecord::createdAt)); + } + + private Optional latestRepairPlan(String taskId, String changeSetId) { + return latestRun(listRuns(taskId, changeSetId), "REPAIR_PLAN") + .map(run -> objectMapper.convertValue(run.payload(), AiRepairPlan.class)); + } + + private Optional latestFailedRun(List runs) { + return runs.stream() + .filter(run -> List.of("AUTO_DEVELOP", "LOCAL_APPLY", "SMOKE").contains(run.runType())) + .filter(run -> !successfulStatus(run.status())) + .max(Comparator.comparingLong(AiRunRecord::createdAt)); + } + + private static boolean successfulStatus(String status) { + return List.of("PASSED", "LOCAL_GATE_PASSED", "READY_FOR_HUMAN_REVIEW").contains(status); + } + + private List repairActions(AiRunRecord source) { + List actions = new ArrayList<>(); + JsonNode payload = source.payload(); + if ("AUTO_DEVELOP".equals(source.runType())) { + JsonNode applyRun = payload.path("applyRun"); + if (applyRun.isObject()) { + actions.addAll(applyRepairActions(source, applyRun)); + } + } else if ("LOCAL_APPLY".equals(source.runType())) { + actions.addAll(applyRepairActions(source, payload)); + } else if ("SMOKE".equals(source.runType())) { + actions.addAll(smokeRepairActions(source, payload)); + } + return List.copyOf(actions); + } + + private List applyRepairActions(AiRunRecord source, JsonNode applyRun) { + List actions = new ArrayList<>(); + JsonNode steps = applyRun.path("steps"); + if (steps.isArray()) { + for (JsonNode step : steps) { + if (!"APPLIED".equals(step.path("status").asText(""))) { + actions.add(applyStepRepairAction(actions.size() + 1, source, step)); + } + } + } + JsonNode smoke = applyRun.path("smokeRun"); + if (smoke.isObject()) { + actions.addAll(smokeRepairActions(source, smoke, actions.size())); + } + return List.copyOf(actions); + } + + private List smokeRepairActions(AiRunRecord source, JsonNode smokeRun) { + return smokeRepairActions(source, smokeRun, 0); + } + + private List smokeRepairActions(AiRunRecord source, JsonNode smokeRun, int offset) { + List actions = new ArrayList<>(); + JsonNode results = smokeRun.path("results"); + if (results.isArray()) { + for (JsonNode result : results) { + if (!result.path("passed").asBoolean(false)) { + actions.add(smokeRepairAction(offset + actions.size() + 1, source, result)); + } + } + } + return List.copyOf(actions); + } + + private AiRepairAction applyStepRepairAction(int index, AiRunRecord source, JsonNode step) { + String artifactType = step.path("artifactType").asText(""); + String target = step.path("target").asText(""); + String message = step.path("message").asText(""); + boolean transientFailure = isTransientFailure(message); + String actionType = transientFailure ? "RETRY_TRANSIENT_APPLY_FAILURE" : switch (artifactType) { + case "ENTITY" -> "REPAIR_ENTITY_METADATA_OR_LOCAL_API"; + case "SERVICEFLOW" -> message.contains("entityId") + ? "RETRY_AFTER_ENTITY_ID_RESOLUTION" : "REPAIR_SERVICEFLOW_XML_OR_SQL"; + case "PAGE_SCHEMA" -> "REPAIR_PAGE_SCHEMA_SQL_OR_SCHEMA"; + case "MENU" -> message.contains("sys_menu_root") + ? "SEED_MENU_ROOT_OR_SET_PARENT" : "REPAIR_MENU_BINDING"; + case "CODE" -> "RUN_CODE_REVIEW_AND_TESTS"; + default -> "INSPECT_APPLY_STEP"; + }; + return new AiRepairAction( + "repair-" + index, + source.runType(), + actionType, + artifactType, + target, + transientFailure, + message.isBlank() ? "本地应用步骤失败,需要修复后重跑 local-apply" : message, + Map.of( + "sourceRunId", source.id(), + "stepId", step.path("id").asText(""), + "stepStatus", step.path("status").asText(""), + "details", step.path("details"))); + } + + private AiRepairAction smokeRepairAction(int index, AiRunRecord source, JsonNode result) { + int actual = result.path("actualHttpStatus").asInt(-1); + String error = result.path("error").asText(""); + String actionType; + boolean automated = false; + if (actual == -1) { + actionType = "START_LOCAL_APP_OR_FIX_BASE_URL"; + } else if (List.of(502, 503, 504).contains(actual)) { + actionType = "RETRY_TRANSIENT_SMOKE_FAILURE"; + automated = true; + } else if (actual == 404) { + actionType = "REPAIR_ROUTE_OR_DRAFT_BINDING"; + } else if (actual >= 500) { + actionType = "REPAIR_BACKEND_FLOW_OR_ENTITY_METADATA"; + } else { + actionType = "REPAIR_SMOKE_EXPECTATION_OR_API_CONTRACT"; + } + return new AiRepairAction( + "repair-" + index, + source.runType(), + actionType, + "TEST", + result.path("name").asText("smoke"), + automated, + error.isBlank() ? "smoke 未通过,需要修复接口契约后重跑" : error, + Map.of( + "sourceRunId", source.id(), + "method", result.path("method").asText(""), + "url", result.path("url").asText(""), + "expectedHttpStatus", result.path("expectedHttpStatus").asInt(200), + "actualHttpStatus", actual, + "responseSnippet", result.path("responseSnippet").asText(""))); + } + + private static boolean isTransientFailure(String message) { + if (message == null || message.isBlank()) { + return false; + } + String text = message.toLowerCase(); + return text.contains("timeout") + || text.contains("timed out") + || text.contains("deadlock") + || text.contains("sqltransient") + || text.contains("http 502") + || text.contains("http 503") + || text.contains("http 504") + || text.contains("temporarily"); + } + + private String extractEntityId(AiRunRecord run) { + JsonNode steps = run.payload().path("steps"); + if (!steps.isArray()) { + return ""; + } + for (JsonNode step : steps) { + if ("ENTITY".equals(step.path("artifactType").asText())) { + String entityId = step.path("details").path("entityId").asText(""); + if (!entityId.isBlank()) { + return entityId; + } + } + } + return ""; + } + + private Map extractMenuIdsByTarget(AiRunRecord run) { + Map out = new LinkedHashMap<>(); + JsonNode steps = run.payload().path("steps"); + if (!steps.isArray()) { + return Map.of(); + } + for (JsonNode step : steps) { + if ("MENU".equals(step.path("artifactType").asText())) { + String target = step.path("target").asText(""); + String menuId = step.path("details").path("menuId").asText(""); + if (!target.isBlank() && !menuId.isBlank()) { + out.put(target, menuId); + } + } + } + return Map.copyOf(out); + } + + private Map deploymentManifest(String taskId, AiChangeSet changeSet, List drafts, + Optional latestApply, + Optional latestSmoke, + String entityId, + long generatedAt) { + Map manifest = new LinkedHashMap<>(); + manifest.put("packageId", "aipkg-" + UUID.randomUUID()); + manifest.put("taskId", taskId); + manifest.put("changeSetId", changeSet.id()); + manifest.put("generatedAt", generatedAt); + manifest.put("productionPolicy", "人工审批 SQL/API 部署包;Agent 不直连线上环境执行变更"); + manifest.put("requiresHumanApproval", true); + manifest.put("entityId", entityId); + manifest.put("drafts", drafts.stream().map(draft -> { + Map item = new LinkedHashMap<>(); + item.put("draftId", draft.id()); + item.put("artifactType", draft.artifactType().name()); + item.put("targetId", draft.targetId()); + item.put("passed", draft.passed()); + item.put("createdAt", draft.createdAt()); + return item; + }).toList()); + Map evidence = new LinkedHashMap<>(); + evidence.put("latestLocalApply", latestApply.map(this::runSummary).orElse(null)); + evidence.put("latestSmoke", latestSmoke.map(this::runSummary).orElse(null)); + manifest.put("evidence", evidence); + return Map.copyOf(manifest); + } + + private Map runSummary(AiRunRecord run) { + Map summary = new LinkedHashMap<>(); + summary.put("runId", run.id()); + summary.put("runType", run.runType()); + summary.put("status", run.status()); + summary.put("createdAt", run.createdAt()); + return Map.copyOf(summary); + } + + private List deploymentSql(List drafts, String entityId, + Map menuIdsByTarget, long generatedAt) { + List out = new ArrayList<>(); + for (AiDraft draft : drafts) { + switch (draft.artifactType()) { + case ENTITY -> out.add(entityDeploymentNote(draft)); + case SERVICEFLOW -> out.addAll(serviceFlowSql(draft, entityId, generatedAt)); + case PAGE_SCHEMA -> out.add(pageSchemaSql(draft, generatedAt)); + case MENU -> out.add(menuSql(draft, menuIdsByTarget.get(draft.targetId()), generatedAt)); + case TEST -> out.add("-- TEST " + draft.targetId() + ": 保留 smoke 结果作为上线审批附件,不生成生产 SQL"); + case CODE -> out.add("-- CODE " + draft.targetId() + ": 代码改动需通过代码仓库发布流程,不生成运行态 SQL"); + } + } + return List.copyOf(out); + } + + private String entityDeploymentNote(AiDraft draft) { + return "-- ENTITY " + draft.targetId() + + ": 人工审批后在目标环境调用 POST /api/meta/entity,payload=" + + json(draft.payload()) + + ";确认返回 entityId 后替换服务流 SQL 中的 ${entityId}"; + } + + private List serviceFlowSql(AiDraft draft, String entityId, long generatedAt) { + List out = new ArrayList<>(); + String resolvedEntityId = entityId == null || entityId.isBlank() ? "${entityId}" : entityId; + for (JsonNode flow : draft.payload().path("flows")) { + String xml = flow.path("contentXml").asText(""); + if (!entityId.isBlank()) { + xml = xml.replace("${entityId}", entityId); + } + out.add(""" + INSERT INTO sys_serviceflow + (sys_serviceflow_id, displayname, contentxml, entityid, iscontrol, isupdateable, + isactive, createtime, updatetime, createby, updateby, version) + VALUES (%s, %s, %s, %s, %d, %d, 1, %d, %d, 'AI_AGENT', 'AI_AGENT', 0) + ON CONFLICT (sys_serviceflow_id) DO UPDATE SET + displayname = EXCLUDED.displayname, + contentxml = EXCLUDED.contentxml, + entityid = EXCLUDED.entityid, + iscontrol = EXCLUDED.iscontrol, + isupdateable = EXCLUDED.isupdateable, + updatetime = EXCLUDED.updatetime, + updateby = EXCLUDED.updateby, + version = sys_serviceflow.version + 1; + """.formatted( + sqlString(flow.path("key").asText()), + sqlString(flow.path("displayName").asText(flow.path("key").asText())), + sqlString(xml), + sqlString(resolvedEntityId), + flow.path("control").asBoolean(true) ? 1 : 0, + flow.path("updateable").asBoolean(true) ? 1 : 0, + generatedAt, + generatedAt)); + } + return out; + } + + private String pageSchemaSql(AiDraft draft, long generatedAt) { + String schemaJson = json(draft.payload()); + return """ + INSERT INTO sys_page_schema (template_id, name, schema_json, schema_etag, version, update_time) + VALUES (%s, %s, %s::jsonb, %s, 1, %d) + ON CONFLICT (template_id) DO UPDATE SET + name = EXCLUDED.name, + schema_json = EXCLUDED.schema_json, + schema_etag = EXCLUDED.schema_etag, + version = sys_page_schema.version + 1, + update_time = EXCLUDED.update_time; + """.formatted( + sqlString(draft.targetId()), + sqlString(draft.payload().path("title").asText(draft.targetId())), + sqlString(schemaJson), + sqlString(sha256(schemaJson)), + generatedAt); + } + + private String menuSql(AiDraft draft, String appliedMenuId, long generatedAt) { + JsonNode payload = draft.payload(); + String menuId = appliedMenuId == null || appliedMenuId.isBlank() ? "${menuId}" : appliedMenuId; + String parentId = payload.path("parentId").asText(""); + if (parentId.isBlank()) { + parentId = "${parentMenuId}"; + } + String menuRoot = payload.path("menuroot").asText(""); + if (menuRoot.isBlank()) { + menuRoot = "${menuRoot}"; + } + return """ + INSERT INTO sys_menu + (sys_menu_id, name, parentid, view_templateid, typename, menuroot, seq, + isactive, version, createtime, createby, updatetime, updateby) + VALUES (%s, %s, %s, %s, %s, %s, %d, 1, 0, %d, 'AI_AGENT', %d, 'AI_AGENT') + ON CONFLICT (sys_menu_id) DO UPDATE SET + name = EXCLUDED.name, + parentid = EXCLUDED.parentid, + view_templateid = EXCLUDED.view_templateid, + typename = EXCLUDED.typename, + menuroot = EXCLUDED.menuroot, + seq = EXCLUDED.seq, + isactive = 1, + updatetime = EXCLUDED.updatetime, + updateby = EXCLUDED.updateby, + version = sys_menu.version + 1; + """.formatted( + sqlString(menuId), + sqlString(payload.path("name").asText(draft.targetId())), + sqlString(parentId), + sqlString(payload.path("viewTemplateId").asText(draft.targetId())), + sqlString(payload.path("typename").asText("功能菜单")), + sqlString(menuRoot), + payload.path("seq").asInt(0), + generatedAt, + generatedAt); + } + + private List rollbackSql(List drafts, long generatedAt) { + List out = new ArrayList<>(); + for (AiDraft draft : drafts) { + switch (draft.artifactType()) { + case ENTITY -> out.add("-- ENTITY " + draft.targetId() + + ": 人工确认后调用 DELETE /api/meta/entity/" + draft.targetId() + + ",并清理对应菜单/服务流/页面 schema"); + case SERVICEFLOW -> out.add(serviceFlowRollbackSql(draft)); + case PAGE_SCHEMA -> out.add("DELETE FROM sys_page_schema WHERE template_id = " + + sqlString(draft.targetId()) + ";"); + case MENU -> out.add(""" + UPDATE sys_menu + SET isactive = 0, updatetime = %d, updateby = 'AI_AGENT_ROLLBACK', + version = version + 1 + WHERE TRIM(view_templateid) = %s; + """.formatted(generatedAt, sqlString(draft.targetId()))); + case TEST -> out.add("-- TEST " + draft.targetId() + ": 无生产数据回滚动作"); + case CODE -> out.add("-- CODE " + draft.targetId() + ": 通过代码仓库反向补丁或回滚发布单处理"); + } + } + return List.copyOf(out); + } + + private String serviceFlowRollbackSql(AiDraft draft) { + List keys = new ArrayList<>(); + for (JsonNode flow : draft.payload().path("flows")) { + keys.add(sqlString(flow.path("key").asText())); + } + return "DELETE FROM sys_serviceflow WHERE sys_serviceflow_id IN (" + + String.join(", ", keys) + ");"; + } + + private String json(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (JsonProcessingException ex) { + throw new IllegalArgumentException("AI Agent 部署包 JSON 序列化失败", ex); + } + } + + private static String sqlString(String value) { + String text = value == null ? "" : value; + return "'" + text.replace("'", "''") + "'"; + } + + private static String sha256(String text) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + return HexFormat.of().formatHex(digest.digest(text.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException ex) { + throw new IllegalStateException(ex); + } + } + + private static List defaultPlan() { + List plan = new ArrayList<>(); + plan.add("采集需求和上下文"); + plan.add("生成实体/页面/服务流/菜单草稿"); + plan.add("执行 schema 校验、渲染冒烟和 API smoke"); + plan.add("失败时自动修复并重跑门禁"); + plan.add("生成待人审变更包和回滚说明"); + return List.copyOf(plan); + } + + private static Map stringifyKeys(Map counts) { + Map out = new LinkedHashMap<>(); + for (Map.Entry e : counts.entrySet()) { + out.put(e.getKey().name(), e.getValue()); + } + return out; + } + + 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 static boolean stepPassed(AiApplyStepResult step) { + return step != null && ("APPLIED".equals(step.status()) || "SKIPPED".equals(step.status())); + } + + private static String defaultBaseUrl(String baseUrl) { + return baseUrl == null || baseUrl.isBlank() ? "http://localhost:8084" : baseUrl.trim(); + } + + private static AiReleaseStep releaseStep(int index, AiDraft draft) { + return switch (draft.artifactType()) { + case ENTITY -> new AiReleaseStep( + "step-" + index, + draft.artifactType(), + "创建实体元数据和物理表", + "LOCAL_EXECUTABLE", + draft.targetId(), + "POST /api/meta/entity", + Map.of("payload", draft.payload())); + case SERVICEFLOW -> new AiReleaseStep( + "step-" + index, + draft.artifactType(), + "发布实体默认服务流", + "LOCAL_EXECUTABLE", + draft.targetId(), + "UPSERT sys_serviceflow after ENTITY returns entityId", + Map.of( + "flowCount", draft.payload().path("flows").size(), + "requiresEntityId", draft.payload().path("requiresEntityId").asBoolean(false))); + case PAGE_SCHEMA -> new AiReleaseStep( + "step-" + index, + draft.artifactType(), + "发布页面 schema", + "LOCAL_EXECUTABLE", + draft.targetId(), + "UPSERT sys_page_schema", + Map.of("templateId", draft.targetId(), "schema", draft.payload())); + case MENU -> new AiReleaseStep( + "step-" + index, + draft.artifactType(), + "挂载菜单入口", + "LOCAL_EXECUTABLE", + draft.targetId(), + "POST /api/admin/menus/create or SYS_MENU upsert", + Map.of("payload", draft.payload())); + case TEST -> new AiReleaseStep( + "step-" + index, + draft.artifactType(), + "运行本地 smoke 测试", + "LOCAL_GATE", + draft.targetId(), + "execute smokeTests locally", + Map.of("smokeTestCount", draft.payload().path("smokeTests").size())); + case CODE -> new AiReleaseStep( + "step-" + index, + draft.artifactType(), + "应用代码改动", + "LOCAL_EXECUTABLE", + draft.targetId(), + "apply patch and run tests", + Map.of("payload", draft.payload())); + }; + } + + private static List rollbackNotes(List drafts) { + List notes = new ArrayList<>(); + for (AiDraft draft : drafts) { + switch (draft.artifactType()) { + case ENTITY -> notes.add("如实体发布失败或需回滚,调用 DELETE /api/meta/entity/" + draft.targetId() + + "(仅 EIP4 前缀实体)并清 POInfo/白名单缓存"); + case SERVICEFLOW -> notes.add("删除本次新增/更新的 sys_serviceflow 记录: " + draft.targetId()); + case PAGE_SCHEMA -> notes.add("删除或恢复 sys_page_schema template_id=" + draft.targetId()); + case MENU -> notes.add("删除或禁用指向 templateId=" + draft.targetId() + " 的菜单项"); + case TEST -> notes.add("保留 smoke 测试结果作为上线审批附件"); + case CODE -> notes.add("按代码变更包反向补丁回滚: " + draft.targetId()); + } + } + return List.copyOf(notes); + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/AiFeatureDraftGenerator.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiFeatureDraftGenerator.java new file mode 100644 index 0000000..5c15e76 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiFeatureDraftGenerator.java @@ -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 SYSTEM_COLUMNS = Set.of( + "VERSION", "CREATETIME", "UPDATETIME", "CREATEBY", "UPDATEBY", "ISACTIVE"); + + private final ObjectMapper objectMapper; + + public AiFeatureDraftGenerator(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + public List generate(AiFeatureRequest request) { + FeatureSpec spec = normalize(request); + List 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 fields = normalizeFields(request == null ? null : request.fields()); + return new FeatureSpec(feature, table, entityName, templateId, menuName, fields); + } + + private List normalizeFields(List input) { + List raw = input == null ? List.of() : input; + List out = new ArrayList<>(); + Set 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 metadata(String generatorStep, String publishTarget) { + Map 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 fields) { + } + + private record FieldSpec( + String column, + String label, + String type, + Integer length, + boolean required) { + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/AiHttpResponse.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiHttpResponse.java new file mode 100644 index 0000000..e40b917 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiHttpResponse.java @@ -0,0 +1,6 @@ +package com.eip4.platform.ai.service; + +public record AiHttpResponse( + int statusCode, + String body) { +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/AiLlmRepairClient.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiLlmRepairClient.java new file mode 100644 index 0000000..3bae86c --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiLlmRepairClient.java @@ -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 repair(AiAgentRepairContext context); +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/AiLocalReleaseExecutor.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiLocalReleaseExecutor.java new file mode 100644 index 0000000..db3c7e2 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiLocalReleaseExecutor.java @@ -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 apply(String baseUrl, List drafts) { + URI base = safeLocalBase(baseUrl); + ApplyContext ctx = new ApplyContext(base); + List 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 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 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 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 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 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 details) { + return new AiApplyStepResult("apply-" + index, draft.artifactType(), draft.targetId(), + "APPLIED", message, details); + } + + private static AiApplyStepResult failed(int index, AiDraft draft, String message, Map 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) { + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/AiSmokeHttpClient.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiSmokeHttpClient.java new file mode 100644 index 0000000..558393c --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiSmokeHttpClient.java @@ -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; +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/AiSmokeRunner.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiSmokeRunner.java new file mode 100644 index 0000000..fdd37d4 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/AiSmokeRunner.java @@ -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 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 ""; + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/DeterministicAiAgentRepairExecutor.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/DeterministicAiAgentRepairExecutor.java new file mode 100644 index 0000000..8dd193b --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/DeterministicAiAgentRepairExecutor.java @@ -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 llmRepairClients; + + @Autowired + public DeterministicAiAgentRepairExecutor(ObjectMapper objectMapper, List 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 patches = new ArrayList<>(); + List 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 patches = new ArrayList<>(); + List messages = new ArrayList<>(); + for (AiLlmRepairClient client : llmRepairClients) { + List 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 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 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 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 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 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); + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/HttpAiLlmRepairClient.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/HttpAiLlmRepairClient.java new file mode 100644 index 0000000..d8e3d94 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/HttpAiLlmRepairClient.java @@ -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> 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 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 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 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 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); + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/service/JdkAiSmokeHttpClient.java b/platform-ai/src/main/java/com/eip4/platform/ai/service/JdkAiSmokeHttpClient.java new file mode 100644 index 0000000..a1c5392 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/service/JdkAiSmokeHttpClient.java @@ -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 response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + return new AiHttpResponse(response.statusCode(), response.body()); + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/store/AiAgentStore.java b/platform-ai/src/main/java/com/eip4/platform/ai/store/AiAgentStore.java new file mode 100644 index 0000000..3bdb1fc --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/store/AiAgentStore.java @@ -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 findTask(String taskId); + + void saveDraft(AiDraft draft); + + List listDrafts(String taskId); + + void saveChangeSet(AiChangeSet changeSet); + + List listChangeSets(String taskId); + + void saveRun(AiRunRecord run); + + List listRuns(String taskId); + + void saveAudit(AiAuditEntry entry); + + List listAudit(String taskId); +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/store/InMemoryAiAgentStore.java b/platform-ai/src/main/java/com/eip4/platform/ai/store/InMemoryAiAgentStore.java new file mode 100644 index 0000000..9d1b166 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/store/InMemoryAiAgentStore.java @@ -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 tasks = new ConcurrentHashMap<>(); + private final Map> draftsByTask = new ConcurrentHashMap<>(); + private final Map> auditByTask = new ConcurrentHashMap<>(); + private final Map> changeSetsByTask = new ConcurrentHashMap<>(); + private final Map> 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 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 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 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 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 listAudit(String taskId) { + return List.copyOf(auditByTask.getOrDefault(taskId, List.of())); + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/store/JdbcAiAgentStore.java b/platform-ai/src/main/java/com/eip4/platform/ai/store/JdbcAiAgentStore.java new file mode 100644 index 0000000..413f3a7 --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/store/JdbcAiAgentStore.java @@ -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> STRING_LIST = new TypeReference<>() { + }; + private static final TypeReference> GATE_LIST = new TypeReference<>() { + }; + private static final TypeReference> 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 findTask(String taskId) { + List 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 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 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 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 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 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 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 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 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 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 read(String json, TypeReference 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); + } +} diff --git a/platform-ai/src/main/java/com/eip4/platform/ai/web/AiAgentController.java b/platform-ai/src/main/java/com/eip4/platform/ai/web/AiAgentController.java new file mode 100644 index 0000000..f5316ca --- /dev/null +++ b/platform-ai/src/main/java/com/eip4/platform/ai/web/AiAgentController.java @@ -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 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 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 runs(@PathVariable String taskId) { + return service.listRuns(taskId); + } + + @Operation(summary = "列出变更包执行证据", description = "按变更包过滤本地 smoke/apply 结构化结果") + @GetMapping("/tasks/{taskId}/change-sets/{changeSetId}/runs") + public List 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 audit(@PathVariable String taskId) { + return service.listAudit(taskId); + } + + @Operation(summary = "校验任意 amis schema", description = "AI 生成 schema 的第一道闸;后续仍需渲染冒烟") + @PostMapping("/tools/validate-schema") + public Map validateSchema(@RequestBody JsonNode schema) { + return service.validateSchema(schema); + } + + public record CreateTaskRequest(String objective) { + } + + public record CreateDraftRequest( + String artifactType, + String targetId, + JsonNode payload, + Map metadata) { + } + + public record SmokeRunRequest(String baseUrl) { + } +} diff --git a/platform-ai/src/main/resources/bootstrap/bootstrap-ai-agent.sql b/platform-ai/src/main/resources/bootstrap/bootstrap-ai-agent.sql new file mode 100644 index 0000000..f4a01a6 --- /dev/null +++ b/platform-ai/src/main/resources/bootstrap/bootstrap-ai-agent.sql @@ -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); diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/service/AiAgentServiceTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiAgentServiceTest.java new file mode 100644 index 0000000..53f4fc2 --- /dev/null +++ b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiAgentServiceTest.java @@ -0,0 +1,689 @@ +package com.eip4.platform.ai.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.web.server.ResponseStatusException; + +import com.eip4.platform.ai.model.AiAutoDevelopmentRequest; +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.AiRepairDraftPatch; +import com.eip4.platform.ai.store.InMemoryAiAgentStore; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +class AiAgentServiceTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + @DisplayName("创建任务后保存有效页面草稿并生成待人审变更包") + void createTaskDraftAndChangeSet() throws Exception { + AiAgentService service = newService(); + var task = service.createTask("新增合同类型维护功能"); + + JsonNode page = MAPPER.readTree(""" + {"type":"page","title":"合同类型维护","body":{"type":"tpl","tpl":"ok"}} + """); + var draft = service.addDraft(task.id(), "PAGE_SCHEMA", "contract-type-page", page, Map.of("source", "test")); + + assertTrue(draft.passed()); + assertEquals(1, service.listDrafts(task.id()).size()); + + var changeSet = service.createChangeSet(task.id()); + assertEquals("READY_FOR_REVIEW", changeSet.status()); + assertEquals(1, changeSet.draftIds().size()); + assertEquals(1, service.listChangeSets(task.id()).size()); + assertEquals(3, service.listAudit(task.id()).size()); + } + + @Test + @DisplayName("无效 schema 草稿会阻止生成变更包") + void invalidSchemaBlocksChangeSet() throws Exception { + AiAgentService service = newService(); + var task = service.createTask("生成坏页面"); + JsonNode invalid = MAPPER.readTree("\"not-object\""); + + var draft = service.addDraft(task.id(), "PAGE_SCHEMA", "bad", invalid, null); + + assertFalse(draft.passed()); + ResponseStatusException ex = assertThrows(ResponseStatusException.class, + () -> service.createChangeSet(task.id())); + assertEquals(409, ex.getStatusCode().value()); + } + + @Test + @DisplayName("不允许空目标或未知产物类型") + void validatesInputs() { + AiAgentService service = newService(); + assertThrows(ResponseStatusException.class, () -> service.createTask(" ")); + var task = service.createTask("合法任务"); + JsonNode payload = MAPPER.createObjectNode().put("x", 1); + ResponseStatusException blankTarget = assertThrows(ResponseStatusException.class, + () -> service.addDraft(task.id(), "CODE", " ", payload, null)); + assertEquals(400, blankTarget.getStatusCode().value()); + ResponseStatusException ex = assertThrows(ResponseStatusException.class, + () -> service.addDraft(task.id(), "UNKNOWN", "x", payload, null)); + assertEquals(400, ex.getStatusCode().value()); + } + + @Test + @DisplayName("自动开发功能:生成实体/页面/服务流/菜单/测试草稿并创建待人审变更包") + void developFeatureCreatesFullDraftSet() { + AiAgentService service = newService(); + + var result = service.developFeature(contractTypeFeature()); + + assertEquals(5, result.drafts().size()); + assertTrue(result.drafts().stream().allMatch(d -> d.passed()), "自动生成草稿必须全部过基础门禁"); + assertEquals("READY_FOR_REVIEW", result.changeSet().status()); + assertEquals(5, result.changeSet().draftIds().size()); + assertEquals(5, service.listDrafts(result.task().id()).size()); + + var plan = service.createReleasePlan(result.task().id(), result.changeSet().id()); + assertTrue(plan.requiresHumanApproval()); + assertEquals(5, plan.steps().size()); + assertEquals("ENTITY", plan.steps().get(0).artifactType().name()); + assertEquals("TEST", plan.steps().get(4).artifactType().name()); + assertEquals("READY_FOR_LOCAL_APPLY", plan.status()); + + var smoke = service.runLocalSmoke(result.task().id(), result.changeSet().id(), "http://localhost:8084"); + assertTrue(smoke.passed()); + assertEquals("PASSED", smoke.status()); + assertEquals(4, smoke.results().size()); + assertEquals(1, service.listRuns(result.task().id(), result.changeSet().id()).size()); + + var apply = service.applyLocalRelease(result.task().id(), result.changeSet().id(), "http://localhost:8084"); + assertTrue(apply.passed()); + assertEquals("PASSED", apply.status()); + assertEquals(4, apply.steps().size()); + assertEquals("PASSED", apply.smokeRun().status()); + assertEquals(3, service.listRuns(result.task().id()).size()); + + var deploymentPackage = service.createDeploymentPackage(result.task().id(), result.changeSet().id()); + assertEquals("READY_FOR_HUMAN_REVIEW", deploymentPackage.status()); + assertTrue(deploymentPackage.requiresHumanApproval()); + assertTrue(deploymentPackage.sqlStatements().stream().anyMatch(sql -> sql.contains("sys_page_schema"))); + assertTrue(deploymentPackage.sqlStatements().stream().anyMatch(sql -> sql.contains("sys_serviceflow"))); + assertTrue(deploymentPackage.rollbackSqlStatements().stream().anyMatch(sql -> sql.contains("sys_serviceflow"))); + assertTrue(deploymentPackage.warnings().stream().anyMatch(w -> w.contains("parentId"))); + } + + @Test + @DisplayName("一键自动开发会串联草稿生成、本地应用、smoke 和部署包") + void autoDevelopFeatureRunsFullPipeline() { + AiAgentService service = newService(); + + var run = service.autoDevelopFeature(new AiAutoDevelopmentRequest( + contractTypeFeature(), "http://localhost:8084", true, null)); + + assertEquals("READY_FOR_HUMAN_REVIEW", run.status()); + assertEquals(run.originalChangeSetId(), run.changeSetId()); + assertEquals(5, run.development().drafts().size()); + assertEquals("READY_FOR_LOCAL_APPLY", run.releasePlan().status()); + assertEquals("PASSED", run.applyRun().status()); + assertEquals("READY_FOR_HUMAN_REVIEW", run.deploymentPackage().status()); + assertTrue(run.repairExecutions().isEmpty()); + assertTrue(run.messages().stream().anyMatch(m -> m.contains("parentId"))); + assertEquals("READY_FOR_HUMAN_REVIEW", service.getTask(run.taskId()).status()); + assertEquals(3, service.listRuns(run.taskId()).size()); + assertTrue(service.listRuns(run.taskId()).stream().anyMatch(r -> "AUTO_DEVELOP".equals(r.runType()))); + } + + @Test + @DisplayName("一键自动开发本地应用失败时返回诊断消息并保留执行证据") + void autoDevelopFeatureReturnsDiagnosticsWhenLocalApplyFails() { + AiAgentService service = newService(new FailingLocalReleaseExecutor()); + + var run = service.autoDevelopFeature(new AiAutoDevelopmentRequest( + contractTypeFeature(), "http://localhost:8084", true, 0)); + + assertEquals("LOCAL_GATE_FAILED", run.status()); + assertEquals("APPLY_FAILED", run.applyRun().status()); + assertEquals("BLOCKED_PENDING_LOCAL_PASS", run.deploymentPackage().status()); + assertTrue(run.repairExecutions().isEmpty()); + assertTrue(run.messages().stream().anyMatch(m -> m.contains("实体接口不可用"))); + assertTrue(run.messages().stream().anyMatch(m -> m.contains("LOCAL_APPLY"))); + assertEquals("LOCAL_GATE_FAILED", service.getTask(run.taskId()).status()); + assertEquals(2, service.listRuns(run.taskId()).size()); + assertTrue(service.listRuns(run.taskId()).stream().anyMatch(r -> "AUTO_DEVELOP".equals(r.runType()))); + + var repairPlan = service.createRepairPlan(run.taskId(), run.changeSetId()); + + assertEquals("NEEDS_HUMAN_ACTION", repairPlan.status()); + assertEquals(1, repairPlan.actions().size()); + assertEquals("ENTITY", repairPlan.actions().get(0).artifactType()); + assertEquals("REPAIR_ENTITY_METADATA_OR_LOCAL_API", repairPlan.actions().get(0).actionType()); + assertTrue(repairPlan.actions().get(0).rationale().contains("实体接口不可用")); + assertEquals(3, service.listRuns(run.taskId()).size()); + assertTrue(service.listRuns(run.taskId()).stream().anyMatch(r -> "REPAIR_PLAN".equals(r.runType()))); + } + + @Test + @DisplayName("一键自动开发默认会自动修复可恢复的本地门禁失败") + void autoDevelopFeatureAutomaticallyRepairsRecoverableSmokeFailure() { + AtomicInteger smokeCalls = new AtomicInteger(); + AiSmokeRunner flakySmokeRunner = new AiSmokeRunner((method, uri, requestBody, timeout) -> { + if (smokeCalls.incrementAndGet() <= 4) { + return new AiHttpResponse(503, "temporary unavailable"); + } + return new AiHttpResponse(200, "{\"status\":0}"); + }); + AiAgentService service = newService(new NoopLocalReleaseExecutor(), flakySmokeRunner); + + var run = service.autoDevelopFeature(new AiAutoDevelopmentRequest( + contractTypeFeature(), "http://localhost:8084", true, null)); + + assertEquals("READY_FOR_HUMAN_REVIEW", run.status()); + assertEquals(run.originalChangeSetId(), run.changeSetId()); + assertEquals("PASSED", run.applyRun().status()); + assertEquals(1, run.repairExecutions().size()); + assertEquals("REPAIRED", run.repairExecutions().get(0).status()); + assertEquals("READY_FOR_HUMAN_REVIEW", run.deploymentPackage().status()); + assertTrue(run.messages().stream().anyMatch(m -> m.contains("自动修复第 1 轮结果: REPAIRED"))); + assertEquals("READY_FOR_HUMAN_REVIEW", service.getTask(run.taskId()).status()); + assertTrue(service.listRuns(run.taskId()).stream().anyMatch(r -> "REPAIR_EXECUTION".equals(r.runType()))); + } + + @Test + @DisplayName("一键自动开发关闭部署包时自动修复后只返回本地门禁通过") + void autoDevelopFeatureHonorsDeploymentPackageSwitchAfterRepair() { + AtomicInteger smokeCalls = new AtomicInteger(); + AiSmokeRunner flakySmokeRunner = new AiSmokeRunner((method, uri, requestBody, timeout) -> { + if (smokeCalls.incrementAndGet() <= 4) { + return new AiHttpResponse(503, "temporary unavailable"); + } + return new AiHttpResponse(200, "{\"status\":0}"); + }); + AiAgentService service = newService(new NoopLocalReleaseExecutor(), flakySmokeRunner); + + var run = service.autoDevelopFeature(new AiAutoDevelopmentRequest( + contractTypeFeature(), "http://localhost:8084", false, null)); + + assertEquals("LOCAL_GATE_PASSED", run.status()); + assertEquals("PASSED", run.applyRun().status()); + assertEquals(1, run.repairExecutions().size()); + assertEquals("REPAIRED", run.repairExecutions().get(0).status()); + assertNull(run.deploymentPackage()); + assertNull(run.repairExecutions().get(0).deploymentPackage()); + assertEquals("LOCAL_GATE_PASSED", service.getTask(run.taskId()).status()); + } + + @Test + @DisplayName("自动修复执行会重试瞬时 smoke 失败并生成新部署包") + void executeRepairPlanRetriesTransientSmokeFailure() { + AtomicInteger smokeCalls = new AtomicInteger(); + AiSmokeRunner flakySmokeRunner = new AiSmokeRunner((method, uri, requestBody, timeout) -> { + if (smokeCalls.incrementAndGet() <= 4) { + return new AiHttpResponse(503, "temporary unavailable"); + } + return new AiHttpResponse(200, "{\"status\":0}"); + }); + AiAgentService service = newService(new NoopLocalReleaseExecutor(), flakySmokeRunner); + + var run = service.autoDevelopFeature(new AiAutoDevelopmentRequest( + contractTypeFeature(), "http://localhost:8084", true, 0)); + + assertEquals("LOCAL_GATE_FAILED", run.status()); + assertEquals("SMOKE_FAILED", run.applyRun().status()); + + var repairPlan = service.createRepairPlan(run.taskId(), run.changeSetId()); + + assertEquals("READY_FOR_AUTO_RETRY", repairPlan.status()); + assertEquals(4, repairPlan.actions().size()); + assertTrue(repairPlan.actions().stream().allMatch(a -> a.automated())); + assertTrue(repairPlan.actions().stream() + .allMatch(a -> "RETRY_TRANSIENT_SMOKE_FAILURE".equals(a.actionType()))); + + var execution = service.executeRepairPlan(run.taskId(), run.changeSetId(), "http://localhost:8084"); + + assertEquals("REPAIRED", execution.status()); + assertTrue(execution.retryApplyRun().passed()); + assertEquals("READY_FOR_HUMAN_REVIEW", execution.deploymentPackage().status()); + assertEquals("READY_FOR_HUMAN_REVIEW", service.getTask(run.taskId()).status()); + assertTrue(service.listRuns(run.taskId()).stream().anyMatch(r -> "REPAIR_EXECUTION".equals(r.runType()))); + } + + @Test + @DisplayName("Agent 修复执行器会生成 TEST 草稿修复 HTTP 契约偏差并重跑") + void executeRepairPlanGeneratesDraftPatchForSmokeContractMismatch() { + AiSmokeRunner contractSmokeRunner = new AiSmokeRunner((method, uri, requestBody, timeout) -> { + if ("POST".equals(method) && uri.toString().contains("/save")) { + return new AiHttpResponse(201, "{\"status\":0}"); + } + return new AiHttpResponse(200, "{\"status\":0}"); + }); + AiAgentService service = newService(new NoopLocalReleaseExecutor(), contractSmokeRunner); + + var run = service.autoDevelopFeature(new AiAutoDevelopmentRequest( + contractTypeFeature(), "http://localhost:8084", true, 0)); + + assertEquals("LOCAL_GATE_FAILED", run.status()); + assertEquals("SMOKE_FAILED", run.applyRun().status()); + + var repairPlan = service.createRepairPlan(run.taskId(), run.changeSetId()); + + assertEquals("NEEDS_HUMAN_ACTION", repairPlan.status()); + assertEquals(1, repairPlan.actions().size()); + assertEquals("REPAIR_SMOKE_EXPECTATION_OR_API_CONTRACT", repairPlan.actions().get(0).actionType()); + + var execution = service.executeRepairPlan(run.taskId(), run.changeSetId(), "http://localhost:8084"); + + assertEquals("REPAIRED", execution.status()); + assertEquals(1, execution.generatedDrafts().size()); + assertEquals("TEST", execution.generatedDrafts().get(0).artifactType().name()); + assertTrue(execution.generatedDrafts().get(0).payload().path("smokeTests").toString() + .contains("\"expectHttpStatus\":201")); + assertTrue(execution.retryApplyRun().passed()); + assertEquals("READY_FOR_HUMAN_REVIEW", execution.deploymentPackage().status()); + assertEquals(5, execution.repairedChangeSet().draftIds().size()); + } + + @Test + @DisplayName("Agent 修复执行器会生成 PAGE_SCHEMA 草稿补齐缺失 body 并重跑") + void executeRepairPlanGeneratesPageSchemaPatch() throws Exception { + AiAgentService service = newService(new PageSchemaBodyRequiredExecutor()); + var task = service.createTask("修复页面 schema"); + JsonNode pageWithoutBody = MAPPER.readTree(""" + {"type":"page","title":"坏页面"} + """); + var pageDraft = service.addDraft(task.id(), "PAGE_SCHEMA", "bad-page", pageWithoutBody, Map.of()); + assertTrue(pageDraft.passed()); + JsonNode testPayload = MAPPER.readTree(""" + {"smokeTests":[{"name":"page-schema","method":"GET","url":"/api/page/schema/bad-page","expectHttpStatus":200}]} + """); + service.addDraft(task.id(), "TEST", "bad-page-smoke", testPayload, Map.of()); + var changeSet = service.createChangeSet(task.id()); + + var apply = service.applyLocalRelease(task.id(), changeSet.id(), "http://localhost:8084"); + assertEquals("APPLY_FAILED", apply.status()); + + var repairPlan = service.createRepairPlan(task.id(), changeSet.id()); + assertEquals("NEEDS_HUMAN_ACTION", repairPlan.status()); + assertEquals("REPAIR_PAGE_SCHEMA_SQL_OR_SCHEMA", repairPlan.actions().get(0).actionType()); + + var execution = service.executeRepairPlan(task.id(), changeSet.id(), "http://localhost:8084"); + + assertEquals("REPAIRED", execution.status()); + assertEquals(1, execution.generatedDrafts().size()); + assertEquals("PAGE_SCHEMA", execution.generatedDrafts().get(0).artifactType().name()); + assertTrue(execution.generatedDrafts().get(0).payload().has("body")); + assertTrue(execution.retryApplyRun().passed()); + assertEquals("READY_FOR_HUMAN_REVIEW", execution.deploymentPackage().status()); + assertEquals(2, execution.repairedChangeSet().draftIds().size()); + } + + @Test + @DisplayName("Agent 修复执行器会生成 MENU 草稿显式父级占位并重跑") + void executeRepairPlanGeneratesMenuParentPatch() throws Exception { + AiAgentService service = newService(new MenuParentRequiredExecutor()); + var task = service.createTask("修复菜单挂载"); + JsonNode menu = MAPPER.readTree(""" + {"name":"坏菜单","viewTemplateId":"bad-page","typename":"功能菜单","seq":0} + """); + service.addDraft(task.id(), "MENU", "bad-page", menu, Map.of()); + JsonNode testPayload = MAPPER.readTree(""" + {"smokeTests":[{"name":"page-schema","method":"GET","url":"/api/page/schema/bad-page","expectHttpStatus":200}]} + """); + service.addDraft(task.id(), "TEST", "bad-page-smoke", testPayload, Map.of()); + var changeSet = service.createChangeSet(task.id()); + + var apply = service.applyLocalRelease(task.id(), changeSet.id(), "http://localhost:8084"); + assertEquals("APPLY_FAILED", apply.status()); + + var repairPlan = service.createRepairPlan(task.id(), changeSet.id()); + assertEquals("NEEDS_HUMAN_ACTION", repairPlan.status()); + assertEquals("SEED_MENU_ROOT_OR_SET_PARENT", repairPlan.actions().get(0).actionType()); + + var execution = service.executeRepairPlan(task.id(), changeSet.id(), "http://localhost:8084"); + + assertEquals("REPAIRED", execution.status()); + assertEquals(1, execution.generatedDrafts().size()); + assertEquals("MENU", execution.generatedDrafts().get(0).artifactType().name()); + assertEquals("${parentMenuId}", execution.generatedDrafts().get(0).payload().path("parentId").asText()); + assertTrue(execution.retryApplyRun().passed()); + assertEquals("READY_FOR_HUMAN_REVIEW", execution.deploymentPackage().status()); + assertTrue(execution.deploymentPackage().warnings().stream().anyMatch(w -> w.contains("parentId"))); + assertEquals(2, execution.repairedChangeSet().draftIds().size()); + } + + @Test + @DisplayName("Agent 修复执行器会生成 SERVICEFLOW 草稿恢复 entityId 占位绑定并重跑") + void executeRepairPlanGeneratesServiceFlowEntityBindingPatch() throws Exception { + AiAgentService service = newService(new ServiceFlowEntityBindingExecutor()); + var task = service.createTask("修复服务流 entityId 绑定"); + JsonNode entity = MAPPER.readTree(""" + {"tablename":"EIP4AI_FLOW_FIX","name":"服务流修复","attributes":[{"column":"NAME","display":"名称","type":"string","mandatory":true}]} + """); + service.addDraft(task.id(), "ENTITY", "EIP4AI_FLOW_FIX", entity, Map.of()); + JsonNode serviceFlow = MAPPER.readTree(""" + {"requiresEntityId":true,"flows":[{"key":"EIP4AI_FLOW_FIX_SEARCH","displayName":"查询","entityId":"wrong-entity-id","control":true,"updateable":true,"contentXml":""}]} + """); + service.addDraft(task.id(), "SERVICEFLOW", "EIP4AI_FLOW_FIX_DEFAULT_FLOWS", serviceFlow, Map.of()); + JsonNode testPayload = MAPPER.readTree(""" + {"smokeTests":[{"name":"flow-search","method":"GET","url":"/api/flow/EIP4AI_FLOW_FIX_SEARCH","expectHttpStatus":200}]} + """); + service.addDraft(task.id(), "TEST", "flow-fix-smoke", testPayload, Map.of()); + var changeSet = service.createChangeSet(task.id()); + + var apply = service.applyLocalRelease(task.id(), changeSet.id(), "http://localhost:8084"); + assertEquals("APPLY_FAILED", apply.status()); + + var repairPlan = service.createRepairPlan(task.id(), changeSet.id()); + assertEquals("NEEDS_HUMAN_ACTION", repairPlan.status()); + assertEquals("RETRY_AFTER_ENTITY_ID_RESOLUTION", repairPlan.actions().get(0).actionType()); + + var execution = service.executeRepairPlan(task.id(), changeSet.id(), "http://localhost:8084"); + + assertEquals("REPAIRED", execution.status()); + assertEquals(1, execution.generatedDrafts().size()); + assertEquals("SERVICEFLOW", execution.generatedDrafts().get(0).artifactType().name()); + assertTrue(execution.generatedDrafts().get(0).payload().toString().contains("${entityId}")); + assertTrue(execution.retryApplyRun().passed()); + assertEquals("READY_FOR_HUMAN_REVIEW", execution.deploymentPackage().status()); + assertEquals(3, execution.repairedChangeSet().draftIds().size()); + } + + @Test + @DisplayName("Agent 修复执行器会生成 ENTITY 草稿补齐发布目标并重跑") + void executeRepairPlanGeneratesEntityPublishTargetPatch() throws Exception { + AiAgentService service = newService(new EntityPublishTargetRequiredExecutor()); + var task = service.createTask("修复实体发布目标"); + JsonNode entity = MAPPER.readTree(""" + {"tablename":"EIP4AI_ENTITY_FIX","name":"实体修复","attributes":[{"column":"NAME","display":"","type":"string","mandatory":true}]} + """); + service.addDraft(task.id(), "ENTITY", "EIP4AI_ENTITY_FIX", entity, Map.of()); + JsonNode testPayload = MAPPER.readTree(""" + {"smokeTests":[{"name":"entity-list","method":"GET","url":"/api/entity/EIP4AI_ENTITY_FIX/list","expectHttpStatus":200}]} + """); + service.addDraft(task.id(), "TEST", "entity-fix-smoke", testPayload, Map.of()); + var changeSet = service.createChangeSet(task.id()); + + var apply = service.applyLocalRelease(task.id(), changeSet.id(), "http://localhost:8084"); + assertEquals("APPLY_FAILED", apply.status()); + + var repairPlan = service.createRepairPlan(task.id(), changeSet.id()); + assertEquals("NEEDS_HUMAN_ACTION", repairPlan.status()); + assertEquals("REPAIR_ENTITY_METADATA_OR_LOCAL_API", repairPlan.actions().get(0).actionType()); + + var execution = service.executeRepairPlan(task.id(), changeSet.id(), "http://localhost:8084"); + + assertEquals("REPAIRED", execution.status()); + assertEquals(1, execution.generatedDrafts().size()); + assertEquals("ENTITY", execution.generatedDrafts().get(0).artifactType().name()); + assertEquals("/api/meta/entity", execution.generatedDrafts().get(0).payload().path("publishTarget").asText()); + assertEquals("NAME", execution.generatedDrafts().get(0).payload().path("attributes").get(0).path("display").asText()); + assertTrue(execution.retryApplyRun().passed()); + assertEquals("READY_FOR_HUMAN_REVIEW", execution.deploymentPackage().status()); + assertEquals(2, execution.repairedChangeSet().draftIds().size()); + } + + @Test + @DisplayName("LLM 修复客户端返回草稿补丁时优先于确定性 fallback") + void executeRepairPlanUsesLlmDraftPatchBeforeDeterministicFallback() throws Exception { + AiLlmRepairClient llmClient = context -> java.util.List.of(new AiRepairDraftPatch( + AiArtifactType.ENTITY, + "EIP4AI_ENTITY_FIX", + json(""" + {"publishTarget":"/api/meta/entity","tablename":"EIP4AI_ENTITY_FIX","name":"LLM实体修复","attributes":[{"column":"NAME","display":"LLM名称","type":"string","mandatory":true}]} + """), + Map.of("source", "fake-llm"))); + AiAgentService service = newService(new EntityPublishTargetRequiredExecutor(), + new AiSmokeRunner((method, uri, requestBody, timeout) -> new AiHttpResponse(200, "{\"status\":0}")), + new DeterministicAiAgentRepairExecutor(MAPPER, java.util.List.of(llmClient))); + var task = service.createTask("LLM 修复实体发布目标"); + JsonNode entity = MAPPER.readTree(""" + {"tablename":"EIP4AI_ENTITY_FIX","name":"实体修复","attributes":[{"column":"NAME","display":"","type":"string","mandatory":true}]} + """); + service.addDraft(task.id(), "ENTITY", "EIP4AI_ENTITY_FIX", entity, Map.of()); + JsonNode testPayload = MAPPER.readTree(""" + {"smokeTests":[{"name":"entity-list","method":"GET","url":"/api/entity/EIP4AI_ENTITY_FIX/list","expectHttpStatus":200}]} + """); + service.addDraft(task.id(), "TEST", "entity-fix-smoke", testPayload, Map.of()); + var changeSet = service.createChangeSet(task.id()); + service.applyLocalRelease(task.id(), changeSet.id(), "http://localhost:8084"); + service.createRepairPlan(task.id(), changeSet.id()); + + var execution = service.executeRepairPlan(task.id(), changeSet.id(), "http://localhost:8084"); + + assertEquals("REPAIRED", execution.status()); + assertEquals("LLM实体修复", execution.generatedDrafts().get(0).payload().path("name").asText()); + assertEquals("fake-llm", execution.generatedDrafts().get(0).metadata().get("source")); + assertTrue(execution.retryApplyRun().passed()); + } + + @Test + @DisplayName("实体草稿字段非法会阻止生成变更包") + void invalidEntityDraftBlocksChangeSet() { + AiAgentService service = newService(); + var task = service.createTask("坏实体"); + JsonNode invalidEntity = MAPPER.createObjectNode() + .put("tablename", "bad table") + .put("name", "坏实体") + .set("attributes", MAPPER.createArrayNode() + .add(MAPPER.createObjectNode().put("column", "BAD-COL").put("type", "unknown"))); + + var draft = service.addDraft(task.id(), "ENTITY", "bad", invalidEntity, null); + + assertFalse(draft.passed()); + ResponseStatusException ex = assertThrows(ResponseStatusException.class, + () -> service.createChangeSet(task.id())); + assertEquals(409, ex.getStatusCode().value()); + } + + private static AiAgentService newService() { + return newService(new NoopLocalReleaseExecutor()); + } + + private static AiAgentService newService(AiLocalReleaseExecutor localReleaseExecutor) { + return newService(localReleaseExecutor, + new AiSmokeRunner((method, uri, requestBody, timeout) -> new AiHttpResponse(200, "{\"status\":0}"))); + } + + private static AiAgentService newService(AiLocalReleaseExecutor localReleaseExecutor, AiSmokeRunner smokeRunner) { + return newService(localReleaseExecutor, smokeRunner, new DeterministicAiAgentRepairExecutor(MAPPER)); + } + + private static AiAgentService newService(AiLocalReleaseExecutor localReleaseExecutor, + AiSmokeRunner smokeRunner, + AiAgentRepairExecutor repairExecutor) { + return new AiAgentService(new InMemoryAiAgentStore(), new AiFeatureDraftGenerator(MAPPER), + smokeRunner, localReleaseExecutor, repairExecutor, MAPPER); + } + + private static AiFeatureRequest contractTypeFeature() { + return new AiFeatureRequest( + "新增合同类型维护功能", + "合同类型维护", + "EIP4AI_CONTRACT_TYPE", + "合同类型", + "eip4ai-contract-type", + "合同类型维护", + java.util.List.of( + new AiFeatureField("NAME", "名称", "string", 100, true), + new AiFeatureField("CODE", "编码", "string", 64, true), + new AiFeatureField("ENABLED", "启用", "boolean", null, false))); + } + + private static JsonNode json(String text) { + try { + return MAPPER.readTree(text); + } catch (Exception ex) { + throw new IllegalArgumentException(ex); + } + } + + private static class NoopLocalReleaseExecutor extends AiLocalReleaseExecutor { + NoopLocalReleaseExecutor() { + super(org.mockito.Mockito.mock(org.springframework.jdbc.core.JdbcTemplate.class), + (method, uri, requestBody, timeout) -> new AiHttpResponse(200, "{\"status\":0}"), MAPPER); + } + + @Override + public java.util.List apply( + String baseUrl, java.util.List drafts) { + return drafts.stream() + .filter(d -> d.artifactType() != com.eip4.platform.ai.model.AiArtifactType.TEST) + .map(d -> { + Map details = switch (d.artifactType()) { + case ENTITY -> Map.of("entityId", "e-test-entity-id", "tableName", d.targetId()); + case SERVICEFLOW -> Map.of("flowCount", 5, "entityId", "e-test-entity-id"); + case PAGE_SCHEMA -> Map.of("templateId", d.targetId(), "etag", "test-etag"); + case MENU -> Map.of("menuId", "m-test-menu-id"); + case CODE, TEST -> Map.of(); + }; + return new com.eip4.platform.ai.model.AiApplyStepResult( + "apply-" + d.id(), d.artifactType(), d.targetId(), "APPLIED", "ok", details); + }) + .toList(); + } + } + + private static class FailingLocalReleaseExecutor extends AiLocalReleaseExecutor { + FailingLocalReleaseExecutor() { + super(org.mockito.Mockito.mock(org.springframework.jdbc.core.JdbcTemplate.class), + (method, uri, requestBody, timeout) -> new AiHttpResponse(500, "{\"status\":1}"), MAPPER); + } + + @Override + public java.util.List apply( + String baseUrl, java.util.List drafts) { + var first = drafts.get(0); + return java.util.List.of(new com.eip4.platform.ai.model.AiApplyStepResult( + "apply-1", first.artifactType(), first.targetId(), "FAILED", + "实体接口不可用", Map.of())); + } + } + + private static class PageSchemaBodyRequiredExecutor extends AiLocalReleaseExecutor { + PageSchemaBodyRequiredExecutor() { + super(org.mockito.Mockito.mock(org.springframework.jdbc.core.JdbcTemplate.class), + (method, uri, requestBody, timeout) -> new AiHttpResponse(200, "{\"status\":0}"), MAPPER); + } + + @Override + public java.util.List apply( + String baseUrl, java.util.List drafts) { + java.util.List out = new java.util.ArrayList<>(); + int index = 1; + for (var draft : drafts) { + if (draft.artifactType() == com.eip4.platform.ai.model.AiArtifactType.TEST) { + continue; + } + if (draft.artifactType() == com.eip4.platform.ai.model.AiArtifactType.PAGE_SCHEMA + && !draft.payload().has("body")) { + out.add(new com.eip4.platform.ai.model.AiApplyStepResult( + "apply-" + index, draft.artifactType(), draft.targetId(), "FAILED", + "页面 schema 缺少 body", Map.of())); + return out; + } + out.add(new com.eip4.platform.ai.model.AiApplyStepResult( + "apply-" + index, draft.artifactType(), draft.targetId(), "APPLIED", "ok", Map.of())); + index++; + } + return out; + } + } + + private static class MenuParentRequiredExecutor extends AiLocalReleaseExecutor { + MenuParentRequiredExecutor() { + super(org.mockito.Mockito.mock(org.springframework.jdbc.core.JdbcTemplate.class), + (method, uri, requestBody, timeout) -> new AiHttpResponse(200, "{\"status\":0}"), MAPPER); + } + + @Override + public java.util.List apply( + String baseUrl, java.util.List drafts) { + java.util.List out = new java.util.ArrayList<>(); + int index = 1; + for (var draft : drafts) { + if (draft.artifactType() == com.eip4.platform.ai.model.AiArtifactType.TEST) { + continue; + } + if (draft.artifactType() == com.eip4.platform.ai.model.AiArtifactType.MENU + && draft.payload().path("parentId").asText("").isBlank()) { + out.add(new com.eip4.platform.ai.model.AiApplyStepResult( + "apply-" + index, draft.artifactType(), draft.targetId(), "FAILED", + "缺少 sys_menu_root,不能自动挂载菜单", Map.of())); + return out; + } + out.add(new com.eip4.platform.ai.model.AiApplyStepResult( + "apply-" + index, draft.artifactType(), draft.targetId(), "APPLIED", "ok", Map.of())); + index++; + } + return out; + } + } + + private static class ServiceFlowEntityBindingExecutor extends AiLocalReleaseExecutor { + ServiceFlowEntityBindingExecutor() { + super(org.mockito.Mockito.mock(org.springframework.jdbc.core.JdbcTemplate.class), + (method, uri, requestBody, timeout) -> new AiHttpResponse(200, "{\"status\":0}"), MAPPER); + } + + @Override + public java.util.List apply( + String baseUrl, java.util.List drafts) { + java.util.List out = new java.util.ArrayList<>(); + int index = 1; + for (var draft : drafts) { + if (draft.artifactType() == com.eip4.platform.ai.model.AiArtifactType.TEST) { + continue; + } + if (draft.artifactType() == com.eip4.platform.ai.model.AiArtifactType.SERVICEFLOW + && !draft.payload().toString().contains("${entityId}")) { + out.add(new com.eip4.platform.ai.model.AiApplyStepResult( + "apply-" + index, draft.artifactType(), draft.targetId(), "FAILED", + "服务流 contentXml 缺少 ${entityId} 占位", Map.of())); + return out; + } + out.add(new com.eip4.platform.ai.model.AiApplyStepResult( + "apply-" + index, draft.artifactType(), draft.targetId(), "APPLIED", "ok", Map.of())); + index++; + } + return out; + } + } + + private static class EntityPublishTargetRequiredExecutor extends AiLocalReleaseExecutor { + EntityPublishTargetRequiredExecutor() { + super(org.mockito.Mockito.mock(org.springframework.jdbc.core.JdbcTemplate.class), + (method, uri, requestBody, timeout) -> new AiHttpResponse(200, "{\"status\":0}"), MAPPER); + } + + @Override + public java.util.List apply( + String baseUrl, java.util.List drafts) { + java.util.List out = new java.util.ArrayList<>(); + int index = 1; + for (var draft : drafts) { + if (draft.artifactType() == com.eip4.platform.ai.model.AiArtifactType.TEST) { + continue; + } + if (draft.artifactType() == com.eip4.platform.ai.model.AiArtifactType.ENTITY + && !"/api/meta/entity".equals(draft.payload().path("publishTarget").asText(""))) { + out.add(new com.eip4.platform.ai.model.AiApplyStepResult( + "apply-" + index, draft.artifactType(), draft.targetId(), "FAILED", + "实体草稿缺少 publishTarget=/api/meta/entity", Map.of())); + return out; + } + out.add(new com.eip4.platform.ai.model.AiApplyStepResult( + "apply-" + index, draft.artifactType(), draft.targetId(), "APPLIED", "ok", + draft.artifactType() == com.eip4.platform.ai.model.AiArtifactType.ENTITY + ? Map.of("entityId", "e-test-entity-id") : Map.of())); + index++; + } + return out; + } + } +} diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/service/AiFeatureDraftGeneratorTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiFeatureDraftGeneratorTest.java new file mode 100644 index 0000000..6ac0e6d --- /dev/null +++ b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiFeatureDraftGeneratorTest.java @@ -0,0 +1,71 @@ +package com.eip4.platform.ai.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import com.eip4.platform.ai.model.AiArtifactType; +import com.eip4.platform.ai.model.AiFeatureField; +import com.eip4.platform.ai.model.AiFeatureRequest; +import com.fasterxml.jackson.databind.ObjectMapper; + +class AiFeatureDraftGeneratorTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + @DisplayName("根据功能规格生成 5 类草稿") + void generatesFeatureDrafts() { + AiFeatureDraftGenerator generator = new AiFeatureDraftGenerator(MAPPER); + + var drafts = generator.generate(new AiFeatureRequest( + "新增合同类型维护", + "合同类型维护", + "EIP4AI_CONTRACT_TYPE", + "合同类型", + "eip4ai-contract-type", + "合同类型维护", + List.of(new AiFeatureField("NAME", "名称", "string", 100, true)))); + + assertEquals(5, drafts.size()); + assertTrue(drafts.stream().anyMatch(d -> d.artifactType() == AiArtifactType.ENTITY)); + assertTrue(drafts.stream().anyMatch(d -> d.artifactType() == AiArtifactType.PAGE_SCHEMA)); + assertTrue(drafts.stream().anyMatch(d -> d.artifactType() == AiArtifactType.SERVICEFLOW)); + assertTrue(drafts.stream().anyMatch(d -> d.artifactType() == AiArtifactType.MENU)); + assertTrue(drafts.stream().anyMatch(d -> d.artifactType() == AiArtifactType.TEST)); + var serviceFlow = drafts.stream().filter(d -> d.artifactType() == AiArtifactType.SERVICEFLOW) + .findFirst().orElseThrow(); + assertEquals(5, serviceFlow.payload().path("flows").size()); + assertFalse(serviceFlow.payload().path("flows").get(0).path("contentXml").asText().isBlank()); + var test = drafts.stream().filter(d -> d.artifactType() == AiArtifactType.TEST) + .findFirst().orElseThrow(); + assertTrue(test.payload().path("smokeTests").get(3).has("requestBody")); + } + + @Test + @DisplayName("功能规格缺表名和字段时生成安全默认值") + void fillsSafeDefaults() { + AiFeatureDraftGenerator generator = new AiFeatureDraftGenerator(MAPPER); + + var drafts = generator.generate(new AiFeatureRequest( + "新增客户反馈登记", + "客户反馈登记", + null, + null, + null, + null, + null)); + + var entity = drafts.stream().filter(d -> d.artifactType() == AiArtifactType.ENTITY) + .findFirst().orElseThrow(); + assertTrue(entity.targetId().startsWith("EIP4AI_")); + assertNotNull(entity.payload().path("attributes").get(0)); + assertEquals("NAME", entity.payload().path("attributes").get(0).path("column").asText()); + } +} diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/service/AiLocalReleaseExecutorTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiLocalReleaseExecutorTest.java new file mode 100644 index 0000000..616d2ff --- /dev/null +++ b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiLocalReleaseExecutorTest.java @@ -0,0 +1,128 @@ +package com.eip4.platform.ai.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockingDetails; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.core.JdbcTemplate; + +import com.eip4.platform.ai.model.AiArtifactType; +import com.eip4.platform.ai.model.AiDraft; +import com.eip4.platform.ai.model.AiFeatureField; +import com.eip4.platform.ai.model.AiFeatureRequest; +import com.eip4.platform.ai.model.AiGeneratedDraft; +import com.eip4.platform.ai.model.AiGateResult; +import com.fasterxml.jackson.databind.ObjectMapper; + +class AiLocalReleaseExecutorTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + @DisplayName("本地应用按实体→服务流→页面→菜单写入") + void appliesGeneratedDrafts() { + JdbcTemplate jdbc = mock(JdbcTemplate.class); + when(jdbc.queryForObject(anyString(), eq(Boolean.class), any())).thenReturn(true); + when(jdbc.queryForList(anyString(), eq(String.class))).thenReturn(List.of("ROOT")); + when(jdbc.queryForList(anyString(), eq(String.class), any())).thenReturn(List.of()); + when(jdbc.update(anyString(), org.mockito.ArgumentMatchers.any())).thenReturn(1); + when(jdbc.update(anyString(), org.mockito.ArgumentMatchers.any())).thenReturn(1); + + AiLocalReleaseExecutor executor = new AiLocalReleaseExecutor(jdbc, + (method, uri, requestBody, timeout) -> new AiHttpResponse(200, + "{\"status\":0,\"data\":{\"entityId\":\"e1000000-0000-0000-0000-00000000ai01\"}}"), + MAPPER); + AiFeatureDraftGenerator generator = new AiFeatureDraftGenerator(MAPPER); + List drafts = toDrafts(generator.generate(new AiFeatureRequest( + "新增合同类型维护", "合同类型维护", "EIP4AI_CONTRACT_TYPE", "合同类型", + "eip4ai-contract-type", "合同类型维护", + List.of(new AiFeatureField("NAME", "名称", "string", 100, true))))); + + var results = executor.apply("http://localhost:8084", drafts); + + assertEquals(4, results.size()); + assertTrue(results.stream().allMatch(r -> "APPLIED".equals(r.status()))); + assertEquals("ENTITY", results.get(0).artifactType().name()); + assertEquals("SERVICEFLOW", results.get(1).artifactType().name()); + assertEquals("PAGE_SCHEMA", results.get(2).artifactType().name()); + assertEquals("MENU", results.get(3).artifactType().name()); + assertTrue(hasUpdateSql(jdbc, "sys_serviceflow")); + assertTrue(hasUpdateSql(jdbc, "sys_page_schema")); + assertTrue(hasUpdateSql(jdbc, "sys_menu")); + } + + @Test + @DisplayName("实体已存在时复用本地 entityId 并视为幂等成功") + void reusesExistingEntityId() { + JdbcTemplate jdbc = mock(JdbcTemplate.class); + when(jdbc.queryForList(anyString(), eq(String.class), eq("EIP4AI_EXISTING"))) + .thenReturn(List.of("entity-existing-001")); + + AiLocalReleaseExecutor executor = new AiLocalReleaseExecutor(jdbc, + (method, uri, requestBody, timeout) -> new AiHttpResponse(200, + "{\"status\":1,\"msg\":\"实体已存在: EIP4AI_EXISTING\"}"), + MAPPER); + AiDraft draft = new AiDraft("d-entity", "t-1", AiArtifactType.ENTITY, "EIP4AI_EXISTING", + MAPPER.createObjectNode().put("tablename", "EIP4AI_EXISTING"), + 1L, List.of(new AiGateResult("ok", true, List.of())), Map.of()); + + var results = executor.apply("http://localhost:8084", List.of(draft)); + + assertEquals(1, results.size()); + assertEquals("APPLIED", results.get(0).status()); + assertEquals("entity-existing-001", results.get(0).details().get("entityId")); + assertEquals(true, results.get(0).details().get("idempotent")); + } + + @Test + @DisplayName("本地库缺 sys_menu 时菜单发布跳过但不阻断 apply") + void skipsMenuWhenLocalSchemaDoesNotHaveMenuTable() { + JdbcTemplate jdbc = mock(JdbcTemplate.class); + when(jdbc.queryForObject(anyString(), eq(Boolean.class), any())).thenReturn(false); + when(jdbc.update(anyString(), org.mockito.ArgumentMatchers.any())).thenReturn(1); + + AiLocalReleaseExecutor executor = new AiLocalReleaseExecutor(jdbc, + (method, uri, requestBody, timeout) -> new AiHttpResponse(200, + "{\"status\":0,\"data\":{\"entityId\":\"e1000000-0000-0000-0000-00000000ai01\"}}"), + MAPPER); + AiFeatureDraftGenerator generator = new AiFeatureDraftGenerator(MAPPER); + List drafts = toDrafts(generator.generate(new AiFeatureRequest( + "新增合同类型维护", "合同类型维护", "EIP4AI_CONTRACT_TYPE", "合同类型", + "eip4ai-contract-type", "合同类型维护", + List.of(new AiFeatureField("NAME", "名称", "string", 100, true))))); + + var results = executor.apply("http://localhost:8084", drafts); + + assertEquals(4, results.size()); + assertEquals("SKIPPED", results.get(3).status()); + assertTrue(results.get(3).message().contains("sys_menu")); + } + + private static List toDrafts(List generated) { + List drafts = new ArrayList<>(); + for (AiGeneratedDraft g : generated) { + drafts.add(new AiDraft("d-" + drafts.size(), "t-1", g.artifactType(), g.targetId(), g.payload(), + 1L, List.of(new AiGateResult("ok", true, List.of())), Map.of())); + } + return drafts; + } + + private static boolean hasUpdateSql(JdbcTemplate jdbc, String token) { + return mockingDetails(jdbc).getInvocations().stream() + .filter(i -> "update".equals(i.getMethod().getName())) + .anyMatch(i -> i.getArguments().length > 0 && String.valueOf(i.getArguments()[0]).contains(token)); + } +} diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/service/AiSmokeRunnerTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiSmokeRunnerTest.java new file mode 100644 index 0000000..b616005 --- /dev/null +++ b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiSmokeRunnerTest.java @@ -0,0 +1,76 @@ +package com.eip4.platform.ai.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.web.server.ResponseStatusException; + +import com.fasterxml.jackson.databind.ObjectMapper; + +class AiSmokeRunnerTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + @DisplayName("运行 smokeTests 并返回逐条结果") + void runsSmokeTests() throws Exception { + List called = new ArrayList<>(); + AiSmokeRunner runner = new AiSmokeRunner((method, uri, requestBody, timeout) -> { + called.add(uri); + return new AiHttpResponse(uri.getPath().endsWith("/ok") ? 200 : 500, "{\"ok\":true}"); + }); + + var run = runner.run("ait-1", "aics-1", "http://localhost:8084", MAPPER.readTree(""" + {"smokeTests":[ + {"name":"ok","method":"GET","url":"/api/ok","expectHttpStatus":200}, + {"name":"bad","method":"GET","url":"/api/bad","expectHttpStatus":200} + ]} + """)); + + assertFalse(run.passed()); + assertEquals("FAILED", run.status()); + assertEquals(2, run.results().size()); + assertTrue(run.results().get(0).passed()); + assertFalse(run.results().get(1).passed()); + assertEquals("http://localhost:8084/api/ok", called.get(0).toString()); + } + + @Test + @DisplayName("HTTP 200 但响应 JSON status 非 0 时判失败") + void failsOnBusinessStatusError() throws Exception { + AiSmokeRunner runner = new AiSmokeRunner((method, uri, requestBody, timeout) -> + new AiHttpResponse(200, "{\"status\":1,\"msg\":\"业务失败\"}")); + + var run = runner.run("ait-1", "aics-1", "http://localhost:8084", MAPPER.readTree(""" + {"smokeTests":[ + {"name":"biz","method":"GET","url":"/api/biz","expectHttpStatus":200} + ]} + """)); + + assertFalse(run.passed()); + assertEquals("FAILED", run.status()); + assertFalse(run.results().get(0).passed()); + assertTrue(run.results().get(0).error().contains("status=1")); + } + + @Test + @DisplayName("smoke runner 拒绝非本机 baseUrl") + void rejectsRemoteBaseUrl() throws Exception { + AiSmokeRunner runner = new AiSmokeRunner((method, uri, requestBody, timeout) -> new AiHttpResponse(200, "")); + + ResponseStatusException ex = assertThrows(ResponseStatusException.class, + () -> runner.run("ait-1", "aics-1", "https://example.com", MAPPER.readTree(""" + {"smokeTests":[{"name":"x","method":"GET","url":"/api/x","expectHttpStatus":200}]} + """))); + + assertEquals(400, ex.getStatusCode().value()); + } +} diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/service/AiSpringWiringTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiSpringWiringTest.java new file mode 100644 index 0000000..e88acf5 --- /dev/null +++ b/platform-ai/src/test/java/com/eip4/platform/ai/service/AiSpringWiringTest.java @@ -0,0 +1,37 @@ +package com.eip4.platform.ai.service; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.core.JdbcTemplate; + +import com.eip4.platform.ai.store.AiAgentStore; +import com.eip4.platform.ai.web.AiAgentController; +import com.fasterxml.jackson.databind.ObjectMapper; + +class AiSpringWiringTest { + + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withUserConfiguration(AiModuleConfiguration.class) + .withBean(ObjectMapper.class, ObjectMapper::new) + .withBean(JdbcTemplate.class, () -> org.mockito.Mockito.mock(JdbcTemplate.class)); + + @Test + void aiModuleComponentsWireInSpringContext() { + contextRunner.run(context -> { + assertThat(context).hasSingleBean(AiAgentController.class); + assertThat(context).hasSingleBean(AiAgentService.class); + assertThat(context).hasSingleBean(AiSmokeRunner.class); + assertThat(context).hasSingleBean(AiSmokeHttpClient.class); + assertThat(context).hasSingleBean(AiAgentStore.class); + }); + } + + @Configuration + @ComponentScan("com.eip4.platform.ai") + static class AiModuleConfiguration { + } +} diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/service/HttpAiLlmRepairClientTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/service/HttpAiLlmRepairClientTest.java new file mode 100644 index 0000000..5dcce10 --- /dev/null +++ b/platform-ai/src/test/java/com/eip4/platform/ai/service/HttpAiLlmRepairClientTest.java @@ -0,0 +1,113 @@ +package com.eip4.platform.ai.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; + +import com.eip4.platform.ai.model.AiAgentRepairContext; +import com.eip4.platform.ai.model.AiArtifactType; +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.AiRepairAction; +import com.eip4.platform.ai.model.AiRepairDraftPatch; +import com.eip4.platform.ai.model.AiRepairPlan; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpServer; + +import org.junit.jupiter.api.Test; + +class HttpAiLlmRepairClientTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void sendsRepairContextAndParsesDraftPatches() throws Exception { + AtomicReference authorization = new AtomicReference<>(); + AtomicReference requestBody = new AtomicReference<>(); + HttpServer server = startServer(200, authorization, requestBody, """ + { + "draftPatches": [ + { + "artifactType": "PAGE_SCHEMA", + "targetId": "customer-page", + "payload": {"type":"page","title":"客户管理","body":[]}, + "metadata": {"source":"llm-repair"} + } + ] + } + """); + try { + String endpoint = "http://127.0.0.1:" + server.getAddress().getPort() + "/repair"; + HttpAiLlmRepairClient client = new HttpAiLlmRepairClient( + MAPPER, HttpClient.newHttpClient(), endpoint, "secret-token", "repair-model"); + + List patches = client.repair(context()); + + assertEquals("Bearer secret-token", authorization.get()); + assertTrue(requestBody.get().contains("\"model\":\"repair-model\"")); + assertTrue(requestBody.get().contains("\"taskId\":\"ait-1\"")); + assertTrue(requestBody.get().contains("\"responseField\":\"draftPatches\"")); + assertEquals(1, patches.size()); + assertEquals(AiArtifactType.PAGE_SCHEMA, patches.get(0).artifactType()); + assertEquals("customer-page", patches.get(0).targetId()); + assertEquals("llm-repair", patches.get(0).metadata().get("source")); + } finally { + server.stop(0); + } + } + + @Test + void returnsEmptyPatchesWhenProviderFails() throws Exception { + HttpServer server = startServer(500, new AtomicReference<>(), new AtomicReference<>(), "{}"); + try { + String endpoint = "http://127.0.0.1:" + server.getAddress().getPort() + "/repair"; + HttpAiLlmRepairClient client = new HttpAiLlmRepairClient( + MAPPER, HttpClient.newHttpClient(), endpoint, "", "repair-model"); + + assertTrue(client.repair(context()).isEmpty()); + } finally { + server.stop(0); + } + } + + private static HttpServer startServer(int statusCode, + AtomicReference authorization, + AtomicReference requestBody, + String response) throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/repair", exchange -> { + authorization.set(exchange.getRequestHeaders().getFirst("Authorization")); + requestBody.set(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)); + byte[] bytes = response.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(statusCode, bytes.length); + exchange.getResponseBody().write(bytes); + exchange.close(); + }); + server.start(); + return server; + } + + private static AiAgentRepairContext context() throws Exception { + AiRepairPlan plan = new AiRepairPlan("ait-1", "aics-1", "run-1", "READY_FOR_AUTO_RETRY", + 100L, + List.of(new AiRepairAction("repair-1", "LOCAL_APPLY", "REPAIR_PAGE_SCHEMA_SQL_OR_SCHEMA", + "PAGE_SCHEMA", "customer-page", false, "页面 schema 缺少 body", Map.of())), + List.of("需要修复页面 schema")); + AiDraft draft = new AiDraft("aid-1", "ait-1", AiArtifactType.PAGE_SCHEMA, "customer-page", + MAPPER.readTree("{\"type\":\"page\",\"title\":\"客户管理\"}"), + 90L, + List.of(new AiGateResult("schema", true, List.of())), + Map.of("source", "test")); + return new AiAgentRepairContext("ait-1", new AiChangeSet("aics-1", "ait-1", + "READY_FOR_REVIEW", 80L, List.of("aid-1"), Map.of()).id(), plan, List.of(draft)); + } +} diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/store/AiAgentDdlTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/store/AiAgentDdlTest.java new file mode 100644 index 0000000..91d104a --- /dev/null +++ b/platform-ai/src/test/java/com/eip4/platform/ai/store/AiAgentDdlTest.java @@ -0,0 +1,27 @@ +package com.eip4.platform.ai.store; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.util.StreamUtils; + +class AiAgentDdlTest { + + @Test + @DisplayName("AI Agent bootstrap DDL 包含运行态平台表") + void bootstrapDdlDeclaresTables() throws Exception { + String ddl = StreamUtils.copyToString( + getClass().getResourceAsStream("/bootstrap/bootstrap-ai-agent.sql"), + StandardCharsets.UTF_8); + + assertTrue(ddl.contains("CREATE TABLE IF NOT EXISTS sys_ai_task")); + assertTrue(ddl.contains("CREATE TABLE IF NOT EXISTS sys_ai_draft")); + assertTrue(ddl.contains("CREATE TABLE IF NOT EXISTS sys_ai_change_set")); + assertTrue(ddl.contains("CREATE TABLE IF NOT EXISTS sys_ai_run")); + assertTrue(ddl.contains("CREATE TABLE IF NOT EXISTS sys_ai_audit_log")); + assertTrue(ddl.contains("CREATE INDEX IF NOT EXISTS idx_sys_ai_run_task")); + } +} diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/store/InMemoryAiAgentStoreTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/store/InMemoryAiAgentStoreTest.java new file mode 100644 index 0000000..1cde54c --- /dev/null +++ b/platform-ai/src/test/java/com/eip4/platform/ai/store/InMemoryAiAgentStoreTest.java @@ -0,0 +1,52 @@ +package com.eip4.platform.ai.store; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +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.databind.ObjectMapper; + +class InMemoryAiAgentStoreTest { + + @Test + @DisplayName("内存存储按任务隔离 task/draft/change-set/audit") + void storesTaskScopedArtifacts() { + ObjectMapper mapper = new ObjectMapper(); + InMemoryAiAgentStore store = new InMemoryAiAgentStore(); + AiTask task = new AiTask("ait-1", "目标", "DRAFTING", 1L, 1L, List.of("plan")); + AiDraft draft = new AiDraft("aid-1", task.id(), AiArtifactType.CODE, "target", + mapper.createObjectNode().put("ok", true), 2L, + List.of(new AiGateResult("required", true, List.of())), Map.of()); + AiChangeSet changeSet = new AiChangeSet("aics-1", task.id(), "READY_FOR_REVIEW", 3L, + List.of(draft.id()), Map.of("draftCount", 1)); + AiRunRecord run = new AiRunRecord("air-1", task.id(), changeSet.id(), "SMOKE", "PASSED", 4L, + mapper.createObjectNode().put("status", "PASSED")); + AiAuditEntry audit = new AiAuditEntry("aia-1", task.id(), "draft.saved", "agent", 4L, Map.of()); + + store.saveTask(task); + store.saveDraft(draft); + store.saveChangeSet(changeSet); + store.saveRun(run); + store.saveAudit(audit); + + assertTrue(store.findTask(task.id()).isPresent()); + assertEquals(1, store.listDrafts(task.id()).size()); + assertEquals(1, store.listChangeSets(task.id()).size()); + assertEquals(1, store.listRuns(task.id()).size()); + assertEquals(1, store.listAudit(task.id()).size()); + assertEquals(List.of(), store.listDrafts("other-task")); + assertEquals(List.of(), store.listRuns("other-task")); + } +} diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/store/JdbcAiAgentStoreTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/store/JdbcAiAgentStoreTest.java new file mode 100644 index 0000000..5947ffa --- /dev/null +++ b/platform-ai/src/test/java/com/eip4/platform/ai/store/JdbcAiAgentStoreTest.java @@ -0,0 +1,121 @@ +package com.eip4.platform.ai.store; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.sql.ResultSet; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.RowMapper; + +import com.eip4.platform.ai.model.AiRunRecord; +import com.eip4.platform.ai.model.AiTask; +import com.fasterxml.jackson.databind.ObjectMapper; + +class JdbcAiAgentStoreTest { + + @Test + @DisplayName("JDBC 存储写入 task 使用 sys_ai_task 和 jsonb plan") + void savesTask() { + JdbcTemplate jdbc = mock(JdbcTemplate.class); + JdbcAiAgentStore store = new JdbcAiAgentStore(jdbc, new ObjectMapper()); + + store.saveTask(new AiTask("ait-1", "目标", "DRAFTING", 1L, 2L, List.of("采集上下文"))); + + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(jdbc).update(sql.capture(), eq("ait-1"), eq("目标"), eq("DRAFTING"), + eq("[\"采集上下文\"]"), eq(1L), eq(2L)); + org.junit.jupiter.api.Assertions.assertTrue(sql.getValue().contains("sys_ai_task")); + org.junit.jupiter.api.Assertions.assertTrue(sql.getValue().contains("?::jsonb")); + } + + @Test + @DisplayName("JDBC 存储可从 jsonb 行还原 task") + @SuppressWarnings("unchecked") + void mapsTaskRow() throws Exception { + JdbcTemplate jdbc = mock(JdbcTemplate.class); + JdbcAiAgentStore store = new JdbcAiAgentStore(jdbc, new ObjectMapper()); + when(jdbc.query(any(String.class), any(RowMapper.class), eq("ait-1"))).thenAnswer(invocation -> { + RowMapper mapper = invocation.getArgument(1); + ResultSet rs = mock(ResultSet.class); + when(rs.getString("task_id")).thenReturn("ait-1"); + when(rs.getString("objective")).thenReturn("目标"); + when(rs.getString("status")).thenReturn("DRAFTING"); + when(rs.getLong("created_at")).thenReturn(1L); + when(rs.getLong("updated_at")).thenReturn(2L); + when(rs.getObject("plan_json")).thenReturn("[\"采集上下文\"]"); + return List.of(mapper.mapRow(rs, 0)); + }); + + AiTask task = store.findTask("ait-1").orElseThrow(); + + assertEquals("目标", task.objective()); + assertEquals(List.of("采集上下文"), task.plan()); + } + + @Test + @DisplayName("JDBC 存储写入 audit 使用 sys_ai_audit_log") + void savesAudit() { + JdbcTemplate jdbc = mock(JdbcTemplate.class); + JdbcAiAgentStore store = new JdbcAiAgentStore(jdbc, new ObjectMapper()); + + store.saveAudit(new com.eip4.platform.ai.model.AiAuditEntry( + "aia-1", "ait-1", "task.created", "agent", 3L, Map.of("k", "v"))); + + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(jdbc).update(sql.capture(), eq("aia-1"), eq("ait-1"), eq("task.created"), + eq("agent"), eq("{\"k\":\"v\"}"), eq(3L)); + org.junit.jupiter.api.Assertions.assertTrue(sql.getValue().contains("sys_ai_audit_log")); + } + + @Test + @DisplayName("JDBC 存储写入 run 使用 sys_ai_run 和 jsonb payload") + void savesRun() { + JdbcTemplate jdbc = mock(JdbcTemplate.class); + ObjectMapper mapper = new ObjectMapper(); + JdbcAiAgentStore store = new JdbcAiAgentStore(jdbc, mapper); + + store.saveRun(new AiRunRecord("air-1", "ait-1", "aics-1", "SMOKE", "PASSED", 5L, + mapper.createObjectNode().put("status", "PASSED"))); + + ArgumentCaptor sql = ArgumentCaptor.forClass(String.class); + verify(jdbc).update(sql.capture(), eq("air-1"), eq("ait-1"), eq("aics-1"), eq("SMOKE"), + eq("PASSED"), eq("{\"status\":\"PASSED\"}"), eq(5L)); + org.junit.jupiter.api.Assertions.assertTrue(sql.getValue().contains("sys_ai_run")); + org.junit.jupiter.api.Assertions.assertTrue(sql.getValue().contains("?::jsonb")); + } + + @Test + @DisplayName("JDBC 存储可从 jsonb 行还原 run") + @SuppressWarnings("unchecked") + void mapsRunRow() throws Exception { + JdbcTemplate jdbc = mock(JdbcTemplate.class); + JdbcAiAgentStore store = new JdbcAiAgentStore(jdbc, new ObjectMapper()); + when(jdbc.query(any(String.class), any(RowMapper.class), eq("ait-1"))).thenAnswer(invocation -> { + RowMapper mapper = invocation.getArgument(1); + ResultSet rs = mock(ResultSet.class); + when(rs.getString("run_id")).thenReturn("air-1"); + when(rs.getString("task_id")).thenReturn("ait-1"); + when(rs.getString("change_set_id")).thenReturn("aics-1"); + when(rs.getString("run_type")).thenReturn("LOCAL_APPLY"); + when(rs.getString("status")).thenReturn("PASSED"); + when(rs.getLong("created_at")).thenReturn(5L); + when(rs.getObject("payload_json")).thenReturn("{\"status\":\"PASSED\"}"); + return List.of(mapper.mapRow(rs, 0)); + }); + + AiRunRecord run = store.listRuns("ait-1").get(0); + + assertEquals("LOCAL_APPLY", run.runType()); + assertEquals("PASSED", run.payload().path("status").asText()); + } +} diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/web/AiAgentApiPipelineTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/web/AiAgentApiPipelineTest.java new file mode 100644 index 0000000..849eb7a --- /dev/null +++ b/platform-ai/src/test/java/com/eip4/platform/ai/web/AiAgentApiPipelineTest.java @@ -0,0 +1,120 @@ +package com.eip4.platform.ai.web; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.MvcResult; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import com.eip4.platform.ai.model.AiApplyStepResult; +import com.eip4.platform.ai.model.AiArtifactType; +import com.eip4.platform.ai.model.AiDraft; +import com.eip4.platform.ai.service.AiAgentService; +import com.eip4.platform.ai.service.AiFeatureDraftGenerator; +import com.eip4.platform.ai.service.AiHttpResponse; +import com.eip4.platform.ai.service.AiLocalReleaseExecutor; +import com.eip4.platform.ai.service.AiSmokeRunner; +import com.eip4.platform.ai.service.DeterministicAiAgentRepairExecutor; +import com.eip4.platform.ai.store.InMemoryAiAgentStore; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +class AiAgentApiPipelineTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private AiAgentService service; + private MockMvc mvc; + + @BeforeEach + void setUp() { + AtomicInteger smokeCalls = new AtomicInteger(); + AiSmokeRunner flakySmokeRunner = new AiSmokeRunner((method, uri, requestBody, timeout) -> { + if (smokeCalls.incrementAndGet() <= 4) { + return new AiHttpResponse(503, "temporary unavailable"); + } + return new AiHttpResponse(200, "{\"status\":0}"); + }); + service = new AiAgentService(new InMemoryAiAgentStore(), new AiFeatureDraftGenerator(MAPPER), + flakySmokeRunner, new NoopLocalReleaseExecutor(), + new DeterministicAiAgentRepairExecutor(MAPPER), MAPPER); + mvc = MockMvcBuilders.standaloneSetup(new AiAgentController(service)).build(); + } + + @Test + void autoDevelopEndpointRunsFullPipelineWithAutomaticRepair() throws Exception { + MvcResult result = mvc.perform(post("/api/ai/features/auto-develop") + .contentType("application/json") + .content(""" + { + "baseUrl": "http://localhost:8084", + "generateDeploymentPackage": true, + "feature": { + "objective": "新增客户等级维护功能", + "featureName": "客户等级维护", + "tableName": "EIP4AI_CUSTOMER_LEVEL", + "entityName": "客户等级", + "templateId": "eip4ai-customer-level", + "menuName": "客户等级维护", + "fields": [ + {"column": "NAME", "label": "名称", "type": "string", "length": 100, "required": true}, + {"column": "CODE", "label": "编码", "type": "string", "length": 64, "required": true}, + {"column": "ENABLED", "label": "启用", "type": "boolean", "required": false} + ] + } + } + """)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.status").value("READY_FOR_HUMAN_REVIEW")) + .andExpect(jsonPath("$.originalChangeSetId").isNotEmpty()) + .andExpect(jsonPath("$.changeSetId").isNotEmpty()) + .andExpect(jsonPath("$.development.drafts.length()").value(5)) + .andExpect(jsonPath("$.applyRun.status").value("PASSED")) + .andExpect(jsonPath("$.repairExecutions.length()").value(1)) + .andExpect(jsonPath("$.repairExecutions[0].status").value("REPAIRED")) + .andExpect(jsonPath("$.deploymentPackage.status").value("READY_FOR_HUMAN_REVIEW")) + .andExpect(jsonPath("$.deploymentPackage.requiresHumanApproval").value(true)) + .andReturn(); + + JsonNode response = MAPPER.readTree(result.getResponse().getContentAsString()); + String taskId = response.path("taskId").asText(); + assertTrue(service.listRuns(taskId).stream().anyMatch(run -> "AUTO_DEVELOP".equals(run.runType()))); + assertTrue(service.listRuns(taskId).stream().anyMatch(run -> "REPAIR_EXECUTION".equals(run.runType()))); + assertTrue(service.listAudit(taskId).stream().anyMatch(audit -> "auto-development.completed".equals(audit.action()))); + } + + private static class NoopLocalReleaseExecutor extends AiLocalReleaseExecutor { + + NoopLocalReleaseExecutor() { + super(org.mockito.Mockito.mock(org.springframework.jdbc.core.JdbcTemplate.class), + (method, uri, requestBody, timeout) -> new AiHttpResponse(200, "{\"status\":0}"), MAPPER); + } + + @Override + public java.util.List apply(String baseUrl, java.util.List drafts) { + return drafts.stream() + .filter(draft -> draft.artifactType() != AiArtifactType.TEST) + .map(draft -> new AiApplyStepResult("apply-" + draft.id(), draft.artifactType(), + draft.targetId(), "APPLIED", "ok", details(draft))) + .toList(); + } + + private static Map details(AiDraft draft) { + return switch (draft.artifactType()) { + case ENTITY -> Map.of("entityId", "e-test-entity-id", "tableName", draft.targetId()); + case SERVICEFLOW -> Map.of("flowCount", 5, "entityId", "e-test-entity-id"); + case PAGE_SCHEMA -> Map.of("templateId", draft.targetId(), "etag", "test-etag"); + case MENU -> Map.of("menuId", "m-test-menu-id"); + case CODE, TEST -> Map.of(); + }; + } + } +} diff --git a/platform-ai/src/test/java/com/eip4/platform/ai/web/AiAgentControllerTest.java b/platform-ai/src/test/java/com/eip4/platform/ai/web/AiAgentControllerTest.java new file mode 100644 index 0000000..70bfaad --- /dev/null +++ b/platform-ai/src/test/java/com/eip4/platform/ai/web/AiAgentControllerTest.java @@ -0,0 +1,222 @@ +package com.eip4.platform.ai.web; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; + +import com.eip4.platform.ai.model.AiApplyRun; +import com.eip4.platform.ai.model.AiApplyStepResult; +import com.eip4.platform.ai.model.AiArtifactType; +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.AiFeatureField; +import com.eip4.platform.ai.model.AiFeatureRequest; +import com.eip4.platform.ai.model.AiGateResult; +import com.eip4.platform.ai.model.AiReleasePlan; +import com.eip4.platform.ai.model.AiReleaseStep; +import com.eip4.platform.ai.model.AiRepairAction; +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.AiSmokeResult; +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 com.fasterxml.jackson.databind.ObjectMapper; + +@ExtendWith(MockitoExtension.class) +class AiAgentControllerTest { + + @Mock + AiAgentService service; + + MockMvc mvc; + + ObjectMapper objectMapper; + + @BeforeEach + void setUp() { + objectMapper = new ObjectMapper(); + mvc = MockMvcBuilders.standaloneSetup(new AiAgentController(service)).build(); + } + + @Test + void 一键自动开发转调service并返回执行证据() throws Exception { + AiAutoDevelopmentRun run = autoDevelopmentRun(); + when(service.autoDevelopFeature(any(AiAutoDevelopmentRequest.class))).thenReturn(run); + + AiAutoDevelopmentRequest request = new AiAutoDevelopmentRequest( + new AiFeatureRequest("开发客户管理", "客户管理", "SYS_CUSTOMER", + "Customer", "list-form", "客户管理", + List.of(new AiFeatureField("NAME", "客户名称", "text", 64, true))), + "http://127.0.0.1:18080", + true, + 2); + + mvc.perform(post("/api/ai/features/auto-develop") + .contentType("application/json") + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.taskId").value("ait-1")) + .andExpect(jsonPath("$.changeSetId").value("aics-1")) + .andExpect(jsonPath("$.originalChangeSetId").value("aics-0")) + .andExpect(jsonPath("$.status").value("READY_FOR_DEPLOYMENT_REVIEW")) + .andExpect(jsonPath("$.applyRun.smokeRun.results[0].passed").value(true)) + .andExpect(jsonPath("$.repairExecutions").isArray()) + .andExpect(jsonPath("$.deploymentPackage.requiresHumanApproval").value(true)); + + ArgumentCaptor captor = ArgumentCaptor.forClass(AiAutoDevelopmentRequest.class); + verify(service).autoDevelopFeature(captor.capture()); + assertEquals("客户管理", captor.getValue().feature().featureName()); + assertEquals("http://127.0.0.1:18080", captor.getValue().baseUrl()); + assertTrue(captor.getValue().shouldGenerateDeploymentPackage()); + assertEquals(2, captor.getValue().repairAttemptLimit()); + } + + @Test + void 修复计划接口返回自动化动作() throws Exception { + AiRepairPlan plan = repairPlan(); + when(service.createRepairPlan("ait-1", "aics-1")).thenReturn(plan); + + mvc.perform(post("/api/ai/tasks/ait-1/change-sets/aics-1/repair-plan")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.taskId").value("ait-1")) + .andExpect(jsonPath("$.actions[0].artifactType").value("TEST")) + .andExpect(jsonPath("$.actions[0].automated").value(true)); + + verify(service).createRepairPlan("ait-1", "aics-1"); + } + + @Test + void 执行修复接口透传baseUrl并返回重跑结果() throws Exception { + AiRepairExecution execution = repairExecution(); + when(service.executeRepairPlan(eq("ait-1"), eq("aics-1"), eq("http://localhost:18080"))) + .thenReturn(execution); + + AiRepairExecutionRequest request = new AiRepairExecutionRequest("http://localhost:18080"); + + mvc.perform(post("/api/ai/tasks/ait-1/change-sets/aics-1/repair-execution") + .contentType("application/json") + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.status").value("PASSED")) + .andExpect(jsonPath("$.generatedDrafts[0].artifactType").value("PAGE_SCHEMA")) + .andExpect(jsonPath("$.retryApplyRun.smokeRun.status").value("PASSED")); + + verify(service).executeRepairPlan("ait-1", "aics-1", "http://localhost:18080"); + } + + @Test + void schema校验接口转发JsonNode() throws Exception { + when(service.validateSchema(any(JsonNode.class))).thenReturn(Map.of( + "valid", true, + "warnings", List.of())); + + mvc.perform(post("/api/ai/tools/validate-schema") + .contentType("application/json") + .content("{\"type\":\"page\",\"title\":\"客户\",\"body\":[]}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.valid").value(true)); + + ArgumentCaptor captor = ArgumentCaptor.forClass(JsonNode.class); + verify(service).validateSchema(captor.capture()); + assertEquals("page", captor.getValue().path("type").asText()); + } + + private AiAutoDevelopmentRun autoDevelopmentRun() { + AiFeatureDevelopment development = new AiFeatureDevelopment(task(), List.of(draft()), changeSet()); + AiReleasePlan releasePlan = new AiReleasePlan("ait-1", "aics-1", "READY", + true, + Map.of("policy", "local-only"), + List.of(new AiReleaseStep("step-1", AiArtifactType.PAGE_SCHEMA, "页面", + "LOCAL_APPLY", "customer-page", "UPSERT", Map.of())), + List.of("按变更包反向回滚")); + AiApplyRun applyRun = applyRun(); + AiDeploymentPackage deploymentPackage = deploymentPackage(); + return new AiAutoDevelopmentRun("ait-1", "aics-1", "aics-0", "READY_FOR_DEPLOYMENT_REVIEW", + 100L, 200L, development, releasePlan, applyRun, deploymentPackage, + List.of(), + List.of("本地门禁通过,等待人工部署")); + } + + private AiRepairExecution repairExecution() { + return new AiRepairExecution("ait-1", "aics-1", "PASSED", + 100L, 200L, repairPlan(), List.of(draft()), changeSet(), applyRun(), + deploymentPackage(), List.of("已生成修复草稿并通过本地 smoke")); + } + + private AiRepairPlan repairPlan() { + return new AiRepairPlan("ait-1", "aics-1", "run-1", "READY", + 100L, + List.of(new AiRepairAction("repair-1", "SMOKE", "PATCH_DRAFT", + "TEST", "customer-smoke", true, "同步测试契约", + Map.of("expectedStatus", 200))), + List.of("发现测试契约不匹配")); + } + + private AiTask task() { + return new AiTask("ait-1", "开发客户管理", "READY_FOR_REVIEW", + 1L, 2L, List.of("生成草稿", "本地验证")); + } + + private AiDraft draft() { + return new AiDraft("aid-1", "ait-1", AiArtifactType.PAGE_SCHEMA, "customer-page", + objectMapper.createObjectNode() + .put("type", "page") + .put("title", "客户管理") + .set("body", objectMapper.createArrayNode()), + 3L, + List.of(new AiGateResult("schema", true, List.of())), + Map.of("source", "test")); + } + + private AiChangeSet changeSet() { + return new AiChangeSet("aics-1", "ait-1", "READY_FOR_REVIEW", + 4L, List.of("aid-1"), Map.of("draftCount", 1)); + } + + private AiApplyRun applyRun() { + AiSmokeRun smokeRun = new AiSmokeRun("ait-1", "aics-1", "http://localhost:18080", + "PASSED", 10L, 20L, + List.of(new AiSmokeResult("打开页面", "GET", "/customer", + 200, 200, true, 12L, null, "ok"))); + return new AiApplyRun("ait-1", "aics-1", "http://localhost:18080", + "PASSED", 5L, 25L, + List.of(new AiApplyStepResult("step-1", AiArtifactType.PAGE_SCHEMA, + "customer-page", "APPLIED", "ok", Map.of())), + smokeRun); + } + + private AiDeploymentPackage deploymentPackage() { + return new AiDeploymentPackage("ait-1", "aics-1", "READY_FOR_HUMAN_APPROVAL", + true, 30L, Map.of("changeSetId", "aics-1"), + List.of("insert into sys_page_schema ..."), + List.of("delete from sys_page_schema where id = 'customer-page'"), + List.of(), + List.of()); + } +} diff --git a/platform-app/src/main/resources/application-dev.yml b/platform-app/src/main/resources/application-dev.yml index baed538..8b3c4ab 100644 --- a/platform-app/src/main/resources/application-dev.yml +++ b/platform-app/src/main/resources/application-dev.yml @@ -22,6 +22,10 @@ spring: hikari: maximum-pool-size: 10 read-only: false + sql: + init: + mode: always + schema-locations: classpath:bootstrap/bootstrap-ai-agent.sql eip4: auth: @@ -29,6 +33,14 @@ eip4: secret: ${EIP4_AUTH_JWT_SECRET:dev-only-eip4-jwt-secret-change-me-in-production-0123456789} expire-seconds: 28800 # 8h issuer: eip4-platform + ai: + store: jdbc + llm: + repair: + enabled: ${EIP4_AI_LLM_REPAIR_ENABLED:false} + endpoint: ${EIP4_AI_LLM_REPAIR_ENDPOINT:} + api-key: ${EIP4_AI_LLM_REPAIR_API_KEY:} + model: ${EIP4_AI_LLM_REPAIR_MODEL:} file: root: ${EIP4_FILE_ROOT:./data/files} script: diff --git a/platform-app/src/main/resources/application-local.yml b/platform-app/src/main/resources/application-local.yml index 3f1f0df..8b3fe79 100644 --- a/platform-app/src/main/resources/application-local.yml +++ b/platform-app/src/main/resources/application-local.yml @@ -13,6 +13,10 @@ spring: hikari: maximum-pool-size: 5 read-only: false + sql: + init: + mode: always + schema-locations: classpath:bootstrap/bootstrap-ai-agent.sql server: port: 8084 @@ -25,6 +29,14 @@ eip4: secret: ${EIP4_AUTH_JWT_SECRET:dev-only-eip4-jwt-secret-change-me-in-production-0123456789} expire-seconds: 28800 # 8h issuer: eip4-platform + ai: + store: jdbc + llm: + repair: + enabled: ${EIP4_AI_LLM_REPAIR_ENABLED:false} + endpoint: ${EIP4_AI_LLM_REPAIR_ENDPOINT:} + api-key: ${EIP4_AI_LLM_REPAIR_API_KEY:} + model: ${EIP4_AI_LLM_REPAIR_MODEL:} logging: level: diff --git a/platform-app/src/main/resources/bootstrap/bootstrap-ai-agent.sql b/platform-app/src/main/resources/bootstrap/bootstrap-ai-agent.sql new file mode 100644 index 0000000..8cfcf1a --- /dev/null +++ b/platform-app/src/main/resources/bootstrap/bootstrap-ai-agent.sql @@ -0,0 +1,68 @@ +-- ============================================================================ +-- eip4-platform P5 AI Agent 运行态自举 schema —— bootstrap-ai-agent.sql +-- ---------------------------------------------------------------------------- +-- 用途:platform-app 启动器本地/dev profile 直接加载的 AI Agent 表自举脚本。 +-- +-- 纪律:可重复执行(CREATE TABLE IF NOT EXISTS / CREATE INDEX IF NOT EXISTS); +-- 只保存 AI 运行态和草稿,不直接写 SYS_PAGE_SCHEMA / SYS_ENTITY / 服务流等生产元数据。 +-- platform-ai 模块内保留同名副本,生产脚本副本见 docs/sql/SYS_AI_AGENT.sql。 +-- ============================================================================ + +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); diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/flow/FlowNameResolver.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/flow/FlowNameResolver.java index 5959c98556047dacbc27a2a112695c6ec0e54e16..e05d86cbe68ff1f20be28225b2415b36be4e0b92 100644 GIT binary patch delta 26 icmbQ2(3P-Zo80EzaxyHN?o&I&jH delta 50 rcmeB5n3u3&n;dIuW`VKZ=52B^EKuepB~La8bF#FiB~&m(a~m4~!j}-1 diff --git a/platform-metadata/src/main/java/com/eip4/platform/metadata/web/MetaController.java b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/MetaController.java index cad9bbc..aeb27c7 100644 --- a/platform-metadata/src/main/java/com/eip4/platform/metadata/web/MetaController.java +++ b/platform-metadata/src/main/java/com/eip4/platform/metadata/web/MetaController.java @@ -92,7 +92,7 @@ public class MetaController { // 属性模板:取 SYS_USERGROUP.NAME 属性行做默认值载体 Map attrTpl = loadAttrTemplate(idOf(tplEnt)); - List> created = new ArrayList<>(); + List created = new ArrayList<>(); // 标准列 created.add(saveAttr(attrTpl, entityId, table + "_ID", "主键", "CHAR", 36, true, true, ctx)); created.add(saveAttr(attrTpl, entityId, "VERSION", "版本", "INTEGER", null, true, false, ctx)); @@ -125,9 +125,9 @@ public class MetaController { } } - // 动态建表 - Entity newEnt = (Entity) dataDicService.getSYSEntity(entityId); - String ddl = newEnt.createTableSql(); + // 动态建表前先清刚保存实体/属性带来的 POInfo 缓存,保证后续读写立即拿到新字段。 + cacheInvalidator.evictByEntityId(entityId, table); + String ddl = createTableDdl(table, created); dataDicService.executeCreateSql(ddl); // P1-5:建表后按元数据补索引(外键 uuid 列 + UPDATETIME),引擎只建表不建索引 @@ -224,9 +224,9 @@ public class MetaController { return resp; } - private Map saveAttr(Map tpl, String entityId, String col, - String display, String ref, Integer len, - boolean mandatory, boolean isKey, Properties ctx) { + private GeneralPOJO saveAttr(Map tpl, String entityId, String col, + String display, String ref, Integer len, + boolean mandatory, boolean isKey, Properties ctx) { Map m = new HashMap<>(tpl); m.remove("SYS_ENTITYATTRIBUTE_ID"); m.put("ENTITYID", entityId); @@ -243,8 +243,100 @@ public class MetaController { } else { m.remove("FIELDLENGTH"); } - pojoCRUDService.save(m, "SYS_ENTITYATTRIBUTE", ctx); - return Map.of("column", col, "type", ref); + return pojoCRUDService.save(m, "SYS_ENTITYATTRIBUTE", ctx); + } + + static String createTableDdl(String table, List attrs) { + if (attrs == null || attrs.isEmpty()) { + throw new IllegalStateException("实体属性为空,无法建表: " + table); + } + StringBuilder sql = new StringBuilder(); + StringBuilder unique = new StringBuilder(); + StringBuilder combUnique = new StringBuilder(); + sql.append("CREATE TABLE ").append(table).append("\n"); + sql.append("(\n"); + for (GeneralPOJO attr : attrs) { + appendColumnDdl(table, attr, sql, unique, combUnique); + } + sql.append(unique); + if (!combUnique.isEmpty()) { + sql.append(combUnique).append("), \n"); + } + sql.append("primary key (").append(table).append("_ID)\n"); + sql.append("); \n"); + return sql.toString(); + } + + private static void appendColumnDdl(String table, GeneralPOJO attr, StringBuilder sql, + StringBuilder unique, StringBuilder combUnique) { + if (attr.get_ValueAsBoolean("ISREADONLY")) { + return; + } + String ref = value(attr, "REFERENCEID"); + if ("LIST".equals(ref) || "BLOB".equals(ref) || "STATUS".equals(ref)) { + return; + } + String col = value(attr, "COLUMNNAME"); + if (col == null || !col.matches("[A-Z][A-Z0-9_]{1,60}")) { + throw new IllegalStateException("实体字段名不合法: " + col); + } + if ("CREATEBY".equals(col) || "UPDATEBY".equals(col) || "ORGID".equals(col) || "DEPARTID".equals(col)) { + sql.append(col).append(" character(36) "); + } else if ("NVARCHAR".equals(ref) || "CODE".equals(ref)) { + int length = positiveInt(attr.get_Value("FIELDLENGTH"), 100); + sql.append(col).append(" character varying(").append(length).append(") "); + } else if ("INTEGER".equals(ref) || "BOOLEAN".equals(ref) || "ENUMERATE".equals(ref)) { + sql.append(col).append(" integer "); + } else if ("DECIMAL".equals(ref) || "MONEY".equals(ref)) { + sql.append(col).append(" numeric(18,6) "); + } else if ("DATE".equals(ref) || "TIME".equals(ref)) { + sql.append(col).append(" bigint "); + } else if ("CHAR".equals(ref)) { + sql.append(col).append(" character(36) "); + } else { + sql.append(col).append(" character(36) REFERENCES ").append(table); + } + if (attr.get_ValueAsBoolean("ISMANDATORY")) { + sql.append(" NOT NULL "); + } + String defValue = value(attr, "DEFAULTVALUE"); + if (defValue != null && !defValue.isBlank() + && ("INTEGER".equals(ref) || "BOOLEAN".equals(ref) || "DECIMAL".equals(ref) || "MONEY".equals(ref))) { + sql.append(" DEFAULT ").append(defValue); + } + sql.append(", \n"); + if (attr.get_ValueAsBoolean("ISIDENTIFIER")) { + unique.append(" unique (").append(col).append("), \n"); + } else if (attr.get_ValueAsBoolean("ISCOMBIDENTIFIER")) { + if (combUnique.isEmpty()) { + combUnique.append(" unique ("); + } else { + combUnique.append(","); + } + combUnique.append(col); + } + } + + private static int positiveInt(Object value, int defaultValue) { + if (value instanceof Number n && n.intValue() > 0) { + return n.intValue(); + } + if (value != null) { + try { + int parsed = Integer.parseInt(value.toString()); + if (parsed > 0) { + return parsed; + } + } catch (NumberFormatException ignore) { + return defaultValue; + } + } + return defaultValue; + } + + private static String value(GeneralPOJO po, String column) { + Object value = po.get_Value(column); + return value == null ? null : value.toString(); } private Map loadAttrTemplate(String tplEntityId) { diff --git a/platform-metadata/src/test/java/com/eip4/platform/metadata/web/MetaControllerDdlTest.java b/platform-metadata/src/test/java/com/eip4/platform/metadata/web/MetaControllerDdlTest.java new file mode 100644 index 0000000..12ceefc --- /dev/null +++ b/platform-metadata/src/test/java/com/eip4/platform/metadata/web/MetaControllerDdlTest.java @@ -0,0 +1,40 @@ +package com.eip4.platform.metadata.web; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.List; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import com.dsasp.server.common.dataDic.bean.GeneralPOJO; + +class MetaControllerDdlTest { + + @Test + @DisplayName("运行态实体 DDL 按旧引擎类型规则生成主键、字符串和布尔列") + void createTableDdlUsesSavedAttributes() { + String ddl = MetaController.createTableDdl("EIP4AI_RT_DEMO", List.of( + attr("EIP4AI_RT_DEMO_ID", "CHAR", null, true), + attr("NAME", "NVARCHAR", 100, true), + attr("ENABLED", "BOOLEAN", null, false) + )); + + assertTrue(ddl.contains("CREATE TABLE EIP4AI_RT_DEMO")); + assertTrue(ddl.contains("EIP4AI_RT_DEMO_ID character(36) NOT NULL")); + assertTrue(ddl.contains("NAME character varying(100) NOT NULL")); + assertTrue(ddl.contains("ENABLED integer")); + assertTrue(ddl.contains("primary key (EIP4AI_RT_DEMO_ID)")); + } + + private static GeneralPOJO attr(String column, String referenceId, Integer length, boolean mandatory) { + GeneralPOJO po = mock(GeneralPOJO.class); + when(po.get_Value("COLUMNNAME")).thenReturn(column); + when(po.get_Value("REFERENCEID")).thenReturn(referenceId); + when(po.get_Value("FIELDLENGTH")).thenReturn(length); + when(po.get_ValueAsBoolean("ISMANDATORY")).thenReturn(mandatory); + return po; + } +}