Merge branch 'feat/human-five-ring' into main
Some checks failed
ci / build-test-parity (push) Has been cancelled
Some checks failed
ci / build-test-parity (push) Has been cancelled
人走五环建新功能(设计中心新建入口) + 主子表 v1 完整四件:基础 master-detail、 派生字段(金额=数量×单价)、父级汇总(总额=之和)、引用驱动联动(选物料→带出单价/规格)。 platform-metadata 468 单测 + Playwright 真事件 e2e 全绿。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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/
|
||||||
|
|||||||
182
docs/AI_AGENT_AUTO_DEVELOPMENT.md
Normal file
182
docs/AI_AGENT_AUTO_DEVELOPMENT.md
Normal file
@@ -0,0 +1,182 @@
|
|||||||
|
# AI Agent 辅助开发运行说明(生成草稿 + 本地验证 + 人工复核发布)
|
||||||
|
|
||||||
|
> **能力边界(对外口径,红线)**:本能力是「**AI 辅助生成草稿 + 人工复核发布**」,**不是** AI 全自动开发。当前只覆盖最简单的 CRUD recipe,存量复杂场景未取得数据;按《EIP3架构决策会纪要》红线,**严禁在报价/合同中承诺「AI 全自动开发 / 人力大幅下降」**。线上变更一律输出人工部署包、由人工复核后发布。
|
||||||
|
|
||||||
|
`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:AI 辅助开发主链路(人工复核发布)
|
||||||
|
|
||||||
|
状态:已完成。
|
||||||
|
|
||||||
|
完成内容:
|
||||||
|
|
||||||
|
- `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 页面必填结构"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
133
docs/plans/2026-06-19-EIP4开发平台-架构方向-design.md
Normal file
133
docs/plans/2026-06-19-EIP4开发平台-架构方向-design.md
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
# EIP4 开发平台 · 架构方向(与最初设计对齐版)
|
||||||
|
|
||||||
|
> 日期:2026-06-19 | 性质:方向级 design(brainstorm 收敛 + 最初设计考古 + 引擎代码核实 + 对抗审查产出)
|
||||||
|
> 配套权威:`项目进度与路线-总览-2026-06-17.md`(A 兼容 / B 新功能全景)、`架构设计.md`(双层制/选型/红线)、`决策与盘点/EIP4前端与收尾实施计划.md`(F4 低代码工具链原始定义)
|
||||||
|
> 方法:9-agent workflow(7 路考古/代码核实 → 综合 → 对抗审查),逐行核实引擎实况。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. 一句话结论
|
||||||
|
|
||||||
|
**「153 收尾后做可视化开发平台」不是另起炉灶,是项目最初路线图里 F4「低代码工具链 L1→L3」的兑现。** 方向成立(对抗审查判决 `sound-with-fixes`),但最初设计逼出三根硬约束(一根是「触发重新决策」级),需带 6 条修正落地。
|
||||||
|
|
||||||
|
## 1. 背景与驱动(用户拍板)
|
||||||
|
|
||||||
|
- **先 B 提效、再 A 卖点**:先用新能力填「建页/建模/交付太慢太贵」的钱坑,再讲 AI/现代化差异化。
|
||||||
|
- **递进**:存量 153 定制视图用现有兼容方式(转换器 mutator)啃完(已完成几十个);真正重点是 153 后,面向「**未来功能维护 + 新功能开发**」要有一套现代可视化开发平台,覆盖【**元数据 → 表结构 → 设计 → 实现功能 → 发布**】五环。
|
||||||
|
- **AI 独立轨**:已在另一分支做,定位=给 AI coding 工具(Claude Code/Cursor)供 **MCP + CLI**,不是应用内 AI 生成 schema。
|
||||||
|
- **定位**:内部交付提效工具(**非**对客户售卖的低代码/自助配置平台——见 §5 红线)。
|
||||||
|
|
||||||
|
## 2. 与最初设计「一脉相承」的依据(5 处文档锚点)
|
||||||
|
|
||||||
|
| 本方向 | 最初设计原文锚点 |
|
||||||
|
|---|---|
|
||||||
|
| 五环【元数据→表→设计→实现→发布】 | 《EIP4前端与收尾实施计划》F4 总览:**「低代码工具链 L1→L3,门控:无(架构已拍板)」**;§七:L1 页面设计器=amis-editor 二开 / L2 实体建模器=可视化维护 SYS_ENTITY / L3 流程设计器=bpmn.js + Flowable。末环=§6.3 在线导入发布 |
|
||||||
|
| 现代层 authoring 长在引擎上 | 架构设计 §一「**保真层供奉、现代层生长**」+ ArchUnit 单向纪律(`com.eip4.*` 可调 `com.dsasp.*`,反向禁止) |
|
||||||
|
| 一个 schema 世界 | §6.2「SYS_PAGE_SCHEMA 标准层 + overlay 层,升级时标准层整体替换、overlay 保留提示 diff」 |
|
||||||
|
| AI 独立轨给 MCP+CLI | 最初 **P5「MCP/AI 工具层」** 逐字吻合 |
|
||||||
|
|
||||||
|
**引擎实况(已读码核实)**:四环里**三环引擎已在保真层活着**——`Entity.java`/`POInfo.java`/`POJOCRUDServiceImpl`(元数据 CRUD)、`Entity.createTableSql`→`DataDicServiceImpl`(动态建表)、`FlowExcuteServiceImpl`(534 行,含 `insertNodeAfter/removeNode` 图编辑原语 + `saveOrUpdate` 写回 `SYS_SERVICEFLOW`)、Groovy/JUEL 脚本引擎。
|
||||||
|
|
||||||
|
## 3. 最初设计强加的三根硬约束(对抗审查核实)
|
||||||
|
|
||||||
|
### ① 最大矛盾 · 焊死退路(go/no-go 级)—— 决策:**签字下注 amis**
|
||||||
|
最初把 amis-editor/自研设计器钉为「amis fork 失败时的防御性 **Plan B**」(止损 S2,换渲染器损失仅 1–2 人月)。架构决策报告 §四「触发重新决策条件#1」:*若决策层不接受永久 fork + 终身自维护前端渲染器的预算 → 须重评其他 Apache 渲染层*。把 amis-editor 升为战略主线 = 主动焊死退路 = 踩中该触发条件。
|
||||||
|
**已知天花板(写进立项)**:amis-fork 6.13.0 冻结于 2025-08、近 3 月零上游提交、bus factor≈1、需 **0.5–1 人/年自维护**。
|
||||||
|
**用户拍板**:✅ 签字下注 amis。**但附带关键现实**:**DesignerPage 当前还无法真正使用**(见 §7)——下注成立的前提是先把它弄到能用。
|
||||||
|
|
||||||
|
### ② 「补 UI 非造引擎」被系统性低估 —— 真实=「一环就位 + 两环要补引擎」
|
||||||
|
- **设计环**:✅ 就位,但**仅 edit-only on 存量页**(e2e 68/68 验的是 overlay 存取往返,**不等于设计器可用**)。
|
||||||
|
- **建模环**:🔴 引擎层**不能 ALTER**(`executeCreateSql` 只接受 CREATE,`DataDicServiceImpl:193-200`);`MetaController` 是克隆 SYS_USERGROUP、限 `EIP4AI_` 前缀的 **AI 雏形**,非面向人。新建实体后改字段**零迁移路径**。
|
||||||
|
- **编排环**:🔴 `FlowController` **只执行不编辑**,flow 仍是老 XML,EIP4 侧 **0 个 authoring REST**。
|
||||||
|
|
||||||
|
### ③ overlay 是 edit-only —— 「一个 schema 世界」附条件成立(一次性数据建模门)
|
||||||
|
`SYS_PAGE_SCHEMA_OVERLAY` 以 `template_id` 为主键、`base_etag` 挂靠**转换器产出的标准层**。「一个 schema 世界 + 可升级」的优雅**只在「先有标准底版、overlay 是其差量」时成立**。**从零新建的页没有标准底版**,其生命周期/升级/diff 在最初设计里是**空白**。「改存量页已上线」≠「新建页平台就绪」。
|
||||||
|
|
||||||
|
## 4. 逻辑编排器(唯一硬骨头)—— 决策:**b 主干 + 人工 20% + c 增量,否决 a**
|
||||||
|
|
||||||
|
- **否决 a(节点图编辑器)**:最初零根基;`Flow.java:422/454` 对非线性流主动抛「请用高级配置进行编辑」——证明**连老 EIP3 自己的可视化也只覆盖线性流**。节点图是最重前端投资、对冻结栈纯新增,ROI 最差。
|
||||||
|
- **b 主干**:80% 常规联动/线性服务流走声明式配置面(32 个 facade 动词 onEvent 面板,复用已有),不写代码即提效。
|
||||||
|
- **诚实修正(对抗审查)**:b 只覆盖**老系统已能可视化的线性流**;那 20% 复杂逻辑(非线性流/有副作用 Groovy/跨流条件=最初 S3 留下的 **115 份人工作业单**)**b 接不住**。
|
||||||
|
- **故**:那 20% **默认保留「人工作业单」兜底**(人写 Groovy/JUEL,复用 `field-editor`);**c(AI 生成)仅「加速人工 + 人工复核入库」增量**,platform-ai 空壳未落地前**不算进对外交付能力**。对外能力边界=「**b 声明式 80% + 人工 20%**」。
|
||||||
|
|
||||||
|
## 5. 落地形态(与最初设计对齐)
|
||||||
|
|
||||||
|
不立「新平台」为独立大项目,而是把 F4 三件套 + §6.2 overlay + §6.3 发布 + P5 MCP 正式化为一套「**现代层 authoring 模块集合**」,落在 `platform-metadata` 等现有模块内(不新进程),守三红线:
|
||||||
|
|
||||||
|
> **4 进程私有化单体 / 无新中间件 / 无多租户**;authoring 必须走既有引擎接口签名(POInfo/Entity/DataPrivilege/FlowExcuteService)**不旁路**。
|
||||||
|
|
||||||
|
- **存储层零新增**:authoring 全部读写 `SYS_ENTITY`/`SYS_ENTITYATTRIBUTE`(元数据真相)、`SYS_SERVICEFLOW.CONTENTXML`(服务流真相)、`SYS_PAGE_SCHEMA`+overlay(页面真相)。「元数据即白名单」运行期/开发期同源。
|
||||||
|
- **定位红线**:架构决策报告 §2.1a 已把「交付带动态建表的低代码平台能力给客户继续配置」定性为合同敏感地带(曾用于否决路线 B)。新平台守在**内部提效工具**,不对外做 SaaS/多租户配置平台。
|
||||||
|
|
||||||
|
## 6. 分期路线(每期标复用什么 / 补什么引擎欠账)
|
||||||
|
|
||||||
|
| 期 | 目标 | 关键交付 | 真实前置 / 复用 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **P0** | 立底座 + 门禁 | 组件设计体系 **L1 主题 token 做到生产级**(决策2「先 B 提效」的 UI 前提);为新 authoring 产物补**正确性门禁**(新建页无对拍基准!→ 元数据变更 CRUD 烟测 + 编排执行对拍 + overlay 版本可审计回滚 + schema 双闸复用);amis 战略取舍立项书签字 | **真实前置=组件 L1,非 153**;复用 overlay 双层、schema 双闸 |
|
||||||
|
| **P1** | 设计环正式化 + **先修 DesignerPage 可用性** | 诊断并修复 DesignerPage「无法使用」(见 §7);从「改存量」升级到能用;**补 net-new 页数据模型/生命周期**(闭合 §3③门);收敛独立设计中心(评估 `DesignCenterPage.tsx` 雏形);facade onEvent 声明式面板第一块 | 复用 DesignerPage/overlayApi、PageSchemaController、facade 动词表 |
|
||||||
|
| **P2** | 建模环 | **先补引擎安全 `alterTableSql`**(加法在线/改删走升级窗口,守 §6.3 红线)再做 L2 建模器 UI;MetaController 从 AI 雏形重写为面向人 | 复用 Entity.createTableSql + 缓存失效免重启 |
|
||||||
|
| **P3** | 编排环(硬骨头·打法 b) | 服务流 authoring REST 出口(暴露 `FlowServiceImpl.saveOrUpdate` + 图编辑原语)+ 声明式线性流配置面 + Groovy 代码编辑器兜底;BPMN 审批流走 L3 bpmn.js | 复用 FlowExcuteService + Flow 图编辑原语 + DefaultFlowHelper |
|
||||||
|
| **P4** | 发布环 + 链条贯通 | §6.3 元数据资产包另存/导入;「建实体→合成默认流→生成默认页→设计器微调→发布」串通 | 复用 §6.3 资产包 + 缓存失效 + DefaultFlowHelper |
|
||||||
|
| **P5** | AI 工具面(决策3 独立轨·c 兜底) | Meta/Flow 端点升级为正式 MCP,接通 platform-ai 空壳,消除两套 authoring 入口 | 复用已建端点 + schema 校验 |
|
||||||
|
|
||||||
|
> 启动次序:**与 153 收尾并行**(用户拍板)。解除「153 收尾后才做」硬前置——153 进度由商务 S1 拍板、不由技术,挂其后会被无限期阻塞。**但据实承认**:新平台真实前置是组件 L1,不是把「等 153」换成「等组件 L1」的隐藏依赖游戏。
|
||||||
|
|
||||||
|
## 7. DesignerPage 现状(状态标记,非当前动手任务)
|
||||||
|
|
||||||
|
> 定性:这是一个**已知状态**(用户实测不可用),作为 D1 amis 下注的前置验证项纳入 P1,**不在架构方向讨论里展开 debug**。诊断已查实环境层根因嫌疑(见下),最终复现/修复留到 P1 执行期。
|
||||||
|
|
||||||
|
**入口模型(D5 已定)**:单一「设计中心」菜单入口(运行态/设计态分离),废弃每页注入按钮。`DesignCenterPage.tsx`(fetchMenu→collectLeaves 列页 + 「设计」入口)是正确雏形方向,需补「新建页」与 net-new 生命周期(§3③)。
|
||||||
|
|
||||||
|
**「打开没有内容」环境层查实(curl/lsof 实测,2026-06-19)**:
|
||||||
|
- **8093 是纯 API 后端,完全不托管前端**(`/`、`/index.html`、`/assets/*`、`/editor.html` 全 404);
|
||||||
|
- 前端只活在 **4 个 stale 重复 vite dev server**(5174-5177);`.env` 有重复 `VITE_BACKEND_TARGET`(8084→8093)——**stale 实例代理到死端口 8084 → schema 拉不到 → 画布空** 是头号嫌疑;
|
||||||
|
- editor.html 入口页本身没坏(vite 上 200 + CSS 直链 200,dist 构建也正确);
|
||||||
|
- 这同时暴露 **A10:整个前端(设计器在内)没有被托管的家,只跑临时 dev 进程** —— 设计器「无法使用」一半是部署/托管缺失。
|
||||||
|
|
||||||
|
**旧线索(仍待 P1 复现确认)**:
|
||||||
|
- e2e 只验 overlay 存取往返,**未验设计器作为 authoring 工具可用**;
|
||||||
|
- 报告自承「**facade onEvent 可视化面板未做**」——能拖布局、配不了行为;
|
||||||
|
- `editor.html` CSS 走 `/node_modules/...` 直链(dev-only hack),**生产构建可能裂**;
|
||||||
|
- **edit-only on 存量页**,不能新建/绑新实体(§3③门);
|
||||||
|
- `DesignerPage.handleRestore` 注释自承:amis-editor 整体替换 value 会「白屏」,故还原后整页 reload(提示 amis-editor 二开的脆性)。
|
||||||
|
|
||||||
|
**下一步**:钉准「无法使用」的真实症状(开不了 / 白屏 / 只能改存量 / 能改但太糙/配不了逻辑 / 生产构建裂),再定 P1 第一锤。
|
||||||
|
|
||||||
|
## 8. 6 条必须吞下的修正(对抗审查 fixes)
|
||||||
|
|
||||||
|
1. 「放弃渲染层可换退路」升为立项**硬 go/no-go**,立项书签字接受 amis-fork 冻结天花板。(✅ 用户已签)
|
||||||
|
2. 为 net-new 页补数据模型与生命周期,再谈「一个 schema 世界」;闭合前不把「设计中心」当「新平台就绪」对外宣称。
|
||||||
|
3. 拆 b/c 真空:20% 复杂逻辑默认「人工作业单」兜底,c 仅「加速人工 + 人工复核」,platform-ai 落地前不算进交付。
|
||||||
|
4. 引擎层**先补安全 `alterTableSql` 并冻结边界**再做 L2 UI;MetaController 重写为面向人,别在 AI 雏形上长 UI。
|
||||||
|
5. 解除「153 后才做」硬前置,但 P0 据实命名「L1 底座 + authoring 门禁」,不用隐藏前置替换显式前置。
|
||||||
|
6. 为新 authoring 产物新设正确性门禁(新建页无对拍基准)——提为 **P0 交付物**,是绕过最初数据事故控制机制的唯一补偿。
|
||||||
|
|
||||||
|
## 9. 顶层风险
|
||||||
|
|
||||||
|
- 逻辑编排环是最初真空地带、无对拍基准、最高不确定(S3 自动化率 <80% 即触发工期重估)。
|
||||||
|
- amis-fork 冻结天花板被加码(押更多二开在 bus factor≈1 的栈上)。
|
||||||
|
- 建表 ALTER 缺口 × §6.3「DDL 只允许加法在线」红线夹击——「改表」体验天然受限,不能做成自由在线 DDL。
|
||||||
|
- 「元数据即白名单」在线 authoring 下可能反转为约束:白名单变活动目标,并发 authoring 的一致性/缓存时序是新攻击面。
|
||||||
|
- 组件体系未达生产级即做设计中心=重蹈「功能对但观感差」覆辙。
|
||||||
|
|
||||||
|
## 10. 决策记录(本次锁定)
|
||||||
|
|
||||||
|
| # | 决策 | 选择 |
|
||||||
|
|---|---|---|
|
||||||
|
| D1 | amis-editor 战略下注 | ✅ 签字下注(接受冻结天花板);前提=先修 DesignerPage 可用性 |
|
||||||
|
| D2 | 新平台启动次序 | ✅ 与 153 并行(真实前置=组件 L1) |
|
||||||
|
| D3 | 逻辑编排打法 | ✅ b 主干 + 人工 20% + c 增量,否决 a |
|
||||||
|
| D4 | 对外定位 | 内部提效工具(守 §5 合同红线)|
|
||||||
|
| D5 | **设计入口模型** | ✅ **单一「设计中心」菜单入口**(运行态/设计态分离);**废弃每页注入的设计按钮**(转换器 `EngineclassDelta:898` + PageRenderPage「设计」按钮,用户已移除)。开发/设计是独立工作区,不混进业务页工具栏 |
|
||||||
|
| D6 | **AI 轨形态** | ✅ AI = **独立 NocoBase 式 CLI 编程轨**(`feature-package` 为单元的 scaffold→dev→verify→release 生命周期,供 Claude Code/Cursor 等 AI coding 工具操作),**不并入设计中心**。EIP4 的「插件」等价物 = 元数据 feature-package(非代码插件) |
|
||||||
|
| D7 | **设计中心定位** | ✅ 设计中心 = **给实施人员的纯人工 no-code**(b 轨),不挂 AI 入口;AI 走 D6 独立 CLI 轨 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 落地状态(2026-06-19 续)
|
||||||
|
|
||||||
|
- **AI agent 分支已合入 main(`9aea6c1`)**:交付了五环+横向的后端地基一大半(schema 门禁/三真相 authoring 端点/recipe-blueprint/元数据建实体/CLI 种子),并由 3 个收口提交保障合 main 安全(分流 `bac69d8` / admin 门 `c379f5b` / 对外口径 `9aea6c1`)。逐项对账 + 有序里程碑见 **`2026-06-19-EIP4开发平台-落地执行路线图.md`**(活计划)。
|
||||||
|
- **仍为 P0 锁定前置且未起步**:组件设计体系 **L1 主题 token 生产级**(D2)——路线图 M0。
|
||||||
|
- 本方向级 design 为权威决策记录;可执行里程碑/状态以路线图为准。
|
||||||
|
|
||||||
|
*本文为方向级 design;细化实施计划见配套《落地执行路线图》。*
|
||||||
76
docs/plans/2026-06-19-EIP4开发平台-落地执行路线图.md
Normal file
76
docs/plans/2026-06-19-EIP4开发平台-落地执行路线图.md
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
# EIP4 开发平台 · 落地执行路线图
|
||||||
|
|
||||||
|
> 日期 2026-06-19 | 活计划,配套《2026-06-19-EIP4开发平台-架构方向-design.md》(方向+锁定决策 D1-D7)。本文是该 design doc 承诺的「另立 plan 文档」。每里程碑落地后回写状态。
|
||||||
|
> **经对抗审查修订**:补回 D2 锁定的 P0 前置(组件 L1);把正确性门禁(渲染冒烟)置于真库 dogfood 之前;net-new 旁路先收口为单一写真相再立新端点;区分「build 完成 vs env 终验」。
|
||||||
|
|
||||||
|
## 0. 修订要点(为什么不照搬初稿)
|
||||||
|
|
||||||
|
- design §6 的 P0 = **组件 L1 主题 token 生产级**,是 D2 锁定的「真实前置」;初稿漏了,本版补为 **M0**,且设计中心-facing 里程碑(M3b 新建入口 / M5 面板)必须 gated 在 M0 之后(否则重蹈 design §9「功能对观感差」覆辙)。
|
||||||
|
- design fix#6:新 authoring 产物无对拍基准,**渲染冒烟闸是绕过原数据事故控制的唯一补偿**——必须先于任何真库 dogfood。
|
||||||
|
- net-new 标准层现由 `AiLocalReleaseExecutor:158` 裸 JDBC 旁路直写;新端点必须**先把旁路收口为单一写函数**,否则两套写法并存(语义/审计/etag 漂移)。
|
||||||
|
|
||||||
|
## 1. AI 合并交付对账(设计五环+横向 → 已交付 → 状态 → 剩余)
|
||||||
|
|
||||||
|
> 图例:🟢=主体已交付且无 P0 级剩余 | 🟡=部分交付/有 P0 级剩余(见右列)| 🔴=未起步。main 现位于 `9aea6c1`(fast-forward 纳入 AI 合并 `bd4c642` + 3 收口 `bac69d8`/`c379f5b`/`9aea6c1`,全 reactor 10 模块绿)。
|
||||||
|
|
||||||
|
| 环/横向 | 已交付 | 状态 | 剩余(含 P0 标注) |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 横向·正确性门禁 | TypedPageSchemaValidator + recipe 逐字节对拍 + 官方 draft-07,已接 putOverlay(分流后只对 AI 草稿严格) | 🟡 | **[P0] 渲染冒烟闸未做**(`AiSmokeRunner` 仅 HTTP 探针,playwright-render 无执行代码)= design fix#6 唯一补偿控制 |
|
||||||
|
| ①元数据 | `MetaController.createEntity` + 动态 CREATE + 缓存失效 | 🟡 | 引擎不能 ALTER;L2 建模器 UI 无;仍克隆 `SYS_USERGROUP` 做载体 |
|
||||||
|
| ②表结构 | `createTableDdl`(控制器内联) | 🟡 | ALTER 缺口;DDL 类型映射双份真相(与引擎漂移险) |
|
||||||
|
| ③设计 | recipe/blueprint 编译器(2 recipe)生成 amis 页;DesignerPage 改存量(分流后存量页可存 overlay) | 🟡 | DesignerPage 打不开(serving/env);net-new 正规写端点缺(走 AI 旁路);onEvent 声明式面板未做;recipe 仅 2 |
|
||||||
|
| ④实现功能 | `AiFeatureDraftGenerator` 用保真层 `DefaultFlowHelper` 生成默认 5 服务流 | 🟡 | 无人工编排 UI;只默认流;无服务流语义级 gate |
|
||||||
|
| ⑤发布 | deployment-package + CLI release ops + feature-package/revision 快照 | 🟡 | online apply 断档(人工跑 SQL);菜单注册未串端到端;**净新标准行无删除/回滚路径** |
|
||||||
|
| 横向·CLI | `Eip4Cli`(env/ai/release ops) | 🟡 | feature-package 为单元的 scaffold→dev→verify→release 生命周期未成型 |
|
||||||
|
| 横向·安全 | admin 门 + localhost 门 | 🟡 | `check()` 身份/scope 未织入写路径(等 CLI 身份模型) |
|
||||||
|
| 横向·UI 底座(组件 L1) | — | 🔴 | **[P0] L1 主题 token 未起步**(design §6 P0 锁定前置,D2);repo 无 token 资产 |
|
||||||
|
|
||||||
|
## 2. 有序里程碑
|
||||||
|
|
||||||
|
### 前置地基(design 锁定 P0,先于一切设计中心-facing 工作)
|
||||||
|
- **M0 组件设计体系 L1 主题 token 生产级**[自主 build / 需 env 终验观感]:落 `组件设计体系-design` L1 主题层。D2 锁定前置 + 设计中心/设计器观感底座。**M3b/M5 必须在 M0 后**。
|
||||||
|
- **M-Gate 正确性门禁第二闸(渲染冒烟)**[harness 自主 / 需 headless 终验]:Playwright/headless 对 previewUrl 真渲染断言(可视 + 无控制台报错),替 `AiSmokeRunner` HTTP 探针。design fix#6 唯一补偿控制——**必须先于任何真库 dogfood(M2)**。
|
||||||
|
|
||||||
|
### 先宽度(让 2 recipe + 设计器对存量 真端到端可用)
|
||||||
|
- **M1 Serving 解锁(A10)**[配置部分自主 / 终验需 env]:(a) 修 stale vite 代理死端口 8084 + `safeLocalBase` 默认(可自主改配置);(b) 前端(含设计器)被真正托管 → DesignerPage 能打开(终验需 env)。先消 design §7 已定位的环境性根因。
|
||||||
|
- **M3a net-new 写路径收口(单一写真相)**[自主 + TDD]:把 `AiLocalReleaseExecutor:158` 裸 `INSERT sys_page_schema` 改为调用**唯一共享写函数**(复用 typed 校验/审计/etag);`PageSchemaController` 加标准层写端点复用同一函数。**验收 = sys_page_schema 写入只剩一个函数,无旁路裸 INSERT**。**收口先于新建入口**。
|
||||||
|
- **M2 真库 dogfood(沙箱 schema)**[需 env + admin creds]:AI 产 EIP4AI_净新 CRUD → 过三闸(**含 M-Gate 渲染冒烟**)→ **写一次性/沙箱 schema(非共享生产 PG)** → 浏览器打开可用;附净新行清理/回滚脚本。**前置 = M-Gate + M3a**。
|
||||||
|
- **M3b 设计中心「新建功能」入口**[前端,gated by M0 + M3a]:`DesignCenterPage` 加新建入口,走 M3a 共享写函数;设计角色细分(复用 RBAC)。
|
||||||
|
- → **宽度闭环**「建实体→生成默认页→设计器微调→发布」可演示(前置 M0/M-Gate/M1/M3a 全绿)。
|
||||||
|
|
||||||
|
### 再深度
|
||||||
|
- **M4 引擎 ALTER 安全通道 + DDL 单源**[自主 build / 需 env 终验]:保真层白名单化 `alterTableSql`(只加列/扩长/改可空,改删走升级窗口)+ `MetaController` alter 端点 + 独立安全门;顺带把 `createTableDdl` 的第二份 DDL 类型映射收敛回引擎单源(消漂移)。
|
||||||
|
- **M5 onEvent 声明式面板(逻辑 b 主干第一块·design P3 硬骨头)**[前端,gated by M0]:32 facade 动词配置面板。**风险储备**:design 标的最高不确定环(S3 自动化率 <80% 触发工期重估);**20% 复杂逻辑保留「人工作业单」兜底**(design fix#3),不进面板。
|
||||||
|
- **M7 recipe 扩面**[自主 + TDD]:主子表/EditGrid/审批/组合 tabs recipe + 字段控件补 select/picker/input-tree/引用列(每种自带逐字节对拍基准)。
|
||||||
|
- **M8 CLI NocoBase 化 + 安全 Part2**[design + code 自主]:feature-package 为单元 scaffold→dev→verify→release 生命周期(D6);「认证用户→AI employee→scope」映射 + `check()` 织入写路径。
|
||||||
|
|
||||||
|
## 3. 自主 vs 需环境(build 完成 ≠ 集成已证)
|
||||||
|
|
||||||
|
| 里程碑 | 可自主 build + unit-test | 需 env/creds 终验 |
|
||||||
|
|---|---|---|
|
||||||
|
| M0 L1 token | 定义 token 层 | 生产级观感(浏览器) |
|
||||||
|
| M-Gate 渲染冒烟 | Playwright harness 代码 | 真渲染断言(headless) |
|
||||||
|
| M1 serving | 改 vite/8084 配置 | 托管 + 打开终验 |
|
||||||
|
| M3a 收口 | 共享写函数 + 端点 + TDD | —(纯写路径,集成在 M2 证) |
|
||||||
|
| M2 dogfood | — | 端到端(沙箱 PG + admin) |
|
||||||
|
| M3b 新建入口 | 端点接线 | 浏览器新建终验 |
|
||||||
|
| M4 ALTER | alterSql + 端点 + TDD | 真 PG 在线加列证 |
|
||||||
|
| M5 面板 | 面板代码 | 浏览器联动证 |
|
||||||
|
| M7 recipe | 编译器 + 对拍 TDD | 渲染证 |
|
||||||
|
| M8 CLI/Part2 | 命令 + 身份映射 + TDD | 端到端证 |
|
||||||
|
|
||||||
|
> **纪律**:M3a/M4/M7 的「完成」= **code-complete, integration-pending**;集成声明等 env 终验,不在绿单测上宣称端到端 done。
|
||||||
|
|
||||||
|
## 4. 下一步(已定,honest)
|
||||||
|
|
||||||
|
**M3a — net-new 写路径收口为单一写真相**(自主 + TDD,不依赖 env,不碰 L1-gated UI,收口 critic 点名的三真相旁路纪律)。其「完成」严格限 **code-complete**;端到端宽度价值待 M0/M-Gate/M1/M2 解锁后证。
|
||||||
|
**M0(L1)与 M1(serving 配置)可并行起**(L1 是 D2 锁定前置);M2/M3b/M5 的浏览器/真库终验等用户给登录方式。
|
||||||
|
|
||||||
|
## 5. Housekeeping
|
||||||
|
- 本文 + design doc(补 D6/D7)commit 进 main。
|
||||||
|
- main 现领先 origin/main 20 提交(AI 合并 + 3 收口),**push = 用户决策**(两仓需先 add remote / git.latent.chat,见 memory `eip3-git-remotes-latentchat`)。
|
||||||
|
- worktree `eip4-platform-ai-agent` 已与 main 同 commit,可清理。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*本文为活的执行计划;状态随里程碑落地回写。方向/决策权威见配套 design doc。*
|
||||||
99
docs/plans/2026-06-20-人走五环建新功能-NocoBase式-design.md
Normal file
99
docs/plans/2026-06-20-人走五环建新功能-NocoBase式-design.md
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
# 人走五环建新功能 · NocoBase 式(建模器 + 实时设计器)· 设计
|
||||||
|
|
||||||
|
> 日期 2026-06-20 | brainstorm 产物 | 配套《2026-06-19-EIP4开发平台-架构方向-design.md》(方向 D1-D7)+《2026-06-19-EIP4开发平台-落地执行路线图.md》(里程碑 M0-M8)。
|
||||||
|
> 决策来源:memory `eip4-human-five-ring-wizard`(宽度 vs 深度 → 选 B:人走五环建新功能,AI 退回加速器)。
|
||||||
|
> 本文是该特性的设计定型,供新会话直接跑 `superpowers:writing-plans` 出实施计划。
|
||||||
|
|
||||||
|
## 0. 一句话
|
||||||
|
|
||||||
|
给老引擎本来就有的「元数据驱动低代码核」配一套 **NocoBase 式的现代 UI(建模器 + 实时设计器),不做线性问卷向导**;让人能走完整五环(元数据→设计→实现→发布)建新功能,AI 作为加速器、不是唯一通道。
|
||||||
|
|
||||||
|
## 1. 锁定的决策(带依据)
|
||||||
|
|
||||||
|
- **D-A 形态 = 建模器 + 实时设计器,不做线性 wizard。** 依据:用户指定参考 NocoBase,NocoBase 用「实时所见即所得区块设计器 + 一键切使用/配置模式」,明确**不用向导**;且我们今天刚把 DesignerPage(amis-editor)修到全闭环,与之天然契合。
|
||||||
|
- **D-B v1 只「建新功能」,不「改已有表」。** 依据:CREATE 建表后端已 live 验证(见 §3);唯一缺口是 ALTER(改已有表的列)= 路线图 M4,留给 v2。
|
||||||
|
- **D-C 建完实体走「recipe 自动产默认页 → 进设计器微调」,不走「空白页现拖组件绑实体」。** 依据:`PageBlueprintCompiler.compile()` 吃 blueprint 直接产出**已接好 `/api/flow/{TABLE}_SEARCH` 的页**(`PageBlueprintCompiler.java:50`);DesignerPage 现为 **edit-only**(只改存量页),recipe 预接好页正好落在它能干的范围内,**设计器无需长「从零绑实体」的新能力**。
|
||||||
|
- **D-D「AI 帮我」走 ①面(外部 agent + Skills + CLI 驱动确定性工具),不在平台内置生成 LLM。** 依据:见 §3——平台主路径零 LLM,NocoBase 的「建功能 AI」本身就是外部 coding-agent CLI + Skills;EIP4 已建好这套底座(`docs/skills/` + `platform-cli` + `AiToolRegistry` + `AiEmployee`)。②面(in-app AI employees,平台内置 LLM)= v1 之后单独立项。
|
||||||
|
- **D-E 元数据单一真相 = `SYS_ENTITY` + `SYS_ENTITYATTRIBUTE`(老系统保真层),新旧共用。** 见 §3。
|
||||||
|
|
||||||
|
## 2. 整体形态 + 建功能流程
|
||||||
|
|
||||||
|
**两个界面(落在设计中心):**
|
||||||
|
1. **建模器**(新建的唯一无对应 UI 的环)— 建/浏览实体 + 字段,包 `POST /api/meta/entity`。
|
||||||
|
2. **实时设计器**(DesignerPage / amis-editor,已有,edit-only)— 微调页面。
|
||||||
|
|
||||||
|
**建一个新功能的流:**
|
||||||
|
|
||||||
|
```
|
||||||
|
①建模器建实体+字段
|
||||||
|
→ POST /api/meta/entity(写 SYS_ENTITY/SYS_ENTITYATTRIBUTE + 真 CREATE 物理表)
|
||||||
|
②选 recipe(维护CRUD / 树CRUD)
|
||||||
|
→ PageBlueprintCompiler 自动产出已接 /api/flow 的默认页 → 落 sys_page_schema(标准层)
|
||||||
|
③默认页进 DesignerPage 微调(拖列/调布局)
|
||||||
|
④选菜单位置 + 发布(PageSchemaWriter 单一写真相 + 菜单注册)
|
||||||
|
(五流 _ADD/_UPDATE/_SEARCH/_DELETE/_LOAD 由 DefaultFlowHelper 默认生成,可见可确认,多数不用人管)
|
||||||
|
```
|
||||||
|
|
||||||
|
**设计中心两入口(人/AI 共用同一套后端 + 同一份 schema):**
|
||||||
|
- **`[+ 新建功能]`**(人):自己在建模器 + 设计器里走五环。
|
||||||
|
- **`[⚡ AI 建功能]`**(AI ①面):触发外部 agent + 现有 skills/CLI 链(`POST /api/ai/features/auto-develop`),产 `READY_FOR_HUMAN_REVIEW` 草稿,人回设计器审/改/发。
|
||||||
|
|
||||||
|
## 3. 关键架构事实(brainstorm 核实,几条反直觉的)
|
||||||
|
|
||||||
|
1. **元数据单一真相、新旧共用。** `MetaController.createEntity` 把实体行写进 **`SYS_ENTITY`**(`:89`,克隆 SYS_USERGROUP 的实体描述行做模板载体)、字段行写进 **`SYS_ENTITYATTRIBUTE`**(`:246`)。这两张表 + 引擎在 `platform-legacy-core`,包名 `com.dsasp.server.common.dataDic.service`——**老系统保真层原物**。eip3 老系统本身就是元数据驱动低代码平台;「转换」只动页面层(XML/engineclass → amis `sys_page_schema`),元数据一行没转。
|
||||||
|
2. **CREATE 建表后端已 live。** `createEntity` 走 `createTableDdl()` 拼真 DDL → `dataDicService.executeCreateSql(ddl)` 真执行(`MetaController.java:130-131`),补索引、失效缓存。AI agent 建新表就走这条。**唯一缺口是 ALTER**(改已有表)= M4。
|
||||||
|
3. **平台主路径零 LLM。** `AiFeatureRequest` 完全结构化(`featureName/tableName/entityName/List<AiFeatureField> fields/pageRecipe`),连 `auto-develop` 吃的都是它,不是自然语言。`AiFeatureDraftGenerator` 按规则确定性编译。**平台内唯一 LLM = `HttpAiLlmRepairClient`,`@ConditionalOnProperty(...repair.enabled,"true")` 默认关,且只做修复不做生成。** NL→结构化 spec 的魔法在平台外(外部 coding-agent 经 CLI)。
|
||||||
|
4. **NocoBase 的「建功能 AI」= 外部 agent CLI + Skills。** NocoBase Skills 官方定义 =「给 AI Agent CLI(Claude Code、Codex、Cursor 等)用的可复用领域知识包」,外部加载、非服务端组件,agent 经 CLI/API 在权限+审计下驱动 no-code 操作。EIP4 已有对应底座。NocoBase 另有 in-platform「AI Employees」(业务用户在 App 内对话,内置 LLM)= 我们的 ②面,v1 不做。
|
||||||
|
5. **recipe 编译器吃 blueprint 产已接 API 的页。** `PageBlueprintCompiler.compile()` 设 `crud.api=/api/flow/{TABLE}_SEARCH`、列、增删改按钮(`:45-72`);`AiFeatureDraftGenerator` 已串了这条(`:47-52`)。
|
||||||
|
|
||||||
|
## 4. 真正要新建 vs 复用(端点均已核实)
|
||||||
|
|
||||||
|
**复用(端点/能力都已 live):**
|
||||||
|
|
||||||
|
| 环 | 复用 |
|
||||||
|
|---|---|
|
||||||
|
| 建实体+建表 | `POST /api/meta/entity` |
|
||||||
|
| 标准层页写 | `PUT /api/page/schema/{templateId}/standard`(M3a 单一真相)|
|
||||||
|
| 设计器存改+门禁 | `/api/page/schema/{templateId}/overlay` + `/validate` + `/components` |
|
||||||
|
| recipe 列表 | `GET /api/ai/page-recipes` |
|
||||||
|
| 菜单注册 | `POST /api/admin/menus/create` |
|
||||||
|
| 微调页面 | DesignerPage(amis-editor) |
|
||||||
|
| AI 建功能链(①面) | `POST /api/ai/features/auto-develop`(基址 `/api/ai`)|
|
||||||
|
| CRUD/flow 自动伺服 | 保真层引擎 |
|
||||||
|
|
||||||
|
**真正要新建(4 件):**
|
||||||
|
1. **建模器 UI(前端,最大块)**:列已有实体 / 建新实体(名/表)+ 字段表(列/类型/显示名/长度/必填/引用其它实体)。包 `POST /api/meta/entity`。最复杂控件 = **引用列(referenceid,外键选其它实体)**。
|
||||||
|
2. **「recipe→默认页→落标准层」单步端点(后端,小)**:把 `PageBlueprintCompiler.compile` + `/standard` 写串成人可单步调的端点(现在只埋在 `auto-develop` 里)。属路线图「把 AI pipeline 拆成可单步调」收口的第一块。
|
||||||
|
3. **「+ 新建功能」编排薄壳(前端)**:建模器→选 recipe→落页→跳设计器→发布(菜单注册)串起来。
|
||||||
|
4. **「⚡ AI 建功能」入口接线(前端 + 少量后端)**:网页触发 `auto-develop`,把 `READY_FOR_HUMAN_REVIEW` 草稿回流到设计器供人审/改/发。
|
||||||
|
|
||||||
|
## 5. v1 边界(YAGNI)
|
||||||
|
|
||||||
|
- 只建新,**不改已有表**(ALTER/M4 = v2)。
|
||||||
|
- recipe 限现有 2 种(维护 CRUD / 树 CRUD)→ **v1 只覆盖简单 CRUD/树类功能**;主子表/审批/组合 = 路线图 M7 扩面后。
|
||||||
|
- 设计器 **edit-only** 够用(recipe 预接好页)。
|
||||||
|
- **②面 in-app AI employees 不做**(平台内置 LLM = 独立大特性 + 红线扩面,v1 之后立项)。
|
||||||
|
|
||||||
|
## 6. 守红线(与架构 D3 + memory `eip4-ai-agent-merge-mapping` 一致)
|
||||||
|
|
||||||
|
- 发布**恒人审**。
|
||||||
|
- AI 入口产物状态**恒 `READY_FOR_HUMAN_REVIEW`**。
|
||||||
|
- 标准层写**恒走 `PageSchemaWriter` 单一真相**(M3a 已收口,不得旁路裸 INSERT)。
|
||||||
|
- 平台进程内**不内置生成 LLM**(仅 repair 钩子,默认关)。
|
||||||
|
|
||||||
|
## 7. 要在 plan 里钉死的 3 个未知
|
||||||
|
|
||||||
|
1. **建模器引用列(外键)UI**:怎么选其它实体?下拉已有实体列表 + 选目标显示列?这是建模器最复杂的控件,需先定交互。
|
||||||
|
2. **recipe 仅 2 种 = v1 能建的功能类型窄**:这是 v1 定位,需跟产品对齐——v1 明确只支持简单 CRUD/树类新功能,复杂功能引导走老路或等 M7。
|
||||||
|
3. **发布 online apply 断档**(路线图:线上仍人工跑 SQL):v1「发布」到哪一步算完?**真上线** vs **出部署包人工执行**?决定 ④环的终点与是否需要 env/creds 终验。
|
||||||
|
|
||||||
|
## 8. 不做 / 推迟
|
||||||
|
|
||||||
|
- ALTER/改已有表(M4,v2)
|
||||||
|
- recipe 扩面:主子表/EditGrid/审批/组合 tabs(M7)
|
||||||
|
- ②面 in-app AI employees / 平台内置 LLM 生成端点
|
||||||
|
- 纯 NocoBase「空白页拖组件现绑实体」(需给 amis-editor 造绑定能力,v1 用 recipe 预接好规避)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*本文为 brainstorm 定型设计。下一步:新会话跑 `superpowers:writing-plans` 出带文件路径/代码示例/验证步骤的实施计划,§7 三未知在 plan 阶段钉死。*
|
||||||
5650
docs/plans/2026-06-20-人走五环建新功能-实施计划.md
Normal file
5650
docs/plans/2026-06-20-人走五环建新功能-实施计划.md
Normal file
File diff suppressed because it is too large
Load Diff
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,422 @@
|
|||||||
|
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";
|
||||||
|
}
|
||||||
|
// 与 PageBlueprintCompiler.maintenanceCrud 的 house-style 对齐:列表走保真层 _SEARCH 服务流。
|
||||||
|
return "/api/flow/" + spec.tableName() + "_SEARCH";
|
||||||
|
}
|
||||||
|
|
||||||
|
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,346 @@
|
|||||||
|
package com.eip4.platform.ai.service;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Comparator;
|
||||||
|
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.eip4.platform.metadata.schema.PageSchemaWriter;
|
||||||
|
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;
|
||||||
|
private final PageSchemaWriter pageSchemaWriter;
|
||||||
|
|
||||||
|
public AiLocalReleaseExecutor(JdbcTemplate jdbcTemplate, AiSmokeHttpClient httpClient, ObjectMapper objectMapper) {
|
||||||
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
|
this.httpClient = httpClient;
|
||||||
|
this.objectMapper = objectMapper;
|
||||||
|
// M3a 收口:标准层页面 schema 写统一走 PageSchemaWriter(与设计中心新建端点共用单一写真相)
|
||||||
|
this.pageSchemaWriter = new PageSchemaWriter(jdbcTemplate);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
// M3a 收口:不再裸 INSERT sys_page_schema;走 PageSchemaWriter 唯一写真相(typed 校验告警 + etag + UPSERT)
|
||||||
|
String schemaJson = objectMapper.writeValueAsString(draft.payload());
|
||||||
|
String name = draft.payload().path("title").asText(draft.targetId());
|
||||||
|
String etag = pageSchemaWriter.upsertStandard(draft.targetId(), name, schemaJson, "AI_AGENT");
|
||||||
|
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 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,280 @@
|
|||||||
|
package com.eip4.platform.ai.web;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
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 org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import com.dsasp.server.common.user.service.LoggedInUser;
|
||||||
|
import com.dsasp.server.common.util.UserSession;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 变更/动作类端点要求管理员,与 {@code PageSchemaController.requireAdmin} /
|
||||||
|
* {@code AdminWriteController.requireAdmin} 对齐:AI 开发工具的变更入口(建任务/草稿/
|
||||||
|
* 变更包/本地落库/部署包/修复执行)会写 sys_ai_* 与触发三真相落库,不能让任意已登录
|
||||||
|
* 用户触发。读类(各 GET)与纯校验/判定端点(validate-schema / access-check)不门控。
|
||||||
|
*
|
||||||
|
* <p>判定口径:{@code UserSession.CURRENTUSER == "ADMIN"}(JWT 过滤器按 token 注入)。
|
||||||
|
* prod 链 /api/** 已 authenticated,本门把 AI 变更入口进一步收敛到管理员,消除「同级写
|
||||||
|
* 端点要 admin、AI 写端点只要登录」的鉴权档位差。
|
||||||
|
*/
|
||||||
|
private static void requireAdmin() {
|
||||||
|
java.util.Properties ctx = UserSession.get();
|
||||||
|
String cu = ctx == null ? "" : ctx.getProperty(LoggedInUser.CURRENTUSER, "").trim();
|
||||||
|
if (!"ADMIN".equalsIgnoreCase(cu)) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "AI 开发工具变更入口仅管理员可用");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "创建 Agent 开发任务", description = "只创建受控任务和初始计划,不执行线上变更")
|
||||||
|
@PostMapping("/tasks")
|
||||||
|
public AiTask createTask(@RequestBody CreateTaskRequest req) {
|
||||||
|
requireAdmin();
|
||||||
|
return service.createTask(req.objective());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "AI 辅助生成功能草稿", description = "创建任务并生成实体/页面/服务流/菜单/测试草稿,门禁通过后生成待人审变更包(草稿仍需人工复核)")
|
||||||
|
@PostMapping("/features/develop")
|
||||||
|
public AiFeatureDevelopment developFeature(@RequestBody AiFeatureRequest req) {
|
||||||
|
requireAdmin();
|
||||||
|
return service.developFeature(req);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "AI 辅助一键生成功能(本地验证 + 待人工复核发布)", description = "生成草稿、变更包、发布计划,执行本地落库和 smoke,并生成线上人工部署包;不连接线上执行,线上变更须人工复核发布")
|
||||||
|
@PostMapping("/features/auto-develop")
|
||||||
|
public AiAutoDevelopmentRun autoDevelopFeature(@RequestBody(required = false) AiAutoDevelopmentRequest req) {
|
||||||
|
requireAdmin();
|
||||||
|
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) {
|
||||||
|
requireAdmin();
|
||||||
|
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 = "在既有任务下 AI 辅助生成功能草稿")
|
||||||
|
@PostMapping("/tasks/{taskId}/develop-feature")
|
||||||
|
public AiFeatureDevelopment developFeature(@PathVariable String taskId, @RequestBody AiFeatureRequest req) {
|
||||||
|
requireAdmin();
|
||||||
|
return service.developFeature(taskId, req);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "生成待人审变更包", description = "任何草稿门禁失败时拒绝生成")
|
||||||
|
@PostMapping("/tasks/{taskId}/change-sets")
|
||||||
|
public AiChangeSet createChangeSet(@PathVariable String taskId) {
|
||||||
|
requireAdmin();
|
||||||
|
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) {
|
||||||
|
requireAdmin();
|
||||||
|
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) {
|
||||||
|
requireAdmin();
|
||||||
|
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) {
|
||||||
|
requireAdmin();
|
||||||
|
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) {
|
||||||
|
requireAdmin();
|
||||||
|
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) {
|
||||||
|
requireAdmin();
|
||||||
|
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) {
|
||||||
|
requireAdmin();
|
||||||
|
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) {
|
||||||
|
requireAdmin();
|
||||||
|
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) {
|
||||||
|
requireAdmin();
|
||||||
|
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: master-detail-v1
|
||||||
|
title: EIP4 master-detail page
|
||||||
|
purpose: 主子表实体维护页,覆盖主表列表、含内联子表的新增/编辑、删除;子表为 amis input-table。
|
||||||
|
compiler: com.eip4.platform.metadata.schema.blueprint.PageBlueprintCompiler
|
||||||
|
requirements:
|
||||||
|
childTable: 子表表名(普通实体 tabletype=1,含指向主表的引用列)
|
||||||
|
listColumn: 主表 LIST 属性列名(amis input-table 的 name,如 DETAILS)
|
||||||
|
childFields: 子表可编辑列(非空)
|
||||||
|
amis:
|
||||||
|
rootType: page
|
||||||
|
body:
|
||||||
|
type: crud
|
||||||
|
syncLocation: false
|
||||||
|
apiPattern: /api/flow/{tableName}_SEARCH
|
||||||
|
headerToolbar:
|
||||||
|
- addButton:
|
||||||
|
label: 新增
|
||||||
|
level: primary
|
||||||
|
icon: fa fa-plus
|
||||||
|
actionType: dialog
|
||||||
|
formApiPattern: post:/api/flow/{tableName}_ADD
|
||||||
|
child:
|
||||||
|
type: input-table
|
||||||
|
namePattern: "{listColumn}"
|
||||||
|
addable: true
|
||||||
|
removable: true
|
||||||
|
needConfirm: false
|
||||||
|
staticOn: ${__readonly}
|
||||||
|
- editButton:
|
||||||
|
label: 编辑
|
||||||
|
level: primary
|
||||||
|
actionType: dialog
|
||||||
|
disabledOn: ${!selectedItems || selectedItems.length === 0}
|
||||||
|
initApiPattern: post:/api/flow/{tableName}_LOAD
|
||||||
|
formApiPattern: post:/api/flow/{tableName}_UPDATE
|
||||||
|
child:
|
||||||
|
type: input-table
|
||||||
|
namePattern: "{listColumn}"
|
||||||
|
- deleteButton:
|
||||||
|
label: 删除
|
||||||
|
level: danger
|
||||||
|
actionType: ajax
|
||||||
|
confirmText: 确认要删除此记录吗?
|
||||||
|
apiPattern: /api/flow/{tableName}_DELETE
|
||||||
|
- pagination
|
||||||
|
footerToolbar:
|
||||||
|
- statistics
|
||||||
|
- pagination
|
||||||
|
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/flow/EIP4AI_TEST_SEARCH",
|
||||||
|
"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,138 @@
|
|||||||
|
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.AfterEach;
|
||||||
|
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();
|
||||||
|
// AI 变更端点要求管理员
|
||||||
|
setAdminSession();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() {
|
||||||
|
clearSession();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void setAdminSession() {
|
||||||
|
java.util.Properties p = new java.util.Properties();
|
||||||
|
p.setProperty(com.dsasp.server.common.user.service.LoggedInUser.CURRENTUSER, "ADMIN");
|
||||||
|
com.dsasp.server.common.util.UserSession.set(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void clearSession() {
|
||||||
|
com.dsasp.server.common.util.UserSession.set(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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,358 @@
|
|||||||
|
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.AfterEach;
|
||||||
|
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();
|
||||||
|
// AI 变更端点要求管理员;既有用例默认以 ADMIN 上下文运行
|
||||||
|
setAdminSession();
|
||||||
|
}
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() {
|
||||||
|
clearSession();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void setAdminSession() {
|
||||||
|
java.util.Properties p = new java.util.Properties();
|
||||||
|
p.setProperty(com.dsasp.server.common.user.service.LoggedInUser.CURRENTUSER, "ADMIN");
|
||||||
|
com.dsasp.server.common.util.UserSession.set(p);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void clearSession() {
|
||||||
|
com.dsasp.server.common.util.UserSession.set(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
@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 非管理员调用AI变更端点返回403() throws Exception {
|
||||||
|
clearSession(); // 覆盖 setUp 的 ADMIN 上下文 → 非管理员
|
||||||
|
|
||||||
|
mvc.perform(post("/api/ai/features/auto-develop")
|
||||||
|
.contentType("application/json")
|
||||||
|
.content("{}"))
|
||||||
|
.andExpect(status().isForbidden());
|
||||||
|
}
|
||||||
|
|
||||||
|
@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) {
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -0,0 +1,197 @@
|
|||||||
|
package com.eip4.platform.metadata.flow;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.MathContext;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 极小安全算术求值器——recipe 派生字段服务端 compute-on-save 专用(如 金额=数量×单价)。
|
||||||
|
*
|
||||||
|
* <p>只支持 {@code + - * / ( )}、数字字面量、列名(标识符,从当前行 map 解析)。<b>无任意代码执行</b>
|
||||||
|
* (不走 Groovy/JS/EL 引擎,杜绝注入面),故公式来源即便最终来自设计者输入也安全。递归下降解析,
|
||||||
|
* BigDecimal 计算(金额场景精度安全)。
|
||||||
|
*
|
||||||
|
* <p>取值约定:列名 → 行 map 同名值,{@code null}/空白当 {@code 0}(缺失操作数=0,合理);
|
||||||
|
* 数字(Number)精确转 BigDecimal;非空非数字字符串 → 抛 {@link NumberFormatException}
|
||||||
|
* (交由调用方逐行兜底跳过,绝不静默写错值)。除零、畸形表达式均抛异常。
|
||||||
|
*/
|
||||||
|
public final class RecipeArithmeticEvaluator {
|
||||||
|
|
||||||
|
private static final MathContext MC = MathContext.DECIMAL64;
|
||||||
|
/** 表达式长度上限:防超长合法表达式 × 大子表逐行求值的 CPU 放大 DoS。 */
|
||||||
|
private static final int MAX_EXPR_LEN = 512;
|
||||||
|
/** 递归嵌套深度上限:防深嵌套括号/连续一元符触发 StackOverflowError(Error 会逃过逐行兜底→500 DoS)。 */
|
||||||
|
private static final int MAX_DEPTH = 64;
|
||||||
|
|
||||||
|
/** 求值 {@code expr},列名从 {@code row} 解析。空/超长/畸形/嵌套过深/除零/非数字操作数 → 抛运行时异常。 */
|
||||||
|
public BigDecimal eval(String expr, Map<String, Object> row) {
|
||||||
|
if (expr == null || expr.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("空表达式");
|
||||||
|
}
|
||||||
|
if (expr.length() > MAX_EXPR_LEN) {
|
||||||
|
throw new IllegalArgumentException("表达式过长(>" + MAX_EXPR_LEN + ")");
|
||||||
|
}
|
||||||
|
Parser p = new Parser(expr, row == null ? Map.of() : row);
|
||||||
|
BigDecimal result = p.parseExpression();
|
||||||
|
p.expectEnd();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 递归下降:expression = term (('+'|'-') term)* ; term = factor (('*'|'/') factor)* 。 */
|
||||||
|
private static final class Parser {
|
||||||
|
private final String s;
|
||||||
|
private final Map<String, Object> row;
|
||||||
|
private int pos;
|
||||||
|
private int depth;
|
||||||
|
|
||||||
|
Parser(String s, Map<String, Object> row) {
|
||||||
|
this.s = s;
|
||||||
|
this.row = row;
|
||||||
|
}
|
||||||
|
|
||||||
|
BigDecimal parseExpression() {
|
||||||
|
BigDecimal v = parseTerm();
|
||||||
|
while (true) {
|
||||||
|
char op = peekOp();
|
||||||
|
if (op == '+') {
|
||||||
|
pos++;
|
||||||
|
v = v.add(parseTerm(), MC);
|
||||||
|
} else if (op == '-') {
|
||||||
|
pos++;
|
||||||
|
v = v.subtract(parseTerm(), MC);
|
||||||
|
} else {
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BigDecimal parseTerm() {
|
||||||
|
BigDecimal v = parseFactor();
|
||||||
|
while (true) {
|
||||||
|
char op = peekOp();
|
||||||
|
if (op == '*') {
|
||||||
|
pos++;
|
||||||
|
v = v.multiply(parseFactor(), MC);
|
||||||
|
} else if (op == '/') {
|
||||||
|
pos++;
|
||||||
|
BigDecimal d = parseFactor();
|
||||||
|
if (d.signum() == 0) {
|
||||||
|
throw new ArithmeticException("除零");
|
||||||
|
}
|
||||||
|
v = v.divide(d, 10, RoundingMode.HALF_UP).stripTrailingZeros();
|
||||||
|
} else {
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BigDecimal parseFactor() {
|
||||||
|
// 嵌套深度护栏:递增进、try/finally 递出,反映当前栈深而非总调用数;超限抛 RuntimeException
|
||||||
|
// (会被 RecipeDerivedFieldComputer 逐行兜底吞掉),避免 StackOverflowError(Error)逃过兜底致 500。
|
||||||
|
if (++depth > MAX_DEPTH) {
|
||||||
|
throw new IllegalArgumentException("表达式嵌套过深(>" + MAX_DEPTH + ")");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
skipWs();
|
||||||
|
if (pos >= s.length()) {
|
||||||
|
throw new IllegalArgumentException("表达式提前结束: " + s);
|
||||||
|
}
|
||||||
|
char c = s.charAt(pos);
|
||||||
|
if (c == '-') {
|
||||||
|
pos++;
|
||||||
|
return parseFactor().negate();
|
||||||
|
}
|
||||||
|
if (c == '+') {
|
||||||
|
pos++;
|
||||||
|
return parseFactor();
|
||||||
|
}
|
||||||
|
if (c == '(') {
|
||||||
|
pos++;
|
||||||
|
BigDecimal v = parseExpression();
|
||||||
|
skipWs();
|
||||||
|
if (pos >= s.length() || s.charAt(pos) != ')') {
|
||||||
|
throw new IllegalArgumentException("缺右括号: " + s);
|
||||||
|
}
|
||||||
|
pos++;
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
if (c == '.' || Character.isDigit(c)) {
|
||||||
|
return parseNumber();
|
||||||
|
}
|
||||||
|
if (Character.isLetter(c) || c == '_') {
|
||||||
|
return resolve(parseIdentifier());
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("非法字符 '" + c + "' @ " + pos + " in " + s);
|
||||||
|
} finally {
|
||||||
|
depth--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BigDecimal parseNumber() {
|
||||||
|
int start = pos;
|
||||||
|
while (pos < s.length() && (Character.isDigit(s.charAt(pos)) || s.charAt(pos) == '.')) {
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
return new BigDecimal(s.substring(start, pos));
|
||||||
|
}
|
||||||
|
|
||||||
|
private String parseIdentifier() {
|
||||||
|
int start = pos;
|
||||||
|
while (pos < s.length()
|
||||||
|
&& (Character.isLetterOrDigit(s.charAt(pos)) || s.charAt(pos) == '_')) {
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
return s.substring(start, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 列名 → 行值 → BigDecimal。null/空白当 0;Number 精确;非空非数字字符串抛 NumberFormatException。 */
|
||||||
|
private BigDecimal resolve(String name) {
|
||||||
|
Object v = row.get(name);
|
||||||
|
if (v == null) {
|
||||||
|
// 大小写兜底(保真层有时回大写键)。
|
||||||
|
for (Map.Entry<String, Object> e : row.entrySet()) {
|
||||||
|
if (name.equalsIgnoreCase(e.getKey())) {
|
||||||
|
v = e.getValue();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (v == null) {
|
||||||
|
return BigDecimal.ZERO;
|
||||||
|
}
|
||||||
|
if (v instanceof BigDecimal bd) {
|
||||||
|
return bd;
|
||||||
|
}
|
||||||
|
if (v instanceof Number n) {
|
||||||
|
return new BigDecimal(n.toString());
|
||||||
|
}
|
||||||
|
String str = v.toString().trim();
|
||||||
|
if (str.isEmpty()) {
|
||||||
|
return BigDecimal.ZERO;
|
||||||
|
}
|
||||||
|
return new BigDecimal(str); // 非数字 → NumberFormatException,交由调用方逐行兜底
|
||||||
|
}
|
||||||
|
|
||||||
|
private char peekOp() {
|
||||||
|
skipWs();
|
||||||
|
if (pos >= s.length()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return s.charAt(pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void skipWs() {
|
||||||
|
while (pos < s.length() && Character.isWhitespace(s.charAt(pos))) {
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void expectEnd() {
|
||||||
|
skipWs();
|
||||||
|
if (pos != s.length()) {
|
||||||
|
throw new IllegalArgumentException("表达式有多余内容 @ " + pos + ": " + s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
package com.eip4.platform.metadata.flow;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.math.RoundingMode;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* recipe 主子表写流 compute-on-save:落库前对提交 map 的子表数组逐行补算派生字段
|
||||||
|
* (如 金额=数量×单价),服务端权威,绕开 amis input-table 前端 onEvent 的 React setState 竞态。
|
||||||
|
*
|
||||||
|
* <p>与 {@link EditGridDerivedFieldComputer}(迁移页·读 view_page XML 跑 Groovy)不同:本组件服务
|
||||||
|
* <b>新建 recipe 页</b>——派生公式由设计中心编译时以 {@code ?__derive=} 透传,无 view_page 依赖、无
|
||||||
|
* 存储改造。求值走 {@link RecipeArithmeticEvaluator}(纯算术、无任意代码执行)。
|
||||||
|
*
|
||||||
|
* <p>spec 格式(Spring @RequestParam 已 URL 解码):{@code "LISTCOL|TARGET1=EXPR1|TARGET2=EXPR2"}。
|
||||||
|
* 首段为子表列名(amis input-table 的 name,如 DETAILS),其后每段 {@code 目标列=公式}。同一行内
|
||||||
|
* 按声明顺序应用,后者可引用前者刚算出的结果(如 含税=金额*1.13)。
|
||||||
|
*
|
||||||
|
* <p>纪律:任一行任一列求值失败(非数字操作数/除零/畸形)只跳过该格并告警,绝不静默写错值、绝不阻断
|
||||||
|
* 保存(派生字段缺失好过保存失败)。零改 {@code com.dsasp}。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class RecipeDerivedFieldComputer {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(RecipeDerivedFieldComputer.class);
|
||||||
|
|
||||||
|
private final RecipeArithmeticEvaluator evaluator = new RecipeArithmeticEvaluator();
|
||||||
|
|
||||||
|
/** 就地为提交 map 补算 recipe 派生字段。spec 空 / 无子表数组 → 无操作。 */
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public void enrich(Map<String, Object> map, String deriveSpec) {
|
||||||
|
if (map == null || deriveSpec == null || deriveSpec.isBlank()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
String[] parts = deriveSpec.split("\\|");
|
||||||
|
if (parts.length < 2) {
|
||||||
|
return; // 无 target=expr 段
|
||||||
|
}
|
||||||
|
String listColumn = parts[0].trim();
|
||||||
|
Object listObj = caseInsensitiveGet(map, listColumn);
|
||||||
|
if (!(listObj instanceof List<?> rawRows) || rawRows.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
List<String[]> specs = new ArrayList<>();
|
||||||
|
for (int i = 1; i < parts.length; i++) {
|
||||||
|
String seg = parts[i];
|
||||||
|
int eq = seg.indexOf('=');
|
||||||
|
if (eq <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String target = seg.substring(0, eq).trim();
|
||||||
|
String expr = seg.substring(eq + 1).trim();
|
||||||
|
if (!target.isEmpty() && !expr.isEmpty()) {
|
||||||
|
specs.add(new String[] {target, expr});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (specs.isEmpty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (Object r : rawRows) {
|
||||||
|
if (!(r instanceof Map)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
Map<String, Object> rowMap = (Map<String, Object>) r;
|
||||||
|
for (String[] sp : specs) {
|
||||||
|
try {
|
||||||
|
BigDecimal val = evaluator.eval(sp[1], rowMap);
|
||||||
|
rowMap.put(sp[0], val); // 写回:后续派生列可引用本列结果
|
||||||
|
} catch (RuntimeException ex) {
|
||||||
|
log.warn("[RecipeDerived] 跳过 {}={} : {}", sp[0], sp[1], ex.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[RecipeDerived] compute-on-save 跳过 spec={}: {}", deriveSpec, e.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 父级聚合 compute-on-save:把子表某列聚合写回主 map(如 主表总额=SUM(明细.金额))。须在
|
||||||
|
* {@link #enrich}(行级派生)之后调用,使被聚合的派生列已算好。spec 格式(已 URL 解码):
|
||||||
|
* {@code "主列=AGG:子表列名:子列|..."},AGG ∈ SUM/COUNT/AVG/MIN/MAX。空子表 → SUM/COUNT=0,
|
||||||
|
* MIN/MAX/AVG 跳过不写。未知聚合/缺子表列/求值失败 → 跳过并告警,绝不阻断保存。
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public void enrichRollup(Map<String, Object> map, String rollupSpec) {
|
||||||
|
if (map == null || rollupSpec == null || rollupSpec.isBlank()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
for (String seg : rollupSpec.split("\\|")) {
|
||||||
|
int eq = seg.indexOf('=');
|
||||||
|
if (eq <= 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String target = seg.substring(0, eq).trim();
|
||||||
|
String[] parts = seg.substring(eq + 1).split(":");
|
||||||
|
if (target.isEmpty() || parts.length != 3) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
String agg = parts[0].trim().toUpperCase();
|
||||||
|
String listColumn = parts[1].trim();
|
||||||
|
String childColumn = parts[2].trim();
|
||||||
|
Object listObj = caseInsensitiveGet(map, listColumn);
|
||||||
|
if (!(listObj instanceof List<?> rawRows)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
List<BigDecimal> vals = new ArrayList<>();
|
||||||
|
for (Object r : rawRows) {
|
||||||
|
if (r instanceof Map) {
|
||||||
|
BigDecimal bd = toBigDecimal(caseInsensitiveGet((Map<String, Object>) r, childColumn));
|
||||||
|
if (bd != null) {
|
||||||
|
vals.add(bd);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BigDecimal result = aggregate(agg, vals);
|
||||||
|
if (result != null) {
|
||||||
|
map.put(target, result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("[RecipeRollup] compute-on-save 跳过 spec={}: {}", rollupSpec, e.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 对一组数值做聚合;空集时 SUM/COUNT 返 0,AVG/MIN/MAX 返 null(跳过不写);未知聚合返 null。 */
|
||||||
|
private static BigDecimal aggregate(String agg, List<BigDecimal> vals) {
|
||||||
|
switch (agg) {
|
||||||
|
case "SUM":
|
||||||
|
return vals.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||||
|
case "COUNT":
|
||||||
|
return BigDecimal.valueOf(vals.size());
|
||||||
|
case "AVG":
|
||||||
|
if (vals.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
BigDecimal sum = vals.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||||
|
return sum.divide(BigDecimal.valueOf(vals.size()), 10, RoundingMode.HALF_UP).stripTrailingZeros();
|
||||||
|
case "MIN":
|
||||||
|
return vals.stream().min(BigDecimal::compareTo).orElse(null);
|
||||||
|
case "MAX":
|
||||||
|
return vals.stream().max(BigDecimal::compareTo).orElse(null);
|
||||||
|
default:
|
||||||
|
return null; // 未知聚合 → 跳过
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 数值强转:null/空白/非数字 → null(聚合时跳过);Number/字符串数字 → BigDecimal。 */
|
||||||
|
private static BigDecimal toBigDecimal(Object v) {
|
||||||
|
if (v == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (v instanceof BigDecimal bd) {
|
||||||
|
return bd;
|
||||||
|
}
|
||||||
|
if (v instanceof Number n) {
|
||||||
|
return new BigDecimal(n.toString());
|
||||||
|
}
|
||||||
|
String s = v.toString().trim();
|
||||||
|
if (s.isEmpty()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return new BigDecimal(s);
|
||||||
|
} catch (NumberFormatException ex) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Object caseInsensitiveGet(Map<String, Object> map, String key) {
|
||||||
|
if (map.containsKey(key)) {
|
||||||
|
return map.get(key);
|
||||||
|
}
|
||||||
|
for (Map.Entry<String, Object> e : map.entrySet()) {
|
||||||
|
if (key.equalsIgnoreCase(e.getKey())) {
|
||||||
|
return e.getValue();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
package com.eip4.platform.metadata.meta;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import com.dsasp.server.common.dataDic.service.DataDicService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取某实体的列清单(类型/显示名/引用目标表)并推断显示列。
|
||||||
|
*
|
||||||
|
* <p>真实表 {@code SYS_ENTITYATTRIBUTE}(无 table_name 列,靠 {@code entityid ⋈ SYS_ENTITY} 过滤);
|
||||||
|
* 引用列(REFERENCEID 为 36 位 uuid)的目标表名经 {@link DataDicService#getReferenceEntityTableName(String)} 反解。
|
||||||
|
*
|
||||||
|
* <p>本 service 是建模器后端(MetaController.attributes)与 recipe 编译(Section 2 EntityAttributeReader)的
|
||||||
|
* 同源读取面,二者委托它保证同结果。
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class EntityAttributesService {
|
||||||
|
|
||||||
|
public record Column(String column, String display, String type, boolean mandatory, String referenceTable) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public record Result(String tablename, String displayColumn, List<Column> columns) {
|
||||||
|
}
|
||||||
|
|
||||||
|
private final DataDicService dataDicService;
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
public EntityAttributesService(DataDicService dataDicService, JdbcTemplate jdbcTemplate) {
|
||||||
|
this.dataDicService = dataDicService;
|
||||||
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 读取某表的列清单 + 推断显示列;表名大小写无关。 */
|
||||||
|
public Result read(String table) {
|
||||||
|
String t = table == null ? "" : table.toUpperCase();
|
||||||
|
List<Map<String, Object>> raw = jdbcTemplate.query(
|
||||||
|
"SELECT A.COLUMNNAME, A.DISPLAYNAME, A.REFERENCEID, A.ISMANDATORY, A.ISKEY, "
|
||||||
|
+ "A.ISENTITYDISPLAY, A.ENTITYDISPLAYSEQ "
|
||||||
|
+ "FROM SYS_ENTITYATTRIBUTE A INNER JOIN SYS_ENTITY E ON A.ENTITYID=E.SYS_ENTITY_ID "
|
||||||
|
+ "WHERE E.TABLENAME=? AND E.ISACTIVE=1 AND A.ISACTIVE=1 "
|
||||||
|
+ "ORDER BY A.ENTITYDISPLAYSEQ ASC",
|
||||||
|
(rs, i) -> {
|
||||||
|
Map<String, Object> m = new LinkedHashMap<>();
|
||||||
|
m.put("COLUMNNAME", rs.getString("COLUMNNAME"));
|
||||||
|
m.put("DISPLAYNAME", rs.getString("DISPLAYNAME"));
|
||||||
|
m.put("REFERENCEID", rs.getString("REFERENCEID"));
|
||||||
|
m.put("ISMANDATORY", rs.getInt("ISMANDATORY"));
|
||||||
|
m.put("ISKEY", rs.getInt("ISKEY"));
|
||||||
|
m.put("ISENTITYDISPLAY", rs.getInt("ISENTITYDISPLAY"));
|
||||||
|
return m;
|
||||||
|
},
|
||||||
|
t);
|
||||||
|
|
||||||
|
List<Column> columns = new ArrayList<>();
|
||||||
|
String displayByFlag = null;
|
||||||
|
String displayByString = null;
|
||||||
|
String keyColumn = null;
|
||||||
|
for (Map<String, Object> r : raw) {
|
||||||
|
String col = (String) r.get("COLUMNNAME");
|
||||||
|
String refId = (String) r.get("REFERENCEID");
|
||||||
|
boolean isKey = asInt(r.get("ISKEY")) == 1;
|
||||||
|
boolean isEntityDisplay = asInt(r.get("ISENTITYDISPLAY")) == 1;
|
||||||
|
boolean mandatory = asInt(r.get("ISMANDATORY")) == 1;
|
||||||
|
String apiType = refToApiType(refId);
|
||||||
|
String referenceTable = "reference".equals(apiType)
|
||||||
|
? dataDicService.getReferenceEntityTableName(refId) : null;
|
||||||
|
|
||||||
|
columns.add(new Column(col, (String) r.get("DISPLAYNAME"), apiType, mandatory, referenceTable));
|
||||||
|
|
||||||
|
if (isKey) {
|
||||||
|
keyColumn = col;
|
||||||
|
}
|
||||||
|
if (isEntityDisplay && displayByFlag == null) {
|
||||||
|
displayByFlag = col;
|
||||||
|
}
|
||||||
|
if (displayByString == null && !isKey && "string".equals(apiType) && !isAuditColumn(col)) {
|
||||||
|
displayByString = col;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String displayColumn = displayByFlag != null ? displayByFlag
|
||||||
|
: (displayByString != null ? displayByString : keyColumn);
|
||||||
|
return new Result(t, displayColumn, columns);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** REFERENCEID 反映射成 API 语义类型;36 位 uuid(外键引用) → reference。 */
|
||||||
|
public static String refToApiType(String referenceId) {
|
||||||
|
if (referenceId == null) {
|
||||||
|
return "string";
|
||||||
|
}
|
||||||
|
return switch (referenceId) {
|
||||||
|
case "NVARCHAR", "CODE", "CHAR" -> "string";
|
||||||
|
case "INTEGER", "ENUMERATE" -> "integer";
|
||||||
|
case "DECIMAL", "MONEY" -> "number";
|
||||||
|
case "DATE" -> "date";
|
||||||
|
case "TIME" -> "datetime";
|
||||||
|
case "BOOLEAN" -> "boolean";
|
||||||
|
default -> referenceId.length() >= 32 ? "reference" : "string";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isAuditColumn(String col) {
|
||||||
|
return "VERSION".equals(col) || "CREATETIME".equals(col) || "UPDATETIME".equals(col)
|
||||||
|
|| "CREATEBY".equals(col) || "UPDATEBY".equals(col) || "ISACTIVE".equals(col)
|
||||||
|
|| "ORGID".equals(col) || "DEPARTID".equals(col);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int asInt(Object v) {
|
||||||
|
if (v instanceof Number n) {
|
||||||
|
return n.intValue();
|
||||||
|
}
|
||||||
|
if (v != null) {
|
||||||
|
try {
|
||||||
|
return Integer.parseInt(v.toString());
|
||||||
|
} catch (NumberFormatException ignore) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
package com.eip4.platform.metadata.publish;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import org.springframework.jdbc.core.JdbcTemplate;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 默认服务流「预览/持久态」读取(建物 3 · 发布前人工确认)。
|
||||||
|
*
|
||||||
|
* <p>flowName 与 {@code com.dsasp.server.core.service.flow.model.DefaultFlowHelper}
|
||||||
|
* 的 Flow id 完全一致({@code <TABLE>_ADD} 等),在 SYS_SERVICEFLOW 中即主键 sys_serviceflow_id。
|
||||||
|
*
|
||||||
|
* <ul>
|
||||||
|
* <li>实体尚无流(SYS_SERVICEFLOW 无 entityid 行)→ 返回合成名预览,
|
||||||
|
* 含 STATUS 列时 +2(SUBMIT / SAVE_AND_SUBMIT)。</li>
|
||||||
|
* <li>实体已有流 → 从 SYS_SERVICEFLOW 读真实行(sys_serviceflow_id + displayname)。</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* <p>不引入保真层重型 POInfo:STATUS 列存在性用元数据 SQL 判断,避免预览阶段触发 POInfo 缓存。
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class DefaultFlowPreviewService {
|
||||||
|
|
||||||
|
/** 5 个基础流的有序后缀 → kind / 显名映射。 */
|
||||||
|
private static final String[][] BASE_FLOWS = {
|
||||||
|
{"_ADD", "ADD", "新增"},
|
||||||
|
{"_DELETE", "DELETE", "删除"},
|
||||||
|
{"_UPDATE", "UPDATE", "更新"},
|
||||||
|
{"_SEARCH", "SEARCH", "查询"},
|
||||||
|
{"_LOAD", "LOAD", "加载"},
|
||||||
|
};
|
||||||
|
/** 含 STATUS 列时追加的 2 个提交流。 */
|
||||||
|
private static final String[][] STATUS_FLOWS = {
|
||||||
|
{"_SUBMIT", "SUBMIT", "提交审批"},
|
||||||
|
{"_SAVE_AND_SUBMIT", "SAVE_AND_SUBMIT", "保存并提交审批"},
|
||||||
|
};
|
||||||
|
|
||||||
|
private final JdbcTemplate jdbcTemplate;
|
||||||
|
|
||||||
|
public DefaultFlowPreviewService(JdbcTemplate jdbcTemplate) {
|
||||||
|
this.jdbcTemplate = jdbcTemplate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public record FlowItem(String flowName, String displayName, String kind) {}
|
||||||
|
|
||||||
|
public record FlowsPreview(String entityId, String tableName, boolean persisted, List<FlowItem> flows) {}
|
||||||
|
|
||||||
|
public FlowsPreview preview(String entityId) {
|
||||||
|
Integer existing = jdbcTemplate.queryForObject(
|
||||||
|
"SELECT COUNT(*) FROM SYS_SERVICEFLOW WHERE entityid=?", Integer.class, entityId);
|
||||||
|
String tableName = jdbcTemplate.queryForObject(
|
||||||
|
"SELECT TRIM(tablename) FROM SYS_ENTITY WHERE TRIM(sys_entity_id)=?", String.class, entityId);
|
||||||
|
if (existing != null && existing >= 1) {
|
||||||
|
return new FlowsPreview(entityId, tableName, true, persistedFlows(entityId));
|
||||||
|
}
|
||||||
|
return new FlowsPreview(entityId, tableName, false, synthesizedFlows(entityId, tableName));
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<FlowItem> synthesizedFlows(String entityId, String tableName) {
|
||||||
|
List<FlowItem> out = new ArrayList<>();
|
||||||
|
for (String[] f : BASE_FLOWS) {
|
||||||
|
out.add(new FlowItem(tableName + f[0], tableName + " " + f[2], f[1]));
|
||||||
|
}
|
||||||
|
Integer hasStatus = jdbcTemplate.queryForObject(
|
||||||
|
"SELECT COUNT(*) FROM SYS_ENTITYATTRIBUTE WHERE entityid=? AND UPPER(TRIM(columnname))='STATUS'",
|
||||||
|
Integer.class, entityId);
|
||||||
|
if (hasStatus != null && hasStatus >= 1) {
|
||||||
|
for (String[] f : STATUS_FLOWS) {
|
||||||
|
out.add(new FlowItem(tableName + f[0], tableName + " " + f[2], f[1]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<FlowItem> persistedFlows(String entityId) {
|
||||||
|
List<Map<String, Object>> rows = jdbcTemplate.queryForList(
|
||||||
|
"SELECT TRIM(sys_serviceflow_id) AS fid, displayname FROM SYS_SERVICEFLOW WHERE entityid=?"
|
||||||
|
+ " ORDER BY sys_serviceflow_id", entityId);
|
||||||
|
List<FlowItem> out = new ArrayList<>();
|
||||||
|
for (Map<String, Object> r : rows) {
|
||||||
|
String fid = String.valueOf(r.get("fid"));
|
||||||
|
String display = r.get("displayname") == null ? fid : String.valueOf(r.get("displayname"));
|
||||||
|
out.add(new FlowItem(fid, display, kindOf(fid)));
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String kindOf(String flowName) {
|
||||||
|
int us = flowName.indexOf('_');
|
||||||
|
if (us < 0) {
|
||||||
|
return "UNKNOWN";
|
||||||
|
}
|
||||||
|
return flowName.substring(us + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package com.eip4.platform.metadata.publish;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Production 人审部署包(建物 3 · DECISION-2)。
|
||||||
|
*
|
||||||
|
* <p>与 platform-ai 的 {@code AiDeploymentPackage} 同形精简版:
|
||||||
|
* 不含 taskId/changeSetId/runEvidence(人走五环无 AiTask 上下文),其余字段一致。
|
||||||
|
* 恒 requiresHumanApproval=true —— 生产上线走既有人审流程,本包不执行任何生产 SQL。
|
||||||
|
*/
|
||||||
|
public record DeploymentPackage(
|
||||||
|
String status,
|
||||||
|
boolean requiresHumanApproval,
|
||||||
|
long generatedAt,
|
||||||
|
Map<String, Object> manifest,
|
||||||
|
List<String> sqlStatements,
|
||||||
|
List<String> rollbackSqlStatements,
|
||||||
|
List<String> warnings) {
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user