ai-direct-execute.mjs 20.6 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
#!/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,
	};

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

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

	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" },
		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"),
	});
	// #endregion
	const response = await fetch(endpoint, {
		method: "POST",
		headers: {
			"content-type": "application/json",
			authorization: `Bearer ${apiKey}`,
			connection: "close",
		},
		signal: AbortSignal.timeout(180_000),
		body: requestBody,
	});
	// #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,
	});
	// #endregion

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

	const payload = await response.json();
	const content = payload.choices?.[0]?.message?.content;
	return {
		provider: "openai-compatible",
		model: resolvedModel,
		raw: payload,
		content,
	};
}

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

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

	console.log("[ai-direct-execute] 开始执行 AI 直生闭环...");
	console.log(`  → bundle: ${bundlePath}`);

	ensureBundle(args, bundlePath);
	const bundle = readJson(bundlePath);

	runNodeScript("ai-direct-messages.mjs", ["--bundle-file", bundlePath]);

	const previewArgs = ["--bundle-file", bundlePath, "--dir", args.previewDir];
	if (args.previewName) {
		previewArgs.push("--name", args.previewName);
	}
	if (args.existingPreviewProjectRoot) {
		previewArgs.push("--existing-project-root", path.resolve(args.existingPreviewProjectRoot));
	}
	if (args.install) {
		previewArgs.push("--install");
	}
	if (args.force) {
		previewArgs.push("--force");
	}
	runNodeScript("ai-direct-preview-project.mjs", previewArgs);

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

	// #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 aiResult = await resolveAiResponse({ args, bundlePath });
	const plainResponse = aiResult.mode === "manual-replay" ? aiResult.response : aiResult.response;
	// #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
	runNodeScript("ai-direct-apply-output.mjs", [
		"--response-file",
		aiResult.responsePath,
		"--preview-file",
		previewPath,
	]);

	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 validationPath = path.join(
		path.dirname(aiResult.responsePath),
		`${path.basename(aiResult.responsePath, path.extname(aiResult.responsePath))}.validation-result.json`,
	);
	const validation = readJson(validationPath);

	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}`);
	if (!validationPassed) {
		console.error("[ai-direct-execute] 失败,已生成 repair artifacts");
		process.exit(1);
	}

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

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