check-ai-artifacts.mjs 24.8 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
#!/usr/bin/env node

/**
 * AI 产物专项 fitness 检查
 *
 * 验证 contracts/ai/examples/ 和 packages/ai/patcher/examples/ 下的 AI 产物:
 * 1. page-schema 结构完整性 + 语义字段覆盖率
 * 2. incremental-patch-plan 结构完整性 + operation 有效性
 * 3. project-context 结构完整性 + 新增字段存在性
 */

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

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

const repoRoot = requireWorkspaceRoot();
const failures = [];
const warnings = [];
const stats = {
	pageSchemas: 0,
	patchPlans: 0,
	projectContexts: 0,
	designMapperSuggestions: 0,
	aiDirectBundles: 0,
	totalChecks: 0,
};

// ── 1. Page Schema 检查 ──

function findFiles(dir, suffix) {
	if (!fs.existsSync(dir)) {
		return [];
	}
	const results = [];
	const queue = [dir];
	while (queue.length > 0) {
		const current = queue.shift();
		for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
			const full = path.join(current, entry.name);
			if (entry.isDirectory()) {
				queue.push(full);
			} else if (entry.name.endsWith(suffix)) {
				results.push(full);
			}
		}
	}
	return results;
}

function relativePath(file) {
	return path.relative(repoRoot, file).replaceAll("\\", "/");
}

function check(condition, file, message) {
	stats.totalChecks++;
	if (!condition) {
		failures.push(`${relativePath(file)}: ${message}`);
	}
}

function warn(file, message) {
	warnings.push(`${relativePath(file)}: ${message}`);
}

// ── Page Schema 验证 ──

function validatePageSchema(data, file) {
	stats.pageSchemas++;

	// 必需字段
	for (const key of ["pageId", "title", "source", "layout", "sections"]) {
		check(key in data, file, `missing required field: ${key}`);
	}

	// source 检查
	if (data.source) {
		check("kind" in data.source, file, "source missing 'kind'");
		const validKinds = ["figma-frame", "manual", "mixed", "requirement-text"];
		check(
			validKinds.includes(data.source.kind),
			file,
			`source.kind "${data.source.kind}" not in ${validKinds.join(", ")}`,
		);
	}

	// layout 检查
	if (data.layout) {
		check("shell" in data.layout, file, "layout missing 'shell'");
		const validShells = ["blank", "dashboard", "detail", "form", "list", "workspace"];
		check(
			validShells.includes(data.layout.shell),
			file,
			`layout.shell "${data.layout.shell}" not in ${validShells.join(", ")}`,
		);
	}

	// sections 检查
	if (Array.isArray(data.sections)) {
		check(data.sections.length > 0, file, "sections must have at least 1 item");

		let sectionsWithRole = 0;
		let blocksWithRole = 0;
		let blocksTotal = 0;
		let actionsWithScope = 0;
		let actionsTotal = 0;
		let fieldsWithGroup = 0;
		let fieldsTotal = 0;

		for (const section of data.sections) {
			check("id" in section, file, "section missing 'id'");
			check("name" in section, file, `section ${section.id || "?"} missing 'name'`);
			check(
				Array.isArray(section.blocks) && section.blocks.length > 0,
				file,
				`section ${section.id || "?"} must have at least 1 block`,
			);

			if (section.role) {
				sectionsWithRole++;
			}

			for (const block of section.blocks || []) {
				blocksTotal++;
				check("id" in block, file, `block in section ${section.id || "?"} missing 'id'`);
				check("kind" in block, file, `block ${block.id || "?"} missing 'kind'`);

				const validBlockKinds = [
					"actions",
					"card",
					"chart",
					"container",
					"description",
					"form",
					"hero",
					"list",
					"stats",
					"table",
					"text",
				];
				check(
					validBlockKinds.includes(block.kind),
					file,
					`block ${block.id || "?"} kind "${block.kind}" not in ${validBlockKinds.join(", ")}`,
				);

				if (block.role) {
					blocksWithRole++;
				}

				for (const action of block.actions || []) {
					actionsTotal++;
					check("id" in action, file, `action in block ${block.id || "?"} missing 'id'`);
					check("label" in action, file, `action ${action.id || "?"} missing 'label'`);
					check("kind" in action, file, `action ${action.id || "?"} missing 'kind'`);

					const validActionKinds = ["dialog", "navigate", "request", "submit", "toggle"];
					check(
						validActionKinds.includes(action.kind),
						file,
						`action ${action.id || "?"} kind "${action.kind}" not in ${validActionKinds.join(", ")}`,
					);

					if (action.scope) {
						actionsWithScope++;
					}
				}

				for (const field of block.fields || []) {
					fieldsTotal++;
					check("id" in field, file, `field in block ${block.id || "?"} missing 'id'`);
					check("label" in field, file, `field ${field.id || "?"} missing 'label'`);
					check("type" in field, file, `field ${field.id || "?"} missing 'type'`);

					const validFieldTypes = ["date", "number", "select", "switch", "text", "textarea"];
					check(
						validFieldTypes.includes(field.type),
						file,
						`field ${field.id || "?"} type "${field.type}" not in ${validFieldTypes.join(", ")}`,
					);

					if (field.group) {
						fieldsWithGroup++;
					}
				}
			}
		}

		// 语义覆盖率报告(warn 不阻断,但如果覆盖率为 0 且有 actions/fields 则标记为 warning)
		const sectionCount = data.sections.length;
		if (sectionsWithRole === 0 && sectionCount > 0) {
			warn(file, `section role coverage: 0/${sectionCount} (no sections have role)`);
		}
		if (blocksTotal > 0 && blocksWithRole === 0) {
			warn(file, `block role coverage: 0/${blocksTotal} (no blocks have role)`);
		}
		if (actionsTotal > 0 && actionsWithScope === 0) {
			warn(file, `action scope coverage: 0/${actionsTotal} (no actions have scope)`);
		}
		if (fieldsTotal > 0 && fieldsWithGroup === 0) {
			warn(file, `field group coverage: 0/${fieldsTotal} (no fields have group)`);
		}
	}
}

// ── Incremental Patch Plan 验证 ──

function validatePatchPlan(data, file) {
	stats.patchPlans++;

	// 必需字段
	for (const key of ["planId", "targetProject", "page", "routeRegistration", "operations", "validation"]) {
		check(key in data, file, `missing required field: ${key}`);
	}

	// targetProject 检查
	if (data.targetProject) {
		for (const key of ["projectName", "projectRoot", "framework"]) {
			check(key in data.targetProject, file, `targetProject missing '${key}'`);
		}
	}

	// routeRegistration 检查
	if (data.routeRegistration) {
		check("strategy" in data.routeRegistration, file, "routeRegistration missing 'strategy'");
		check("routeFile" in data.routeRegistration, file, "routeRegistration missing 'routeFile'");

		const validStrategies = [
			"static-routes-array",
			"router-factory-routes-array",
			"dynamic-add-routes-helper",
			"generic-review",
		];
		check(
			validStrategies.includes(data.routeRegistration.strategy),
			file,
			`routeRegistration.strategy "${data.routeRegistration.strategy}" not in ${validStrategies.join(", ")}`,
		);
	}

	// operations 检查
	if (Array.isArray(data.operations)) {
		check(data.operations.length > 0, file, "operations must have at least 1 item");

		const validKinds = ["create-file", "patch-file", "review-only"];
		const validPatchStrategies = ["append-snippet", "manual-review", "none"];

		const operationIds = new Set();
		for (const op of data.operations) {
			check("id" in op, file, "operation missing 'id'");
			check("kind" in op, file, `operation ${op.id || "?"} missing 'kind'`);
			check("targetPath" in op, file, `operation ${op.id || "?"} missing 'targetPath'`);
			check("description" in op, file, `operation ${op.id || "?"} missing 'description'`);

			check(
				validKinds.includes(op.kind),
				file,
				`operation ${op.id || "?"} kind "${op.kind}" not in ${validKinds.join(", ")}`,
			);

			if (op.patchStrategy) {
				check(
					validPatchStrategies.includes(op.patchStrategy),
					file,
					`operation ${op.id || "?"} patchStrategy "${op.patchStrategy}" not in ${validPatchStrategies.join(", ")}`,
				);
			}

			// 检查 operation ID 唯一性
			if (op.id) {
				check(!operationIds.has(op.id), file, `duplicate operation id: ${op.id}`);
				operationIds.add(op.id);
			}

			// dependsOn 引用检查
			if (Array.isArray(op.dependsOn)) {
				for (const dep of op.dependsOn) {
					check(operationIds.has(dep), file, `operation ${op.id || "?"} depends on unknown id: ${dep}`);
				}
			}
		}

		// 检查是否至少有一个 create-file 或 patch-file 操作
		const fileOps = data.operations.filter((op) => op.kind === "create-file" || op.kind === "patch-file");
		check(fileOps.length > 0, file, "operations must include at least one create-file or patch-file");
	}

	// validation 检查
	if (data.validation) {
		check(
			Array.isArray(data.validation.commands) && data.validation.commands.length > 0,
			file,
			"validation.commands must be a non-empty array",
		);
	}

	// semanticContext 存在性检查(warn 级别)
	if (!data.semanticContext) {
		warn(file, "patch plan missing semanticContext (expected for enriched plans)");
	} else {
		// 验证 semanticContext 的已知子字段类型
		const sc = data.semanticContext;
		if (sc.sectionRoles && !Array.isArray(sc.sectionRoles)) {
			check(false, file, "semanticContext.sectionRoles should be an array");
		}
		if (sc.actionScopeDistribution && typeof sc.actionScopeDistribution !== "object") {
			check(false, file, "semanticContext.actionScopeDistribution should be an object");
		}
		if (sc.blockRoleDistribution && typeof sc.blockRoleDistribution !== "object") {
			check(false, file, "semanticContext.blockRoleDistribution should be an object");
		}
	}
}

// ── Project Context 验证 ──

function validateProjectContext(data, file) {
	stats.projectContexts++;

	// 必需字段
	for (const key of ["projectName", "projectRoot", "workspace", "framework", "directories", "qualityGates"]) {
		check(key in data, file, `missing required field: ${key}`);
	}

	// workspace 检查
	if (data.workspace) {
		check("inWorkspace" in data.workspace, file, "workspace missing 'inWorkspace'");
	}

	// directories 检查
	if (data.directories) {
		check("srcDir" in data.directories, file, "directories missing 'srcDir'");
	}

	// qualityGates 检查
	if (data.qualityGates) {
		check("lint" in data.qualityGates, file, "qualityGates missing 'lint'");
	}

	// 新增字段检查(warn 级别)
	if (!("existingPages" in data)) {
		warn(file, "project context missing 'existingPages' (added in project-intelligence enhancement)");
	}
	if (!("namingConventions" in data)) {
		warn(file, "project context missing 'namingConventions' (added in project-intelligence enhancement)");
	}
	if (!("apiLayer" in data)) {
		warn(file, "project context missing 'apiLayer' (added in project-intelligence enhancement)");
	}

	// existingPages 结构检查
	if (data.existingPages) {
		check("total" in data.existingPages, file, "existingPages missing 'total'");
		check("pages" in data.existingPages, file, "existingPages missing 'pages'");
		check(Array.isArray(data.existingPages.pages), file, "existingPages.pages should be an array");
	}

	// namingConventions 结构检查
	if (data.namingConventions) {
		check("dominantConvention" in data.namingConventions, file, "namingConventions missing 'dominantConvention'");
		const validConventions = ["PascalCase", "kebab-case", "camelCase", "unknown"];
		check(
			validConventions.includes(data.namingConventions.dominantConvention),
			file,
			`namingConventions.dominantConvention "${data.namingConventions.dominantConvention}" not in ${validConventions.join(", ")}`,
		);
	}

	// apiLayer 结构检查
	if (data.apiLayer) {
		check("hasApiLayer" in data.apiLayer, file, "apiLayer missing 'hasApiLayer'");
		check(typeof data.apiLayer.hasApiLayer === "boolean", file, "apiLayer.hasApiLayer should be a boolean");
	}

	// framework 枚举检查
	if (data.framework) {
		const validFrameworks = ["micro-frontend", "react", "shared", "uniappX", "unknown", "vue"];
		check(
			validFrameworks.includes(data.framework),
			file,
			`framework "${data.framework}" not in ${validFrameworks.join(", ")}`,
		);
	}
}

// ── Design Mapper Suggestions 验证 ──

function validateDesignMapperSuggestions(data, file) {
	stats.designMapperSuggestions++;

	// $meta
	check("$meta" in data, file, "missing '$meta'");
	if (data.$meta) {
		check("generator" in data.$meta, file, "$meta missing 'generator'");
		check("source" in data.$meta, file, "$meta missing 'source'");
		check("manifest" in data.$meta || "manifests" in data.$meta, file, "$meta missing 'manifest' or 'manifests'");
		if (data.$meta.manifests) {
			check(Array.isArray(data.$meta.manifests), file, "$meta.manifests should be array");
		}
	}

	// suggestions report
	check("suggestions" in data, file, "missing 'suggestions'");
	if (data.suggestions) {
		const s = data.suggestions;
		for (const key of ["frameId", "frameTitle", "totalElements", "summary", "suggestions"]) {
			check(key in s, file, `suggestions missing '${key}'`);
		}

		if (s.summary) {
			for (const key of ["mapped", "unmapped", "highConfidence", "mediumConfidence", "lowConfidence"]) {
				check(key in s.summary, file, `suggestions.summary missing '${key}'`);
			}
			if (s.summary.tierDistribution) {
				for (const key of ["vui", "elementPlus", "html"]) {
					check(key in s.summary.tierDistribution, file, `tierDistribution missing '${key}'`);
					check(
						typeof s.summary.tierDistribution[key] === "number",
						file,
						`tierDistribution.${key} should be number`,
					);
				}
			} else {
				warn(file, "suggestions.summary missing 'tierDistribution' (Phase 2)");
			}
		}

		if (Array.isArray(s.suggestions)) {
			const validConfidence = ["high", "low", "medium", "none"];
			const validTiers = ["vui", "element-plus", "html", "custom"];
			for (const sg of s.suggestions) {
				check("elementId" in sg, file, "suggestion missing 'elementId'");
				check("confidence" in sg, file, `suggestion ${sg.elementId || "?"} missing 'confidence'`);
				check(
					validConfidence.includes(sg.confidence),
					file,
					`suggestion ${sg.elementId || "?"} confidence "${sg.confidence}" not in ${validConfidence.join(", ")}`,
				);
				if ("tier" in sg) {
					check(
						validTiers.includes(sg.tier),
						file,
						`suggestion ${sg.elementId || "?"} tier "${sg.tier}" not in ${validTiers.join(", ")}`,
					);
				} else {
					warn(file, `suggestion ${sg.elementId || "?"} missing 'tier' (Phase 2)`);
				}
				// HTML fallback validation
				if (sg.tier === "html" && sg.htmlFallback) {
					check("htmlTag" in sg.htmlFallback, file, `htmlFallback ${sg.elementId || "?"} missing 'htmlTag'`);
					check(
						"rationale" in sg.htmlFallback,
						file,
						`htmlFallback ${sg.elementId || "?"} missing 'rationale'`,
					);
				}
			}
		}

		// reuseAnalysis
		if (s.reuseAnalysis) {
			const ra = s.reuseAnalysis;
			check(
				Array.isArray(ra.uniqueSuggestedComponents),
				file,
				"reuseAnalysis.uniqueSuggestedComponents should be array",
			);
			check(Array.isArray(ra.reusedComponents), file, "reuseAnalysis.reusedComponents should be array");
			check(Array.isArray(ra.reusedHints), file, "reuseAnalysis.reusedHints should be array");

			if (ra.summary) {
				for (const key of ["totalUniqueSuggested", "totalReusedSuggested"]) {
					check(key in ra.summary, file, `reuseAnalysis.summary missing '${key}'`);
				}
			}

			// 复用组件结构检查
			if (Array.isArray(ra.reusedComponents)) {
				const validPatterns = ["cross-kind", "same-kind"];
				for (const rc of ra.reusedComponents) {
					check("component" in rc, file, "reusedComponent missing 'component'");
					check("usageCount" in rc, file, `reusedComponent ${rc.component || "?"} missing 'usageCount'`);
					if (rc.variantPattern) {
						check(
							validPatterns.includes(rc.variantPattern),
							file,
							`reusedComponent ${rc.component || "?"} variantPattern "${rc.variantPattern}" not in ${validPatterns.join(", ")}`,
						);
					}
				}
			}
		}
	}

	// enhancedFrame
	check("enhancedFrame" in data, file, "missing 'enhancedFrame'");

	// componentChain (optional, present in pipeline output)
	if ("componentChain" in data && data.componentChain) {
		check("chain" in data.componentChain, file, "componentChain missing 'chain'");
		check("summary" in data.componentChain, file, "componentChain missing 'summary'");
		if (data.componentChain.summary) {
			check(
				"tierBreakdown" in data.componentChain.summary,
				file,
				"componentChain.summary missing 'tierBreakdown'",
			);
		}
		if (Array.isArray(data.componentChain.chain)) {
			for (const entry of data.componentChain.chain) {
				check("elementId" in entry, file, "chain entry missing 'elementId'");
				check("fallbackChain" in entry, file, `chain entry ${entry.elementId || "?"} missing 'fallbackChain'`);
			}
		}
	}
}

// ── AI Direct Context Bundle 验证 ──

function validateAiDirectContextBundle(data, file) {
	stats.aiDirectBundles++;

	for (const key of ["meta", "figma", "projectContext", "projectUi", "componentFacts", "rules", "artifacts"]) {
		check(key in data, file, `missing required field: ${key}`);
	}

	if (data.meta) {
		for (const key of ["generator", "mode", "generatedAt", "repoRoot"]) {
			check(key in data.meta, file, `meta missing '${key}'`);
		}
		check(data.meta.mode === "ai-direct", file, `meta.mode "${data.meta.mode}" should be "ai-direct"`);
	}

	if (data.figma) {
		for (const key of ["figmaUrl", "pageName", "pageTitle", "pageSlug", "designContextExcerpt"]) {
			check(key in data.figma, file, `figma missing '${key}'`);
		}
	}

	if (data.projectUi) {
		check(Array.isArray(data.projectUi.projectInstalledPackages), file, "projectUi.projectInstalledPackages should be array");
		check(Array.isArray(data.projectUi.workspacePackageExports), file, "projectUi.workspacePackageExports should be array");
	}

	if (data.componentFacts) {
		for (const key of ["preferredPackages", "fallbackPackages", "vuiCatalog", "fallbackCatalogs"]) {
			check(key in data.componentFacts, file, `componentFacts missing '${key}'`);
		}

		for (const catalogKey of ["vuiCatalog"]) {
			const catalog = data.componentFacts[catalogKey];
			if (!catalog) {
				continue;
			}

			for (const key of ["packageName", "components", "projectInstalled"]) {
				check(key in catalog, file, `${catalogKey} missing '${key}'`);
			}

			if (Array.isArray(catalog.components)) {
				for (const component of catalog.components) {
					check("exportName" in component, file, `${catalogKey} component missing 'exportName'`);
					check("packageInstalledInProject" in component, file, `${catalogKey} component missing 'packageInstalledInProject'`);
				}
			}
		}

		check(Array.isArray(data.componentFacts.fallbackCatalogs), file, "componentFacts.fallbackCatalogs should be array");
		for (const catalog of data.componentFacts.fallbackCatalogs || []) {
			for (const key of ["packageName", "components", "projectInstalled"]) {
				check(key in catalog, file, `fallbackCatalog missing '${key}'`);
			}
		}
	}

	if (data.rules) {
		for (const key of ["framework", "preferredVuiPackage", "fallbackPackages", "enforcement", "previewProjectPolicy"]) {
			check(key in data.rules, file, `rules missing '${key}'`);
		}
		for (const key of ["componentSelection", "generationConstraints", "validationGoals"]) {
			check(Array.isArray(data.rules[key]), file, `rules.${key} should be array`);
		}
		check(typeof data.rules.enforcement === "object" && data.rules.enforcement !== null, file, "rules.enforcement should be object");
		check(
			typeof data.rules.previewProjectPolicy === "object" && data.rules.previewProjectPolicy !== null,
			file,
			"rules.previewProjectPolicy should be object",
		);
	}

	if (data.artifacts) {
		for (const key of ["designContextFile", "variableDefsFile", "promptFile"]) {
			check(key in data.artifacts, file, `artifacts missing '${key}'`);
		}
		if ("screenshotFile" in data.artifacts) {
			check(typeof data.artifacts.screenshotFile === "string", file, "artifacts.screenshotFile must be a string");
		}
		if ("screenshotSummaryFile" in data.artifacts) {
			check(
				typeof data.artifacts.screenshotSummaryFile === "string",
				file,
				"artifacts.screenshotSummaryFile must be a string",
			);
		}
	}
}

// ── 主流程 ──

console.log("[ai-artifacts] Scanning AI artifacts...");

// 扫描 contracts/ai/examples/
const contractsExamplesDir = path.join(repoRoot, "contracts", "ai", "examples");
if (fs.existsSync(contractsExamplesDir)) {
	// Page schemas
	const pageSchemaFiles = findFiles(contractsExamplesDir, ".page-schema.json");
	for (const file of pageSchemaFiles) {
		const data = JSON.parse(fs.readFileSync(file, "utf8"));
		validatePageSchema(data, file);
	}

	// Patch plans
	const patchPlanFiles = findFiles(contractsExamplesDir, ".incremental-patch-plan.json");
	for (const file of patchPlanFiles) {
		const data = JSON.parse(fs.readFileSync(file, "utf8"));
		validatePatchPlan(data, file);
	}

	// Project contexts
	const projectContextFiles = findFiles(contractsExamplesDir, ".project-context.json");
	for (const file of projectContextFiles) {
		const data = JSON.parse(fs.readFileSync(file, "utf8"));
		validateProjectContext(data, file);
	}

	// Design mapper suggestions
	const dmFiles = findFiles(contractsExamplesDir, ".design-mapper-suggestions.json");
	for (const file of dmFiles) {
		const data = JSON.parse(fs.readFileSync(file, "utf8"));
		validateDesignMapperSuggestions(data, file);
	}

	// AI direct context bundles
	const aiDirectBundleFiles = findFiles(contractsExamplesDir, ".ai-direct-context-bundle.json");
	for (const file of aiDirectBundleFiles) {
		const data = JSON.parse(fs.readFileSync(file, "utf8"));
		validateAiDirectContextBundle(data, file);
	}
}

// 扫描 packages/ai/patcher/examples/
const patcherExamplesDir = path.join(repoRoot, "packages", "ai", "patcher", "examples");
if (fs.existsSync(patcherExamplesDir)) {
	const patchPlanFiles = findFiles(patcherExamplesDir, ".incremental-patch-plan.json");
	for (const file of patchPlanFiles) {
		const data = JSON.parse(fs.readFileSync(file, "utf8"));
		validatePatchPlan(data, file);
	}
}

// 扫描 packages/ai/codegen/examples/(codegen 产物是生成的 Vue 文件,暂不做结构检查)

// ── Schema 文件自身可解析性检查 ──

const schemaFiles = [
	path.join(repoRoot, "contracts", "ai", "page-schema.schema.json"),
	path.join(repoRoot, "contracts", "ai", "incremental-patch-plan.schema.json"),
	path.join(repoRoot, "contracts", "ai", "project-context.schema.json"),
	path.join(repoRoot, "contracts", "ai", "figma-frame.schema.json"),
	path.join(repoRoot, "contracts", "ai", "ai-direct-context-bundle.schema.json"),
	path.join(repoRoot, "contracts", "ai", "component-manifest.schema.json"),
	path.join(repoRoot, "contracts", "ai", "component-manifest-index.schema.json"),
	path.join(repoRoot, "contracts", "ai", "component-manifest-item.schema.json"),
];

for (const schemaFile of schemaFiles) {
	if (fs.existsSync(schemaFile)) {
		stats.totalChecks++;
		try {
			JSON.parse(fs.readFileSync(schemaFile, "utf8"));
		} catch (error) {
			failures.push(`${relativePath(schemaFile)}: schema JSON parse error: ${error.message}`);
		}
	}
}

// ── Manifest 文件可解析性 + 结构检查 ──

const manifestFiles = [
	path.join(repoRoot, "contracts", "ai", "element-plus.manifest.json"),
	path.join(repoRoot, "packages", "vui", "vue", "meta", "index.json"),
];

for (const manifestFile of manifestFiles) {
	if (fs.existsSync(manifestFile)) {
		stats.totalChecks++;
		try {
			const manifest = JSON.parse(fs.readFileSync(manifestFile, "utf8"));
			check("packageName" in manifest, relativePath(manifestFile), "manifest missing 'packageName'");
			check("components" in manifest, relativePath(manifestFile), "manifest missing 'components'");
			if (Array.isArray(manifest.components)) {
				for (const comp of manifest.components) {
					const componentName = comp.exportName || comp.name || "?";
					check("exportName" in comp, relativePath(manifestFile), `component "${componentName}" missing 'exportName'`);
					if ("manifest" in comp) {
						check(
							typeof comp.manifest === "string" && comp.manifest.length > 0,
							relativePath(manifestFile),
							`component "${componentName}" missing 'manifest' path`,
						);
					} else {
						check(
							"figmaMapping" in comp,
							relativePath(manifestFile),
							`component "${componentName}" missing 'figmaMapping'`,
						);
					}
				}
			}
		} catch (error) {
			failures.push(`${relativePath(manifestFile)}: manifest JSON parse error: ${error.message}`);
		}
	}
}

// ── 输出 ──

console.log("\n[ai-artifacts] Results");
console.log(`  Page schemas checked: ${stats.pageSchemas}`);
console.log(`  Patch plans checked: ${stats.patchPlans}`);
console.log(`  Project contexts checked: ${stats.projectContexts}`);
console.log(`  Design mapper suggestions checked: ${stats.designMapperSuggestions}`);
console.log(`  AI direct bundles checked: ${stats.aiDirectBundles}`);
console.log(`  Total checks: ${stats.totalChecks}`);

if (warnings.length > 0) {
	console.log(`\n[ai-artifacts] Warnings (${warnings.length}):`);
	for (const w of warnings) {
		console.log(`  ⚠ ${w}`);
	}
}

if (failures.length > 0) {
	console.error(`\n[ai-artifacts] FAILED (${failures.length} issue(s)):`);
	for (const f of failures) {
		console.error(`  ✗ ${f}`);
	}
	process.exit(1);
}

console.log("\n[ai-artifacts] All checks passed.");
process.exit(0);