ai-direct-execute.mjs 38.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 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
#!/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";

const repoRoot = requireWorkspaceRoot();

function parseCliArgs() {
	const args = process.argv.slice(2);
	const parsed = {
		bundleFile: "",
		projectDir: "",
		figmaUrl: "",
		pageName: "",
		pageTitle: "",
		outputDir: "",
		previewName: "",
		previewDir: "apps/web/ai-previews",
		existingPreviewProjectRoot: "",
		responseFile: "",
		provider: "",
		model: "",
		autoRepair: false,
		maxRepairRounds: 1,
		withoutVariables: false,
		install: false,
		refreshContext: false,
		force: false,
		skipPreview: false,
		targetPlatform: "",
		fallbackUi: "",
	};

	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
			switch (arg) {
				case "--auto-repair": {
					parsed.autoRepair = true;

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

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

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

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

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

					break;
				}
				// No default
			}
	}

	return parsed;
}

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

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

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);
	}

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

	const projectDir = path.resolve(args.projectDir);
	const pageSlug = slugify(derivePageName(args.pageName, args.pageTitle, args.figmaUrl));
	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) {
	const commandArgs = [path.join(repoRoot, "scripts", scriptFile), ...scriptArgs];
	childProcess.execFileSync(process.execPath, commandArgs, {
		cwd: repoRoot,
		stdio: "inherit",
	});
}

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

	const cliEntry = path.join(repoRoot, "packages", "cli", "dist", "index.cjs.js");
	if (!fs.existsSync(cliEntry)) {
		console.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 {}
	console.log(`[ai-direct-execute]   ✓ Venus CLI 已就绪`);
	console.log(`[ai-direct-execute]   → pnpm: ${pnpmVersion}`);

	// 检查 git
	try {
		const gitBranch = childProcess.execSync("git branch --show-current", { stdio: "pipe", shell: true }).toString().trim();
		console.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,
		});
		console.log("[ai-direct-execute]   ✓ 模板契约校验通过");
	} catch (error) {
		const output = (error.stdout?.toString() || "") + (error.stderr?.toString() || "");
		console.warn("[ai-direct-execute]   ⚠ 模板契约存在警告:", output.slice(0, 300));
	}
	console.log("[ai-direct-execute] ✓ [0/8] 环境预检完成");
}

// [5] Fitness 全维度校验
function runFitnessChecks() {
	console.log("[ai-direct-execute] ⏳ [5/8] 质量校验 — 执行 Fitness 全维度校验...");

	const shell = process.platform === "win32";
	const checks = [
		{ name: "CodeQuality (typecheck)", cmd: "pnpm run check:type" },
		{ name: "TemplateContract", cmd: "pnpm run check:template-contract" },
		{ name: "ReviewTriggers", cmd: "pnpm run review:trigger" },
		{ name: "Evolvability (file-budget)", cmd: "pnpm run check:file-budget" },
		{ name: "AIArtifacts", cmd: "pnpm run check:ai-artifacts" },
	];

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

	const passed = results.filter((r) => r.status === "pass").length;
	console.log(`[ai-direct-execute] ✓ [5/8] Fitness 汇总: ${passed}/${results.length} 维度通过`);
	return results;
}

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

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

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

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);
}

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 返回为空");
	}

	try {
		return JSON.parse(trimmed);
	} catch {}

	const fencedMatch = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/i);
	if (fencedMatch) {
		return JSON.parse(fencedMatch[1].trim());
	}

	const start = trimmed.indexOf("{");
	const end = trimmed.lastIndexOf("}");
	if (start !== -1 && end !== -1 && end > start) {
		return JSON.parse(trimmed.slice(start, end + 1));
	}

	throw new Error("无法从 AI 返回中提取 JSON");
}

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}`);
	}

	console.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);
						console.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);
	console.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,
	};
}

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);
	let providerResult;

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

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

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

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 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,
		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 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 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、列名和示例数据,不要让截图摘要覆盖这些文本事实。",
		"- 如果失败项来自截图视觉摘要校验,优先修正标题、筛选标签、选择框数量、表格列、操作文案和分页布局,使页面与截图摘要一致。",
		"- 如果失败项来自样式责任校验,直接在生成文件中补齐页面级样式,不要把布局或视觉修复转嫁给预览项目壳层。",
		"- 输出完整结构化 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);
}

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

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

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

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

	console.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);
		console.log(`[ai-direct-execute]   ✓ pnpm install 完成 (耗时 ${installElapsed} 秒)`);
	} catch {
		if (!fs.existsSync(nodeModulesPath)) {
			console.error("[ai-direct-execute]   ✗ pnpm install 失败且 node_modules 不存在,跳过启动预览项目");
			return;
		}
		console.warn("[ai-direct-execute]   ⚠ pnpm install postinstall 存在非致命错误,但依赖已安装,继续启动");
	}

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

	console.log(`[ai-direct-execute]   ✓ 预览服务已在后台启动 (pid: ${devServer.pid})`);
}

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

	console.log("[ai-direct-execute] ═══════════════════════════════════════");
	console.log("[ai-direct-execute]   Venus AI Direct Pipeline");
	console.log(`[ai-direct-execute]   时间: ${new Date().toLocaleString()}`);
	console.log(`[ai-direct-execute]   Bundle: ${bundlePath}`);
	console.log(`[ai-direct-execute]   Provider: ${args.provider || "manual"}`);
	console.log(`[ai-direct-execute]   Model: ${args.model || process.env.AI_DIRECT_OPENAI_MODEL || "unknown"}`);
	console.log(`[ai-direct-execute]   Force: ${args.force}`);
	console.log("[ai-direct-execute] ═══════════════════════════════════════");

	runEnvironmentPreCheck();

	console.log("[ai-direct-execute] ⏳ [1/8] Context 收集 — figma-client + project-intelligence + component-manifest...");
	const ctxStart = Date.now();
	ensureBundle(args, bundlePath);
	const 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 || [];
	console.log(`[ai-direct-execute]   → 项目: ${pc.projectName || "unknown"}`);
	console.log(`[ai-direct-execute]   → 框架: ${pc.framework || "unknown"}`);
	console.log(`[ai-direct-execute]   → 项目 UI 包: ${(pc.installedUiPackages || []).join(", ") || "none"}`);
	console.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) {
		console.log(`[ai-direct-execute]   → VUI 组件数: ${vuiCat.components?.length || 0}`);
	}
	if (fbCats.length > 0) {
		console.log(`[ai-direct-execute]   → Fallback catalogs: ${fbCats.map((c) => `${c.packageName}=${c.components?.length || 0}`).join(", ")}`);
	}
	if (dc.nodeId) {
		console.log(`[ai-direct-execute]   → Figma Node: ${dc.nodeId}`);
	}
	console.log(`[ai-direct-execute] ✓ [1/8] Context 收集完成 (耗时 ${ctxElapsed} 秒)`);

	console.log("[ai-direct-execute] ⏳ [2/8] Messages — 注入 Venus 治理规则 + 组件事实源...");
	const msgStart = Date.now();
	runNodeScript("ai-direct-messages.mjs", ["--bundle-file", bundlePath]);
	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);
		console.log(`[ai-direct-execute]   → 消息数: ${msgCount} 条`);
		console.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;
		}
		console.log(`[ai-direct-execute]   → 角色分布: ${Object.entries(roles).map(([r, n]) => `${r}=${n}`).join(", ")}`);
	}
	console.log(`[ai-direct-execute] ✓ [2/8] Messages 构建完成 (耗时 ${msgElapsed} 秒)`);

	console.log("[ai-direct-execute] ⏳ [3/8] 项目决策 — venus create 创建预览项目骨架...");
	console.log(`[ai-direct-execute]   → 预览目录: ${args.previewDir}`);
	if (args.force) {
		console.log(`[ai-direct-execute]   → 模式: force (覆盖已有项目)`);
	}
	const previewArgs = ["--bundle-file", bundlePath, "--dir", args.previewDir];
	if (args.previewName) {
		previewArgs.push("--name", args.previewName);
		console.log(`[ai-direct-execute]   → 预览名: ${args.previewName}`);
	}
	if (args.existingPreviewProjectRoot) {
		previewArgs.push("--existing-project-root", path.resolve(args.existingPreviewProjectRoot));
		console.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);

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

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

	console.log("[ai-direct-execute] ⏳ [4/8] AI 生成 — Provider 调用 + apply-output(含路由注册)...");
	console.log(`[ai-direct-execute]   → 模型: ${args.model || process.env.AI_DIRECT_OPENAI_MODEL || "unknown"}`);
	console.log(`[ai-direct-execute]   → Provider: ${args.provider || "manual"}`);
	console.log(`[ai-direct-execute]   → 最大修复轮数: ${args.maxRepairRounds}`);
	console.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);
	console.log(`[ai-direct-execute]   ✓ AI Provider 响应完成 (耗时 ${aiElapsed} 秒)`);
	const plainResponse = aiResult.mode === "manual-replay" ? aiResult.response : aiResult.response;

	// 输出 AI 响应详情
	if (plainResponse?.files) {
		console.log(`[ai-direct-execute]   → 生成文件数: ${plainResponse.files.length}`);
		for (const f of plainResponse.files) {
			console.log(`     • ${f.path || f.filePath || "unknown"}`);
		}
	}
	if (plainResponse?.dependencyPlan) {
		const deps = plainResponse.dependencyPlan;
		console.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
	console.log(`[ai-direct-execute]   → 开始应用 AI 输出...`);
	runNodeScript("ai-direct-apply-output.mjs", [
		"--response-file",
		aiResult.responsePath,
		"--preview-file",
		previewPath,
	]);
	console.log("[ai-direct-execute] ✓ [4/8] AI 生成完成(代码已应用 + 路由已注册)");

	console.log("[ai-direct-execute] ⏳ [5/8] 质量校验 — validate + fitness 全维度 + smart-check...");
	console.log(`[ai-direct-execute]   → Response: ${normalizePath(aiResult.responsePath)}`);
	console.log(`[ai-direct-execute]   → Preview: ${normalizePath(previewPath)}`);
	const valStart = Date.now();
	let validationPassed = true;
	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) {
		console.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 failedCmds = (validation.commandResults || []).filter((item) => !item.ok);
		console.log(`[ai-direct-execute]   → 规则: ${ruleErrors.length} 错误, ${ruleWarnings.length} 警告`);
		console.log(`[ai-direct-execute]   → 样式: ${styleErrors.length} 错误, ${styleWarnings.length} 警告`);
		console.log(`[ai-direct-execute]   → 主数据: ${primaryErrors.length} 错误`);
		console.log(`[ai-direct-execute]   → 视觉摘要: ${visualErrors.length} 错误, ${visualWarnings.length} 警告`);
		if (failedCmds.length > 0) {
			console.log(`[ai-direct-execute]   → 命令失败: ${failedCmds.map((c) => c.command).join(", ")}`);
		}
	}
	console.log(`[ai-direct-execute] ${validationPassed ? "✓" : "✗"} [5/8] 质量校验完成 (耗时 ${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;
		console.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,
			];

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

			runNodeScript("ai-direct-repair-output.mjs", repairArgs);
		} catch {
			// Repair script writes validation artifacts even on failure.
		}

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

	console.log(`  → summary: ${summaryPath}`);

	// Fitness 全维度校验
	runFitnessChecks();

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

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

	// 人工确认
	console.log("[ai-direct-execute] ⏳ [8/8] 人工确认 — 查看控制台 Fitness 报告 + 预览 + 文件浏览");
	console.log(`[ai-direct-execute]   → Summary: ${summaryPath}`);
	console.log(`[ai-direct-execute]   → 状态: ${summary.status}`);
	if (summary.repairArtifacts) {
		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]   → 修复轮数: ${summary.repairRoundsAttempted}`);

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

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

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