audit-module.mjs 32.7 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
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

/**
 * 模块 / 菜单规范巡检器。
 *
 * 真源:docs/PORT_CONVERSION.md(§1 铁律、§3 UI、§4 请求、§5 主题、§6 筛选、
 * §7 列表、§8 权限、§9 骨架、§13 菜单对齐、§14 下载、§15 共享层)、ARCHITECTURE.md。
 * 与本脚本并列的 check-boundaries / check-tokens / reconcile 是「全仓 CI 门禁」;
 * 本脚本解决的是「只看某个模块 / 某条菜单」且「能自动改的当场改」。
 *
 * 设计原则:
 *  1. 只报有真源可查的约束,不发明规范;
 *  2. 每条 finding 带 spec 条款号与文件行号,可逐条反驳;
 *  3. 自动修复只做确定性改写(import 名、令牌值、权限码补齐、入口类名),
 *     涉及语义判断的(下载方式、网关、页面结构)只报不改;
 *  4. 修复前把原文件备份到 .tmp/audit-backup/<时间戳>/,改完可用 git diff 复核。
 *
 * 用法:
 *   node scripts/audit-module.mjs <target> [options]
 *   target: 子应用名(usedcar) | 菜单路由(/usedcar/assessment) | menu_code(1002603)
 *           | 子应用/页面(usedcar/Assessment) | 目录路径 | --all
 *   options: --fix        应用可自动修复项(默认只检查)
 *            --dry-run    只打印将做的改写,不落盘
 *            --json       机器可读输出
 */
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const read = (rel) => fs.readFileSync(path.join(ROOT, rel), 'utf8');
const exists = (rel) => fs.existsSync(path.join(ROOT, rel));
const rel = (abs) => path.relative(ROOT, abs).split(path.sep).join('/');

const argv = process.argv.slice(2);
const FLAGS = {
  fix: argv.includes('--fix'),
  dryRun: argv.includes('--dry-run'),
  json: argv.includes('--json'),
  all: argv.includes('--all'),
};
const target = argv.find((a) => !a.startsWith('--'));

/* ------------------------------------------------------------------ */
/* 磁盘事实:UI 导出 / 令牌 / 图标 / 菜单 SQL                          */
/* ------------------------------------------------------------------ */

function exportedNames(file) {
  if (!exists(file)) return new Set();
  const text = read(file);
  const names = new Set();
  for (const m of text.matchAll(
    /export\s+(?:type\s+)?\{([\s\S]*?)\}\s*(?:from\s*['"][^'"]+['"])?\s*;/g,
  )) {
    for (const part of m[1].split(',')) {
      const clean = part.trim().replace(/^type\s+/, '');
      const name = clean
        .split(/\s+as\s+/)
        .pop()
        ?.trim();
      if (name && /^[A-Za-z_$][\w$]*$/.test(name)) names.add(name);
    }
  }
  for (const m of text.matchAll(/export\s+(?:const|function|class)\s+(\w+)/g)) names.add(m[1]);
  return names;
}

const UI_EXPORTS = exportedNames('packages/ui/src/index.ts');
const BIZ_EXPORTS = exportedNames('packages/biz/src/components/index.ts');

// antd 值组件 → @uj/ui 导出名。只收确实已在 packages/ui/src/index.ts 存在的名字。
const ANTD_TO_U = {
  Button: 'UButton',
  Input: 'UInput',
  Select: 'USelect',
  Cascader: 'UCascader',
  Form: 'UForm',
  Typography: 'UTypography',
  Card: 'UCard',
  Tag: 'UTag',
  Image: 'UImage',
  Alert: 'UAlert',
  Modal: 'UModal',
  Drawer: 'UDrawer',
  Table: 'UTable',
  Upload: 'UUpload',
  Tabs: 'UTabs',
  Checkbox: 'UCheckbox',
  List: 'UList',
  Tooltip: 'UTooltip',
  Result: 'UResult',
  Empty: 'UEmpty',
  Steps: 'USteps',
  Timeline: 'UTimeline',
  Dropdown: 'UDropdown',
  DatePicker: 'UDatePicker',
  Radio: 'URadio',
  Switch: 'USwitch',
  Descriptions: 'UDescriptions',
  Skeleton: 'Skeleton',
};
const U_MAP = Object.fromEntries(Object.entries(ANTD_TO_U).filter(([, u]) => UI_EXPORTS.has(u)));

// tokens.css:hex → css 变量名;一个 hex 对应多个变量时不可自动替换。
const TOKEN_BY_HEX = new Map();
{
  const css = exists('packages/design-tokens/src/tokens.css')
    ? read('packages/design-tokens/src/tokens.css')
    : '';
  for (const m of css.matchAll(/(--[\w-]+)\s*:\s*(#[0-9a-fA-F]{6})\b/g)) {
    const hex = m[2].slice(1).toLowerCase();
    if (!TOKEN_BY_HEX.has(hex)) TOKEN_BY_HEX.set(hex, []);
    TOKEN_BY_HEX.get(hex).push(m[1]);
  }
}

const ICON_MAP_KEYS = (() => {
  const file = 'apps/web/shell/src/layouts/SideNav.tsx';
  if (!exists(file)) return new Set();
  const block = /const iconMap[^=]*=\s*\{([\s\S]*?)\n\};/.exec(read(file))?.[1] ?? '';
  return new Set([...block.matchAll(/^\s{2}(\w+):\s*</gm)].map((m) => m[1]));
})();

/** 解析 scripts/*menu*.sql 的 menu_type=2/3 行(含 finance 的 UPDATE 形式)。 */
function parseMenuRows() {
  const rows = new Map(); // menu_id -> row
  const dir = path.join(ROOT, 'scripts');
  const files = fs.readdirSync(dir).filter((f) => f.endsWith('.sql') && !/rollback/i.test(f));
  for (const file of files) {
    const sql = fs.readFileSync(path.join(dir, file), 'utf8');
    // INSERT 形式:(id, 'code', parent, 'name', type, perm, product, route, icon, ...)
    const rowRe =
      /\(\s*(\d+)\s*,\s*'([^']*)'\s*,\s*(?:NULL|'[^']*')\s*,\s*'([^']*)'\s*,\s*([123])\s*,\s*(NULL|'[^']*')\s*,\s*'([^']*)'\s*,\s*(NULL|'[^']*')\s*,\s*(NULL|'[^']*')/g;
    for (const m of sql.matchAll(rowRe)) {
      const unq = (s) => (s === 'NULL' ? null : s.replace(/^'|'$/g, ''));
      rows.set(Number(m[1]), {
        id: Number(m[1]),
        code: m[2],
        name: m[3],
        type: Number(m[4]),
        perm: unq(m[5]),
        route: unq(m[7]),
        icon: unq(m[8]),
        file,
      });
    }
    // UPDATE 形式(finance 迁移:原地改 5 行)
    for (const block of sql.split(/UPDATE\s+`sys_menu`/).slice(1)) {
      const id = /\bWHERE\s+`menu_id`\s*=\s*(\d+)/.exec(block)?.[1];
      if (!id) continue;
      const set = (field) =>
        new RegExp('`' + field + "`\\s*=\\s*\\'([^\\']*)\\'").exec(block)?.[1] ?? null;
      const prev = rows.get(Number(id)) ?? { id: Number(id), file };
      rows.set(Number(id), {
        ...prev,
        code: set('menu_code') ?? prev.code,
        name: set('menu_name') ?? prev.name,
        type: prev.type ?? 2,
        perm: set('perm_code') ?? prev.perm,
        route: set('route') ?? prev.route,
        icon: set('icon') ?? prev.icon,
        file,
      });
    }
  }
  return [...rows.values()];
}
const MENU_ROWS = parseMenuRows();

function collect(dir, exts, out = []) {
  if (!fs.existsSync(dir)) return out;
  for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
    if (['node_modules', 'dist', '.turbo', 'out'].includes(e.name)) continue;
    const full = path.join(dir, e.name);
    if (e.isDirectory()) collect(full, exts, out);
    else if (exts.some((x) => e.name.endsWith(x))) out.push(full);
  }
  return out;
}

const SUBAPP_ROOT = path.join(ROOT, 'apps/web/subapps');
const SUBAPPS = fs.existsSync(SUBAPP_ROOT)
  ? fs
      .readdirSync(SUBAPP_ROOT, { withFileTypes: true })
      .filter((e) => e.isDirectory())
      .map((e) => e.name)
  : [];

/* ------------------------------------------------------------------ */
/* 目标解析                                                            */
/* ------------------------------------------------------------------ */

function subappMeta(name) {
  const dir = path.join(SUBAPP_ROOT, name);
  if (!fs.existsSync(dir)) return null;
  const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
  return { name, dir, route: pkg.uj?.route ?? name, pkg };
}

function pageTable(app) {
  const appTs = path.join(app.dir, 'src/App.tsx');
  if (!fs.existsSync(appTs)) return new Map();
  const text = fs.readFileSync(appTs, 'utf8');
  const imports = new Map();
  for (const m of text.matchAll(/import\s+(\w+)\s+from\s+'(\.[^']+)';/g)) {
    imports.set(m[1], m[2]);
  }
  const out = new Map();
  const routes = /const\s+ROUTES[^=]*=\s*\[([\s\S]*?)\]\s*;/.exec(text)?.[1] ?? '';
  for (const m of routes.matchAll(/\{\s*path:\s*'([^']+)'\s*,\s*Page:\s*(\w+)\s*\}/g)) {
    out.set(m[1], imports.get(m[2]) ?? null);
  }
  const pages = /const\s+PAGES[^=]*=\s*\{([\s\S]*?)\}\s+as\s+const;/.exec(text)?.[1] ?? '';
  for (const m of pages.matchAll(/^\s*([\w-]+):\s*(\w+),/gm)) {
    out.set(m[1], imports.get(m[2]) ?? null);
  }
  return out;
}

function resolveTarget() {
  const apps = [];
  const focusFiles = new Set();
  const focusRows = [];
  const notes = [];

  if (FLAGS.all || !target) {
    for (const name of SUBAPPS) apps.push(subappMeta(name));
    notes.push(`全子应用:${apps.map((a) => a.name).join(' / ')}`);
    return { apps, focusFiles, focusRows, notes };
  }

  let app = null;
  let pageSeg = null;

  // Git Bash(MSYS) 会把以 / 开头的参数改写成 D:/.../finance/payment;
  // 同时支持 /finance/payment、finance/payment 与 MSYS 改写后的绝对路径。
  let normTarget = target;
  const hit = SUBAPPS.find(
    (n) => normTarget === n || normTarget.endsWith('/' + n) || normTarget.includes('/' + n + '/'),
  );
  if (hit && normTarget !== hit) {
    const idx = normTarget.lastIndexOf('/' + hit + '/');
    normTarget = idx >= 0 ? normTarget.slice(idx + 1) : hit;
  }
  if (normTarget.startsWith('/')) {
    const norm = normTarget.replace(/\/+$/, '');
    const row = MENU_ROWS.find((r) => r.route === norm && r.type === 2);
    if (!row) throw new Error(`菜单 SQL 里没有 route=${norm} 的页面行(menu_type=2)`);
    const seg = norm.split('/').filter(Boolean);
    app = subappMeta(seg[0]);
    pageSeg = seg.slice(1).join('/');
    focusRows.push(row);
    notes.push(`菜单:${row.name}(menu_code ${row.code} / ${norm})`);
  } else if (/^\d+$/.test(target)) {
    const row = MENU_ROWS.find((r) => r.code === target);
    if (!row) throw new Error(`菜单 SQL 里没有 menu_code=${target}`);
    const seg = (row.route ?? '').split('/').filter(Boolean);
    app = subappMeta(seg[0]);
    pageSeg = seg.slice(1).join('/');
    focusRows.push(row);
    notes.push(`菜单:${row.name}(${row.code})`);
  } else if (normTarget.includes('/')) {
    const [name, ...rest] = normTarget.split('/');
    app = subappMeta(name);
    pageSeg = rest.join('/') || null;
    for (const r of MENU_ROWS) {
      if (r.type !== 2 || !r.route) continue;
      const s = r.route.split('/').filter(Boolean);
      if (s[0] === name && s.slice(1).join('/') === pageSeg) focusRows.push(r);
    }
  } else {
    app = subappMeta(normTarget);
    if (!app)
      throw new Error(`未知目标 ${target};可用:${SUBAPPS.join(' / ')},或菜单路由 /<域>/<页>`);
  }
  if (!app) throw new Error(`目标 ${target} 对应的子应用不存在`);
  apps.push(app);

  if (pageSeg) {
    const table = pageTable(app);
    const spec = table.get(pageSeg);
    if (spec) {
      const base = path.resolve(app.dir, 'src', spec.replace(/^\.\//, ''));
      const hit = [base + '.tsx', path.join(base, 'index.tsx')].find((p) => fs.existsSync(p));
      if (hit) focusFiles.add(hit);
    }
    // 路由表里没有的页面目标(如尚未登记菜单的新页 / 组件文件)按目录约定兜底解析,
    // 否则会退化成扫描整个模块——与目标语义不符。
    if (!focusFiles.size) {
      const seg = pageSeg.split('/').filter(Boolean);
      const bases = [path.join(app.dir, 'src/pages', ...seg), path.join(app.dir, 'src', ...seg)];
      for (const base of bases) {
        const hit = [base + '.tsx', path.join(base, 'index.tsx')].find((p) => fs.existsSync(p));
        if (hit) {
          focusFiles.add(hit);
          break;
        }
      }
    }
    // 页面级巡检覆盖该页目录全部源码(index.tsx + 同目录 css / 子组件),
    // 不能只看入口文件——样式与弹窗组件恰恰是铁律最容易破的地方。
    for (const p of [...focusFiles]) {
      const dir = fs.existsSync(p) && fs.statSync(p).isDirectory() ? p : path.dirname(p);
      for (const f of collect(dir, ['.ts', '.tsx', '.css'])) focusFiles.add(f);
    }
    for (const r of MENU_ROWS) {
      if (r.type !== 2) continue;
      const s = (r.route ?? '').split('/').filter(Boolean);
      if (s[0] === app.route && s.slice(1).join('/') === pageSeg) focusRows.push(r);
    }
    notes.push(
      `聚焦页面:${pageSeg}${focusFiles.size ? ' → ' + rel([...focusFiles][0]) : '(未找到页面文件)'}`,
    );
    const menuNote = focusRows.find((r) => r.type === 2);
    if (menuNote) notes.unshift(`菜单:${menuNote.name}(menu_code ${menuNote.code})`);
  } else {
    notes.push(`模块:${app.name}(route 前缀 /${app.route})`);
  }
  return { apps, focusFiles, focusRows, notes };
}

/* ------------------------------------------------------------------ */
/* finding 收集                                                        */
/* ------------------------------------------------------------------ */

const findings = [];
function add(rule, spec, severity, file, line, message, edits = [], extra = {}) {
  findings.push({
    rule,
    spec,
    severity,
    file: file ? rel(file) : null,
    line,
    message,
    edits,
    ...extra,
  });
}

function lineOf(text, index) {
  return text.slice(0, index).split('\n').length;
}

/**
 * 只把注释抹成空格,保留长度、换行与字符串字面量。
 * 源色值常出现在「已改用令牌」的说明注释里(finance/Payment/constant.ts 就有三处),
 * 直接对全文扫 hex 会把合规代码误报成违规。返回值与原串等长,edit 区间仍可复用。
 */
function maskComments(text, isCss) {
  const out = text.split('');
  const blank = (i) => {
    if (out[i] !== '\n' && out[i] !== '\r') out[i] = ' ';
  };
  let state = 'code';
  let quote = '';
  for (let i = 0; i < text.length; i++) {
    const c = text[i];
    const n = text[i + 1];
    if (state === 'code') {
      if (c === '/' && n === '*') {
        blank(i);
        blank(i + 1);
        state = 'block';
        i++;
        continue;
      }
      if (!isCss && c === '/' && n === '/') {
        blank(i);
        blank(i + 1);
        state = 'line';
        i++;
        continue;
      }
      if (c === "'" || c === '"' || c === '`') {
        state = 'str';
        quote = c;
      }
      continue;
    }
    if (state === 'block') {
      blank(i);
      if (c === '*' && n === '/') {
        blank(i + 1);
        state = 'code';
        i++;
      }
      continue;
    }
    if (state === 'line') {
      blank(i);
      if (c === '\n') state = 'code';
      continue;
    }
    // 字符串:其中的 # 仍是真实色值,不能抹;只跳过转义。
    if (c === '\\') {
      i++;
      continue;
    }
    if (c === quote) state = 'code';
  }
  return out.join('');
}

function varSpans(text) {
  const spans = [];
  for (const m of text.matchAll(/var\([^)]*\)/g)) spans.push([m.index, m.index + m[0].length]);
  return spans;
}

function checkFile(file) {
  const raw = fs.readFileSync(file, 'utf8');
  const isCss = file.endsWith('.css');
  const isTs = /\.(ts|tsx)$/.test(file);
  const text = maskComments(raw, isCss);

  // §1.1 / §1.2 / §1.8:与 scripts/check-boundaries.mjs 同口径(子应用侧)。
  if (isTs) {
    const boundary = [
      [
        'host-runtime',
        /@uj\/platform-core/,
        '引用 host 独占运行时 @uj/platform-core;改用 @uj/platform-sdk(§2)',
      ],
      [
        'virtual-key',
        /virtual:(client-private-key|server-public-key)/,
        '子应用不得注入 PEM 虚拟模块(§2)',
      ],
      [
        'secret-env',
        /VITE_(CLIENT_PRIVATE_KEY|SERVER_PUBLIC_KEY|API_TARGET|SIGN_ENABLED|STRICT_VERIFY)/,
        '签名/后端 env 只属于 shell(§2)',
      ],
      [
        'wujie-core',
        /from\s+['"]wujie['"]/,
        '子应用只用 window.$wujie.bus / props,不直 import wujie(§2)',
      ],
      [
        'axios-runtime',
        /^import\s+(?!type\s)[^;]*from\s+['"]axios['"]/m,
        '运行时 import axios;请求必须经 props.request(§1.1)',
      ],
      ['cross-subapp', /@uj\/web-/, '禁止引用主壳或其它子应用包(§2)'],
      [
        'download-direct',
        /\bcreateObjectURL\s*\(|\bwindow\.open\s*\(|\.download\s*=\s*[^=]|\ba\.click\s*\(/,
        '自行落地文件;下载必须经 downloadCenter(§1.8 / §14)',
      ],
    ];
    for (const [id, re, msg] of boundary) {
      const m = re.exec(text);
      if (m) add(`boundary/${id}`, '§1 / §2 / §14', 'error', file, lineOf(text, m.index), msg);
    }

    // §1.3 / §3:值导入只能来自 @uj/ui 的 U*;type-only 允许(仓库现状即如此)。
    const antdRe = /import\s*\{([^}]+)\}\s*from\s*['"]antd['"]\s*;?/g;
    for (const m of text.matchAll(antdRe)) {
      const specs = m[1]
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean);
      const values = specs.filter((s) => !/^type\s/.test(s));
      if (!values.length) continue; // 纯 type import,放行
      const bad = values.filter((s) => /\s+as\s+/.test(s) || !U_MAP[s]);
      const where = { file, line: lineOf(text, m.index) };
      if (bad.length) {
        add(
          'ui/antd-import',
          '§1.3 / §3',
          'error',
          where.file,
          where.line,
          `从 antd 值导入 ${bad.join(', ')};必须用 @uj/ui 的 U*(缺失先在 packages/ui 建再导出)`,
        );
        continue;
      }
      const names = values.map((s) => U_MAP[s]);
      const memberUsed = values.filter((s) => new RegExp('\\b' + s + '\\.').test(text));
      if (memberUsed.length) {
        add(
          'ui/antd-import',
          '§1.3 / §3',
          'error',
          where.file,
          where.line,
          `antd 组件 ${memberUsed.join(', ')} 存在成员用法(如 Form.Item),需人工改为 UFormItem 等,不自动改`,
        );
        continue;
      }
      const replacement = `import { ${names.join(', ')} } from '@uj/ui';`;
      const edits = [{ start: m.index, end: m.index + m[0].length, text: replacement }];
      for (const s of values) {
        const re = new RegExp('\\b' + s + '\\b', 'g');
        for (const u of text.matchAll(re)) {
          if (u.index >= m.index && u.index < m.index + m[0].length) continue;
          edits.push({ start: u.index, end: u.index + s.length, text: U_MAP[s] });
        }
      }
      add(
        'ui/antd-import',
        '§1.3 / §3',
        'error',
        where.file,
        where.line,
        `从 antd 值导入 ${values.join(', ')} → 改为 @uj/ui ${names.join(', ')}`,
        edits,
        { auto: true, hint: `import ${values.join('/')} → ${names.join('/')}` },
      );
    }

    // §3 反幻觉:@uj/ui / @/components 的命名导入必须真实存在。
    for (const [mod, set] of [
      ['@uj/ui', UI_EXPORTS],
      ['@/components', BIZ_EXPORTS],
    ]) {
      if (!set.size) continue;
      for (const m of text.matchAll(
        new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*['"]${mod.replace('/', '\\/')}['"]`, 'g'),
      )) {
        for (const part of m[1].split(',')) {
          const name = part
            .trim()
            .replace(/^type\s+/, '')
            .split(/\s+as\s+/)[0];
          if (name && !set.has(name)) {
            add(
              'ui/export-missing',
              '§3 / §12',
              'error',
              file,
              lineOf(text, m.index),
              `从 ${mod} 导入了未导出的 ${name};先建 U* / 业务组件再引`,
            );
          }
        }
      }
    }

    // §1.7:rowSelection 的 selectedRowKeys 禁止 .map(String) 强转。
    if (/rowSelection/.test(text) && /selectedRowKeys[\s\S]{0,120}\.map\(String\)/.test(text)) {
      const m = /\.map\(String\)/.exec(text);
      add(
        'table/key-cast',
        '§1.7 / §7',
        'error',
        file,
        lineOf(text, m.index),
        'selectedRowKeys 与 rowKey 必须同类型;禁止 keys.map(String) 强转',
      );
    }

    // §1.9 / §15.2:共享方法不得在子应用里写第二份。
    for (const m of text.matchAll(
      /\bfunction\s+(errorDetail|goTo|loadRemoteConfig|openExportUrl|formatDateTime)\s*\(/g,
    )) {
      const after = text.slice(m.index, m.index + 500);
      // §15.3② 明示的刻意分叉(老接口时间串只做 T→空格,不换时区):源码已标注条款就不报。
      // 标注在注释里,得看原文——text 已经把注释抹掉了。
      if (/15\.3/.test(raw.slice(Math.max(0, m.index - 400), m.index))) continue;
      // 薄委托适配器:体内已直接走 downloadCenter,不是「第二份实现」。
      if (m[1] === 'openExportUrl' && /downloadCenter\./.test(after)) continue;
      add(
        'util/duplicate',
        '§1.9 / §15.2',
        'warn',
        file,
        lineOf(text, m.index),
        `${m[1]} 已收进 @uj/biz 或 @uj/platform-sdk,别写第二份(§15.3 的刻意分叉除外)`,
      );
    }
  }

  // §1.4 / §5:硬编码颜色;var(..., #fallback) 里的回退值不算。
  const spans = isTs || isCss ? varSpans(text) : [];
  for (const m of text.matchAll(/#[0-9a-fA-F]{3,8}\b/g)) {
    if (spans.some(([s, e]) => m.index >= s && m.index < e)) continue;
    let hex = m[0].slice(1).toLowerCase();
    if (/^[0-9a-f]{3}$/.test(hex)) hex = [...hex].map((c) => c + c).join('');
    if (!/^[0-9a-f]{6}$/.test(hex)) continue;
    const toks = TOKEN_BY_HEX.get(hex) ?? [];
    const where = { file, line: lineOf(text, m.index) };
    if (toks.length === 1) {
      add(
        'theme/hardcoded-color',
        '§1.4 / §5',
        'error',
        where.file,
        where.line,
        `写死颜色 ${m[0]} → var(${toks[0]})`,
        [{ start: m.index, end: m.index + m[0].length, text: `var(${toks[0]})` }],
        { auto: true, hint: `${m[0]} → var(${toks[0]})` },
      );
    } else if (toks.length > 1) {
      add(
        'theme/hardcoded-color',
        '§1.4 / §5',
        'error',
        where.file,
        where.line,
        `写死颜色 ${m[0]};tokens.css 有 ${toks.length} 个同值变量 ${toks.join(' / ')},需人工选语义`,
      );
    } else {
      add(
        'theme/hardcoded-color',
        '§1.4 / §5',
        'error',
        where.file,
        where.line,
        `写死颜色 ${m[0]};tokens.css 无同值令牌,先在 palette.ts + tokens.css 定义再引`,
      );
    }
  }

  // §1.5:只有 .ant-* 自己作为选择器主体才算裸用(会覆盖 antd 内部样式)。
  // 「.ant-drawer-body .uj-xxx」只是拿 antd 容器做祖先限定来抬特异性,动的是自己的类,放行。
  if (isCss) {
    for (const m of text.matchAll(/(^|\n)\s*([^{}]+)\{/g)) {
      const bare = m[2].split(',').some((part) => {
        const chain = part
          .trim()
          .split(/\s+|>|\+|~/)
          .filter(Boolean);
        // 整条链都是 .ant-* 才算裸用;带 .uj-xxx / .uc-xxx 自有类祖先的是局部限定,放行。
        return chain.length > 0 && chain.every((s) => /^\.ant-/.test(s));
      });
      if (bare) {
        add(
          'theme/ant-selector',
          '§1.5',
          'warn',
          file,
          lineOf(text, m.index),
          '裸 .ant-* 选择器;确认未覆盖 antd 内部盒模型/几何',
        );
        break;
      }
    }
  }
}

/** 入口骨架:tokens.css 导入 + uj-scope 根类名(§5)。 */
function checkEntry(app) {
  const main = path.join(app.dir, 'src/main.tsx');
  if (fs.existsSync(main)) {
    const text = fs.readFileSync(main, 'utf8');
    if (!text.includes('@uj/design-tokens/tokens.css')) {
      add(
        'entry/tokens-css',
        '§5',
        'error',
        main,
        1,
        'main.tsx 未 import @uj/design-tokens/tokens.css',
        [{ start: 0, end: 0, text: "import '@uj/design-tokens/tokens.css';\n" }],
        { auto: true, hint: '顶部补 tokens.css import' },
      );
    }
  }
  const appTs = path.join(app.dir, 'src/App.tsx');
  if (fs.existsSync(appTs)) {
    const text = fs.readFileSync(appTs, 'utf8');
    const m = /<div className="([^"]*uj-[a-z-]+-app[^"]*)">/.exec(text);
    if (m && !/\buj-scope\b/.test(m[1])) {
      add(
        'entry/uj-scope',
        '§5',
        'error',
        appTs,
        lineOf(text, m.index),
        `根节点 className="${m[1]}" 缺 uj-scope,CSS 变量不生效`,
        [
          {
            start: m.index + '<div className="'.length,
            end: m.index + '<div className="'.length + m[1].length,
            text: `uj-scope ${m[1]}`,
          },
        ],
        { auto: true, hint: '根节点补 uj-scope' },
      );
    }
  }
}

/** 菜单 → 子应用 → 路由表 → 页面文件 → 权限码(§13 / §8 / §9)。 */
function checkMenu(app, rows) {
  const pkgRoute = app.route;
  const table = pageTable(app);
  const mine = rows.filter((r) => r.type === 2 && (r.route ?? '').startsWith(`/${pkgRoute}/`));
  // 这批 SQL 只登记了 points / usedcar / finance 三个域;store / system 不在菜单 SQL 里,
  // 没行可对齐不等于违规。仅当该域确实出现在 SQL 中却没有页面行时才告警。
  const inSql = rows.some((r) => (r.route ?? '').startsWith(`/${pkgRoute}`));
  if (!mine.length && inSql) {
    add(
      'menu/no-page-row',
      '§13',
      'warn',
      null,
      0,
      `菜单 SQL 里没有 /${pkgRoute}/ 开头的页面行(menu_type=2)`,
    );
  }
  for (const r of mine) {
    const seg = r.route.split('/').filter(Boolean);
    const tail = seg.slice(1).join('/');
    const spec = table.get(tail);
    if (!spec) {
      add(
        'menu/route-missing',
        '§13.2 / §9',
        'error',
        path.join(app.dir, 'src/App.tsx'),
        0,
        `菜单 ${r.code} 的 ${r.route} 在 App.tsx 页面表里没有「${tail}」条目(点进去会白屏/UEmpty)`,
      );
      continue;
    }
    const base = path.resolve(app.dir, 'src', spec.replace(/^\.\//, ''));
    const hit = [base + '.tsx', path.join(base, 'index.tsx')].find((p) => fs.existsSync(p));
    if (!hit) {
      add(
        'menu/page-file-missing',
        '§13.2',
        'error',
        path.join(app.dir, 'src/App.tsx'),
        0,
        `菜单 ${r.code}→页面「${tail}」映射到 ${rel(base)},但文件不存在`,
      );
    }
    if (r.icon && !ICON_MAP_KEYS.has(r.icon)) {
      add(
        'menu/icon-unregistered',
        '§13.1',
        'warn',
        null,
        0,
        `菜单 ${r.code} 图标 ${r.icon} 未登记在 SideNav iconMap;dev 告警后静默回落`,
      );
    }
  }

  // 权限码表对账:SQL 中本域 perm_code 必须逐字出现在 codes.ts。
  const codesFile = path.join(app.dir, 'src/permissions/codes.ts');
  if (fs.existsSync(codesFile)) {
    const text = fs.readFileSync(codesFile, 'utf8');
    const body = /export const \w+\s*=\s*\{([\s\S]*?)\n\}\s+as\s+const;/.exec(text)?.[1] ?? '';
    const declared = new Set(
      [...body.matchAll(/['"]([\w-]+:[\w-]+(?::[\w-]+)?)['"]/g)].map((m) => m[1]),
    );
    const expected = new Set(
      rows.filter((r) => r.perm && r.perm.startsWith(`${pkgRoute}:`)).map((r) => r.perm),
    );
    const close = /\n\}\s+as\s+const;/.exec(text);
    for (const code of expected) {
      if (declared.has(code)) continue;
      const parts = code.split(':').slice(1);
      const key = parts.join('_').toUpperCase().replace(/-/g, '_');
      const keyTaken = new RegExp(`\\b${key}\\s*:`).test(body);
      const where = { file: codesFile, line: close ? lineOf(text, close.index) : 1 };
      if (keyTaken || !close) {
        add(
          'menu/perm-code-missing',
          '§8 / §13.4',
          'error',
          where.file,
          where.line,
          `菜单 SQL 有权限码 ${code},${rel(codesFile)} 缺失;键名 ${key} 已占用,需人工处理`,
        );
        continue;
      }
      const insert = `\n  // [audit 自动补齐] ${code}\n  ${key}: '${code}',`;
      add(
        'menu/perm-code-missing',
        '§8 / §13.4',
        'error',
        where.file,
        where.line,
        `菜单 SQL 有权限码 ${code},补进 ${rel(codesFile)}`,
        [{ start: close.index, end: close.index, text: insert }],
        { auto: true, hint: `+ ${key}: '${code}'` },
      );
    }
    for (const code of declared) {
      if (!expected.has(code)) {
        add(
          'menu/perm-code-orphan',
          '§8 / §13.4',
          'warn',
          codesFile,
          0,
          `${rel(codesFile)} 的权限码 ${code} 在菜单 SQL 中不存在(可能已迁移,见 §16)`,
        );
      }
    }

    // 页面源码里硬编码的域权限码也必须在表里。
    const files = collect(path.join(app.dir, 'src'), ['.ts', '.tsx']);
    for (const f of files) {
      const t = fs.readFileSync(f, 'utf8');
      // 权限码口径:域前缀 + 小写 kebab 段(§8 `资源:动作`)。localStorage 键如
      // finance:devSessionId 含大写,不是权限码,必须排除——否则每次都误报两条。
      const codeRe = new RegExp(`['"](${pkgRoute}:[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*)*)['"]`, 'g');
      for (const m of t.matchAll(codeRe)) {
        const code = m[1];
        if (!code.includes(':') || code.split(':').length < 2) continue;
        if (declared.has(code) || expected.has(code)) continue;
        add(
          'perm/undeclared',
          '§8',
          'error',
          f,
          lineOf(t, m.index),
          `页面硬编码未登记的权限码 ${code}`,
        );
      }
    }
  }
}

/* ------------------------------------------------------------------ */
/* 修复落盘                                                            */
/* ------------------------------------------------------------------ */

function applyFixes() {
  const byFile = new Map();
  for (const f of findings) {
    if (!f.auto || !f.file || !f.edits?.length) continue;
    if (!byFile.has(f.file)) byFile.set(f.file, []);
    byFile.get(f.file).push(...f.edits);
  }
  const stamp = new Date().toISOString().replace(/[:.]/g, '-');
  const changed = [];
  for (const [file, edits] of byFile) {
    const abs = path.join(ROOT, file);
    const before = fs.readFileSync(abs, 'utf8');
    let after = before;
    const sorted = [...edits].sort((a, b) => b.start - a.start);
    for (const e of sorted) {
      if (e.end > before.length || e.start < 0 || e.start > e.end) {
        throw new Error(`修复区间越界 ${file}: ${e.start}-${e.end}`);
      }
      after = after.slice(0, e.start) + e.text + after.slice(e.end);
    }
    if (after === before) continue;
    if (FLAGS.dryRun) {
      changed.push({ file, status: 'dry-run' });
      continue;
    }
    const backup = path.join(ROOT, '.tmp/audit-backup', stamp, file);
    fs.mkdirSync(path.dirname(backup), { recursive: true });
    fs.writeFileSync(backup, before);
    fs.writeFileSync(abs, after);
    changed.push({ file, backup: rel(backup), status: 'fixed' });
  }
  return changed;
}

/* ------------------------------------------------------------------ */
/* 主流程                                                              */
/* ------------------------------------------------------------------ */

let resolved;
try {
  resolved = resolveTarget();
} catch (err) {
  console.error(`[audit] ${err.message}`);
  process.exit(2);
}

for (const app of resolved.apps.filter(Boolean)) {
  const files = resolved.focusFiles.size
    ? [...resolved.focusFiles].filter((f) => f.startsWith(app.dir))
    : collect(path.join(app.dir, 'src'), ['.ts', '.tsx', '.css']);
  for (const f of files) checkFile(f);
  checkEntry(app);
  checkMenu(app, MENU_ROWS);
}

findings.sort(
  (a, b) =>
    (a.file ?? '').localeCompare(b.file ?? '') || a.line - b.line || a.rule.localeCompare(b.rule),
);

let changed = [];
if (FLAGS.fix) changed = applyFixes();

if (FLAGS.json) {
  console.log(
    JSON.stringify(
      {
        target: target ?? '--all',
        notes: resolved.notes,
        findings,
        changed,
      },
      null,
      2,
    ),
  );
} else {
  console.log(`[audit] 目标:${resolved.notes.join(';')}`);
  console.log(
    `[audit] 菜单 SQL 行 ${MENU_ROWS.length} / tokens ${TOKEN_BY_HEX.size} / UI 导出 ${UI_EXPORTS.size}`,
  );
  console.log('');
  for (const f of findings) {
    const icon = f.severity === 'error' ? '✗' : '⚠';
    const fixable = f.auto ? ' [可自动修复]' : '';
    console.log(`${icon} [${f.rule}] ${f.spec} ${f.file ?? '(全局)'}:${f.line || '-'}`);
    console.log(`    ${f.message}${fixable}`);
    if (f.hint) console.log(`    → ${f.hint}`);
  }
  const errs = findings.filter((f) => f.severity === 'error').length;
  const warns = findings.filter((f) => f.severity === 'warn').length;
  const autos = findings.filter((f) => f.auto).length;
  console.log('');
  console.log(`[audit] 错误 ${errs} / 告警 ${warns} / 可自动修复 ${autos}`);
  for (const c of changed) {
    console.log(
      `[audit] ${c.status === 'dry-run' ? '将修改' : '已修改'} ${c.file}${c.backup ? `(备份 ${c.backup})` : ''}`,
    );
  }
  if (FLAGS.fix && !FLAGS.dryRun) {
    console.log('[audit] 修复后请跑 git diff 复核,再跑 pnpm verify。');
  }
}

const remaining = findings.filter(
  (f) => f.severity === 'error' && !(FLAGS.fix && f.auto && !FLAGS.dryRun),
);
process.exit(remaining.length ? 1 : 0);