Commit cfc01f07 by liimin

feat(ai-toolchain): 新增二手车参拍页面并完善AI管线能力

- 新增二手车参拍详情页面Car.vue并在testpage-preview项目中注册对应路由
- 为AI生成的代码添加自动归因功能,生成co-author头部注释和.ai-attribution.json归因清单
- 重构文件预算检查脚本,新增Ratchet棘轮模式,避免超预算文件继续膨胀
- 为Fitness质量校验新增增量过滤逻辑,仅在存在相关文件变更时执行对应检查
- 更新AI治理文档,补充增量过滤、AI贡献追踪、文件预算棘轮机制的相关内容
- 优化AI管线相关脚本,完善参数传递、预览项目管理及文件查看功能
- 补充全局组件类型声明,新增VButton、VPopup的类型定义
- 添加阶段报告所需的文档图片
1 parent 768e63e2
{
"generator": "scripts/ai-direct-apply-output.mjs",
"generatedAt": "2026-06-04T06:59:25.024Z",
"model": "unknown",
"provider": "unknown",
"files": [
{
"path": "apps/web/ai-previews/testpage-preview/src/views/Car.vue",
"language": "vue",
"purpose": "广联二手车参拍详情页面",
"coAuthor": "@ai-co-author venus-ai-direct | unknown-provider/unknown-model | 2026-06-04T06:59:15.709Z",
"action": "updated"
}
]
}
...@@ -9,7 +9,9 @@ declare module 'vue' { ...@@ -9,7 +9,9 @@ declare module 'vue' {
export interface GlobalComponents { export interface GlobalComponents {
RouterLink: typeof import('vue-router')['RouterLink'] RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView'] RouterView: typeof import('vue-router')['RouterView']
VButton: typeof import('@vui/mobile')['VButton']
VNavBar: typeof import('@vui/mobile')['VNavBar'] VNavBar: typeof import('@vui/mobile')['VNavBar']
VPopup: typeof import('@vui/mobile')['VPopup']
VSearch: typeof import('@vui/mobile')['VSearch'] VSearch: typeof import('@vui/mobile')['VSearch']
} }
} }
...@@ -25,6 +25,15 @@ const routes = [ ...@@ -25,6 +25,15 @@ const routes = [
title: "TestPage", title: "TestPage",
}, },
}, },
{
path: "/car",
name: "Car",
component: () => import("@/views/Car.vue"),
meta: {
title: "Car",
},
},
]; ];
export function createRouter(): Router { export function createRouter(): Router {
......
...@@ -194,10 +194,76 @@ AI 设计到代码链路通过以下中间层保持可校验边界: ...@@ -194,10 +194,76 @@ AI 设计到代码链路通过以下中间层保持可校验边界:
- `Evolvability`:文件预算与登记热点上限 - `Evolvability`:文件预算与登记热点上限
- `AIArtifacts`:AI 中间产物结构完整性与语义字段覆盖率 - `AIArtifacts`:AI 中间产物结构完整性与语义字段覆盖率
### 增量 Fitness 过滤
AI 管线的 Fitness 检查支持增量过滤模式。当提供变更文件列表时,每个检查根据其 `triggers` 条件判断是否需要执行:
- `CodeQuality (typecheck)`:仅在 `.ts/.tsx/.vue/.jsx` 文件变更时执行
- `TemplateContract`:仅在 `packages/cli/templates/` 或 `contracts/templates/` 变更时执行
- `AIArtifacts`:仅在 `contracts/` 或 `.manifest.json/.schema.json` 变更时执行
- `ReviewTriggers`、`Evolvability`:脚本内置文件过滤逻辑,始终运行
未匹配触发条件的检查会被标记为 `skipped`,减少噪音并加速管线。
## 第七步:仓库级防线 ## 第七步:仓库级防线
`.github/workflows/defense.yml` 在仓库级别继续执行治理检查,确保本地未覆盖或未触发的问题仍能被拦截。 `.github/workflows/defense.yml` 在仓库级别继续执行治理检查,确保本地未覆盖或未触发的问题仍能被拦截。
## AI 贡献追踪
AI 管线生成的代码会自动添加归因标记,使 AI 贡献可追踪、可审计。
### Co-author 头部注释
每个 AI 生成的文件顶部会自动添加一行注释:
```javascript
// @ai-co-author venus-ai-direct | provider/model | 2026-06-04T12:00:00.000Z
```
这个标记:
- 标识文件由 AI 生成
- 记录使用的 provider 和 model
- 包含生成时间戳
### 归因清单文件
每个预览项目根目录会生成 `.ai-attribution.json`,记录:
- 生成时间
- 使用的 model 和 provider
- 所有 AI 生成/修改的文件列表
- 每个文件的语言、用途和 co-author 信息
这为后续的代码审查、质量分析和 AI 效果评估提供数据基础。
## 文件预算 Ratchet 机制
Ratchet(棘轮)机制针对**已超预算的大文件**,冻结其当前大小,防止继续膨胀。核心原则:**大文件只允许缩小,不允许增长;小文件在预算内可自由增长**。
### 工作原理
| 文件状态 | 标准模式 | Ratchet 模式 |
|---------|---------|-------------|
| 当前行数 ≤ 预算上限 | 通过 | 通过 |
| 当前行数 > 预算上限,比 HEAD 更大 | 违规 | Ratchet 膨胀违规 |
| 当前行数 > 预算上限,与 HEAD 相等 | 违规 | 冻结违规(要求缩小) |
| 当前行数 > 预算上限,比 HEAD 更小 | 违规 | **通过**(鼓励精简) |
| 新文件超预算 | 违规 | 标准违规 |
**关键设计**:Ratchet 只对已超预算的文件生效。小文件(在预算上限内)不受影响,可以正常增长到预算上限。
### 启用方式
```bash
# 标准模式:只检查绝对行数上限
pnpm run check:file-budget
# Ratchet 模式:超预算文件冻结基线,只允许缩小
node scripts/check-file-budgets.mjs --ratchet
```
AI 管线的 Fitness 检查默认启用 Ratchet 模式,防止 AI 生成导致大文件继续膨胀。
仓库级防线关注的不是单个文件是否运行,而是当前改动是否仍然满足工作区规则。 仓库级防线关注的不是单个文件是否运行,而是当前改动是否仍然满足工作区规则。
## 子项目目录中的治理规则 ## 子项目目录中的治理规则
......
...@@ -12,6 +12,8 @@ function parseCliArgs() { ...@@ -12,6 +12,8 @@ function parseCliArgs() {
const parsed = { const parsed = {
responseFile: "", responseFile: "",
previewFile: "", previewFile: "",
model: "",
provider: "",
}; };
for (let index = 0; index < args.length; index++) { for (let index = 0; index < args.length; index++) {
...@@ -24,6 +26,12 @@ function parseCliArgs() { ...@@ -24,6 +26,12 @@ function parseCliArgs() {
} else if (arg === "--preview-file" && next) { } else if (arg === "--preview-file" && next) {
parsed.previewFile = next; parsed.previewFile = next;
index++; index++;
} else if (arg === "--model" && next) {
parsed.model = next;
index++;
} else if (arg === "--provider" && next) {
parsed.provider = next;
index++;
} }
} }
...@@ -59,6 +67,36 @@ function runCommand(command, args, cwd) { ...@@ -59,6 +67,36 @@ function runCommand(command, args, cwd) {
}; };
} }
function buildCoAuthorHeader(model, provider) {
const timestamp = new Date().toISOString();
const tool = "venus-ai-direct";
const modelPart = model || "unknown-model";
const providerPart = provider || "unknown-provider";
const text = `@ai-co-author ${tool} | ${providerPart}/${modelPart} | ${timestamp}`;
return { text, line: `// ${text}` };
}
function prependCoAuthorHeader(filePath, headerLine) {
const existing = fs.readFileSync(filePath, "utf8");
if (existing.includes("@ai-co-author")) {
return;
}
fs.writeFileSync(filePath, `${headerLine}\n${existing}`, "utf8");
}
function writeAttributionManifest(projectRoot, attributionEntries, model, provider) {
const manifestPath = path.join(projectRoot, ".ai-attribution.json");
const manifest = {
generator: "scripts/ai-direct-apply-output.mjs",
generatedAt: new Date().toISOString(),
model: model || "unknown",
provider: provider || "unknown",
files: attributionEntries,
};
fs.writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
return manifestPath;
}
function runAutoFix(writtenFiles) { function runAutoFix(writtenFiles) {
if (writtenFiles.length === 0) { if (writtenFiles.length === 0) {
return []; return [];
...@@ -83,12 +121,22 @@ function runAutoFix(writtenFiles) { ...@@ -83,12 +121,22 @@ function runAutoFix(writtenFiles) {
} }
function validateResponseShape(response) { function validateResponseShape(response) {
for (const key of ["summary", "dependencyPlan", "previewProject", "files", "notes", "validationChecklist"]) { const requiredFields = ["summary", "dependencyPlan", "previewProject", "files"];
const optionalFields = ["notes", "validationChecklist"];
for (const key of requiredFields) {
if (!(key in response)) { if (!(key in response)) {
throw new Error(`AI 输出缺少字段: ${key}`); throw new Error(`AI 输出缺少字段: ${key}`);
} }
} }
// 为可选字段提供默认值
for (const key of optionalFields) {
if (!(key in response)) {
response[key] = [];
}
}
if (!Array.isArray(response.files) || response.files.length === 0) { if (!Array.isArray(response.files) || response.files.length === 0) {
throw new Error("AI 输出 files 必须是非空数组"); throw new Error("AI 输出 files 必须是非空数组");
} }
...@@ -247,6 +295,12 @@ function run() { ...@@ -247,6 +295,12 @@ function run() {
console.log("[ai-direct-apply-output] 应用 AI 结构化结果..."); console.log("[ai-direct-apply-output] 应用 AI 结构化结果...");
console.log(` → response: ${responsePath}`); console.log(` → response: ${responsePath}`);
console.log(` → project: ${projectRoot}`); console.log(` → project: ${projectRoot}`);
console.log(` → model: ${args.model || "unknown"}`);
console.log(` → provider: ${args.provider || "unknown"}`);
// AI 贡献追踪:构建 co-author 头部注释
const coAuthorHeader = buildCoAuthorHeader(args.model, args.provider);
const attributionEntries = [];
// 路由文件由模板生成,AI 不应覆盖;registerRoutesInRouter 会自动追加路由 // 路由文件由模板生成,AI 不应覆盖;registerRoutesInRouter 会自动追加路由
const routerFilePatterns = new Set(["src/router.ts", "src/router/index.ts"]); const routerFilePatterns = new Set(["src/router.ts", "src/router/index.ts"]);
...@@ -263,10 +317,22 @@ function run() { ...@@ -263,10 +317,22 @@ function run() {
const targetPath = resolveTargetPath(projectRoot, file.path); const targetPath = resolveTargetPath(projectRoot, file.path);
ensureDir(path.dirname(targetPath)); ensureDir(path.dirname(targetPath));
fs.writeFileSync(targetPath, file.content, "utf8"); fs.writeFileSync(targetPath, file.content, "utf8");
// 为 AI 生成的文件添加 co-author 头部注释
prependCoAuthorHeader(targetPath, coAuthorHeader.line);
const relativePath = normalizePath(path.relative(repoRoot, targetPath));
writtenFiles.push({ writtenFiles.push({
path: normalizePath(path.relative(repoRoot, targetPath)), path: relativePath,
language: file.language,
purpose: file.purpose,
});
attributionEntries.push({
path: relativePath,
language: file.language, language: file.language,
purpose: file.purpose, purpose: file.purpose,
coAuthor: coAuthorHeader.text,
action: fs.existsSync(targetPath) ? "updated" : "created",
}); });
} }
...@@ -294,6 +360,10 @@ function run() { ...@@ -294,6 +360,10 @@ function run() {
} }
} }
// 写入 AI 归因清单
const attributionPath = writeAttributionManifest(projectRoot, attributionEntries, args.model, args.provider);
console.log(`[ai-direct-apply-output] ✓ AI 归因清单已写入: ${normalizePath(path.relative(repoRoot, attributionPath))}`);
const summary = { const summary = {
meta: { meta: {
generator: "scripts/ai-direct-apply-output.mjs", generator: "scripts/ai-direct-apply-output.mjs",
...@@ -301,6 +371,13 @@ function run() { ...@@ -301,6 +371,13 @@ function run() {
responseFile: normalizePath(responsePath), responseFile: normalizePath(responsePath),
previewFile: normalizePath(previewPath), previewFile: normalizePath(previewPath),
}, },
attribution: {
model: args.model || "unknown",
provider: args.provider || "unknown",
coAuthorHeader: coAuthorHeader.text,
attributionFile: normalizePath(path.relative(repoRoot, attributionPath)),
fileCount: attributionEntries.length,
},
result: { result: {
projectRoot: normalizePath(projectRoot), projectRoot: normalizePath(projectRoot),
writtenFiles, writtenFiles,
...@@ -319,6 +396,7 @@ function run() { ...@@ -319,6 +396,7 @@ function run() {
console.log("[ai-direct-apply-output] ✓ 完成"); console.log("[ai-direct-apply-output] ✓ 完成");
console.log(` → written files: ${writtenFiles.length}`); console.log(` → written files: ${writtenFiles.length}`);
console.log(` → AI 归因: ${attributionEntries.length} 个文件已标记 co-author`);
console.log(` → summary: ${summaryPath}`); console.log(` → summary: ${summaryPath}`);
} }
......
...@@ -265,21 +265,62 @@ function runEnvironmentPreCheck() { ...@@ -265,21 +265,62 @@ function runEnvironmentPreCheck() {
console.log("[ai-direct-execute] ✓ [0/8] 环境预检完成"); console.log("[ai-direct-execute] ✓ [0/8] 环境预检完成");
} }
// [5] Fitness 全维度校验 // [5] Fitness 全维度校验(增量过滤模式)
function runFitnessChecks() { function runFitnessChecks(changedFiles = []) {
console.log("[ai-direct-execute] ⏳ [5/8] 质量校验 — 执行 Fitness 全维度校验..."); console.log("[ai-direct-execute] ⏳ [5/8] 质量校验 — 执行 Fitness 全维度校验...");
if (changedFiles.length > 0) {
console.log(`[ai-direct-execute] → 增量模式: ${changedFiles.length} 个变更文件`);
}
const shell = process.platform === "win32"; const shell = process.platform === "win32";
const checks = [ const checks = [
{ name: "CodeQuality (typecheck)", cmd: "pnpm run check:type" }, {
{ name: "TemplateContract", cmd: "pnpm run check:template-contract" }, name: "CodeQuality (typecheck)",
{ name: "ReviewTriggers", cmd: "pnpm run review:trigger" }, cmd: "pnpm run check:type",
{ name: "Evolvability (file-budget)", cmd: "pnpm run check:file-budget" }, triggers: [/\.(ts|tsx|vue|jsx|mts|cts)$/],
{ name: "AIArtifacts", cmd: "pnpm run check:ai-artifacts" }, },
{
name: "TemplateContract",
cmd: "pnpm run check:template-contract",
triggers: [/^packages\/cli\/templates\//, /^contracts\/templates\//],
},
{
name: "ReviewTriggers",
cmd: "pnpm run review:trigger",
triggers: [], // 脚本内置文件过滤
},
{
name: "Evolvability (file-budget)",
cmd: "pnpm run check:file-budget",
triggers: [], // 脚本内置文件过滤
},
{
name: "Evolvability (ratchet)",
cmd: "node scripts/check-file-budgets.mjs --ratchet",
triggers: [], // 脚本内置文件过滤
},
{
name: "AIArtifacts",
cmd: "pnpm run check:ai-artifacts",
triggers: [/^contracts\//, /\.manifest\.json$/, /\.schema\.json$/],
},
]; ];
const results = []; const results = [];
let skippedCount = 0;
for (const check of checks) { for (const check of checks) {
// 增量过滤:如果提供了变更文件列表且检查有触发条件,则检查是否匹配
if (changedFiles.length > 0 && check.triggers.length > 0) {
const hasTrigger = changedFiles.some((file) => check.triggers.some((pattern) => pattern.test(file)));
if (!hasTrigger) {
console.log(`[ai-direct-execute] ⏭ Fitness ${check.name}: 跳过(无相关变更)`);
results.push({ name: check.name, status: "skipped", reason: "no relevant changes" });
skippedCount++;
continue;
}
}
console.log(`[ai-direct-execute] → 执行 ${check.name}...`); console.log(`[ai-direct-execute] → 执行 ${check.name}...`);
try { try {
childProcess.execSync(check.cmd, { cwd: repoRoot, stdio: "pipe", timeout: 120_000, shell }); childProcess.execSync(check.cmd, { cwd: repoRoot, stdio: "pipe", timeout: 120_000, shell });
...@@ -293,8 +334,9 @@ function runFitnessChecks() { ...@@ -293,8 +334,9 @@ function runFitnessChecks() {
} }
} }
const passed = results.filter((r) => r.status === "pass").length; const executed = results.filter((r) => r.status !== "skipped");
console.log(`[ai-direct-execute] ✓ [5/8] Fitness 汇总: ${passed}/${results.length} 维度通过`); const passed = executed.filter((r) => r.status === "pass").length;
console.log(`[ai-direct-execute] ✓ [5/8] Fitness 汇总: ${passed}/${executed.length} 通过${skippedCount > 0 ? `,${skippedCount} 跳过` : ""}`);
return results; return results;
} }
...@@ -912,12 +954,21 @@ async function run() { ...@@ -912,12 +954,21 @@ async function run() {
}); });
// #endregion // #endregion
console.log(`[ai-direct-execute] → 开始应用 AI 输出...`); console.log(`[ai-direct-execute] → 开始应用 AI 输出...`);
runNodeScript("ai-direct-apply-output.mjs", [ const applyArgs = [
"--response-file", "--response-file",
aiResult.responsePath, aiResult.responsePath,
"--preview-file", "--preview-file",
previewPath, previewPath,
]); ];
if (args.model) {
applyArgs.push("--model", args.model);
} else if (process.env.AI_DIRECT_OPENAI_MODEL) {
applyArgs.push("--model", process.env.AI_DIRECT_OPENAI_MODEL);
}
if (args.provider) {
applyArgs.push("--provider", args.provider);
}
runNodeScript("ai-direct-apply-output.mjs", applyArgs);
console.log("[ai-direct-execute] ✓ [4/8] AI 生成完成(代码已应用 + 路由已注册)"); console.log("[ai-direct-execute] ✓ [4/8] AI 生成完成(代码已应用 + 路由已注册)");
console.log("[ai-direct-execute] ⏳ [5/8] 质量校验 — validate + fitness 全维度 + smart-check..."); console.log("[ai-direct-execute] ⏳ [5/8] 质量校验 — validate + fitness 全维度 + smart-check...");
...@@ -1070,8 +1121,17 @@ async function run() { ...@@ -1070,8 +1121,17 @@ async function run() {
console.log(` → summary: ${summaryPath}`); console.log(` → summary: ${summaryPath}`);
// Fitness 全维度校验 // Fitness 全维度校验(增量过滤模式)
const fitnessResults = runFitnessChecks(); const previewProjectRoot = preview.previewProject?.projectRoot || "";
const aiChangedFiles = plainResponse.files.map((f) => {
const filePath = f.path.replaceAll("\\", "/");
// 转换为仓库相对路径
if (previewProjectRoot) {
return normalizePath(path.relative(repoRoot, path.join(previewProjectRoot, filePath)));
}
return filePath;
});
const fitnessResults = runFitnessChecks(aiChangedFiles);
const failedFitness = fitnessResults.filter((r) => r.status === "fail"); const failedFitness = fitnessResults.filter((r) => r.status === "fail");
summary.fitnessResults = fitnessResults; summary.fitnessResults = fitnessResults;
...@@ -1097,13 +1157,18 @@ async function run() { ...@@ -1097,13 +1157,18 @@ async function run() {
} }
// 人工确认 // 人工确认
const skippedFitness = fitnessResults.filter((r) => r.status === "skipped");
const executedFitness = fitnessResults.filter((r) => r.status !== "skipped");
console.log("[ai-direct-execute] ⏳ [8/8] 人工确认 — 查看控制台 Fitness 报告 + 预览 + 文件浏览"); console.log("[ai-direct-execute] ⏳ [8/8] 人工确认 — 查看控制台 Fitness 报告 + 预览 + 文件浏览");
console.log(`[ai-direct-execute] → Summary: ${summaryPath}`); console.log(`[ai-direct-execute] → Summary: ${summaryPath}`);
console.log(`[ai-direct-execute] → 状态: ${summary.status}`); console.log(`[ai-direct-execute] → 状态: ${summary.status}`);
console.log(`[ai-direct-execute] → Fitness: ${fitnessResults.filter((r) => r.status === "pass").length}/${fitnessResults.length} 通过`); console.log(`[ai-direct-execute] → Fitness: ${executedFitness.filter((r) => r.status === "pass").length}/${executedFitness.length} 通过${skippedFitness.length > 0 ? `,${skippedFitness.length} 跳过` : ""}`);
if (failedFitness.length > 0) { if (failedFitness.length > 0) {
console.log(`[ai-direct-execute] → ⚠ 未通过: ${failedFitness.map((f) => f.name).join(", ")}`); console.log(`[ai-direct-execute] → ⚠ 未通过: ${failedFitness.map((f) => f.name).join(", ")}`);
} }
if (skippedFitness.length > 0) {
console.log(`[ai-direct-execute] → ⏭ 跳过: ${skippedFitness.map((f) => f.name).join(", ")}`);
}
if (summary.repairArtifacts) { if (summary.repairArtifacts) {
console.log(`[ai-direct-execute] → Repair feedback: ${summary.repairArtifacts.feedbackFile}`); console.log(`[ai-direct-execute] → Repair feedback: ${summary.repairArtifacts.feedbackFile}`);
console.log(`[ai-direct-execute] → Repair request: ${summary.repairArtifacts.requestFile}`); console.log(`[ai-direct-execute] → Repair request: ${summary.repairArtifacts.requestFile}`);
......
...@@ -79,16 +79,34 @@ function listPreviewProjects() { ...@@ -79,16 +79,34 @@ function listPreviewProjects() {
} }
function listBundlePages() { function listBundlePages() {
const dir = path.join(repoRoot, "apps/web/ai-workspace/.ai-direct"); const previewDir = path.join(repoRoot, PREVIEW_DIR);
if (!fs.existsSync(dir)) return []; if (!fs.existsSync(previewDir)) return [];
return fs.readdirSync(dir, { withFileTypes: true })
.filter(e => e.isDirectory()) const results = [];
.map(e => { const projects = fs.readdirSync(previewDir, { withFileTypes: true })
const files = fs.readdirSync(path.join(dir, e.name)); .filter(e => e.isDirectory());
for (const project of projects) {
const aiDir = path.join(previewDir, project.name, ".ai-direct");
if (!fs.existsSync(aiDir)) continue;
const pages = fs.readdirSync(aiDir, { withFileTypes: true })
.filter(e => e.isDirectory());
for (const page of pages) {
const pageDir = path.join(aiDir, page.name);
const files = fs.readdirSync(pageDir);
const bundle = files.find(f => f.endsWith(".ai-direct-context-bundle.json")); const bundle = files.find(f => f.endsWith(".ai-direct-context-bundle.json"));
return { slug: e.name, bundleFile: bundle ? path.join(dir, e.name, bundle) : null }; if (bundle) {
}) results.push({
.filter(p => p.bundleFile); slug: `${project.name}/${page.name}`,
bundleFile: path.join(pageDir, bundle),
});
}
}
}
return results;
} }
function listGeneratedFiles(projectRoot) { function listGeneratedFiles(projectRoot) {
...@@ -100,7 +118,7 @@ function listGeneratedFiles(projectRoot) { ...@@ -100,7 +118,7 @@ function listGeneratedFiles(projectRoot) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const relPath = prefix ? `${prefix}/${entry.name}` : entry.name; const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
if (entry.isDirectory()) walk(path.join(dir, entry.name), relPath); if (entry.isDirectory()) walk(path.join(dir, entry.name), relPath);
else if (/\.(vue|ts|tsx|css|scss)$/.test(entry.name)) else if (/\.(?:vue|ts|tsx|css|scss)$/.test(entry.name))
results.push({ path: `src/views/${relPath}`, fullPath: path.join(dir, entry.name) }); results.push({ path: `src/views/${relPath}`, fullPath: path.join(dir, entry.name) });
} }
} }
...@@ -168,23 +186,40 @@ async function runPipeline(config) { ...@@ -168,23 +186,40 @@ async function runPipeline(config) {
const args = ["scripts/ai-direct-execute.mjs"]; const args = ["scripts/ai-direct-execute.mjs"];
// 清理空字符串参数 // 清理空字符串参数
const bundleFile = config.bundleFile?.trim() || null;
const figmaUrl = config.figmaUrl?.trim() || null; const figmaUrl = config.figmaUrl?.trim() || null;
const existingProject = config.existingProject?.trim() || null;
if (!figmaUrl) {
broadcast("error", { message: "必须提供 Figma URL" });
broadcast("status", { running: false, step: "error" });
isRunning = false;
stopHeartbeat();
return;
}
if (bundleFile) { if (existingProject) {
args.push("--bundle-file", bundleFile); // 追加到已有项目模式
log(`使用已有 bundle: ${bundleFile}`); const existingRoot = path.join(repoRoot, PREVIEW_DIR, existingProject);
} else if (figmaUrl) { if (!fs.existsSync(existingRoot)) {
// 新建页面模式:智能选择参考项目 broadcast("error", { message: `已有项目不存在: ${existingProject}` });
broadcast("status", { running: false, step: "error" });
isRunning = false;
stopHeartbeat();
return;
}
args.push("--project-dir", existingRoot, "--figma-url", figmaUrl, "--existing-preview-project-root", existingRoot);
if (config.pageName?.trim()) args.push("--page-name", config.pageName.trim());
if (config.refreshContext) args.push("--refresh-context");
log(`追加到已有项目: ${existingProject}`);
} else {
// 新建预览项目模式:智能选择参考项目
let projectDir = config.projectDir?.trim() || null; let projectDir = config.projectDir?.trim() || null;
if (!projectDir) { if (!projectDir) {
// 优先使用已有的预览项目作为参考
const previews = listPreviewProjects(); const previews = listPreviewProjects();
if (previews.length > 0) { if (previews.length > 0) {
projectDir = previews[0].path; projectDir = previews[0].path;
log(`使用已有预览项目作为参考: ${previews[0].name}`); log(`使用已有预览项目作为参考: ${previews[0].name}`);
} else { } else {
// 没有预览项目,使用仓库根目录
projectDir = "."; projectDir = ".";
log("使用仓库根目录作为项目参考"); log("使用仓库根目录作为项目参考");
} }
...@@ -192,12 +227,6 @@ async function runPipeline(config) { ...@@ -192,12 +227,6 @@ async function runPipeline(config) {
args.push("--project-dir", projectDir, "--figma-url", figmaUrl); args.push("--project-dir", projectDir, "--figma-url", figmaUrl);
if (config.pageName?.trim()) args.push("--page-name", config.pageName.trim()); if (config.pageName?.trim()) args.push("--page-name", config.pageName.trim());
if (config.refreshContext) args.push("--refresh-context"); if (config.refreshContext) args.push("--refresh-context");
} else {
broadcast("error", { message: "必须提供 Figma URL 或选择已有的 Context Bundle" });
broadcast("status", { running: false, step: "error" });
isRunning = false;
stopHeartbeat();
return;
} }
args.push("--provider", "openai-compatible", "--model", config.aiModel || DEFAULT_CONFIG.aiModel, "--auto-repair", "--without-variables", "--preview-dir", PREVIEW_DIR); args.push("--provider", "openai-compatible", "--model", config.aiModel || DEFAULT_CONFIG.aiModel, "--auto-repair", "--without-variables", "--preview-dir", PREVIEW_DIR);
if (config.force !== false) args.push("--force"); if (config.force !== false) args.push("--force");
...@@ -234,8 +263,8 @@ async function runPipeline(config) { ...@@ -234,8 +263,8 @@ async function runPipeline(config) {
const text = data.toString(); const text = data.toString();
broadcast("output", { stream: "stdout", text, timestamp: Date.now() }); broadcast("output", { stream: "stdout", text, timestamp: Date.now() });
// 检测 Vite dev server URL // 检测 Vite dev server URL (支持多种格式)
const viteMatch = text.match(/Local:\s+(https?:\/\/localhost:\d+\/?)/); const viteMatch = text.match(/Local:\s+(https?:\/\/(?:localhost|127\.0\.0\.1):\d+\/?)/);
if (viteMatch) { if (viteMatch) {
setPreviewUrl(viteMatch[1]); setPreviewUrl(viteMatch[1]);
} }
...@@ -315,19 +344,35 @@ async function runPipeline(config) { ...@@ -315,19 +344,35 @@ async function runPipeline(config) {
const projects = listPreviewProjects(); const projects = listPreviewProjects();
let target = null; let target = null;
if (config.pageName) {
// 优先使用 existingProject 匹配
if (config.existingProject) {
target = projects.find(p => p.name === config.existingProject);
log(`尝试匹配已有项目: ${config.existingProject} → ${target ? "找到" : "未找到"}`);
}
// 其次使用 pageName 匹配
if (!target && config.pageName) {
target = projects.find(p => p.name.includes(config.pageName.toLowerCase())); target = projects.find(p => p.name.includes(config.pageName.toLowerCase()));
if (target) log(`通过 pageName 匹配: ${config.pageName} → ${target.name}`);
} }
// 最后使用最近修改的项目
if (!target && projects.length > 0) { if (!target && projects.length > 0) {
// 找不到匹配的项目,取最近修改的
target = projects.sort((a, b) => { target = projects.sort((a, b) => {
const aStat = fs.statSync(a.path); const aStat = fs.statSync(a.path);
const bStat = fs.statSync(b.path); const bStat = fs.statSync(b.path);
return bStat.mtimeMs - aStat.mtimeMs; return bStat.mtimeMs - aStat.mtimeMs;
})[0]; })[0];
log(`使用最近修改的项目: ${target.name}`);
} }
if (target) { if (target) {
broadcast("files", { project: target.name, files: listGeneratedFiles(target.path) }); const files = listGeneratedFiles(target.path);
log(`广播文件列表: ${target.name}, ${files.length} 个文件`);
broadcast("files", { project: target.name, files });
} else {
log(`未找到预览项目,无法广播文件列表`);
} }
}); });
...@@ -378,10 +423,26 @@ const server = http.createServer(async (req, res) => { ...@@ -378,10 +423,26 @@ const server = http.createServer(async (req, res) => {
if (req.method === "GET" && p === "/api/file") { if (req.method === "GET" && p === "/api/file") {
const fp = url.searchParams.get("path"); const fp = url.searchParams.get("path");
if (!fp) { res.writeHead(400); res.end("path required"); return; } if (!fp) { res.writeHead(400); res.end("path required"); return; }
const full = path.resolve(path.join(repoRoot, PREVIEW_DIR, fp));
if (!full.startsWith(path.resolve(path.join(repoRoot, PREVIEW_DIR)))) { res.writeHead(403); res.end("forbidden"); return; } // 支持绝对路径和相对路径,但限制在仓库根目录内
try { res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" }); res.end(await fsp.readFile(full, "utf8")); } let full;
catch { res.writeHead(404); res.end("not found"); } if (path.isAbsolute(fp)) {
full = path.resolve(fp);
} else {
full = path.resolve(path.join(repoRoot, fp));
}
// 安全检查:只允许读取仓库根目录内的文件
if (!full.startsWith(path.resolve(repoRoot))) {
res.writeHead(403); res.end("forbidden"); return;
}
try {
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
res.end(await fsp.readFile(full, "utf8"));
} catch {
res.writeHead(404); res.end("not found");
}
return; return;
} }
if (req.method === "GET" && p === "/api/status") { if (req.method === "GET" && p === "/api/status") {
......
...@@ -46,12 +46,14 @@ body { font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial, ...@@ -46,12 +46,14 @@ body { font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Helvetica,Arial,
.sidebar::-webkit-scrollbar { width:4px; } .sidebar::-webkit-scrollbar { width:4px; }
.sidebar::-webkit-scrollbar-thumb { background:var(--border); border-radius:4px; } .sidebar::-webkit-scrollbar-thumb { background:var(--border); border-radius:4px; }
.section { background:var(--surface-2); border:1px solid var(--border); border-radius:8px; overflow:hidden; } .section { background:var(--surface-2); border:1px solid var(--border); border-radius:8px; }
.section-header { display:flex; align-items:center; justify-content:space-between; padding:10px 12px; cursor:pointer; user-select:none; font-size:13px; font-weight:600; } .section-header { display:flex; align-items:center; justify-content:space-between; padding:10px 12px; cursor:pointer; user-select:none; font-size:13px; font-weight:600; }
.section-header:hover { background:rgba(255,255,255,0.03); } .section-header:hover { background:rgba(255,255,255,0.03); }
.section-header .arrow { transition:transform 0.2s; font-size:10px; color:var(--text-dim); } .section-header .arrow { transition:transform 0.2s; font-size:10px; color:var(--text-dim); }
.section-header .arrow.open { transform:rotate(90deg); } .section-header .arrow.open { transform:rotate(90deg); }
.section-body { padding:8px 12px 12px; display:flex; flex-direction:column; gap:8px; } .section-body { padding:8px 12px 12px; display:flex; flex-direction:column; gap:8px; max-height:45vh; overflow-y:auto; }
.section-body::-webkit-scrollbar { width:4px; }
.section-body::-webkit-scrollbar-thumb { background:var(--border); border-radius:4px; }
.section-body.hidden { display:none; } .section-body.hidden { display:none; }
label { font-size:12px; color:var(--text-dim); display:flex; flex-direction:column; gap:3px; } label { font-size:12px; color:var(--text-dim); display:flex; flex-direction:column; gap:3px; }
...@@ -96,6 +98,8 @@ select { cursor:pointer; } ...@@ -96,6 +98,8 @@ select { cursor:pointer; }
.console-line.warning { color:var(--warn); } .console-line.warning { color:var(--warn); }
.console-line.info { color:var(--accent); } .console-line.info { color:var(--accent); }
.console-line.dim { color:var(--text-dim); } .console-line.dim { color:var(--text-dim); }
.file-link { color:var(--accent); text-decoration:underline; text-decoration-style:dotted; cursor:pointer; transition:color 0.2s; }
.file-link:hover { color:var(--accent-bg); text-decoration-style:solid; }
.heartbeat-live { animation:hbPulse 1.2s ease-in-out infinite; } .heartbeat-live { animation:hbPulse 1.2s ease-in-out infinite; }
@keyframes hbPulse { 0%,100%{opacity:0.5} 50%{opacity:1} } @keyframes hbPulse { 0%,100%{opacity:0.5} 50%{opacity:1} }
.console-empty { color:var(--text-dim); text-align:center; padding-top:40vh; } .console-empty { color:var(--text-dim); text-align:center; padding-top:40vh; }
...@@ -145,9 +149,9 @@ select { cursor:pointer; } ...@@ -145,9 +149,9 @@ select { cursor:pointer; }
<div class="section"> <div class="section">
<div class="section-header" onclick="toggleSection(this)"> <div class="section-header" onclick="toggleSection(this)">
<span>AI 模型配置</span> <span>AI 模型配置</span>
<span class="arrow open">&#9654;</span> <span class="arrow">&#9654;</span>
</div> </div>
<div class="section-body"> <div class="section-body hidden">
<label>模型 <label>模型
<select id="aiModel"></select> <select id="aiModel"></select>
</label> </label>
...@@ -169,9 +173,9 @@ select { cursor:pointer; } ...@@ -169,9 +173,9 @@ select { cursor:pointer; }
<div class="section"> <div class="section">
<div class="section-header" onclick="toggleSection(this)"> <div class="section-header" onclick="toggleSection(this)">
<span>Figma 配置</span> <span>Figma 配置</span>
<span class="arrow open">&#9654;</span> <span class="arrow">&#9654;</span>
</div> </div>
<div class="section-body"> <div class="section-body hidden">
<label>Figma API Key <label>Figma API Key
<input type="password" id="figmaApiKey" placeholder="figd_..."> <input type="password" id="figmaApiKey" placeholder="figd_...">
</label> </label>
...@@ -184,13 +188,13 @@ select { cursor:pointer; } ...@@ -184,13 +188,13 @@ select { cursor:pointer; }
<div class="section"> <div class="section">
<div class="section-header" onclick="toggleSection(this)"> <div class="section-header" onclick="toggleSection(this)">
<span>项目配置</span> <span>项目配置</span>
<span class="arrow open">&#9654;</span> <span class="arrow">&#9654;</span>
</div> </div>
<div class="section-body"> <div class="section-body hidden">
<label>项目来源 <label>项目来源
<select id="projectSource" onchange="onProjectSourceChange()"> <select id="projectSource" onchange="onProjectSourceChange()">
<option value="new">新建预览项目</option> <option value="new">新建预览项目</option>
<option value="bundle">已有 Context Bundle</option> <option value="append">追加到已有项目</option>
</select> </select>
</label> </label>
<div id="newProjectOptions"> <div id="newProjectOptions">
...@@ -198,9 +202,12 @@ select { cursor:pointer; } ...@@ -198,9 +202,12 @@ select { cursor:pointer; }
<input type="text" id="pageName" placeholder="AllocationConfirmation"> <input type="text" id="pageName" placeholder="AllocationConfirmation">
</label> </label>
</div> </div>
<div id="bundleOptions" style="display:none"> <div id="appendOptions" style="display:none">
<label>选择已有 Bundle <label>选择已有项目
<select id="bundleSelect"></select> <select id="projectSelect"></select>
</label>
<label>新页面名称 (PascalCase)
<input type="text" id="appendPageName" placeholder="NewPage">
</label> </label>
</div> </div>
<label class="checkbox-row"> <label class="checkbox-row">
...@@ -341,12 +348,12 @@ function init() { ...@@ -341,12 +348,12 @@ function init() {
function loadProjects() { function loadProjects() {
fetch('/api/projects').then(r=>r.json()).then(data => { fetch('/api/projects').then(r=>r.json()).then(data => {
const sel = document.getElementById('bundleSelect'); const sel = document.getElementById('projectSelect');
sel.innerHTML = ''; sel.innerHTML = '';
data.bundlePages.forEach(p => { data.previewProjects.forEach(p => {
const opt = document.createElement('option'); const opt = document.createElement('option');
opt.value = p.bundleFile; opt.value = p.name;
opt.textContent = p.slug; opt.textContent = p.name;
sel.appendChild(opt); sel.appendChild(opt);
}); });
}); });
...@@ -390,6 +397,63 @@ function connectSSE() { ...@@ -390,6 +397,63 @@ function connectSSE() {
}); });
} }
function linkifyFilePaths(text) {
// 匹配文件路径的正则表达式
// 支持:绝对路径(Windows/Unix)、相对路径、带行号的路径
const filePathRegex = /(?:(?:[A-Z]:[\\\/])?(?:[\w\-\.\+]+[\\\/])+[\w\-\.\+]+\.\w+(?:\:\d+(?:\:\d+)?)?)/g;
return text.replace(filePathRegex, (match) => {
// 提取行号信息(如果存在)
let filePath = match;
let lineNum = '';
const lineMatch = match.match(/^(.+?)(\:\d+(?:\:\d+)?)$/);
if (lineMatch) {
filePath = lineMatch[1];
lineNum = lineMatch[2];
}
// 转义 HTML 特殊字符
const escapedPath = match
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;');
// 使用 data-path 属性,点击时在浏览器内查看
return `<a href="#" class="file-link" data-path="${filePath}" onclick="viewFile(event, '${filePath.replace(/\\/g, '\\\\')}')" title="点击在浏览器中查看">${escapedPath}</a>`;
});
}
function viewFile(event, filePath) {
event.preventDefault();
event.stopPropagation();
// 切换到生成文件标签页
switchTab('files', document.querySelector('.tab[onclick*="files"]'));
// 请求文件内容
fetch(`/api/file?path=${encodeURIComponent(filePath)}`)
.then(r => {
if (!r.ok) throw new Error('文件不存在');
return r.text();
})
.then(content => {
const viewer = document.getElementById('codeViewer');
viewer.innerHTML = `
<div class="file-path">${filePath}</div>
<pre><code>${content
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')}</code></pre>
`;
})
.catch(err => {
const viewer = document.getElementById('codeViewer');
viewer.innerHTML = `<div class="code-empty">无法加载文件: ${filePath}<br><small>${err.message}</small></div>`;
});
}
function appendConsole(text, stream) { function appendConsole(text, stream) {
const el = document.getElementById('consoleOutput'); const el = document.getElementById('consoleOutput');
if (el.querySelector('.console-empty')) el.innerHTML = ''; if (el.querySelector('.console-empty')) el.innerHTML = '';
...@@ -455,7 +519,8 @@ function appendConsole(text, stream) { ...@@ -455,7 +519,8 @@ function appendConsole(text, stream) {
} }
div.className = cls; div.className = cls;
div.textContent = line; // 将文件路径转换为可点击链接
div.innerHTML = linkifyFilePaths(line);
el.appendChild(div); el.appendChild(div);
}); });
el.scrollTop = el.scrollHeight; el.scrollTop = el.scrollHeight;
...@@ -562,21 +627,24 @@ function startGenerate() { ...@@ -562,21 +627,24 @@ function startGenerate() {
}; };
const source = document.getElementById('projectSource').value; const source = document.getElementById('projectSource').value;
if (source === 'bundle') {
const bundleFile = document.getElementById('bundleSelect').value.trim();
if (!bundleFile) {
alert('请选择一个已有的 Context Bundle');
return;
}
config.bundleFile = bundleFile;
} else {
const figmaUrl = document.getElementById('figmaUrl').value.trim(); const figmaUrl = document.getElementById('figmaUrl').value.trim();
const pageName = document.getElementById('pageName').value.trim();
if (!figmaUrl) { if (!figmaUrl) {
alert('请提供 Figma URL'); alert('请提供 Figma URL');
return; return;
} }
config.figmaUrl = figmaUrl; config.figmaUrl = figmaUrl;
if (source === 'append') {
const projectName = document.getElementById('projectSelect').value.trim();
const appendPageName = document.getElementById('appendPageName').value.trim();
if (!projectName) {
alert('请选择一个已有的预览项目');
return;
}
config.existingProject = projectName;
if (appendPageName) config.pageName = appendPageName;
} else {
const pageName = document.getElementById('pageName').value.trim();
if (pageName) config.pageName = pageName; if (pageName) config.pageName = pageName;
} }
...@@ -603,7 +671,7 @@ function toggleSection(header) { ...@@ -603,7 +671,7 @@ function toggleSection(header) {
function onProjectSourceChange() { function onProjectSourceChange() {
const v = document.getElementById('projectSource').value; const v = document.getElementById('projectSource').value;
document.getElementById('newProjectOptions').style.display = v === 'new' ? '' : 'none'; document.getElementById('newProjectOptions').style.display = v === 'new' ? '' : 'none';
document.getElementById('bundleOptions').style.display = v === 'bundle' ? '' : 'none'; document.getElementById('appendOptions').style.display = v === 'append' ? '' : 'none';
} }
function onUrlSelectChange(sel) { function onUrlSelectChange(sel) {
......
...@@ -10,6 +10,7 @@ import { requireWorkspaceRoot } from "./workspace-root.mjs"; ...@@ -10,6 +10,7 @@ import { requireWorkspaceRoot } from "./workspace-root.mjs";
const repoRoot = requireWorkspaceRoot(); const repoRoot = requireWorkspaceRoot();
const configPath = path.join(repoRoot, "tools", "fitness", "file-budgets.json"); const configPath = path.join(repoRoot, "tools", "fitness", "file-budgets.json");
const config = JSON.parse(fs.readFileSync(configPath, "utf8")); const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
const ratchetMode = process.argv.includes("--ratchet");
const changedFiles = resolveChangedFiles().filter((file) => fs.existsSync(path.join(repoRoot, file))); const changedFiles = resolveChangedFiles().filter((file) => fs.existsSync(path.join(repoRoot, file)));
if (changedFiles.length === 0) { if (changedFiles.length === 0) {
...@@ -18,6 +19,8 @@ if (changedFiles.length === 0) { ...@@ -18,6 +19,8 @@ if (changedFiles.length === 0) {
} }
const violations = []; const violations = [];
// 标准预算检查 + Ratchet 棘轮
for (const file of changedFiles) { for (const file of changedFiles) {
const ext = path.extname(file); const ext = path.extname(file);
const defaultMax = config.defaults[ext]; const defaultMax = config.defaults[ext];
...@@ -26,42 +29,77 @@ for (const file of changedFiles) { ...@@ -26,42 +29,77 @@ for (const file of changedFiles) {
continue; continue;
} }
const lines = countLines(file); const currentLines = countLines(file);
if (hotspotMax !== undefined) { const maxLimit = hotspotMax ?? defaultMax;
if (lines > hotspotMax) { const limitType = hotspotMax !== undefined ? "hotspot" : "budget";
violations.push({
type: "hotspot", if (currentLines <= maxLimit) {
file, // 文件在预算内,正常通过
lines, continue;
max: hotspotMax,
});
} }
if (!ratchetMode) {
// 非 Ratchet 模式:标准预算违规
violations.push({ type: limitType, file, lines: currentLines, max: maxLimit });
continue;
}
// Ratchet 模式:文件已超预算,用 HEAD 基线冻结,只允许缩小不允许膨胀
const baselineLines = countLinesInGitHead(file);
if (baselineLines === null) {
// 新文件且超预算,标准违规
violations.push({ type: limitType, file, lines: currentLines, max: maxLimit });
continue; continue;
} }
if (lines > defaultMax) { if (currentLines > baselineLines) {
// 比 HEAD 更大 → 棘轮膨胀违规
violations.push({ violations.push({
type: "budget", type: "ratchet",
file, file,
lines, lines: currentLines,
max: defaultMax, baseline: baselineLines,
delta: currentLines - baselineLines,
}); });
} else if (currentLines === baselineLines) {
// 与 HEAD 相等且超预算 → 冻结违规(要求缩小)
violations.push({ type: limitType, file, lines: currentLines, max: maxLimit });
} }
// currentLines < baselineLines → 在缩小,允许通过(鼓励精简)
} }
if (violations.length > 0) { if (violations.length > 0) {
console.error("[file-budget] violated"); console.error("[file-budget] violated");
for (const violation of violations) { for (const violation of violations) {
if (violation.type === "ratchet") {
console.error(`- Ratchet 膨胀: ${violation.file} 当前 ${violation.lines} 行,基线 ${violation.baseline} 行(+${violation.delta} 行)`);
} else {
const label = violation.type === "hotspot" ? "热点冻结" : "文件预算"; const label = violation.type === "hotspot" ? "热点冻结" : "文件预算";
console.error(`- ${label}: ${violation.file} 当前 ${violation.lines} 行,允许上限 ${violation.max} 行`); console.error(`- ${label}: ${violation.file} 当前 ${violation.lines} 行,允许上限 ${violation.max} 行`);
} }
}
process.exit(1); process.exit(1);
} }
console.log("[file-budget] passed"); console.log(`[file-budget] passed${ratchetMode ? " (ratchet mode)" : ""}`);
function countLinesInGitHead(file) {
const result = childProcess.spawnSync("git", ["show", `HEAD:${file}`], {
cwd: repoRoot,
encoding: "utf8",
});
if (result.status !== 0 || !result.stdout) {
return null; // 文件不存在于 HEAD(新文件)
}
if (result.stdout.length === 0) {
return 0;
}
return result.stdout.split(/\r?\n/).length;
}
function resolveChangedFiles() { function resolveChangedFiles() {
const fromArgs = process.argv.slice(2).filter(Boolean); const fromArgs = process.argv.slice(2).filter((arg) => arg && !arg.startsWith("--"));
if (fromArgs.length > 0) { if (fromArgs.length > 0) {
return normalize(fromArgs); return normalize(fromArgs);
} }
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!