ai-direct-execute.mjs 65.2 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 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
#!/usr/bin/env node

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";

// pipe 模式下强制逐行刷新,避免输出批量刷出
const _timePrefix = () => `[${new Date().toISOString().slice(11, 23)}]`;
const _log = !process.stdout.isTTY
	? (...args) => { try { fs.writeSync(1, `${_timePrefix()} ${args.map(String).join(" ")}\n`); } catch { /* noop */ } }
	: (...args) => process.stdout.write(`${_timePrefix()} ${args.map(String).join(" ")}\n`);
const _warn = _log;
const _error = !process.stdout.isTTY
	? (...args) => { try { fs.writeSync(2, `${_timePrefix()} ${args.map(String).join(" ")}\n`); } catch { /* noop */ } }
	: (...args) => process.stderr.write(`${_timePrefix()} ${args.map(String).join(" ")}\n`);

const repoRoot = requireWorkspaceRoot();

function parseCliArgs() {
	const args = process.argv.slice(2);
	const parsed = {
		bundleFile: "",
		projectDir: "",
		figmaUrl: "",
		multiFigmaUrls: [],
		pageName: "",
		pageTitle: "",
		outputDir: "",
		previewName: "",
		previewDir: "apps/web/ai-previews",
		existingPreviewProjectRoot: "",
		responseFile: "",
		provider: "",
		model: "",
		autoRepair: false,
		maxRepairRounds: 1,
		batchIndex: undefined,
		withoutVariables: false,
		install: false,
		refreshContext: false,
		force: false,
		skipPreview: false,
		targetPlatform: "",
		fallbackUi: "",
		appendMode: false,
		skipFitness: false,
		skipPreamble: false,
		skipValidate: false,
		skipScreenshotSummary: false, // 是否跳过截图视觉摘要(节省 5-15 秒)
		skipGovernance: false, // 是否跳过 Venus 治理(fitness 质检、健康检查、文件大小检测等)
	};

	for (let index = 0; index < args.length; index++) {
		const arg = args[index];
		const next = args[index + 1];

		if (arg === "--bundle-file" && next) {
			parsed.bundleFile = next;
			index++;
		} else if (arg === "--project-dir" && next) {
			parsed.projectDir = next;
			index++;
		} else if (arg === "--figma-url" && next) {
			parsed.figmaUrl = next;
			index++;
		} else if (arg === "--page-name" && next) {
			parsed.pageName = next;
			index++;
		} else if (arg === "--page-title" && next) {
			parsed.pageTitle = next;
			index++;
		} else if (arg === "--output-dir" && next) {
			parsed.outputDir = next;
			index++;
		} else if (arg === "--preview-name" && next) {
			parsed.previewName = next;
			index++;
		} else if (arg === "--preview-dir" && next) {
			parsed.previewDir = next;
			index++;
		} else if (arg === "--existing-preview-project-root" && next) {
			parsed.existingPreviewProjectRoot = next;
			index++;
		} else if (arg === "--response-file" && next) {
			parsed.responseFile = next;
			index++;
		} else if (arg === "--provider" && next) {
			parsed.provider = next;
			index++;
		} else if (arg === "--model" && next) {
			parsed.model = next;
			index++;
		} else if (arg === "--max-repair-rounds" && next) {
			parsed.maxRepairRounds = Number.parseInt(next, 10) || 1;
			index++;
		} else if (arg === "--target-platform" && next) {
			parsed.targetPlatform = next;
			index++;
		} else if (arg === "--fallback-ui" && next) {
			parsed.fallbackUi = next;
			index++;
		} else if (arg === "--multi-figma-urls" && next) {
			parsed.multiFigmaUrls = next.split(",").map((u) => u.trim()).filter(Boolean);
			index++;
		} else
			switch (arg) {
				case "--append-mode": {
					parsed.appendMode = true;

					break;
				}
				case "--auto-repair": {
					parsed.autoRepair = true;

					break;
				}
				case "--batch-index": {
					if (typeof next === "string") {
						parsed.batchIndex = Number.parseInt(next, 10);
						index++;
					}

					break;
				}
				case "--force": {
					parsed.force = true;

					break;
				}
				case "--install": {
					parsed.install = true;

					break;
				}
				case "--no-skip-validate": {
					parsed.skipValidate = false;

					break;
				}
				case "--refresh-context": {
					parsed.refreshContext = true;

					break;
				}
				case "--skip-fitness": {
					parsed.skipFitness = true;

					break;
				}
				case "--skip-governance": {
					parsed.skipGovernance = true;

					break;
				}
				case "--skip-preamble": {
					parsed.skipPreamble = true;

					break;
				}
				case "--skip-preview": {
					parsed.skipPreview = true;

					break;
				}
				case "--skip-screenshot-summary": {
					parsed.skipScreenshotSummary = true;

					break;
				}
				case "--skip-validate": {
					parsed.skipValidate = true;

					break;
				}
				case "--without-variables": {
					parsed.withoutVariables = true;

					break;
				}
				// No default
			}
	}

	// skipGovernance 会自动跳过所有 Venus 治理检查
	if (parsed.skipGovernance) {
		parsed.skipFitness = true;
		parsed.skipValidate = true;
	}

	return parsed;
}

function fileExists(targetPath) {
	return fs.existsSync(targetPath);
}

function readJson(filePath) {
	try { return JSON.parse(fs.readFileSync(filePath, "utf8")); } catch { return null; }
}

function normalizePath(targetPath) {
	return targetPath.replaceAll("\\", "/");
}

// #region debug-point A:report-helper
function reportDebugEvent(hypothesisId, location, msg, data = {}, runId = process.env.DEBUG_RUN_ID || "pre-fix") {
	try {
		const envPath = path.join(repoRoot, ".dbg", "provider-hang.env");
		let debugServerUrl = "http://127.0.0.1:7777/event";
		let sessionId = "provider-hang";
		if (fs.existsSync(envPath)) {
			const envText = fs.readFileSync(envPath, "utf8");
			debugServerUrl = envText.match(/DEBUG_SERVER_URL=(.+)/)?.[1]?.trim() || debugServerUrl;
			sessionId = envText.match(/DEBUG_SESSION_ID=(.+)/)?.[1]?.trim() || sessionId;
		}
		fetch(debugServerUrl, {
			method: "POST",
			headers: { "content-type": "application/json" },
			body: JSON.stringify({
				sessionId,
				runId,
				hypothesisId,
				location,
				msg,
				data,
				ts: Date.now(),
			}),
		}).catch(() => {});
	} catch {}
}
// #endregion

function slugify(value) {
	const normalized = String(value || "")
		.trim()
		.toLowerCase()
		.replaceAll(/[^a-z0-9]+/g, "-")
		.replaceAll(/^-+|-+$/g, "");

	return normalized || "figma-page";
}

function toPascalCase(value) {
	return (
		String(value || "")
			.split(/[^a-z0-9]+/gi)
			.filter(Boolean)
			.map((token) => token.charAt(0).toUpperCase() + token.slice(1).toLowerCase())
			.join("") || "FigmaPage"
	);
}

function derivePageTitle(figmaUrl) {
	try {
		const url = new URL(figmaUrl);
		const parts = url.pathname.split("/").filter(Boolean);
		const rawTitle = parts[2] || parts.at(-1) || "Figma Page";
		return decodeURIComponent(rawTitle);
	} catch {
		return "Figma Page";
	}
}

function derivePageName(pageName, pageTitle, figmaUrl) {
	if (pageName) {
		return pageName;
	}

	return toPascalCase(pageTitle || derivePageTitle(figmaUrl));
}

function deriveBundlePath(args) {
	if (args.bundleFile) {
		return path.resolve(args.bundleFile);
	}

	// 批量模式:使用第一个 URL 作为主 URL
	const effectiveFigmaUrl = args.figmaUrl || (args.multiFigmaUrls.length > 0 ? args.multiFigmaUrls[0] : null);

	if (!args.projectDir || !effectiveFigmaUrl) {
		throw new Error("必须提供 --bundle-file,或者同时提供 --project-dir 与 --figma-url(或 --multi-figma-urls)");
	}

	const projectDir = path.resolve(args.projectDir);
	const pageSlug = slugify(derivePageName(args.pageName, args.pageTitle, effectiveFigmaUrl));
	const outputDir = args.outputDir ? path.resolve(args.outputDir) : path.join(projectDir, ".ai-direct", pageSlug);

	return path.join(outputDir, `${pageSlug}.ai-direct-context-bundle.json`);
}

function runNodeScript(scriptFile, scriptArgs, timeoutMs) {
	const commandArgs = [path.join(repoRoot, "scripts", scriptFile), ...scriptArgs];
	const options = {
		cwd: repoRoot,
		stdio: "inherit",
	};
	if (timeoutMs) {
		options.timeout = timeoutMs;
	}
	childProcess.execFileSync(process.execPath, commandArgs, options);
}

// [0] 环境预检:检查 Venus CLI 和模板契约
function runEnvironmentPreCheck() {
	_log("[ai-direct-execute] ⏳ [0/9] 环境预检 — 检查 Venus CLI 和模板契约...");
	_log(`[ai-direct-execute]   → Node: ${process.version}`);
	_log(`[ai-direct-execute]   → Platform: ${process.platform} (${process.arch})`);
	_log(`[ai-direct-execute]   → Workspace: ${repoRoot}`);

	const cliEntry = path.join(repoRoot, "packages", "cli", "dist", "index.cjs.js");
	if (!fs.existsSync(cliEntry)) {
		_error("[ai-direct-execute] ✗ Venus CLI 未构建,请先执行 pnpm run venus:build");
		throw new Error("Venus CLI not built");
	}
	// 检查 pnpm
	let pnpmVersion = "unknown";
	try {
		pnpmVersion = childProcess.execSync("pnpm --version", { stdio: "pipe", shell: true }).toString().trim();
	} catch {}
	_log(`[ai-direct-execute]   ✓ Venus CLI 已就绪`);
	_log(`[ai-direct-execute]   → pnpm: ${pnpmVersion}`);

	// 检查 git
	try {
		const gitBranch = childProcess.execSync("git branch --show-current", { stdio: "pipe", shell: true }).toString().trim();
		_log(`[ai-direct-execute]   → Git branch: ${gitBranch}`);
	} catch {}

	const shell = process.platform === "win32";
	try {
		childProcess.execSync("pnpm run check:template-contract", {
			cwd: repoRoot, stdio: "pipe", shell, timeout: 30_000,
		});
		_log("[ai-direct-execute]   ✓ 模板契约校验通过");
	} catch (error) {
		const output = (error.stdout?.toString() || "") + (error.stderr?.toString() || "");
		_warn("[ai-direct-execute]   ⚠ 模板契约存在警告:", output.slice(0, 300));
	}
	_log("[ai-direct-execute] ✓ [0/9] 环境预检完成");
}

// [6] Fitness 全维度校验(增量过滤模式)
function runFitnessChecks(changedFiles = []) {
	_log("[ai-direct-execute] ⏳ [6/9] 质量校验 — 执行 Fitness 全维度校验...");
	if (changedFiles.length > 0) {
		_log(`[ai-direct-execute]   → 增量模式: ${changedFiles.length} 个变更文件`);
	}

	const shell = process.platform === "win32";
	const checks = [
		{
			name: "CodeQuality (typecheck)",
			cmd: "pnpm run check:type",
			triggers: [/\.(ts|tsx|vue|jsx|mts|cts)$/],
		},
		{
			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 = [];
	let skippedCount = 0;

	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) {
				_log(`[ai-direct-execute]   ⏭ Fitness ${check.name}: 跳过(无相关变更)`);
				results.push({ name: check.name, status: "skipped", reason: "no relevant changes" });
				skippedCount++;
				continue;
			}
		}

		_log(`[ai-direct-execute]   → 执行 ${check.name}...`);
		try {
			childProcess.execSync(check.cmd, { cwd: repoRoot, stdio: "pipe", timeout: 120_000, shell });
			_log(`[ai-direct-execute]   ✓ Fitness ${check.name}: 通过`);
			results.push({ name: check.name, status: "pass" });
		} catch (error) {
			const output = (error.stdout?.toString() || "") + (error.stderr?.toString() || "");
			_warn(`[ai-direct-execute]   ✗ Fitness ${check.name}: 未通过`);
			_warn(`    ${output.slice(0, 500)}`);
			results.push({ name: check.name, status: "fail", detail: output.slice(0, 500) });
		}
	}

	const executed = results.filter((r) => r.status !== "skipped");
	const passed = executed.filter((r) => r.status === "pass").length;
	_log(`[ai-direct-execute] ✓ [6/9] Fitness 汇总: ${passed}/${executed.length} 通过${skippedCount > 0 ? `,${skippedCount} 跳过` : ""}`);
	return results;
}

// [6] 健康修复:venus diagnose + venus fix
function runDiagnoseAndFix(projectRoot) {
	_log("[ai-direct-execute] ⏳ [7/9] 健康修复 — 项目诊断...");

	const cliEntry = path.join(repoRoot, "packages", "cli", "dist", "index.cjs.js");
	if (!fs.existsSync(cliEntry)) {
		_warn("[ai-direct-execute]   ⚠ CLI 不可用,跳过诊断");
		_log("[ai-direct-execute] ✓ [7/9] 健康修复跳过");
		return;
	}

	try {
		childProcess.execFileSync(process.execPath, [cliEntry, "diagnose", projectRoot], {
			cwd: repoRoot, stdio: "inherit", timeout: 60_000,
		});
		_log("[ai-direct-execute]   ✓ 项目诊断完成");
	} catch {
		_warn("[ai-direct-execute]   ⚠ 诊断发现问题,尝试自动修复...");
		try {
			childProcess.execFileSync(process.execPath, [cliEntry, "fix", "--all", projectRoot], {
				cwd: repoRoot, stdio: "inherit", timeout: 60_000,
			});
			_log("[ai-direct-execute]   ✓ 自动修复完成");
		} catch {
			_warn("[ai-direct-execute]   ⚠ 部分问题需人工介入");
		}
	}
	_log("[ai-direct-execute] ✓ [7/9] 健康修复完成");
}

function ensureBundle(args, bundlePath) {
	if (fileExists(bundlePath) && !args.refreshContext) {
		return;
	}

	if (!args.projectDir || !args.figmaUrl) {
		throw new Error("启用 --refresh-context 时,必须同时提供 --project-dir 与 --figma-url");
	}

	const scriptArgs = ["--project-dir", path.resolve(args.projectDir), "--figma-url", args.figmaUrl];
	if (args.pageName) {
		scriptArgs.push("--page-name", args.pageName);
	}
	if (args.pageTitle) {
		scriptArgs.push("--page-title", args.pageTitle);
	}
	if (args.outputDir) {
		scriptArgs.push("--output-dir", path.resolve(args.outputDir));
	}
	if (args.withoutVariables) {
		scriptArgs.push("--without-variables");
	}
	if (args.targetPlatform) {
		scriptArgs.push("--target-platform", args.targetPlatform);
	}
	if (args.fallbackUi) {
		scriptArgs.push("--fallback-ui", args.fallbackUi);
	}

	runNodeScript("ai-direct-context.mjs", scriptArgs);
}

// 批量模式:为每个 URL 生成 context,然后合并 designContext 到主 bundle
function ensureMergedBundle(args, bundlePath, figmaUrls) {
	_log(`[ai-direct-execute]   → 批量模式: ${figmaUrls.length} 个 URL`);

	// 使用第一个 URL 生成主 bundle
	const primaryUrl = figmaUrls[0];
	args.figmaUrl = primaryUrl;
	ensureBundle(args, bundlePath);

	if (figmaUrls.length === 1) {
		return; // 只有一个 URL,不需要合并
	}

	// 读取主 bundle
	const mainBundle = readJson(bundlePath);
	const bundleDir = path.dirname(bundlePath);

	// 收集所有 designContext
	const allDesignContexts = [];
	_log(`[ai-direct-execute]   → 主 bundle 路径: ${bundlePath}`);
	_log(`[ai-direct-execute]   → 主 bundle artifacts: ${JSON.stringify(mainBundle.artifacts || {})}`);

	if (mainBundle.designContext || mainBundle.figma) {
		allDesignContexts.push({
			url: primaryUrl,
			context: mainBundle.designContext || mainBundle.figma?.designContextExcerpt,
			artifacts: mainBundle.artifacts || {},
		});
		_log(`[ai-direct-execute]   → ✓ 主 bundle context 已收集`);
	} else {
		_warn(`[ai-direct-execute]   ⚠ 主 bundle 没有 designContext 或 figma 字段`);
	}

	// 为剩余 URL 生成 context 并合并
	for (let i = 1; i < figmaUrls.length; i++) {
		const url = figmaUrls[i];
		_log(`[ai-direct-execute]   → [${i + 1}/${figmaUrls.length}] 收集 context: ${url}`);

		// 使用临时输出目录,让 context 脚本自己决定文件名
		const tempOutputDir = path.join(bundleDir, `_temp-ctx-${i}`);
		try {
			const scriptArgs = ["--project-dir", path.resolve(args.projectDir), "--figma-url", url, "--output-dir", tempOutputDir];
			if (args.withoutVariables) {
				scriptArgs.push("--without-variables");
			}
			if (args.targetPlatform) {
				scriptArgs.push("--target-platform", args.targetPlatform);
			}
			if (args.fallbackUi) {
				scriptArgs.push("--fallback-ui", args.fallbackUi);
			}

			runNodeScript("ai-direct-context.mjs", scriptArgs, 60_000); // 60秒超时

			// 在临时目录中找到生成的 bundle 文件
			if (fileExists(tempOutputDir)) {
				const tempFiles = fs.readdirSync(tempOutputDir);
				const tempBundleFile = tempFiles.find((f) => f.endsWith(".ai-direct-context-bundle.json"));
				_log(`[ai-direct-execute]     → 临时目录文件: ${tempFiles.join(", ")}`);

				if (tempBundleFile) {
					const tempBundlePath = path.join(tempOutputDir, tempBundleFile);
					_log(`[ai-direct-execute]     → 读取临时 bundle: ${tempBundlePath}`);
					const tempBundle = readJson(tempBundlePath);

					// 复制截图和设计上下文到主 bundle 目录(在删除临时目录前)
					const artifacts = tempBundle.artifacts || {};
					_log(`[ai-direct-execute]     → artifacts: ${JSON.stringify(artifacts)}`);
					const copiedArtifacts = {};

					// 复制截图
					if (artifacts.screenshotFile) {
						_log(`[ai-direct-execute]     → 检查截图: ${artifacts.screenshotFile} (exists: ${fileExists(artifacts.screenshotFile)})`);
						if (fileExists(artifacts.screenshotFile)) {
							const screenshotName = `module-${i + 1}.screenshot.png`;
							const copiedPath = path.join(bundleDir, screenshotName);
							try {
								fs.copyFileSync(artifacts.screenshotFile, copiedPath);
								copiedArtifacts.screenshotFile = copiedPath;
								_log(`[ai-direct-execute]     → ✓ 截图已复制: ${copiedPath}`);
							} catch (copyError) {
								_warn(`[ai-direct-execute]     ⚠ 截图复制失败: ${copyError.message}`);
							}
						}
					}

					// 复制设计上下文 HTML
					if (artifacts.designContextFile) {
						_log(`[ai-direct-execute]     → 检查设计上下文: ${artifacts.designContextFile} (exists: ${fileExists(artifacts.designContextFile)})`);
						if (fileExists(artifacts.designContextFile)) {
							const dcName = `module-${i + 1}.design-context.html`;
							const copiedPath = path.join(bundleDir, dcName);
							try {
								fs.copyFileSync(artifacts.designContextFile, copiedPath);
								copiedArtifacts.designContextFile = copiedPath;
								_log(`[ai-direct-execute]     → ✓ 设计上下文已复制: ${copiedPath}`);
							} catch (copyError) {
								_warn(`[ai-direct-execute]     ⚠ 设计上下文复制失败: ${copyError.message}`);
							}
						}
					}

					// 收集 designContext 和复制的 artifacts
					if (tempBundle.designContext || tempBundle.figma) {
						allDesignContexts.push({
							url,
							context: tempBundle.designContext || tempBundle.figma?.designContextExcerpt,
							artifacts: copiedArtifacts,
						});
						_log(`[ai-direct-execute]     → ✓ 已收集 context (artifacts: ${Object.keys(copiedArtifacts).length} 个文件)`);
					}
				}

				// 清理整个临时目录
				_log(`[ai-direct-execute]     → 清理临时目录: ${tempOutputDir}`);
				try {
					fs.rmSync(tempOutputDir, { recursive: true, force: true });
					_log(`[ai-direct-execute]     → ✓ 临时目录已清理`);
				} catch (rmError) {
					_warn(`[ai-direct-execute]     ⚠ 临时目录清理失败: ${rmError.message}`);
				}
			} else {
				_warn(`[ai-direct-execute]     ⚠ 临时目录不存在: ${tempOutputDir}`);
			}
		} catch (error) {
			_warn(`[ai-direct-execute]   ⚠ [${i + 1}/${figmaUrls.length}] context 收集失败: ${error.message}`);
			// 清理临时目录(即使失败)
			if (fileExists(tempOutputDir)) {
				fs.rmSync(tempOutputDir, { recursive: true, force: true });
			}
		}
	}

	// 合并所有 designContext
	if (allDesignContexts.length > 1) {
		_log(`[ai-direct-execute]   → 合并 ${allDesignContexts.length} 个 designContext`);
		_log(`[ai-direct-execute]   → 模块列表: ${allDesignContexts.map((c) => c.url).join(", ")}`);

		// 合并 designContext 内容
		const mergeResult = mergeDesignContexts(allDesignContexts);
		_log(`[ai-direct-execute]   → 合并结果: ${mergeResult.allScreenshots.length} 个截图, ${mergeResult.allDesignContextFiles.length} 个设计上下文`);
		_log(`[ai-direct-execute]   → 合并后的设计上下文长度: ${mergeResult.mergedDesignContext.length} 字符`);

		// 写入合并后的设计上下文文件
		const mergedDesignContextPath = path.join(bundleDir, "merged-design-context.html");
		try {
			fs.writeFileSync(mergedDesignContextPath, mergeResult.mergedDesignContext, "utf8");
			_log(`[ai-direct-execute]   → ✓ 合并设计上下文已写入: ${mergedDesignContextPath}`);
		} catch (writeError) {
			_error(`[ai-direct-execute]   ✗ 写入合并设计上下文失败: ${writeError.message}`);
		}

		// 更新主 bundle 的 figma 字段(合并 designContextExcerpt)
		if (mainBundle.figma) {
			mainBundle.figma.designContextExcerpt = mergeResult.mergedText;
			mainBundle.figma._mergedModules = mergeResult.modules;
			_log(`[ai-direct-execute]   → ✓ figma.designContextExcerpt 已更新`);
		}

		// 更新主 bundle 的 artifacts 字段
		if (mainBundle.artifacts) {
			// 指向合并后的设计上下文文件
			mainBundle.artifacts.designContextFile = mergedDesignContextPath;
			mainBundle.artifacts.allDesignContextFiles = mergeResult.allDesignContextFiles;

			// 添加所有截图路径
			if (mergeResult.allScreenshots.length > 0) {
				mainBundle.artifacts.allScreenshotFiles = mergeResult.allScreenshots;
				_log(`[ai-direct-execute]   → ✓ artifacts.allScreenshotFiles 已更新: ${mergeResult.allScreenshots.join(", ")}`);
			}
		}

		// 写回主 bundle
		_log(`[ai-direct-execute]   → 写入合并后的 bundle...`);
		try {
			fs.writeFileSync(bundlePath, `${JSON.stringify(mainBundle, null, 2)}\n`, "utf8");
			_log(`[ai-direct-execute]   ✓ 已合并 ${allDesignContexts.length} 个模块的 designContext`);
			_log(`[ai-direct-execute]   → Bundle 路径: ${bundlePath}`);

			// 验证写入是否成功
			const verifyBundle = readJson(bundlePath);
			_log(`[ai-direct-execute]   → ✓ Bundle 验证成功,designContextFile: ${verifyBundle.artifacts?.designContextFile}`);
		} catch (writeError) {
			_error(`[ai-direct-execute]   ✗ Bundle 写入失败: ${writeError.message}`);
		}
	} else {
		_log(`[ai-direct-execute]   → 只有 ${allDesignContexts.length} 个 context,无需合并`);
	}
}

// 合并多个 designContext
function mergeDesignContexts(contexts) {
	// 合并各个字段
	const textParts = [];
	const designContextParts = []; // 完整的设计上下文(从文件读取)
	const modules = [];
	const allScreenshots = [];
	const allDesignContextFiles = [];

	for (const { url, context, artifacts } of contexts) {
		modules.push(url);

		// 收集文本摘要
		if (typeof context === "string") {
			textParts.push(`\n## Module: ${url}\n\n${context}`);
		} else if (context && typeof context === "object") {
			if (context.text) {
				textParts.push(`\n## Module: ${url}\n\n${context.text}`);
			} else if (context.designContextExcerpt) {
				textParts.push(`\n## Module: ${url}\n\n${context.designContextExcerpt}`);
			}
		}

		// 读取完整的设计上下文文件内容
		if (artifacts?.designContextFile && fileExists(artifacts.designContextFile)) {
			try {
				const fileContent = fs.readFileSync(artifacts.designContextFile, "utf8");
				designContextParts.push(`\n\n### === Module: ${url} ===\n\n${fileContent}`);
				allDesignContextFiles.push(artifacts.designContextFile);
			} catch (error) {
				_warn(`[ai-direct-execute]   ⚠ 读取设计上下文失败: ${artifacts.designContextFile} - ${error.message}`);
			}
		}

		// 收集截图路径
		if (artifacts?.screenshotFile) {
			allScreenshots.push(artifacts.screenshotFile);
		}
	}

	return {
		mergedText: textParts.join("\n"),
		mergedDesignContext: designContextParts.join("\n"),
		modules,
		allScreenshots,
		allDesignContextFiles,
	};
}

function resolveResponseFile(bundlePath, responseFile) {
	if (responseFile) {
		return path.resolve(responseFile);
	}

	return path.join(
		path.dirname(bundlePath),
		`${path.basename(bundlePath, ".ai-direct-context-bundle.json")}.provider-response.json`,
	);
}

function extractJsonPayload(text) {
	const trimmed = String(text || "").trim();
	if (!trimmed) {
		throw new Error("AI 返回为空");
	}

	// 1. 直接解析
	try {
		return JSON.parse(trimmed);
	} catch {}

	// 2. 提取 markdown 代码块中的 JSON(贪婪匹配最后一个)
	const fencedMatches = [...trimmed.matchAll(/```(?:json)?\s*([\s\S]*?)```/gi)];
	for (const match of fencedMatches.reverse()) {
		try {
			return JSON.parse(match[1].trim());
		} catch {}
	}

	// 3. 找到最外层 {} 并尝试解析
	const firstBrace = trimmed.indexOf("{");
	const lastBrace = trimmed.lastIndexOf("}");
	if (firstBrace !== -1 && lastBrace > firstBrace) {
		const candidate = trimmed.slice(firstBrace, lastBrace + 1);
		try {
			return JSON.parse(candidate);
		} catch {
			// 4. 尝试修复常见 JSON 问题(尾逗号)
			const fixed = candidate.replaceAll(/,(\s*[}\]])/g, "$1");
			try {
				return JSON.parse(fixed);
			} catch {}
		}
	}

	// 5. 尝试逐字符匹配大括号找到最大 JSON 对象
	let depth = 0;
	let jsonStart = -1;
	let jsonEnd = -1;
	for (const [i, element] of trimmed.entries()) {
		if (element === "{") {
			if (depth === 0) jsonStart = i;
			depth++;
		} else if (element === "}") {
			depth--;
			if (depth === 0) {
				jsonEnd = i;
				break;
			}
		}
	}
	if (jsonStart !== -1 && jsonEnd !== -1 && jsonEnd > jsonStart) {
		try {
			return JSON.parse(trimmed.slice(jsonStart, jsonEnd + 1));
		} catch {}
	}

	throw new Error(`无法从 AI 返回中提取 JSON(${trimmed.length} 字符)`);
}

async function callOpenAiCompatible(messages, model) {
	const baseUrl = process.env.AI_DIRECT_OPENAI_BASE_URL || process.env.OPENAI_BASE_URL;
	const apiKey = process.env.AI_DIRECT_OPENAI_API_KEY || process.env.OPENAI_API_KEY;
	const resolvedModel = model || process.env.AI_DIRECT_OPENAI_MODEL || process.env.OPENAI_MODEL;

	if (!baseUrl || !apiKey || !resolvedModel) {
		throw new Error(
			"openai-compatible 模式需要配置 AI_DIRECT_OPENAI_BASE_URL、AI_DIRECT_OPENAI_API_KEY、AI_DIRECT_OPENAI_MODEL",
		);
	}

	const endpoint = `${baseUrl.replace(/\/$/, "")}/chat/completions`;
	const requestBody = JSON.stringify({
		model: resolvedModel,
		temperature: 0.2,
		response_format: { type: "json_object" },
		stream: true,
		messages,
	});
	// #region debug-point A:provider-request-start
	reportDebugEvent("A", "scripts/ai-direct-execute.mjs:callOpenAiCompatible:start", "[DEBUG] provider request start", {
		endpoint,
		model: resolvedModel,
		messageCount: messages.length,
		requestBytes: Buffer.byteLength(requestBody, "utf8"),
		stream: true,
	});
	// #endregion

	const startTime = Date.now();
	const idleTimeoutMs = 120_000;
	const controller = new AbortController();
	let idleTimer = setTimeout(() => controller.abort(new Error("idle timeout")), idleTimeoutMs);

	let response;
	try {
		response = await fetch(endpoint, {
			method: "POST",
			headers: {
				"content-type": "application/json",
				authorization: `Bearer ${apiKey}`,
				connection: "close",
			},
			signal: controller.signal,
			body: requestBody,
		});
	} catch (fetchError) {
		clearTimeout(idleTimer);
		if (controller.signal.aborted && controller.signal.reason?.message === "idle timeout") {
			throw new Error(`AI provider 请求空闲超时(${idleTimeoutMs / 1000} 秒内未收到数据)`);
		}
		throw fetchError;
	}
	// #region debug-point A:provider-response
	reportDebugEvent("A", "scripts/ai-direct-execute.mjs:callOpenAiCompatible:response", "[DEBUG] provider response received", {
		status: response.status,
		statusText: response.statusText,
		ok: response.ok,
		stream: true,
	});
	// #endregion

	if (!response.ok) {
		clearTimeout(idleTimer);
		const errorText = (await response.text()).trim();
		const errorPreview = errorText ? ` | ${errorText.slice(0, 600)}` : "";
		throw new Error(`AI provider 请求失败: ${response.status} ${response.statusText}${errorPreview}`);
	}

	_log("[ai-direct-execute]   → 开始接收流式数据...");

	let accumulatedContent = "";
	let chunkCount = 0;
	let lastLogTime = startTime;

	try {
		const reader = response.body.getReader();
		const decoder = new TextDecoder();
		let buffer = "";

		while (true) {
			const { done, value } = await reader.read();
			if (done) break;

			clearTimeout(idleTimer);
			idleTimer = setTimeout(() => controller.abort(new Error("idle timeout")), idleTimeoutMs);

			buffer += decoder.decode(value, { stream: true });
			const lines = buffer.split("\n");
			buffer = lines.pop() || "";

			for (const line of lines) {
				const trimmed = line.trim();
				if (!trimmed || trimmed === "data: [DONE]") continue;
				if (!trimmed.startsWith("data: ")) continue;

				try {
					const json = JSON.parse(trimmed.slice(6));
					const delta = json.choices?.[0]?.delta?.content || "";
					accumulatedContent += delta;
					chunkCount++;

					const now = Date.now();
					if (now - lastLogTime >= 5000) {
						const elapsed = ((now - startTime) / 1000).toFixed(1);
						_log(`[ai-direct-execute]   → 已接收 ${accumulatedContent.length} 字符,耗时 ${elapsed} 秒...`);
						lastLogTime = now;
					}
				} catch {
					// Ignore parse errors
				}
			}
		}
	} catch (streamError) {
		clearTimeout(idleTimer);
		if (controller.signal.aborted && controller.signal.reason?.message === "idle timeout") {
			const elapsed = ((Date.now() - startTime) / 1000).toFixed(1);
			throw new Error(`AI provider 流式接收空闲超时(已接收 ${accumulatedContent.length} 字符,${elapsed} 秒后超过 ${idleTimeoutMs / 1000} 秒无新数据)`);
		}
		throw streamError;
	}

	clearTimeout(idleTimer);

	const totalElapsed = ((Date.now() - startTime) / 1000).toFixed(1);
	_log(`[ai-direct-execute]   → 流式接收完成: ${accumulatedContent.length} 字符,${chunkCount} 个 chunks,耗时 ${totalElapsed} 秒`);

	const payload = {
		choices: [{ message: { content: accumulatedContent } }],
	};

	return {
		provider: "openai-compatible",
		model: resolvedModel,
		raw: payload,
		content: accumulatedContent,
	};
}

function validateResponse(structured) {
	if (!structured || typeof structured !== "object") {
		return { valid: false, reason: "响应不是有效对象" };
	}
	if (!Array.isArray(structured.files) || structured.files.length === 0) {
		return { valid: false, reason: "files 数组为空或缺失" };
	}
	return { valid: true };
}

async function resolveAiResponse({ args, bundlePath }) {
	const responsePath = resolveResponseFile(bundlePath, args.responseFile);

	if (args.responseFile) {
		return {
			mode: "manual-replay",
			responsePath,
			response: readJson(responsePath),
		};
	}

	if (!args.provider || args.provider === "manual") {
		throw new Error("当前未提供 --response-file,若要自动调用 provider,请传入 --provider openai-compatible");
	}

	const messagesPath = path.join(
		path.dirname(bundlePath),
		`${path.basename(bundlePath, ".ai-direct-context-bundle.json")}.messages.json`,
	);
	const messagesPayload = readJson(messagesPath);
	if (!messagesPayload?.messages) {
		throw new Error(`无法加载 messages: ${messagesPath}`);
	}

	// 重试逻辑:最多尝试 3 次(首次 + 2 次重试)
	const maxAttempts = 3;
	let lastResponse = null;
	let lastRawContent = "";

	for (let attempt = 1; attempt <= maxAttempts; attempt++) {
		let currentMessages;

		if (attempt === 1) {
			// 首次尝试:使用原始 messages
			currentMessages = messagesPayload.messages;
		} else {
			// 重试:添加强制修正消息
			const previousSummary = lastResponse?.summary || "(无摘要)";
			const correctionMessage = {
				role: "user",
				content: `## ⚠ 上次响应不合格,必须重新生成\n\n你上次返回的内容:\n\`\`\`json\n${JSON.stringify(lastResponse, null, 2)}\n\`\`\`\n\n**问题**:${lastResponse && !Array.isArray(lastResponse.files) ? "缺少 files 数组,只返回了 summary" : (Array.isArray(lastResponse.files) && lastResponse.files.length === 0 ? "files 数组为空" : "响应格式错误")}\n\n**你必须输出包含 files 数组的完整 JSON。**\n即使 design context 非常简单(比如只有一个按钮、一个导航栏),也必须生成完整的 Vue SFC 代码。\n\n**输出格式模板(必须严格遵循):**\n\`\`\`json\n{\n  "summary": "简要描述",\n  "files": [\n    {\n      "path": "src/views/<PageName>/components/<ComponentName>.vue",\n      "language": "vue",\n      "purpose": "组件用途描述",\n      "content": "<script setup lang=\\"ts\\">\\n// 组件逻辑\\n</script>\\n\\n<template>\\n  <!-- 组件模板 -->\\n</template>\\n\\n<style scoped>\\n/* 样式 */\\n</style>"\n    }\n  ]\n}\n\`\`\`\n\n**现在立即按上述格式重新生成完整 JSON。files 数组不能为空,content 必须是完整的 Vue SFC 代码。**`,
			};
			currentMessages = [...messagesPayload.messages, correctionMessage];
			_log(`[ai-direct-execute] ⚠ 第 ${attempt} 次重试:上次响应 ${previousSummary}`);
		}

		let providerResult;
		if (args.provider === "openai-compatible") {
			providerResult = await callOpenAiCompatible(currentMessages, args.model);
		} else {
			throw new Error(`不支持的 provider: ${args.provider}`);
		}

		// 保存原始响应(即使解析失败也能调试)
		const rawContent = providerResult.content || "";
		const rawPath = attempt === 1
			? responsePath.replace(".provider-response.json", ".provider-response.raw.txt")
			: responsePath.replace(".provider-response.json", `.provider-response.raw.attempt-${attempt}.txt`);
		if (rawContent) {
			fs.writeFileSync(rawPath, rawContent, "utf8");
		}
		lastRawContent = rawContent;

		let structured;
		try {
			structured = extractJsonPayload(providerResult.content);
			lastResponse = structured;
		} catch (parseError) {
			const preview = rawContent.slice(0, 500);
			_log(`[ai-direct-execute] ⚠ 第 ${attempt} 次尝试:JSON 解析失败: ${parseError.message}`);
			_log(`[ai-direct-execute] ⚠ 原始响应前 500 字符:\n${preview}`);
			if (attempt === maxAttempts) throw parseError;
			continue;
		}

		// 验证响应
		const validation = validateResponse(structured);
		if (!validation.valid) {
			_log(`[ai-direct-execute] ⚠ 第 ${attempt} 次尝试:${validation.reason}`);
			if (attempt === maxAttempts) {
				// 最后一次尝试也失败,抛出错误
				throw new Error(`AI 响应验证失败(${maxAttempts} 次尝试均失败): ${validation.reason}`);
			}
			continue;
		}

		// 验证通过
		_log(`[ai-direct-execute] ✓ 第 ${attempt} 次尝试:验证通过,生成 ${structured.files.length} 个文件`);

		const persisted = {
			meta: {
				generator: "scripts/ai-direct-execute.mjs",
				generatedAt: new Date().toISOString(),
				mode: providerResult.provider,
				model: providerResult.model,
				bundleFile: normalizePath(bundlePath),
				attempts: attempt,
			},
			response: structured,
			raw: providerResult.raw,
		};
		fs.writeFileSync(responsePath, `${JSON.stringify(persisted, null, 2)}\n`, "utf8");

		return {
			mode: providerResult.provider,
			responsePath,
			response: structured,
		};
	}

	// 不应到达这里,但作为安全检查
	throw new Error("resolveAiResponse: 重试循环异常退出");
}

function unwrapResponseFile(responsePath) {
	const payload = readJson(responsePath);
	if (payload && typeof payload === "object" && "response" in payload && payload.response) {
		return payload.response;
	}

	return payload;
}

function persistPlainResponse(responsePath, response) {
	fs.writeFileSync(responsePath, `${JSON.stringify(response, null, 2)}\n`, "utf8");
}

function buildRepairArtifacts({ bundle, preview, response, validation, responsePath }) {
	const baseName = path.basename(responsePath, path.extname(responsePath));
	const feedbackPath = path.join(path.dirname(responsePath), `${baseName}.repair-feedback.json`);
	const requestPath = path.join(path.dirname(responsePath), `${baseName}.repair-request.md`);
	const failedCommands = (validation.commandResults || []).filter((item) => !item.ok);
	const ruleErrors = validation.ruleValidation?.errors || [];
	const ruleWarnings = validation.ruleValidation?.warnings || [];
	const styleErrors = validation.styleValidation?.errors || [];
	const styleWarnings = validation.styleValidation?.warnings || [];
	const primaryDataErrors = validation.primaryDataValidation?.errors || [];
	const primaryDataWarnings = validation.primaryDataValidation?.warnings || [];
	const visualSummaryErrors = validation.visualSummaryValidation?.errors || [];
	const visualSummaryWarnings = validation.visualSummaryValidation?.warnings || [];
	const templateSyntaxErrors = validation.templateSyntaxValidation?.errors || [];
	const templateSyntaxWarnings = validation.templateSyntaxValidation?.warnings || [];
	const designFidelityErrors = validation.designFidelityValidation?.errors || [];
	const designFidelityWarnings = validation.designFidelityValidation?.warnings || [];

	const feedback = {
		meta: {
			generator: "scripts/ai-direct-execute.mjs",
			generatedAt: new Date().toISOString(),
			bundleFile: normalizePath(preview.meta.bundleFile),
			previewFile: normalizePath(
				path.resolve(
					path.dirname(responsePath),
					`${path.basename(preview.meta.bundleFile, ".ai-direct-context-bundle.json")}.preview-project.json`,
				),
			),
			responseFile: normalizePath(responsePath),
		},
		status: validation.status,
		ruleErrors,
		ruleWarnings,
		styleErrors,
		styleWarnings,
		primaryDataErrors,
		primaryDataWarnings,
		visualSummaryErrors,
		visualSummaryWarnings,
		templateSyntaxErrors,
		templateSyntaxWarnings,
		designFidelityErrors,
		designFidelityWarnings,
		failedCommands: failedCommands.map((item) => ({
			command: item.command,
			exitCode: item.exitCode,
			stdout: item.stdout,
			stderr: item.stderr,
			skipped: item.skipped || false,
			reason: item.reason || "",
		})),
		originalResponse: response,
	};

	const requestLines = [
		"# AI Repair Request",
		"",
		`- Project: \`${bundle.projectContext.projectName}\``,
		`- Framework: \`${bundle.rules.framework}\``,
		`- Preferred VUI: \`${bundle.rules.preferredVuiPackage || "none"}\``,
		"",
		"## Fix Targets",
		"",
	];

	for (const error of ruleErrors) {
		requestLines.push(`- Rule Error: ${error}`);
	}
	for (const error of styleErrors) {
		requestLines.push(`- Style Error: ${error}`);
	}
	for (const error of primaryDataErrors) {
		requestLines.push(`- Primary Data Error: ${error}`);
	}
	for (const error of visualSummaryErrors) {
		requestLines.push(`- Visual Summary Error: ${error}`);
	}
	for (const error of templateSyntaxErrors) {
		requestLines.push(`- Template Syntax Error: ${error}`);
	}
	for (const error of designFidelityErrors) {
		requestLines.push(`- Design Fidelity Error: ${error}`);
	}
	for (const warning of ruleWarnings) {
		requestLines.push(`- Rule Warning: ${warning}`);
	}
	for (const warning of styleWarnings) {
		requestLines.push(`- Style Warning: ${warning}`);
	}
	for (const warning of primaryDataWarnings) {
		requestLines.push(`- Primary Data Warning: ${warning}`);
	}
	for (const warning of visualSummaryWarnings) {
		requestLines.push(`- Visual Summary Warning: ${warning}`);
	}
	for (const warning of templateSyntaxWarnings) {
		requestLines.push(`- Template Syntax Warning: ${warning}`);
	}
	for (const warning of designFidelityWarnings) {
		requestLines.push(`- Design Fidelity Warning: ${warning}`);
	}
	for (const command of feedback.failedCommands) {
		requestLines.push(`- Command Failure: ${command.command} (exit=${command.exitCode})`);
		if (command.stderr) {
			requestLines.push("", "```text");
			requestLines.push(command.stderr.trim(), "```");
		}
	}

	requestLines.push(
		"",
		"## Original Response",
		"",
		"```json",
		JSON.stringify(response, null, 2),
		"```",
		"",
		"## Instructions",
		"",
		"- 保持 previewProject.mustUseVenusCli=true。",
		"- 只修复失败项,不要引入新的 UI 包违规。",
		"- 如果失败项来自 Figma 原始数据校验,优先保留 design context 中明确给出的标签、placeholder、列名和示例数据,不要让截图摘要覆盖这些文本事实。",
		"- 如果失败项来自截图视觉摘要校验,优先修正标题、筛选标签、选择框数量、表格列、操作文案和分页布局,使页面与截图摘要一致。",
		"- 如果失败项来自设计还原度校验,必须严格按照 layoutOrder / sectionOrder 顺序重新排列页面区块,并将设计稿中的关键颜色值原样写入 CSS,禁止用'合理推断'覆盖。",
		"- 如果失败项涉及 grid 列数不匹配,必须修改 CSS 的 grid-template-columns 使其与截图摘要指定的 columns 值一致。例如:columns=2 → `grid-template-columns: repeat(2, 1fr)`。",
		"- 如果失败项涉及 flex-direction 错误(如 direction=row 但代码用了 column),必须修改 CSS 的 flex-direction 为 row,或移除 flex-direction: column 让其默认为 row。",
		"- 如果失败项涉及底部固定操作栏缺失,必须添加一个 position: fixed; bottom: 0; left: 0; right: 0 的容器,并在其中放置指定按钮。",
		"- 如果失败项涉及浮动元素位置错误(如 left-top 实际在 left-bottom),必须修改 CSS 的 position: absolute 定位属性,将 top/bottom/left/right 对应到正确方位。",
		"- 如果失败项涉及区块顺序错误,必须调整 template 中 DOM 元素的顺序使其与 sectionOrder/layoutOrder 一致。",
		"- 如果失败项来自样式责任校验,直接在生成文件中补齐页面级样式,不要把布局或视觉修复转嫁给预览项目壳层。",
		"- 输出完整结构化 JSON,沿用既定 response schema。",
	);

	fs.writeFileSync(feedbackPath, `${JSON.stringify(feedback, null, 2)}\n`, "utf8");
	fs.writeFileSync(requestPath, `${requestLines.join("\n")}\n`, "utf8");

	return { feedbackPath, requestPath };
}

function shouldAttemptAutoRepair(args) {
	return Boolean(args.autoRepair && args.provider === "openai-compatible" && !args.responseFile);
}

async function launchPreviewProject(preview) {
	const projectRoot = preview.previewProject?.projectRoot;
	if (!projectRoot) {
		_log("[ai-direct-execute] preview-project 缺少 projectRoot,跳过启动");
		return;
	}

	const projectName = preview.previewProject.name;
	const packageName = `@venus/${projectName}`;
	const shell = process.platform === "win32";

	_log(`[ai-direct-execute]   → 项目名: ${projectName}`);
	_log(`[ai-direct-execute]   → Package: ${packageName}`);
	_log(`[ai-direct-execute]   → 路径: ${projectRoot}`);

	// 检查 node_modules 是否已存在
	const nodeModulesPath = path.join(projectRoot, "node_modules");
	const nodeModulesExists = fs.existsSync(nodeModulesPath);
	_log(`[ai-direct-execute]   → node_modules: ${nodeModulesExists ? "已存在" : "不存在,需要安装"}`);

	_log("[ai-direct-execute]   → 执行 pnpm install...");
	const installStart = Date.now();
	try {
		childProcess.execSync("pnpm install", {
			cwd: repoRoot,
			stdio: "inherit",
			shell,
		});
		const installElapsed = ((Date.now() - installStart) / 1000).toFixed(1);
		_log(`[ai-direct-execute]   ✓ pnpm install 完成 (耗时 ${installElapsed} 秒)`);
	} catch {
		if (!fs.existsSync(nodeModulesPath)) {
			_error("[ai-direct-execute]   ✗ pnpm install 失败且 node_modules 不存在,跳过启动预览项目");
			return;
		}
		_warn("[ai-direct-execute]   ⚠ pnpm install postinstall 存在非致命错误,但依赖已安装,继续启动");
	}

	_log("[ai-direct-execute]   → 启动 dev server...");
	const devServer = childProcess.spawn(`pnpm --filter ${packageName} run dev`, {
		cwd: repoRoot,
		stdio: ["inherit", "pipe", "pipe"],
		detached: true,
		shell,
	});

	// 等待 Vite dev server 输出 Local URL(最多 30 秒)
	const urlDetected = await new Promise((resolve) => {
		let detected = false;
		let resolved = false;

		const handleOutput = (data) => {
			if (resolved) return;
			const output = data.toString();
			const patterns = [
				/Local:\s+(https?:\/\/(?:localhost|127\.0\.0\.1):\d+\/?)/i,
				/(https?:\/\/localhost:\d+\/?)/i,
				/> Local:\s+(https?:\/\/\S+)/i,
			];
			for (const pattern of patterns) {
				const match = output.match(pattern);
				if (match) {
					detected = true;
					resolved = true;
					const url = match[1];
					_log(`  Local:   ${url}`);
					_log(`[ai-direct-execute]   ✓ 预览服务已启动 (pid: ${devServer.pid})`);
					devServer.stdout.removeAllListeners("data");
					devServer.stderr.removeAllListeners("data");
					resolve(true);
					return;
				}
			}
		};

		devServer.stdout.on("data", handleOutput);
		devServer.stderr.on("data", handleOutput);

		// 30 秒超时
		setTimeout(() => {
			if (!resolved) {
				resolved = true;
				_log(`[ai-direct-execute]   ✓ 预览服务已在后台启动 (pid: ${devServer.pid})`);
				devServer.stdout.removeAllListeners("data");
				devServer.stderr.removeAllListeners("data");
				resolve(false);
			}
		}, 30_000);
	});

	devServer.unref();
}

async function run() {
	const args = parseCliArgs();
	const bundlePath = deriveBundlePath(args);

	_log("[ai-direct-execute] ═══════════════════════════════════════");
	_log("[ai-direct-execute]   Venus AI Direct Pipeline");
	_log(`[ai-direct-execute]   时间: ${new Date().toLocaleString()}`);
	_log(`[ai-direct-execute]   Bundle: ${bundlePath}`);
	_log(`[ai-direct-execute]   Provider: ${args.provider || "manual"}`);
	_log(`[ai-direct-execute]   Model: ${args.model || process.env.AI_DIRECT_OPENAI_MODEL || "unknown"}`);
	_log(`[ai-direct-execute]   Force: ${args.force}`);
	if (args.multiFigmaUrls.length > 0) {
		_log(`[ai-direct-execute]   模式: 批量合并 (${args.multiFigmaUrls.length} 个 URL)`);
	}
	_log("[ai-direct-execute] ═══════════════════════════════════════");

	const previewPath = path.join(
		path.dirname(bundlePath),
		`${path.basename(bundlePath, ".ai-direct-context-bundle.json")}.preview-project.json`,
	);

	let bundle;
	let preview;

	if (args.skipPreamble) {
		_log("[ai-direct-execute] ⏭ --skip-preamble: 跳过环境检查 + Context 收集 + 项目决策,重新构建 Messages");
		bundle = readJson(bundlePath);
		preview = readJson(previewPath);
		if (!bundle) {
			throw new Error(`--skip-preamble: 无法加载 bundle: ${bundlePath}`);
		}
		if (!preview) {
			throw new Error(`--skip-preamble: 无法加载 preview: ${previewPath}`);
		}
		_log(`[ai-direct-execute]   → Bundle: ${bundlePath}`);
		_log(`[ai-direct-execute]   → Preview: ${previewPath}`);

		// 每个批次必须重新构建 Messages(context 不同)
		_log("[ai-direct-execute] ⏳ [2/9] Messages — 从当前批次 bundle 重新构建...");
		const msgStart = Date.now();
		const messagesArgs = ["--bundle-file", bundlePath];
		if (args.existingPreviewProjectRoot) {
			messagesArgs.push("--append-mode", "--project-dir", args.existingPreviewProjectRoot);
		}
		if (args.skipScreenshotSummary) {
			messagesArgs.push("--skip-screenshot-summary");
		}
		runNodeScript("ai-direct-messages.mjs", messagesArgs);
		const msgElapsed = ((Date.now() - msgStart) / 1000).toFixed(1);
		_log(`[ai-direct-execute] ✓ [2/9] Messages 重新构建完成 (耗时 ${msgElapsed} 秒)`);
	} else {
		runEnvironmentPreCheck();

		_log("[ai-direct-execute] ⏳ [1/9] Context 收集 — figma-client + project-intelligence + component-manifest...");
		const ctxStart = Date.now();

		// 批量模式 vs 单 URL 模式
		if (args.multiFigmaUrls.length > 0) {
			ensureMergedBundle(args, bundlePath, args.multiFigmaUrls);
		} else {
			ensureBundle(args, bundlePath);
		}

		bundle = readJson(bundlePath);
		const ctxElapsed = ((Date.now() - ctxStart) / 1000).toFixed(1);

		// 输出 bundle 详情
		const pc = bundle.projectContext || {};
		const rules = bundle.rules || {};
		const dc = bundle.designContext || {};
		const catalogs = bundle.componentCatalogs || [];
		_log(`[ai-direct-execute]   → 项目: ${pc.projectName || "unknown"}`);
		_log(`[ai-direct-execute]   → 框架: ${pc.framework || "unknown"}`);
		_log(`[ai-direct-execute]   → 项目 UI 包: ${(pc.installedUiPackages || []).join(", ") || "none"}`);
		_log(`[ai-direct-execute]   → Preferred VUI: ${rules.preferredVuiPackage || "none"}`);
		const vuiCat = catalogs.find((c) => c.packageName === rules.preferredVuiPackage);
		const fbCats = catalogs.filter((c) => c.packageName !== rules.preferredVuiPackage);
		if (vuiCat) {
			_log(`[ai-direct-execute]   → VUI 组件数: ${vuiCat.components?.length || 0}`);
		}
		if (fbCats.length > 0) {
			_log(`[ai-direct-execute]   → Fallback catalogs: ${fbCats.map((c) => `${c.packageName}=${c.components?.length || 0}`).join(", ")}`);
		}
		if (dc.nodeId) {
			_log(`[ai-direct-execute]   → Figma Node: ${dc.nodeId}`);
		}
		_log(`[ai-direct-execute] ✓ [1/9] Context 收集完成 (耗时 ${ctxElapsed} 秒)`);

		_log("[ai-direct-execute] ⏳ [2/9] Messages — 注入 Venus 治理规则 + 组件事实源...");
		const msgStart = Date.now();
		const messagesArgs = ["--bundle-file", bundlePath];
		if (args.existingPreviewProjectRoot) {
			messagesArgs.push("--append-mode", "--project-dir", args.existingPreviewProjectRoot);
			_log("[ai-direct-execute]   → 追加模式:将注入已有页面结构");
		}
		if (args.skipScreenshotSummary) {
			messagesArgs.push("--skip-screenshot-summary");
		}
		runNodeScript("ai-direct-messages.mjs", messagesArgs);
		const msgElapsed = ((Date.now() - msgStart) / 1000).toFixed(1);

		// 输出 messages 详情
		const messagesPath = path.join(path.dirname(bundlePath), `${path.basename(bundlePath, ".ai-direct-context-bundle.json")}.messages.json`);
		const messagesPayload = readJson(messagesPath);
		if (messagesPayload?.messages) {
			const msgCount = messagesPayload.messages.length;
			const totalChars = messagesPayload.messages.reduce((sum, m) => sum + (m.content?.length || 0), 0);
			_log(`[ai-direct-execute]   → 消息数: ${msgCount} 条`);
			_log(`[ai-direct-execute]   → 总字符数: ${(totalChars / 1000).toFixed(1)}K`);
			const roles = {};
			for (const m of messagesPayload.messages) {
				roles[m.role] = (roles[m.role] || 0) + 1;
			}
			_log(`[ai-direct-execute]   → 角色分布: ${Object.entries(roles).map(([r, n]) => `${r}=${n}`).join(", ")}`);
		}
		_log(`[ai-direct-execute] ✓ [2/9] Messages 构建完成 (耗时 ${msgElapsed} 秒)`);

		_log("[ai-direct-execute] ⏳ [3/9] 项目决策 — venus create 创建预览项目骨架...");
		_log(`[ai-direct-execute]   → 预览目录: ${args.previewDir}`);
		if (args.force) {
			_log(`[ai-direct-execute]   → 模式: force (覆盖已有项目)`);
		}
		const previewArgs = ["--bundle-file", bundlePath, "--dir", args.previewDir];
		if (args.previewName) {
			previewArgs.push("--name", args.previewName);
			_log(`[ai-direct-execute]   → 预览名: ${args.previewName}`);
		}
		if (args.existingPreviewProjectRoot) {
			previewArgs.push("--existing-project-root", path.resolve(args.existingPreviewProjectRoot));
			_log(`[ai-direct-execute]   → 已有项目: ${args.existingPreviewProjectRoot}`);
		}
		if (args.install) {
			previewArgs.push("--install");
		}
		if (args.force) {
			previewArgs.push("--force");
		}
		const projStart = Date.now();
		runNodeScript("ai-direct-preview-project.mjs", previewArgs);
		const projElapsed = ((Date.now() - projStart) / 1000).toFixed(1);

		preview = readJson(previewPath);

		// 输出预览项目详情
		if (preview?.previewProject) {
			_log(`[ai-direct-execute]   → 项目名: ${preview.previewProject.name || "unknown"}`);
			_log(`[ai-direct-execute]   → 模板: ${preview.previewProject.template || "unknown"}`);
			_log(`[ai-direct-execute]   → 选项: ${(preview.previewProject.optionals || []).join(", ") || "none"}`);
			_log(`[ai-direct-execute]   → 路径: ${preview.previewProject.projectRoot || "unknown"}`);
		}
		_log(`[ai-direct-execute] ✓ [3/9] 项目决策完成 (耗时 ${projElapsed} 秒)`);
	}

	_log("[ai-direct-execute] ⏳ [4/9] AI 生成 — Provider 调用...");
	_log(`[ai-direct-execute]   → 模型: ${args.model || process.env.AI_DIRECT_OPENAI_MODEL || "unknown"}`);
	_log(`[ai-direct-execute]   → Provider: ${args.provider || "manual"}`);
	_log(`[ai-direct-execute]   → 最大修复轮数: ${args.maxRepairRounds}`);
	_log("[ai-direct-execute]   → AI 正在生成代码,通常需要 2-5 分钟,请耐心等待...");
	// #region debug-point A:before-provider
	reportDebugEvent("A", "scripts/ai-direct-execute.mjs:run:before-provider", "[DEBUG] entering resolveAiResponse", {
		bundleFile: normalizePath(bundlePath),
		previewFile: normalizePath(previewPath),
		provider: args.provider || "manual",
		model: args.model || process.env.AI_DIRECT_OPENAI_MODEL || process.env.OPENAI_MODEL || "",
	});
	// #endregion
	const aiStartTime = Date.now();
	const aiResult = await resolveAiResponse({ args, bundlePath });
	const aiElapsed = ((Date.now() - aiStartTime) / 1000).toFixed(1);
	_log(`[ai-direct-execute]   ✓ AI Provider 响应完成 (耗时 ${aiElapsed} 秒)`);
	const plainResponse = aiResult.mode === "manual-replay" ? aiResult.response : aiResult.response;

	// 输出 AI 响应详情
	if (plainResponse?.files) {
		_log(`[ai-direct-execute]   → 生成文件数: ${plainResponse.files.length}`);
		for (const f of plainResponse.files) {
			_log(`     • ${f.path || f.filePath || "unknown"}`);
		}
	}
	if (plainResponse?.dependencyPlan) {
		const deps = plainResponse.dependencyPlan;
		_log(`[ai-direct-execute]   → 依赖变更: ${deps.dependencies ? Object.keys(deps.dependencies).length : 0} deps, ${deps.devDependencies ? Object.keys(deps.devDependencies).length : 0} devDeps`);
	}
	// #region debug-point D:after-provider
	reportDebugEvent("D", "scripts/ai-direct-execute.mjs:run:after-provider", "[DEBUG] resolveAiResponse completed", {
		mode: aiResult.mode,
		responseFile: normalizePath(aiResult.responsePath),
		fileExists: fileExists(aiResult.responsePath),
	});
	// #endregion
	persistPlainResponse(aiResult.responsePath, plainResponse);

	// #region debug-point D:before-apply
	reportDebugEvent("D", "scripts/ai-direct-execute.mjs:run:before-apply", "[DEBUG] starting apply stage", {
		responseFile: normalizePath(aiResult.responsePath),
	});
	// #endregion
	_log("[ai-direct-execute] ✓ [4/9] AI 生成完成(Provider 响应已接收)");
	_log("[ai-direct-execute] ⏳ [5/9] 文件写入 — apply-output(含路由注册)...");
	_log(`[ai-direct-execute]   → 开始应用 AI 输出...`);
	const applyArgs = [
		"--response-file",
		aiResult.responsePath,
		"--preview-file",
		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);
	}
	if (args.existingPreviewProjectRoot) {
		applyArgs.push("--append-mode");
		// 检测单页面模式:bundle 没有 _batchMode 时为单 URL 生成
		const isSinglePageMode = !bundle.figma?._batchMode;
		if (isSinglePageMode) {
			applyArgs.push("--single-page-mode");
		}
		if (args.pageName) {
			applyArgs.push("--page-name", args.pageName);
		}
		// 传递批次信息,让管道控制文件组织
		const batchUrls = bundle.figma?._batchUrls || [];
		if (batchUrls.length > 0) {
			applyArgs.push("--batch-urls", batchUrls.join(","));
		}
		if (args.batchIndex !== undefined) {
			applyArgs.push("--batch-index", String(args.batchIndex));
		}
	}
	runNodeScript("ai-direct-apply-output.mjs", applyArgs);
	_log("[ai-direct-execute] ✓ [5/9] 文件写入完成(代码已应用 + 路由已注册)");

	let validationPassed = true;
	const valStart = Date.now();

	if (args.skipValidate) {
		_log("[ai-direct-execute] ⏳ [6/9] 质量校验 — 跳过(--skip-validate)");
	} else if (args.skipFitness) {
		_log("[ai-direct-execute] ⏳ [6/9] 质量校验 — 跳过(--skip-fitness,将在最后统一校验)");
	} else {
		_log("[ai-direct-execute] ⏳ [6/9] 质量校验 — validate + fitness 全维度 + smart-check...");
		_log(`[ai-direct-execute]   → Response: ${normalizePath(aiResult.responsePath)}`);
		_log(`[ai-direct-execute]   → Preview: ${normalizePath(previewPath)}`);
		try {
		// #region debug-point B:before-validate
			reportDebugEvent("B", "scripts/ai-direct-execute.mjs:run:before-validate", "[DEBUG] starting validate stage", {
				responseFile: normalizePath(aiResult.responsePath),
				previewFile: normalizePath(previewPath),
			});
			// #endregion
			runNodeScript("ai-direct-validate-output.mjs", [
				"--response-file",
				aiResult.responsePath,
				"--preview-file",
				previewPath,
			]);
		} catch {
			validationPassed = false;
		}
		// #region debug-point D:after-validate
		reportDebugEvent("D", "scripts/ai-direct-execute.mjs:run:after-validate", "[DEBUG] validate stage completed", {
			validationPassed,
		});
	// #endregion
	}
	const valElapsed = ((Date.now() - valStart) / 1000).toFixed(1);

	const validationPath = path.join(
		path.dirname(aiResult.responsePath),
		`${path.basename(aiResult.responsePath, path.extname(aiResult.responsePath))}.validation-result.json`,
	);
	const validation = readJson(validationPath);

	// 输出校验结果详情
	if (validation) {
		_log(`[ai-direct-execute]   → 校验状态: ${validation.status || "unknown"}`);
		const ruleErrors = validation.ruleValidation?.errors || [];
		const ruleWarnings = validation.ruleValidation?.warnings || [];
		const styleErrors = validation.styleValidation?.errors || [];
		const styleWarnings = validation.styleValidation?.warnings || [];
		const primaryErrors = validation.primaryDataValidation?.errors || [];
		const visualErrors = validation.visualSummaryValidation?.errors || [];
		const visualWarnings = validation.visualSummaryValidation?.warnings || [];
		const pageStructureErrors = validation.pageStructureValidation?.errors || [];
		const pageStructureWarnings = validation.pageStructureValidation?.warnings || [];
		const importErrors = validation.importConsistencyValidation?.errors || [];
		const failedCmds = (validation.commandResults || []).filter((item) => !item.ok);
		_log(`[ai-direct-execute]   → 规则: ${ruleErrors.length} 错误, ${ruleWarnings.length} 警告`);
		_log(`[ai-direct-execute]   → 样式: ${styleErrors.length} 错误, ${styleWarnings.length} 警告`);
		_log(`[ai-direct-execute]   → 主数据: ${primaryErrors.length} 错误`);
		_log(`[ai-direct-execute]   → 视觉摘要: ${visualErrors.length} 错误, ${visualWarnings.length} 警告`);
		const templateSyntaxErrors = validation.templateSyntaxValidation?.errors || [];
		const templateSyntaxWarnings = validation.templateSyntaxValidation?.warnings || [];
		const designFidelityErrors = validation.designFidelityValidation?.errors || [];
		const designFidelityWarnings = validation.designFidelityValidation?.warnings || [];
		if (templateSyntaxErrors.length > 0 || templateSyntaxWarnings.length > 0) {
			_log(`[ai-direct-execute]   → Template语法: ${templateSyntaxErrors.length} 错误, ${templateSyntaxWarnings.length} 警告`);
		}
		if (designFidelityErrors.length > 0 || designFidelityWarnings.length > 0) {
			_log(`[ai-direct-execute]   → 设计还原: ${designFidelityErrors.length} 错误, ${designFidelityWarnings.length} 警告`);
		}
		if (pageStructureErrors.length > 0 || pageStructureWarnings.length > 0) {
			_log(`[ai-direct-execute]   → 页面目录: ${pageStructureErrors.length} 错误, ${pageStructureWarnings.length} 警告`);
		}
		if (importErrors.length > 0) {
			_log(`[ai-direct-execute]   → 导入一致性: ${importErrors.length} 错误`);
			for (const err of importErrors) {
				_log(`[ai-direct-execute]     - ${err}`);
			}
		}
		if (failedCmds.length > 0) {
			_log(`[ai-direct-execute]   → 命令失败: ${failedCmds.map((c) => c.command).join(", ")}`);
		}
		const typeCheckResult = validation.typeCheckResult;
		if (typeCheckResult && !typeCheckResult.ok) {
			_log(`[ai-direct-execute]   → type-check: warning (exit=${typeCheckResult.exitCode}),不阻断校验`);
		}
	}
	if (!args.skipFitness) {
		_log(`[ai-direct-execute] ${validationPassed ? "✓" : "✗"} [6/9] 质量校验完成 (耗时 ${valElapsed} 秒) — ${validationPassed ? "通过" : "未通过"}`);
	}

	const summary = {
		meta: {
			generator: "scripts/ai-direct-execute.mjs",
			generatedAt: new Date().toISOString(),
			mode: aiResult.mode,
			bundleFile: normalizePath(bundlePath),
			previewFile: normalizePath(previewPath),
			responseFile: normalizePath(aiResult.responsePath),
			validationFile: normalizePath(validationPath),
		},
		status: validationPassed ? "passed" : "failed",
		repairRoundsAttempted: 0,
	};

	let latestResponse = plainResponse;
	let latestValidation = validation;
	let repairArtifacts = null;
	if (!validationPassed) {
		repairArtifacts = buildRepairArtifacts({
			bundle,
			preview,
			response: latestResponse,
			validation: latestValidation,
			responsePath: aiResult.responsePath,
		});
		summary.repairArtifacts = {
			feedbackFile: normalizePath(repairArtifacts.feedbackPath),
			requestFile: normalizePath(repairArtifacts.requestPath),
		};
	}

	while (!validationPassed && shouldAttemptAutoRepair(args) && summary.repairRoundsAttempted < args.maxRepairRounds) {
		summary.repairRoundsAttempted += 1;
		_log(`[ai-direct-execute] 尝试第 ${summary.repairRoundsAttempted} 轮 repair...`);

		try {
			const repairArgs = [
				"--response-file",
				aiResult.responsePath,
				"--preview-file",
				previewPath,
				"--provider",
				args.provider,
				"--request-file",
				repairArtifacts.requestPath,
				"--feedback-file",
				repairArtifacts.feedbackPath,
				"--round",
				String(summary.repairRoundsAttempted),
			];

			if (args.model) {
				repairArgs.push("--model", args.model);
			}

			// Repair 不设超时限制,让 AI 充分完成复杂修复
			_log(`[ai-direct-execute]   → Repair 执行中...`);
			runNodeScript("ai-direct-repair-output.mjs", repairArgs, 0);
		} catch (repairError) {
			const msg = repairError.message || String(repairError);
			_warn(`[ai-direct-execute]   ⚠ Repair 执行失败: ${msg}`);
		}

		latestResponse = unwrapResponseFile(aiResult.responsePath);
		latestValidation = readJson(validationPath);
		validationPassed = latestValidation.status === "passed";
		summary.status = validationPassed ? "passed" : "failed";

		if (!validationPassed) {
			repairArtifacts = buildRepairArtifacts({
				bundle,
				preview,
				response: latestResponse,
				validation: latestValidation,
				responsePath: aiResult.responsePath,
			});
			summary.repairArtifacts = {
				feedbackFile: normalizePath(repairArtifacts.feedbackPath),
				requestFile: normalizePath(repairArtifacts.requestPath),
			};
		}
	}

	const summaryPath = path.join(
		path.dirname(bundlePath),
		`${path.basename(bundlePath, ".ai-direct-context-bundle.json")}.execute-result.json`,
	);
	fs.writeFileSync(summaryPath, `${JSON.stringify(summary, null, 2)}\n`, "utf8");

	_log(`  → summary: ${summaryPath}`);

	// Fitness 全维度校验(增量过滤模式)
	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;
	});
	let fitnessResults = [];
	let failedFitness = [];

	if (args.skipValidate) {
		_log("[ai-direct-execute] ⏳ [7/9] 健康修复 — 跳过(--skip-validate)");
	} else if (!args.skipFitness) {
		fitnessResults = runFitnessChecks(aiChangedFiles);
		failedFitness = fitnessResults.filter((r) => r.status === "fail");
		summary.fitnessResults = fitnessResults;

		if (failedFitness.length > 0) {
			_warn(`[ai-direct-execute]   ⚠ Fitness ${failedFitness.length} 个维度未通过,需要人工处理:`);
			for (const item of failedFitness) {
				_warn(`[ai-direct-execute]     - ${item.name}: ${item.detail?.slice(0, 200) || "无详情"}`);
			}
		}
	}

	// 健康修复
	const projectRoot = preview.previewProject?.projectRoot;
	if (projectRoot && !args.skipValidate) {
		runDiagnoseAndFix(projectRoot);
	}

	// 安装启动
	_log("[ai-direct-execute] ⏳ [8/9] 安装启动 — pnpm install + dev server + iframe 预览...");
	if (args.skipPreview) {
		_log("[ai-direct-execute]   → skipPreview=true,跳过安装启动");
	} else {
		await launchPreviewProject(preview);
	}

	// 汇总
	const skippedFitness = fitnessResults.filter((r) => r.status === "skipped");
	const executedFitness = fitnessResults.filter((r) => r.status !== "skipped");
	_log(`[ai-direct-execute]   → Summary: ${summaryPath}`);
	_log(`[ai-direct-execute]   → 状态: ${summary.status}`);
	_log(`[ai-direct-execute]   → Fitness: ${executedFitness.filter((r) => r.status === "pass").length}/${executedFitness.length} 通过${skippedFitness.length > 0 ? `,${skippedFitness.length} 跳过` : ""}`);
	if (failedFitness.length > 0) {
		_log(`[ai-direct-execute]   → ⚠ 未通过: ${failedFitness.map((f) => f.name).join(", ")}`);
	}
	if (skippedFitness.length > 0) {
		_log(`[ai-direct-execute]   → ⏭ 跳过: ${skippedFitness.map((f) => f.name).join(", ")}`);
	}
	if (summary.repairArtifacts) {
		_log(`[ai-direct-execute]   → Repair feedback: ${summary.repairArtifacts.feedbackFile}`);
		_log(`[ai-direct-execute]   → Repair request: ${summary.repairArtifacts.requestFile}`);
	}
	_log(`[ai-direct-execute]   → 修复轮数: ${summary.repairRoundsAttempted}`);

	if (!validationPassed) {
		_error("[ai-direct-execute] ✗ 校验未通过,已生成 repair artifacts");
		process.exit(1);
	}

	_log("[ai-direct-execute] ═══════════════════════════════════════");
	_log("[ai-direct-execute]   ✓ 全流程完成");
	_log("[ai-direct-execute] ═══════════════════════════════════════");
	process.exit(0);
}

run().catch((error) => {
	_error("[ai-direct-execute] 执行失败:", error.message);
	process.exit(1);
});