capture-ai-pitfalls.mjs 11.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
#!/usr/bin/env node

/**
 * AI Pitfall Auto-Capture
 *
 * 自动检测 AI 生成代码中的 lint / typecheck 错误,
 * 将错误模式提取为反模式条目,追加到 docs/ai/ai-anti-patterns.md。
 *
 * 工作流程:
 * 1. 收集带 @ai-co-author 标记的变更文件
 * 2. 对这些文件运行 ESLint / TypeScript 检查
 * 3. 提取错误模式,与已有条目去重
 * 4. 新条目追加到注册表
 *
 * 用法:
 *   pnpm run ai:capture-pitfalls              # 扫描所有变更的 AI 文件
 *   pnpm run ai:capture-pitfalls -- --all      # 扫描所有 AI 文件(不限变更)
 *   pnpm run ai:capture-pitfalls -- --dry-run  # 只检测,不写入
 */

import childProcess from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import process from "node:process";

import { requireWorkspaceRoot } from "./workspace-root.mjs";

const repoRoot = requireWorkspaceRoot();
const REGISTRY_PATH = path.join(repoRoot, "docs", "ai", "ai-anti-patterns.md");
const CO_AUTHOR_REGEX = /@ai-co-author\s+(\S+)\s*\|\s*(\S+)/;

// ── Lint Rule → Anti-Pattern Mapping ──

const RULE_CATEGORY_MAP = {
	"vue/no-unused-imports": { category: "component-misuse", scope: "vue-sfc" },
	"no-unused-vars": { category: "import-error", scope: "general" },
	"@typescript-eslint/no-unused-vars": { category: "import-error", scope: "typescript" },
	"perfectionist/sort-imports": { category: "import-error", scope: "general" },
	"import/order": { category: "import-error", scope: "general" },
	"stylelint/property-order": { category: "style-error", scope: "css" },
	"stylelint-config-recess-order": { category: "style-error", scope: "css" },
	"vue/no-v-for-template-key": { category: "template-error", scope: "vue-sfc" },
	"vue/no-v-model-argument": { category: "template-error", scope: "vue-sfc" },
	"vue/require-v-for-key": { category: "template-error", scope: "vue-sfc" },
	"vue/valid-v-for": { category: "template-error", scope: "vue-sfc" },
	"vue/no-unused-vars": { category: "template-error", scope: "vue-sfc" },
	"@typescript-eslint/no-explicit-any": { category: "type-error", scope: "typescript" },
	"no-unreachable": { category: "logic-error", scope: "general" },
	"no-constant-condition": { category: "logic-error", scope: "general" },
};

const DEFAULT_CATEGORY = { category: "other", scope: "general" };

// ── CLI ──

function parseCliArgs() {
	const args = process.argv.slice(2);
	return {
		all: args.includes("--all"),
		dryRun: args.includes("--dry-run"),
	};
}

// ── Step 1: Collect AI files ──

function getChangedFiles() {
	const commands = [
		"git diff --name-only",
		"git diff --cached --name-only",
		"git ls-files --others --exclude-standard",
	];

	const files = new Set();
	for (const cmd of commands) {
		const result = childProcess.spawnSync(cmd, {
			cwd: repoRoot,
			shell: true,
			encoding: "utf8",
		});
		if (result.status === 0 && result.stdout) {
			for (const line of result.stdout.trim().split(/\r?\n/)) {
				if (line) files.add(line.replaceAll("\\", "/"));
			}
		}
	}
	return [...files];
}

function getAllAiFiles() {
	const fileSet = new Set();

	const result = childProcess.spawnSync(
		'git ls-files -- "*.ts" "*.tsx" "*.vue" "*.js" "*.mjs" "*.uvue" "*.uts"',
		{ cwd: repoRoot, shell: true, encoding: "utf8" },
	);
	if (result.status === 0 && result.stdout) {
		for (const line of result.stdout.trim().split(/\r?\n/)) {
			if (line) fileSet.add(line.replaceAll("\\", "/"));
		}
	}

	const previewDir = path.join(repoRoot, "apps", "web", "ai-previews");
	if (fs.existsSync(previewDir)) {
		walkForAiFiles(previewDir, repoRoot, fileSet);
	}

	return [...fileSet];
}

function walkForAiFiles(dir, baseDir, fileSet) {
	let entries;
	try {
		entries = fs.readdirSync(dir, { withFileTypes: true });
	} catch {
		return;
	}

	for (const entry of entries) {
		const fullPath = path.join(dir, entry.name);
		if (entry.isDirectory()) {
			if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "dist") continue;
			walkForAiFiles(fullPath, baseDir, fileSet);
		} else if (entry.isFile()) {
			const ext = path.extname(entry.name).toLowerCase();
			if ([".ts", ".tsx", ".vue", ".js", ".mjs", ".uvue", ".uts"].includes(ext)) {
				fileSet.add(path.relative(baseDir, fullPath).replaceAll("\\", "/"));
			}
		}
	}
}

function hasCoAuthorHeader(filePath) {
	const absPath = path.join(repoRoot, filePath);
	if (!fs.existsSync(absPath)) return false;

	try {
		const fd = fs.openSync(absPath, "r");
		const buf = Buffer.alloc(512);
		const bytesRead = fs.readSync(fd, buf, 0, 512, 0);
		fs.closeSync(fd);

		const head = buf.toString("utf8", 0, bytesRead);
		return CO_AUTHOR_REGEX.test(head);
	} catch {
		return false;
	}
}

// ── Step 2: Run lint / typecheck ──

function runEslintOnFiles(files) {
	if (files.length === 0) return [];

	const tsFiles = files.filter((f) => /\.(ts|tsx|vue|js|mjs)$/.test(f));
	if (tsFiles.length === 0) return [];

	const result = childProcess.spawnSync(
		`npx eslint --format json ${tsFiles.map((f) => `"${f}"`).join(" ")}`,
		{ cwd: repoRoot, shell: true, encoding: "utf8", maxBuffer: 10 * 1024 * 1024 },
	);

	const errors = [];
	try {
		const parsed = JSON.parse(result.stdout || "[]");
		for (const fileResult of parsed) {
			for (const msg of fileResult.messages || []) {
				if (msg.severity === 2) {
					errors.push({
						file: fileResult.filePath.replace(repoRoot, "").replace(/^[\\/]/, "").replaceAll("\\", "/"),
						rule: msg.ruleId || "unknown",
						line: msg.line,
						column: msg.column,
						message: msg.message,
						type: "lint",
					});
				}
			}
		}
	} catch { /* eslint output may not be valid JSON */ }

	return errors;
}

function runTypecheckOnFiles(files) {
	if (files.length === 0) return [];

	const tsFiles = files.filter((f) => /\.(ts|tsx)$/.test(f));
	if (tsFiles.length === 0) return [];

	const result = childProcess.spawnSync(
		`npx tsc --noEmit --pretty false 2>&1`,
		{ cwd: repoRoot, shell: true, encoding: "utf8", maxBuffer: 10 * 1024 * 1024 },
	);

	const errors = [];
	const fileSet = new Set(files.map((f) => f.replaceAll("\\", "/")));

	if (result.stdout) {
		for (const line of result.stdout.split(/\r?\n/)) {
			const match = line.match(/^(.+?)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.+)$/);
			if (match) {
				const file = match[1].replaceAll("\\", "/");
				if (fileSet.has(file) || fileSet.size === 0) {
					errors.push({
						file,
						rule: match[4],
						line: Number.parseInt(match[2], 10),
						column: Number.parseInt(match[3], 10),
						message: match[5],
						type: "typecheck",
					});
				}
			}
		}
	}

	return errors;
}

// ── Step 3: Extract patterns & deduplicate ──

function categorizeError(rule) {
	for (const [pattern, mapping] of Object.entries(RULE_CATEGORY_MAP)) {
		if (rule.includes(pattern) || pattern.includes(rule)) {
			return mapping;
		}
	}
	return DEFAULT_CATEGORY;
}

function extractPatternKey(error) {
	const msg = error.message.slice(0, 60).toLowerCase().replace(/\s+/g, " ").trim();
	return `${error.rule}|${msg}`;
}

function loadExistingPatterns() {
	if (!fs.existsSync(REGISTRY_PATH)) return new Set();

	const content = fs.readFileSync(REGISTRY_PATH, "utf8");
	const patterns = new Set();

	const patternRegex = /"pattern":\s*"([^"]+)"/g;
	let match;
	while ((match = patternRegex.exec(content)) !== null) {
		patterns.add(match[1].toLowerCase());
	}

	const ruleRegex = /"sourceRule":\s*"([^"]+)"/g;
	while ((match = ruleRegex.exec(content)) !== null) {
		patterns.add(match[1]);
	}

	return patterns;
}

function getNextId() {
	if (!fs.existsSync(REGISTRY_PATH)) return "AP-001";

	const content = fs.readFileSync(REGISTRY_PATH, "utf8");
	const idRegex = /"id":\s*"AP-(\d+)"/g;
	let maxNum = 0;
	let match;
	while ((match = idRegex.exec(content)) !== null) {
		const num = Number.parseInt(match[1], 10);
		if (num > maxNum) maxNum = num;
	}

	return `AP-${String(maxNum + 1).padStart(3, "0")}`;
}

function buildEntry(error, existingPatterns) {
	const { category, scope } = categorizeError(error.rule);
	const id = getNextId();
	const now = new Date().toISOString();

	const entry = {
		id,
		category,
		scope,
		severity: error.type === "typecheck" ? "high" : "medium",
		pattern: `${error.rule}: ${error.message.slice(0, 80)}`,
		correction: `TODO: 填写正确做法`,
		capturedAt: now,
		capturedBy: error.type === "lint" ? "auto-lint" : "auto-typecheck",
		sourceFile: error.file,
		sourceRule: error.rule,
		sourceLine: error.line,
	};

	const patternKey = error.rule.toLowerCase();
	if (existingPatterns.has(patternKey)) {
		return null;
	}

	return entry;
}

// ── Step 4: Append to registry ──

function appendEntry(entry) {
	const jsonBlock = JSON.stringify(entry, null, 4);

	const markdown = `
---
${jsonBlock}
---

### 描述

${entry.sourceRule} 错误出现在 \`${entry.sourceFile}\` 第 ${entry.sourceLine} 行。

错误信息:${entry.message || "N/A"}

### 错误示例

\`\`\`
// TODO: 填写触发此错误的代码片段
\`\`\`

### 正确示例

\`\`\`
// TODO: 填写修复后的代码
\`\`\`

`;

	let content = "";
	if (fs.existsSync(REGISTRY_PATH)) {
		content = fs.readFileSync(REGISTRY_PATH, "utf8");
	}

	fs.writeFileSync(REGISTRY_PATH, content + markdown, "utf8");
}

// ── Main ──

function main() {
	const args = parseCliArgs();

	console.log("[ai-pitfalls] Starting auto-capture...");

	let candidateFiles;
	if (args.all) {
		console.log("[ai-pitfalls] Scanning all AI-generated files...");
		candidateFiles = getAllAiFiles();
	} else {
		console.log("[ai-pitfalls] Scanning changed files...");
		candidateFiles = getChangedFiles();
	}

	const aiFiles = candidateFiles.filter((f) => hasCoAuthorHeader(f));
	console.log(`[ai-pitfalls] Found ${aiFiles.length} AI-generated files to check`);

	if (aiFiles.length === 0) {
		console.log("[ai-pitfalls] No AI-generated files to check. Done.");
		return;
	}

	console.log("[ai-pitfalls] Running ESLint...");
	const lintErrors = runEslintOnFiles(aiFiles);
	console.log(`[ai-pitfalls]   Found ${lintErrors.length} lint errors`);

	console.log("[ai-pitfalls] Running typecheck...");
	const typeErrors = runTypecheckOnFiles(aiFiles);
	console.log(`[ai-pitfalls]   Found ${typeErrors.length} type errors`);

	const allErrors = [...lintErrors, ...typeErrors];
	if (allErrors.length === 0) {
		console.log("[ai-pitfalls] No errors found. Registry is up to date.");
		return;
	}

	const existingPatterns = loadExistingPatterns();
	const newEntries = [];
	const seen = new Set();

	for (const error of allErrors) {
		const key = extractPatternKey(error);
		if (seen.has(key)) continue;
		seen.add(key);

		const entry = buildEntry(error, existingPatterns);
		if (entry) {
			newEntries.push({ entry, error });
		}
	}

	console.log(`[ai-pitfalls] ${newEntries.length} new anti-patterns to register (${seen.size - newEntries.length} duplicates skipped)`);

	if (newEntries.length === 0) {
		console.log("[ai-pitfalls] All error patterns already registered. Done.");
		return;
	}

	if (args.dryRun) {
		console.log("[ai-pitfalls] Dry run - would add the following entries:");
		for (const { entry } of newEntries) {
			console.log(`  [${entry.id}] ${entry.category}/${entry.scope}: ${entry.pattern}`);
		}
		return;
	}

	for (const { entry, error } of newEntries) {
		entry.message = error.message;
		appendEntry(entry);
		console.log(`[ai-pitfalls] + ${entry.id}: ${entry.pattern}`);
	}

	console.log(`[ai-pitfalls] Registry updated: ${REGISTRY_PATH}`);
	console.log(`[ai-pitfalls] Please review and refine the TODO entries.`);
}

main();