project-scanner.ts 23.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
/**
 * ProjectProfile scanner — Phase 1.
 *
 * A dependency-free, best-effort scanner that inspects a target frontend
 * project ("Project A") and drafts a `ProjectProfile` (画像): its framework,
 * styling strategy, component library, bespoke design tokens (CSS custom
 * properties), reusable components / hooks / utils, and a prose `conventions`
 * draft (the CODERIO.md). The goal is to give the generator a vocabulary of
 * the team's real building blocks so output looks hand-written rather than a
 * generic scaffold.
 *
 * It runs inside the server process on demand (a one-shot "生成画像" action),
 * so it must be cheap and fail-soft: any unreadable file is skipped, and the
 * result is always a valid (possibly partial) profile.
 */
import { readFileSync, existsSync, readdirSync, statSync } from 'node:fs';
import path from 'node:path';
import { emptyProfile, type ProjectProfile, type ComponentMapping, type UtilMapping, type TokenMapping, type TokenCategory } from 'coderio';

const SKIP_DIRS = new Set([
    'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', '.vite',
    '.turbo', 'coverage', '.cache', '.idea', '.history', 'public', 'assets',
    'static', '.output', '.svelte-kit',
]);
const SOURCE_EXT = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs']);
const STYLE_EXT = new Set(['.css', '.scss', '.less']);
const MAX_DEPTH = 14;
const MAX_TOKENS = 120;
const MAX_COMPONENTS = 80;
const MAX_UTILS = 60;
const MAX_FILES = 4000;

interface AliasInfo {
    prefix: string; // e.g. "@"
    baseDir: string; // absolute dir the alias maps to, e.g. <root>/src
}

function safeRead(filePath: string): string {
    try {
        return readFileSync(filePath, 'utf8');
    } catch {
        return '';
    }
}

function listDir(dir: string): string[] {
    try {
        return readdirSync(dir);
    } catch {
        return [];
    }
}

function isDir(p: string): boolean {
    try {
        return statSync(p).isDirectory();
    } catch {
        return false;
    }
}

/** Recursively collect source / style files under root, skipping noise. */
function collectFiles(root: string): { sources: string[]; styles: string[] } {
    const sources: string[] = [];
    const styles: string[] = [];
    let count = 0;

    const walk = (dir: string, depth: number): void => {
        if (depth > MAX_DEPTH || count > MAX_FILES) return;
        for (const name of listDir(dir)) {
            if (SKIP_DIRS.has(name)) continue;
            const full = path.join(dir, name);
            let st;
            try {
                st = statSync(full);
            } catch {
                continue;
            }
            if (st.isDirectory()) {
                walk(full, depth + 1);
            } else if (st.isFile()) {
                const ext = path.extname(name).toLowerCase();
                if (SOURCE_EXT.has(ext) && !name.endsWith('.d.ts')) {
                    sources.push(full);
                    count++;
                } else if (STYLE_EXT.has(ext)) {
                    styles.push(full);
                    count++;
                }
            }
        }
    };
    walk(root, 0);
    return { sources, styles };
}

/** Merge dependencies + devDependencies from package.json (if present). */
function readDeps(root: string): Record<string, string> {
    const pkgPath = path.join(root, 'package.json');
    if (!existsSync(pkgPath)) return {};
    const raw = safeRead(pkgPath);
    if (!raw) return {};
    try {
        const pkg = JSON.parse(raw);
        return { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
    } catch {
        return {};
    }
}

/** Detect the import alias (e.g. "@/*" → src) from ts/jsconfig + vite. */
function detectAlias(root: string): AliasInfo | null {
    for (const cfgName of ['tsconfig.json', 'jsconfig.json']) {
        const cfgPath = path.join(root, cfgName);
        if (!existsSync(cfgPath)) continue;
        const raw = safeRead(cfgPath);
        if (!raw) continue;
        try {
            // Minimal JSON5-ish parse: strip comments + trailing commas.
            const cleaned = raw
                .replace(/\/\/.*$/gm, '')
                .replace(/\/\*[\s\S]*?\*\//g, '')
                .replace(/,(\s*[}\]])/g, '$1');
            const cfg = JSON.parse(cleaned);
            const paths = cfg?.compilerOptions?.paths as Record<string, string[]> | undefined;
            if (paths) {
                for (const [alias, targets] of Object.entries(paths)) {
                    const t = targets?.[0];
                    if (!t) continue;
                    const star = alias.indexOf('*');
                    const targetStar = t.indexOf('*');
                    if (star >= 0 && targetStar >= 0) {
                        // The wildcard sits after the path separator, e.g.
                        // "@/src/*" → prefix "@" (strip the trailing slash so we
                        // don't end up with a double slash when joined later).
                        const prefix = alias.slice(0, star).replace(/\/$/, '');
                        const baseRel = t.slice(0, targetStar);
                        const baseDir = path.resolve(root, baseRel);
                        if (isDir(baseDir)) return { prefix, baseDir };
                    }
                }
            }
        } catch {
            /* ignore malformed config */
        }
    }
    // Fallback: vite alias.
    for (const v of ['vite.config.ts', 'vite.config.js', 'vite.config.mjs']) {
        const vp = path.join(root, v);
        if (!existsSync(vp)) continue;
        const raw = safeRead(vp);
        const m = raw.match(/alias:\s*\{[^}]*?'(@|~)'?\s*:\s*(?:path\.(?:resolve|join)\(['"][^'"]*['"]\s*,\s*['"]([^'"]+)['"]\)|['"]([^'"]+)['"])/);
        if (m) {
            const baseRel = m[2] || m[3];
            if (baseRel) {
                const baseDir = path.resolve(root, baseRel);
                if (isDir(baseDir)) return { prefix: m[1], baseDir };
            }
        }
    }
    return null;
}

/** Build the canonical import path for a file: alias-based when possible. */
function toImportPath(file: string, root: string, alias: AliasInfo | null): string {
    const rel = path.relative(root, file).replace(/\\/g, '/');
    const noExt = rel.replace(/\.(tsx?|jsx?|mjs|cjs)$/, '');
    if (alias) {
        const relToBase = path.relative(alias.baseDir, file).replace(/\\/g, '/');
        if (!relToBase.startsWith('..')) {
            const noExt2 = relToBase.replace(/\.(tsx?|jsx?|mjs|cjs)$/, '');
            return `${alias.prefix}/${noExt2}`;
        }
    }
    return `./${noExt}`;
}

function detectFramework(deps: Record<string, string>): string {
    const has = (k: string) => k in deps;
    // 元框架优先(它们已隐含框架,单独成项便于与预设下拉匹配)
    if (has('next')) return 'Next.js (App Router)';
    if (has('nuxt') || has('@nuxt/kit') || has('@nuxt/schema')) return 'Nuxt 3';
    if (has('@remix-run/react') || has('@remix-run/node')) return 'Remix';
    if (has('@sveltejs/kit')) return 'SvelteKit';
    if (has('svelte')) return 'Svelte';
    if (has('@angular/core')) return 'Angular';
    if (has('astro')) return 'Astro';
    if (has('solid-js') || has('@solidjs/router')) return 'SolidJS';
    if (has('@builder.io/qwik') || has('@qwikcity/router')) return 'Qwik';
    if (has('vue')) {
        // 预设只有 "Vue 3",版本号丢失但可接受
        return 'Vue 3';
    }
    if (has('react') || has('react-dom')) {
        const v = deps['react'] || '';
        if (v.startsWith('^19') || v.startsWith('19')) return 'React 19';
        return 'React 18';
    }
    return '';
}

function detectStyling(deps: Record<string, string>): string {
    const has = (k: string) => k in deps;
    const parts: string[] = [];
    if (has('tailwindcss')) parts.push('Tailwind CSS');
    if (has('sass')) parts.push('Sass / SCSS');
    if (has('less')) parts.push('Less');
    if (has('styled-components')) parts.push('styled-components');
    if (has('@emotion/react') || has('@emotion/styled')) parts.push('Emotion');
    if (has('@stitches/react')) parts.push('Stitches');
    if (has('unocss')) parts.push('UnoCSS');
    if (has('styled-jsx')) parts.push('Styled JSX');
    // 未检测到样式依赖时不硬猜(CSS Modules 取决于构建配置,无法从依赖判断)
    return parts.join(' + ');
}

function detectComponentLibrary(deps: Record<string, string>): string {
    const known: [string, string][] = [
        ['antd', 'Ant Design'],
        ['@ant-design/pro-components', 'Ant Design'],
        ['@mui/material', 'Material UI (MUI)'],
        ['@chakra-ui/react', 'Chakra UI'],
        ['@nextui-org/react', 'NextUI'],
        ['@arco-design/web-react', 'Arco Design'],
        ['@semi-design/react', 'Semi Design'],
        ['react-bootstrap', 'React Bootstrap'],
        ['@mantine/core', 'Mantine'],
        ['element-plus', 'Element Plus'],
        ['naive-ui', 'Naive UI'],
        ['vant', 'Vant'],
        ['@headlessui/react', 'Headless UI'],
        ['@radix-ui/react', 'Radix UI'],
    ];
    const found = known.filter(([k]) => k in deps).map(([, label]) => label);
    if (found.length === 0) return '无(原生元素)';
    return found.join(' / ');
}

/** 状态管理:能从依赖明确识别才填,否则留空让用户选。 */
function detectStateManagement(deps: Record<string, string>): string {
    const has = (k: string) => k in deps;
    if (has('@reduxjs/toolkit') || has('redux')) return 'Redux Toolkit';
    if (has('zustand')) return 'Zustand';
    if (has('jotai')) return 'Jotai';
    if (has('recoil')) return 'Recoil';
    if (has('mobx') || has('mobx-react') || has('mobx-react-lite')) return 'MobX';
    if (has('pinia')) return 'Pinia';
    if (has('vuex')) return 'Vuex';
    return '';
}

/** 数据请求层:能从依赖明确识别才填,否则留空。 */
function detectDataFetching(deps: Record<string, string>): string {
    const has = (k: string) => k in deps;
    if (has('@tanstack/react-query') || has('react-query')) return 'React Query (TanStack Query)';
    if (has('swr')) return 'SWR';
    if (has('@apollo/client') || has('apollo-client') || has('@apollo/client/core')) return 'Apollo Client';
    if (has('axios')) return 'Axios';
    if (has('@vue/apollo-composable') || has('vue-query')) return 'Vue Query';
    return '';
}

/** 路由:能从依赖明确识别才填,否则留空。 */
function detectRouting(deps: Record<string, string>): string {
    const has = (k: string) => k in deps;
    if (has('next')) return 'Next.js 路由';
    if (has('nuxt') || has('@nuxt/kit')) return 'Nuxt 路由';
    if (has('react-router') || has('react-router-dom')) return 'React Router';
    if (has('vue-router')) return 'Vue Router';
    if (has('@tanstack/router')) return 'TanStack Router';
    if (has('@angular/router') || has('@angular/core')) return 'Angular Router';
    return '';
}

/** Extract all local import specifiers from a source file. */
function extractImportSpecifiers(code: string): string[] {
    const specs: string[] = [];
    const re = /(?:import\s[^'"]*?from\s*|import\s*|require\(\s*|import\(\s*)['"]([^'"]+)['"]/g;
    let m: RegExpExecArray | null;
    while ((m = re.exec(code))) {
        specs.push(m[1]);
    }
    return specs;
}

/** Classify an exported PascalCase/camelCase name in a file. */
function classifyExport(name: string, code: string, isJsx: boolean): 'component' | 'hook' | 'util' {
    if (/^use[A-Z]/.test(name)) return 'hook';
    if (/^[A-Z]/.test(name)) {
        const looksLikeComponent =
            isJsx ||
            /React\.(FC|Component|PureComponent)/.test(code) ||
            /:\s*React\./.test(code) ||
            /JSX\.Element/.test(code) ||
            /createElement/.test(code);
        if (looksLikeComponent) return 'component';
        return 'util';
    }
    return 'util';
}

interface ExportedSymbol {
    name: string;
    kind: 'component' | 'hook' | 'util';
}

function extractExports(code: string, isJsx: boolean): ExportedSymbol[] {
    const out: ExportedSymbol[] = [];
    const seen = new Set<string>();

    const push = (name: string) => {
        if (!name || seen.has(name)) return;
        seen.add(name);
        out.push({ name, kind: classifyExport(name, code, isJsx) });
    };

    // export default function Foo / export default Foo / export default class Foo
    const defRe = /export\s+default\s+(?:function|class|const|let|var)?\s*([A-Za-z_$][\w$]*)/g;
    let m: RegExpExecArray | null;
    while ((m = defRe.exec(code))) push(m[1]);

    // export function/const/class Foo
    const declRe = /export\s+(?:async\s+)?(?:function|class|const|let|var)\s+([A-Za-z_$][\w$]*)/g;
    while ((m = declRe.exec(code))) push(m[1]);

    // export { A, B as C }
    const blockRe = /export\s*\{([^}]*)\}/g;
    while ((m = blockRe.exec(code))) {
        const inner = m[1];
        for (const part of inner.split(',')) {
            const trimmed = part.trim();
            if (!trimmed) continue;
            const asMatch = trimmed.match(/([\w$]+)\s+as\s+([\w$]+)/);
            if (asMatch) push(asMatch[2]);
            else push(trimmed);
        }
    }
    return out;
}

const TOKEN_CATEGORY_KEYWORDS: [RegExp, TokenCategory][] = [
    [/color|colour|bg|background|text|fill|border|fg|foreground|accent|primary|secondary|neutral|brand|surface|overlay/i, 'color'],
    [/radius|rounded|round/i, 'radius'],
    [/spacing|gap|margin|padding|space|size|inset|indent/i, 'spacing'],
    [/font-size|fontsize|text-size|type-scale|typescale/i, 'fontSize'],
    [/font-family|fontfamily|fontface|typeface/i, 'fontFamily'],
    [/shadow|elevation|depth/i, 'shadow'],
];

function categorizeToken(name: string): TokenCategory {
    for (const [re, cat] of TOKEN_CATEGORY_KEYWORDS) {
        if (re.test(name)) return cat;
    }
    return 'other';
}

/** Extract CSS custom properties as design tokens. */
function scanTokens(styles: string[]): TokenMapping[] {
    const tokens: TokenMapping[] = [];
    const seen = new Set<string>();
    for (const file of styles) {
        const code = safeRead(file);
        if (!code) continue;
        const re = /(--[\w-]+)\s*:\s*([^;{}]+)/g;
        let m: RegExpExecArray | null;
        while ((m = re.exec(code))) {
            const rawName = m[1];
            if (seen.has(rawName)) continue;
            seen.add(rawName);
            const value = m[2].trim();
            tokens.push({
                name: rawName.replace(/^--/, ''),
                code: `var(${rawName})`,
                value,
                category: categorizeToken(rawName),
            });
            if (tokens.length >= MAX_TOKENS) return tokens;
        }
    }
    return tokens;
}

interface ScanResult {
    profile: ProjectProfile;
    pages: string[];
    warnings: string[];
}

/**
 * Scan a target project root and draft a ProjectProfile. Always returns a valid
 * profile (possibly with empty arrays) even when nothing recognizable is found.
 */
export function scanProject(rootDir: string): ScanResult {
    const warnings: string[] = [];
    if (!existsSync(rootDir) || !isDir(rootDir)) {
        warnings.push(`目录不存在或不可读:${rootDir}`);
        return { profile: { ...emptyProfile(), rootDir }, pages: [], warnings };
    }

    const deps = readDeps(rootDir);
    const alias = detectAlias(rootDir);
    const { sources, styles } = collectFiles(rootDir);

    if (sources.length === 0) {
        warnings.push('未在项目根目录找到任何源码文件(已跳过 node_modules 等目录)。请确认工作目录是前端项目根。');
    }

    // ---- Pass 1: gather exported symbols per file + local import frequency ----
    const fileSymbols = new Map<string, ExportedSymbol[]>();
    const importFreq = new Map<string, number>(); // absolute module path -> count
    const rootFiles = new Set(sources);

    for (const file of sources) {
        const code = safeRead(file);
        const isJsx = /\.(tsx|jsx)$/.test(file) || /<\/?[A-Za-z]/.test(code);
        const exports = extractExports(code, isJsx);
        if (exports.length) fileSymbols.set(file, exports);

        for (const spec of extractImportSpecifiers(code)) {
            let resolved: string | null = null;
            if (spec.startsWith('.') || spec.startsWith('/')) {
                const abs = path.resolve(path.dirname(file), spec);
                if (rootFiles.has(abs) || rootFiles.has(abs + '.ts') || rootFiles.has(abs + '.tsx') || rootFiles.has(abs + '.js') || rootFiles.has(abs + '.jsx')) {
                    resolved = abs;
                }
            } else if (alias && spec.startsWith(alias.prefix + '/')) {
                const rel = spec.slice(alias.prefix.length + 1);
                const abs = path.resolve(alias.baseDir, rel);
                if (rootFiles.has(abs) || rootFiles.has(abs + '.ts') || rootFiles.has(abs + '.tsx') || rootFiles.has(abs + '.js') || rootFiles.has(abs + '.jsx')) {
                    resolved = abs;
                }
            }
            if (resolved) importFreq.set(resolved, (importFreq.get(resolved) ?? 0) + 1);
        }
    }

    // ---- Pass 2: build component / util mappings ranked by frequency ----
    const components: ComponentMapping[] = [];
    const utils: UtilMapping[] = [];

    for (const [file, symbols] of fileSymbols) {
        const importPath = toImportPath(file, rootDir, alias);
        const freq = importFreq.get(file) ?? 0;
        for (const sym of symbols) {
            if (sym.kind === 'component') {
                components.push({
                    name: sym.name,
                    importPath,
                    description: freq > 0 ? `项目内被引用 ${freq} 次` : '业务/通用组件',
                    exportType: 'named',
                    props: [],
                });
            } else {
                utils.push({
                    name: sym.name,
                    importPath,
                    description:
                        sym.kind === 'hook'
                            ? '自定义 Hook'
                            : freq > 0
                              ? `项目内被引用 ${freq} 次`
                              : '工具函数 / 模块',
                });
            }
        }
    }

    // Rank by how often each symbol's module is imported across the project,
    // then alphabetically — most-reused building blocks surface first.
    const compFreq = (c: ComponentMapping) => {
        const abs = alias ? path.resolve(alias.baseDir, c.importPath.slice(alias.prefix.length + 1)) : path.resolve(rootDir, c.importPath);
        return importFreq.get(abs) ?? 0;
    };
    components.sort((a, b) => compFreq(b) - compFreq(a) || a.name.localeCompare(b.name));
    utils.sort((a, b) => {
        const absA = alias ? path.resolve(alias.baseDir, a.importPath.slice(alias.prefix.length + 1)) : path.resolve(rootDir, a.importPath);
        const absB = alias ? path.resolve(alias.baseDir, b.importPath.slice(alias.prefix.length + 1)) : path.resolve(rootDir, b.importPath);
        return (importFreq.get(absB) ?? 0) - (importFreq.get(absA) ?? 0) || a.name.localeCompare(b.name);
    });

    const tokens = scanTokens(styles);

    // ---- Pages enumeration (route/page-like dirs) ----
    const pages = enumeratePages(rootDir);

    // ---- Assemble profile ----
    const framework = detectFramework(deps);
    const styling = detectStyling(deps);
    const componentLibrary = detectComponentLibrary(deps);
    const stateManagement = detectStateManagement(deps);
    const dataFetching = detectDataFetching(deps);
    const routing = detectRouting(deps);
    const projectName = path.basename(rootDir);

    const conventions = draftConventions({
        projectName,
        framework,
        styling,
        componentLibrary,
        alias,
        componentCount: components.length,
        utilCount: utils.length,
        tokenCount: tokens.length,
    });

    const profile: ProjectProfile = {
        ...emptyProfile(),
        projectName,
        rootDir,
        framework,
        language: 'typescript' in deps ? 'TypeScript' : 'JavaScript',
        styling,
        componentLibrary,
        stateManagement,
        dataFetching,
        routing,
        importAlias: alias ? `${alias.prefix}/` : undefined,
        landingPath: alias ? `${alias.prefix}/` + 'features/<page>/' : 'src/generated/',
        tokens,
        components: components.slice(0, MAX_COMPONENTS),
        utils: utils.slice(0, MAX_UTILS),
        conventions,
        lastScannedAt: new Date().toISOString(),
    };

    if (components.length === 0 && utils.length === 0) {
        warnings.push('未在源码中发现可导出的组件/工具,可能项目结构特殊(如全部内联)或使用了非标准的导出方式。');
    }
    if (tokens.length === 0) {
        warnings.push('未发现 CSS 自定义属性(设计令牌),引擎将退化为使用通用样式。');
    }

    return { profile, pages, warnings };
}

function enumeratePages(rootDir: string): string[] {
    const candidates = ['src/pages', 'src/views', 'src/routes', 'src/screens', 'src/app', 'pages', 'views', 'routes', 'screens'];
    const pages: string[] = [];
    for (const c of candidates) {
        const dir = path.join(rootDir, c);
        if (!isDir(dir)) continue;
        for (const name of listDir(dir)) {
            const full = path.join(dir, name);
            if (isDir(full)) pages.push(`${c}/${name}`);
            else if (/\.(tsx?|jsx?)$/.test(name)) pages.push(`${c}/${name.replace(/\.(tsx?|jsx?)$/, '')}`);
        }
    }
    return pages.slice(0, 40);
}

function draftConventions(opts: {
    projectName: string;
    framework: string;
    styling: string;
    componentLibrary: string;
    alias: AliasInfo | null;
    componentCount: number;
    utilCount: number;
    tokenCount: number;
}): string {
    const lines: string[] = [];
    lines.push('# 生成约束(CODERIO.md)');
    lines.push('');
    lines.push(`> 由 CodeRio 自动扫描「${opts.projectName}」生成,请按需修订后再保存。`);
    lines.push('');
    lines.push(`- 目标项目:${opts.projectName}`);
    lines.push(`- 技术栈:${opts.framework}`);
    lines.push(`- 样式策略:${opts.styling}`);
    lines.push(`- 组件库:${opts.componentLibrary}`);
    lines.push(`- 导入别名:${opts.alias ? opts.alias.prefix + '/' : '相对路径'}`);
    lines.push('');
    lines.push('## 组件优先');
    lines.push(`生成代码时优先复用项目已有组件(引擎画像表已列出 ${opts.componentCount} 个候选,按引用频次排序),严禁重复造轮子。`);
    lines.push('');
    lines.push('## 设计令牌');
    lines.push(`使用项目自有设计令牌(已扫描到 ${opts.tokenCount} 个 CSS 变量),通过 var(--token) 引用,**禁止硬编码**颜色、间距、圆角、字体等值。`);
    lines.push('');
    lines.push('## 公共能力');
    lines.push(`复用项目工具函数与 Hook(已识别 ${opts.utilCount} 个),如请求封装、格式化、状态管理等,不要自行实现。`);
    lines.push('');
    lines.push('## 目录与命名');
    lines.push(`新页面/区块遵循项目既有目录与命名约定;新增文件置于合适的功能目录下,import 使用项目别名。`);
    lines.push('');
    lines.push('## 禁止项');
    lines.push('- 禁止引入项目未使用的第三方库;');
    lines.push('- 禁止为已存在的组件再写一遍;');
    lines.push('- 禁止忽略 TypeScript 类型与项目 lint 规则。');
    return lines.join('\n');
}