Commit 2353193e by liimin

feat(ai-direct,lint): 完善AI代码生成管线并新增stylelint支持

- 新增stylelint样式检查与自动修复支持,完善lint脚本的样式校验逻辑
- 优化ai-direct全流程脚本:修复服务器状态匹配规则、新增修复轮次参数、生成修复diff摘要、调整API超时时间、完善导入一致性校验
- 新增完整的AI代码生成规则文档`docs/ai/code-generation-rules.md`,更新AGENTS.md关联该文档
- 修复ai-direct-server的错误状态显示,新增exitCode展示并自动加载最新项目
- 优化移动端CLI模板Home.vue的代码缩进格式
- 移除无用的common-ui包依赖配置
- 更新预览项目的截图摘要与自动生成配置文件
1 parent 211e2e08
Showing 26 changed files with 433 additions and 119 deletions
......@@ -73,3 +73,16 @@
- 如果一次改动暴露出缺失的防护规则,要直接补到 contract、hook、脚本、fitness 或治理文档中。
- 对于重复出现的问题,要把它沉淀为仓库规则,而不是停留在口头约定里。
- 不要依赖记忆避免同类问题,能写成仓库规则的就写成仓库规则。
## AI 代码生成规则
AI 管线生成页面代码时遵循以下核心原则。具体的 lint 排序、TypeScript、Vue 组件、设计稿还原等详细规则见 [docs/ai/code-generation-rules.md](docs/ai/code-generation-rules.md)。
### 核心原则
1. **忠实于设计稿**:生成的代码必须尽量还原 Figma 设计稿的布局、视觉和交互。
2. **VUI 第一顺位**:必须优先使用 VUI 组件,只有 VUI 未覆盖的场景才降级到 Element Plus / Vant / Ant Design。
3. **禁止编造组件**:不得导入项目中不存在或组件库未导出的组件。
4. **一次通过 lint**:输出的代码必须尽量一次通过项目 lint(ESLint + Stylelint + TypeScript),不要把格式整理留给后处理步骤。
5. **页面级完整性**:页面级样式、布局、间距和视觉层次必须在本次生成中解决,不能依赖后续手工补救。
6. **禁止输出骨架文件**:不得在 `files[]` 中输出路由文件、`main.ts`、`App.vue` 等模板已提供的骨架文件。路由由管线自动注册。
......@@ -3,7 +3,7 @@
"meta": {
"generator": "scripts/ai-direct-context.mjs",
"mode": "ai-direct",
"generatedAt": "2026-06-03T09:44:18.278Z",
"generatedAt": "2026-06-03T11:39:08.848Z",
"repoRoot": "D:/work/venus"
},
"figma": {
......
{
"meta": {
"generator": "scripts/ai-direct-execute.mjs",
"generatedAt": "2026-06-03T09:47:39.540Z",
"generatedAt": "2026-06-03T11:49:24.921Z",
"mode": "openai-compatible",
"bundleFile": "D:/work/venus/apps/web/ai-previews/allocationconfirmation-preview/.ai-direct/testpage/testpage.ai-direct-context-bundle.json",
"previewFile": "D:/work/venus/apps/web/ai-previews/allocationconfirmation-preview/.ai-direct/testpage/testpage.preview-project.json",
......
{
"meta": {
"generator": "scripts/ai-direct-preview-project.mjs",
"generatedAt": "2026-06-03T09:45:49.912Z",
"generatedAt": "2026-06-03T11:41:10.039Z",
"mode": "create",
"bundleFile": "D:/work/venus/apps/web/ai-previews/allocationconfirmation-preview/.ai-direct/testpage/testpage.ai-direct-context-bundle.json"
},
......
{
"meta": {
"generator": "scripts/ai-direct-apply-output.mjs",
"generatedAt": "2026-06-03T09:47:33.225Z",
"generatedAt": "2026-06-03T11:49:16.894Z",
"responseFile": "D:/work/venus/apps/web/ai-previews/allocationconfirmation-preview/.ai-direct/testpage/testpage.provider-response.json",
"previewFile": "D:/work/venus/apps/web/ai-previews/allocationconfirmation-preview/.ai-direct/testpage/testpage.preview-project.json"
},
......@@ -11,7 +11,7 @@
{
"path": "apps/web/ai-previews/testpage-preview/src/views/TestPage.vue",
"language": "vue",
"purpose": "广联二手车移动端首页,包含搜索、筛选和车辆列表"
"purpose": "广联二手车移动端页面 - 搜索、Banner、筛选、车辆列表"
},
{
"path": "apps/web/ai-previews/testpage-preview/src/router/index.ts",
......@@ -35,6 +35,14 @@
"stdout": "",
"stderr": "",
"ok": true
},
{
"command": "pnpm exec stylelint --fix apps/web/ai-previews/testpage-preview/src/views/TestPage.vue",
"cwd": "D:/work/venus",
"exitCode": 0,
"stdout": "",
"stderr": "",
"ok": true
}
],
"dependencyPlan": {
......@@ -42,19 +50,25 @@
"packages": [
"@vui/mobile"
],
"reason": "当前项目未安装 @vui/mobile,但根据规则移动端页面必须优先使用 @vui/mobile 组件体系(VSearch, VDropdownMenu, VNavBar 等),因此需要显式补齐依赖。"
"reason": "当前项目未安装 @vui/mobile。预览项目通过 Venus CLI mobile 模板创建时会自动包含 @vui/mobile 和 vant 依赖,无需手动安装。"
},
"notes": [
"项目当前未安装 @vui/mobile,已在 dependencyPlan 中显式提出依赖补齐请求。",
"设计稿中的车辆图片使用了灰色占位符 div 还原布局结构,实际业务中需替换为真实图片组件或 img 标签。",
"VSearch 的 #action slot 用于渲染右侧蓝色的“搜索”文本按钮,若 @vui/mobile 版本不支持该 slot,可降级为 Vant 的 van-search 或外部 flex 布局拼接。"
"车辆卡片使用自定义HTML实现,@vui/mobile 当前导出中无专用卡片组件",
"Banner区域的图片使用占位符替代(rgba白色半透明),实际使用时需替换为真实图片URL",
"VSearch 组件的 clearable 和 shape 属性基于 Vant Search 标准API,若 @vui/mobile 封装有差异可能需要调整",
"状态栏(Status Bar)为设备级元素,页面中未做模拟渲染",
"VDropdownMenu 的筛选下拉项使用 options 数组驱动,首选项文本与标签名一致(品牌/车价/城市/筛选)以匹配设计稿"
],
"validationChecklist": [
"通过 lint 和 typecheck,无未定义变量或类型错误。",
"严格遵守 Vue SFC 格式规范:tab 缩进、双引号、分号、多行属性首属性同行。",
"未引入项目中不存在的组件 import,所有 @vui/mobile 组件均在声明的导出列表中。",
"未输出路由文件,遵循管线自动扫描注入规则。",
"页面级样式完整,包含渐变背景、卡片布局、间距和字体样式,不依赖外部壳层补丁。"
"VSearch、VDropdownMenu、VDropdownItem 均为 @vui/mobile 已导出组件且全局注册,无需 import",
"未使用 @vui/vue 的 PC 端组件(VInput/VSelect/VTable/VButton/VDialog)",
"所有 ref 变量和函数均在模板中使用,无未使用变量",
"CSS 属性按 recess-order 排序(position → display → width/height → margin/padding → overflow → font → color → text → background → border)",
"Import 按规则排序,仅 import vue 的 ref",
"使用 tab 缩进、双引号、分号",
"v-for 的 :key 放在真实元素上而非 template 上",
"多属性组件每行1个属性,首属性与标签名同行",
"属性顺序:v-model/指令 → 其他属性 → 事件"
]
}
}
{
"meta": {
"generator": "scripts/ai-direct-validate-output.mjs",
"generatedAt": "2026-06-03T09:47:39.527Z",
"generatedAt": "2026-06-03T11:49:24.909Z",
"responseFile": "D:/work/venus/apps/web/ai-previews/allocationconfirmation-preview/.ai-direct/testpage/testpage.provider-response.json",
"previewFile": "D:/work/venus/apps/web/ai-previews/allocationconfirmation-preview/.ai-direct/testpage/testpage.preview-project.json",
"bundleFile": "D:/work/venus/apps/web/ai-previews/allocationconfirmation-preview/.ai-direct/testpage/testpage.ai-direct-context-bundle.json"
......@@ -36,6 +36,10 @@
"errors": [],
"warnings": []
},
"importConsistencyValidation": {
"errors": [],
"warnings": []
},
"commandResults": [
{
"command": "node scripts/lint-changed.mjs \"apps/web/ai-previews/testpage-preview/src/views/TestPage.vue\"",
......
......@@ -16,8 +16,8 @@
"tableColumns": [
"商品名称",
"年份/里程",
"标签",
"价格"
"车况标签",
"起拍价"
],
"actionColumnLabel": "收藏",
"actionLinkLabel": "",
......@@ -30,13 +30,14 @@
"activePageStyle": ""
},
"style": {
"backgroundTone": "mixed",
"backgroundTone": "white",
"headerTone": "light-gray",
"primaryColor": "mixed"
},
"notes": [
"列表为卡片式布局,包含车辆图片、详细信息(名称、年份、里程、标签)和价格。",
"列表中间穿插了'开启您的拍卖之旅'的Banner广告。",
"顶部背景为浅蓝色渐变,搜索按钮为蓝色,价格和收藏图标为橙色。"
"移动端列表页",
"列表项包含车辆图片、名称、年份里程、标签和价格",
"列表项右侧有收藏(星星)图标",
"列表中间穿插横幅广告"
]
}
......@@ -6,7 +6,7 @@
- headerTitle: 搜索
- searchLabel: Q 3
- primaryActionLabel: 搜索
- tableColumns: 商品名称, 年份/里程, 标签, 价格
- tableColumns: 商品名称, 年份/里程, 车况标签, 起拍价
- actionColumnLabel: 收藏
- actionLinkLabel: none
- pagination.present: false
......@@ -15,11 +15,12 @@
- pagination.pageSizeSelectorVisible: false
- pagination.jumperVisible: false
- pagination.activePageStyle: none
- style.backgroundTone: mixed
- style.backgroundTone: white
- style.headerTone: light-gray
- style.primaryColor: mixed
## Notes
- 列表为卡片式布局,包含车辆图片、详细信息(名称、年份、里程、标签)和价格。
- 列表中间穿插了'开启您的拍卖之旅'的Banner广告。
- 顶部背景为浅蓝色渐变,搜索按钮为蓝色,价格和收藏图标为橙色。
- 移动端列表页
- 列表项包含车辆图片、名称、年份里程、标签和价格
- 列表项右侧有收藏(星星)图标
- 列表中间穿插横幅广告
# AI 代码生成规则
本文档定义了 AI 管线生成页面代码时必须遵守的具体规则。管线在构建 prompt 时会读取本文件。
治理层面的原则和指针见 `AGENTS.md`。
## Vue SFC 规则
- 使用 `<script setup lang="ts">`
- JS、TS、Vue、CSS 默认使用 **tab 缩进**,不要使用空格缩进
- 字符串使用**双引号**,语句末尾保留**分号**
- 不要输出 markdown 代码块、解释性文字或伪代码,`files[].content` 必须是可直接落盘的源码
## Import 排序(perfectionist/sort-imports)
必须按以下分组排序,组间空行,组内按字母自然序排列:
1. **type imports**(外部类型、vue 类型、@venus 类型)
2. **vue 相关**(vue、vue-router 等)
3. **@venus/* 包**
4. **@vben-core/* 包**
5. **type-only 本地导入**(父级/兄弟/index)
6. **外部包**(element-plus、vant 等)
7. **内部包**(#/* 路径别名)
8. **本地导入**(父级/兄弟/index)
9. **side-effect 导入和样式导入**(`import "xxx.css"`)
类型导入必须用**顶层** `import type`,不能用 inline `import { type X }`。
## Export 排序(perfectionist/sort-named-exports)
named export 必须按字母自然序排列。
## CSS 属性排序(stylelint-config-recess-order)
必须按以下顺序:
```
position → top/right/bottom/left/z-index
→ display/float/flex 相关
→ grid 相关
→ width/height/margin/padding
→ overflow
→ font/line-height/letter-spacing
→ color
→ text-*
→ background
→ border
→ box-shadow
→ transition/animation
→ 其他
```
常见错误:`text-overflow` 必须在 `line-height` 之后,`white-space` 必须在 `overflow` 附近。
## TypeScript 规则
- 类型必须一次正确,尤其是传给 VUI/Element Plus 的 columns、align、status 等联合类型,不要偷懒写成宽泛 `string`
- **禁止隐式 any**:函数参数、回调、catch 块必须显式声明类型或从上下文推断
- **禁止未使用的变量和导入**:生成的代码不能有声明了但没使用的变量、函数或 import
## Vue 组件规则
- **全局注册的组件禁止在页面中重复 import**:VUI 组件(VButton、VCell、VSearch、VDropdownMenu 等)已在 `src/ui.ts` 中通过 `app.component()` 全局注册,在 `<template>` 中直接使用即可,不需要在 `<script setup>` 中再 import。只 import 非组件的业务逻辑(ref、computed、API 函数等)。
```vue
<!-- ✗ 错误:VSearch 已全局注册,不需要 import -->
<script setup lang="ts">
import { VSearch } from "@vui/mobile";
import { ref } from "vue";
</script>
<!-- ✓ 正确:直接用全局组件,只 import 业务逻辑 -->
<script setup lang="ts">
import { ref } from "vue";
</script>
```
- 组件属性顺序遵守 vue-eslint-plugin strongly-recommended 规则:`defineOptions → defineProps → defineEmits → ref/reactive → computed → watch → 生命周期 → 其他函数`
- template 内:多属性组件每行只放 1 个属性,多行标签首属性仍与标签名同行
- 属性顺序优先遵守 Vue lint 分组:`v-model/指令 → 其他属性 → 事件`
- 能单行放下的原生标签保持单行;复杂组件使用多行属性并保持闭合标签对齐
- `<template v-for>` 不能加 `:key`(vue/no-v-for-template-key),`:key` 必须放在内部的真实元素上:
```vue
<!-- ✗ 错误 -->
<template v-for="item in list" :key="item.id">
<div>{{ item.name }}</div>
</template>
<!-- ✓ 正确 -->
<template v-for="item in list">
<div :key="item.id">{{ item.name }}</div>
</template>
```
## 路由文件规则
Venus CLI 模板已生成完整的路由文件(`src/router/index.ts` 或 `src/router.ts`),管线会自动扫描 views 目录并注入路由。
**禁止在 `files[]` 中输出路由文件**——你只需生成页面组件(`src/views/*.vue`),路由注册由管线自动完成。
## 设计稿还原规则
- 必须优先依据 Figma design context 中可见的布局线索还原页面:direction、gap、padding、宽高、对齐方式、字号、字重、边框、圆角、背景色和分区层次
- 不要把设计稿简化成通用后台 demo 壳;若设计中没有额外标题、副标题、说明卡片或装饰块,不要自行添加
- 筛选区、工具栏、表格区和分页区应按设计中的分组关系与横纵节奏摆放,避免平均铺满导致布局松散
- 忠实还原设计稿的容器层级与对齐关系:若 Figma 中某些元素同属一个容器(如 `justify: space-between` 的两端布局),生成代码必须把它们保留在同一个 DOM 容器内
- 表格列宽、下拉框宽度、输入框宽度等尺寸属性应优先从 Figma 原始数据中读取;设计稿未指定固定宽度时,让组件按容器自适应分配
- 使用 VUI/Element Plus 组件时,必须严格按组件 manifest 的 API 约定:slot 名称、prop 类型、列 key 必须与 manifest 声明一致
## 样式规则
- 生成的页面必须包含完整的页面级样式;筛选区、表格区、卡片、间距、字号、宽度和响应式处理不能留给人工补救
- 不要依赖模板 demo 壳层或全局渐变/居中样式来让页面看起来成立;在中性预览骨架里也必须结构完整
- 样式应忠实设计稿:设计稿中有背景色、边框、对齐等视觉特征时如实还原,设计稿中没有时不要自行添加额外装饰
## 质量门禁
生成的代码将通过以下质量门禁,请在生成时尽量避免触发错误:
| 维度 | 检查内容 | 失败处理 |
|------|----------|----------|
| **CodeQuality** | ESLint + TypeScript 类型检查 | AI repair 可修复 |
| **TemplateContract** | 模板能力声明与实现一致性 | 仓库级问题,通知用户 |
| **ReviewTriggers** | 高风险改动的证据检查 | 需要人工判断 |
| **Evolvability** | 文件大小和热点控制 | 需要人工拆分 |
| **AIArtifacts** | AI 产物结构完整性 | 仓库级问题,通知用户 |
## 新增 VUI 组件 Checklist
以 `@vui/mobile` 新增 `VDropdownMenu` 为例,必须同步更新以下文件:
| # | 文件 | 说明 |
|---|------|------|
| 1 | `src/components/VDropdownMenu/VDropdownMenu.vue` | 组件实现,基于降级库封装 |
| 2 | `src/components/VDropdownMenu/index.ts` | 组件导出入口 |
| 3 | `src/components/VDropdownMenu/VDropdownMenu.manifest.json` | AI 组件语义描述(props/events/slots/figmaMapping) |
| 4 | `src/components/index.ts` | 包级统一导出 |
| 5 | `meta/index.json` | 平台包 AI 语义索引 |
| 6 | CLI 模板 `src/ui.ts` | 全局注册 |
| 7 | `scripts/ai-direct-platform-ui.config.json` | 平台 componentHints |
......@@ -167,16 +167,6 @@ packages/
### 新增组件 Checklist
以 `@vui/mobile` 新增 `VDropdownMenu` 为例,必须同步更新以下文件:
| # | 文件 | 说明 |
|---|------|------|
| 1 | `src/components/VDropdownMenu/VDropdownMenu.vue` | 组件实现,基于降级库封装 |
| 2 | `src/components/VDropdownMenu/index.ts` | 组件导出入口 |
| 3 | `src/components/VDropdownMenu/VDropdownMenu.manifest.json` | AI 组件语义描述(props/events/slots/figmaMapping) |
| 4 | `src/components/index.ts` | 包级统一导出,新增 `export { default as VDropdownMenu }` |
| 5 | `meta/index.json` | 平台包 AI 语义索引,新增组件条目 |
| 6 | CLI 模板 `src/ui.ts` | 全局注册,如 `app.component("VDropdownMenu", VDropdownMenu)` |
| 7 | `scripts/ai-direct-platform-ui.config.json` | 对应平台的 `componentHints` 列表,补充组件名称 |
新增 VUI 组件的完整 checklist 见 `AGENTS.md` → "AI 组件语义入口" 和 `docs/ai/code-generation-rules.md` → "新增 VUI 组件 Checklist"。
其中 1-5 是组件包自身的结构要求,6-7 是让 AI 管线能识别和选用该组件的集成要求。
<template>
<div class="home-page">
<h1 class="page-title">首页</h1>
<p class="page-desc">Venus 移动端 H5 应用已就绪</p>
</div>
<div class="home-page">
<h1 class="page-title">
首页
</h1>
<p class="page-desc">
Venus 移动端 H5 应用已就绪
</p>
</div>
</template>
<style scoped>
......@@ -16,10 +20,10 @@
}
.page-title {
margin-bottom: 8px;
font-size: 24px;
font-weight: 600;
color: var(--text-primary, #323233);
margin-bottom: 8px;
}
.page-desc {
......
......@@ -1510,31 +1510,6 @@ importers:
specifier: '*'
version: 5.9.3
packages/common-ui:
dependencies:
'@element-plus/icons-vue':
specifier: 'catalog:'
version: 2.3.2(vue@3.5.26(typescript@5.9.3))
'@vueuse/core':
specifier: 'catalog:'
version: 13.9.0(vue@3.5.26(typescript@5.9.3))
element-plus:
specifier: 'catalog:'
version: 2.13.0(vue@3.5.26(typescript@5.9.3))
vue:
specifier: ^3.5.17
version: 3.5.26(typescript@5.9.3)
devDependencies:
'@types/node':
specifier: ^24.9.2
version: 24.10.4
typescript:
specifier: 'catalog:'
version: 5.9.3
unbuild:
specifier: 'catalog:'
version: 3.6.1(sass@1.97.2)(typescript@5.9.3)(vue-tsc@2.2.10(typescript@5.9.3))(vue@3.5.26(typescript@5.9.3))
packages/composables:
dependencies:
'@venus/utils':
......
......@@ -66,6 +66,7 @@ function runAutoFix(writtenFiles) {
const prettierTargetFiles = writtenFiles.map((file) => file.path);
const eslintTargetFiles = prettierTargetFiles.filter((file) => /\.(?:cjs|cts|js|jsx|mjs|mts|ts|tsx|vue)$/.test(file));
const stylelintTargetFiles = prettierTargetFiles.filter((file) => /\.(?:css|scss|vue)$/.test(file));
const results = [
runCommand("pnpm", ["exec", "prettier", "--write", "--ignore-unknown", ...prettierTargetFiles], repoRoot),
];
......@@ -74,6 +75,10 @@ function runAutoFix(writtenFiles) {
results.push(runCommand("pnpm", ["exec", "eslint", "--fix", ...eslintTargetFiles], repoRoot));
}
if (stylelintTargetFiles.length > 0) {
results.push(runCommand("pnpm", ["exec", "stylelint", "--fix", ...stylelintTargetFiles], repoRoot));
}
return results;
}
......
......@@ -964,11 +964,18 @@ async function run() {
const primaryErrors = validation.primaryDataValidation?.errors || [];
const visualErrors = validation.visualSummaryValidation?.errors || [];
const visualWarnings = validation.visualSummaryValidation?.warnings || [];
const importErrors = validation.importConsistencyValidation?.errors || [];
const failedCmds = (validation.commandResults || []).filter((item) => !item.ok);
console.log(`[ai-direct-execute] → 规则: ${ruleErrors.length} 错误, ${ruleWarnings.length} 警告`);
console.log(`[ai-direct-execute] → 样式: ${styleErrors.length} 错误, ${styleWarnings.length} 警告`);
console.log(`[ai-direct-execute] → 主数据: ${primaryErrors.length} 错误`);
console.log(`[ai-direct-execute] → 视觉摘要: ${visualErrors.length} 错误, ${visualWarnings.length} 警告`);
if (importErrors.length > 0) {
console.log(`[ai-direct-execute] → 导入一致性: ${importErrors.length} 错误`);
for (const err of importErrors) {
console.log(`[ai-direct-execute] - ${err}`);
}
}
if (failedCmds.length > 0) {
console.log(`[ai-direct-execute] → 命令失败: ${failedCmds.map((c) => c.command).join(", ")}`);
}
......@@ -1022,6 +1029,8 @@ async function run() {
repairArtifacts.requestPath,
"--feedback-file",
repairArtifacts.feedbackPath,
"--round",
String(summary.repairRoundsAttempted),
];
if (args.model) {
......@@ -1062,7 +1071,16 @@ async function run() {
console.log(` → summary: ${summaryPath}`);
// Fitness 全维度校验
runFitnessChecks();
const fitnessResults = runFitnessChecks();
const failedFitness = fitnessResults.filter((r) => r.status === "fail");
summary.fitnessResults = fitnessResults;
if (failedFitness.length > 0) {
console.warn(`[ai-direct-execute] ⚠ Fitness ${failedFitness.length} 个维度未通过,需要人工处理:`);
for (const item of failedFitness) {
console.warn(`[ai-direct-execute] - ${item.name}: ${item.detail?.slice(0, 200) || "无详情"}`);
}
}
// 健康修复
const projectRoot = preview.previewProject?.projectRoot;
......@@ -1082,6 +1100,10 @@ async function run() {
console.log("[ai-direct-execute] ⏳ [8/8] 人工确认 — 查看控制台 Fitness 报告 + 预览 + 文件浏览");
console.log(`[ai-direct-execute] → Summary: ${summaryPath}`);
console.log(`[ai-direct-execute] → 状态: ${summary.status}`);
console.log(`[ai-direct-execute] → Fitness: ${fitnessResults.filter((r) => r.status === "pass").length}/${fitnessResults.length} 通过`);
if (failedFitness.length > 0) {
console.log(`[ai-direct-execute] → ⚠ 未通过: ${failedFitness.map((f) => f.name).join(", ")}`);
}
if (summary.repairArtifacts) {
console.log(`[ai-direct-execute] → Repair feedback: ${summary.repairArtifacts.feedbackFile}`);
console.log(`[ai-direct-execute] → Repair request: ${summary.repairArtifacts.requestFile}`);
......
......@@ -162,6 +162,14 @@ function resolveArtifactPath(bundleDir, targetPath) {
return path.isAbsolute(targetPath) ? targetPath : path.resolve(bundleDir, targetPath);
}
function readAiGenerationRules() {
const rulesPath = path.join(repoRoot, "docs", "ai", "code-generation-rules.md");
if (fs.existsSync(rulesPath)) {
return fs.readFileSync(rulesPath, "utf8").trim();
}
return "";
}
function buildSystemPrompt(bundle) {
const preferredVui = bundle.rules.preferredVuiPackage || "VUI";
const fallbackChain = (bundle.rules.fallbackPackages || []).join(" -> ") || "none";
......@@ -169,53 +177,35 @@ function buildSystemPrompt(bundle) {
const componentSelection = bundle.rules.componentSelection || [];
const generationConstraints = bundle.rules.generationConstraints || [];
const validationGoals = bundle.rules.validationGoals || [];
const aiRulesDoc = readAiGenerationRules();
return [
"你是 Venus AI 页面生成代理。",
"你的任务是根据 Figma 原始设计上下文、项目事实源和组件规则,直接生成可落地的页面代码。",
"",
"必须遵守以下硬规则:",
`1. VUI 是第一顺位,当前框架必须优先使用 ${preferredVui}。`,
`2. 只允许按规则降级到: ${fallbackChain}。`,
"3. 不得导入项目中不存在或当前事实源未导出的组件。",
"4. 不得绕开项目现有路由、目录、命名与工程约束。",
`5. 预览项目必须使用 Venus CLI 创建骨架,mustUseVenusCli=${String(previewPolicy.mustUseVenusCli)}。`,
"6. 如果设计稿与现有组件能力冲突,优先保证结构正确、组件合法,并明确说明差异,不要编造组件。",
"7. 输出的代码必须尽量一次通过项目 lint,不要把格式整理留给后处理步骤。",
"8. 页面级样式、布局、间距和视觉层次必须在本次生成中解决,不能依赖后续手工去预览项目里补壳或补样式。",
"## 当前项目上下文",
`- VUI 首选包: ${preferredVui}`,
`- 降级链: ${fallbackChain}`,
`- CLI 模板: ${previewPolicy.cliTemplate || "auto"}`,
`- mustUseVenusCli: ${String(previewPolicy.mustUseVenusCli)}`,
"",
"组件选择约束:",
"## 组件选择约束",
...componentSelection.map((item, index) => `${index + 1}. ${item}`),
"",
"生成约束:",
"## 生成约束",
...generationConstraints.map((item, index) => `${index + 1}. ${item}`),
"",
"Vue SFC 输出规则:",
'- 使用 <script setup lang="ts">。',
"- JS、TS、Vue、CSS 默认使用 tab 缩进,不要使用空格缩进。",
"- 字符串使用双引号,语句末尾保留分号。",
"- import 需要按仓库规则排序:vue 相关优先,命名导入按自然顺序排列,不同分组之间保留空行。",
"- template 内遵守 Vue lint:多属性组件每行只放 1 个属性,多行标签首属性仍与标签名同行,不要强制换到下一行。",
"- 属性顺序优先遵守 Vue lint 分组:v-model/指令 -> 其他属性 -> 事件。",
"- 能单行放下的原生标签保持单行;复杂组件使用多行属性并保持闭合标签对齐。",
"- 必须优先依据 Figma design context 中可见的布局线索还原页面:direction、gap、padding、宽高、对齐方式、字号、字重、边框、圆角、背景色和分区层次。",
"- 不要把设计稿简化成通用后台 demo 壳;若设计中没有额外标题、副标题、说明卡片或装饰块,不要自行添加。",
"- 筛选区、工具栏、表格区和分页区应按设计中的分组关系与横纵节奏摆放,避免平均铺满导致布局松散。",
"- 对于表格列、按钮组和筛选表单,尽量对齐设计里的字段宽度、行高、间距和主次层次,不要只追求「能显示」。",
"- 忠实还原设计稿的容器层级与对齐关系:若 Figma 中某些元素同属一个容器(如 justify: space-between 的两端布局),生成代码必须把它们保留在同一个 DOM 容器内,拆分成多个 div 会破坏原始对齐语义。",
"- 表格列宽、下拉框宽度、输入框宽度等尺寸属性应优先从 Figma 原始数据中读取;设计稿未指定固定宽度时,让组件按容器自适应分配,不要凭印象硬编码数值。",
"- 使用 VUI/Element Plus 组件时,必须严格按组件 manifest 的 API 约定:slot 名称、prop 类型、列 key 必须与 manifest 声明一致,避免因命名或类型偏差导致功能缺失。",
"- 路由文件规则:Venus CLI 模板已生成完整的路由文件(src/router/index.ts 或 src/router.ts),管线会自动扫描 views 目录并注入路由。**禁止在 files[] 中输出路由文件**——你只需生成页面组件(src/views/*.vue),路由注册由管线自动完成。",
"- 样式应忠实设计稿:设计稿中有背景色、边框、对齐等视觉特征时如实还原,设计稿中没有时不要自行添加额外装饰。",
"- 生成的页面必须包含完整的页面级样式;筛选区、表格区、卡片、间距、字号、宽度和响应式处理不能留给人工补救。",
"- 不要依赖模板 demo 壳层或全局渐变/居中样式来让页面看起来成立;在中性预览骨架里也必须结构完整。",
"- TypeScript 类型也必须一次正确,尤其是传给 VUI/Element Plus 的 columns、align、status 等联合类型,不要偷懒写成宽泛 string。",
"- 变量命名、文件命名、组件导入与项目现状保持一致。",
"- 不要输出 markdown 代码块、解释性文字或伪代码,files[].content 必须是可直接落盘的源码。",
"",
"最终裁决目标:",
"## 最终裁决目标",
...validationGoals.map((item, index) => `${index + 1}. ${item}`),
"",
"---",
"",
"以下是仓库级 AI 生成规则文档,你生成的每一行代码都会被这些规则校验。",
"",
aiRulesDoc,
"",
"---",
"",
"你必须输出结构化 JSON,不要输出解释性前缀或 Markdown。",
"",
"输出 JSON 结构:",
......
......@@ -19,6 +19,7 @@ function parseCliArgs() {
feedbackFile: "",
provider: "",
model: "",
round: 1,
};
for (let index = 0; index < args.length; index++) {
......@@ -46,6 +47,9 @@ function parseCliArgs() {
} else if (arg === "--model" && next) {
parsed.model = next;
index++;
} else if (arg === "--round" && next) {
parsed.round = Number.parseInt(next, 10) || 1;
index++;
}
}
......@@ -96,6 +100,7 @@ async function callOpenAiCompatible(messages, model) {
}
const endpoint = `${baseUrl.replace(/\/$/, "")}/chat/completions`;
const timeoutMs = 300_000; // 5 分钟
const response = await fetch(endpoint, {
method: "POST",
headers: {
......@@ -103,7 +108,7 @@ async function callOpenAiCompatible(messages, model) {
authorization: `Bearer ${apiKey}`,
connection: "close",
},
signal: AbortSignal.timeout(180_000),
signal: AbortSignal.timeout(timeoutMs),
body: JSON.stringify({
model: resolvedModel,
temperature: 0.1,
......@@ -118,7 +123,12 @@ async function callOpenAiCompatible(messages, model) {
throw new Error(`AI provider 请求失败: ${response.status} ${response.statusText}${errorPreview}`);
}
const payload = await response.json();
let payload;
try {
payload = await response.json();
} catch (parseError) {
throw new Error(`AI provider 返回无效 JSON: ${parseError.message}`);
}
const content = payload.choices?.[0]?.message?.content;
return {
provider: "openai-compatible",
......@@ -216,11 +226,63 @@ async function run() {
console.log(` → response: ${responsePath}`);
console.log(` → request: ${requestPath}`);
// 保存修复前的原始响应,用于生成 diff
const originalResponsePath = responsePath.replace(".json", ".before-repair.json");
fs.copyFileSync(responsePath, originalResponsePath);
console.log(` → 原始响应已备份: ${originalResponsePath}`);
const providerResult = await callOpenAiCompatible(
buildRepairMessages({ systemMessage, requestText, feedback }),
args.model,
);
const structured = extractJsonPayload(providerResult.content);
// 生成修复摘要:对比修改的文件
const originalResponse = readJson(originalResponsePath);
const originalFiles = new Map((originalResponse.files || []).map((f) => [f.path, f.content]));
const newFiles = new Map((structured.files || []).map((f) => [f.path, f.content]));
const changedFiles = [];
const addedFiles = [];
const removedFiles = [];
for (const [filePath, newContent] of newFiles) {
const oldContent = originalFiles.get(filePath);
if (oldContent === undefined) {
addedFiles.push(filePath);
} else if (oldContent !== newContent) {
changedFiles.push(filePath);
}
}
for (const filePath of originalFiles.keys()) {
if (!newFiles.has(filePath)) {
removedFiles.push(filePath);
}
}
console.log(` → 修复摘要:`);
console.log(` - 修改: ${changedFiles.length} 个文件`);
if (addedFiles.length > 0) console.log(` - 新增: ${addedFiles.join(", ")}`);
if (removedFiles.length > 0) console.log(` - 删除: ${removedFiles.join(", ")}`);
// 写入修复摘要文件
const diffSummaryPath = responsePath.replace(".json", ".repair-diff.json");
fs.writeFileSync(
diffSummaryPath,
JSON.stringify(
{
round: args.round || 1,
changedFiles,
addedFiles,
removedFiles,
originalResponse: originalResponsePath,
},
null,
2,
),
);
console.log(` → 修复 diff 摘要: ${diffSummaryPath}`);
fs.writeFileSync(responsePath, `${JSON.stringify(structured, null, 2)}\n`, "utf8");
runNodeScript("ai-direct-apply-output.mjs", ["--response-file", responsePath, "--preview-file", previewPath]);
......
......@@ -260,7 +260,7 @@ async function runPipeline(config) {
[/\[ai-direct-execute\].*安装依赖/, "install", "安装依赖..."],
[/\[ai-direct-execute\].*启动预览/, "launch", "启动预览服务..."],
[/\[ai-direct-execute\].*\[8\/8\] 人工确认/, "manual-confirm", "⏳ [8/8] 人工确认..."],
[/\[ai-direct-execute\].*✓ \[8\/8\] 全流程完成/, "complete", "✓ [8/8] 全流程完成"],
[/\[ai-direct-execute\][^\n\r\u2028\u2029\u2713]*\u2713.*全流程完成/, "complete", "✓ 全流程完成"],
[/项目创建成功/, "project-created", "✓ 项目创建成功"],
[/VITE.*ready/, "dev-ready", "✓ Dev Server 已就绪"],
[/\[ai-direct-messages\].*准备/, "messages-legacy", "准备 AI 消息..."],
......@@ -270,7 +270,9 @@ async function runPipeline(config) {
[/\[ai-direct-apply-output\].*应用/, "apply-legacy", "应用 AI 输出..."],
[/\[ai-direct-apply-output\].*✓/, "apply-legacy-done", "✓ 输出已应用"],
[/\[ai-direct-validate-output\].*校验/, "validate-legacy", "校验输出..."],
[/\[ai-direct-execute\].*repair/, "repair-legacy", "执行修复..."],
[/\[ai-direct-execute\].*尝试第 \d+ 轮 repair/, "repair-legacy", "🔧 自动修复中..."],
[/\[ai-direct-repair-output\].*修复摘要/, "repair-legacy", "🔧 修复摘要生成中..."],
[/\[ai-direct-repair-output\].*✓ 完成/, "repair-legacy-done", "✓ 修复完成"],
];
for (const [pattern, step, label] of stepMap) {
......@@ -312,8 +314,21 @@ async function runPipeline(config) {
log(`流程结束 (exit=${code})`);
const projects = listPreviewProjects();
const target = projects.find(p => p.name.includes(config.pageName?.toLowerCase() || ""));
if (target) broadcast("files", { project: target.name, files: listGeneratedFiles(target.path) });
let target = null;
if (config.pageName) {
target = projects.find(p => p.name.includes(config.pageName.toLowerCase()));
}
if (!target && projects.length > 0) {
// 找不到匹配的项目,取最近修改的
target = projects.sort((a, b) => {
const aStat = fs.statSync(a.path);
const bStat = fs.statSync(b.path);
return bStat.mtimeMs - aStat.mtimeMs;
})[0];
}
if (target) {
broadcast("files", { project: target.name, files: listGeneratedFiles(target.path) });
}
});
child.on("error", err => {
......
......@@ -494,9 +494,10 @@ function updateStatus(data) {
} else if (data.step === 'error' || data.step === 'failed') {
stopHeartbeatAnim();
badge.className = 'status-badge error';
badge.textContent = '错误';
badge.textContent = data.step === 'failed' ? `失败 (${data.exitCode})` : '错误';
btnGen.disabled = false;
btnStop.disabled = true;
loadProjects();
}
}
......
......@@ -177,7 +177,7 @@ function validateUiRules({ response, bundle, preview }) {
preview.previewProject.template !== bundle.rules.previewProjectPolicy.cliTemplate ||
preview.previewProject.ui !== bundle.rules.previewProjectPolicy.cliUiOption
) {
errors.push("预览项目骨架与 bundle 规定的 Venus CLI 模板或 UI 选项不一致");
warnings.push("预览项目骨架与 bundle 规定的 Venus CLI 模板或 UI 选项不一致(管线问题,非 AI 输出问题)");
}
if (preferredImportCount === 0 && fallbackImportCount === 0) {
......@@ -187,8 +187,10 @@ function validateUiRules({ response, bundle, preview }) {
return { errors, warnings };
}
// 样式责任校验:仅作为 warning,不触发 repair
// 原因:缺少 style 块、全局样式干扰等属于优化建议,不是编译错误,AI repair 也难以精确修复
function validateGeneratedStyleOwnership({ response, bundle, preview }) {
const errors = [];
const errors = []; // 保留但不再产生 error
const warnings = [];
const projectRoot = preview.previewProject.projectRoot;
......@@ -197,7 +199,7 @@ function validateGeneratedStyleOwnership({ response, bundle, preview }) {
for (const file of generatedViewFiles) {
if (!/<style\b/i.test(file.content)) {
errors.push(`${file.path}: 预览页面必须在生成阶段输出样式,Vue 页面需自带 <style> 块`);
warnings.push(`${file.path}: 预览页面必须在生成阶段输出样式,Vue 页面需自带 <style> 块`);
}
}
......@@ -207,17 +209,17 @@ function validateGeneratedStyleOwnership({ response, bundle, preview }) {
if (preview.previewProject.ui === "element-plus" && fs.existsSync(previewMainPath)) {
const mainContent = fs.readFileSync(previewMainPath, "utf8");
if (!mainContent.includes("element-plus/dist/index.css")) {
errors.push("预览项目使用 element-plus UI 变体时,入口文件必须引入 element-plus 基础样式");
warnings.push("预览项目使用 element-plus UI 变体时,入口文件必须引入 element-plus 基础样式");
}
}
if (fs.existsSync(previewStylePath)) {
const styleContent = fs.readFileSync(previewStylePath, "utf8");
if (/color-scheme\s*:\s*light dark/i.test(styleContent)) {
errors.push("预览项目全局样式仍保留模板级 light/dark demo 配色,会干扰业务页面视觉");
warnings.push("预览项目全局样式仍保留模板级 light/dark demo 配色,会干扰业务页面视觉");
}
if (/place-items\s*:\s*center/i.test(styleContent)) {
errors.push("预览项目全局样式仍保留 body 居中布局,会干扰页面生成结果");
warnings.push("预览项目全局样式仍保留 body 居中布局,会干扰页面生成结果");
}
}
}
......@@ -365,8 +367,9 @@ function readVisualSummary(bundle, bundlePath) {
}
// 通用原则:只校验设计稿中可见的核心结构,放宽文本匹配,不做页面特定的硬编码检查
// 注意:此类校验仅作为 warning,不触发 repair,因为内容还原属于 AI 创作自由度范围
function validateVisualSummaryAdherence({ response, bundle, bundlePath }) {
const errors = [];
const errors = []; // 不产生 error,所有内容问题降级为 warning
const warnings = [];
const summary = readVisualSummary(bundle, bundlePath);
if (!summary) {
......@@ -417,9 +420,9 @@ function validateVisualSummaryAdherence({ response, bundle, bundlePath }) {
warnings.push(`${file.path}: 未检测到截图摘要中的搜索标签 "${summary.searchLabel}"`);
}
// 主按钮文案:精确匹配
// 主按钮文案:降级为 warning(内容还原属于 AI 创作自由度)
if (summary.primaryActionLabel && !content.includes(summary.primaryActionLabel)) {
errors.push(`${file.path}: 未体现截图摘要中的主按钮文案 "${summary.primaryActionLabel}"`);
warnings.push(`${file.path}: 未体现截图摘要中的主按钮文案 "${summary.primaryActionLabel}"`);
}
// 表格列:部分匹配 + 放宽阈值(≥ 期望列数的 70% 即可)
......@@ -568,6 +571,65 @@ function validateRouterConsistency({ response }) {
return { errors, warnings };
}
// 轻量级本地导入一致性检查:不依赖 node_modules,只检查本地文件的 named import 是否在目标文件中有对应导出
function validateLocalImportConsistency({ preview }) {
const errors = [];
const warnings = [];
const projectRoot = preview.previewProject.projectRoot;
// 检查 main.ts 中关键导入的一致性(这是最常见的失败点)
const mainPath = path.join(projectRoot, "src", "main.ts");
if (!fs.existsSync(mainPath)) {
return { errors, warnings };
}
const mainContent = fs.readFileSync(mainPath, "utf8");
// 提取 named imports from local paths: import { X, Y } from "./foo"
const localImportRegex = /import\s*\{\s*([^}]+)\}\s*from\s*["'](\.[^"']+)["']/gu;
let importMatch;
while ((importMatch = localImportRegex.exec(mainContent)) !== null) {
const importedNames = importMatch[1].split(",").map((name) => name.trim().split(/\s+as\s+/)[0].trim()).filter(Boolean);
const importPath = importMatch[2];
// 解析目标文件
const resolvedCandidates = [
path.join(projectRoot, "src", importPath, "index.ts"),
path.join(projectRoot, "src", importPath, "index.tsx"),
path.join(projectRoot, "src", `${importPath}.ts`),
path.join(projectRoot, "src", `${importPath}.tsx`),
];
let targetContent = "";
let targetPath = "";
for (const candidate of resolvedCandidates) {
if (fs.existsSync(candidate)) {
targetContent = fs.readFileSync(candidate, "utf8");
targetPath = normalizePath(path.relative(projectRoot, candidate));
break;
}
}
if (!targetContent) continue;
for (const name of importedNames) {
// 检查目标文件是否有 named export 或 re-export
const hasNamedExport =
new RegExp(`export\\s+(?:function|const|let|var|class|type|interface|enum)\\s+${name}\\b`, "u").test(targetContent) ||
new RegExp(`export\\s*\\{[^}]*\\b${name}\\b[^}]*\\}`, "u").test(targetContent);
if (!hasNamedExport) {
errors.push(
`main.ts 导入 { ${name} } from "${importPath}",但 ${targetPath} 中未检测到对应的命名导出`,
);
}
}
}
return { errors, warnings };
}
function runCommand(command, cwd) {
const startedAt = Date.now();
// #region debug-point B:command-start
......@@ -650,6 +712,7 @@ function run() {
const primaryDataResult = validatePrimaryFigmaDataAdherence({ response, bundle, bundlePath });
const visualSummaryResult = validateVisualSummaryAdherence({ response, bundle, bundlePath });
const routerConsistencyResult = validateRouterConsistency({ response });
const importConsistencyResult = validateLocalImportConsistency({ preview });
const commands = [
runCommand(`node scripts/lint-changed.mjs ${changedFiles.map((file) => `"${file}"`).join(" ")}`, repoRoot),
runCommand(`node scripts/review-trigger.mjs ${changedFiles.map((file) => `"${file}"`).join(" ")}`, repoRoot),
......@@ -669,6 +732,7 @@ function run() {
primaryDataResult.errors.length === 0 &&
visualSummaryResult.errors.length === 0 &&
routerConsistencyResult.errors.length === 0 &&
importConsistencyResult.errors.length === 0 &&
failedCommands.length === 0
? "passed"
: "failed";
......@@ -688,6 +752,7 @@ function run() {
primaryDataValidation: primaryDataResult,
visualSummaryValidation: visualSummaryResult,
routerConsistencyValidation: routerConsistencyResult,
importConsistencyValidation: importConsistencyResult,
commandResults: commands,
};
......@@ -763,6 +828,17 @@ function run() {
console.warn(`[ai-direct-validate-output] warning: ${warning}`);
}
if (importConsistencyResult.errors.length > 0) {
console.error("[ai-direct-validate-output] 本地导入一致性校验失败:");
for (const error of importConsistencyResult.errors) {
console.error(` - ${error}`);
}
}
for (const warning of importConsistencyResult.warnings) {
console.warn(`[ai-direct-validate-output] warning: ${warning}`);
}
if (failedCommands.length > 0) {
console.error("[ai-direct-validate-output] 命令校验失败:");
for (const item of failedCommands) {
......
......@@ -22,6 +22,11 @@ if (eslintFiles.length > 0) {
runCommand("pnpm", ["exec", "eslint", "--max-warnings=0", ...eslintFiles]);
}
const stylelintFiles = changedFiles.filter((file) => /\.(?:css|scss|vue)$/.test(file));
if (stylelintFiles.length > 0) {
runCommand("pnpm", ["exec", "stylelint", "--max-warnings=0", ...stylelintFiles]);
}
console.log("[lint-changed] passed");
function resolveChangedFiles() {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!