merge ai agent module
This commit is contained in:
27
README.md
27
README.md
@@ -12,7 +12,8 @@ EIP4 平台正式工程(路线 A'):双层制模块化单体——**保真层供
|
|||||||
| platform-auth | 数据权限真实现(C2 已替换桩)+ P2 组织/权限 | |
|
| platform-auth | 数据权限真实现(C2 已替换桩)+ P2 组织/权限 | |
|
||||||
| platform-converter | 模板转换器(P4) | 可独立 CLI 跑批 |
|
| platform-converter | 模板转换器(P4) | 可独立 CLI 跑批 |
|
||||||
| platform-flow-gateway | P3 占位:Flowable 网关 | |
|
| platform-flow-gateway | P3 占位:Flowable 网关 | |
|
||||||
| platform-ai | P5 占位:MCP Server | |
|
| platform-ai | P5 AI Agent 开发底座:草稿/变更包/本地门禁/自动修复/人工部署包 | Agent 不直连线上执行生产变更 |
|
||||||
|
| platform-cli | EIP4 Agent 受控命令入口:环境探测、AI 自动开发、后续发布编排 | Agent 优先通过 CLI/API 操作 |
|
||||||
| platform-parity | C1 对拍框架:录制/重放/RowDiff/自对拍 CLI | P1 一级交付物 |
|
| platform-parity | C1 对拍框架:录制/重放/RowDiff/自对拍 CLI | P1 一级交付物 |
|
||||||
| platform-app | Boot 启动器,组装全部模块 | ArchUnit 规则在此模块测试里 |
|
| platform-app | Boot 启动器,组装全部模块 | ArchUnit 规则在此模块测试里 |
|
||||||
|
|
||||||
@@ -75,6 +76,30 @@ java -cp "$CP" com.eip4.platform.parity.selfcheck.ParityCli --privilege # C
|
|||||||
# 指向 eip4dev 自对拍:
|
# 指向 eip4dev 自对拍:
|
||||||
mvn -pl platform-parity exec:java -Dexec.mainClass="com.eip4.platform.parity.selfcheck.ParityCli" \
|
mvn -pl platform-parity exec:java -Dexec.mainClass="com.eip4.platform.parity.selfcheck.ParityCli" \
|
||||||
"-Dexec.args=--discover --jdbc=jdbc:postgresql://localhost:5433/eip4dev?currentSchema=eip3 --engine=http://localhost:8093 --out=parity-reports/eip4dev"
|
"-Dexec.args=--discover --jdbc=jdbc:postgresql://localhost:5433/eip4dev?currentSchema=eip3 --engine=http://localhost:8093 --out=parity-reports/eip4dev"
|
||||||
|
|
||||||
|
# EIP4 Agent CLI
|
||||||
|
mvn -pl platform-cli package
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar env add --name local --base-url http://localhost:8084 --use
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar env status --base-url http://localhost:8084
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai feature-package --task-id ait-xxx --change-set-id aics-xxx --output target/ai-runs/package.json
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar release verify --package-file target/ai-runs/package.json
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar release export --package-file target/ai-runs/package.json --output target/ai-runs/package.eip4pkg.json
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar release import-preview --package-file target/ai-runs/package.eip4pkg.json
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar release diff --left target/ai-runs/package-old.json --right target/ai-runs/package.json
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar release rollback-plan --package-file target/ai-runs/package.eip4pkg.json --output target/ai-runs/rollback-plan.json
|
||||||
|
|
||||||
|
# Typed page schema
|
||||||
|
curl http://localhost:8084/api/page/schema/components
|
||||||
|
curl -X POST http://localhost:8084/api/page/schema/validate \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
--data-binary @target/ai-runs/page-schema.json
|
||||||
|
|
||||||
|
# AI tools / employees / ACL
|
||||||
|
curl http://localhost:8084/api/ai/tools
|
||||||
|
curl http://localhost:8084/api/ai/employees
|
||||||
|
curl -X POST http://localhost:8084/api/ai/tools/access-check \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"employeeId":"agent-developer","toolName":"local.apply","grantedScopes":["ai:local:apply"],"targetEnv":"local","productionWrite":false}'
|
||||||
```
|
```
|
||||||
|
|
||||||
## tools/
|
## tools/
|
||||||
|
|||||||
180
docs/AI_AGENT_AUTO_DEVELOPMENT.md
Normal file
180
docs/AI_AGENT_AUTO_DEVELOPMENT.md
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
# 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
|
||||||
|
```
|
||||||
|
|
||||||
|
## 请求示例
|
||||||
|
|
||||||
|
推荐优先使用 `platform-cli`,让 Agent 通过稳定命令入口操作自动开发链路:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mvn -pl platform-cli package
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai auto-develop \
|
||||||
|
--base-url http://localhost:8093 \
|
||||||
|
--objective "新增客户等级维护功能" \
|
||||||
|
--feature-name "客户等级维护" \
|
||||||
|
--table-name EIP4AI_CUSTOMER_LEVEL \
|
||||||
|
--entity-name "客户等级" \
|
||||||
|
--template-id eip4ai-customer-level \
|
||||||
|
--menu-name "客户等级维护" \
|
||||||
|
--field NAME:名称:string:100:true \
|
||||||
|
--field CODE:编码:string:64:true \
|
||||||
|
--field ENABLED:启用:boolean::false \
|
||||||
|
--page-recipe maintenance-crud-v1 \
|
||||||
|
--max-repair-attempts 2 \
|
||||||
|
--output target/ai-runs/customer-level.json
|
||||||
|
```
|
||||||
|
|
||||||
|
树形维护页使用 `tree-crud-v1`。如果字段列表没有显式提供 `PARENTID`,生成器会自动补一个父级字段,
|
||||||
|
页面使用 `/api/entity/{table}/tree?parentKey=PARENTID&idKey={table}_ID&perPage=2000`
|
||||||
|
作为树数据接口,并把 `PARENTID` 从树列表列中隐藏:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai auto-develop \
|
||||||
|
--base-url http://localhost:8093 \
|
||||||
|
--objective "新增组织分类树形维护功能" \
|
||||||
|
--feature-name "组织分类维护" \
|
||||||
|
--table-name EIP4AI_ORG_CATEGORY \
|
||||||
|
--entity-name "组织分类" \
|
||||||
|
--template-id eip4ai-org-category \
|
||||||
|
--menu-name "组织分类维护" \
|
||||||
|
--field NAME:名称:string:100:true \
|
||||||
|
--field CODE:编码:string:64:true \
|
||||||
|
--page-recipe tree-crud-v1 \
|
||||||
|
--max-repair-attempts 2 \
|
||||||
|
--output target/ai-runs/org-category-tree.json
|
||||||
|
```
|
||||||
|
|
||||||
|
本地门禁通过后,可以把最终变更包封装成功能包快照,并保存一个里程碑 revision:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai feature-package \
|
||||||
|
--base-url http://localhost:8093 \
|
||||||
|
--task-id ait-xxx \
|
||||||
|
--change-set-id aics-xxx \
|
||||||
|
--output target/ai-runs/customer-level-package.json
|
||||||
|
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai revision \
|
||||||
|
--base-url http://localhost:8093 \
|
||||||
|
--task-id ait-xxx \
|
||||||
|
--package-id aipkg-xxx \
|
||||||
|
--note "本地门禁通过,待人工部署" \
|
||||||
|
--output target/ai-runs/customer-level-revision.json
|
||||||
|
```
|
||||||
|
|
||||||
|
底层 REST API 仍可直接调用:
|
||||||
|
|
||||||
|
```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": "客户等级维护",
|
||||||
|
"pageRecipe": "maintenance-crud-v1",
|
||||||
|
"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. 读取 `/api/ai/page-recipes` 中的 EIP4 页面 recipe,确认当前页面类型的 UI/UE 约束。
|
||||||
|
3. 生成 `ENTITY`、`PAGE_SCHEMA`、`SERVICEFLOW`、`MENU`、`TEST` 草稿。`PAGE_SCHEMA`
|
||||||
|
先生成 EIP4 PageBlueprint,再由平台编译器输出 amis schema;草稿 metadata 保留 blueprint 证据。
|
||||||
|
未指定 `feature.pageRecipe` 时默认使用 `maintenance-crud-v1`;树形维护页应指定 `tree-crud-v1`。
|
||||||
|
4. 对草稿执行基础门禁,包括 page-recipe、amis schema、typed page schema、服务流 XML、实体字段、smoke 计划和 render plan。
|
||||||
|
5. 生成待人审 `AiChangeSet`。
|
||||||
|
6. 生成 release plan。
|
||||||
|
7. 本地 apply:实体走本机 `/api/meta/entity`,页面/服务流写本地库;如果本地最小库缺少 `sys_menu`,菜单发布标记为 `SKIPPED`,不阻断本地 gate,部署包仍保留菜单 SQL 供线上人审。
|
||||||
|
8. 本地 smoke:只允许 `localhost`、`127.0.0.1`、`::1` baseUrl;HTTP 状态必须匹配,且 JSON 响应体存在 `status` 时必须为 0。
|
||||||
|
`TEST` 草稿同时包含 `renderTests`,给 Playwright 渲染验收提供 recipe、schemaUrl、previewUrl、预期组件、CRUD 名、数据 API、列、动作和关键文本。
|
||||||
|
9. 若失败,自动生成 repair plan 并执行修复重试。
|
||||||
|
10. 生成线上人工部署包,包含 manifest、SQL 草案、回滚 SQL 和本地执行证据。
|
||||||
|
11. 可选:生成功能包快照并保存 revision,用于后续导出、差异比较和回滚扩展。
|
||||||
|
|
||||||
|
返回体中的关键字段:
|
||||||
|
|
||||||
|
- `originalChangeSetId`: 首轮自动生成的变更包。
|
||||||
|
- `changeSetId`: 最终用于部署包的变更包;如果修复生成了替代草稿,可能不同于 `originalChangeSetId`。
|
||||||
|
- `repairExecutions`: 每轮自动修复证据。
|
||||||
|
- `deploymentPackage.requiresHumanApproval`: 固定为 `true`,线上发布必须人工审批。
|
||||||
|
|
||||||
|
## 功能包和 revision
|
||||||
|
|
||||||
|
P2 第一版新增功能包快照和里程碑版本:
|
||||||
|
|
||||||
|
- `POST /api/ai/tasks/{taskId}/change-sets/{changeSetId}/feature-package`
|
||||||
|
- `GET /api/ai/tasks/{taskId}/feature-packages`
|
||||||
|
- `POST /api/ai/tasks/{taskId}/feature-packages/{packageId}/revisions`
|
||||||
|
- `GET /api/ai/tasks/{taskId}/revisions`
|
||||||
|
|
||||||
|
功能包封装部署包、manifest、本地 evidence、SQL 草案和回滚 SQL。revision 当前保存功能包 JSON 快照,作为后续差异比较和回滚执行的基础。生产执行仍不自动化,必须人审。
|
||||||
|
|
||||||
|
## 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 兼容清理。
|
||||||
215
docs/AI_AGENT_Nocobase_ADOPTION_PLAN.md
Normal file
215
docs/AI_AGENT_Nocobase_ADOPTION_PLAN.md
Normal file
@@ -0,0 +1,215 @@
|
|||||||
|
# AI Agent 借鉴 NocoBase 的落地路线
|
||||||
|
|
||||||
|
日期:2026-06-17
|
||||||
|
|
||||||
|
本文记录 EIP4 对 NocoBase AI + no-code 体系的可借鉴点和落地顺序。目标不是照搬 NocoBase 的 TypeScript 插件运行时,而是吸收它的工程边界:核心平台稳定、业务能力包化、AI 通过受控 CLI/API 操作、所有变更可审计、可验证、可回滚。
|
||||||
|
|
||||||
|
参考:
|
||||||
|
|
||||||
|
- NocoBase README: https://github.com/nocobase/nocobase
|
||||||
|
- NocoBase Plugin Development: https://docs.nocobase.com/plugin-development/
|
||||||
|
- NocoBase Project Structure: https://docs.nocobase.com/plugin-development/project-structure
|
||||||
|
- NocoBase AI Builder: https://docs.nocobase.com/ai-builder/
|
||||||
|
- NocoBase AI Plugin Development: https://docs.nocobase.com/ai-dev/
|
||||||
|
- NocoBase CLI: https://docs.nocobase.com/api/cli/
|
||||||
|
- NocoBase Skills: https://github.com/nocobase/skills
|
||||||
|
|
||||||
|
## 一、判断
|
||||||
|
|
||||||
|
NocoBase 最核心的启发是:AI 不应该默认直接写一堆业务代码,而是基于平台已有的可配置能力工作。AI 负责把自然语言需求转换为数据模型、页面配置、工作流、权限和发布包,人负责审核关键边界。
|
||||||
|
|
||||||
|
EIP4 当前已经有实体、页面 schema、服务流、菜单、smoke、部署包这些受控对象,因此更适合走“AI 操作元数据和发布包”的路线,而不是引入一套新的插件运行时。
|
||||||
|
|
||||||
|
## 二、可借鉴点
|
||||||
|
|
||||||
|
| NocoBase 做法 | EIP4 对应落点 | 处理方式 |
|
||||||
|
|---|---|---|
|
||||||
|
| AI 基于 no-code 基础设施工作 | `platform-ai` 生成实体/页面/服务流/菜单草稿 | 已落地,继续收敛到受控接口 |
|
||||||
|
| CLI 作为 Agent 操作入口 | `platform-cli` | P1 建立,后续扩展环境/发布/回滚 |
|
||||||
|
| Skills 让 Agent 理解平台 | `docs/skills/` | P1 建立规范骨架 |
|
||||||
|
| 插件生命周期 | EIP4 `FeaturePackage` 生命周期 | P2 设计和持久化 |
|
||||||
|
| 版本控制/里程碑回滚 | `SYS_AI_REVISION` / release evidence | P2-P3 |
|
||||||
|
| FlowEngine 的可配置模型 | EIP4 typed page schema + component registry | P4 借鉴思想,不照搬实现 |
|
||||||
|
|
||||||
|
## 三、落地顺序
|
||||||
|
|
||||||
|
### P0:全自动开发主链路
|
||||||
|
|
||||||
|
状态:已完成。
|
||||||
|
|
||||||
|
完成内容:
|
||||||
|
|
||||||
|
- `POST /api/ai/features/auto-develop`
|
||||||
|
- 草稿生成、变更包、release plan、本地 apply、smoke、自动修复、人工部署包
|
||||||
|
- JDBC 审计和运行证据
|
||||||
|
- 本地 jar 验证通过
|
||||||
|
|
||||||
|
验收标准:
|
||||||
|
|
||||||
|
- 本地可从一段功能需求生成可审核部署包
|
||||||
|
- 线上执行仍停在人审边界
|
||||||
|
|
||||||
|
### P1:受控入口和 Agent 知识包
|
||||||
|
|
||||||
|
状态:第一版完成。
|
||||||
|
|
||||||
|
目标:
|
||||||
|
|
||||||
|
- 建立 `platform-cli`,让 Agent 通过命令调用 EIP4,而不是直接猜 HTTP 接口或直连数据库。
|
||||||
|
- 建立 `docs/skills/`,把 EIP4 的环境管理、自动开发、发布管理写成 Agent 可复用的操作规程。
|
||||||
|
|
||||||
|
本阶段交付:
|
||||||
|
|
||||||
|
- `eip4 env status`
|
||||||
|
- `eip4 ai auto-develop`
|
||||||
|
- `docs/skills/eip4-env-manage.md`
|
||||||
|
- `docs/skills/eip4-ai-feature-development.md`
|
||||||
|
- `docs/skills/eip4-release-manage.md`
|
||||||
|
|
||||||
|
验收标准:
|
||||||
|
|
||||||
|
- CLI 单测覆盖命令解析和请求组装
|
||||||
|
- README 和自动开发文档给出 CLI 用法
|
||||||
|
- Agent 后续操作优先引用 Skills 和 CLI
|
||||||
|
|
||||||
|
### P2:FeaturePackage 和里程碑版本
|
||||||
|
|
||||||
|
状态:第一版完成。
|
||||||
|
|
||||||
|
目标:
|
||||||
|
|
||||||
|
- 把 AI 生成结果从松散的 draft/change-set 升级为稳定的 `FeaturePackage`。
|
||||||
|
- 保存里程碑版本,支持本地回滚和线上部署前差异确认。
|
||||||
|
|
||||||
|
建议对象:
|
||||||
|
|
||||||
|
- `FeaturePackage`: manifest、entity、serviceflow、page schema、menu、acl、sql、rollback、smoke、evidence
|
||||||
|
- `SYS_AI_FEATURE_PACKAGE`
|
||||||
|
- `SYS_AI_REVISION`
|
||||||
|
|
||||||
|
验收标准:
|
||||||
|
|
||||||
|
- 一个功能包可以导出、导入、重复校验
|
||||||
|
- 每个通过 smoke 的里程碑都能追溯输入、输出、测试证据和回滚脚本
|
||||||
|
|
||||||
|
第一版已落地:
|
||||||
|
|
||||||
|
- `POST /api/ai/tasks/{taskId}/change-sets/{changeSetId}/feature-package`
|
||||||
|
- `GET /api/ai/tasks/{taskId}/feature-packages`
|
||||||
|
- `POST /api/ai/tasks/{taskId}/feature-packages/{packageId}/revisions`
|
||||||
|
- `GET /api/ai/tasks/{taskId}/revisions`
|
||||||
|
- `eip4 ai feature-package`
|
||||||
|
- `eip4 ai revision`
|
||||||
|
- `sys_ai_feature_package`
|
||||||
|
- `sys_ai_revision`
|
||||||
|
|
||||||
|
未完成项:
|
||||||
|
|
||||||
|
- 功能包导出/导入文件格式
|
||||||
|
- revision 差异比较
|
||||||
|
- 回滚执行编排
|
||||||
|
|
||||||
|
### P3:发布、回滚和环境治理
|
||||||
|
|
||||||
|
状态:进行中。
|
||||||
|
|
||||||
|
目标:
|
||||||
|
|
||||||
|
- CLI 扩展为环境管理和发布编排入口。
|
||||||
|
- 建立本地、测试、生产环境的只读探测、部署前检查和人工批准边界。
|
||||||
|
|
||||||
|
建议命令:
|
||||||
|
|
||||||
|
- `eip4 env list/use/status`
|
||||||
|
- `eip4 release package`
|
||||||
|
- `eip4 release verify`
|
||||||
|
- `eip4 release apply --require-approval`
|
||||||
|
- `eip4 release rollback-plan --package-file FILE --output FILE`
|
||||||
|
|
||||||
|
验收标准:
|
||||||
|
|
||||||
|
- 默认不能连接线上执行写操作
|
||||||
|
- 生产写操作必须有显式环境、审批标记和部署包
|
||||||
|
- 发布失败能用结构化 evidence 回到本地修复链路
|
||||||
|
|
||||||
|
源码级修订:
|
||||||
|
|
||||||
|
- 参考 NocoBase `env/status.ts` 和 `env-guard.ts`,`platform-cli` 新增本地 env registry/current env。
|
||||||
|
- 参考 NocoBase revision 创建前检查版本控制插件的思路,EIP4 后续 revision restore/diff 不能只依赖 JSON 快照,必须有发布系统能力检查。
|
||||||
|
- 新增 `eip4 release verify --package-file FILE`,先做离线发布前门禁,阻断未替换占位符和缺失本地 evidence 的功能包。
|
||||||
|
- 新增 `eip4 release export/import-preview`,形成 `.eip4pkg.json` 文件格式和 checksum 门禁;导入预览不写环境、不启用功能。
|
||||||
|
- 新增 `eip4 release diff/rollback-plan`,先落地离线差异检查和计划型回滚;回滚计划不执行生产 SQL。
|
||||||
|
- 详细源码对照见 `docs/AI_AGENT_Nocobase_SOURCE_REVIEW.md`。
|
||||||
|
|
||||||
|
### P4:Typed Page Schema 和组件注册表
|
||||||
|
|
||||||
|
状态:第一版完成。
|
||||||
|
|
||||||
|
目标:
|
||||||
|
|
||||||
|
- 借鉴 NocoBase FlowEngine 的“可配置模型”思想,把页面 block、field、action、linkage 抽象为 typed schema。
|
||||||
|
- 让 AI 和人工设计器操作同一份 schema。
|
||||||
|
|
||||||
|
验收标准:
|
||||||
|
|
||||||
|
- 页面 schema 有版本、类型、组件能力表和校验器
|
||||||
|
- AI 只能选择注册过的组件和动作
|
||||||
|
- 设计器变更和 AI 变更能互相接续
|
||||||
|
|
||||||
|
第一版已落地:
|
||||||
|
|
||||||
|
- `GET /api/page/schema/components` 下发组件能力表。
|
||||||
|
- `POST /api/page/schema/validate` 做 typed page schema 离线校验。
|
||||||
|
- `PUT /api/page/schema/{templateId}/overlay` 保存 overlay 前强制校验组件和 actionType。
|
||||||
|
- 当前仍是第一版 registry;后续要继续补 linkage/event/resource 和组件属性级 schema。
|
||||||
|
|
||||||
|
### P5:多 Agent 协作和 AI 员工
|
||||||
|
|
||||||
|
状态:第一版完成。
|
||||||
|
|
||||||
|
目标:
|
||||||
|
|
||||||
|
- 在平台内提供面向业务用户的 AI 助手能力,而不只是在开发侧使用 Agent。
|
||||||
|
|
||||||
|
建议方向:
|
||||||
|
|
||||||
|
- 数据分析 Agent
|
||||||
|
- 表单配置 Agent
|
||||||
|
- 服务流诊断 Agent
|
||||||
|
- 权限风险审查 Agent
|
||||||
|
- 发布审计 Agent
|
||||||
|
|
||||||
|
验收标准:
|
||||||
|
|
||||||
|
- 每个 Agent 有独立权限、审计、工具白名单
|
||||||
|
- 业务侧操作和开发侧操作共用平台审计模型
|
||||||
|
|
||||||
|
第一版已落地:
|
||||||
|
|
||||||
|
- `GET /api/ai/tools` 下发工具注册表和 scope 要求。
|
||||||
|
- `GET /api/ai/employees` 下发 AI employee 定义。
|
||||||
|
- `POST /api/ai/tools/access-check` 统一检查 employee/tool/scope/targetEnv/productionWrite。
|
||||||
|
- 生产写默认阻断;当前只开放本地开发、校验、smoke、功能包和发布准备工具。
|
||||||
|
|
||||||
|
## 四、不照搬的部分
|
||||||
|
|
||||||
|
NocoBase 是 TypeScript/Yarn workspace/插件包体系。EIP4 是 Java/Spring/Maven,并且必须兼容 EIP3 的实体、服务流和 XML 模板迁移路径。直接照搬 NocoBase 插件运行时会引入过高迁移成本。
|
||||||
|
|
||||||
|
EIP4 应该借鉴的是边界和流程:
|
||||||
|
|
||||||
|
1. 稳定核心能力。
|
||||||
|
2. 业务功能包化。
|
||||||
|
3. Agent 通过 CLI/API 操作。
|
||||||
|
4. 人审控制生产变更。
|
||||||
|
5. 每一步有 evidence、版本和回滚。
|
||||||
|
|
||||||
|
## 五、当前推进状态
|
||||||
|
|
||||||
|
| 阶段 | 状态 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| P0 | 完成 | `platform-ai` 主链路已提交 |
|
||||||
|
| P1 | 第一版完成 | 已新增 `platform-cli` 和 Skills 规范骨架 |
|
||||||
|
| P2 | 第一版完成 | 已新增功能包快照、里程碑 revision、CLI 命令和持久化表 |
|
||||||
|
| P3 | 进行中 | 已完成 env registry/current env/cross-env guard/release verify/export/import-preview/diff/rollback-plan 第一版 |
|
||||||
|
| P4 | 第一版完成 | 已新增组件 registry、typed schema validator、校验 API 和 overlay 保存前门禁 |
|
||||||
|
| P5 | 第一版完成 | 已新增 AI tool registry、AI employee registry 和 access-check 门禁 |
|
||||||
136
docs/AI_AGENT_Nocobase_SOURCE_REVIEW.md
Normal file
136
docs/AI_AGENT_Nocobase_SOURCE_REVIEW.md
Normal file
@@ -0,0 +1,136 @@
|
|||||||
|
# NocoBase 源码级对照和 EIP4 修订
|
||||||
|
|
||||||
|
日期:2026-06-17
|
||||||
|
|
||||||
|
本文件补充 `docs/AI_AGENT_Nocobase_ADOPTION_PLAN.md` 的源码级依据。结论:EIP4 不照搬 NocoBase 的 TypeScript 插件运行时,但 P3 之后必须参考它的 CLI/env/revision/skills/tool-registry 边界,否则容易只做出“HTTP wrapper”,做不到可持续的 Agent 开发体系。
|
||||||
|
|
||||||
|
## 一、已抽样源码
|
||||||
|
|
||||||
|
| 主题 | NocoBase 源码 | 对 EIP4 的影响 |
|
||||||
|
|---|---|---|
|
||||||
|
| CLI env status | `packages/core/cli/src/commands/env/status.ts` | CLI 要有 env registry/current env/status,不应只靠 `--base-url` |
|
||||||
|
| 跨 env 确认 | `packages/core/cli/src/lib/env-guard.ts` | 显式选择非当前 env 时需要确认边界 |
|
||||||
|
| API client | `packages/core/cli/src/lib/api-client.ts` | CLI 请求应带结构化 env/token/role/header,后续不能散落在命令里 |
|
||||||
|
| runtime command registry | `packages/core/cli/src/generated/command-registry.ts` | 可根据运行时 API 生成命令,EIP4 后续可用 OpenAPI 生成安全 CLI |
|
||||||
|
| generic resource command | `packages/core/cli/src/lib/resource-command.ts` | CRUD 类命令应统一处理 JSON body、分页、过滤、错误输出 |
|
||||||
|
| plugin import/enable | `packages/core/cli/src/commands/plugin/import.ts`, `packages/core/cli/src/commands/plugin/enable.ts` | EIP4 的 FeaturePackage 后续也要区分导入、启用、发布和重启/刷新 |
|
||||||
|
| revision create | `packages/core/cli/src/commands/revision/create.ts` | revision 不能只是保存 JSON,发布前要检查版本控制能力是否可用 |
|
||||||
|
| skills install | `packages/core/cli/src/commands/skills/install.ts` | Skills 应由 CLI 安装/检查/更新,而不是只放仓库文档 |
|
||||||
|
| AI plugin server | `packages/plugins/@nocobase/plugin-ai/src/server/plugin.ts` | AI 功能要注册 tools、skills、MCP、AI employees、ACL snippet |
|
||||||
|
| FlowEngine | `packages/core/flow-engine/src/flowEngine.ts`, `packages/core/flow-engine/src/models/flowModel.tsx` | 页面 schema 需要演进到 typed model/action/event/resource registry |
|
||||||
|
|
||||||
|
## 二、对当前实现的校正
|
||||||
|
|
||||||
|
### P0-P2 是否做实
|
||||||
|
|
||||||
|
已做实:
|
||||||
|
|
||||||
|
- `platform-ai` 主链路有 Java 实现、JDBC/内存 store、DDL、Web API 和测试。
|
||||||
|
- `platform-cli` 是可运行 jar,不是伪命令。
|
||||||
|
- `FeaturePackage` 和 `Revision` 已有最小持久化模型。
|
||||||
|
|
||||||
|
但它还不是 NocoBase 级完整度:
|
||||||
|
|
||||||
|
- CLI 之前缺少 env registry/current env。
|
||||||
|
- revision 只是功能包快照,不是完整版本控制。
|
||||||
|
- Skills 只是仓库文档,没有 CLI 安装/检查/更新。
|
||||||
|
- AI tools/permissions/MCP/AI employee 还没有平台级注册。
|
||||||
|
- 页面配置还没有 typed FlowModel registry。
|
||||||
|
|
||||||
|
### 已按源码对照修订的 P3 第一批
|
||||||
|
|
||||||
|
- `platform-cli` 新增本地 env registry,默认保存到 `~/.eip4/eip4-cli.json`。
|
||||||
|
- 新增 `eip4 env add/list/use/current/status`。
|
||||||
|
- AI 命令支持 `--env`。
|
||||||
|
- 显式选择非当前 env 时必须加 `--yes`,避免误操作共享环境。
|
||||||
|
- 新增 `eip4 release verify --package-file FILE`,离线检查功能包是否具备本地门禁 evidence、人审标记、SQL/rollback,并阻断 `${...}` 占位符。
|
||||||
|
- 新增 `eip4 release export --package-file FILE --output FILE`,将功能包封装为 `.eip4pkg.json`,包含格式版本和 SHA-256 checksum。
|
||||||
|
- 新增 `eip4 release import-preview --package-file FILE`,离线验证 `.eip4pkg.json` checksum 和发布门禁,不写任何环境。
|
||||||
|
- 新增 `eip4 release diff --left FILE --right FILE`,离线比较两个功能包或 `.eip4pkg.json` 的标识、SQL、rollback SQL 和 manifest 差异。
|
||||||
|
- 新增 `eip4 release rollback-plan --package-file FILE --output FILE`,只生成结构化回滚计划,不执行生产写入。
|
||||||
|
|
||||||
|
## 三、后续实现顺序
|
||||||
|
|
||||||
|
### P3-1:CLI env 和发布前治理
|
||||||
|
|
||||||
|
状态:进行中。
|
||||||
|
|
||||||
|
目标:
|
||||||
|
|
||||||
|
- env registry/current env
|
||||||
|
- `release verify`
|
||||||
|
- package/revision 差异检查
|
||||||
|
- 生产环境默认只读
|
||||||
|
|
||||||
|
### P3-2:FeaturePackage 导出/导入
|
||||||
|
|
||||||
|
状态:第一版完成。
|
||||||
|
|
||||||
|
目标:
|
||||||
|
|
||||||
|
- `.eip4pkg.json` 文件格式
|
||||||
|
- checksum
|
||||||
|
- import preview
|
||||||
|
- import 后不自动启用
|
||||||
|
|
||||||
|
第一版已落地:
|
||||||
|
|
||||||
|
- export: 普通 feature package JSON -> `.eip4pkg.json` 信封。
|
||||||
|
- import-preview: 校验 format/version/checksum/payload 和 release gate。
|
||||||
|
- import-preview 只读,不落库、不启用、不发布。
|
||||||
|
|
||||||
|
### P3-3:Revision diff/restore
|
||||||
|
|
||||||
|
状态:第一版完成。
|
||||||
|
|
||||||
|
目标:
|
||||||
|
|
||||||
|
- revision diff
|
||||||
|
- rollback plan
|
||||||
|
- rollback 只生成计划和 SQL,不默认执行生产写入
|
||||||
|
|
||||||
|
第一版已落地:
|
||||||
|
|
||||||
|
- diff: 比较两个普通 feature package JSON 或 `.eip4pkg.json`,支持 checksum 校验和 JSON 输出。
|
||||||
|
- rollback-plan: 生成 `EIP4_ROLLBACK_PLAN` JSON,包含 package/task/changeSet、rollback SQL、source evidence 和人审要求。
|
||||||
|
- rollback-plan 会阻断 rollback SQL 中的 `${...}` 占位符;命令不连接环境、不落库、不执行 SQL。
|
||||||
|
|
||||||
|
### P4:Typed UI Registry
|
||||||
|
|
||||||
|
状态:第一版完成。
|
||||||
|
|
||||||
|
目标:
|
||||||
|
|
||||||
|
- typed page schema
|
||||||
|
- component/action/event registry
|
||||||
|
- AI 只能选择 registry 中允许的组件和动作
|
||||||
|
|
||||||
|
第一版已落地:
|
||||||
|
|
||||||
|
- `PageComponentRegistry` 提供页面组件能力表,当前覆盖 page/crud/form/operation/button、常用 layout/display 和字段组件。
|
||||||
|
- `TypedPageSchemaValidator` 校验根节点、已注册组件和 actionType 能力。
|
||||||
|
- `GET /api/page/schema/components` 返回组件能力表。
|
||||||
|
- `POST /api/page/schema/validate` 离线校验页面 schema,不写库。
|
||||||
|
- `PUT /api/page/schema/{templateId}/overlay` 保存前会先跑 typed schema 校验,未注册组件或不支持 action 会被 400 阻断。
|
||||||
|
|
||||||
|
### P5:AI tools/skills/employee/ACL
|
||||||
|
|
||||||
|
状态:第一版完成。
|
||||||
|
|
||||||
|
目标:
|
||||||
|
|
||||||
|
- AI tool registry
|
||||||
|
- AI employee registry
|
||||||
|
- ACL/scope check
|
||||||
|
- 生产写默认阻断
|
||||||
|
|
||||||
|
第一版已落地:
|
||||||
|
|
||||||
|
- `AiToolRegistry` 注册工具、操作入口、所需 scope、本地限定和生产写边界。
|
||||||
|
- `GET /api/ai/tools` 返回 AI 工具注册表。
|
||||||
|
- `GET /api/ai/employees` 返回 AI employee 定义。
|
||||||
|
- `POST /api/ai/tools/access-check` 只做权限判定,不执行工具;`local.apply` 等本地工具在 prod target 会被阻断。
|
||||||
|
- 当前所有工具都不允许生产写;线上部署仍由人工拿发布包执行。
|
||||||
|
- Skills CLI check/update
|
||||||
|
- AI Agent 权限和审计
|
||||||
|
- MCP 工具白名单
|
||||||
127
docs/AI_AGENT_PAGE_BLUEPRINT_CONTRACT.md
Normal file
127
docs/AI_AGENT_PAGE_BLUEPRINT_CONTRACT.md
Normal file
@@ -0,0 +1,127 @@
|
|||||||
|
# AI Agent Page Blueprint Contract
|
||||||
|
|
||||||
|
日期:2026-06-17
|
||||||
|
|
||||||
|
## 目标
|
||||||
|
|
||||||
|
EIP4 的 AI Agent 不直接自由生成 amis JSON。Agent 应先生成 EIP4 PageBlueprint,再由平台编译器输出 amis schema,并继续通过 typed page schema、amis schema 和真实浏览器 E2E。
|
||||||
|
|
||||||
|
这条路径借鉴 NocoBase 的做法:AI 操作受控配置模型,平台负责规范化、校验、模板复用和版本证据。
|
||||||
|
|
||||||
|
## 当前已落地对象
|
||||||
|
|
||||||
|
代码位置:
|
||||||
|
|
||||||
|
- `platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageBlueprint.java`
|
||||||
|
- `platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageBlueprintField.java`
|
||||||
|
- `platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageBlueprintCompiler.java`
|
||||||
|
- `platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeRegistry.java`
|
||||||
|
- `platform-metadata/src/main/java/com/eip4/platform/metadata/schema/blueprint/PageRecipeValidator.java`
|
||||||
|
- `platform-ai/src/main/resources/ai/page-recipes/maintenance-crud-v1.yaml`
|
||||||
|
- `platform-ai/src/main/resources/ai/page-recipes/tree-crud-v1.yaml`
|
||||||
|
|
||||||
|
AI 可查询入口:
|
||||||
|
|
||||||
|
- `GET /api/ai/page-recipes`
|
||||||
|
- `GET /api/ai/page-recipes/{recipe}`
|
||||||
|
|
||||||
|
工具注册表中对应工具为 `page-recipe.read`,所需 scope 为 `ai:page-recipe:read`。Agent 生成
|
||||||
|
PageBlueprint 前应先读取 recipe 定义,再生成草稿。
|
||||||
|
|
||||||
|
AI 自动开发链路中的 `PAGE_SCHEMA` 草稿仍然保存编译后的 amis schema,保持现有落库和前端渲染契约不变;草稿 metadata 额外保存:
|
||||||
|
|
||||||
|
- `pageRecipe`
|
||||||
|
- `pageBlueprintVersion`
|
||||||
|
- `pageBlueprint`
|
||||||
|
|
||||||
|
声明了 `pageRecipe` 的草稿必须通过 `page-recipe` 门禁。该门禁会重新解析 metadata 中的
|
||||||
|
`pageBlueprint`,用平台注册的 recipe/compiler 重新编译,并要求草稿 payload 与编译结果一致。
|
||||||
|
因此 Agent 不能一边声明使用标准 recipe,一边绕过 compiler 私改 amis JSON。没有声明 recipe 的
|
||||||
|
历史/手工 `PAGE_SCHEMA` 草稿暂按自由 schema 处理,只走 amis schema 和 typed page schema。
|
||||||
|
|
||||||
|
## Recipe: maintenance-crud-v1
|
||||||
|
|
||||||
|
适用范围:
|
||||||
|
|
||||||
|
- 普通实体维护页
|
||||||
|
- 单主表列表
|
||||||
|
- 新增、编辑、删除
|
||||||
|
- 本地 smoke 可覆盖列表、新增、服务流搜索
|
||||||
|
|
||||||
|
标准输出结构:
|
||||||
|
|
||||||
|
- 顶层 `type=page`
|
||||||
|
- `body` 为 `crud`
|
||||||
|
- `crud.name` 固定为 `{lowerCamel(tableName)}Crud`
|
||||||
|
- `crud.syncLocation=false`
|
||||||
|
- 列表 API 固定为 `/api/entity/{table}/list?page=${page}&perPage=${perPage}`
|
||||||
|
- 新增按钮位于 `headerToolbar[0]`
|
||||||
|
- 新增按钮使用 `level=primary`、`icon=fa fa-plus`、`actionType=dialog`
|
||||||
|
- 新增和编辑表单提交到 `post:/api/entity/{table}/save`
|
||||||
|
- 编辑按钮位于操作列第一位
|
||||||
|
- 删除按钮位于操作列第二位
|
||||||
|
- 删除按钮使用 `className=text-danger`、`actionType=ajax`、`confirmText`
|
||||||
|
- 删除 API 固定为 `/api/entity/{table}/delete`
|
||||||
|
- 页大小默认 `20`
|
||||||
|
- `footerToolbar` 固定包含 `statistics` 和 `pagination`
|
||||||
|
|
||||||
|
## Recipe: tree-crud-v1
|
||||||
|
|
||||||
|
适用范围:
|
||||||
|
|
||||||
|
- 自引用层级实体维护页
|
||||||
|
- 实体必须包含 `PARENTID` 字段
|
||||||
|
- 覆盖树形列表、新增顶级节点、加子节点、编辑、删除
|
||||||
|
|
||||||
|
标准输出结构:
|
||||||
|
|
||||||
|
- 顶层 `type=page`
|
||||||
|
- `body` 为 `crud`
|
||||||
|
- `crud.name` 固定为 `{lowerCamel(tableName)}TreeCrud`
|
||||||
|
- `crud.childrenColumnName=children`
|
||||||
|
- 列表 API 固定为 `/api/entity/{table}/tree?parentKey=PARENTID&idKey={primaryKey}&perPage=2000`
|
||||||
|
- 新增顶级按钮位于 `headerToolbar[0]`
|
||||||
|
- 新增顶级按钮使用 `level=primary`、`icon=fa fa-plus`、`actionType=dialog`
|
||||||
|
- 操作列按钮顺序固定为:加子项、编辑、删除
|
||||||
|
- 加子项表单必须隐藏写入 `PARENTID=${primaryKey}`
|
||||||
|
- 编辑表单必须保留隐藏主键和 `PARENTID`
|
||||||
|
- 删除按钮使用 `className=text-danger`、`actionType=ajax`、`confirmText`
|
||||||
|
- 树数据端点返回 `data.items` 层级数组,每个节点的子节点字段为 `children`
|
||||||
|
|
||||||
|
字段映射:
|
||||||
|
|
||||||
|
- `string` -> `input-text`
|
||||||
|
- `integer` / `number` -> `input-number`
|
||||||
|
- `date` -> `input-date`
|
||||||
|
- `datetime` -> `input-datetime`
|
||||||
|
- `boolean` -> `switch`
|
||||||
|
- 主键不出现在新增表单,编辑表单最后追加 `hidden`
|
||||||
|
|
||||||
|
## 当前边界
|
||||||
|
|
||||||
|
本阶段只解决“AI 生成维护类 CRUD 页时走受控 recipe”。还未覆盖:
|
||||||
|
|
||||||
|
- 主子表页面
|
||||||
|
- 审批办理页面
|
||||||
|
- 看板、日历、图表、报表页
|
||||||
|
- 复杂字段分组
|
||||||
|
- 条件联动
|
||||||
|
- 引用选择器策略
|
||||||
|
- 权限按钮策略
|
||||||
|
|
||||||
|
这些类型必须作为新的 recipe 增量加入,不能让 Agent 直接绕过 blueprint 生成最终 amis JSON。
|
||||||
|
|
||||||
|
## 已落地门禁
|
||||||
|
|
||||||
|
- `page-recipe`:校验 recipe 已注册、metadata 证据完整、payload 等于 blueprint 编译结果。
|
||||||
|
- `typed-page-schema`:校验组件和 actionType 来自 EIP4 注册表。
|
||||||
|
- `amis-schema`:校验最终 schema 符合 amis schema。
|
||||||
|
- `local-smoke`:本地发布后访问页面、实体、服务流和新增接口。
|
||||||
|
- `render-plan`:`TEST` 草稿必须提供 Playwright 可消费的 `renderTests`,包含 recipe、schemaUrl、previewUrl、预期根组件、CRUD 名、数据 API、列表列、页面动作和关键文本。
|
||||||
|
|
||||||
|
## 后续演进
|
||||||
|
|
||||||
|
1. 增加 `master-detail-v1`、`approval-task-v1` recipe。
|
||||||
|
2. 让设计器 overlay 保存也能记录对应 blueprint 或 template 来源。
|
||||||
|
3. 在功能包中导出 blueprint,线上部署包继续导出编译后的 amis schema。
|
||||||
|
4. Playwright E2E 消费 `renderTests`,执行真实浏览器渲染并回写运行证据。
|
||||||
155
docs/AI_AGENT_REPAIR_CONTRACT.md
Normal file
155
docs/AI_AGENT_REPAIR_CONTRACT.md
Normal file
@@ -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 <api-key>`。接口超时为 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 页面必填结构"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
19
docs/skills/README.md
Normal file
19
docs/skills/README.md
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
# EIP4 Agent Skills
|
||||||
|
|
||||||
|
本目录是 EIP4 给 AI Agent 使用的领域操作规程。目标是让 Codex、Claude Code、Cursor、OpenCode 等 Agent 都按同一套规则操作 EIP4,而不是临时猜接口、猜表结构或直连线上库。
|
||||||
|
|
||||||
|
## Skills
|
||||||
|
|
||||||
|
| Skill | 用途 |
|
||||||
|
|---|---|
|
||||||
|
| `eip4-env-manage` | 环境探测、启动检查、端口和 profile 边界 |
|
||||||
|
| `eip4-ai-feature-development` | 从自然语言需求生成实体、服务流、页面、菜单和本地 smoke |
|
||||||
|
| `eip4-release-manage` | 部署包、人审、发布前校验和回滚边界 |
|
||||||
|
|
||||||
|
## 通用原则
|
||||||
|
|
||||||
|
1. 优先使用 `platform-cli`,其次使用公开 REST API,最后才考虑人工 SQL。
|
||||||
|
2. 默认只允许本地开发和测试环境自动执行写操作。
|
||||||
|
3. 线上环境只能生成部署包和校验证据,不能由 Agent 默认直接写入。
|
||||||
|
4. 每次自动开发必须保留 request、draft、change-set、apply、smoke、repair、deployment package evidence。
|
||||||
|
5. 任何失败先回到本地复现和修复,再重新生成部署包。
|
||||||
113
docs/skills/eip4-ai-feature-development.md
Normal file
113
docs/skills/eip4-ai-feature-development.md
Normal file
@@ -0,0 +1,113 @@
|
|||||||
|
# Skill: eip4-ai-feature-development
|
||||||
|
|
||||||
|
## 触发场景
|
||||||
|
|
||||||
|
- 用户描述一个新功能,希望 AI 自动生成。
|
||||||
|
- 用户要求从 EIP3 模板、实体、服务流或页面定义生成 EIP4 功能。
|
||||||
|
- 用户要求本地自动开发、自动修复和 smoke。
|
||||||
|
|
||||||
|
## 输入要求
|
||||||
|
|
||||||
|
最小需求应包含:
|
||||||
|
|
||||||
|
- 功能目标
|
||||||
|
- 功能名称
|
||||||
|
- 业务表名
|
||||||
|
- 实体名称
|
||||||
|
- 页面 templateId
|
||||||
|
- 菜单名称
|
||||||
|
- 字段列表
|
||||||
|
- 页面配方,可省略。默认 `maintenance-crud-v1`;树形维护页使用 `tree-crud-v1`
|
||||||
|
|
||||||
|
字段格式:
|
||||||
|
|
||||||
|
```text
|
||||||
|
column:label:type[:length][:required]
|
||||||
|
```
|
||||||
|
|
||||||
|
示例:
|
||||||
|
|
||||||
|
```text
|
||||||
|
NAME:名称:string:100:true
|
||||||
|
CODE:编码:string:64:true
|
||||||
|
ENABLED:启用:boolean::false
|
||||||
|
```
|
||||||
|
|
||||||
|
## 推荐命令
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai auto-develop \
|
||||||
|
--base-url http://localhost:8084 \
|
||||||
|
--objective "新增客户等级维护功能" \
|
||||||
|
--feature-name "客户等级维护" \
|
||||||
|
--table-name EIP4AI_CUSTOMER_LEVEL \
|
||||||
|
--entity-name "客户等级" \
|
||||||
|
--template-id eip4ai-customer-level \
|
||||||
|
--menu-name "客户等级维护" \
|
||||||
|
--field NAME:名称:string:100:true \
|
||||||
|
--field CODE:编码:string:64:true \
|
||||||
|
--field ENABLED:启用:boolean::false \
|
||||||
|
--page-recipe maintenance-crud-v1 \
|
||||||
|
--max-repair-attempts 2 \
|
||||||
|
--output target/ai-runs/customer-level.json
|
||||||
|
```
|
||||||
|
|
||||||
|
树形维护页示例:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai auto-develop \
|
||||||
|
--base-url http://localhost:8084 \
|
||||||
|
--objective "新增组织分类树形维护功能" \
|
||||||
|
--feature-name "组织分类维护" \
|
||||||
|
--table-name EIP4AI_ORG_CATEGORY \
|
||||||
|
--entity-name "组织分类" \
|
||||||
|
--template-id eip4ai-org-category \
|
||||||
|
--menu-name "组织分类维护" \
|
||||||
|
--field NAME:名称:string:100:true \
|
||||||
|
--field CODE:编码:string:64:true \
|
||||||
|
--page-recipe tree-crud-v1 \
|
||||||
|
--max-repair-attempts 2 \
|
||||||
|
--output target/ai-runs/org-category-tree.json
|
||||||
|
```
|
||||||
|
|
||||||
|
## 通过标准
|
||||||
|
|
||||||
|
- `applyStatus` 为 `PASSED`。
|
||||||
|
- `smokeStatus` 为 `PASSED`。
|
||||||
|
- 最终状态为 `READY_FOR_HUMAN_REVIEW`。
|
||||||
|
- 部署包存在且 `requiresHumanApproval=true`。
|
||||||
|
- 页面 schema 只能使用组件能力表中注册的组件和动作。
|
||||||
|
- `PAGE_SCHEMA` 草稿必须声明并通过 `page-recipe` 门禁;普通维护页为 `maintenance-crud-v1`,树形维护页为 `tree-crud-v1`。
|
||||||
|
- `TEST` 草稿必须通过 `smoke-plan` 和 `render-plan`;`renderTests` 是后续 Playwright 渲染验收的输入,需包含 previewUrl、预期组件、列、动作、数据 API 和关键文本。
|
||||||
|
|
||||||
|
## 页面 schema 校验
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://localhost:8084/api/page/schema/components
|
||||||
|
|
||||||
|
curl -X POST http://localhost:8084/api/page/schema/validate \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
--data-binary @target/ai-runs/page-schema.json
|
||||||
|
```
|
||||||
|
|
||||||
|
设计器保存 overlay 时也会执行同一套 typed schema 校验;未注册组件或不支持的 `actionType` 会被拒绝。
|
||||||
|
|
||||||
|
## AI 工具权限检查
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://localhost:8084/api/ai/tools
|
||||||
|
curl http://localhost:8084/api/ai/employees
|
||||||
|
|
||||||
|
curl -X POST http://localhost:8084/api/ai/tools/access-check \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"employeeId":"agent-developer","toolName":"local.apply","grantedScopes":["ai:local:apply"],"targetEnv":"local","productionWrite":false}'
|
||||||
|
```
|
||||||
|
|
||||||
|
本地 apply、smoke 等工具只允许本地目标;生产写默认被阻断,线上部署仍走人工发布。
|
||||||
|
|
||||||
|
## 失败处理
|
||||||
|
|
||||||
|
1. 查看输出 JSON 中的 apply/smoke/repair evidence。
|
||||||
|
2. 如果自动修复已尝试但失败,基于 evidence 修改本地代码或元数据生成逻辑。
|
||||||
|
3. 重新运行本地 auto-develop。
|
||||||
|
4. 不直接连接线上库修复。
|
||||||
49
docs/skills/eip4-env-manage.md
Normal file
49
docs/skills/eip4-env-manage.md
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
# Skill: eip4-env-manage
|
||||||
|
|
||||||
|
## 触发场景
|
||||||
|
|
||||||
|
- 用户要求启动、检查或切换 EIP4 环境。
|
||||||
|
- 用户要求 Agent 在本地验证功能。
|
||||||
|
- 用户要求确认当前服务是否可被 AI 自动开发链路使用。
|
||||||
|
|
||||||
|
## 操作规则
|
||||||
|
|
||||||
|
1. 确认当前目录是否是独立 worktree,避免污染用户正在做的任务。
|
||||||
|
2. 使用 JDK 21,不能使用 JDK 26。
|
||||||
|
3. 默认本地 profile:
|
||||||
|
- `local`: `http://localhost:8084`
|
||||||
|
- `dev`: `http://localhost:8093`
|
||||||
|
4. 使用 CLI 探测环境:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar env add \
|
||||||
|
--name local \
|
||||||
|
--base-url http://localhost:8084 \
|
||||||
|
--kind local \
|
||||||
|
--use
|
||||||
|
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar env status
|
||||||
|
```
|
||||||
|
|
||||||
|
5. 如果服务未启动,优先使用重新打包后的 jar:
|
||||||
|
|
||||||
|
```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
|
||||||
|
```
|
||||||
|
|
||||||
|
## 禁止事项
|
||||||
|
|
||||||
|
- 不在用户原始任务目录中直接改动或启动长时间任务,除非用户明确要求。
|
||||||
|
- 不把线上环境设置为默认写入目标。
|
||||||
|
- 不跳过 JDK 版本检查。
|
||||||
|
- 显式选择非当前 env 执行 AI 或发布类命令时,必须要求 `--yes` 或等效人工确认。
|
||||||
|
|
||||||
|
## 常用命令
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar env list
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar env current
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar env use --name local
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar env status --all
|
||||||
|
```
|
||||||
96
docs/skills/eip4-release-manage.md
Normal file
96
docs/skills/eip4-release-manage.md
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
# Skill: eip4-release-manage
|
||||||
|
|
||||||
|
## 触发场景
|
||||||
|
|
||||||
|
- 用户要求生成部署包。
|
||||||
|
- 用户要求发布 AI 生成的功能。
|
||||||
|
- 用户要求线上 bug 修复或回滚。
|
||||||
|
|
||||||
|
## 当前边界
|
||||||
|
|
||||||
|
当前 `platform-ai` 只生成线上人工部署包,不自动连接线上环境执行写操作。这是设计边界,不是功能缺失。
|
||||||
|
|
||||||
|
## 发布前检查
|
||||||
|
|
||||||
|
1. 确认本地 auto-develop 已通过。
|
||||||
|
2. 使用 CLI 生成 AI 功能包快照:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai feature-package \
|
||||||
|
--base-url http://localhost:8084 \
|
||||||
|
--task-id ait-xxx \
|
||||||
|
--change-set-id aics-xxx \
|
||||||
|
--output target/ai-runs/feature-package.json
|
||||||
|
```
|
||||||
|
|
||||||
|
3. 保存里程碑 revision:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar ai revision \
|
||||||
|
--base-url http://localhost:8084 \
|
||||||
|
--task-id ait-xxx \
|
||||||
|
--package-id aipkg-xxx \
|
||||||
|
--note "本地门禁通过,待人工部署" \
|
||||||
|
--output target/ai-runs/revision.json
|
||||||
|
```
|
||||||
|
|
||||||
|
4. 运行离线发布校验:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar release verify \
|
||||||
|
--package-file target/ai-runs/feature-package.json
|
||||||
|
```
|
||||||
|
|
||||||
|
5. 导出 `.eip4pkg.json` 并做导入预览:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar release export \
|
||||||
|
--package-file target/ai-runs/feature-package.json \
|
||||||
|
--output target/ai-runs/feature-package.eip4pkg.json
|
||||||
|
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar release import-preview \
|
||||||
|
--package-file target/ai-runs/feature-package.eip4pkg.json
|
||||||
|
```
|
||||||
|
|
||||||
|
6. 如存在上一版功能包,先做离线差异检查:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar release diff \
|
||||||
|
--left target/ai-runs/feature-package-old.json \
|
||||||
|
--right target/ai-runs/feature-package.json
|
||||||
|
```
|
||||||
|
|
||||||
|
7. 需要回滚预案时,只生成回滚计划文件:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
java -jar platform-cli/target/platform-cli-0.1.0-SNAPSHOT.jar release rollback-plan \
|
||||||
|
--package-file target/ai-runs/feature-package.eip4pkg.json \
|
||||||
|
--output target/ai-runs/rollback-plan.json
|
||||||
|
```
|
||||||
|
|
||||||
|
8. 确认部署包包含:
|
||||||
|
- manifest
|
||||||
|
- SQL 草案
|
||||||
|
- rollback SQL
|
||||||
|
- 本地 apply evidence
|
||||||
|
- smoke evidence
|
||||||
|
- repair evidence
|
||||||
|
9. 确认部署包需要人工审批。
|
||||||
|
10. 如果包含 `${parentMenuId}` 等占位符,必须人工替换并复核;`release verify` 默认会阻断这类包。
|
||||||
|
|
||||||
|
## 线上 bug 修复路径
|
||||||
|
|
||||||
|
1. 收集线上错误日志、请求样本或人工复现步骤。
|
||||||
|
2. 在本地创建新的 AI 修复任务。
|
||||||
|
3. 本地执行 apply/smoke/repair。
|
||||||
|
4. 生成新的部署包。
|
||||||
|
5. 人工审核后走现有上线流程。
|
||||||
|
|
||||||
|
## 禁止事项
|
||||||
|
|
||||||
|
- 不让 Agent 默认直接写线上数据库。
|
||||||
|
- 不绕过部署包和人审。
|
||||||
|
- 不把 smoke 失败的变更包交给发布流程。
|
||||||
|
- 不发布 `release verify` 失败的功能包。
|
||||||
|
- 不把 `import-preview` 当成导入或启用;它只是离线检查。
|
||||||
|
- 不把 `rollback-plan` 当成回滚执行;它只生成计划和 SQL 清单。
|
||||||
129
docs/sql/SYS_AI_AGENT.sql
Normal file
129
docs/sql/SYS_AI_AGENT.sql
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
-- ============================================================================
|
||||||
|
-- 生产建表脚本: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_feature_package (
|
||||||
|
package_id character varying(64) NOT NULL,
|
||||||
|
task_id character varying(64) NOT NULL,
|
||||||
|
change_set_id character varying(64) NOT NULL,
|
||||||
|
status character varying(32) NOT NULL,
|
||||||
|
manifest_json jsonb NOT NULL,
|
||||||
|
deployment_package_json jsonb NOT NULL,
|
||||||
|
created_at bigint NOT NULL,
|
||||||
|
CONSTRAINT pk_sys_ai_feature_package PRIMARY KEY (package_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sys_ai_revision (
|
||||||
|
revision_id character varying(64) NOT NULL,
|
||||||
|
task_id character varying(64) NOT NULL,
|
||||||
|
package_id character varying(64) NOT NULL,
|
||||||
|
status character varying(32) NOT NULL,
|
||||||
|
note text NOT NULL,
|
||||||
|
snapshot_json jsonb NOT NULL,
|
||||||
|
created_at bigint NOT NULL,
|
||||||
|
CONSTRAINT pk_sys_ai_revision PRIMARY KEY (revision_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_feature_package_task ON sys_ai_feature_package (task_id, created_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sys_ai_revision_task ON sys_ai_revision (task_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_feature_package IS 'AI Agent 功能包快照。封装部署包、manifest 和本地证据,用于人审/导出/版本里程碑';
|
||||||
|
COMMENT ON TABLE sys_ai_revision IS 'AI Agent 里程碑版本。保存功能包快照,后续用于差异比较和回滚';
|
||||||
|
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_feature_package.manifest_json IS '功能包 manifest,包含包 id、变更包 id、证据数量和发布边界';
|
||||||
|
COMMENT ON COLUMN sys_ai_feature_package.deployment_package_json IS '部署包完整 JSON 快照';
|
||||||
|
COMMENT ON COLUMN sys_ai_revision.snapshot_json IS '里程碑快照 JSON,当前保存 AiFeaturePackage';
|
||||||
|
COMMENT ON COLUMN sys_ai_audit_log.details_json IS '操作详情 JSON';
|
||||||
@@ -18,7 +18,8 @@ eip4-platform(Maven 多模块单体)
|
|||||||
├── platform-auth P2:组织/权限/数据权限真实现(替换 PoC 桩)
|
├── platform-auth P2:组织/权限/数据权限真实现(替换 PoC 桩)
|
||||||
├── platform-flow-gateway Flowable REST 客户端、待办聚合、3 个 handler bean
|
├── platform-flow-gateway Flowable REST 客户端、待办聚合、3 个 handler bean
|
||||||
├── platform-converter 模板转换器 + S3 脚本改写器(可独立 CLI 跑批)
|
├── platform-converter 模板转换器 + S3 脚本改写器(可独立 CLI 跑批)
|
||||||
├── platform-ai MCP Server、schema 双闸校验
|
├── platform-ai AI Agent 开发底座、schema 双闸校验、自动修复、本地门禁和人工部署包
|
||||||
|
├── platform-cli EIP4 Agent 受控命令入口:环境探测、AI 自动开发、后续发布编排
|
||||||
├── platform-parity C1 逐行对拍框架:录制/重放/逐行 diff(P1 一级交付物,可独立 CLI 跑批)
|
├── platform-parity C1 逐行对拍框架:录制/重放/逐行 diff(P1 一级交付物,可独立 CLI 跑批)
|
||||||
└── platform-app Spring Boot 启动器,组装上述模块
|
└── platform-app Spring Boot 启动器,组装上述模块
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -13,5 +13,12 @@
|
|||||||
<description>P5 占位:MCP Server、schema 双闸校验</description>
|
<description>P5 占位:MCP Server、schema 双闸校验</description>
|
||||||
<dependencies>
|
<dependencies>
|
||||||
<dependency><groupId>com.eip4</groupId><artifactId>platform-legacy-core</artifactId></dependency>
|
<dependency><groupId>com.eip4</groupId><artifactId>platform-legacy-core</artifactId></dependency>
|
||||||
|
<dependency><groupId>com.eip4</groupId><artifactId>platform-converter</artifactId></dependency>
|
||||||
|
<dependency><groupId>com.eip4</groupId><artifactId>platform-metadata</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springdoc</groupId><artifactId>springdoc-openapi-starter-webmvc-ui</artifactId></dependency>
|
||||||
|
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId></dependency>
|
||||||
|
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</project>
|
</project>
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiAgentRepairContext(
|
||||||
|
String taskId,
|
||||||
|
String changeSetId,
|
||||||
|
AiRepairPlan repairPlan,
|
||||||
|
List<AiDraft> drafts) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiAgentRepairResult(
|
||||||
|
String status,
|
||||||
|
List<AiRepairDraftPatch> draftPatches,
|
||||||
|
List<String> messages) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiApplyRun(
|
||||||
|
String taskId,
|
||||||
|
String changeSetId,
|
||||||
|
String baseUrl,
|
||||||
|
String status,
|
||||||
|
long startedAt,
|
||||||
|
long finishedAt,
|
||||||
|
List<AiApplyStepResult> steps,
|
||||||
|
AiSmokeRun smokeRun) {
|
||||||
|
|
||||||
|
public boolean passed() {
|
||||||
|
boolean stepsPassed = steps != null && steps.stream()
|
||||||
|
.allMatch(s -> "APPLIED".equals(s.status()) || "SKIPPED".equals(s.status()));
|
||||||
|
return stepsPassed && smokeRun != null && smokeRun.passed();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public record AiApplyStepResult(
|
||||||
|
String id,
|
||||||
|
AiArtifactType artifactType,
|
||||||
|
String target,
|
||||||
|
String status,
|
||||||
|
String message,
|
||||||
|
Map<String, Object> details) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Agent 允许产生的受控产物类型。
|
||||||
|
*
|
||||||
|
* <p>这里刻意不用自由字符串:后续 MCP 工具、发布门禁和审计都需要按类型施加不同规则。
|
||||||
|
*/
|
||||||
|
public enum AiArtifactType {
|
||||||
|
ENTITY,
|
||||||
|
PAGE_SCHEMA,
|
||||||
|
SERVICEFLOW,
|
||||||
|
MENU,
|
||||||
|
CODE,
|
||||||
|
TEST
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public record AiAuditEntry(
|
||||||
|
String id,
|
||||||
|
String taskId,
|
||||||
|
String action,
|
||||||
|
String actor,
|
||||||
|
long createdAt,
|
||||||
|
Map<String, Object> details) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
public record AiAutoDevelopmentRequest(
|
||||||
|
AiFeatureRequest feature,
|
||||||
|
String baseUrl,
|
||||||
|
Boolean generateDeploymentPackage,
|
||||||
|
Integer maxRepairAttempts) {
|
||||||
|
|
||||||
|
public boolean shouldGenerateDeploymentPackage() {
|
||||||
|
return generateDeploymentPackage == null || generateDeploymentPackage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int repairAttemptLimit() {
|
||||||
|
if (maxRepairAttempts == null) {
|
||||||
|
return 2;
|
||||||
|
}
|
||||||
|
return Math.max(0, Math.min(5, maxRepairAttempts));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiAutoDevelopmentRun(
|
||||||
|
String taskId,
|
||||||
|
String changeSetId,
|
||||||
|
String originalChangeSetId,
|
||||||
|
String status,
|
||||||
|
long startedAt,
|
||||||
|
long finishedAt,
|
||||||
|
AiFeatureDevelopment development,
|
||||||
|
AiReleasePlan releasePlan,
|
||||||
|
AiApplyRun applyRun,
|
||||||
|
AiDeploymentPackage deploymentPackage,
|
||||||
|
List<AiRepairExecution> repairExecutions,
|
||||||
|
List<String> messages) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public record AiChangeSet(
|
||||||
|
String id,
|
||||||
|
String taskId,
|
||||||
|
String status,
|
||||||
|
long createdAt,
|
||||||
|
List<String> draftIds,
|
||||||
|
Map<String, Object> summary) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public record AiDeploymentPackage(
|
||||||
|
String taskId,
|
||||||
|
String changeSetId,
|
||||||
|
String status,
|
||||||
|
boolean requiresHumanApproval,
|
||||||
|
long generatedAt,
|
||||||
|
Map<String, Object> manifest,
|
||||||
|
List<String> sqlStatements,
|
||||||
|
List<String> rollbackSqlStatements,
|
||||||
|
List<String> warnings,
|
||||||
|
List<AiRunRecord> runEvidence) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
|
||||||
|
public record AiDraft(
|
||||||
|
String id,
|
||||||
|
String taskId,
|
||||||
|
AiArtifactType artifactType,
|
||||||
|
String targetId,
|
||||||
|
JsonNode payload,
|
||||||
|
long createdAt,
|
||||||
|
List<AiGateResult> gates,
|
||||||
|
Map<String, Object> metadata) {
|
||||||
|
|
||||||
|
public boolean passed() {
|
||||||
|
return gates == null || gates.stream().allMatch(AiGateResult::passed);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiEmployeeDefinition(
|
||||||
|
String id,
|
||||||
|
String name,
|
||||||
|
String role,
|
||||||
|
List<String> toolNames,
|
||||||
|
List<String> requiredScopes,
|
||||||
|
List<String> policies) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiFeatureDevelopment(
|
||||||
|
AiTask task,
|
||||||
|
List<AiDraft> drafts,
|
||||||
|
AiChangeSet changeSet) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
public record AiFeatureField(
|
||||||
|
String column,
|
||||||
|
String label,
|
||||||
|
String type,
|
||||||
|
Integer length,
|
||||||
|
Boolean required) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public record AiFeaturePackage(
|
||||||
|
String id,
|
||||||
|
String taskId,
|
||||||
|
String changeSetId,
|
||||||
|
String status,
|
||||||
|
long createdAt,
|
||||||
|
Map<String, Object> manifest,
|
||||||
|
AiDeploymentPackage deploymentPackage) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiFeatureRequest(
|
||||||
|
String objective,
|
||||||
|
String featureName,
|
||||||
|
String tableName,
|
||||||
|
String entityName,
|
||||||
|
String templateId,
|
||||||
|
String menuName,
|
||||||
|
List<AiFeatureField> fields,
|
||||||
|
String pageRecipe) {
|
||||||
|
|
||||||
|
public AiFeatureRequest(String objective,
|
||||||
|
String featureName,
|
||||||
|
String tableName,
|
||||||
|
String entityName,
|
||||||
|
String templateId,
|
||||||
|
String menuName,
|
||||||
|
List<AiFeatureField> fields) {
|
||||||
|
this(objective, featureName, tableName, entityName, templateId, menuName, fields, null);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiGateResult(
|
||||||
|
String name,
|
||||||
|
boolean passed,
|
||||||
|
List<String> messages) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
|
||||||
|
public record AiGeneratedDraft(
|
||||||
|
AiArtifactType artifactType,
|
||||||
|
String targetId,
|
||||||
|
JsonNode payload,
|
||||||
|
Map<String, Object> metadata) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public record AiReleasePlan(
|
||||||
|
String taskId,
|
||||||
|
String changeSetId,
|
||||||
|
String status,
|
||||||
|
boolean requiresHumanApproval,
|
||||||
|
Map<String, Object> environmentPolicy,
|
||||||
|
List<AiReleaseStep> steps,
|
||||||
|
List<String> rollbackNotes) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public record AiReleaseStep(
|
||||||
|
String id,
|
||||||
|
AiArtifactType artifactType,
|
||||||
|
String title,
|
||||||
|
String mode,
|
||||||
|
String target,
|
||||||
|
String action,
|
||||||
|
Map<String, Object> details) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public record AiRepairAction(
|
||||||
|
String id,
|
||||||
|
String source,
|
||||||
|
String actionType,
|
||||||
|
String artifactType,
|
||||||
|
String targetId,
|
||||||
|
boolean automated,
|
||||||
|
String rationale,
|
||||||
|
Map<String, Object> details) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
|
||||||
|
public record AiRepairDraftPatch(
|
||||||
|
AiArtifactType artifactType,
|
||||||
|
String targetId,
|
||||||
|
JsonNode payload,
|
||||||
|
Map<String, Object> metadata) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiRepairExecution(
|
||||||
|
String taskId,
|
||||||
|
String changeSetId,
|
||||||
|
String status,
|
||||||
|
long startedAt,
|
||||||
|
long finishedAt,
|
||||||
|
AiRepairPlan repairPlan,
|
||||||
|
List<AiDraft> generatedDrafts,
|
||||||
|
AiChangeSet repairedChangeSet,
|
||||||
|
AiApplyRun retryApplyRun,
|
||||||
|
AiDeploymentPackage deploymentPackage,
|
||||||
|
List<String> messages) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
public record AiRepairExecutionRequest(String baseUrl) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiRepairPlan(
|
||||||
|
String taskId,
|
||||||
|
String changeSetId,
|
||||||
|
String sourceRunId,
|
||||||
|
String status,
|
||||||
|
long generatedAt,
|
||||||
|
List<AiRepairAction> actions,
|
||||||
|
List<String> messages) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
|
||||||
|
public record AiRevision(
|
||||||
|
String id,
|
||||||
|
String taskId,
|
||||||
|
String packageId,
|
||||||
|
String status,
|
||||||
|
String note,
|
||||||
|
long createdAt,
|
||||||
|
JsonNode snapshot) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
|
||||||
|
public record AiRunRecord(
|
||||||
|
String id,
|
||||||
|
String taskId,
|
||||||
|
String changeSetId,
|
||||||
|
String runType,
|
||||||
|
String status,
|
||||||
|
long createdAt,
|
||||||
|
JsonNode payload) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
public record AiSmokeResult(
|
||||||
|
String name,
|
||||||
|
String method,
|
||||||
|
String url,
|
||||||
|
int expectedHttpStatus,
|
||||||
|
int actualHttpStatus,
|
||||||
|
boolean passed,
|
||||||
|
long durationMillis,
|
||||||
|
String error,
|
||||||
|
String responseSnippet) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiSmokeRun(
|
||||||
|
String taskId,
|
||||||
|
String changeSetId,
|
||||||
|
String baseUrl,
|
||||||
|
String status,
|
||||||
|
long startedAt,
|
||||||
|
long finishedAt,
|
||||||
|
List<AiSmokeResult> results) {
|
||||||
|
|
||||||
|
public boolean passed() {
|
||||||
|
return results != null && results.stream().allMatch(AiSmokeResult::passed);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiTask(
|
||||||
|
String id,
|
||||||
|
String objective,
|
||||||
|
String status,
|
||||||
|
long createdAt,
|
||||||
|
long updatedAt,
|
||||||
|
List<String> plan) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiToolAccessDecision(
|
||||||
|
boolean allowed,
|
||||||
|
List<String> missingScopes,
|
||||||
|
List<String> blockers,
|
||||||
|
AiToolDefinition tool,
|
||||||
|
AiEmployeeDefinition employee) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiToolAccessRequest(
|
||||||
|
String employeeId,
|
||||||
|
String toolName,
|
||||||
|
List<String> grantedScopes,
|
||||||
|
String targetEnv,
|
||||||
|
boolean productionWrite) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package com.eip4.platform.ai.model;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record AiToolDefinition(
|
||||||
|
String name,
|
||||||
|
String category,
|
||||||
|
String description,
|
||||||
|
List<String> operations,
|
||||||
|
List<String> requiredScopes,
|
||||||
|
boolean localOnly,
|
||||||
|
boolean productionWriteAllowed) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import com.eip4.platform.ai.model.AiAgentRepairContext;
|
||||||
|
import com.eip4.platform.ai.model.AiAgentRepairResult;
|
||||||
|
|
||||||
|
public interface AiAgentRepairExecutor {
|
||||||
|
|
||||||
|
AiAgentRepairResult repair(AiAgentRepairContext context);
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,421 @@
|
|||||||
|
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.eip4.platform.metadata.schema.blueprint.PageBlueprint;
|
||||||
|
import com.eip4.platform.metadata.schema.blueprint.PageBlueprintCompiler;
|
||||||
|
import com.eip4.platform.metadata.schema.blueprint.PageBlueprintField;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class AiFeatureDraftGenerator {
|
||||||
|
|
||||||
|
private static final String ENTITY_ID_PLACEHOLDER = "${entityId}";
|
||||||
|
private static final Set<String> SYSTEM_COLUMNS = Set.of(
|
||||||
|
"VERSION", "CREATETIME", "UPDATETIME", "CREATEBY", "UPDATEBY", "ISACTIVE");
|
||||||
|
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
private final PageBlueprintCompiler pageBlueprintCompiler;
|
||||||
|
|
||||||
|
public AiFeatureDraftGenerator(ObjectMapper objectMapper) {
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
this.pageBlueprintCompiler = new PageBlueprintCompiler(objectMapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<AiGeneratedDraft> generate(AiFeatureRequest request) {
|
||||||
|
FeatureSpec spec = normalize(request);
|
||||||
|
PageBlueprint pageBlueprint = pageBlueprint(spec);
|
||||||
|
List<AiGeneratedDraft> drafts = new ArrayList<>();
|
||||||
|
drafts.add(new AiGeneratedDraft(AiArtifactType.ENTITY, spec.tableName(),
|
||||||
|
entityPayload(spec), metadata("entity-meta", "/api/meta/entity")));
|
||||||
|
drafts.add(new AiGeneratedDraft(AiArtifactType.PAGE_SCHEMA, spec.templateId(),
|
||||||
|
pageBlueprintCompiler.compile(pageBlueprint), pageSchemaMetadata(pageBlueprint)));
|
||||||
|
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 PageBlueprint pageBlueprint(FeatureSpec spec) {
|
||||||
|
List<PageBlueprintField> fields = new ArrayList<>();
|
||||||
|
for (FieldSpec field : spec.fields()) {
|
||||||
|
boolean treeParentField = PageBlueprint.RECIPE_TREE_CRUD.equals(spec.pageRecipe())
|
||||||
|
&& "PARENTID".equals(field.column());
|
||||||
|
fields.add(new PageBlueprintField(field.column(), field.label(), field.type(),
|
||||||
|
field.required(), !treeParentField, true));
|
||||||
|
}
|
||||||
|
return new PageBlueprint(PageBlueprint.VERSION, spec.pageRecipe(),
|
||||||
|
spec.templateId(), spec.featureName(), spec.tableName(), spec.entityName(),
|
||||||
|
spec.tableName() + "_ID", displayColumn(spec), fields,
|
||||||
|
true, true, true, 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
if (PageBlueprint.RECIPE_TREE_CRUD.equals(spec.pageRecipe())) {
|
||||||
|
addSmoke(tests, "entity-tree", "GET", "/api/entity/" + spec.tableName()
|
||||||
|
+ "/tree?parentKey=PARENTID&idKey=" + spec.tableName() + "_ID&perPage=2000", 200);
|
||||||
|
} else {
|
||||||
|
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 renderTests = root.putArray("renderTests");
|
||||||
|
addRender(renderTests, spec);
|
||||||
|
ArrayNode manual = root.putArray("manualGates");
|
||||||
|
manual.add("确认实体字段、菜单位置、权限角色和服务流写入策略");
|
||||||
|
manual.add("按 renderTests 使用 Playwright 渲染页面,确认组件、列和操作按钮符合 recipe");
|
||||||
|
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 void addRender(ArrayNode renderTests, FeatureSpec spec) {
|
||||||
|
ObjectNode render = renderTests.addObject();
|
||||||
|
render.put("name", "page-render");
|
||||||
|
render.put("recipe", spec.pageRecipe());
|
||||||
|
render.put("schemaUrl", "/api/page/schema/" + spec.templateId());
|
||||||
|
render.put("previewUrl", "/amis.html?schema=" + spec.templateId());
|
||||||
|
render.put("expectedRootType", "page");
|
||||||
|
render.put("expectedBodyType", "crud");
|
||||||
|
render.put("expectedCrudName", expectedCrudName(spec));
|
||||||
|
render.put("expectedApi", expectedPageApi(spec));
|
||||||
|
if (PageBlueprint.RECIPE_TREE_CRUD.equals(spec.pageRecipe())) {
|
||||||
|
render.put("childrenColumnName", "children");
|
||||||
|
}
|
||||||
|
ArrayNode components = render.putArray("expectedComponents");
|
||||||
|
components.add("page");
|
||||||
|
components.add("crud");
|
||||||
|
components.add("form");
|
||||||
|
components.add("button");
|
||||||
|
addExpectedColumns(render.putArray("expectedColumns"), spec);
|
||||||
|
addExpectedActions(render.putArray("expectedActions"), spec);
|
||||||
|
ArrayNode texts = render.putArray("expectedTexts");
|
||||||
|
texts.add(spec.featureName());
|
||||||
|
texts.add(spec.entityName());
|
||||||
|
for (FieldSpec field : spec.fields()) {
|
||||||
|
if (!"PARENTID".equals(field.column())) {
|
||||||
|
texts.add(field.label());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addExpectedColumns(ArrayNode columns, FeatureSpec spec) {
|
||||||
|
for (FieldSpec field : spec.fields()) {
|
||||||
|
if ("PARENTID".equals(field.column())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ObjectNode column = columns.addObject();
|
||||||
|
column.put("name", field.column());
|
||||||
|
column.put("label", field.label());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addExpectedActions(ArrayNode actions, FeatureSpec spec) {
|
||||||
|
if (PageBlueprint.RECIPE_TREE_CRUD.equals(spec.pageRecipe())) {
|
||||||
|
actions.add("新增顶级" + spec.entityName());
|
||||||
|
actions.add("刷新");
|
||||||
|
actions.add("加子" + spec.entityName());
|
||||||
|
} else {
|
||||||
|
actions.add("新增");
|
||||||
|
}
|
||||||
|
actions.add("编辑");
|
||||||
|
actions.add("删除");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String expectedCrudName(FeatureSpec spec) {
|
||||||
|
return lowerCamel(spec.tableName())
|
||||||
|
+ (PageBlueprint.RECIPE_TREE_CRUD.equals(spec.pageRecipe()) ? "TreeCrud" : "Crud");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String expectedPageApi(FeatureSpec spec) {
|
||||||
|
if (PageBlueprint.RECIPE_TREE_CRUD.equals(spec.pageRecipe())) {
|
||||||
|
return "/api/entity/" + spec.tableName()
|
||||||
|
+ "/tree?parentKey=PARENTID&idKey=" + spec.tableName() + "_ID&perPage=2000";
|
||||||
|
}
|
||||||
|
return "/api/entity/" + spec.tableName() + "/list?page=${page}&perPage=${perPage}";
|
||||||
|
}
|
||||||
|
|
||||||
|
private ObjectNode sampleEntityBody(FeatureSpec spec) {
|
||||||
|
ObjectNode body = objectMapper.createObjectNode();
|
||||||
|
for (FieldSpec field : spec.fields()) {
|
||||||
|
if ("PARENTID".equals(field.column())) {
|
||||||
|
body.put(field.column(), "");
|
||||||
|
} else 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);
|
||||||
|
String pageRecipe = normalizePageRecipe(request == null ? null : request.pageRecipe());
|
||||||
|
List<FieldSpec> fields = normalizeFields(request == null ? null : request.fields(), pageRecipe);
|
||||||
|
return new FeatureSpec(feature, table, entityName, templateId, menuName, pageRecipe, fields);
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<FieldSpec> normalizeFields(List<AiFeatureField> input, String pageRecipe) {
|
||||||
|
List<AiFeatureField> raw = input == null ? List.of() : input;
|
||||||
|
List<FieldSpec> out = new ArrayList<>();
|
||||||
|
Set<String> seen = new LinkedHashSet<>();
|
||||||
|
for (AiFeatureField f : raw) {
|
||||||
|
String column = normalizeColumn(f == null ? null : f.column());
|
||||||
|
if (column == null || SYSTEM_COLUMNS.contains(column) || !seen.add(column)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String type = normalizeType(f.type());
|
||||||
|
Integer length = normalizeLength(type, f.length());
|
||||||
|
String label = firstText(f.label(), column);
|
||||||
|
out.add(new FieldSpec(column, label, type, length, Boolean.TRUE.equals(f.required())));
|
||||||
|
}
|
||||||
|
if (out.isEmpty()) {
|
||||||
|
out.add(new FieldSpec("NAME", "名称", "string", 100, true));
|
||||||
|
out.add(new FieldSpec("DESCRIPTION", "描述", "string", 500, false));
|
||||||
|
}
|
||||||
|
if (PageBlueprint.RECIPE_TREE_CRUD.equals(pageRecipe) && seen.add("PARENTID")) {
|
||||||
|
out.add(new FieldSpec("PARENTID", "上级", "string", 64, false));
|
||||||
|
}
|
||||||
|
return List.copyOf(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String normalizePageRecipe(String raw) {
|
||||||
|
String recipe = raw == null ? "" : raw.trim();
|
||||||
|
if (recipe.isBlank()) {
|
||||||
|
return PageBlueprint.RECIPE_MAINTENANCE_CRUD;
|
||||||
|
}
|
||||||
|
if (PageBlueprint.RECIPE_MAINTENANCE_CRUD.equals(recipe)
|
||||||
|
|| PageBlueprint.RECIPE_TREE_CRUD.equals(recipe)) {
|
||||||
|
return recipe;
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("Unsupported pageRecipe: " + recipe);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 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 firstText(String... values) {
|
||||||
|
for (String value : values) {
|
||||||
|
if (value != null && !value.isBlank()) {
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, Object> metadata(String generatorStep, String publishTarget) {
|
||||||
|
Map<String, Object> metadata = new LinkedHashMap<>();
|
||||||
|
metadata.put("source", "ai-agent");
|
||||||
|
metadata.put("generator", "deterministic-feature-v1");
|
||||||
|
metadata.put("generatorStep", generatorStep);
|
||||||
|
metadata.put("publishTarget", publishTarget);
|
||||||
|
return metadata;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String 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();
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private Map<String, Object> pageSchemaMetadata(PageBlueprint pageBlueprint) {
|
||||||
|
Map<String, Object> metadata = metadata("page-schema", "sys_page_schema");
|
||||||
|
metadata.put("pageRecipe", pageBlueprint.recipe());
|
||||||
|
metadata.put("pageBlueprintVersion", pageBlueprint.schemaVersion());
|
||||||
|
metadata.put("pageBlueprint", objectMapper.convertValue(pageBlueprint, Map.class));
|
||||||
|
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,
|
||||||
|
String pageRecipe,
|
||||||
|
List<FieldSpec> fields) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private record FieldSpec(
|
||||||
|
String column,
|
||||||
|
String label,
|
||||||
|
String type,
|
||||||
|
Integer length,
|
||||||
|
boolean required) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
public record AiHttpResponse(
|
||||||
|
int statusCode,
|
||||||
|
String body) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.eip4.platform.ai.model.AiAgentRepairContext;
|
||||||
|
import com.eip4.platform.ai.model.AiRepairDraftPatch;
|
||||||
|
|
||||||
|
public interface AiLlmRepairClient {
|
||||||
|
|
||||||
|
List<AiRepairDraftPatch> repair(AiAgentRepairContext context);
|
||||||
|
}
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import com.eip4.platform.ai.model.AiApplyStepResult;
|
||||||
|
import com.eip4.platform.ai.model.AiArtifactType;
|
||||||
|
import com.eip4.platform.ai.model.AiDraft;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class AiLocalReleaseExecutor {
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
private final AiSmokeHttpClient httpClient;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
public AiLocalReleaseExecutor(JdbcTemplate jdbcTemplate, AiSmokeHttpClient httpClient, ObjectMapper objectMapper) {
|
||||||
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<AiApplyStepResult> apply(String baseUrl, List<AiDraft> drafts) {
|
||||||
|
URI base = safeLocalBase(baseUrl);
|
||||||
|
ApplyContext ctx = new ApplyContext(base);
|
||||||
|
List<AiApplyStepResult> results = new ArrayList<>();
|
||||||
|
for (AiDraft draft : drafts.stream().sorted(Comparator.comparingInt(d -> releaseOrder(d.artifactType()))).toList()) {
|
||||||
|
if (draft.artifactType() == AiArtifactType.TEST) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
AiApplyStepResult result = applyOne(ctx, draft, results.size() + 1);
|
||||||
|
results.add(result);
|
||||||
|
if ("FAILED".equals(result.status())) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return List.copyOf(results);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int releaseOrder(AiArtifactType type) {
|
||||||
|
return switch (type) {
|
||||||
|
case ENTITY -> 10;
|
||||||
|
case SERVICEFLOW -> 20;
|
||||||
|
case PAGE_SCHEMA -> 30;
|
||||||
|
case MENU -> 40;
|
||||||
|
case TEST -> 50;
|
||||||
|
case CODE -> 60;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private AiApplyStepResult applyOne(ApplyContext ctx, AiDraft draft, int index) {
|
||||||
|
try {
|
||||||
|
return switch (draft.artifactType()) {
|
||||||
|
case ENTITY -> applyEntity(ctx, draft, index);
|
||||||
|
case SERVICEFLOW -> applyServiceFlows(ctx, draft, index);
|
||||||
|
case PAGE_SCHEMA -> applyPageSchema(draft, index);
|
||||||
|
case MENU -> applyMenu(ctx, draft, index);
|
||||||
|
case CODE -> skipped(index, draft, "代码草稿暂不由平台运行时应用");
|
||||||
|
case TEST -> skipped(index, draft, "TEST 由 smoke runner 执行");
|
||||||
|
};
|
||||||
|
} catch (Exception ex) {
|
||||||
|
return new AiApplyStepResult("apply-" + index, draft.artifactType(), draft.targetId(), "FAILED",
|
||||||
|
ex.getClass().getSimpleName() + ": " + String.valueOf(ex.getMessage()), Map.of());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private AiApplyStepResult applyEntity(ApplyContext ctx, AiDraft draft, int index) throws Exception {
|
||||||
|
String tableName = draft.payload().path("tablename").asText(draft.targetId()).toUpperCase(Locale.ROOT);
|
||||||
|
AiHttpResponse response = httpClient.exchange("POST", ctx.base().resolve("/api/meta/entity"),
|
||||||
|
draft.payload(), Duration.ofSeconds(20));
|
||||||
|
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||||
|
return failed(index, draft, "实体发布 HTTP " + response.statusCode(), Map.of("response", response.body()));
|
||||||
|
}
|
||||||
|
JsonNode root = objectMapper.readTree(response.body());
|
||||||
|
if (root.path("status").asInt(1) != 0) {
|
||||||
|
String message = root.path("msg").asText("unknown");
|
||||||
|
if (message.contains("实体已存在")) {
|
||||||
|
List<String> ids = jdbcTemplate.queryForList(
|
||||||
|
"SELECT TRIM(sys_entity_id) FROM sys_entity WHERE tablename=? AND isactive=1",
|
||||||
|
String.class, tableName);
|
||||||
|
if (!ids.isEmpty()) {
|
||||||
|
ctx.entityId(ids.get(0));
|
||||||
|
ctx.tableName(tableName);
|
||||||
|
return applied(index, draft, "实体已存在,复用本地 entityId",
|
||||||
|
Map.of("entityId", ctx.entityId(), "tableName", ctx.tableName(), "idempotent", true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return failed(index, draft, "实体发布失败: " + message, Map.of());
|
||||||
|
}
|
||||||
|
String entityId = root.path("data").path("entityId").asText("");
|
||||||
|
if (entityId.isBlank()) {
|
||||||
|
return failed(index, draft, "实体发布响应缺 data.entityId", Map.of());
|
||||||
|
}
|
||||||
|
ctx.entityId(entityId);
|
||||||
|
ctx.tableName(tableName);
|
||||||
|
return applied(index, draft, "实体已创建", Map.of("entityId", entityId, "tableName", ctx.tableName()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private AiApplyStepResult applyServiceFlows(ApplyContext ctx, AiDraft draft, int index) {
|
||||||
|
if (ctx.entityId().isBlank()) {
|
||||||
|
return failed(index, draft, "缺少实体 entityId,不能发布服务流", Map.of());
|
||||||
|
}
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
int count = 0;
|
||||||
|
for (JsonNode flow : draft.payload().path("flows")) {
|
||||||
|
String key = flow.path("key").asText();
|
||||||
|
String xml = flow.path("contentXml").asText().replace("${entityId}", ctx.entityId());
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO sys_serviceflow
|
||||||
|
(sys_serviceflow_id, displayname, contentxml, entityid, iscontrol, isupdateable,
|
||||||
|
isactive, createtime, updatetime, createby, updateby, version)
|
||||||
|
VALUES (?, ?, ?::xml, ?, ?, ?, 1, ?, ?, 'AI_AGENT', 'AI_AGENT', 0)
|
||||||
|
ON CONFLICT (sys_serviceflow_id) DO UPDATE SET
|
||||||
|
displayname = EXCLUDED.displayname,
|
||||||
|
contentxml = EXCLUDED.contentxml,
|
||||||
|
entityid = EXCLUDED.entityid,
|
||||||
|
iscontrol = EXCLUDED.iscontrol,
|
||||||
|
isupdateable = EXCLUDED.isupdateable,
|
||||||
|
updatetime = EXCLUDED.updatetime,
|
||||||
|
updateby = EXCLUDED.updateby,
|
||||||
|
version = sys_serviceflow.version + 1
|
||||||
|
""",
|
||||||
|
key,
|
||||||
|
flow.path("displayName").asText(key),
|
||||||
|
xml,
|
||||||
|
ctx.entityId(),
|
||||||
|
flow.path("control").asBoolean(true) ? 1 : 0,
|
||||||
|
flow.path("updateable").asBoolean(true) ? 1 : 0,
|
||||||
|
now,
|
||||||
|
now);
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
return applied(index, draft, "服务流已发布", Map.of("flowCount", count, "entityId", ctx.entityId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private AiApplyStepResult applyPageSchema(AiDraft draft, int index) throws Exception {
|
||||||
|
String schemaJson = objectMapper.writeValueAsString(draft.payload());
|
||||||
|
String etag = sha256(schemaJson);
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO sys_page_schema (template_id, name, schema_json, schema_etag, version, update_time)
|
||||||
|
VALUES (?, ?, ?::jsonb, ?, 1, ?)
|
||||||
|
ON CONFLICT (template_id) DO UPDATE SET
|
||||||
|
name = EXCLUDED.name,
|
||||||
|
schema_json = EXCLUDED.schema_json,
|
||||||
|
schema_etag = EXCLUDED.schema_etag,
|
||||||
|
version = sys_page_schema.version + 1,
|
||||||
|
update_time = EXCLUDED.update_time
|
||||||
|
""",
|
||||||
|
draft.targetId(), draft.payload().path("title").asText(draft.targetId()), schemaJson, etag, now);
|
||||||
|
return applied(index, draft, "页面 schema 已发布", Map.of("templateId", draft.targetId(), "etag", etag));
|
||||||
|
}
|
||||||
|
|
||||||
|
private AiApplyStepResult applyMenu(ApplyContext ctx, AiDraft draft, int index) {
|
||||||
|
if (!tableExists("sys_menu")) {
|
||||||
|
return skipped(index, draft, "本地库缺少 sys_menu,菜单挂载跳过,部署包保留人工 SQL");
|
||||||
|
}
|
||||||
|
String templateId = draft.payload().path("viewTemplateId").asText(draft.targetId());
|
||||||
|
String menuName = draft.payload().path("name").asText(templateId);
|
||||||
|
String parentId = textOrBlank(draft.payload().get("parentId"));
|
||||||
|
String menuRoot = textOrBlank(draft.payload().get("menuroot"));
|
||||||
|
if (parentId.isBlank()) {
|
||||||
|
ParentMenu parent = ensureAiMenuParent(menuRoot);
|
||||||
|
parentId = parent.parentId();
|
||||||
|
menuRoot = parent.menuRoot();
|
||||||
|
}
|
||||||
|
List<String> existing = jdbcTemplate.queryForList(
|
||||||
|
"SELECT TRIM(sys_menu_id) FROM sys_menu WHERE TRIM(view_templateid)=? AND isactive=1",
|
||||||
|
String.class, templateId);
|
||||||
|
String menuId = existing.isEmpty() ? UUID.randomUUID().toString() : existing.get(0);
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
if (existing.isEmpty()) {
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO sys_menu
|
||||||
|
(sys_menu_id, name, parentid, view_templateid, typename, menuroot, seq,
|
||||||
|
isactive, version, createtime, createby, updatetime, updateby)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, 1, 0, ?, 'AI_AGENT', ?, 'AI_AGENT')
|
||||||
|
""",
|
||||||
|
menuId,
|
||||||
|
menuName,
|
||||||
|
parentId,
|
||||||
|
templateId,
|
||||||
|
draft.payload().path("typename").asText("功能菜单"),
|
||||||
|
menuRoot.isBlank() ? null : menuRoot,
|
||||||
|
draft.payload().path("seq").asInt(0),
|
||||||
|
now,
|
||||||
|
now);
|
||||||
|
} else {
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
UPDATE sys_menu
|
||||||
|
SET name=?, parentid=?, view_templateid=?, typename=?, menuroot=?, seq=?,
|
||||||
|
updatetime=?, updateby='AI_AGENT', version=version+1
|
||||||
|
WHERE TRIM(sys_menu_id)=?
|
||||||
|
""",
|
||||||
|
menuName,
|
||||||
|
parentId,
|
||||||
|
templateId,
|
||||||
|
draft.payload().path("typename").asText("功能菜单"),
|
||||||
|
menuRoot.isBlank() ? null : menuRoot,
|
||||||
|
draft.payload().path("seq").asInt(0),
|
||||||
|
now,
|
||||||
|
menuId);
|
||||||
|
}
|
||||||
|
return applied(index, draft, "菜单已挂载", Map.of("menuId", menuId, "parentId", parentId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private ParentMenu ensureAiMenuParent(String preferredRoot) {
|
||||||
|
List<String> existingDir = jdbcTemplate.queryForList(
|
||||||
|
"SELECT TRIM(sys_menu_id) FROM sys_menu WHERE name='AI Agent' AND parentid IS NULL AND isactive=1 ORDER BY seq LIMIT 1",
|
||||||
|
String.class);
|
||||||
|
if (!existingDir.isEmpty()) {
|
||||||
|
String root = preferredRoot;
|
||||||
|
if (root == null || root.isBlank()) {
|
||||||
|
List<String> roots = jdbcTemplate.queryForList(
|
||||||
|
"SELECT TRIM(menuroot) FROM sys_menu WHERE TRIM(sys_menu_id)=?",
|
||||||
|
String.class, existingDir.get(0));
|
||||||
|
root = roots.isEmpty() ? "" : roots.get(0);
|
||||||
|
}
|
||||||
|
return new ParentMenu(existingDir.get(0), root == null ? "" : root);
|
||||||
|
}
|
||||||
|
String root = preferredRoot;
|
||||||
|
if (root == null || root.isBlank()) {
|
||||||
|
List<String> roots = jdbcTemplate.queryForList(
|
||||||
|
"SELECT TRIM(sys_menu_root_id) FROM sys_menu_root WHERE isactive=1 ORDER BY seq LIMIT 1",
|
||||||
|
String.class);
|
||||||
|
if (roots.isEmpty()) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.CONFLICT, "缺少 sys_menu_root,不能自动挂载菜单");
|
||||||
|
}
|
||||||
|
root = roots.get(0);
|
||||||
|
}
|
||||||
|
String dirId = UUID.randomUUID().toString();
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO sys_menu
|
||||||
|
(sys_menu_id, name, parentid, view_templateid, typename, menuroot, seq,
|
||||||
|
isactive, version, createtime, createby, updatetime, updateby)
|
||||||
|
VALUES (?, 'AI Agent', NULL, NULL, '目录', ?, 9999, 1, 0, ?, 'AI_AGENT', ?, 'AI_AGENT')
|
||||||
|
""",
|
||||||
|
dirId, root, now, now);
|
||||||
|
return new ParentMenu(dirId, root);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean tableExists(String tableName) {
|
||||||
|
try {
|
||||||
|
Boolean exists = jdbcTemplate.queryForObject("SELECT to_regclass(?) IS NOT NULL", Boolean.class, tableName);
|
||||||
|
return Boolean.TRUE.equals(exists);
|
||||||
|
} catch (RuntimeException ex) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AiApplyStepResult applied(int index, AiDraft draft, String message, Map<String, Object> details) {
|
||||||
|
return new AiApplyStepResult("apply-" + index, draft.artifactType(), draft.targetId(),
|
||||||
|
"APPLIED", message, details);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AiApplyStepResult failed(int index, AiDraft draft, String message, Map<String, Object> details) {
|
||||||
|
return new AiApplyStepResult("apply-" + index, draft.artifactType(), draft.targetId(),
|
||||||
|
"FAILED", message, details);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AiApplyStepResult skipped(int index, AiDraft draft, String message) {
|
||||||
|
return new AiApplyStepResult("apply-" + index, draft.artifactType(), draft.targetId(),
|
||||||
|
"SKIPPED", message, Map.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static URI safeLocalBase(String raw) {
|
||||||
|
String value = raw == null || raw.isBlank() ? "http://localhost:8084" : raw.trim();
|
||||||
|
URI uri;
|
||||||
|
try {
|
||||||
|
uri = URI.create(value);
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "baseUrl 不合法: " + value);
|
||||||
|
}
|
||||||
|
String scheme = uri.getScheme();
|
||||||
|
String host = uri.getHost();
|
||||||
|
if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "baseUrl 只允许 http/https");
|
||||||
|
}
|
||||||
|
if (!isLocalHost(host)) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "本地发布仅允许访问本机地址");
|
||||||
|
}
|
||||||
|
String normalized = uri.toString();
|
||||||
|
if (!normalized.endsWith("/")) {
|
||||||
|
normalized += "/";
|
||||||
|
}
|
||||||
|
return URI.create(normalized);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isLocalHost(String host) {
|
||||||
|
if (host == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String h = host.toLowerCase(Locale.ROOT);
|
||||||
|
return "localhost".equals(h) || "127.0.0.1".equals(h) || "::1".equals(h) || "[::1]".equals(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String textOrBlank(JsonNode node) {
|
||||||
|
if (node == null || node.isNull()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String value = node.asText("");
|
||||||
|
return value == null ? "" : value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String sha256(String text) {
|
||||||
|
try {
|
||||||
|
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||||
|
return HexFormat.of().formatHex(digest.digest(text.getBytes(StandardCharsets.UTF_8)));
|
||||||
|
} catch (NoSuchAlgorithmException ex) {
|
||||||
|
throw new IllegalStateException(ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static class ApplyContext {
|
||||||
|
private final URI base;
|
||||||
|
private String entityId = "";
|
||||||
|
private String tableName = "";
|
||||||
|
|
||||||
|
ApplyContext(URI base) {
|
||||||
|
this.base = base;
|
||||||
|
}
|
||||||
|
|
||||||
|
URI base() {
|
||||||
|
return base;
|
||||||
|
}
|
||||||
|
|
||||||
|
String entityId() {
|
||||||
|
return entityId;
|
||||||
|
}
|
||||||
|
|
||||||
|
void entityId(String entityId) {
|
||||||
|
this.entityId = entityId == null ? "" : entityId;
|
||||||
|
}
|
||||||
|
|
||||||
|
String tableName() {
|
||||||
|
return tableName;
|
||||||
|
}
|
||||||
|
|
||||||
|
void tableName(String tableName) {
|
||||||
|
this.tableName = tableName == null ? "" : tableName;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record ParentMenu(String parentId, String menuRoot) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.time.Duration;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
|
||||||
|
public interface AiSmokeHttpClient {
|
||||||
|
|
||||||
|
AiHttpResponse exchange(String method, URI uri, JsonNode requestBody, Duration timeout) throws Exception;
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import com.eip4.platform.ai.model.AiSmokeResult;
|
||||||
|
import com.eip4.platform.ai.model.AiSmokeRun;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class AiSmokeRunner {
|
||||||
|
|
||||||
|
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(8);
|
||||||
|
private static final int SNIPPET_LIMIT = 600;
|
||||||
|
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
|
||||||
|
|
||||||
|
private final AiSmokeHttpClient httpClient;
|
||||||
|
|
||||||
|
public AiSmokeRunner(AiSmokeHttpClient httpClient) {
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
public AiSmokeRun run(String taskId, String changeSetId, String baseUrl, JsonNode testPayload) {
|
||||||
|
URI base = safeLocalBase(baseUrl);
|
||||||
|
JsonNode tests = testPayload == null ? null : testPayload.path("smokeTests");
|
||||||
|
if (tests == null || !tests.isArray() || tests.isEmpty()) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "没有可执行的 smokeTests");
|
||||||
|
}
|
||||||
|
|
||||||
|
long started = System.currentTimeMillis();
|
||||||
|
List<AiSmokeResult> results = new ArrayList<>();
|
||||||
|
for (JsonNode test : tests) {
|
||||||
|
results.add(runOne(base, test));
|
||||||
|
}
|
||||||
|
long finished = System.currentTimeMillis();
|
||||||
|
boolean passed = results.stream().allMatch(AiSmokeResult::passed);
|
||||||
|
return new AiSmokeRun(taskId, changeSetId, base.toString(), passed ? "PASSED" : "FAILED",
|
||||||
|
started, finished, List.copyOf(results));
|
||||||
|
}
|
||||||
|
|
||||||
|
private AiSmokeResult runOne(URI base, JsonNode test) {
|
||||||
|
String name = text(test, "name", "unnamed");
|
||||||
|
String method = text(test, "method", "GET").toUpperCase(Locale.ROOT);
|
||||||
|
String url = text(test, "url", "");
|
||||||
|
int expected = test.path("expectHttpStatus").asInt(200);
|
||||||
|
long started = System.currentTimeMillis();
|
||||||
|
if (!url.startsWith("/api/")) {
|
||||||
|
return failed(name, method, url, expected, -1, started, "smoke url 必须以 /api/ 开头", "");
|
||||||
|
}
|
||||||
|
if (!List.of("GET", "POST", "PUT", "DELETE", "PATCH").contains(method)) {
|
||||||
|
return failed(name, method, url, expected, -1, started, "不支持的 HTTP method: " + method, "");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
URI uri = base.resolve(url);
|
||||||
|
AiHttpResponse response = httpClient.exchange(method, uri, test.get("requestBody"), REQUEST_TIMEOUT);
|
||||||
|
boolean passed = response.statusCode() == expected;
|
||||||
|
String err = passed ? businessStatusError(response.body())
|
||||||
|
: "期望 HTTP " + expected + ",实际 HTTP " + response.statusCode();
|
||||||
|
passed = passed && err.isBlank();
|
||||||
|
return new AiSmokeResult(name, method, url, expected, response.statusCode(), passed,
|
||||||
|
System.currentTimeMillis() - started, err, snippet(response.body()));
|
||||||
|
} catch (Exception ex) {
|
||||||
|
return failed(name, method, url, expected, -1, started,
|
||||||
|
ex.getClass().getSimpleName() + ": " + String.valueOf(ex.getMessage()), "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static AiSmokeResult failed(String name, String method, String url, int expected, int actual,
|
||||||
|
long started, String error, String response) {
|
||||||
|
return new AiSmokeResult(name, method, url, expected, actual, false,
|
||||||
|
System.currentTimeMillis() - started, error, snippet(response));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static URI safeLocalBase(String raw) {
|
||||||
|
String value = raw == null || raw.isBlank() ? "http://localhost:8084" : raw.trim();
|
||||||
|
URI uri;
|
||||||
|
try {
|
||||||
|
uri = URI.create(value);
|
||||||
|
} catch (IllegalArgumentException ex) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "baseUrl 不合法: " + value);
|
||||||
|
}
|
||||||
|
String scheme = uri.getScheme();
|
||||||
|
String host = uri.getHost();
|
||||||
|
if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "baseUrl 只允许 http/https");
|
||||||
|
}
|
||||||
|
if (!isLocalHost(host)) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "smoke 仅允许访问本机地址");
|
||||||
|
}
|
||||||
|
String normalized = uri.toString();
|
||||||
|
if (!normalized.endsWith("/")) {
|
||||||
|
normalized += "/";
|
||||||
|
}
|
||||||
|
return URI.create(normalized);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isLocalHost(String host) {
|
||||||
|
if (host == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String h = host.toLowerCase(Locale.ROOT);
|
||||||
|
return "localhost".equals(h) || "127.0.0.1".equals(h) || "::1".equals(h) || "[::1]".equals(h);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String text(JsonNode node, String field, String fallback) {
|
||||||
|
JsonNode value = node == null ? null : node.get(field);
|
||||||
|
if (value == null || value.isNull()) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
String s = value.asText();
|
||||||
|
return s == null || s.isBlank() ? fallback : s.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String snippet(String body) {
|
||||||
|
if (body == null || body.isBlank()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
String compact = body.replaceAll("\\s+", " ").trim();
|
||||||
|
return compact.length() <= SNIPPET_LIMIT ? compact : compact.substring(0, SNIPPET_LIMIT);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String businessStatusError(String body) {
|
||||||
|
if (body == null || body.isBlank()) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
JsonNode root = OBJECT_MAPPER.readTree(body);
|
||||||
|
JsonNode status = root == null || !root.isObject() ? null : root.get("status");
|
||||||
|
if (status != null && !status.isNull() && status.asInt(0) != 0) {
|
||||||
|
String msg = root.path("msg").asText("");
|
||||||
|
return msg.isBlank() ? "响应 JSON status=" + status.asText()
|
||||||
|
: "响应 JSON status=" + status.asText() + ": " + msg;
|
||||||
|
}
|
||||||
|
} catch (Exception ignore) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
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 com.eip4.platform.ai.model.AiEmployeeDefinition;
|
||||||
|
import com.eip4.platform.ai.model.AiToolAccessDecision;
|
||||||
|
import com.eip4.platform.ai.model.AiToolAccessRequest;
|
||||||
|
import com.eip4.platform.ai.model.AiToolDefinition;
|
||||||
|
|
||||||
|
public final class AiToolRegistry {
|
||||||
|
|
||||||
|
private final Map<String, AiToolDefinition> tools;
|
||||||
|
private final Map<String, AiEmployeeDefinition> employees;
|
||||||
|
|
||||||
|
private AiToolRegistry(Map<String, AiToolDefinition> tools, Map<String, AiEmployeeDefinition> employees) {
|
||||||
|
this.tools = Collections.unmodifiableMap(new LinkedHashMap<>(tools));
|
||||||
|
this.employees = Collections.unmodifiableMap(new LinkedHashMap<>(employees));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static AiToolRegistry defaults() {
|
||||||
|
Map<String, AiToolDefinition> tools = new LinkedHashMap<>();
|
||||||
|
registerTool(tools, "feature.draft.generate", "development",
|
||||||
|
"Generate entity, page schema, serviceflow, menu and smoke drafts.",
|
||||||
|
List.of("POST /api/ai/features/develop", "POST /api/ai/features/auto-develop"),
|
||||||
|
List.of("ai:feature:draft"), false, false);
|
||||||
|
registerTool(tools, "schema.validate", "validation",
|
||||||
|
"Validate AMIS and typed page schema before saving or packaging.",
|
||||||
|
List.of("POST /api/ai/tools/validate-schema", "POST /api/page/schema/validate"),
|
||||||
|
List.of("ai:schema:validate"), false, false);
|
||||||
|
registerTool(tools, "page-recipe.read", "design-contract",
|
||||||
|
"Read EIP4 page recipes and UI/UE constraints before generating page blueprints.",
|
||||||
|
List.of("GET /api/ai/page-recipes", "GET /api/ai/page-recipes/{recipe}"),
|
||||||
|
List.of("ai:page-recipe:read"), false, false);
|
||||||
|
registerTool(tools, "local.apply", "local-gate",
|
||||||
|
"Apply a change set to a local EIP4 environment only.",
|
||||||
|
List.of("POST /api/ai/tasks/{taskId}/change-sets/{changeSetId}/local-apply"),
|
||||||
|
List.of("ai:local:apply"), true, false);
|
||||||
|
registerTool(tools, "smoke.run", "local-gate",
|
||||||
|
"Run local smoke checks against a local EIP4 baseUrl.",
|
||||||
|
List.of("POST /api/ai/tasks/{taskId}/change-sets/{changeSetId}/smoke"),
|
||||||
|
List.of("ai:smoke:run"), true, false);
|
||||||
|
registerTool(tools, "feature.package", "release-prep",
|
||||||
|
"Create feature packages, revisions and release evidence for human review.",
|
||||||
|
List.of("POST /api/ai/tasks/{taskId}/change-sets/{changeSetId}/feature-package",
|
||||||
|
"POST /api/ai/tasks/{taskId}/feature-packages/{packageId}/revisions"),
|
||||||
|
List.of("ai:package:create"), false, false);
|
||||||
|
registerTool(tools, "release.prepare", "release-prep",
|
||||||
|
"Export, verify, diff and prepare rollback plans without production execution.",
|
||||||
|
List.of("eip4 release verify", "eip4 release export", "eip4 release diff",
|
||||||
|
"eip4 release rollback-plan"),
|
||||||
|
List.of("ai:release:prepare"), false, false);
|
||||||
|
|
||||||
|
Map<String, AiEmployeeDefinition> employees = new LinkedHashMap<>();
|
||||||
|
registerEmployee(employees, "agent-developer", "Agent Developer",
|
||||||
|
"Develops EIP4 feature packages in local environments.",
|
||||||
|
List.of("feature.draft.generate", "schema.validate", "page-recipe.read", "local.apply", "smoke.run",
|
||||||
|
"feature.package", "release.prepare"),
|
||||||
|
List.of("ai:feature:draft", "ai:schema:validate", "ai:page-recipe:read", "ai:local:apply", "ai:smoke:run",
|
||||||
|
"ai:package:create", "ai:release:prepare"),
|
||||||
|
List.of("Local apply only", "Production deployment requires human operator"));
|
||||||
|
registerEmployee(employees, "release-auditor", "Release Auditor",
|
||||||
|
"Reviews packages, diffs and rollback plans before human deployment.",
|
||||||
|
List.of("schema.validate", "feature.package", "release.prepare"),
|
||||||
|
List.of("ai:schema:validate", "ai:package:create", "ai:release:prepare"),
|
||||||
|
List.of("Read-only release preparation", "No environment writes"));
|
||||||
|
registerEmployee(employees, "support-diagnoser", "Support Diagnoser",
|
||||||
|
"Reads run evidence and prepares repair plans for local reproduction.",
|
||||||
|
List.of("schema.validate", "smoke.run"),
|
||||||
|
List.of("ai:schema:validate", "ai:smoke:run"),
|
||||||
|
List.of("Local diagnostics only"));
|
||||||
|
return new AiToolRegistry(tools, employees);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<AiToolDefinition> tools() {
|
||||||
|
return List.copyOf(tools.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<AiEmployeeDefinition> employees() {
|
||||||
|
return List.copyOf(employees.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
public AiToolAccessDecision check(AiToolAccessRequest request) {
|
||||||
|
String employeeId = text(request == null ? null : request.employeeId());
|
||||||
|
String toolName = text(request == null ? null : request.toolName());
|
||||||
|
AiEmployeeDefinition employee = employees.get(employeeId);
|
||||||
|
AiToolDefinition tool = tools.get(toolName);
|
||||||
|
List<String> blockers = new ArrayList<>();
|
||||||
|
if (employee == null) {
|
||||||
|
blockers.add("Unknown AI employee: " + employeeId);
|
||||||
|
}
|
||||||
|
if (tool == null) {
|
||||||
|
blockers.add("Unknown AI tool: " + toolName);
|
||||||
|
}
|
||||||
|
if (employee == null || tool == null) {
|
||||||
|
return new AiToolAccessDecision(false, List.of(), List.copyOf(blockers), tool, employee);
|
||||||
|
}
|
||||||
|
if (!employee.toolNames().contains(tool.name())) {
|
||||||
|
blockers.add("Employee " + employee.id() + " is not allowed to use tool " + tool.name());
|
||||||
|
}
|
||||||
|
List<String> requestScopes = request == null || request.grantedScopes() == null
|
||||||
|
? List.of() : request.grantedScopes();
|
||||||
|
Set<String> granted = new LinkedHashSet<>(requestScopes);
|
||||||
|
List<String> missingScopes = new ArrayList<>();
|
||||||
|
for (String scope : tool.requiredScopes()) {
|
||||||
|
if (!granted.contains(scope)) {
|
||||||
|
missingScopes.add(scope);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (String scope : employee.requiredScopes()) {
|
||||||
|
if (tool.requiredScopes().contains(scope) && !granted.contains(scope) && !missingScopes.contains(scope)) {
|
||||||
|
missingScopes.add(scope);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!missingScopes.isEmpty()) {
|
||||||
|
blockers.add("Missing scopes: " + String.join(",", missingScopes));
|
||||||
|
}
|
||||||
|
String targetEnv = text(request == null ? null : request.targetEnv()).toLowerCase(Locale.ROOT);
|
||||||
|
if (tool.localOnly() && !isLocalEnv(targetEnv)) {
|
||||||
|
blockers.add("Tool " + tool.name() + " is local-only, targetEnv=" + targetEnv);
|
||||||
|
}
|
||||||
|
boolean productionWrite = request != null && request.productionWrite();
|
||||||
|
if (productionWrite || isProductionEnv(targetEnv)) {
|
||||||
|
if (!tool.productionWriteAllowed()) {
|
||||||
|
blockers.add("Tool " + tool.name() + " is not allowed to perform production writes");
|
||||||
|
}
|
||||||
|
if (!granted.contains("human:approval")) {
|
||||||
|
blockers.add("Production write requires human:approval scope");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new AiToolAccessDecision(blockers.isEmpty(), List.copyOf(missingScopes), List.copyOf(blockers),
|
||||||
|
tool, employee);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void registerTool(Map<String, AiToolDefinition> tools, String name, String category,
|
||||||
|
String description, List<String> operations, List<String> requiredScopes,
|
||||||
|
boolean localOnly, boolean productionWriteAllowed) {
|
||||||
|
tools.put(name, new AiToolDefinition(name, category, description, List.copyOf(operations),
|
||||||
|
List.copyOf(requiredScopes), localOnly, productionWriteAllowed));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void registerEmployee(Map<String, AiEmployeeDefinition> employees, String id, String name,
|
||||||
|
String role, List<String> toolNames, List<String> requiredScopes,
|
||||||
|
List<String> policies) {
|
||||||
|
employees.put(id, new AiEmployeeDefinition(id, name, role, List.copyOf(toolNames),
|
||||||
|
List.copyOf(requiredScopes), List.copyOf(policies)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isLocalEnv(String targetEnv) {
|
||||||
|
return targetEnv.isBlank()
|
||||||
|
|| targetEnv.equals("local")
|
||||||
|
|| targetEnv.equals("dev")
|
||||||
|
|| targetEnv.startsWith("localhost")
|
||||||
|
|| targetEnv.startsWith("127.0.0.1")
|
||||||
|
|| targetEnv.startsWith("http://localhost")
|
||||||
|
|| targetEnv.startsWith("http://127.0.0.1");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isProductionEnv(String targetEnv) {
|
||||||
|
return targetEnv.equals("prod") || targetEnv.equals("production") || targetEnv.contains("prod");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String text(String value) {
|
||||||
|
return value == null ? "" : value.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.eip4.platform.ai.model.AiAgentRepairContext;
|
||||||
|
import com.eip4.platform.ai.model.AiAgentRepairResult;
|
||||||
|
import com.eip4.platform.ai.model.AiArtifactType;
|
||||||
|
import com.eip4.platform.ai.model.AiDraft;
|
||||||
|
import com.eip4.platform.ai.model.AiRepairAction;
|
||||||
|
import com.eip4.platform.ai.model.AiRepairDraftPatch;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class DeterministicAiAgentRepairExecutor implements AiAgentRepairExecutor {
|
||||||
|
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
private final List<AiLlmRepairClient> llmRepairClients;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public DeterministicAiAgentRepairExecutor(ObjectMapper objectMapper, List<AiLlmRepairClient> llmRepairClients) {
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
this.llmRepairClients = llmRepairClients == null ? List.of() : List.copyOf(llmRepairClients);
|
||||||
|
}
|
||||||
|
|
||||||
|
public DeterministicAiAgentRepairExecutor(ObjectMapper objectMapper) {
|
||||||
|
this(objectMapper, List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AiAgentRepairResult repair(AiAgentRepairContext context) {
|
||||||
|
if (context == null || context.repairPlan() == null || context.drafts() == null) {
|
||||||
|
return new AiAgentRepairResult("NOOP", List.of(), List.of("缺少修复上下文"));
|
||||||
|
}
|
||||||
|
AiAgentRepairResult llmResult = tryLlmRepair(context);
|
||||||
|
if (!llmResult.draftPatches().isEmpty()) {
|
||||||
|
return llmResult;
|
||||||
|
}
|
||||||
|
List<AiRepairDraftPatch> patches = new ArrayList<>();
|
||||||
|
List<String> messages = new ArrayList<>();
|
||||||
|
for (AiRepairAction action : context.repairPlan().actions()) {
|
||||||
|
if ("REPAIR_ENTITY_METADATA_OR_LOCAL_API".equals(action.actionType())) {
|
||||||
|
entityMetadataPatch(context, action).ifPresentOrElse(
|
||||||
|
patch -> {
|
||||||
|
patches.add(patch);
|
||||||
|
messages.add("已生成 ENTITY 草稿修复: " + action.targetId());
|
||||||
|
},
|
||||||
|
() -> messages.add("未找到可确定修复的 ENTITY 草稿: " + action.targetId()));
|
||||||
|
} else if ("REPAIR_SMOKE_EXPECTATION_OR_API_CONTRACT".equals(action.actionType())) {
|
||||||
|
smokeExpectationPatch(context, action).ifPresentOrElse(
|
||||||
|
patch -> {
|
||||||
|
patches.add(patch);
|
||||||
|
messages.add("已生成 TEST 草稿修复: " + action.targetId());
|
||||||
|
},
|
||||||
|
() -> messages.add("未找到可修复的 TEST 草稿: " + action.targetId()));
|
||||||
|
} else if ("REPAIR_PAGE_SCHEMA_SQL_OR_SCHEMA".equals(action.actionType())) {
|
||||||
|
pageSchemaPatch(context, action).ifPresentOrElse(
|
||||||
|
patch -> {
|
||||||
|
patches.add(patch);
|
||||||
|
messages.add("已生成 PAGE_SCHEMA 草稿修复: " + action.targetId());
|
||||||
|
},
|
||||||
|
() -> messages.add("未找到可确定修复的 PAGE_SCHEMA 草稿: " + action.targetId()));
|
||||||
|
} else if ("SEED_MENU_ROOT_OR_SET_PARENT".equals(action.actionType())
|
||||||
|
|| "REPAIR_MENU_BINDING".equals(action.actionType())) {
|
||||||
|
menuParentPatch(context, action).ifPresentOrElse(
|
||||||
|
patch -> {
|
||||||
|
patches.add(patch);
|
||||||
|
messages.add("已生成 MENU 草稿修复: " + action.targetId());
|
||||||
|
},
|
||||||
|
() -> messages.add("未找到可确定修复的 MENU 草稿: " + action.targetId()));
|
||||||
|
} else if ("RETRY_AFTER_ENTITY_ID_RESOLUTION".equals(action.actionType())
|
||||||
|
|| "REPAIR_SERVICEFLOW_XML_OR_SQL".equals(action.actionType())) {
|
||||||
|
serviceFlowEntityBindingPatch(context, action).ifPresentOrElse(
|
||||||
|
patch -> {
|
||||||
|
patches.add(patch);
|
||||||
|
messages.add("已生成 SERVICEFLOW 草稿修复: " + action.targetId());
|
||||||
|
},
|
||||||
|
() -> messages.add("未找到可确定修复的 SERVICEFLOW 草稿: " + action.targetId()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String status = patches.isEmpty() ? "NO_PATCHES" : "PATCHES_GENERATED";
|
||||||
|
return new AiAgentRepairResult(status, List.copyOf(patches), List.copyOf(messages));
|
||||||
|
}
|
||||||
|
|
||||||
|
private AiAgentRepairResult tryLlmRepair(AiAgentRepairContext context) {
|
||||||
|
List<AiRepairDraftPatch> patches = new ArrayList<>();
|
||||||
|
List<String> messages = new ArrayList<>();
|
||||||
|
for (AiLlmRepairClient client : llmRepairClients) {
|
||||||
|
List<AiRepairDraftPatch> one = client.repair(context);
|
||||||
|
if (one != null && !one.isEmpty()) {
|
||||||
|
patches.addAll(one);
|
||||||
|
messages.add("LLM repair client generated " + one.size() + " draft patch(es)");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new AiAgentRepairResult(patches.isEmpty() ? "NO_PATCHES" : "PATCHES_GENERATED",
|
||||||
|
List.copyOf(patches), List.copyOf(messages));
|
||||||
|
}
|
||||||
|
|
||||||
|
private java.util.Optional<AiRepairDraftPatch> entityMetadataPatch(AiAgentRepairContext context,
|
||||||
|
AiRepairAction action) {
|
||||||
|
for (AiDraft draft : context.drafts()) {
|
||||||
|
if (draft.artifactType() != AiArtifactType.ENTITY || !draft.targetId().equals(action.targetId())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ObjectNode copy = draft.payload().deepCopy();
|
||||||
|
boolean changed = false;
|
||||||
|
if (!"/api/meta/entity".equals(copy.path("publishTarget").asText(""))) {
|
||||||
|
copy.put("publishTarget", "/api/meta/entity");
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (copy.path("tablename").asText("").isBlank()) {
|
||||||
|
copy.put("tablename", draft.targetId());
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (copy.path("name").asText("").isBlank()) {
|
||||||
|
copy.put("name", draft.targetId());
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
JsonNode attrs = copy.path("attributes");
|
||||||
|
if (attrs.isArray()) {
|
||||||
|
for (JsonNode attr : attrs) {
|
||||||
|
if (attr instanceof ObjectNode node && node.path("display").asText("").isBlank()) {
|
||||||
|
node.put("display", node.path("column").asText("字段"));
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!changed) {
|
||||||
|
return java.util.Optional.empty();
|
||||||
|
}
|
||||||
|
return java.util.Optional.of(new AiRepairDraftPatch(
|
||||||
|
AiArtifactType.ENTITY,
|
||||||
|
draft.targetId(),
|
||||||
|
copy,
|
||||||
|
Map.of(
|
||||||
|
"source", "deterministic-agent-repair",
|
||||||
|
"repairActionId", action.id(),
|
||||||
|
"supersedesDraftId", draft.id())));
|
||||||
|
}
|
||||||
|
return java.util.Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private java.util.Optional<AiRepairDraftPatch> serviceFlowEntityBindingPatch(AiAgentRepairContext context,
|
||||||
|
AiRepairAction action) {
|
||||||
|
for (AiDraft draft : context.drafts()) {
|
||||||
|
if (draft.artifactType() != AiArtifactType.SERVICEFLOW || !draft.targetId().equals(action.targetId())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ObjectNode copy = draft.payload().deepCopy();
|
||||||
|
JsonNode flows = copy.path("flows");
|
||||||
|
if (!flows.isArray()) {
|
||||||
|
return java.util.Optional.empty();
|
||||||
|
}
|
||||||
|
boolean changed = false;
|
||||||
|
copy.put("requiresEntityId", true);
|
||||||
|
copy.put("entityIdBinding", "publish ENTITY draft first, then replace ${entityId}");
|
||||||
|
for (JsonNode flow : flows) {
|
||||||
|
if (!(flow instanceof ObjectNode node)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String existingEntityId = node.path("entityId").asText("");
|
||||||
|
String xml = node.path("contentXml").asText("");
|
||||||
|
if (!"${entityId}".equals(existingEntityId)) {
|
||||||
|
node.put("entityId", "${entityId}");
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (!xml.contains("${entityId}") && !existingEntityId.isBlank()) {
|
||||||
|
node.put("contentXml", xml.replace(existingEntityId, "${entityId}"));
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!changed) {
|
||||||
|
return java.util.Optional.empty();
|
||||||
|
}
|
||||||
|
return java.util.Optional.of(new AiRepairDraftPatch(
|
||||||
|
AiArtifactType.SERVICEFLOW,
|
||||||
|
draft.targetId(),
|
||||||
|
copy,
|
||||||
|
Map.of(
|
||||||
|
"source", "deterministic-agent-repair",
|
||||||
|
"repairActionId", action.id(),
|
||||||
|
"supersedesDraftId", draft.id())));
|
||||||
|
}
|
||||||
|
return java.util.Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private java.util.Optional<AiRepairDraftPatch> menuParentPatch(AiAgentRepairContext context,
|
||||||
|
AiRepairAction action) {
|
||||||
|
for (AiDraft draft : context.drafts()) {
|
||||||
|
if (draft.artifactType() != AiArtifactType.MENU || !draft.targetId().equals(action.targetId())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ObjectNode copy = draft.payload().deepCopy();
|
||||||
|
boolean changed = false;
|
||||||
|
if (copy.path("parentId").asText("").isBlank()) {
|
||||||
|
copy.put("parentId", "${parentMenuId}");
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (copy.path("menuroot").asText("").isBlank()) {
|
||||||
|
copy.put("menuroot", "${menuRoot}");
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (!changed) {
|
||||||
|
return java.util.Optional.empty();
|
||||||
|
}
|
||||||
|
return java.util.Optional.of(new AiRepairDraftPatch(
|
||||||
|
AiArtifactType.MENU,
|
||||||
|
draft.targetId(),
|
||||||
|
copy,
|
||||||
|
Map.of(
|
||||||
|
"source", "deterministic-agent-repair",
|
||||||
|
"repairActionId", action.id(),
|
||||||
|
"supersedesDraftId", draft.id(),
|
||||||
|
"requiresHumanReplacement", true)));
|
||||||
|
}
|
||||||
|
return java.util.Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private java.util.Optional<AiRepairDraftPatch> pageSchemaPatch(AiAgentRepairContext context,
|
||||||
|
AiRepairAction action) {
|
||||||
|
for (AiDraft draft : context.drafts()) {
|
||||||
|
if (draft.artifactType() != AiArtifactType.PAGE_SCHEMA || !draft.targetId().equals(action.targetId())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ObjectNode copy = draft.payload().deepCopy();
|
||||||
|
boolean changed = false;
|
||||||
|
if (copy.path("type").asText("").isBlank()) {
|
||||||
|
copy.put("type", "page");
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (copy.path("title").asText("").isBlank()) {
|
||||||
|
copy.put("title", draft.targetId());
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
JsonNode body = copy.get("body");
|
||||||
|
if (body == null || body.isNull()) {
|
||||||
|
copy.putArray("body");
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
if (!changed) {
|
||||||
|
return java.util.Optional.empty();
|
||||||
|
}
|
||||||
|
return java.util.Optional.of(new AiRepairDraftPatch(
|
||||||
|
AiArtifactType.PAGE_SCHEMA,
|
||||||
|
draft.targetId(),
|
||||||
|
copy,
|
||||||
|
repairMetadata(draft,
|
||||||
|
"source", "deterministic-agent-repair",
|
||||||
|
"repairActionId", action.id(),
|
||||||
|
"supersedesDraftId", draft.id())));
|
||||||
|
}
|
||||||
|
return java.util.Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private java.util.Optional<AiRepairDraftPatch> smokeExpectationPatch(AiAgentRepairContext context,
|
||||||
|
AiRepairAction action) {
|
||||||
|
int actual = intDetail(action, "actualHttpStatus", -1);
|
||||||
|
if (actual < 200 || actual >= 300) {
|
||||||
|
return java.util.Optional.empty();
|
||||||
|
}
|
||||||
|
String method = stringDetail(action, "method");
|
||||||
|
String url = stringDetail(action, "url");
|
||||||
|
for (AiDraft draft : context.drafts()) {
|
||||||
|
if (draft.artifactType() != AiArtifactType.TEST) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ObjectNode copy = draft.payload().deepCopy();
|
||||||
|
JsonNode tests = copy.path("smokeTests");
|
||||||
|
if (!tests.isArray()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
boolean changed = false;
|
||||||
|
for (JsonNode test : tests) {
|
||||||
|
if (test instanceof ObjectNode node
|
||||||
|
&& method.equalsIgnoreCase(node.path("method").asText(""))
|
||||||
|
&& url.equals(node.path("url").asText(""))) {
|
||||||
|
node.put("expectHttpStatus", actual);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (changed) {
|
||||||
|
return java.util.Optional.of(new AiRepairDraftPatch(
|
||||||
|
AiArtifactType.TEST,
|
||||||
|
draft.targetId(),
|
||||||
|
copy,
|
||||||
|
Map.of(
|
||||||
|
"source", "deterministic-agent-repair",
|
||||||
|
"repairActionId", action.id(),
|
||||||
|
"supersedesDraftId", draft.id())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return java.util.Optional.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int intDetail(AiRepairAction action, String key, int fallback) {
|
||||||
|
Object value = action.details() == null ? null : action.details().get(key);
|
||||||
|
if (value instanceof Number n) {
|
||||||
|
return n.intValue();
|
||||||
|
}
|
||||||
|
if (value instanceof String s) {
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(s);
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String stringDetail(AiRepairAction action, String key) {
|
||||||
|
Object value = action.details() == null ? null : action.details().get(key);
|
||||||
|
return value == null ? "" : String.valueOf(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Map<String, Object> repairMetadata(AiDraft draft, Object... entries) {
|
||||||
|
Map<String, Object> out = new LinkedHashMap<>();
|
||||||
|
if (draft.metadata() != null) {
|
||||||
|
out.putAll(draft.metadata());
|
||||||
|
}
|
||||||
|
for (int i = 0; i + 1 < entries.length; i += 2) {
|
||||||
|
out.put(String.valueOf(entries[i]), entries[i + 1]);
|
||||||
|
}
|
||||||
|
return Map.copyOf(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.eip4.platform.ai.model.AiAgentRepairContext;
|
||||||
|
import com.eip4.platform.ai.model.AiRepairDraftPatch;
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@ConditionalOnProperty(name = "eip4.ai.llm.repair.enabled", havingValue = "true")
|
||||||
|
public class HttpAiLlmRepairClient implements AiLlmRepairClient {
|
||||||
|
|
||||||
|
private static final TypeReference<List<AiRepairDraftPatch>> PATCH_LIST = new TypeReference<>() {
|
||||||
|
};
|
||||||
|
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
private final HttpClient httpClient;
|
||||||
|
private final URI endpoint;
|
||||||
|
private final String apiKey;
|
||||||
|
private final String model;
|
||||||
|
|
||||||
|
public HttpAiLlmRepairClient(ObjectMapper objectMapper,
|
||||||
|
@Value("${eip4.ai.llm.repair.endpoint:}") String endpoint,
|
||||||
|
@Value("${eip4.ai.llm.repair.api-key:}") String apiKey,
|
||||||
|
@Value("${eip4.ai.llm.repair.model:}") String model) {
|
||||||
|
this(objectMapper, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build(),
|
||||||
|
endpoint, apiKey, model);
|
||||||
|
}
|
||||||
|
|
||||||
|
HttpAiLlmRepairClient(ObjectMapper objectMapper, HttpClient httpClient,
|
||||||
|
String endpoint, String apiKey, String model) {
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
this.endpoint = endpoint == null || endpoint.isBlank() ? null : URI.create(endpoint.trim());
|
||||||
|
this.apiKey = apiKey == null ? "" : apiKey.trim();
|
||||||
|
this.model = model == null ? "" : model.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiRepairDraftPatch> repair(AiAgentRepairContext context) {
|
||||||
|
if (endpoint == null || context == null) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
HttpRequest.Builder builder = HttpRequest.newBuilder(endpoint)
|
||||||
|
.timeout(Duration.ofSeconds(60))
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.POST(HttpRequest.BodyPublishers.ofString(json(requestPayload(context))));
|
||||||
|
if (!apiKey.isBlank()) {
|
||||||
|
builder.header("Authorization", "Bearer " + apiKey);
|
||||||
|
}
|
||||||
|
HttpResponse<String> response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofString());
|
||||||
|
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
return parsePatches(response.body());
|
||||||
|
} catch (Exception ex) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> requestPayload(AiAgentRepairContext context) {
|
||||||
|
return Map.of(
|
||||||
|
"model", model,
|
||||||
|
"taskId", context.taskId(),
|
||||||
|
"changeSetId", context.changeSetId(),
|
||||||
|
"repairPlan", context.repairPlan(),
|
||||||
|
"drafts", context.drafts(),
|
||||||
|
"contract", Map.of(
|
||||||
|
"responseField", "draftPatches",
|
||||||
|
"patchShape", "artifactType,targetId,payload,metadata",
|
||||||
|
"rule", "Return only safe draft patches; do not execute production changes"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<AiRepairDraftPatch> parsePatches(String body) throws JsonProcessingException {
|
||||||
|
var root = objectMapper.readTree(body);
|
||||||
|
var patches = root.path("draftPatches");
|
||||||
|
if (!patches.isArray()) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
return objectMapper.convertValue(patches, PATCH_LIST);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String json(Object value) throws JsonProcessingException {
|
||||||
|
return objectMapper.writeValueAsString(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.time.Duration;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class JdkAiSmokeHttpClient implements AiSmokeHttpClient {
|
||||||
|
|
||||||
|
private final HttpClient httpClient;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public JdkAiSmokeHttpClient(ObjectMapper objectMapper) {
|
||||||
|
this(HttpClient.newHttpClient(), objectMapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
JdkAiSmokeHttpClient(HttpClient httpClient, ObjectMapper objectMapper) {
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public AiHttpResponse exchange(String method, URI uri, JsonNode requestBody, Duration timeout) throws Exception {
|
||||||
|
HttpRequest.BodyPublisher body = requestBody == null || requestBody.isNull()
|
||||||
|
? HttpRequest.BodyPublishers.noBody()
|
||||||
|
: HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(requestBody));
|
||||||
|
HttpRequest.Builder builder = HttpRequest.newBuilder(uri)
|
||||||
|
.timeout(timeout)
|
||||||
|
.header("Accept", "application/json");
|
||||||
|
if (requestBody != null && !requestBody.isNull()) {
|
||||||
|
builder.header("Content-Type", "application/json");
|
||||||
|
}
|
||||||
|
HttpRequest request = builder.method(method, body).build();
|
||||||
|
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
|
return new AiHttpResponse(response.statusCode(), response.body());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
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.AiFeaturePackage;
|
||||||
|
import com.eip4.platform.ai.model.AiRevision;
|
||||||
|
import com.eip4.platform.ai.model.AiRunRecord;
|
||||||
|
import com.eip4.platform.ai.model.AiTask;
|
||||||
|
|
||||||
|
public interface AiAgentStore {
|
||||||
|
|
||||||
|
void saveTask(AiTask task);
|
||||||
|
|
||||||
|
Optional<AiTask> findTask(String taskId);
|
||||||
|
|
||||||
|
void saveDraft(AiDraft draft);
|
||||||
|
|
||||||
|
List<AiDraft> listDrafts(String taskId);
|
||||||
|
|
||||||
|
void saveChangeSet(AiChangeSet changeSet);
|
||||||
|
|
||||||
|
List<AiChangeSet> listChangeSets(String taskId);
|
||||||
|
|
||||||
|
void saveRun(AiRunRecord run);
|
||||||
|
|
||||||
|
List<AiRunRecord> listRuns(String taskId);
|
||||||
|
|
||||||
|
void saveFeaturePackage(AiFeaturePackage featurePackage);
|
||||||
|
|
||||||
|
List<AiFeaturePackage> listFeaturePackages(String taskId);
|
||||||
|
|
||||||
|
void saveRevision(AiRevision revision);
|
||||||
|
|
||||||
|
List<AiRevision> listRevisions(String taskId);
|
||||||
|
|
||||||
|
void saveAudit(AiAuditEntry entry);
|
||||||
|
|
||||||
|
List<AiAuditEntry> listAudit(String taskId);
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
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.AiFeaturePackage;
|
||||||
|
import com.eip4.platform.ai.model.AiRevision;
|
||||||
|
import com.eip4.platform.ai.model.AiRunRecord;
|
||||||
|
import com.eip4.platform.ai.model.AiTask;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@ConditionalOnProperty(name = "eip4.ai.store", havingValue = "memory", matchIfMissing = true)
|
||||||
|
public class InMemoryAiAgentStore implements AiAgentStore {
|
||||||
|
|
||||||
|
private final Map<String, AiTask> tasks = new ConcurrentHashMap<>();
|
||||||
|
private final Map<String, List<AiDraft>> draftsByTask = new ConcurrentHashMap<>();
|
||||||
|
private final Map<String, List<AiAuditEntry>> auditByTask = new ConcurrentHashMap<>();
|
||||||
|
private final Map<String, List<AiChangeSet>> changeSetsByTask = new ConcurrentHashMap<>();
|
||||||
|
private final Map<String, List<AiRunRecord>> runsByTask = new ConcurrentHashMap<>();
|
||||||
|
private final Map<String, List<AiFeaturePackage>> featurePackagesByTask = new ConcurrentHashMap<>();
|
||||||
|
private final Map<String, List<AiRevision>> revisionsByTask = 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<>());
|
||||||
|
featurePackagesByTask.computeIfAbsent(task.id(), ignored -> new CopyOnWriteArrayList<>());
|
||||||
|
revisionsByTask.computeIfAbsent(task.id(), ignored -> new CopyOnWriteArrayList<>());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<AiTask> findTask(String taskId) {
|
||||||
|
return Optional.ofNullable(tasks.get(taskId));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveDraft(AiDraft draft) {
|
||||||
|
draftsByTask.computeIfAbsent(draft.taskId(), ignored -> new CopyOnWriteArrayList<>()).add(draft);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiDraft> listDrafts(String taskId) {
|
||||||
|
return List.copyOf(draftsByTask.getOrDefault(taskId, List.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveChangeSet(AiChangeSet changeSet) {
|
||||||
|
changeSetsByTask.computeIfAbsent(changeSet.taskId(), ignored -> new CopyOnWriteArrayList<>()).add(changeSet);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiChangeSet> listChangeSets(String taskId) {
|
||||||
|
return List.copyOf(changeSetsByTask.getOrDefault(taskId, List.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveRun(AiRunRecord run) {
|
||||||
|
runsByTask.computeIfAbsent(run.taskId(), ignored -> new CopyOnWriteArrayList<>()).add(run);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiRunRecord> listRuns(String taskId) {
|
||||||
|
return List.copyOf(runsByTask.getOrDefault(taskId, List.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveFeaturePackage(AiFeaturePackage featurePackage) {
|
||||||
|
featurePackagesByTask.computeIfAbsent(featurePackage.taskId(), ignored -> new CopyOnWriteArrayList<>())
|
||||||
|
.add(featurePackage);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiFeaturePackage> listFeaturePackages(String taskId) {
|
||||||
|
return List.copyOf(featurePackagesByTask.getOrDefault(taskId, List.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveRevision(AiRevision revision) {
|
||||||
|
revisionsByTask.computeIfAbsent(revision.taskId(), ignored -> new CopyOnWriteArrayList<>()).add(revision);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiRevision> listRevisions(String taskId) {
|
||||||
|
return List.copyOf(revisionsByTask.getOrDefault(taskId, List.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveAudit(AiAuditEntry entry) {
|
||||||
|
auditByTask.computeIfAbsent(entry.taskId(), ignored -> new CopyOnWriteArrayList<>()).add(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiAuditEntry> listAudit(String taskId) {
|
||||||
|
return List.copyOf(auditByTask.getOrDefault(taskId, List.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
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.AiDeploymentPackage;
|
||||||
|
import com.eip4.platform.ai.model.AiDraft;
|
||||||
|
import com.eip4.platform.ai.model.AiFeaturePackage;
|
||||||
|
import com.eip4.platform.ai.model.AiGateResult;
|
||||||
|
import com.eip4.platform.ai.model.AiRevision;
|
||||||
|
import com.eip4.platform.ai.model.AiRunRecord;
|
||||||
|
import com.eip4.platform.ai.model.AiTask;
|
||||||
|
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||||
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@ConditionalOnProperty(name = "eip4.ai.store", havingValue = "jdbc")
|
||||||
|
public class JdbcAiAgentStore implements AiAgentStore {
|
||||||
|
|
||||||
|
private static final TypeReference<List<String>> STRING_LIST = new TypeReference<>() {
|
||||||
|
};
|
||||||
|
private static final TypeReference<List<AiGateResult>> GATE_LIST = new TypeReference<>() {
|
||||||
|
};
|
||||||
|
private static final TypeReference<Map<String, Object>> OBJECT_MAP = new TypeReference<>() {
|
||||||
|
};
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
public JdbcAiAgentStore(JdbcTemplate jdbcTemplate, ObjectMapper objectMapper) {
|
||||||
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveTask(AiTask task) {
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO sys_ai_task (task_id, objective, status, plan_json, created_at, updated_at)
|
||||||
|
VALUES (?, ?, ?, ?::jsonb, ?, ?)
|
||||||
|
ON CONFLICT (task_id) DO UPDATE SET
|
||||||
|
objective = EXCLUDED.objective,
|
||||||
|
status = EXCLUDED.status,
|
||||||
|
plan_json = EXCLUDED.plan_json,
|
||||||
|
updated_at = EXCLUDED.updated_at
|
||||||
|
""",
|
||||||
|
task.id(), task.objective(), task.status(), json(task.plan()), task.createdAt(), task.updatedAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Optional<AiTask> findTask(String taskId) {
|
||||||
|
List<AiTask> rows = jdbcTemplate.query("""
|
||||||
|
SELECT task_id, objective, status, plan_json, created_at, updated_at
|
||||||
|
FROM sys_ai_task
|
||||||
|
WHERE task_id = ?
|
||||||
|
""", taskMapper(), taskId);
|
||||||
|
return rows.stream().findFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveDraft(AiDraft draft) {
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO sys_ai_draft
|
||||||
|
(draft_id, task_id, artifact_type, target_id, payload_json, gates_json, metadata_json, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?::jsonb, ?::jsonb, ?::jsonb, ?)
|
||||||
|
ON CONFLICT (draft_id) DO UPDATE SET
|
||||||
|
artifact_type = EXCLUDED.artifact_type,
|
||||||
|
target_id = EXCLUDED.target_id,
|
||||||
|
payload_json = EXCLUDED.payload_json,
|
||||||
|
gates_json = EXCLUDED.gates_json,
|
||||||
|
metadata_json = EXCLUDED.metadata_json
|
||||||
|
""",
|
||||||
|
draft.id(), draft.taskId(), draft.artifactType().name(), draft.targetId(),
|
||||||
|
json(draft.payload()), json(draft.gates()), json(draft.metadata()), draft.createdAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiDraft> listDrafts(String taskId) {
|
||||||
|
return jdbcTemplate.query("""
|
||||||
|
SELECT draft_id, task_id, artifact_type, target_id, payload_json, gates_json, metadata_json, created_at
|
||||||
|
FROM sys_ai_draft
|
||||||
|
WHERE task_id = ?
|
||||||
|
ORDER BY created_at ASC, draft_id ASC
|
||||||
|
""", draftMapper(), taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveChangeSet(AiChangeSet changeSet) {
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO sys_ai_change_set
|
||||||
|
(change_set_id, task_id, status, draft_ids_json, summary_json, created_at)
|
||||||
|
VALUES (?, ?, ?, ?::jsonb, ?::jsonb, ?)
|
||||||
|
ON CONFLICT (change_set_id) DO UPDATE SET
|
||||||
|
status = EXCLUDED.status,
|
||||||
|
draft_ids_json = EXCLUDED.draft_ids_json,
|
||||||
|
summary_json = EXCLUDED.summary_json
|
||||||
|
""",
|
||||||
|
changeSet.id(), changeSet.taskId(), changeSet.status(),
|
||||||
|
json(changeSet.draftIds()), json(changeSet.summary()), changeSet.createdAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiChangeSet> listChangeSets(String taskId) {
|
||||||
|
return jdbcTemplate.query("""
|
||||||
|
SELECT change_set_id, task_id, status, draft_ids_json, summary_json, created_at
|
||||||
|
FROM sys_ai_change_set
|
||||||
|
WHERE task_id = ?
|
||||||
|
ORDER BY created_at ASC, change_set_id ASC
|
||||||
|
""", changeSetMapper(), taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveRun(AiRunRecord run) {
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO sys_ai_run
|
||||||
|
(run_id, task_id, change_set_id, run_type, status, payload_json, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?::jsonb, ?)
|
||||||
|
ON CONFLICT (run_id) DO UPDATE SET
|
||||||
|
run_type = EXCLUDED.run_type,
|
||||||
|
status = EXCLUDED.status,
|
||||||
|
payload_json = EXCLUDED.payload_json
|
||||||
|
""",
|
||||||
|
run.id(), run.taskId(), run.changeSetId(), run.runType(), run.status(),
|
||||||
|
json(run.payload()), run.createdAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiRunRecord> listRuns(String taskId) {
|
||||||
|
return jdbcTemplate.query("""
|
||||||
|
SELECT run_id, task_id, change_set_id, run_type, status, payload_json, created_at
|
||||||
|
FROM sys_ai_run
|
||||||
|
WHERE task_id = ?
|
||||||
|
ORDER BY created_at ASC, run_id ASC
|
||||||
|
""", runMapper(), taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveFeaturePackage(AiFeaturePackage featurePackage) {
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO sys_ai_feature_package
|
||||||
|
(package_id, task_id, change_set_id, status, manifest_json, deployment_package_json, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?::jsonb, ?::jsonb, ?)
|
||||||
|
ON CONFLICT (package_id) DO UPDATE SET
|
||||||
|
status = EXCLUDED.status,
|
||||||
|
manifest_json = EXCLUDED.manifest_json,
|
||||||
|
deployment_package_json = EXCLUDED.deployment_package_json
|
||||||
|
""",
|
||||||
|
featurePackage.id(), featurePackage.taskId(), featurePackage.changeSetId(), featurePackage.status(),
|
||||||
|
json(featurePackage.manifest()), json(featurePackage.deploymentPackage()), featurePackage.createdAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiFeaturePackage> listFeaturePackages(String taskId) {
|
||||||
|
return jdbcTemplate.query("""
|
||||||
|
SELECT package_id, task_id, change_set_id, status, manifest_json, deployment_package_json, created_at
|
||||||
|
FROM sys_ai_feature_package
|
||||||
|
WHERE task_id = ?
|
||||||
|
ORDER BY created_at ASC, package_id ASC
|
||||||
|
""", featurePackageMapper(), taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveRevision(AiRevision revision) {
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO sys_ai_revision
|
||||||
|
(revision_id, task_id, package_id, status, note, snapshot_json, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?::jsonb, ?)
|
||||||
|
ON CONFLICT (revision_id) DO UPDATE SET
|
||||||
|
status = EXCLUDED.status,
|
||||||
|
note = EXCLUDED.note,
|
||||||
|
snapshot_json = EXCLUDED.snapshot_json
|
||||||
|
""",
|
||||||
|
revision.id(), revision.taskId(), revision.packageId(), revision.status(), revision.note(),
|
||||||
|
json(revision.snapshot()), revision.createdAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiRevision> listRevisions(String taskId) {
|
||||||
|
return jdbcTemplate.query("""
|
||||||
|
SELECT revision_id, task_id, package_id, status, note, snapshot_json, created_at
|
||||||
|
FROM sys_ai_revision
|
||||||
|
WHERE task_id = ?
|
||||||
|
ORDER BY created_at ASC, revision_id ASC
|
||||||
|
""", revisionMapper(), taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void saveAudit(AiAuditEntry entry) {
|
||||||
|
jdbcTemplate.update("""
|
||||||
|
INSERT INTO sys_ai_audit_log
|
||||||
|
(audit_id, task_id, action, actor, details_json, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?::jsonb, ?)
|
||||||
|
ON CONFLICT (audit_id) DO UPDATE SET
|
||||||
|
action = EXCLUDED.action,
|
||||||
|
actor = EXCLUDED.actor,
|
||||||
|
details_json = EXCLUDED.details_json
|
||||||
|
""",
|
||||||
|
entry.id(), entry.taskId(), entry.action(), entry.actor(), json(entry.details()), entry.createdAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<AiAuditEntry> listAudit(String taskId) {
|
||||||
|
return jdbcTemplate.query("""
|
||||||
|
SELECT audit_id, task_id, action, actor, details_json, created_at
|
||||||
|
FROM sys_ai_audit_log
|
||||||
|
WHERE task_id = ?
|
||||||
|
ORDER BY created_at ASC, audit_id ASC
|
||||||
|
""", auditMapper(), taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private RowMapper<AiTask> taskMapper() {
|
||||||
|
return (rs, rowNum) -> new AiTask(
|
||||||
|
rs.getString("task_id"),
|
||||||
|
rs.getString("objective"),
|
||||||
|
rs.getString("status"),
|
||||||
|
rs.getLong("created_at"),
|
||||||
|
rs.getLong("updated_at"),
|
||||||
|
read(jsonText(rs, "plan_json"), STRING_LIST));
|
||||||
|
}
|
||||||
|
|
||||||
|
private RowMapper<AiDraft> draftMapper() {
|
||||||
|
return (rs, rowNum) -> new AiDraft(
|
||||||
|
rs.getString("draft_id"),
|
||||||
|
rs.getString("task_id"),
|
||||||
|
AiArtifactType.valueOf(rs.getString("artifact_type")),
|
||||||
|
rs.getString("target_id"),
|
||||||
|
readTree(jsonText(rs, "payload_json")),
|
||||||
|
rs.getLong("created_at"),
|
||||||
|
read(jsonText(rs, "gates_json"), GATE_LIST),
|
||||||
|
read(jsonText(rs, "metadata_json"), OBJECT_MAP));
|
||||||
|
}
|
||||||
|
|
||||||
|
private RowMapper<AiChangeSet> changeSetMapper() {
|
||||||
|
return (rs, rowNum) -> new AiChangeSet(
|
||||||
|
rs.getString("change_set_id"),
|
||||||
|
rs.getString("task_id"),
|
||||||
|
rs.getString("status"),
|
||||||
|
rs.getLong("created_at"),
|
||||||
|
read(jsonText(rs, "draft_ids_json"), STRING_LIST),
|
||||||
|
read(jsonText(rs, "summary_json"), OBJECT_MAP));
|
||||||
|
}
|
||||||
|
|
||||||
|
private RowMapper<AiAuditEntry> auditMapper() {
|
||||||
|
return (rs, rowNum) -> new AiAuditEntry(
|
||||||
|
rs.getString("audit_id"),
|
||||||
|
rs.getString("task_id"),
|
||||||
|
rs.getString("action"),
|
||||||
|
rs.getString("actor"),
|
||||||
|
rs.getLong("created_at"),
|
||||||
|
read(jsonText(rs, "details_json"), OBJECT_MAP));
|
||||||
|
}
|
||||||
|
|
||||||
|
private RowMapper<AiRunRecord> runMapper() {
|
||||||
|
return (rs, rowNum) -> new AiRunRecord(
|
||||||
|
rs.getString("run_id"),
|
||||||
|
rs.getString("task_id"),
|
||||||
|
rs.getString("change_set_id"),
|
||||||
|
rs.getString("run_type"),
|
||||||
|
rs.getString("status"),
|
||||||
|
rs.getLong("created_at"),
|
||||||
|
readTree(jsonText(rs, "payload_json")));
|
||||||
|
}
|
||||||
|
|
||||||
|
private RowMapper<AiFeaturePackage> featurePackageMapper() {
|
||||||
|
return (rs, rowNum) -> new AiFeaturePackage(
|
||||||
|
rs.getString("package_id"),
|
||||||
|
rs.getString("task_id"),
|
||||||
|
rs.getString("change_set_id"),
|
||||||
|
rs.getString("status"),
|
||||||
|
rs.getLong("created_at"),
|
||||||
|
read(jsonText(rs, "manifest_json"), OBJECT_MAP),
|
||||||
|
read(jsonText(rs, "deployment_package_json"), AiDeploymentPackage.class));
|
||||||
|
}
|
||||||
|
|
||||||
|
private RowMapper<AiRevision> revisionMapper() {
|
||||||
|
return (rs, rowNum) -> new AiRevision(
|
||||||
|
rs.getString("revision_id"),
|
||||||
|
rs.getString("task_id"),
|
||||||
|
rs.getString("package_id"),
|
||||||
|
rs.getString("status"),
|
||||||
|
rs.getString("note"),
|
||||||
|
rs.getLong("created_at"),
|
||||||
|
readTree(jsonText(rs, "snapshot_json")));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String json(Object value) {
|
||||||
|
try {
|
||||||
|
return objectMapper.writeValueAsString(value);
|
||||||
|
} catch (JsonProcessingException ex) {
|
||||||
|
throw new IllegalArgumentException("AI Agent 产物 JSON 序列化失败", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T read(String json, TypeReference<T> type) {
|
||||||
|
try {
|
||||||
|
return objectMapper.readValue(json, type);
|
||||||
|
} catch (JsonProcessingException ex) {
|
||||||
|
throw new IllegalArgumentException("AI Agent 产物 JSON 反序列化失败", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T read(String json, Class<T> type) {
|
||||||
|
try {
|
||||||
|
return objectMapper.readValue(json, type);
|
||||||
|
} catch (JsonProcessingException ex) {
|
||||||
|
throw new IllegalArgumentException("AI Agent 产物 JSON 反序列化失败", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode readTree(String json) {
|
||||||
|
try {
|
||||||
|
return objectMapper.readTree(json);
|
||||||
|
} catch (JsonProcessingException ex) {
|
||||||
|
throw new IllegalArgumentException("AI Agent schema JSON 反序列化失败", ex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String jsonText(ResultSet rs, String column) throws SQLException {
|
||||||
|
Object value = rs.getObject(column);
|
||||||
|
if (value == null) {
|
||||||
|
return "{}";
|
||||||
|
}
|
||||||
|
return String.valueOf(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
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.AiFeaturePackage;
|
||||||
|
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.AiRevision;
|
||||||
|
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.model.AiToolAccessDecision;
|
||||||
|
import com.eip4.platform.ai.model.AiToolAccessRequest;
|
||||||
|
import com.eip4.platform.ai.model.AiToolDefinition;
|
||||||
|
import com.eip4.platform.ai.model.AiEmployeeDefinition;
|
||||||
|
import com.eip4.platform.ai.service.AiAgentService;
|
||||||
|
import com.eip4.platform.metadata.schema.blueprint.PageRecipeDefinition;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
|
||||||
|
@Tag(name = "AI Agent 开发工具", description = "受控任务/草稿/变更包/校验接口;生产发布前的人审边界")
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/api/ai")
|
||||||
|
public class AiAgentController {
|
||||||
|
|
||||||
|
private final AiAgentService service;
|
||||||
|
|
||||||
|
public AiAgentController(AiAgentService service) {
|
||||||
|
this.service = service;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "创建 Agent 开发任务", description = "只创建受控任务和初始计划,不执行线上变更")
|
||||||
|
@PostMapping("/tasks")
|
||||||
|
public AiTask createTask(@RequestBody CreateTaskRequest req) {
|
||||||
|
return service.createTask(req.objective());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "自动开发功能草稿", description = "创建任务并生成实体/页面/服务流/菜单/测试草稿,门禁通过后生成待人审变更包")
|
||||||
|
@PostMapping("/features/develop")
|
||||||
|
public AiFeatureDevelopment developFeature(@RequestBody AiFeatureRequest req) {
|
||||||
|
return service.developFeature(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "一键自动开发功能", description = "生成草稿、变更包、发布计划,执行本地落库和 smoke,并生成线上人工部署包")
|
||||||
|
@PostMapping("/features/auto-develop")
|
||||||
|
public AiAutoDevelopmentRun autoDevelopFeature(@RequestBody(required = false) AiAutoDevelopmentRequest req) {
|
||||||
|
return service.autoDevelopFeature(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "查看 Agent 开发任务")
|
||||||
|
@GetMapping("/tasks/{taskId}")
|
||||||
|
public AiTask task(@PathVariable String taskId) {
|
||||||
|
return service.getTask(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "保存 Agent 草稿产物", description = "PAGE_SCHEMA 草稿会自动跑 amis schema 校验")
|
||||||
|
@PostMapping("/tasks/{taskId}/drafts")
|
||||||
|
public AiDraft addDraft(@PathVariable String taskId, @RequestBody CreateDraftRequest req) {
|
||||||
|
return service.addDraft(taskId, req.artifactType(), req.targetId(), req.payload(), req.metadata());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "列出任务草稿")
|
||||||
|
@GetMapping("/tasks/{taskId}/drafts")
|
||||||
|
public List<AiDraft> drafts(@PathVariable String taskId) {
|
||||||
|
return service.listDrafts(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "在既有任务下自动开发功能草稿")
|
||||||
|
@PostMapping("/tasks/{taskId}/develop-feature")
|
||||||
|
public AiFeatureDevelopment developFeature(@PathVariable String taskId, @RequestBody AiFeatureRequest req) {
|
||||||
|
return service.developFeature(taskId, req);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "生成待人审变更包", description = "任何草稿门禁失败时拒绝生成")
|
||||||
|
@PostMapping("/tasks/{taskId}/change-sets")
|
||||||
|
public AiChangeSet createChangeSet(@PathVariable String taskId) {
|
||||||
|
return service.createChangeSet(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "列出任务变更包")
|
||||||
|
@GetMapping("/tasks/{taskId}/change-sets")
|
||||||
|
public List<AiChangeSet> changeSets(@PathVariable String taskId) {
|
||||||
|
return service.listChangeSets(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "生成变更包发布计划", description = "按实体→服务流→页面→菜单→smoke 排序;线上发布仍要求人工批准")
|
||||||
|
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/release-plan")
|
||||||
|
public AiReleasePlan releasePlan(@PathVariable String taskId, @PathVariable String changeSetId) {
|
||||||
|
return service.createReleasePlan(taskId, changeSetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "运行本地 smoke 门禁", description = "只允许访问本机 baseUrl;返回逐条 HTTP smoke 结果")
|
||||||
|
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/smoke")
|
||||||
|
public AiSmokeRun runSmoke(@PathVariable String taskId,
|
||||||
|
@PathVariable String changeSetId,
|
||||||
|
@RequestBody(required = false) SmokeRunRequest req) {
|
||||||
|
return service.runLocalSmoke(taskId, changeSetId, req == null ? null : req.baseUrl());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "本地应用变更包并运行 smoke", description = "仅允许本机 baseUrl;不会执行线上部署")
|
||||||
|
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/local-apply")
|
||||||
|
public AiApplyRun localApply(@PathVariable String taskId,
|
||||||
|
@PathVariable String changeSetId,
|
||||||
|
@RequestBody(required = false) SmokeRunRequest req) {
|
||||||
|
return service.applyLocalRelease(taskId, changeSetId, req == null ? null : req.baseUrl());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "列出任务执行证据", description = "包含本地 smoke 和本地 apply 的结构化结果")
|
||||||
|
@GetMapping("/tasks/{taskId}/runs")
|
||||||
|
public List<AiRunRecord> runs(@PathVariable String taskId) {
|
||||||
|
return service.listRuns(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "列出变更包执行证据", description = "按变更包过滤本地 smoke/apply 结构化结果")
|
||||||
|
@GetMapping("/tasks/{taskId}/change-sets/{changeSetId}/runs")
|
||||||
|
public List<AiRunRecord> runs(@PathVariable String taskId, @PathVariable String changeSetId) {
|
||||||
|
return service.listRuns(taskId, changeSetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "生成线上人工部署包", description = "输出 manifest、SQL 草案、回滚 SQL 和本地执行证据;不连接线上环境执行")
|
||||||
|
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/deployment-package")
|
||||||
|
public AiDeploymentPackage deploymentPackage(@PathVariable String taskId, @PathVariable String changeSetId) {
|
||||||
|
return service.createDeploymentPackage(taskId, changeSetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "生成 AI 功能包快照", description = "封装部署包、manifest、本地 evidence 和回滚 SQL;用于人审、导出和里程碑版本")
|
||||||
|
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/feature-package")
|
||||||
|
public AiFeaturePackage featurePackage(@PathVariable String taskId, @PathVariable String changeSetId) {
|
||||||
|
return service.createFeaturePackage(taskId, changeSetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "列出任务功能包快照")
|
||||||
|
@GetMapping("/tasks/{taskId}/feature-packages")
|
||||||
|
public List<AiFeaturePackage> featurePackages(@PathVariable String taskId) {
|
||||||
|
return service.listFeaturePackages(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "保存 AI 功能包里程碑", description = "保存功能包快照作为可追溯 revision;后续回滚/差异比较基于该快照扩展")
|
||||||
|
@PostMapping("/tasks/{taskId}/feature-packages/{packageId}/revisions")
|
||||||
|
public AiRevision createRevision(@PathVariable String taskId,
|
||||||
|
@PathVariable String packageId,
|
||||||
|
@RequestBody(required = false) CreateRevisionRequest req) {
|
||||||
|
return service.createRevision(taskId, packageId, req == null ? "" : req.note());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "列出任务 AI 里程碑版本")
|
||||||
|
@GetMapping("/tasks/{taskId}/revisions")
|
||||||
|
public List<AiRevision> revisions(@PathVariable String taskId) {
|
||||||
|
return service.listRevisions(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "生成自动修复计划", description = "读取最近失败的自动开发/本地应用/smoke 证据,输出结构化修复动作并写入 run history")
|
||||||
|
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/repair-plan")
|
||||||
|
public AiRepairPlan repairPlan(@PathVariable String taskId, @PathVariable String changeSetId) {
|
||||||
|
return service.createRepairPlan(taskId, changeSetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "执行自动修复并重跑本地门禁", description = "仅执行 repair-plan 中标记 automated=true 的动作;存在人工动作时阻断")
|
||||||
|
@PostMapping("/tasks/{taskId}/change-sets/{changeSetId}/repair-execution")
|
||||||
|
public AiRepairExecution executeRepairPlan(@PathVariable String taskId,
|
||||||
|
@PathVariable String changeSetId,
|
||||||
|
@RequestBody(required = false) AiRepairExecutionRequest req) {
|
||||||
|
return service.executeRepairPlan(taskId, changeSetId, req == null ? null : req.baseUrl());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "列出任务审计日志")
|
||||||
|
@GetMapping("/tasks/{taskId}/audit")
|
||||||
|
public List<AiAuditEntry> audit(@PathVariable String taskId) {
|
||||||
|
return service.listAudit(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "校验任意 amis schema", description = "AI 生成 schema 的第一道闸;后续仍需渲染冒烟")
|
||||||
|
@PostMapping("/tools/validate-schema")
|
||||||
|
public Map<String, Object> validateSchema(@RequestBody JsonNode schema) {
|
||||||
|
return service.validateSchema(schema);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "列出 AI 工具注册表", description = "返回工具、操作入口、所需 scope 和生产写边界")
|
||||||
|
@GetMapping("/tools")
|
||||||
|
public List<AiToolDefinition> tools() {
|
||||||
|
return service.listTools();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "列出 AI 员工定义", description = "返回 AI employee 可用工具、所需 scope 和策略")
|
||||||
|
@GetMapping("/employees")
|
||||||
|
public List<AiEmployeeDefinition> employees() {
|
||||||
|
return service.listEmployees();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "列出 AI 页面 recipe", description = "返回 Agent 生成页面前必须读取的 EIP4 UI/UE recipe 定义")
|
||||||
|
@GetMapping("/page-recipes")
|
||||||
|
public List<PageRecipeDefinition> pageRecipes() {
|
||||||
|
return service.listPageRecipes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "查看 AI 页面 recipe", description = "按 recipe id 返回字段映射、门禁和版本信息")
|
||||||
|
@GetMapping("/page-recipes/{recipe}")
|
||||||
|
public PageRecipeDefinition pageRecipe(@PathVariable String recipe) {
|
||||||
|
return service.getPageRecipe(recipe);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "检查 AI 工具访问权限", description = "只做权限判定,不执行工具;生产写默认阻断")
|
||||||
|
@PostMapping("/tools/access-check")
|
||||||
|
public AiToolAccessDecision checkToolAccess(@RequestBody(required = false) AiToolAccessRequest request) {
|
||||||
|
return service.checkToolAccess(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
public record CreateTaskRequest(String objective) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record CreateDraftRequest(
|
||||||
|
String artifactType,
|
||||||
|
String targetId,
|
||||||
|
JsonNode payload,
|
||||||
|
Map<String, Object> metadata) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record SmokeRunRequest(String baseUrl) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record CreateRevisionRequest(String note) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
schemaVersion: 1
|
||||||
|
recipe: maintenance-crud-v1
|
||||||
|
title: EIP4 maintenance CRUD page
|
||||||
|
purpose: 普通实体维护页,覆盖列表、新增、编辑、删除。
|
||||||
|
compiler: com.eip4.platform.metadata.schema.blueprint.PageBlueprintCompiler
|
||||||
|
amis:
|
||||||
|
rootType: page
|
||||||
|
body:
|
||||||
|
type: crud
|
||||||
|
syncLocation: false
|
||||||
|
perPage: 20
|
||||||
|
apiPattern: /api/entity/{tableName}/list?page=${page}&perPage=${perPage}
|
||||||
|
headerToolbar:
|
||||||
|
- addButton:
|
||||||
|
label: 新增
|
||||||
|
level: primary
|
||||||
|
icon: fa fa-plus
|
||||||
|
actionType: dialog
|
||||||
|
formApiPattern: post:/api/entity/{tableName}/save
|
||||||
|
- pagination
|
||||||
|
footerToolbar:
|
||||||
|
- statistics
|
||||||
|
- pagination
|
||||||
|
operationColumn:
|
||||||
|
label: 操作
|
||||||
|
width: 180
|
||||||
|
actions:
|
||||||
|
- edit:
|
||||||
|
level: link
|
||||||
|
actionType: dialog
|
||||||
|
formApiPattern: post:/api/entity/{tableName}/save
|
||||||
|
- delete:
|
||||||
|
level: link
|
||||||
|
className: text-danger
|
||||||
|
actionType: ajax
|
||||||
|
confirmText: 确认删除该记录?
|
||||||
|
apiPattern: /api/entity/{tableName}/delete
|
||||||
|
fieldMappings:
|
||||||
|
string: input-text
|
||||||
|
integer: input-number
|
||||||
|
number: input-number
|
||||||
|
date: input-date
|
||||||
|
datetime: input-datetime
|
||||||
|
boolean: switch
|
||||||
|
gates:
|
||||||
|
- page-recipe
|
||||||
|
- typed-page-schema
|
||||||
|
- amis-schema
|
||||||
|
- local-smoke
|
||||||
|
- playwright-render
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
schemaVersion: 1
|
||||||
|
recipe: tree-crud-v1
|
||||||
|
title: EIP4 tree CRUD page
|
||||||
|
purpose: 自引用层级实体维护页,覆盖树形列表、新增顶级、加子项、编辑、删除。
|
||||||
|
compiler: com.eip4.platform.metadata.schema.blueprint.PageBlueprintCompiler
|
||||||
|
requirements:
|
||||||
|
parentField: PARENTID
|
||||||
|
childrenColumnName: children
|
||||||
|
amis:
|
||||||
|
rootType: page
|
||||||
|
body:
|
||||||
|
type: crud
|
||||||
|
syncLocation: false
|
||||||
|
childrenColumnName: children
|
||||||
|
apiPattern: /api/entity/{tableName}/tree?parentKey=PARENTID&idKey={primaryKey}&perPage=2000
|
||||||
|
headerToolbar:
|
||||||
|
- addRootButton:
|
||||||
|
labelPattern: 新增顶级{entityName}
|
||||||
|
level: primary
|
||||||
|
icon: fa fa-plus
|
||||||
|
actionType: dialog
|
||||||
|
formApiPattern: post:/api/entity/{tableName}/save
|
||||||
|
- reloadButton:
|
||||||
|
label: 刷新
|
||||||
|
level: link
|
||||||
|
icon: fa fa-refresh
|
||||||
|
actionType: reload
|
||||||
|
targetPattern: "{crudName}"
|
||||||
|
footerToolbar: []
|
||||||
|
operationColumn:
|
||||||
|
label: 操作
|
||||||
|
width: 240
|
||||||
|
actions:
|
||||||
|
- addChild:
|
||||||
|
labelPattern: 加子{entityName}
|
||||||
|
level: link
|
||||||
|
actionType: dialog
|
||||||
|
parentBinding: PARENTID=${primaryKey}
|
||||||
|
formApiPattern: post:/api/entity/{tableName}/save
|
||||||
|
- edit:
|
||||||
|
level: link
|
||||||
|
actionType: dialog
|
||||||
|
formApiPattern: post:/api/entity/{tableName}/save
|
||||||
|
- delete:
|
||||||
|
level: link
|
||||||
|
className: text-danger
|
||||||
|
actionType: ajax
|
||||||
|
confirmText: 确认删除该记录?
|
||||||
|
apiPattern: /api/entity/{tableName}/delete
|
||||||
|
fieldMappings:
|
||||||
|
string: input-text
|
||||||
|
integer: input-number
|
||||||
|
number: input-number
|
||||||
|
date: input-date
|
||||||
|
datetime: input-datetime
|
||||||
|
boolean: switch
|
||||||
|
gates:
|
||||||
|
- page-recipe
|
||||||
|
- typed-page-schema
|
||||||
|
- amis-schema
|
||||||
|
- local-smoke
|
||||||
|
- playwright-render
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
-- ============================================================================
|
||||||
|
-- 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_feature_package (
|
||||||
|
package_id character varying(64) NOT NULL,
|
||||||
|
task_id character varying(64) NOT NULL,
|
||||||
|
change_set_id character varying(64) NOT NULL,
|
||||||
|
status character varying(32) NOT NULL,
|
||||||
|
manifest_json jsonb NOT NULL,
|
||||||
|
deployment_package_json jsonb NOT NULL,
|
||||||
|
created_at bigint NOT NULL,
|
||||||
|
CONSTRAINT pk_sys_ai_feature_package PRIMARY KEY (package_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sys_ai_revision (
|
||||||
|
revision_id character varying(64) NOT NULL,
|
||||||
|
task_id character varying(64) NOT NULL,
|
||||||
|
package_id character varying(64) NOT NULL,
|
||||||
|
status character varying(32) NOT NULL,
|
||||||
|
note text NOT NULL,
|
||||||
|
snapshot_json jsonb NOT NULL,
|
||||||
|
created_at bigint NOT NULL,
|
||||||
|
CONSTRAINT pk_sys_ai_revision PRIMARY KEY (revision_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_feature_package_task ON sys_ai_feature_package (task_id, created_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sys_ai_revision_task ON sys_ai_revision (task_id, created_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sys_ai_audit_log_task ON sys_ai_audit_log (task_id, created_at);
|
||||||
@@ -0,0 +1,839 @@
|
|||||||
|
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;
|
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
|
||||||
|
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("页面草稿必须通过 typed 组件注册表门禁")
|
||||||
|
void typedPageSchemaGateBlocksUnsupportedComponent() throws Exception {
|
||||||
|
AiAgentService service = newService();
|
||||||
|
var task = service.createTask("生成未注册组件页面");
|
||||||
|
JsonNode invalid = MAPPER.readTree("""
|
||||||
|
{"type":"page","title":"坏页面","body":{"type":"evil-widget"}}
|
||||||
|
""");
|
||||||
|
|
||||||
|
var draft = service.addDraft(task.id(), "PAGE_SCHEMA", "bad-component-page", invalid, null);
|
||||||
|
|
||||||
|
assertFalse(draft.passed());
|
||||||
|
assertTrue(draft.gates().stream().anyMatch(g -> "typed-page-schema".equals(g.name()) && !g.passed()));
|
||||||
|
assertTrue(draft.gates().stream().flatMap(g -> g.messages().stream())
|
||||||
|
.anyMatch(m -> m.contains("UNSUPPORTED_COMPONENT")));
|
||||||
|
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
|
||||||
|
() -> service.createChangeSet(task.id()));
|
||||||
|
assertEquals(409, ex.getStatusCode().value());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("AI schema 校验工具返回 AMIS + typed 双闸结果")
|
||||||
|
void validateSchemaReturnsCombinedGateReport() throws Exception {
|
||||||
|
AiAgentService service = newService();
|
||||||
|
JsonNode invalid = MAPPER.readTree("""
|
||||||
|
{"type":"page","body":{"type":"evil-widget"}}
|
||||||
|
""");
|
||||||
|
|
||||||
|
Map<String, Object> report = service.validateSchema(invalid);
|
||||||
|
|
||||||
|
assertEquals(false, report.get("valid"));
|
||||||
|
assertEquals(true, report.get("schemaValid"));
|
||||||
|
assertEquals(false, report.get("typedSchemaValid"));
|
||||||
|
assertTrue(report.get("validationErrors").toString().contains("UNSUPPORTED_COMPONENT"));
|
||||||
|
assertTrue(report.get("typedSchemaIssues").toString().contains("evil-widget"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@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("TEST 草稿必须包含页面渲染计划")
|
||||||
|
void testDraftRequiresRenderPlan() throws Exception {
|
||||||
|
AiAgentService service = newService();
|
||||||
|
var task = service.createTask("验证渲染计划门禁");
|
||||||
|
JsonNode payload = MAPPER.readTree("""
|
||||||
|
{"publishTarget":"local-smoke","smokeTests":[
|
||||||
|
{"name":"page-schema","method":"GET","url":"/api/page/schema/demo","expectHttpStatus":200}
|
||||||
|
]}
|
||||||
|
""");
|
||||||
|
|
||||||
|
var draft = service.addDraft(task.id(), "TEST", "demo-smoke", payload, null);
|
||||||
|
|
||||||
|
assertFalse(draft.passed());
|
||||||
|
assertTrue(draft.gates().stream()
|
||||||
|
.anyMatch(g -> "render-plan".equals(g.name()) && !g.passed()
|
||||||
|
&& g.messages().toString().contains("renderTests")));
|
||||||
|
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
|
||||||
|
() -> service.createChangeSet(task.id()));
|
||||||
|
assertEquals(409, ex.getStatusCode().value());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("TEST 渲染计划必须声明列和动作断言")
|
||||||
|
void testDraftRequiresRenderColumnsAndActions() throws Exception {
|
||||||
|
AiAgentService service = newService();
|
||||||
|
var task = service.createTask("验证渲染计划细节门禁");
|
||||||
|
JsonNode payload = MAPPER.readTree("""
|
||||||
|
{
|
||||||
|
"publishTarget":"local-smoke",
|
||||||
|
"smokeTests":[
|
||||||
|
{"name":"page-schema","method":"GET","url":"/api/page/schema/demo","expectHttpStatus":200}
|
||||||
|
],
|
||||||
|
"renderTests":[
|
||||||
|
{
|
||||||
|
"name":"page-render",
|
||||||
|
"recipe":"maintenance-crud-v1",
|
||||||
|
"schemaUrl":"/api/page/schema/demo",
|
||||||
|
"previewUrl":"/amis.html?schema=demo",
|
||||||
|
"expectedRootType":"page",
|
||||||
|
"expectedBodyType":"crud",
|
||||||
|
"expectedCrudName":"demoCrud",
|
||||||
|
"expectedApi":"/api/entity/EIP4AI_DEMO/list?page=${page}&perPage=${perPage}",
|
||||||
|
"expectedComponents":["page","crud"],
|
||||||
|
"expectedTexts":["示例"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
|
||||||
|
var draft = service.addDraft(task.id(), "TEST", "demo-smoke", payload, null);
|
||||||
|
|
||||||
|
assertFalse(draft.passed());
|
||||||
|
assertTrue(draft.gates().stream()
|
||||||
|
.anyMatch(g -> "render-plan".equals(g.name()) && !g.passed()
|
||||||
|
&& g.messages().toString().contains("expectedColumns")
|
||||||
|
&& g.messages().toString().contains("expectedActions")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@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()), "自动生成草稿必须全部过基础门禁");
|
||||||
|
assertTrue(result.drafts().stream()
|
||||||
|
.filter(d -> d.artifactType() == AiArtifactType.PAGE_SCHEMA)
|
||||||
|
.flatMap(d -> d.gates().stream())
|
||||||
|
.anyMatch(g -> "page-recipe".equals(g.name()) && g.passed()));
|
||||||
|
assertEquals("READY_FOR_REVIEW", result.changeSet().status());
|
||||||
|
assertEquals(5, result.changeSet().draftIds().size());
|
||||||
|
assertEquals(5, service.listDrafts(result.task().id()).size());
|
||||||
|
|
||||||
|
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.sqlStatements().stream().anyMatch(sql -> sql.contains("::xml")));
|
||||||
|
assertTrue(deploymentPackage.rollbackSqlStatements().stream().anyMatch(sql -> sql.contains("sys_serviceflow")));
|
||||||
|
assertTrue(deploymentPackage.warnings().stream().anyMatch(w -> w.contains("parentId")));
|
||||||
|
|
||||||
|
var featurePackage = service.createFeaturePackage(result.task().id(), result.changeSet().id());
|
||||||
|
assertEquals("READY_FOR_HUMAN_REVIEW", featurePackage.status());
|
||||||
|
assertEquals(result.changeSet().id(), featurePackage.changeSetId());
|
||||||
|
assertEquals("EIP4_AI_FEATURE_PACKAGE", featurePackage.manifest().get("packageType"));
|
||||||
|
assertEquals(1, service.listFeaturePackages(result.task().id()).size());
|
||||||
|
|
||||||
|
var revision = service.createRevision(result.task().id(), featurePackage.id(), "本地门禁通过");
|
||||||
|
assertEquals("RESTORABLE", revision.status());
|
||||||
|
assertEquals(featurePackage.id(), revision.packageId());
|
||||||
|
assertEquals("本地门禁通过", revision.note());
|
||||||
|
assertEquals(featurePackage.id(), revision.snapshot().path("id").asText());
|
||||||
|
assertEquals(1, service.listRevisions(result.task().id()).size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("声明 PageBlueprint 的页面草稿必须匹配 recipe 编译结果")
|
||||||
|
void pageRecipeGateRejectsTamperedSchema() {
|
||||||
|
AiAgentService service = newService();
|
||||||
|
var generated = new AiFeatureDraftGenerator(MAPPER).generate(contractTypeFeature()).stream()
|
||||||
|
.filter(d -> d.artifactType() == AiArtifactType.PAGE_SCHEMA)
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
ObjectNode tampered = generated.payload().deepCopy();
|
||||||
|
tampered.put("title", "被篡改标题");
|
||||||
|
var task = service.createTask("验证 page recipe 门禁");
|
||||||
|
|
||||||
|
var draft = service.addDraft(task.id(), "PAGE_SCHEMA", generated.targetId(), tampered, generated.metadata());
|
||||||
|
|
||||||
|
assertFalse(draft.passed());
|
||||||
|
assertTrue(draft.gates().stream()
|
||||||
|
.anyMatch(g -> "page-recipe".equals(g.name()) && !g.passed()
|
||||||
|
&& g.messages().toString().contains("$.title")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("一键自动开发会串联草稿生成、本地应用、smoke 和部署包")
|
||||||
|
void autoDevelopFeatureRunsFullPipeline() {
|
||||||
|
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 = testPayload("page-schema", "/api/page/schema/bad-page");
|
||||||
|
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 = testPayload("page-schema", "/api/page/schema/bad-page");
|
||||||
|
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":"<flow><input entityid=\\"wrong-entity-id\\"/><transition/></flow>"}]}
|
||||||
|
""");
|
||||||
|
service.addDraft(task.id(), "SERVICEFLOW", "EIP4AI_FLOW_FIX_DEFAULT_FLOWS", serviceFlow, Map.of());
|
||||||
|
JsonNode testPayload = testPayload("flow-search", "/api/flow/EIP4AI_FLOW_FIX_SEARCH");
|
||||||
|
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 = testPayload("entity-list", "/api/entity/EIP4AI_ENTITY_FIX/list");
|
||||||
|
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 = testPayload("entity-list", "/api/entity/EIP4AI_ENTITY_FIX/list");
|
||||||
|
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 JsonNode testPayload(String smokeName, String smokeUrl) {
|
||||||
|
return json("""
|
||||||
|
{
|
||||||
|
"smokeTests": [
|
||||||
|
{"name": "%s", "method": "GET", "url": "%s", "expectHttpStatus": 200}
|
||||||
|
],
|
||||||
|
"renderTests": [
|
||||||
|
{
|
||||||
|
"name": "page-render",
|
||||||
|
"recipe": "maintenance-crud-v1",
|
||||||
|
"schemaUrl": "/api/page/schema/test-page",
|
||||||
|
"previewUrl": "/amis.html?schema=test-page",
|
||||||
|
"expectedRootType": "page",
|
||||||
|
"expectedBodyType": "crud",
|
||||||
|
"expectedCrudName": "testPageCrud",
|
||||||
|
"expectedApi": "/api/entity/EIP4AI_TEST/list?page=${page}&perPage=${perPage}",
|
||||||
|
"expectedComponents": ["page", "crud", "form", "button"],
|
||||||
|
"expectedColumns": [{"name": "NAME", "label": "名称"}],
|
||||||
|
"expectedActions": ["新增", "编辑", "删除"],
|
||||||
|
"expectedTexts": ["测试页面"]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
""".formatted(smokeName, smokeUrl));
|
||||||
|
}
|
||||||
|
|
||||||
|
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<com.eip4.platform.ai.model.AiApplyStepResult> apply(
|
||||||
|
String baseUrl, java.util.List<com.eip4.platform.ai.model.AiDraft> drafts) {
|
||||||
|
return drafts.stream()
|
||||||
|
.filter(d -> d.artifactType() != com.eip4.platform.ai.model.AiArtifactType.TEST)
|
||||||
|
.map(d -> {
|
||||||
|
Map<String, Object> 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<com.eip4.platform.ai.model.AiApplyStepResult> apply(
|
||||||
|
String baseUrl, java.util.List<com.eip4.platform.ai.model.AiDraft> 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<com.eip4.platform.ai.model.AiApplyStepResult> apply(
|
||||||
|
String baseUrl, java.util.List<com.eip4.platform.ai.model.AiDraft> drafts) {
|
||||||
|
java.util.List<com.eip4.platform.ai.model.AiApplyStepResult> 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<com.eip4.platform.ai.model.AiApplyStepResult> apply(
|
||||||
|
String baseUrl, java.util.List<com.eip4.platform.ai.model.AiDraft> drafts) {
|
||||||
|
java.util.List<com.eip4.platform.ai.model.AiApplyStepResult> 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<com.eip4.platform.ai.model.AiApplyStepResult> apply(
|
||||||
|
String baseUrl, java.util.List<com.eip4.platform.ai.model.AiDraft> drafts) {
|
||||||
|
java.util.List<com.eip4.platform.ai.model.AiApplyStepResult> 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<com.eip4.platform.ai.model.AiApplyStepResult> apply(
|
||||||
|
String baseUrl, java.util.List<com.eip4.platform.ai.model.AiDraft> drafts) {
|
||||||
|
java.util.List<com.eip4.platform.ai.model.AiApplyStepResult> 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
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.assertThrows;
|
||||||
|
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.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 pageSchema = drafts.stream().filter(d -> d.artifactType() == AiArtifactType.PAGE_SCHEMA)
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
assertEquals("maintenance-crud-v1", pageSchema.metadata().get("pageRecipe"));
|
||||||
|
assertEquals(1, pageSchema.metadata().get("pageBlueprintVersion"));
|
||||||
|
assertEquals("crud", pageSchema.payload().path("body").path("type").asText());
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
Map<String, Object> blueprint = (Map<String, Object>) pageSchema.metadata().get("pageBlueprint");
|
||||||
|
assertEquals("EIP4AI_CONTRACT_TYPE", blueprint.get("tableName"));
|
||||||
|
assertEquals("NAME", blueprint.get("displayField"));
|
||||||
|
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"));
|
||||||
|
assertEquals("maintenance-crud-v1", test.payload().path("renderTests").get(0).path("recipe").asText());
|
||||||
|
assertEquals("/api/page/schema/eip4ai-contract-type",
|
||||||
|
test.payload().path("renderTests").get(0).path("schemaUrl").asText());
|
||||||
|
assertEquals("/amis.html?schema=eip4ai-contract-type",
|
||||||
|
test.payload().path("renderTests").get(0).path("previewUrl").asText());
|
||||||
|
assertEquals("eip4aiContractTypeCrud",
|
||||||
|
test.payload().path("renderTests").get(0).path("expectedCrudName").asText());
|
||||||
|
assertEquals("NAME", test.payload().path("renderTests").get(0)
|
||||||
|
.path("expectedColumns").get(0).path("name").asText());
|
||||||
|
assertTrue(hasText(test.payload().path("renderTests").get(0).path("expectedActions"), "新增"));
|
||||||
|
assertTrue(hasText(test.payload().path("renderTests").get(0).path("expectedActions"), "编辑"));
|
||||||
|
assertTrue(hasText(test.payload().path("renderTests").get(0).path("expectedActions"), "删除"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@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());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("树形配方生成 tree-crud 页面和树接口 smoke")
|
||||||
|
void generatesTreeCrudFeatureDrafts() {
|
||||||
|
AiFeatureDraftGenerator generator = new AiFeatureDraftGenerator(MAPPER);
|
||||||
|
|
||||||
|
var drafts = generator.generate(new AiFeatureRequest(
|
||||||
|
"新增组织分类维护",
|
||||||
|
"组织分类维护",
|
||||||
|
"EIP4AI_ORG_CATEGORY",
|
||||||
|
"组织分类",
|
||||||
|
"eip4ai-org-category",
|
||||||
|
"组织分类维护",
|
||||||
|
List.of(
|
||||||
|
new AiFeatureField("NAME", "名称", "string", 100, true),
|
||||||
|
new AiFeatureField("CODE", "编码", "string", 64, true)),
|
||||||
|
"tree-crud-v1"));
|
||||||
|
|
||||||
|
var entity = drafts.stream().filter(d -> d.artifactType() == AiArtifactType.ENTITY)
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
assertTrue(hasAttribute(entity.payload().path("attributes"), "PARENTID"));
|
||||||
|
|
||||||
|
var pageSchema = drafts.stream().filter(d -> d.artifactType() == AiArtifactType.PAGE_SCHEMA)
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
assertEquals("tree-crud-v1", pageSchema.metadata().get("pageRecipe"));
|
||||||
|
assertEquals("crud", pageSchema.payload().path("body").path("type").asText());
|
||||||
|
assertEquals("children", pageSchema.payload().path("body").path("childrenColumnName").asText());
|
||||||
|
assertEquals("/api/entity/EIP4AI_ORG_CATEGORY/tree?parentKey=PARENTID&idKey=EIP4AI_ORG_CATEGORY_ID&perPage=2000",
|
||||||
|
pageSchema.payload().path("body").path("api").path("url").asText());
|
||||||
|
assertFalse(hasColumn(pageSchema.payload().path("body").path("columns"), "PARENTID"));
|
||||||
|
|
||||||
|
var test = drafts.stream().filter(d -> d.artifactType() == AiArtifactType.TEST)
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
assertEquals("entity-tree", test.payload().path("smokeTests").get(1).path("name").asText());
|
||||||
|
assertEquals("/api/entity/EIP4AI_ORG_CATEGORY/tree?parentKey=PARENTID&idKey=EIP4AI_ORG_CATEGORY_ID&perPage=2000",
|
||||||
|
test.payload().path("smokeTests").get(1).path("url").asText());
|
||||||
|
assertEquals("", test.payload().path("smokeTests").get(3).path("requestBody").path("PARENTID").asText());
|
||||||
|
assertEquals("tree-crud-v1", test.payload().path("renderTests").get(0).path("recipe").asText());
|
||||||
|
assertEquals("eip4aiOrgCategoryTreeCrud",
|
||||||
|
test.payload().path("renderTests").get(0).path("expectedCrudName").asText());
|
||||||
|
assertEquals("children", test.payload().path("renderTests").get(0).path("childrenColumnName").asText());
|
||||||
|
assertEquals("/amis.html?schema=eip4ai-org-category",
|
||||||
|
test.payload().path("renderTests").get(0).path("previewUrl").asText());
|
||||||
|
assertEquals("/api/entity/EIP4AI_ORG_CATEGORY/tree?parentKey=PARENTID&idKey=EIP4AI_ORG_CATEGORY_ID&perPage=2000",
|
||||||
|
test.payload().path("renderTests").get(0).path("expectedApi").asText());
|
||||||
|
assertTrue(hasText(test.payload().path("renderTests").get(0).path("expectedActions"), "新增顶级组织分类"));
|
||||||
|
assertTrue(hasText(test.payload().path("renderTests").get(0).path("expectedActions"), "刷新"));
|
||||||
|
assertTrue(hasText(test.payload().path("renderTests").get(0).path("expectedActions"), "加子组织分类"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("未知页面配方不静默降级")
|
||||||
|
void rejectsUnknownPageRecipe() {
|
||||||
|
AiFeatureDraftGenerator generator = new AiFeatureDraftGenerator(MAPPER);
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> generator.generate(new AiFeatureRequest(
|
||||||
|
"新增客户等级维护",
|
||||||
|
"客户等级维护",
|
||||||
|
"EIP4AI_CUSTOMER_LEVEL",
|
||||||
|
"客户等级",
|
||||||
|
"eip4ai-customer-level",
|
||||||
|
"客户等级维护",
|
||||||
|
List.of(new AiFeatureField("NAME", "名称", "string", 100, true)),
|
||||||
|
"unknown-recipe")));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean hasAttribute(Iterable<?> attributes, String column) {
|
||||||
|
for (Object attribute : attributes) {
|
||||||
|
if (attribute instanceof com.fasterxml.jackson.databind.JsonNode node
|
||||||
|
&& column.equals(node.path("column").asText())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean hasColumn(Iterable<?> columns, String name) {
|
||||||
|
for (Object column : columns) {
|
||||||
|
if (column instanceof com.fasterxml.jackson.databind.JsonNode node
|
||||||
|
&& name.equals(node.path("name").asText())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean hasText(Iterable<?> values, String expected) {
|
||||||
|
for (Object value : values) {
|
||||||
|
if (value instanceof com.fasterxml.jackson.databind.JsonNode node
|
||||||
|
&& expected.equals(node.asText())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import 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.<Object>any())).thenReturn(1);
|
||||||
|
when(jdbc.update(anyString(), org.mockito.ArgumentMatchers.<Object[]>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<AiDraft> 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, "?::xml"));
|
||||||
|
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.<Object[]>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<AiDraft> 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<AiDraft> toDrafts(List<AiGeneratedDraft> generated) {
|
||||||
|
List<AiDraft> 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<URI> 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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 {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.eip4.platform.ai.model.AiToolAccessRequest;
|
||||||
|
|
||||||
|
class AiToolRegistryTest {
|
||||||
|
|
||||||
|
private final AiToolRegistry registry = AiToolRegistry.defaults();
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void agentDeveloperCanUseLocalApplyWithScopeInLocalEnv() {
|
||||||
|
var decision = registry.check(new AiToolAccessRequest(
|
||||||
|
"agent-developer",
|
||||||
|
"local.apply",
|
||||||
|
List.of("ai:local:apply"),
|
||||||
|
"local",
|
||||||
|
false));
|
||||||
|
|
||||||
|
assertTrue(decision.allowed());
|
||||||
|
assertTrue(decision.blockers().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void agentDeveloperCanReadPageRecipes() {
|
||||||
|
var decision = registry.check(new AiToolAccessRequest(
|
||||||
|
"agent-developer",
|
||||||
|
"page-recipe.read",
|
||||||
|
List.of("ai:page-recipe:read"),
|
||||||
|
"local",
|
||||||
|
false));
|
||||||
|
|
||||||
|
assertTrue(decision.allowed());
|
||||||
|
assertTrue(decision.blockers().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void localOnlyToolIsBlockedForProductionTarget() {
|
||||||
|
var decision = registry.check(new AiToolAccessRequest(
|
||||||
|
"agent-developer",
|
||||||
|
"local.apply",
|
||||||
|
List.of("ai:local:apply", "human:approval"),
|
||||||
|
"prod",
|
||||||
|
true));
|
||||||
|
|
||||||
|
assertFalse(decision.allowed());
|
||||||
|
assertTrue(decision.blockers().stream().anyMatch(b -> b.contains("local-only")));
|
||||||
|
assertTrue(decision.blockers().stream().anyMatch(b -> b.contains("production writes")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void missingScopesAreReported() {
|
||||||
|
var decision = registry.check(new AiToolAccessRequest(
|
||||||
|
"release-auditor",
|
||||||
|
"release.prepare",
|
||||||
|
List.of(),
|
||||||
|
"local",
|
||||||
|
false));
|
||||||
|
|
||||||
|
assertFalse(decision.allowed());
|
||||||
|
assertTrue(decision.missingScopes().contains("ai:release:prepare"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void employeeCannotUseUnassignedTool() {
|
||||||
|
var decision = registry.check(new AiToolAccessRequest(
|
||||||
|
"support-diagnoser",
|
||||||
|
"feature.package",
|
||||||
|
List.of("ai:package:create"),
|
||||||
|
"local",
|
||||||
|
false));
|
||||||
|
|
||||||
|
assertFalse(decision.allowed());
|
||||||
|
assertTrue(decision.blockers().stream().anyMatch(b -> b.contains("not allowed")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void nullRequestIsRejectedWithoutException() {
|
||||||
|
var decision = registry.check(null);
|
||||||
|
|
||||||
|
assertFalse(decision.allowed());
|
||||||
|
assertTrue(decision.blockers().stream().anyMatch(b -> b.contains("Unknown AI employee")));
|
||||||
|
assertTrue(decision.blockers().stream().anyMatch(b -> b.contains("Unknown AI tool")));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<String> authorization = new AtomicReference<>();
|
||||||
|
AtomicReference<String> 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<AiRepairDraftPatch> 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<String> authorization,
|
||||||
|
AtomicReference<String> 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
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_feature_package"));
|
||||||
|
assertTrue(ddl.contains("CREATE TABLE IF NOT EXISTS sys_ai_revision"));
|
||||||
|
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"));
|
||||||
|
assertTrue(ddl.contains("CREATE INDEX IF NOT EXISTS idx_sys_ai_feature_package_task"));
|
||||||
|
assertTrue(ddl.contains("CREATE INDEX IF NOT EXISTS idx_sys_ai_revision_task"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
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.AiDeploymentPackage;
|
||||||
|
import com.eip4.platform.ai.model.AiDraft;
|
||||||
|
import com.eip4.platform.ai.model.AiFeaturePackage;
|
||||||
|
import com.eip4.platform.ai.model.AiGateResult;
|
||||||
|
import com.eip4.platform.ai.model.AiRevision;
|
||||||
|
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"));
|
||||||
|
AiDeploymentPackage deploymentPackage = new AiDeploymentPackage(task.id(), changeSet.id(), "READY",
|
||||||
|
true, 5L, Map.of("changeSetId", changeSet.id()), List.of("sql"), List.of("rollback"),
|
||||||
|
List.of(), List.of(run));
|
||||||
|
AiFeaturePackage featurePackage = new AiFeaturePackage("aipkg-1", task.id(), changeSet.id(), "READY",
|
||||||
|
6L, Map.of("packageType", "EIP4_AI_FEATURE_PACKAGE"), deploymentPackage);
|
||||||
|
AiRevision revision = new AiRevision("airev-1", task.id(), featurePackage.id(), "RESTORABLE",
|
||||||
|
"milestone", 7L, mapper.valueToTree(featurePackage));
|
||||||
|
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.saveFeaturePackage(featurePackage);
|
||||||
|
store.saveRevision(revision);
|
||||||
|
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.listFeaturePackages(task.id()).size());
|
||||||
|
assertEquals(1, store.listRevisions(task.id()).size());
|
||||||
|
assertEquals(1, store.listAudit(task.id()).size());
|
||||||
|
assertEquals(List.of(), store.listDrafts("other-task"));
|
||||||
|
assertEquals(List.of(), store.listRuns("other-task"));
|
||||||
|
assertEquals(List.of(), store.listFeaturePackages("other-task"));
|
||||||
|
assertEquals(List.of(), store.listRevisions("other-task"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
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.AiDeploymentPackage;
|
||||||
|
import com.eip4.platform.ai.model.AiFeaturePackage;
|
||||||
|
import com.eip4.platform.ai.model.AiRevision;
|
||||||
|
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<String> 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<AiTask> 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<String> 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<String> 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<AiRunRecord> 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());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("JDBC 存储写入 feature package 使用 sys_ai_feature_package")
|
||||||
|
void savesFeaturePackage() {
|
||||||
|
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
JdbcAiAgentStore store = new JdbcAiAgentStore(jdbc, mapper);
|
||||||
|
AiDeploymentPackage deploymentPackage = new AiDeploymentPackage("ait-1", "aics-1", "READY",
|
||||||
|
true, 10L, Map.of("changeSetId", "aics-1"),
|
||||||
|
List.of("sql"), List.of("rollback"), List.of(), List.of());
|
||||||
|
|
||||||
|
store.saveFeaturePackage(new AiFeaturePackage("aipkg-1", "ait-1", "aics-1", "READY",
|
||||||
|
11L, Map.of("packageType", "EIP4_AI_FEATURE_PACKAGE"), deploymentPackage));
|
||||||
|
|
||||||
|
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
|
||||||
|
verify(jdbc).update(sql.capture(), eq("aipkg-1"), eq("ait-1"), eq("aics-1"), eq("READY"),
|
||||||
|
eq("{\"packageType\":\"EIP4_AI_FEATURE_PACKAGE\"}"), any(String.class), eq(11L));
|
||||||
|
org.junit.jupiter.api.Assertions.assertTrue(sql.getValue().contains("sys_ai_feature_package"));
|
||||||
|
org.junit.jupiter.api.Assertions.assertTrue(sql.getValue().contains("deployment_package_json"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("JDBC 存储写入 revision 使用 sys_ai_revision")
|
||||||
|
void savesRevision() {
|
||||||
|
JdbcTemplate jdbc = mock(JdbcTemplate.class);
|
||||||
|
ObjectMapper mapper = new ObjectMapper();
|
||||||
|
JdbcAiAgentStore store = new JdbcAiAgentStore(jdbc, mapper);
|
||||||
|
|
||||||
|
store.saveRevision(new AiRevision("airev-1", "ait-1", "aipkg-1", "RESTORABLE",
|
||||||
|
"milestone", 12L, mapper.createObjectNode().put("id", "aipkg-1")));
|
||||||
|
|
||||||
|
ArgumentCaptor<String> sql = ArgumentCaptor.forClass(String.class);
|
||||||
|
verify(jdbc).update(sql.capture(), eq("airev-1"), eq("ait-1"), eq("aipkg-1"), eq("RESTORABLE"),
|
||||||
|
eq("milestone"), eq("{\"id\":\"aipkg-1\"}"), eq(12L));
|
||||||
|
org.junit.jupiter.api.Assertions.assertTrue(sql.getValue().contains("sys_ai_revision"));
|
||||||
|
org.junit.jupiter.api.Assertions.assertTrue(sql.getValue().contains("snapshot_json"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<AiApplyStepResult> apply(String baseUrl, java.util.List<AiDraft> 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<String, Object> 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();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,330 @@
|
|||||||
|
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.get;
|
||||||
|
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.model.AiToolAccessDecision;
|
||||||
|
import com.eip4.platform.ai.model.AiToolAccessRequest;
|
||||||
|
import com.eip4.platform.ai.model.AiToolDefinition;
|
||||||
|
import com.eip4.platform.ai.model.AiEmployeeDefinition;
|
||||||
|
import com.eip4.platform.ai.service.AiAgentService;
|
||||||
|
import com.eip4.platform.metadata.schema.blueprint.PageRecipeDefinition;
|
||||||
|
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<AiAutoDevelopmentRequest> 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<JsonNode> captor = ArgumentCaptor.forClass(JsonNode.class);
|
||||||
|
verify(service).validateSchema(captor.capture());
|
||||||
|
assertEquals("page", captor.getValue().path("type").asText());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 工具注册表接口返回工具列表() throws Exception {
|
||||||
|
when(service.listTools()).thenReturn(List.of(new AiToolDefinition(
|
||||||
|
"schema.validate", "validation", "validate schema",
|
||||||
|
List.of("POST /api/page/schema/validate"),
|
||||||
|
List.of("ai:schema:validate"), false, false)));
|
||||||
|
|
||||||
|
mvc.perform(get("/api/ai/tools"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$[0].name").value("schema.validate"))
|
||||||
|
.andExpect(jsonPath("$[0].requiredScopes[0]").value("ai:schema:validate"));
|
||||||
|
|
||||||
|
verify(service).listTools();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void ai员工接口返回员工定义() throws Exception {
|
||||||
|
when(service.listEmployees()).thenReturn(List.of(new AiEmployeeDefinition(
|
||||||
|
"agent-developer", "Agent Developer", "Develops features",
|
||||||
|
List.of("feature.draft.generate"),
|
||||||
|
List.of("ai:feature:draft"),
|
||||||
|
List.of("Local apply only"))));
|
||||||
|
|
||||||
|
mvc.perform(get("/api/ai/employees"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$[0].id").value("agent-developer"))
|
||||||
|
.andExpect(jsonPath("$[0].toolNames[0]").value("feature.draft.generate"));
|
||||||
|
|
||||||
|
verify(service).listEmployees();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 页面Recipe列表接口返回规范定义() throws Exception {
|
||||||
|
when(service.listPageRecipes()).thenReturn(List.of(new PageRecipeDefinition(
|
||||||
|
"maintenance-crud-v1", 1, "EIP4 maintenance CRUD page",
|
||||||
|
Map.of("string", "input-text"),
|
||||||
|
List.of("page-recipe", "typed-page-schema"))));
|
||||||
|
|
||||||
|
mvc.perform(get("/api/ai/page-recipes"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$[0].recipe").value("maintenance-crud-v1"))
|
||||||
|
.andExpect(jsonPath("$[0].fieldMappings.string").value("input-text"))
|
||||||
|
.andExpect(jsonPath("$[0].gates[0]").value("page-recipe"));
|
||||||
|
|
||||||
|
verify(service).listPageRecipes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 页面Recipe详情接口按名称查询() throws Exception {
|
||||||
|
when(service.getPageRecipe(eq("maintenance-crud-v1"))).thenReturn(new PageRecipeDefinition(
|
||||||
|
"maintenance-crud-v1", 1, "EIP4 maintenance CRUD page",
|
||||||
|
Map.of("boolean", "switch"),
|
||||||
|
List.of("page-recipe")));
|
||||||
|
|
||||||
|
mvc.perform(get("/api/ai/page-recipes/maintenance-crud-v1"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.recipe").value("maintenance-crud-v1"))
|
||||||
|
.andExpect(jsonPath("$.fieldMappings.boolean").value("switch"));
|
||||||
|
|
||||||
|
verify(service).getPageRecipe("maintenance-crud-v1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 工具访问检查接口不执行工具只返回判定() throws Exception {
|
||||||
|
var request = new AiToolAccessRequest("agent-developer", "local.apply",
|
||||||
|
List.of("ai:local:apply"), "prod", true);
|
||||||
|
when(service.checkToolAccess(any(AiToolAccessRequest.class))).thenReturn(new AiToolAccessDecision(
|
||||||
|
false,
|
||||||
|
List.of(),
|
||||||
|
List.of("Tool local.apply is not allowed to perform production writes"),
|
||||||
|
new AiToolDefinition("local.apply", "local-gate", "local apply",
|
||||||
|
List.of("POST /local-apply"), List.of("ai:local:apply"), true, false),
|
||||||
|
new AiEmployeeDefinition("agent-developer", "Agent Developer", "Develops features",
|
||||||
|
List.of("local.apply"), List.of("ai:local:apply"), List.of())));
|
||||||
|
|
||||||
|
mvc.perform(post("/api/ai/tools/access-check")
|
||||||
|
.contentType("application/json")
|
||||||
|
.content(objectMapper.writeValueAsString(request)))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.allowed").value(false))
|
||||||
|
.andExpect(jsonPath("$.blockers[0]").value("Tool local.apply is not allowed to perform production writes"));
|
||||||
|
|
||||||
|
ArgumentCaptor<AiToolAccessRequest> captor = ArgumentCaptor.forClass(AiToolAccessRequest.class);
|
||||||
|
verify(service).checkToolAccess(captor.capture());
|
||||||
|
assertEquals("prod", captor.getValue().targetEnv());
|
||||||
|
assertTrue(captor.getValue().productionWrite());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void 工具访问检查允许空body由service返回拒绝判定() throws Exception {
|
||||||
|
when(service.checkToolAccess(null)).thenReturn(new AiToolAccessDecision(
|
||||||
|
false, List.of(), List.of("Unknown AI employee: ", "Unknown AI tool: "),
|
||||||
|
null, null));
|
||||||
|
|
||||||
|
mvc.perform(post("/api/ai/tools/access-check"))
|
||||||
|
.andExpect(status().isOk())
|
||||||
|
.andExpect(jsonPath("$.allowed").value(false))
|
||||||
|
.andExpect(jsonPath("$.blockers[0]").value("Unknown AI employee: "));
|
||||||
|
|
||||||
|
verify(service).checkToolAccess(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
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.<AiRunRecord>of());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,6 +22,10 @@ spring:
|
|||||||
hikari:
|
hikari:
|
||||||
maximum-pool-size: 10
|
maximum-pool-size: 10
|
||||||
read-only: false
|
read-only: false
|
||||||
|
sql:
|
||||||
|
init:
|
||||||
|
mode: always
|
||||||
|
schema-locations: classpath:bootstrap/bootstrap-ai-agent.sql
|
||||||
|
|
||||||
eip4:
|
eip4:
|
||||||
auth:
|
auth:
|
||||||
@@ -29,6 +33,14 @@ eip4:
|
|||||||
secret: ${EIP4_AUTH_JWT_SECRET:dev-only-eip4-jwt-secret-change-me-in-production-0123456789}
|
secret: ${EIP4_AUTH_JWT_SECRET:dev-only-eip4-jwt-secret-change-me-in-production-0123456789}
|
||||||
expire-seconds: 28800 # 8h
|
expire-seconds: 28800 # 8h
|
||||||
issuer: eip4-platform
|
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:
|
file:
|
||||||
root: ${EIP4_FILE_ROOT:./data/files}
|
root: ${EIP4_FILE_ROOT:./data/files}
|
||||||
script:
|
script:
|
||||||
|
|||||||
@@ -13,6 +13,10 @@ spring:
|
|||||||
hikari:
|
hikari:
|
||||||
maximum-pool-size: 5
|
maximum-pool-size: 5
|
||||||
read-only: false
|
read-only: false
|
||||||
|
sql:
|
||||||
|
init:
|
||||||
|
mode: always
|
||||||
|
schema-locations: classpath:bootstrap/bootstrap-ai-agent.sql
|
||||||
|
|
||||||
server:
|
server:
|
||||||
port: 8084
|
port: 8084
|
||||||
@@ -25,6 +29,14 @@ eip4:
|
|||||||
secret: ${EIP4_AUTH_JWT_SECRET:dev-only-eip4-jwt-secret-change-me-in-production-0123456789}
|
secret: ${EIP4_AUTH_JWT_SECRET:dev-only-eip4-jwt-secret-change-me-in-production-0123456789}
|
||||||
expire-seconds: 28800 # 8h
|
expire-seconds: 28800 # 8h
|
||||||
issuer: eip4-platform
|
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:
|
logging:
|
||||||
level:
|
level:
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
-- ============================================================================
|
||||||
|
-- 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_feature_package (
|
||||||
|
package_id character varying(64) NOT NULL,
|
||||||
|
task_id character varying(64) NOT NULL,
|
||||||
|
change_set_id character varying(64) NOT NULL,
|
||||||
|
status character varying(32) NOT NULL,
|
||||||
|
manifest_json jsonb NOT NULL,
|
||||||
|
deployment_package_json jsonb NOT NULL,
|
||||||
|
created_at bigint NOT NULL,
|
||||||
|
CONSTRAINT pk_sys_ai_feature_package PRIMARY KEY (package_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sys_ai_revision (
|
||||||
|
revision_id character varying(64) NOT NULL,
|
||||||
|
task_id character varying(64) NOT NULL,
|
||||||
|
package_id character varying(64) NOT NULL,
|
||||||
|
status character varying(32) NOT NULL,
|
||||||
|
note text NOT NULL,
|
||||||
|
snapshot_json jsonb NOT NULL,
|
||||||
|
created_at bigint NOT NULL,
|
||||||
|
CONSTRAINT pk_sys_ai_revision PRIMARY KEY (revision_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_feature_package_task ON sys_ai_feature_package (task_id, created_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sys_ai_revision_task ON sys_ai_revision (task_id, created_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sys_ai_audit_log_task ON sys_ai_audit_log (task_id, created_at);
|
||||||
@@ -16,10 +16,44 @@
|
|||||||
<script>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
const params = new URLSearchParams(location.search);
|
const params = new URLSearchParams(location.search);
|
||||||
|
const schemaId = params.get('schema') || params.get('templateId');
|
||||||
|
const schemaUrl = params.get('schemaUrl');
|
||||||
|
const source = params.get('source');
|
||||||
const template = params.get('template') || '角色维护';
|
const template = params.get('template') || '角色维护';
|
||||||
fetch('/api/poc/amis-schema?template=' + encodeURIComponent(template))
|
|
||||||
.then(r => r.json())
|
function schemaEndpoint() {
|
||||||
|
if (schemaUrl) {
|
||||||
|
if (!schemaUrl.startsWith('/api/page/schema/')) {
|
||||||
|
throw new Error('schemaUrl 只允许 /api/page/schema/ 路径');
|
||||||
|
}
|
||||||
|
return schemaUrl;
|
||||||
|
}
|
||||||
|
if (schemaId) {
|
||||||
|
return '/api/page/schema/' + encodeURIComponent(schemaId);
|
||||||
|
}
|
||||||
|
if (source === 'page-schema') {
|
||||||
|
return '/api/page/schema/' + encodeURIComponent(template);
|
||||||
|
}
|
||||||
|
return '/api/poc/amis-schema?template=' + encodeURIComponent(template);
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadSchema() {
|
||||||
|
const endpoint = schemaEndpoint();
|
||||||
|
return fetch(endpoint)
|
||||||
|
.then(r => {
|
||||||
|
if (!r.ok) {
|
||||||
|
throw new Error(endpoint + ' 返回 HTTP ' + r.status);
|
||||||
|
}
|
||||||
|
return r.json();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('root').innerText = '加载中...';
|
||||||
|
loadSchema()
|
||||||
.then(schema => {
|
.then(schema => {
|
||||||
|
if (schema && schema.status !== undefined && schema.data) {
|
||||||
|
schema = schema.data;
|
||||||
|
}
|
||||||
const amis = amisRequire('amis/embed');
|
const amis = amisRequire('amis/embed');
|
||||||
amis.embed('#root', schema);
|
amis.embed('#root', schema);
|
||||||
})
|
})
|
||||||
|
|||||||
56
platform-cli/pom.xml
Normal file
56
platform-cli/pom.xml
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>com.eip4</groupId>
|
||||||
|
<artifactId>eip4-platform</artifactId>
|
||||||
|
<version>0.1.0-SNAPSHOT</version>
|
||||||
|
</parent>
|
||||||
|
<artifactId>platform-cli</artifactId>
|
||||||
|
<name>platform-cli</name>
|
||||||
|
<description>EIP4 Agent 受控命令入口:环境探测、AI 自动开发、发布前门禁编排</description>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.fasterxml.jackson.core</groupId>
|
||||||
|
<artifactId>jackson-databind</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-assembly-plugin</artifactId>
|
||||||
|
<version>3.7.1</version>
|
||||||
|
<configuration>
|
||||||
|
<archive>
|
||||||
|
<manifest>
|
||||||
|
<mainClass>com.eip4.platform.cli.Eip4Cli</mainClass>
|
||||||
|
</manifest>
|
||||||
|
</archive>
|
||||||
|
<descriptorRefs>
|
||||||
|
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||||
|
</descriptorRefs>
|
||||||
|
<appendAssemblyId>false</appendAssemblyId>
|
||||||
|
</configuration>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>make-assembly</id>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>single</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
1003
platform-cli/src/main/java/com/eip4/platform/cli/Eip4Cli.java
Normal file
1003
platform-cli/src/main/java/com/eip4/platform/cli/Eip4Cli.java
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,140 @@
|
|||||||
|
package com.eip4.platform.cli;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
final class Eip4EnvStore {
|
||||||
|
|
||||||
|
private static final int SCHEMA_VERSION = 1;
|
||||||
|
|
||||||
|
private final Path configPath;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
Eip4EnvStore(Path configPath, ObjectMapper objectMapper) {
|
||||||
|
this.configPath = configPath;
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
static Eip4EnvStore defaultStore(ObjectMapper objectMapper) {
|
||||||
|
String cliHome = System.getenv("EIP4_CLI_HOME");
|
||||||
|
Path home = cliHome == null || cliHome.isBlank()
|
||||||
|
? Path.of(System.getProperty("user.home"), ".eip4")
|
||||||
|
: Path.of(cliHome);
|
||||||
|
return new Eip4EnvStore(home.resolve("eip4-cli.json"), objectMapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
Config load() throws IOException {
|
||||||
|
if (!Files.exists(configPath)) {
|
||||||
|
return new Config(SCHEMA_VERSION, "", new LinkedHashMap<>());
|
||||||
|
}
|
||||||
|
String json = Files.readString(configPath, StandardCharsets.UTF_8);
|
||||||
|
if (json.isBlank()) {
|
||||||
|
return new Config(SCHEMA_VERSION, "", new LinkedHashMap<>());
|
||||||
|
}
|
||||||
|
Config config = objectMapper.readValue(json, Config.class);
|
||||||
|
return normalize(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
void saveEnv(EnvConfig env, boolean use) throws IOException {
|
||||||
|
Config config = load();
|
||||||
|
Map<String, EnvConfig> envs = new LinkedHashMap<>(config.envs());
|
||||||
|
envs.put(env.name(), env);
|
||||||
|
String current = use || config.currentEnv().isBlank() ? env.name() : config.currentEnv();
|
||||||
|
save(new Config(SCHEMA_VERSION, current, envs));
|
||||||
|
}
|
||||||
|
|
||||||
|
List<EnvConfig> listEnvs() throws IOException {
|
||||||
|
return List.copyOf(load().envs().values());
|
||||||
|
}
|
||||||
|
|
||||||
|
Optional<EnvConfig> findEnv(String name) throws IOException {
|
||||||
|
if (name == null || name.isBlank()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.ofNullable(load().envs().get(name.trim()));
|
||||||
|
}
|
||||||
|
|
||||||
|
Optional<EnvConfig> currentEnv() throws IOException {
|
||||||
|
Config config = load();
|
||||||
|
if (config.currentEnv().isBlank()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.ofNullable(config.envs().get(config.currentEnv()));
|
||||||
|
}
|
||||||
|
|
||||||
|
String currentEnvName() throws IOException {
|
||||||
|
return load().currentEnv();
|
||||||
|
}
|
||||||
|
|
||||||
|
EnvConfig useEnv(String name) throws IOException {
|
||||||
|
String requested = name == null ? "" : name.trim();
|
||||||
|
Config config = load();
|
||||||
|
EnvConfig env = config.envs().get(requested);
|
||||||
|
if (env == null) {
|
||||||
|
throw new IllegalArgumentException("EIP4 env not found: " + requested);
|
||||||
|
}
|
||||||
|
save(new Config(SCHEMA_VERSION, requested, new LinkedHashMap<>(config.envs())));
|
||||||
|
return env;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void save(Config config) throws IOException {
|
||||||
|
if (configPath.getParent() != null) {
|
||||||
|
Files.createDirectories(configPath.getParent());
|
||||||
|
}
|
||||||
|
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(normalize(config));
|
||||||
|
Files.writeString(configPath, json + System.lineSeparator(), StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Config normalize(Config config) {
|
||||||
|
Map<String, EnvConfig> envs = new LinkedHashMap<>();
|
||||||
|
if (config != null && config.envs() != null) {
|
||||||
|
for (EnvConfig env : config.envs().values()) {
|
||||||
|
if (env == null || env.name() == null || env.name().isBlank()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
envs.put(env.name(), normalize(env));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String current = config == null || config.currentEnv() == null ? "" : config.currentEnv().trim();
|
||||||
|
if (!current.isBlank() && !envs.containsKey(current)) {
|
||||||
|
current = "";
|
||||||
|
}
|
||||||
|
return new Config(SCHEMA_VERSION, current, envs);
|
||||||
|
}
|
||||||
|
|
||||||
|
static EnvConfig normalize(EnvConfig env) {
|
||||||
|
String name = required(env.name(), "name");
|
||||||
|
String kind = env.kind() == null || env.kind().isBlank() ? "local" : env.kind().trim();
|
||||||
|
String baseUrl = normalizeBaseUrl(required(env.baseUrl(), "baseUrl"));
|
||||||
|
return new EnvConfig(name, kind, baseUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
static String normalizeBaseUrl(String value) {
|
||||||
|
String out = value == null ? "" : value.trim();
|
||||||
|
while (out.endsWith("/")) {
|
||||||
|
out = out.substring(0, out.length() - 1);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String required(String value, String name) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("Missing required env " + name);
|
||||||
|
}
|
||||||
|
return value.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
record Config(int schemaVersion, String currentEnv, Map<String, EnvConfig> envs) {
|
||||||
|
}
|
||||||
|
|
||||||
|
record EnvConfig(String name, String kind, String baseUrl) {
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.eip4.platform.cli;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
|
||||||
|
interface Eip4HttpClient {
|
||||||
|
Eip4HttpResponse send(String method, URI uri, JsonNode body) throws IOException, InterruptedException;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package com.eip4.platform.cli;
|
||||||
|
|
||||||
|
record Eip4HttpResponse(int statusCode, String body) {
|
||||||
|
boolean successful() {
|
||||||
|
return statusCode >= 200 && statusCode < 300;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.eip4.platform.cli;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.time.Duration;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
final class JdkEip4HttpClient implements Eip4HttpClient {
|
||||||
|
|
||||||
|
private static final Duration TIMEOUT = Duration.ofSeconds(30);
|
||||||
|
|
||||||
|
private final HttpClient client;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
JdkEip4HttpClient(ObjectMapper objectMapper) {
|
||||||
|
this.client = HttpClient.newBuilder().connectTimeout(TIMEOUT).build();
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Eip4HttpResponse send(String method, URI uri, JsonNode body) throws IOException, InterruptedException {
|
||||||
|
HttpRequest.BodyPublisher publisher = body == null
|
||||||
|
? HttpRequest.BodyPublishers.noBody()
|
||||||
|
: HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(body));
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(uri)
|
||||||
|
.timeout(TIMEOUT)
|
||||||
|
.header("Accept", "application/json")
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.method(method, publisher)
|
||||||
|
.build();
|
||||||
|
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
|
||||||
|
return new Eip4HttpResponse(response.statusCode(), response.body());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,458 @@
|
|||||||
|
package com.eip4.platform.cli;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.io.PrintStream;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
class Eip4CliTest {
|
||||||
|
|
||||||
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
Path tempDir;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void envStatusChecksOpenApiEndpoint() {
|
||||||
|
CapturingClient client = new CapturingClient(new Eip4HttpResponse(200, "{}"));
|
||||||
|
CliResult result = run(client, "env", "status", "--base-url", "http://localhost:8084/");
|
||||||
|
|
||||||
|
assertEquals(0, result.code());
|
||||||
|
assertEquals("GET", client.method);
|
||||||
|
assertEquals(URI.create("http://localhost:8084/v3/api-docs"), client.uri);
|
||||||
|
assertTrue(result.out().contains("EIP4 env READY"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void envCommandsPersistAndUseCurrentEnv() {
|
||||||
|
CapturingClient client = new CapturingClient(new Eip4HttpResponse(200, "{}"));
|
||||||
|
Eip4EnvStore store = tempStore();
|
||||||
|
|
||||||
|
CliResult add = run(store, client, "env", "add",
|
||||||
|
"--name", "local",
|
||||||
|
"--base-url", "http://localhost:8084/",
|
||||||
|
"--kind", "local",
|
||||||
|
"--use");
|
||||||
|
CliResult current = run(store, client, "env", "current");
|
||||||
|
CliResult list = run(store, client, "env", "list");
|
||||||
|
CliResult status = run(store, client, "env", "status");
|
||||||
|
|
||||||
|
assertEquals(0, add.code());
|
||||||
|
assertEquals(0, current.code());
|
||||||
|
assertEquals(0, list.code());
|
||||||
|
assertEquals(0, status.code());
|
||||||
|
assertTrue(current.out().contains("currentEnv: local"));
|
||||||
|
assertTrue(list.out().contains("* local local http://localhost:8084"));
|
||||||
|
assertEquals(URI.create("http://localhost:8084/v3/api-docs"), client.uri);
|
||||||
|
assertTrue(status.out().contains("env: local"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void autoDevelopBuildsRequestAndWritesResponse() throws Exception {
|
||||||
|
String response = """
|
||||||
|
{
|
||||||
|
"status": "READY_FOR_HUMAN_REVIEW",
|
||||||
|
"taskId": "task-1",
|
||||||
|
"changeSetId": "cs-1",
|
||||||
|
"applyRun": {"status": "PASSED"},
|
||||||
|
"smokeRun": {"status": "PASSED"}
|
||||||
|
}
|
||||||
|
""";
|
||||||
|
CapturingClient client = new CapturingClient(new Eip4HttpResponse(200, response));
|
||||||
|
Path output = tempDir.resolve("run.json");
|
||||||
|
|
||||||
|
CliResult result = run(client,
|
||||||
|
"ai", "auto-develop",
|
||||||
|
"--base-url", "http://localhost:8084",
|
||||||
|
"--objective", "新增客户等级维护",
|
||||||
|
"--feature-name", "客户等级维护",
|
||||||
|
"--table-name", "EIP4AI_CUSTOMER_LEVEL",
|
||||||
|
"--entity-name", "客户等级",
|
||||||
|
"--template-id", "eip4ai-customer-level",
|
||||||
|
"--menu-name", "客户等级维护",
|
||||||
|
"--field", "NAME:名称:string:100:true",
|
||||||
|
"--field", "ENABLED:启用:boolean::false",
|
||||||
|
"--page-recipe", "tree-crud-v1",
|
||||||
|
"--max-repair-attempts", "3",
|
||||||
|
"--no-deployment-package",
|
||||||
|
"--output", output.toString());
|
||||||
|
|
||||||
|
assertEquals(0, result.code());
|
||||||
|
assertEquals("POST", client.method);
|
||||||
|
assertEquals(URI.create("http://localhost:8084/api/ai/features/auto-develop"), client.uri);
|
||||||
|
assertFalse(client.body.path("generateDeploymentPackage").asBoolean());
|
||||||
|
assertEquals(3, client.body.path("maxRepairAttempts").asInt());
|
||||||
|
JsonNode feature = client.body.path("feature");
|
||||||
|
assertEquals("EIP4AI_CUSTOMER_LEVEL", feature.path("tableName").asText());
|
||||||
|
assertEquals("tree-crud-v1", feature.path("pageRecipe").asText());
|
||||||
|
assertEquals(2, feature.path("fields").size());
|
||||||
|
assertEquals("NAME", feature.path("fields").get(0).path("column").asText());
|
||||||
|
assertEquals(100, feature.path("fields").get(0).path("length").asInt());
|
||||||
|
assertTrue(feature.path("fields").get(0).path("required").asBoolean());
|
||||||
|
assertTrue(Files.readString(output, StandardCharsets.UTF_8).contains("READY_FOR_HUMAN_REVIEW"));
|
||||||
|
assertTrue(result.out().contains("applyStatus: PASSED"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void autoDevelopCanUseConfiguredEnv() {
|
||||||
|
CapturingClient client = new CapturingClient(new Eip4HttpResponse(200, """
|
||||||
|
{"status":"READY_FOR_HUMAN_REVIEW","taskId":"task-1","changeSetId":"cs-1"}
|
||||||
|
"""));
|
||||||
|
Eip4EnvStore store = tempStore();
|
||||||
|
run(store, client, "env", "add", "--name", "dev", "--base-url", "http://localhost:8093", "--use");
|
||||||
|
|
||||||
|
CliResult result = run(store, client,
|
||||||
|
"ai", "auto-develop",
|
||||||
|
"--env", "dev",
|
||||||
|
"--objective", "新增客户等级维护",
|
||||||
|
"--feature-name", "客户等级维护",
|
||||||
|
"--table-name", "EIP4AI_CUSTOMER_LEVEL",
|
||||||
|
"--entity-name", "客户等级",
|
||||||
|
"--template-id", "eip4ai-customer-level",
|
||||||
|
"--menu-name", "客户等级维护",
|
||||||
|
"--field", "NAME:名称:string:100:true");
|
||||||
|
|
||||||
|
assertEquals(0, result.code());
|
||||||
|
assertEquals(URI.create("http://localhost:8093/api/ai/features/auto-develop"), client.uri);
|
||||||
|
assertEquals("http://localhost:8093", client.body.path("baseUrl").asText());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void explicitCrossEnvRequiresYes() {
|
||||||
|
CapturingClient client = new CapturingClient(new Eip4HttpResponse(200, "{}"));
|
||||||
|
Eip4EnvStore store = tempStore();
|
||||||
|
run(store, client, "env", "add", "--name", "local", "--base-url", "http://localhost:8084", "--use");
|
||||||
|
run(store, client, "env", "add", "--name", "dev", "--base-url", "http://localhost:8093");
|
||||||
|
|
||||||
|
CliResult result = run(store, client,
|
||||||
|
"ai", "feature-package",
|
||||||
|
"--env", "dev",
|
||||||
|
"--task-id", "ait-1",
|
||||||
|
"--change-set-id", "aics-1");
|
||||||
|
|
||||||
|
assertEquals(1, result.code());
|
||||||
|
assertTrue(result.err().contains("Refusing to target env `dev`"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void autoDevelopRequiresAtLeastOneField() {
|
||||||
|
CapturingClient client = new CapturingClient(new Eip4HttpResponse(200, "{}"));
|
||||||
|
|
||||||
|
CliResult result = run(client,
|
||||||
|
"ai", "auto-develop",
|
||||||
|
"--objective", "新增客户等级维护",
|
||||||
|
"--feature-name", "客户等级维护",
|
||||||
|
"--table-name", "EIP4AI_CUSTOMER_LEVEL",
|
||||||
|
"--entity-name", "客户等级",
|
||||||
|
"--template-id", "eip4ai-customer-level",
|
||||||
|
"--menu-name", "客户等级维护");
|
||||||
|
|
||||||
|
assertEquals(1, result.code());
|
||||||
|
assertTrue(result.err().contains("Missing required option: --field"));
|
||||||
|
assertEquals(0, client.calls);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void featurePackageCommandPostsToPackageEndpoint() throws Exception {
|
||||||
|
CapturingClient client = new CapturingClient(new Eip4HttpResponse(200, """
|
||||||
|
{"id":"aipkg-1","taskId":"ait-1","changeSetId":"aics-1","status":"READY_FOR_HUMAN_REVIEW"}
|
||||||
|
"""));
|
||||||
|
Path output = tempDir.resolve("package.json");
|
||||||
|
|
||||||
|
CliResult result = run(client,
|
||||||
|
"ai", "feature-package",
|
||||||
|
"--base-url", "http://localhost:8084",
|
||||||
|
"--task-id", "ait-1",
|
||||||
|
"--change-set-id", "aics-1",
|
||||||
|
"--output", output.toString());
|
||||||
|
|
||||||
|
assertEquals(0, result.code());
|
||||||
|
assertEquals("POST", client.method);
|
||||||
|
assertEquals(URI.create("http://localhost:8084/api/ai/tasks/ait-1/change-sets/aics-1/feature-package"),
|
||||||
|
client.uri);
|
||||||
|
assertEquals("aipkg-1", objectMapper.readTree(Files.readString(output)).path("id").asText());
|
||||||
|
assertTrue(result.out().contains("id: aipkg-1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void revisionCommandPostsNoteToRevisionEndpoint() throws Exception {
|
||||||
|
CapturingClient client = new CapturingClient(new Eip4HttpResponse(200, """
|
||||||
|
{"id":"airev-1","taskId":"ait-1","packageId":"aipkg-1","status":"RESTORABLE"}
|
||||||
|
"""));
|
||||||
|
Path output = tempDir.resolve("revision.json");
|
||||||
|
|
||||||
|
CliResult result = run(client,
|
||||||
|
"ai", "revision",
|
||||||
|
"--base-url", "http://localhost:8084",
|
||||||
|
"--task-id", "ait-1",
|
||||||
|
"--package-id", "aipkg-1",
|
||||||
|
"--note", "本地门禁通过",
|
||||||
|
"--output", output.toString());
|
||||||
|
|
||||||
|
assertEquals(0, result.code());
|
||||||
|
assertEquals("POST", client.method);
|
||||||
|
assertEquals(URI.create("http://localhost:8084/api/ai/tasks/ait-1/feature-packages/aipkg-1/revisions"),
|
||||||
|
client.uri);
|
||||||
|
assertEquals("本地门禁通过", client.body.path("note").asText());
|
||||||
|
assertEquals("airev-1", objectMapper.readTree(Files.readString(output)).path("id").asText());
|
||||||
|
assertTrue(result.out().contains("packageId: aipkg-1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void releaseVerifyPassesReadyFeaturePackage() throws Exception {
|
||||||
|
Path file = tempDir.resolve("package.json");
|
||||||
|
Files.writeString(file, """
|
||||||
|
{
|
||||||
|
"id": "aipkg-1",
|
||||||
|
"deploymentPackage": {
|
||||||
|
"taskId": "ait-1",
|
||||||
|
"changeSetId": "aics-1",
|
||||||
|
"status": "READY_FOR_HUMAN_REVIEW",
|
||||||
|
"requiresHumanApproval": true,
|
||||||
|
"sqlStatements": ["insert into sys_page_schema values ('x')"],
|
||||||
|
"rollbackSqlStatements": ["delete from sys_page_schema where id = 'x'"],
|
||||||
|
"warnings": [],
|
||||||
|
"runEvidence": [
|
||||||
|
{"runType": "LOCAL_APPLY", "status": "PASSED"},
|
||||||
|
{"runType": "SMOKE", "status": "PASSED"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""", StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
CliResult result = run(new CapturingClient(new Eip4HttpResponse(200, "{}")),
|
||||||
|
"release", "verify", "--package-file", file.toString());
|
||||||
|
|
||||||
|
assertEquals(0, result.code());
|
||||||
|
assertTrue(result.out().contains("Release package PASSED"));
|
||||||
|
assertTrue(result.out().contains("packageId: aipkg-1"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void releaseVerifyBlocksSqlPlaceholders() throws Exception {
|
||||||
|
Path file = tempDir.resolve("package-with-placeholder.json");
|
||||||
|
Files.writeString(file, """
|
||||||
|
{
|
||||||
|
"deploymentPackage": {
|
||||||
|
"taskId": "ait-1",
|
||||||
|
"changeSetId": "aics-1",
|
||||||
|
"status": "READY_FOR_HUMAN_REVIEW",
|
||||||
|
"requiresHumanApproval": true,
|
||||||
|
"manifest": {"packageId": "aipkg-2"},
|
||||||
|
"sqlStatements": ["insert into sys_menu(parent_id) values ('${parentMenuId}')"],
|
||||||
|
"rollbackSqlStatements": ["delete from sys_menu where id = 'x'"],
|
||||||
|
"warnings": ["菜单 parentId 待替换"],
|
||||||
|
"runEvidence": [
|
||||||
|
{"runType": "LOCAL_APPLY", "status": "PASSED"},
|
||||||
|
{"runType": "SMOKE", "status": "PASSED"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""", StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
CliResult result = run(new CapturingClient(new Eip4HttpResponse(200, "{}")),
|
||||||
|
"release", "verify", "--package-file", file.toString());
|
||||||
|
|
||||||
|
assertEquals(2, result.code());
|
||||||
|
assertTrue(result.err().contains("Release package FAILED"));
|
||||||
|
assertTrue(result.err().contains("占位符"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void releaseExportWritesChecksumEnvelopeAndImportPreviewPasses() throws Exception {
|
||||||
|
Path source = validPackageFile("package-source.json");
|
||||||
|
Path exported = tempDir.resolve("customer-level.eip4pkg.json");
|
||||||
|
|
||||||
|
CliResult export = run(new CapturingClient(new Eip4HttpResponse(200, "{}")),
|
||||||
|
"release", "export",
|
||||||
|
"--package-file", source.toString(),
|
||||||
|
"--output", exported.toString());
|
||||||
|
|
||||||
|
assertEquals(0, export.code());
|
||||||
|
JsonNode envelope = objectMapper.readTree(Files.readString(exported));
|
||||||
|
assertEquals("EIP4_FEATURE_PACKAGE", envelope.path("format").asText());
|
||||||
|
assertEquals(1, envelope.path("formatVersion").asInt());
|
||||||
|
assertEquals("SHA-256", envelope.path("checksumAlgorithm").asText());
|
||||||
|
assertTrue(envelope.path("checksum").asText().startsWith("sha256:"));
|
||||||
|
assertEquals("aipkg-1", envelope.path("payload").path("id").asText());
|
||||||
|
|
||||||
|
CliResult preview = run(new CapturingClient(new Eip4HttpResponse(200, "{}")),
|
||||||
|
"release", "import-preview",
|
||||||
|
"--package-file", exported.toString());
|
||||||
|
|
||||||
|
assertEquals(0, preview.code());
|
||||||
|
assertTrue(preview.out().contains("Import preview PASSED"));
|
||||||
|
assertTrue(preview.out().contains("checksum: sha256:"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void releaseImportPreviewRejectsTamperedChecksum() throws Exception {
|
||||||
|
Path source = validPackageFile("package-source.json");
|
||||||
|
Path exported = tempDir.resolve("customer-level.eip4pkg.json");
|
||||||
|
run(new CapturingClient(new Eip4HttpResponse(200, "{}")),
|
||||||
|
"release", "export",
|
||||||
|
"--package-file", source.toString(),
|
||||||
|
"--output", exported.toString());
|
||||||
|
String tampered = Files.readString(exported, StandardCharsets.UTF_8)
|
||||||
|
.replace("READY_FOR_HUMAN_REVIEW", "BLOCKED_PENDING_LOCAL_PASS");
|
||||||
|
Files.writeString(exported, tampered, StandardCharsets.UTF_8);
|
||||||
|
|
||||||
|
CliResult preview = run(new CapturingClient(new Eip4HttpResponse(200, "{}")),
|
||||||
|
"release", "import-preview",
|
||||||
|
"--package-file", exported.toString());
|
||||||
|
|
||||||
|
assertEquals(2, preview.code());
|
||||||
|
assertTrue(preview.err().contains("Import preview FAILED"));
|
||||||
|
assertTrue(preview.err().contains("checksum 不匹配"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void releaseDiffReportsSqlAndRollbackChanges() throws Exception {
|
||||||
|
Path left = packageFile("left-package.json", "aipkg-left",
|
||||||
|
"insert into sys_page_schema values ('left')",
|
||||||
|
"delete from sys_page_schema where id = 'left'");
|
||||||
|
Path right = packageFile("right-package.json", "aipkg-right",
|
||||||
|
"insert into sys_page_schema values ('right')",
|
||||||
|
"delete from sys_page_schema where id = 'right'");
|
||||||
|
|
||||||
|
CliResult result = run(new CapturingClient(new Eip4HttpResponse(200, "{}")),
|
||||||
|
"release", "diff",
|
||||||
|
"--left", left.toString(),
|
||||||
|
"--right", right.toString(),
|
||||||
|
"--json-output");
|
||||||
|
|
||||||
|
assertEquals(0, result.code());
|
||||||
|
JsonNode report = objectMapper.readTree(result.out());
|
||||||
|
assertTrue(report.path("changed").asBoolean());
|
||||||
|
assertEquals("aipkg-left", report.path("leftPackageId").asText());
|
||||||
|
assertEquals("aipkg-right", report.path("rightPackageId").asText());
|
||||||
|
assertEquals(1, report.path("sqlStatements").path("added").size());
|
||||||
|
assertTrue(report.path("sqlStatements").path("added").get(0).asText().contains("'right'"));
|
||||||
|
assertEquals(1, report.path("rollbackSqlStatements").path("removed").size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void releaseRollbackPlanWritesPlanOnlyArtifact() throws Exception {
|
||||||
|
Path source = validPackageFile("package-source.json");
|
||||||
|
Path planFile = tempDir.resolve("rollback-plan.json");
|
||||||
|
|
||||||
|
CliResult result = run(new CapturingClient(new Eip4HttpResponse(200, "{}")),
|
||||||
|
"release", "rollback-plan",
|
||||||
|
"--package-file", source.toString(),
|
||||||
|
"--output", planFile.toString());
|
||||||
|
|
||||||
|
assertEquals(0, result.code());
|
||||||
|
JsonNode plan = objectMapper.readTree(Files.readString(planFile));
|
||||||
|
assertEquals("EIP4_ROLLBACK_PLAN", plan.path("type").asText());
|
||||||
|
assertEquals("PLAN_ONLY", plan.path("mode").asText());
|
||||||
|
assertEquals("aipkg-1", plan.path("packageId").asText());
|
||||||
|
assertTrue(plan.path("requiresHumanApproval").asBoolean());
|
||||||
|
assertEquals(1, plan.path("rollbackSqlStatements").size());
|
||||||
|
assertTrue(plan.path("policy").asText().contains("does not execute SQL"));
|
||||||
|
assertTrue(result.out().contains("Wrote rollback plan"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void releaseRollbackPlanBlocksRollbackPlaceholders() throws Exception {
|
||||||
|
Path source = packageFile("package-with-rollback-placeholder.json", "aipkg-placeholder",
|
||||||
|
"insert into sys_page_schema values ('x')",
|
||||||
|
"delete from sys_page_schema where id = '${pageSchemaId}'");
|
||||||
|
Path planFile = tempDir.resolve("rollback-plan.json");
|
||||||
|
|
||||||
|
CliResult result = run(new CapturingClient(new Eip4HttpResponse(200, "{}")),
|
||||||
|
"release", "rollback-plan",
|
||||||
|
"--package-file", source.toString(),
|
||||||
|
"--output", planFile.toString());
|
||||||
|
|
||||||
|
assertEquals(2, result.code());
|
||||||
|
assertTrue(result.err().contains("Rollback plan FAILED"));
|
||||||
|
assertTrue(result.err().contains("rollbackSqlStatements 仍包含"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path validPackageFile(String name) throws Exception {
|
||||||
|
return packageFile(name, "aipkg-1",
|
||||||
|
"insert into sys_page_schema values ('x')",
|
||||||
|
"delete from sys_page_schema where id = 'x'");
|
||||||
|
}
|
||||||
|
|
||||||
|
private Path packageFile(String name, String packageId, String sql, String rollbackSql) throws Exception {
|
||||||
|
Path file = tempDir.resolve(name);
|
||||||
|
Files.writeString(file, """
|
||||||
|
{
|
||||||
|
"id": "%s",
|
||||||
|
"deploymentPackage": {
|
||||||
|
"taskId": "ait-1",
|
||||||
|
"changeSetId": "aics-1",
|
||||||
|
"status": "READY_FOR_HUMAN_REVIEW",
|
||||||
|
"requiresHumanApproval": true,
|
||||||
|
"sqlStatements": [%s],
|
||||||
|
"rollbackSqlStatements": [%s],
|
||||||
|
"warnings": [],
|
||||||
|
"runEvidence": [
|
||||||
|
{"runType": "LOCAL_APPLY", "status": "PASSED"},
|
||||||
|
{"runType": "SMOKE", "status": "PASSED"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
""".formatted(packageId, objectMapper.writeValueAsString(sql),
|
||||||
|
objectMapper.writeValueAsString(rollbackSql)), StandardCharsets.UTF_8);
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
private CliResult run(CapturingClient client, String... args) {
|
||||||
|
return run(tempStore(), client, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
private CliResult run(Eip4EnvStore store, CapturingClient client, String... args) {
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
ByteArrayOutputStream err = new ByteArrayOutputStream();
|
||||||
|
int code = new Eip4Cli(client, store).run(
|
||||||
|
args,
|
||||||
|
new PrintStream(out, true, StandardCharsets.UTF_8),
|
||||||
|
new PrintStream(err, true, StandardCharsets.UTF_8));
|
||||||
|
return new CliResult(
|
||||||
|
code,
|
||||||
|
out.toString(StandardCharsets.UTF_8),
|
||||||
|
err.toString(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Eip4EnvStore tempStore() {
|
||||||
|
return new Eip4EnvStore(tempDir.resolve("eip4-cli.json"), objectMapper);
|
||||||
|
}
|
||||||
|
|
||||||
|
private final class CapturingClient implements Eip4HttpClient {
|
||||||
|
private final Eip4HttpResponse response;
|
||||||
|
private int calls;
|
||||||
|
private String method;
|
||||||
|
private URI uri;
|
||||||
|
private JsonNode body = objectMapper.createObjectNode();
|
||||||
|
|
||||||
|
private CapturingClient(Eip4HttpResponse response) {
|
||||||
|
this.response = response;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Eip4HttpResponse send(String method, URI uri, JsonNode body) {
|
||||||
|
this.calls++;
|
||||||
|
this.method = method;
|
||||||
|
this.uri = uri;
|
||||||
|
this.body = body == null ? objectMapper.createObjectNode() : body;
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record CliResult(int code, String out, String err) {
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
@@ -0,0 +1,10 @@
|
|||||||
|
package com.eip4.platform.metadata.schema;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record PageComponentDefinition(
|
||||||
|
String type,
|
||||||
|
String category,
|
||||||
|
List<String> capabilities,
|
||||||
|
List<String> allowedActions) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.eip4.platform.metadata.schema;
|
||||||
|
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public final class PageComponentRegistry {
|
||||||
|
|
||||||
|
public static final int VERSION = 1;
|
||||||
|
|
||||||
|
private final Map<String, PageComponentDefinition> components;
|
||||||
|
|
||||||
|
private PageComponentRegistry(Map<String, PageComponentDefinition> components) {
|
||||||
|
this.components = Collections.unmodifiableMap(new LinkedHashMap<>(components));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PageComponentRegistry defaults() {
|
||||||
|
Map<String, PageComponentDefinition> map = new LinkedHashMap<>();
|
||||||
|
register(map, "page", "layout", List.of("page-root"), List.of());
|
||||||
|
register(map, "crud", "data", List.of("list", "pagination", "toolbar", "columns"), List.of());
|
||||||
|
register(map, "form", "data", List.of("submit", "validation", "api"), List.of("submit", "reset"));
|
||||||
|
register(map, "operation", "data", List.of("row-actions"), List.of());
|
||||||
|
register(map, "service", "data", List.of("remote-schema", "remote-data"), List.of());
|
||||||
|
register(map, "button", "action", List.of("dialog", "ajax", "drawer", "link", "reload"), List.of(
|
||||||
|
"ajax", "dialog", "drawer", "link", "url", "reload", "submit", "reset", "cancel", "copy",
|
||||||
|
"download", "toast", "confirm"));
|
||||||
|
register(map, "tpl", "display", List.of("template-text"), List.of());
|
||||||
|
register(map, "static", "display", List.of("readonly"), List.of());
|
||||||
|
register(map, "static-text", "display", List.of("readonly"), List.of());
|
||||||
|
register(map, "wrapper", "layout", List.of("container"), List.of());
|
||||||
|
register(map, "container", "layout", List.of("container"), List.of());
|
||||||
|
register(map, "grid", "layout", List.of("columns"), List.of());
|
||||||
|
register(map, "hbox", "layout", List.of("columns"), List.of());
|
||||||
|
register(map, "group", "layout", List.of("form-group"), List.of());
|
||||||
|
register(map, "input-text", "field", List.of("text", "required"), List.of());
|
||||||
|
register(map, "textarea", "field", List.of("text", "multiline", "required"), List.of());
|
||||||
|
register(map, "input-password", "field", List.of("password", "required"), List.of());
|
||||||
|
register(map, "input-number", "field", List.of("number", "required"), List.of());
|
||||||
|
register(map, "input-date", "field", List.of("date", "required"), List.of());
|
||||||
|
register(map, "input-datetime", "field", List.of("datetime", "required"), List.of());
|
||||||
|
register(map, "input-time", "field", List.of("time", "required"), List.of());
|
||||||
|
register(map, "input-month", "field", List.of("month", "required"), List.of());
|
||||||
|
register(map, "input-quarter", "field", List.of("quarter", "required"), List.of());
|
||||||
|
register(map, "input-year", "field", List.of("year", "required"), List.of());
|
||||||
|
register(map, "switch", "field", List.of("boolean"), List.of());
|
||||||
|
register(map, "checkbox", "field", List.of("boolean"), List.of());
|
||||||
|
register(map, "checkboxes", "field", List.of("multi-option"), List.of());
|
||||||
|
register(map, "radios", "field", List.of("single-option"), List.of());
|
||||||
|
register(map, "select", "field", List.of("single-option", "remote-options"), List.of());
|
||||||
|
register(map, "picker", "field", List.of("dialog-picker", "remote-options"), List.of());
|
||||||
|
register(map, "input-tree", "field", List.of("tree-options"), List.of());
|
||||||
|
register(map, "input-tag", "field", List.of("tags"), List.of());
|
||||||
|
register(map, "input-color", "field", List.of("color"), List.of());
|
||||||
|
register(map, "input-file", "field", List.of("upload"), List.of());
|
||||||
|
register(map, "input-image", "field", List.of("image-upload"), List.of());
|
||||||
|
register(map, "input-table", "field", List.of("editable-table"), List.of());
|
||||||
|
register(map, "hidden", "field", List.of("hidden-value"), List.of());
|
||||||
|
return new PageComponentRegistry(map);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean supportsComponent(String type) {
|
||||||
|
return components.containsKey(type);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean supportsAction(String componentType, String actionType) {
|
||||||
|
PageComponentDefinition definition = components.get(componentType);
|
||||||
|
return definition != null && definition.allowedActions().contains(actionType);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, PageComponentDefinition> components() {
|
||||||
|
return components;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Map<String, Object> toResponse() {
|
||||||
|
Map<String, Object> data = new LinkedHashMap<>();
|
||||||
|
data.put("schemaVersion", VERSION);
|
||||||
|
data.put("components", components.values());
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void register(Map<String, PageComponentDefinition> map, String type, String category,
|
||||||
|
List<String> capabilities, List<String> allowedActions) {
|
||||||
|
map.put(type, new PageComponentDefinition(type, category, List.copyOf(capabilities),
|
||||||
|
List.copyOf(allowedActions)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
package com.eip4.platform.metadata.schema;
|
||||||
|
|
||||||
|
public record TypedPageSchemaIssue(String path, String code, String message) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.eip4.platform.metadata.schema;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public record TypedPageSchemaReport(
|
||||||
|
int schemaVersion,
|
||||||
|
boolean valid,
|
||||||
|
List<TypedPageSchemaIssue> issues,
|
||||||
|
Set<String> usedComponents,
|
||||||
|
Set<String> usedActions) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
package com.eip4.platform.metadata.schema;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.core.JacksonException;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
public final class TypedPageSchemaValidator {
|
||||||
|
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
private final PageComponentRegistry registry;
|
||||||
|
|
||||||
|
public TypedPageSchemaValidator(ObjectMapper objectMapper, PageComponentRegistry registry) {
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
this.registry = registry;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TypedPageSchemaValidator defaults() {
|
||||||
|
return new TypedPageSchemaValidator(new ObjectMapper(), PageComponentRegistry.defaults());
|
||||||
|
}
|
||||||
|
|
||||||
|
public TypedPageSchemaReport validate(String schemaJson) {
|
||||||
|
List<TypedPageSchemaIssue> issues = new ArrayList<>();
|
||||||
|
Set<String> usedComponents = new LinkedHashSet<>();
|
||||||
|
Set<String> usedActions = new LinkedHashSet<>();
|
||||||
|
JsonNode root;
|
||||||
|
try {
|
||||||
|
root = objectMapper.readTree(schemaJson);
|
||||||
|
} catch (JacksonException ex) {
|
||||||
|
issues.add(new TypedPageSchemaIssue("$", "INVALID_JSON", "schema 不是合法 JSON: " + ex.getOriginalMessage()));
|
||||||
|
return report(issues, usedComponents, usedActions);
|
||||||
|
}
|
||||||
|
if (root == null || !root.isObject()) {
|
||||||
|
issues.add(new TypedPageSchemaIssue("$", "ROOT_NOT_OBJECT", "页面 schema 根节点必须是 JSON object"));
|
||||||
|
return report(issues, usedComponents, usedActions);
|
||||||
|
}
|
||||||
|
if (!"page".equals(root.path("type").asText(""))) {
|
||||||
|
issues.add(new TypedPageSchemaIssue("$.type", "ROOT_TYPE_NOT_PAGE", "页面 schema 根节点 type 必须是 page"));
|
||||||
|
}
|
||||||
|
visit(root, "$", issues, usedComponents, usedActions);
|
||||||
|
return report(issues, usedComponents, usedActions);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void visit(JsonNode node, String path, List<TypedPageSchemaIssue> issues,
|
||||||
|
Set<String> usedComponents, Set<String> usedActions) {
|
||||||
|
if (node.isObject()) {
|
||||||
|
validateObject(node, path, issues, usedComponents, usedActions);
|
||||||
|
node.properties().forEach(entry -> visit(entry.getValue(), childPath(path, entry.getKey()),
|
||||||
|
issues, usedComponents, usedActions));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (node.isArray()) {
|
||||||
|
for (int i = 0; i < node.size(); i++) {
|
||||||
|
visit(node.get(i), path + "[" + i + "]", issues, usedComponents, usedActions);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateObject(JsonNode node, String path, List<TypedPageSchemaIssue> issues,
|
||||||
|
Set<String> usedComponents, Set<String> usedActions) {
|
||||||
|
String componentType = node.path("type").asText("");
|
||||||
|
if (!componentType.isBlank()) {
|
||||||
|
boolean registeredComponent = registry.supportsComponent(componentType);
|
||||||
|
boolean componentCandidate = registeredComponent || isComponentCandidate(path, node);
|
||||||
|
if (componentCandidate) {
|
||||||
|
usedComponents.add(componentType);
|
||||||
|
}
|
||||||
|
if (componentCandidate && !registeredComponent) {
|
||||||
|
issues.add(new TypedPageSchemaIssue(path + ".type", "UNSUPPORTED_COMPONENT",
|
||||||
|
"组件未注册: " + componentType));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String actionType = node.path("actionType").asText("");
|
||||||
|
if (!actionType.isBlank()) {
|
||||||
|
usedActions.add(actionType);
|
||||||
|
if (componentType.isBlank()) {
|
||||||
|
issues.add(new TypedPageSchemaIssue(path + ".actionType", "ACTION_WITHOUT_COMPONENT",
|
||||||
|
"actionType 必须绑定到有 type 的组件"));
|
||||||
|
} else if (!registry.supportsAction(componentType, actionType)) {
|
||||||
|
issues.add(new TypedPageSchemaIssue(path + ".actionType", "UNSUPPORTED_ACTION",
|
||||||
|
"组件 " + componentType + " 不支持 actionType: " + actionType));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isComponentCandidate(String path, JsonNode node) {
|
||||||
|
return "$".equals(path)
|
||||||
|
|| path.endsWith(".body")
|
||||||
|
|| path.contains(".body[")
|
||||||
|
|| path.contains(".columns[")
|
||||||
|
|| path.contains(".buttons[")
|
||||||
|
|| path.contains(".headerToolbar[")
|
||||||
|
|| path.contains(".footerToolbar[")
|
||||||
|
|| path.contains(".tabs[")
|
||||||
|
|| path.contains(".items[")
|
||||||
|
|| node.has("actionType")
|
||||||
|
|| node.has("body")
|
||||||
|
|| node.has("columns")
|
||||||
|
|| node.has("buttons")
|
||||||
|
|| node.has("label")
|
||||||
|
|| node.has("tpl")
|
||||||
|
|| node.has("dialog")
|
||||||
|
|| node.has("drawer")
|
||||||
|
|| node.has("required");
|
||||||
|
}
|
||||||
|
|
||||||
|
private TypedPageSchemaReport report(List<TypedPageSchemaIssue> issues, Set<String> usedComponents,
|
||||||
|
Set<String> usedActions) {
|
||||||
|
return new TypedPageSchemaReport(PageComponentRegistry.VERSION, issues.isEmpty(), List.copyOf(issues),
|
||||||
|
Collections.unmodifiableSet(new LinkedHashSet<>(usedComponents)),
|
||||||
|
Collections.unmodifiableSet(new LinkedHashSet<>(usedActions)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String childPath(String path, String field) {
|
||||||
|
if (field.matches("[A-Za-z_][A-Za-z0-9_]*")) {
|
||||||
|
return path + "." + field;
|
||||||
|
}
|
||||||
|
return path + "['" + field.replace("'", "\\'") + "']";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
package com.eip4.platform.metadata.schema.blueprint;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* EIP4 页面生成蓝图。
|
||||||
|
*
|
||||||
|
* <p>AI 和设计器应优先产出本对象,再由平台编译成 amis schema。这样 UI/UE 规则集中在
|
||||||
|
* recipe/compiler/validator 中,而不是散落在 Agent 提示词里。
|
||||||
|
*/
|
||||||
|
public record PageBlueprint(
|
||||||
|
int schemaVersion,
|
||||||
|
String recipe,
|
||||||
|
String templateId,
|
||||||
|
String title,
|
||||||
|
String tableName,
|
||||||
|
String entityName,
|
||||||
|
String primaryKey,
|
||||||
|
String displayField,
|
||||||
|
List<PageBlueprintField> fields,
|
||||||
|
boolean allowCreate,
|
||||||
|
boolean allowEdit,
|
||||||
|
boolean allowDelete,
|
||||||
|
int pageSize) {
|
||||||
|
|
||||||
|
public static final int VERSION = 1;
|
||||||
|
public static final String RECIPE_MAINTENANCE_CRUD = "maintenance-crud-v1";
|
||||||
|
public static final String RECIPE_TREE_CRUD = "tree-crud-v1";
|
||||||
|
|
||||||
|
public PageBlueprint {
|
||||||
|
fields = fields == null ? List.of() : List.copyOf(fields);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,355 @@
|
|||||||
|
package com.eip4.platform.metadata.schema.blueprint;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把 EIP4 受控 PageBlueprint 编译成当前前端可消费的 amis schema。
|
||||||
|
*/
|
||||||
|
public final class PageBlueprintCompiler {
|
||||||
|
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
public PageBlueprintCompiler(ObjectMapper objectMapper) {
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObjectNode compile(PageBlueprint blueprint) {
|
||||||
|
validate(blueprint);
|
||||||
|
if (PageBlueprint.RECIPE_MAINTENANCE_CRUD.equals(blueprint.recipe())) {
|
||||||
|
return maintenanceCrud(blueprint);
|
||||||
|
}
|
||||||
|
if (PageBlueprint.RECIPE_TREE_CRUD.equals(blueprint.recipe())) {
|
||||||
|
return treeCrud(blueprint);
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("Unsupported page recipe: " + blueprint.recipe());
|
||||||
|
}
|
||||||
|
|
||||||
|
private ObjectNode maintenanceCrud(PageBlueprint blueprint) {
|
||||||
|
ObjectNode page = objectMapper.createObjectNode();
|
||||||
|
page.put("type", "page");
|
||||||
|
page.put("title", blueprint.title());
|
||||||
|
ObjectNode crud = page.putObject("body");
|
||||||
|
String crudName = lowerCamel(blueprint.tableName()) + "Crud";
|
||||||
|
crud.put("type", "crud");
|
||||||
|
crud.put("name", crudName);
|
||||||
|
crud.put("syncLocation", false);
|
||||||
|
ObjectNode api = crud.putObject("api");
|
||||||
|
api.put("method", "get");
|
||||||
|
api.put("url", "/api/entity/" + blueprint.tableName() + "/list?page=${page}&perPage=${perPage}");
|
||||||
|
api.put("adaptor", "return payload;");
|
||||||
|
|
||||||
|
ArrayNode headerToolbar = crud.putArray("headerToolbar");
|
||||||
|
if (blueprint.allowCreate()) {
|
||||||
|
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", "新增" + blueprint.entityName());
|
||||||
|
ObjectNode addForm = addDialog.putObject("body");
|
||||||
|
addForm.put("type", "form");
|
||||||
|
addForm.put("api", "post:/api/entity/" + blueprint.tableName() + "/save");
|
||||||
|
addForm.set("body", formControls(blueprint, false));
|
||||||
|
}
|
||||||
|
headerToolbar.add("pagination");
|
||||||
|
|
||||||
|
ArrayNode footerToolbar = crud.putArray("footerToolbar");
|
||||||
|
footerToolbar.add("statistics");
|
||||||
|
footerToolbar.add("pagination");
|
||||||
|
crud.put("perPage", blueprint.pageSize());
|
||||||
|
crud.set("columns", columns(blueprint, crudName));
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ObjectNode treeCrud(PageBlueprint blueprint) {
|
||||||
|
ObjectNode page = objectMapper.createObjectNode();
|
||||||
|
page.put("type", "page");
|
||||||
|
page.put("title", blueprint.title());
|
||||||
|
ObjectNode crud = page.putObject("body");
|
||||||
|
String crudName = lowerCamel(blueprint.tableName()) + "TreeCrud";
|
||||||
|
crud.put("type", "crud");
|
||||||
|
crud.put("name", crudName);
|
||||||
|
crud.put("syncLocation", false);
|
||||||
|
crud.put("childrenColumnName", "children");
|
||||||
|
ObjectNode api = crud.putObject("api");
|
||||||
|
api.put("method", "get");
|
||||||
|
api.put("url", "/api/entity/" + blueprint.tableName()
|
||||||
|
+ "/tree?parentKey=PARENTID&idKey=" + blueprint.primaryKey() + "&perPage=2000");
|
||||||
|
api.put("adaptor", "return payload;");
|
||||||
|
|
||||||
|
ArrayNode headerToolbar = crud.putArray("headerToolbar");
|
||||||
|
if (blueprint.allowCreate()) {
|
||||||
|
ObjectNode addButton = headerToolbar.addObject();
|
||||||
|
addButton.put("type", "button");
|
||||||
|
addButton.put("label", "新增顶级" + blueprint.entityName());
|
||||||
|
addButton.put("level", "primary");
|
||||||
|
addButton.put("icon", "fa fa-plus");
|
||||||
|
addButton.put("actionType", "dialog");
|
||||||
|
ObjectNode addDialog = addButton.putObject("dialog");
|
||||||
|
addDialog.put("title", "新增顶级" + blueprint.entityName());
|
||||||
|
ObjectNode addForm = addDialog.putObject("body");
|
||||||
|
addForm.put("type", "form");
|
||||||
|
addForm.put("api", "post:/api/entity/" + blueprint.tableName() + "/save");
|
||||||
|
addForm.put("reload", crudName);
|
||||||
|
ArrayNode controls = formControlsExcluding(blueprint, false, "PARENTID");
|
||||||
|
controls.add(hidden("PARENTID", ""));
|
||||||
|
addForm.set("body", controls);
|
||||||
|
}
|
||||||
|
headerToolbar.add(reloadButton(crudName));
|
||||||
|
crud.putArray("footerToolbar");
|
||||||
|
crud.set("columns", treeColumns(blueprint, crudName));
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ArrayNode columns(PageBlueprint blueprint, String crudName) {
|
||||||
|
ArrayNode columns = objectMapper.createArrayNode();
|
||||||
|
for (PageBlueprintField field : blueprint.fields()) {
|
||||||
|
if (!field.listVisible()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ObjectNode column = columns.addObject();
|
||||||
|
column.put("name", field.name());
|
||||||
|
column.put("label", field.label());
|
||||||
|
}
|
||||||
|
if (!blueprint.allowEdit() && !blueprint.allowDelete()) {
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
ObjectNode op = columns.addObject();
|
||||||
|
op.put("type", "operation");
|
||||||
|
op.put("label", "操作");
|
||||||
|
op.put("width", 180);
|
||||||
|
ArrayNode buttons = op.putArray("buttons");
|
||||||
|
if (blueprint.allowEdit()) {
|
||||||
|
addEditAction(blueprint, buttons);
|
||||||
|
}
|
||||||
|
if (blueprint.allowDelete()) {
|
||||||
|
addDeleteAction(blueprint, buttons, crudName);
|
||||||
|
}
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ArrayNode treeColumns(PageBlueprint blueprint, String crudName) {
|
||||||
|
ArrayNode columns = objectMapper.createArrayNode();
|
||||||
|
for (PageBlueprintField field : blueprint.fields()) {
|
||||||
|
if (!field.listVisible() || "PARENTID".equals(field.name())) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ObjectNode column = columns.addObject();
|
||||||
|
column.put("name", field.name());
|
||||||
|
column.put("label", field.label());
|
||||||
|
}
|
||||||
|
ObjectNode op = columns.addObject();
|
||||||
|
op.put("type", "operation");
|
||||||
|
op.put("label", "操作");
|
||||||
|
op.put("width", 240);
|
||||||
|
ArrayNode buttons = op.putArray("buttons");
|
||||||
|
if (blueprint.allowCreate()) {
|
||||||
|
addChildAction(blueprint, buttons, crudName);
|
||||||
|
}
|
||||||
|
if (blueprint.allowEdit()) {
|
||||||
|
addTreeEditAction(blueprint, buttons, crudName);
|
||||||
|
}
|
||||||
|
if (blueprint.allowDelete()) {
|
||||||
|
addDeleteAction(blueprint, buttons, crudName);
|
||||||
|
}
|
||||||
|
return columns;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addChildAction(PageBlueprint blueprint, ArrayNode buttons, String crudName) {
|
||||||
|
ObjectNode addChild = buttons.addObject();
|
||||||
|
addChild.put("type", "button");
|
||||||
|
addChild.put("label", "加子" + blueprint.entityName());
|
||||||
|
addChild.put("level", "link");
|
||||||
|
addChild.put("actionType", "dialog");
|
||||||
|
ObjectNode dialog = addChild.putObject("dialog");
|
||||||
|
dialog.put("title", "在${" + blueprint.displayField() + "}下新增" + blueprint.entityName());
|
||||||
|
ObjectNode form = dialog.putObject("body");
|
||||||
|
form.put("type", "form");
|
||||||
|
form.put("api", "post:/api/entity/" + blueprint.tableName() + "/save");
|
||||||
|
form.put("reload", crudName);
|
||||||
|
ArrayNode controls = objectMapper.createArrayNode();
|
||||||
|
controls.add(hidden("PARENTID", "${" + blueprint.primaryKey() + "}"));
|
||||||
|
controls.addAll(formControlsExcluding(blueprint, false, "PARENTID"));
|
||||||
|
form.set("body", controls);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addTreeEditAction(PageBlueprint blueprint, ArrayNode buttons, String crudName) {
|
||||||
|
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", "编辑${" + blueprint.displayField() + "}");
|
||||||
|
ObjectNode editForm = editDialog.putObject("body");
|
||||||
|
editForm.put("type", "form");
|
||||||
|
editForm.put("api", "post:/api/entity/" + blueprint.tableName() + "/save");
|
||||||
|
editForm.put("reload", crudName);
|
||||||
|
ArrayNode editControls = formControlsExcluding(blueprint, true, "PARENTID");
|
||||||
|
editControls.add(hidden("PARENTID", "${PARENTID}"));
|
||||||
|
editControls.add(hidden(blueprint.primaryKey(), "${" + blueprint.primaryKey() + "}"));
|
||||||
|
editForm.set("body", editControls);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addEditAction(PageBlueprint blueprint, ArrayNode 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", "编辑${" + blueprint.displayField() + "}");
|
||||||
|
ObjectNode editForm = editDialog.putObject("body");
|
||||||
|
editForm.put("type", "form");
|
||||||
|
editForm.put("api", "post:/api/entity/" + blueprint.tableName() + "/save");
|
||||||
|
ArrayNode editControls = formControls(blueprint, true);
|
||||||
|
ObjectNode hiddenPk = objectMapper.createObjectNode();
|
||||||
|
hiddenPk.put("type", "hidden");
|
||||||
|
hiddenPk.put("name", blueprint.primaryKey());
|
||||||
|
hiddenPk.put("value", "${" + blueprint.primaryKey() + "}");
|
||||||
|
editControls.add(hiddenPk);
|
||||||
|
editForm.set("body", editControls);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void addDeleteAction(PageBlueprint blueprint, ArrayNode buttons, String crudName) {
|
||||||
|
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/" + blueprint.tableName() + "/delete");
|
||||||
|
ObjectNode data = delApi.putObject("data");
|
||||||
|
data.put("id", "${" + blueprint.primaryKey() + "}");
|
||||||
|
del.put("reload", crudName);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ArrayNode formControls(PageBlueprint blueprint, boolean bindCurrentRow) {
|
||||||
|
return formControlsExcluding(blueprint, bindCurrentRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
private ArrayNode formControlsExcluding(PageBlueprint blueprint, boolean bindCurrentRow, String... excludedFields) {
|
||||||
|
ArrayNode controls = objectMapper.createArrayNode();
|
||||||
|
for (PageBlueprintField field : blueprint.fields()) {
|
||||||
|
if (!field.formVisible() || isExcluded(field.name(), excludedFields)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
ObjectNode c = controls.addObject();
|
||||||
|
c.put("type", controlType(field.type()));
|
||||||
|
c.put("name", field.name());
|
||||||
|
c.put("label", field.label());
|
||||||
|
if (field.required()) {
|
||||||
|
c.put("required", true);
|
||||||
|
}
|
||||||
|
if (bindCurrentRow) {
|
||||||
|
c.put("value", "${" + field.name() + "}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return controls;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ObjectNode hidden(String name, String value) {
|
||||||
|
ObjectNode hidden = objectMapper.createObjectNode();
|
||||||
|
hidden.put("type", "hidden");
|
||||||
|
hidden.put("name", name);
|
||||||
|
hidden.put("value", value);
|
||||||
|
return hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ObjectNode reloadButton(String target) {
|
||||||
|
ObjectNode button = objectMapper.createObjectNode();
|
||||||
|
button.put("type", "button");
|
||||||
|
button.put("label", "刷新");
|
||||||
|
button.put("level", "link");
|
||||||
|
button.put("icon", "fa fa-refresh");
|
||||||
|
button.put("actionType", "reload");
|
||||||
|
button.put("target", target);
|
||||||
|
return button;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validate(PageBlueprint blueprint) {
|
||||||
|
if (blueprint == null) {
|
||||||
|
throw new IllegalArgumentException("Page blueprint is required");
|
||||||
|
}
|
||||||
|
if (blueprint.schemaVersion() != PageBlueprint.VERSION) {
|
||||||
|
throw new IllegalArgumentException("Unsupported page blueprint version: " + blueprint.schemaVersion());
|
||||||
|
}
|
||||||
|
if (!PageBlueprint.RECIPE_MAINTENANCE_CRUD.equals(blueprint.recipe())
|
||||||
|
&& !PageBlueprint.RECIPE_TREE_CRUD.equals(blueprint.recipe())) {
|
||||||
|
throw new IllegalArgumentException("Unsupported page recipe: " + blueprint.recipe());
|
||||||
|
}
|
||||||
|
required(blueprint.templateId(), "templateId");
|
||||||
|
required(blueprint.title(), "title");
|
||||||
|
required(blueprint.tableName(), "tableName");
|
||||||
|
required(blueprint.entityName(), "entityName");
|
||||||
|
required(blueprint.primaryKey(), "primaryKey");
|
||||||
|
required(blueprint.displayField(), "displayField");
|
||||||
|
if (blueprint.fields() == null || blueprint.fields().isEmpty()) {
|
||||||
|
throw new IllegalArgumentException("fields must not be empty");
|
||||||
|
}
|
||||||
|
boolean displayFieldExists = false;
|
||||||
|
for (PageBlueprintField field : blueprint.fields()) {
|
||||||
|
required(field.name(), "field.name");
|
||||||
|
required(field.label(), "field.label");
|
||||||
|
required(field.type(), "field.type");
|
||||||
|
if (field.name().equals(blueprint.displayField())) {
|
||||||
|
displayFieldExists = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!displayFieldExists) {
|
||||||
|
throw new IllegalArgumentException("displayField must match one blueprint field");
|
||||||
|
}
|
||||||
|
if (PageBlueprint.RECIPE_TREE_CRUD.equals(blueprint.recipe())
|
||||||
|
&& blueprint.fields().stream().noneMatch(field -> "PARENTID".equals(field.name()))) {
|
||||||
|
throw new IllegalArgumentException("tree-crud-v1 requires PARENTID field");
|
||||||
|
}
|
||||||
|
if (blueprint.pageSize() < 1 || blueprint.pageSize() > 200) {
|
||||||
|
throw new IllegalArgumentException("pageSize must be between 1 and 200");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void required(String value, String field) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
throw new IllegalArgumentException(field + " is required");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 boolean isExcluded(String fieldName, String... excludedFields) {
|
||||||
|
for (String excluded : excludedFields) {
|
||||||
|
if (excluded.equals(fieldName)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package com.eip4.platform.metadata.schema.blueprint;
|
||||||
|
|
||||||
|
public record PageBlueprintField(
|
||||||
|
String name,
|
||||||
|
String label,
|
||||||
|
String type,
|
||||||
|
boolean required,
|
||||||
|
boolean listVisible,
|
||||||
|
boolean formVisible) {
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package com.eip4.platform.metadata.schema.blueprint;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public record PageRecipeDefinition(
|
||||||
|
String recipe,
|
||||||
|
int schemaVersion,
|
||||||
|
String title,
|
||||||
|
Map<String, String> fieldMappings,
|
||||||
|
List<String> gates) {
|
||||||
|
|
||||||
|
public PageRecipeDefinition {
|
||||||
|
if (recipe == null || recipe.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("recipe is required");
|
||||||
|
}
|
||||||
|
if (schemaVersion < 1) {
|
||||||
|
throw new IllegalArgumentException("schemaVersion must be positive");
|
||||||
|
}
|
||||||
|
title = title == null ? "" : title;
|
||||||
|
fieldMappings = Map.copyOf(fieldMappings == null ? Map.of() : fieldMappings);
|
||||||
|
gates = List.copyOf(gates == null ? List.of() : gates);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package com.eip4.platform.metadata.schema.blueprint;
|
||||||
|
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||||
|
|
||||||
|
public final class PageRecipeRegistry {
|
||||||
|
|
||||||
|
private final Map<String, PageRecipeDefinition> recipes;
|
||||||
|
|
||||||
|
public PageRecipeRegistry(List<PageRecipeDefinition> definitions) {
|
||||||
|
Map<String, PageRecipeDefinition> ordered = new LinkedHashMap<>();
|
||||||
|
for (PageRecipeDefinition definition : definitions == null ? List.<PageRecipeDefinition>of() : definitions) {
|
||||||
|
PageRecipeDefinition previous = ordered.put(definition.recipe(), definition);
|
||||||
|
if (previous != null) {
|
||||||
|
throw new IllegalArgumentException("Duplicate page recipe: " + definition.recipe());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
this.recipes = Map.copyOf(ordered);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static PageRecipeRegistry defaults() {
|
||||||
|
return new PageRecipeRegistry(List.of(maintenanceCrud(), treeCrud()));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Optional<PageRecipeDefinition> find(String recipe) {
|
||||||
|
if (recipe == null || recipe.isBlank()) {
|
||||||
|
return Optional.empty();
|
||||||
|
}
|
||||||
|
return Optional.ofNullable(recipes.get(recipe));
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean supports(String recipe) {
|
||||||
|
return find(recipe).isPresent();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<PageRecipeDefinition> definitions() {
|
||||||
|
return List.copyOf(recipes.values());
|
||||||
|
}
|
||||||
|
|
||||||
|
public ObjectNode compile(PageBlueprint blueprint, ObjectMapper objectMapper) {
|
||||||
|
if (!supports(blueprint == null ? null : blueprint.recipe())) {
|
||||||
|
String recipe = blueprint == null ? "" : blueprint.recipe();
|
||||||
|
throw new IllegalArgumentException("Unsupported page recipe: " + recipe);
|
||||||
|
}
|
||||||
|
return switch (blueprint.recipe()) {
|
||||||
|
case PageBlueprint.RECIPE_MAINTENANCE_CRUD -> new PageBlueprintCompiler(objectMapper).compile(blueprint);
|
||||||
|
case PageBlueprint.RECIPE_TREE_CRUD -> new PageBlueprintCompiler(objectMapper).compile(blueprint);
|
||||||
|
default -> throw new IllegalArgumentException("Unsupported page recipe: " + blueprint.recipe());
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PageRecipeDefinition maintenanceCrud() {
|
||||||
|
return new PageRecipeDefinition(
|
||||||
|
PageBlueprint.RECIPE_MAINTENANCE_CRUD,
|
||||||
|
PageBlueprint.VERSION,
|
||||||
|
"EIP4 maintenance CRUD page",
|
||||||
|
Map.of(
|
||||||
|
"string", "input-text",
|
||||||
|
"integer", "input-number",
|
||||||
|
"number", "input-number",
|
||||||
|
"date", "input-date",
|
||||||
|
"datetime", "input-datetime",
|
||||||
|
"boolean", "switch"),
|
||||||
|
List.of("page-recipe", "typed-page-schema", "amis-schema", "local-smoke", "playwright-render"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static PageRecipeDefinition treeCrud() {
|
||||||
|
return new PageRecipeDefinition(
|
||||||
|
PageBlueprint.RECIPE_TREE_CRUD,
|
||||||
|
PageBlueprint.VERSION,
|
||||||
|
"EIP4 tree CRUD page",
|
||||||
|
Map.of(
|
||||||
|
"string", "input-text",
|
||||||
|
"integer", "input-number",
|
||||||
|
"number", "input-number",
|
||||||
|
"date", "input-date",
|
||||||
|
"datetime", "input-datetime",
|
||||||
|
"boolean", "switch"),
|
||||||
|
List.of("page-recipe", "typed-page-schema", "amis-schema", "local-smoke", "playwright-render"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package com.eip4.platform.metadata.schema.blueprint;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public record PageRecipeValidationReport(
|
||||||
|
String recipe,
|
||||||
|
boolean valid,
|
||||||
|
List<String> messages) {
|
||||||
|
|
||||||
|
public PageRecipeValidationReport {
|
||||||
|
recipe = recipe == null ? "" : recipe;
|
||||||
|
messages = List.copyOf(messages == null ? List.of() : messages);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user