@perf-engineer/web 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,28 +1,30 @@
1
1
  # Perf Engineer
2
2
 
3
+ **English** | [简体中文](https://github.com/perf-engineer/perf-engineer/blob/main/README.zh-CN.md)
4
+
3
5
  [![npm version](https://img.shields.io/npm/v/@perf-engineer/web)](https://www.npmjs.com/package/@perf-engineer/web)
4
6
  [![CI](https://github.com/perf-engineer/perf-engineer/actions/workflows/ci.yml/badge.svg)](https://github.com/perf-engineer/perf-engineer/actions/workflows/ci.yml)
5
- [![Node.js](https://img.shields.io/badge/node-%3E%3D22.13.0-brightgreen)](#环境要求)
7
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D22.13.0-brightgreen)](#requirements)
6
8
  [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
7
9
 
8
- 面向 Antigravity、Cursor、Claude Code、Codex 与 VS Code 等 AI 编程宿主的只读 Web 首屏性能诊断 MCP Server。基于真实 Chrome 与 Lighthouse 12 多次采样并结合只读源码排查,输出面向团队的问题分析报告(`report.md`)与可直接交给人或 AI 逐项执行的优化施工单(`perf-tasks.md`)。
10
+ A read-only MCP server for diagnosing initial page-load performance in AI coding clients such as Antigravity, Cursor, Claude Code, Codex, and VS Code. It combines repeated measurements from real Chrome and Lighthouse 12 with source-code analysis to produce a diagnostic report (`report.md`) and an optimization task list (`perf-tasks.md`) for developers or AI assistants to work through.
9
11
 
10
- ## 特性
12
+ ## Features
11
13
 
12
- - 真实 Chrome + Lighthouse 12 多次采样取中位数,优先定位影响首屏的最大资源、图片、脚本与接口瓶颈
13
- - 诊断过程严格只读,不修改业务仓库代码,不执行构建、依赖安装或 Git 操作
14
- - 自动核对线上运行产物与本地代码仓库的一致性,存在版本差异时拆分线上运维、线上发版与本地代码任务
15
- - 内置 6 维首屏排查清单,无需额外依赖即可运行,也支持按团队规范扩展
16
- - 支持在优化上线后沿用同一设备、网络与登录条件发起复测,以实测中位数对比前后变化
14
+ - Repeated Chrome and Lighthouse 12 measurements, using median values to identify resource, image, script, and API bottlenecks that affect initial loading
15
+ - Read-only diagnostic tools that do not modify application source code or run builds, dependency installation, or Git commands
16
+ - Checks linking deployed artifacts to local source code, with separate tasks for production operations, deployment, and local code changes when versions differ
17
+ - A built-in diagnostic guide covering six areas of initial page-load performance, with support for team-specific guidance
18
+ - Retests using the same device, network, and login conditions after changes are deployed, with before-and-after metric comparisons
17
19
 
18
- ## 环境要求
20
+ ## Requirements
19
21
 
20
22
  - [Node.js](https://nodejs.org/) `>= 22.13.0`
21
- - 本机已安装 Chrome 或 Chromium
23
+ - Chrome or Chromium installed locally
22
24
 
23
- ## 快速开始
25
+ ## Quick start
24
26
 
25
- 在支持 MCP 的客户端中添加如下标准配置即可直接运行(无需克隆源码仓库):
27
+ Add the following configuration to an MCP-compatible client. You do not need to clone the repository:
26
28
 
27
29
  ```json
28
30
  {
@@ -35,55 +37,55 @@
35
37
  }
36
38
  ```
37
39
 
38
- 也可以按具体客户端使用内置安装命令一键写入配置和只读规则:
40
+ You can also use the built-in installers to add client configuration and, where supported, read-only rules:
39
41
 
40
42
  <details>
41
- <summary>Antigravity(含防误写 Hook 保护)</summary>
43
+ <summary>Antigravity (includes a hook to prevent accidental writes)</summary>
42
44
 
43
45
  ```bash
44
46
  npx -y @perf-engineer/web install antigravity
45
47
  ```
46
48
 
47
- 命令会将插件包写入 `~/.gemini/config/plugins/perf-engineer`,重启或重载 Antigravity 插件后生效。
49
+ The installer writes the plugin to `~/.gemini/config/plugins/perf-engineer`. Restart or reload the Antigravity plugin to apply it.
48
50
 
49
51
  </details>
50
52
 
51
53
  <details>
52
54
  <summary>Cursor</summary>
53
55
 
54
- 在目标项目根目录执行:
56
+ Run this command from the root of the project you want to diagnose:
55
57
 
56
58
  ```bash
57
59
  npx -y @perf-engineer/web install cursor
58
60
  ```
59
61
 
60
- 会安全合并 `.cursor/mcp.json`(保留已有配置)并写入 `.cursor/rules/perf-engineer.mdc`。加 `--global` 参数可安装到 `~/.cursor/mcp.json`。
62
+ The installer merges the MCP configuration into `.cursor/mcp.json`, preserving existing settings, and writes `.cursor/rules/perf-engineer.mdc`. Add `--global` to install the MCP configuration in `~/.cursor/mcp.json`.
61
63
 
62
64
  </details>
63
65
 
64
66
  <details>
65
67
  <summary>Claude Code</summary>
66
68
 
67
- 使用 Claude CLI 添加全局配置:
69
+ Use the Claude CLI to add the MCP server:
68
70
 
69
71
  ```bash
70
72
  claude mcp add perf-engineer -- npx -y @perf-engineer/web
71
73
  ```
72
74
 
73
- 或在目标项目根目录执行 `npx -y @perf-engineer/web install claude-code` 生成 `.mcp.json`。
75
+ Alternatively, run `npx -y @perf-engineer/web install claude-code` from the project root to generate `.mcp.json`.
74
76
 
75
77
  </details>
76
78
 
77
79
  <details>
78
80
  <summary>Codex</summary>
79
81
 
80
- 在目标项目根目录执行:
82
+ Run this command from the project root:
81
83
 
82
84
  ```bash
83
85
  npx -y @perf-engineer/web install codex
84
86
  ```
85
87
 
86
- 若配置全局 `~/.codex/config.toml`:
88
+ For a global configuration in `~/.codex/config.toml`, add:
87
89
 
88
90
  ```toml
89
91
  [mcp_servers.perf-engineer]
@@ -96,13 +98,13 @@ args = ["-y", "@perf-engineer/web"]
96
98
  <details>
97
99
  <summary>VS Code</summary>
98
100
 
99
- 在目标项目根目录执行:
101
+ Run this command from the project root:
100
102
 
101
103
  ```bash
102
104
  npx -y @perf-engineer/web install vscode
103
105
  ```
104
106
 
105
- 或手动配置 `.vscode/mcp.json`:
107
+ Or configure `.vscode/mcp.json` manually:
106
108
 
107
109
  ```json
108
110
  {
@@ -118,78 +120,78 @@ npx -y @perf-engineer/web install vscode
118
120
 
119
121
  </details>
120
122
 
121
- ## 使用方式
123
+ ## Usage
122
124
 
123
- ### 公开页面诊断
125
+ ### Diagnose a public page
124
126
 
125
- > 用 perf-engineer 诊断 `https://shop.example.com/`,本地代码仓库在 `/path/to/storefront`,不需要登录。
127
+ > Use perf-engineer to diagnose `https://shop.example.com/`. The local repository is at `/path/to/storefront`. No login is required.
126
128
 
127
- ### 需要登录的页面
129
+ ### Diagnose a page that requires login
128
130
 
129
- > 用 perf-engineer 诊断 `https://app.example.com/dashboard`,本地代码仓库在 `/path/to/app`,需要登录。
131
+ > Use perf-engineer to diagnose `https://app.example.com/dashboard`. The local repository is at `/path/to/app`. Login is required.
130
132
 
131
- 运行到登录步骤时,会自动打开一个隔离的 Chrome 窗口供你手动登录(支持扫码、验证码或双因素认证);登录完成后通知 AI 继续测速即可,工具不会读取或记录密码、Cookie、本地存储或 Token。
133
+ At the login step, Perf Engineer opens an isolated Chrome window for you to sign in manually, including QR codes, verification codes, or two-factor authentication. Once you are signed in, ask the AI assistant to continue measuring. The diagnostic tools do not read or record passwords, cookies, local storage, or tokens.
132
134
 
133
- ### 执行施工单
135
+ ### Work through the task list
134
136
 
135
- 诊断结束后会直接返回 `perf-tasks.md` 路径。你可以自己按优先级改,也可以把文件发给 AI 执行:
137
+ When diagnosis finishes, Perf Engineer returns the path to `perf-tasks.md`. You can work through the tasks in priority order or pass the file to an AI assistant:
136
138
 
137
- > 按这份 `perf-tasks.md` 逐项完成优化,每完成一项跑一下里面的验收步骤。
139
+ > Complete the optimizations in this `perf-tasks.md` one at a time. Run each task's acceptance checks after completing it.
138
140
 
139
- ### 上线后复测
141
+ ### Retest after deployment
140
142
 
141
- 优化部署完成后,沿用上次的测速条件重跑一次,直接对比前后指标:
143
+ After deploying the changes, repeat the measurements under the same conditions and compare the results:
142
144
 
143
- > 用 perf-engineer 复测 `https://shop.example.com/`,对比上次诊断结果。
145
+ > Use perf-engineer to retest `https://shop.example.com/` and compare it with the previous diagnosis.
144
146
 
145
- ## 输出产物
147
+ ## Output files
146
148
 
147
- 每次运行的结果统一写入 `~/.perf-engineer/data/runs/<run-id>/`:
149
+ Each run writes its results to `~/.perf-engineer/data/runs/<run-id>/`:
148
150
 
149
151
  ```text
150
152
  ~/.perf-engineer/data/runs/<run-id>/
151
- ├── report.md # 性能诊断报告(核心结论、实测对比、线上/本地问题与排查覆盖)
152
- ├── perf-tasks.md # 性能优化施工单(修改范围、具体步骤、低成本验收与回滚方式)
153
- ├── manifest.json # 场景配置、耗时汇总与审计记录
154
- └── evidence/ # 首屏截图、网络请求列表与 Lighthouse 诊断原始明细
153
+ ├── report.md # Findings, measurements, production/local issues, and analysis coverage
154
+ ├── perf-tasks.md # Change scope, implementation steps, acceptance checks, and rollback guidance
155
+ ├── manifest.json # Run metadata
156
+ └── evidence/ # Initial viewport screenshot, network requests, and Lighthouse diagnostics
155
157
  ```
156
158
 
157
- 以下为一次真实电商首页诊断(已脱敏)的实测汇总,完整报告与施工单见 `examples/`:
159
+ The following results come from a real storefront homepage diagnosis, with identifying details removed. The full report and task list are available in `examples/`:
158
160
 
159
- | 用户体验指标 | 实测中位数 | 参考阈值 | 状态 |
161
+ | Metric | Measured median | Reference threshold | Status |
160
162
  | --- | ---: | ---: | --- |
161
- | 综合性能分 | 42 分 | ≥ 85 分 | ❌ 偏低 |
162
- | 首次内容绘制(FCP) | 1.5 秒 | ≤ 1.8 秒 | ✅ 正常 |
163
- | 最大内容绘制(LCP) | 12.2 秒 | ≤ 2.5 秒 | ❌ 太慢 |
164
- | 视觉完成指数(Speed Index) | 9.8 秒 | ≤ 3.4 秒 | ❌ 严重卡顿 |
165
- | 总阻塞时间(TBT) | 429 毫秒 | ≤ 200 毫秒 | ⚠️ 偏高 |
166
- | 累积布局偏移(CLS) | 0.01 | ≤ 0.10 | ✅ 正常 |
163
+ | Performance score | 42 | ≥ 85 | ❌ Low |
164
+ | First Contentful Paint (FCP) | 1.5 s | ≤ 1.8 s | ✅ Within threshold |
165
+ | Largest Contentful Paint (LCP) | 12.2 s | ≤ 2.5 s | ❌ Slow |
166
+ | Speed Index | 9.8 s | ≤ 3.4 s | ❌ Very slow |
167
+ | Total Blocking Time (TBT) | 429 ms | ≤ 200 ms | ⚠️ High |
168
+ | Cumulative Layout Shift (CLS) | 0.01 | ≤ 0.10 | ✅ Within threshold |
167
169
 
168
- - [完整诊断报告示例(report.md)](examples/storefront-report.md)
169
- - [完整优化施工单示例(perf-tasks.md)](examples/storefront-tasks.md)
170
+ - [Full diagnostic report example (Chinese)](examples/storefront-report.md)
171
+ - [Full optimization task list example (Chinese)](examples/storefront-tasks.md)
170
172
 
171
- ## 排查范围与自定义
173
+ ## Diagnostic coverage and customization
172
174
 
173
- 内置排查清单覆盖以下 6 个首屏优化方向,不依赖外部技能库即可直接运行:
175
+ The built-in guide covers six areas of initial page-load performance and does not require an external skill library:
174
176
 
175
- | 排查方向 | 主要检查内容 |
177
+ | Area | What the guide covers |
176
178
  | --- | --- |
177
- | Bundle 瘦身与拆包 | UI/工具库按需引入、公共包拆分非首屏重依赖、重复库与旧版 Polyfill |
178
- | 网络资源调度 | 关键跨域 `preconnect` / `dns-prefetch`、`preload` 与 `prefetch` 误用与双拉问题 |
179
- | 图片全链路 | CDN 裁剪尺寸与 WebP/AVIF 转换、首屏外与轮播非首帧 `loading="lazy"`、本地大图压缩 |
180
- | 渲染与执行时机 | 默认隐藏弹窗提前挂载、长页面下方区块懒加载、统计与支付 SDK 延后加载、首屏透明延迟动画 |
181
- | 缓存与传输策略 | 带哈希静态资源强缓存、入口 HTML 协商缓存、`br`/`gzip`/`zstd` 压缩与 HTTP/2 |
182
- | 接口瀑布与主线程长任务 | 冷启动重复请求、串行接口链、子请求扇出与过大的 DOM 节点规模 |
179
+ | Bundle size and code splitting | On-demand UI and utility imports, moving heavy dependencies out of the initial bundle, duplicate libraries, and legacy polyfills |
180
+ | Network resource scheduling | Critical cross-origin `preconnect` and `dns-prefetch`, incorrect `preload` or `prefetch` usage, and duplicate downloads |
181
+ | Images | CDN resizing and WebP/AVIF conversion, `loading="lazy"` for below-the-fold images and inactive carousel slides, and compression of large local images |
182
+ | Rendering and execution timing | Eagerly mounted hidden dialogs, lazy loading lower sections of long pages, deferred analytics and payment SDKs, and animations that delay initial content visibility |
183
+ | Caching and delivery | Long-lived caching for hashed assets, cache revalidation for entry HTML, `br`/`gzip`/`zstd` compression, and HTTP/2 |
184
+ | API waterfalls and main-thread work | Duplicate startup requests, sequential API chains, request fan-out, and excessive DOM size |
183
185
 
184
- 如需增加团队内部规范,直接编辑 [packages/guidance/playbooks/first-screen-sop.md](packages/guidance/playbooks/first-screen-sop.md) 后重新构建即可生效。
186
+ To add team-specific guidance, edit [the initial page-load diagnostic guide](packages/guidance/playbooks/first-screen-sop.md) and rebuild the package.
185
187
 
186
- ## 安全与边界
188
+ ## Security and scope
187
189
 
188
- - 诊断期间不会修改目标仓库中的任何文件,也不会执行构建、安装或 Git 命令
189
- - 不会读取、记录或索取浏览器 Cookie、`localStorage`/`sessionStorage`、密码或 Token
190
- - 初始只读诊断不会宣称性能已经改善,只有在修改部署并完成同场景复测后才会给出对比结论
190
+ - Diagnostic tools do not modify files in the target repository or run build, installation, or Git commands against it.
191
+ - They do not read, record, or request browser cookies, `localStorage`/`sessionStorage`, passwords, or tokens.
192
+ - An initial read-only diagnosis does not claim that performance has improved. Before-and-after comparisons require a subsequent retest under the same conditions after changes are deployed.
191
193
 
192
- ## 本地开发
194
+ ## Local development
193
195
 
194
196
  ```bash
195
197
  git clone https://github.com/perf-engineer/perf-engineer.git
@@ -201,10 +203,9 @@ npm run check
201
203
  npm test
202
204
  ```
203
205
 
204
- ## 相关文档与许可证
206
+ ## Documentation and license
205
207
 
206
- - [中文产品需求与架构设计](docs/PRODUCT_REQUIREMENTS.zh-CN.md)
207
- - [Product Requirements (English)](docs/PRODUCT_REQUIREMENTS.md)
208
- - [贡献指南](CONTRIBUTING.md)
209
- - [安全策略](SECURITY.md)
210
- - 基于 [MIT License](LICENSE) 开源
208
+ - [Architecture (Chinese)](docs/ARCHITECTURE.md)
209
+ - [Contributing](CONTRIBUTING.md)
210
+ - [Security policy](SECURITY.md)
211
+ - Released under the [MIT License](LICENSE)
package/dist/cli.js CHANGED
@@ -1189,12 +1189,20 @@ function aggregateMeasurements(measurements) {
1189
1189
  sampleCount: sorted.length
1190
1190
  };
1191
1191
  }).sort((a, b) => a.metric.localeCompare(b.metric));
1192
+ const highVarianceMetrics = metrics.filter((item) => item.sampleCount >= 3 && ["lcpMs", "fcpMs", "tbtMs", "speedIndexMs"].includes(item.metric) && item.representative >= 200 && (item.max - item.min) / item.representative > 0.35).map((item) => ({
1193
+ metric: item.metric,
1194
+ spreadRatio: Number(((item.max - item.min) / item.representative).toFixed(2)),
1195
+ min: item.min,
1196
+ max: item.max,
1197
+ representative: item.representative
1198
+ }));
1192
1199
  return {
1193
1200
  representative: measurements.length === 1 ? "single" : "median",
1194
- stabilityVerified: measurements.length >= 3,
1201
+ stabilityVerified: measurements.length >= 3 && highVarianceMetrics.length === 0,
1195
1202
  sampleCount: measurements.length,
1196
1203
  metrics,
1197
- measurementIds: measurements.map((measurement) => measurement.measurementId)
1204
+ measurementIds: measurements.map((measurement) => measurement.measurementId),
1205
+ ...highVarianceMetrics.length > 0 ? { highVarianceMetrics } : {}
1198
1206
  };
1199
1207
  }
1200
1208
  function projectMetrics(lhr, audits) {
@@ -1222,21 +1230,32 @@ function projectMetrics(lhr, audits) {
1222
1230
  return result;
1223
1231
  }
1224
1232
  var KEY_DIAGNOSTIC_AUDITS = [
1233
+ "server-response-time",
1234
+ "redirects",
1235
+ "lcp-discovery-insight",
1236
+ "prioritize-lcp-image",
1225
1237
  "uses-text-compression",
1226
1238
  "render-blocking-insight",
1227
1239
  "render-blocking-resources",
1240
+ "network-dependency-tree-insight",
1241
+ "critical-request-chains",
1242
+ "font-display-insight",
1243
+ "font-display",
1228
1244
  "unused-javascript",
1229
1245
  "unused-css-rules",
1230
1246
  "duplicated-javascript",
1231
1247
  "cache-insight",
1232
1248
  "uses-long-cache-ttl",
1249
+ "image-delivery-insight",
1233
1250
  "offscreen-images",
1234
1251
  "modern-image-formats",
1235
1252
  "uses-responsive-images",
1236
1253
  "uses-optimized-images",
1254
+ "unsized-images",
1237
1255
  "bootup-time",
1238
1256
  "third-party-summary",
1239
1257
  "mainthread-work-breakdown",
1258
+ "forced-reflow-insight",
1240
1259
  "dom-size",
1241
1260
  "uses-rel-preconnect",
1242
1261
  "legacy-javascript",
@@ -1256,7 +1275,7 @@ function projectDiagnostics(audits) {
1256
1275
  const mode = String(audit.scoreDisplayMode ?? "");
1257
1276
  if (score === 1 || mode === "notApplicable" || mode === "manual")
1258
1277
  continue;
1259
- const logicalKey = auditId === "render-blocking-resources" ? "render-blocking" : auditId === "render-blocking-insight" ? "render-blocking" : auditId === "uses-long-cache-ttl" ? "cache" : auditId === "cache-insight" ? "cache" : auditId;
1278
+ const logicalKey = auditId === "render-blocking-resources" || auditId === "render-blocking-insight" ? "render-blocking" : auditId === "uses-long-cache-ttl" || auditId === "cache-insight" ? "cache" : auditId === "prioritize-lcp-image" || auditId === "lcp-discovery-insight" ? "lcp-discovery" : auditId === "critical-request-chains" || auditId === "network-dependency-tree-insight" ? "network-dependency" : auditId === "font-display" || auditId === "font-display-insight" ? "font-display" : auditId;
1260
1279
  if (seenLogical.has(logicalKey))
1261
1280
  continue;
1262
1281
  seenLogical.add(logicalKey);
@@ -1277,6 +1296,7 @@ function projectDiagnostics(audits) {
1277
1296
  const scriptParseCompileMs = finiteNumber(item.scriptParseCompile);
1278
1297
  const blockingTimeMs = finiteNumber(item.blockingTime);
1279
1298
  const cacheLifetimeMs = finiteNumber(item.cacheLifetimeMs);
1299
+ const itemScore = finiteNumber(item.score);
1280
1300
  return {
1281
1301
  ...url ? { url } : {},
1282
1302
  ...label ? { label } : {},
@@ -1287,7 +1307,8 @@ function projectDiagnostics(audits) {
1287
1307
  ...scriptingMs === void 0 ? {} : { scriptingMs },
1288
1308
  ...scriptParseCompileMs === void 0 ? {} : { scriptParseCompileMs },
1289
1309
  ...blockingTimeMs === void 0 ? {} : { blockingTimeMs },
1290
- ...cacheLifetimeMs === void 0 ? {} : { cacheLifetimeMs }
1310
+ ...cacheLifetimeMs === void 0 ? {} : { cacheLifetimeMs },
1311
+ ...itemScore === void 0 ? {} : { score: itemScore }
1291
1312
  };
1292
1313
  }).filter((item) => Object.keys(item).length > 0);
1293
1314
  const overallBytes = finiteNumber(details?.overallSavingsBytes) ?? sumNumbers(items.map((item) => item.wastedBytes)) ?? parseSavingsBytesFromDisplay(audit.displayValue);
@@ -1394,6 +1415,7 @@ function projectNetwork(logs) {
1394
1415
  if (typeof params.type === "string" && params.type)
1395
1416
  existing.resourceType = params.type;
1396
1417
  existing.responseHeaders = redactHeaders(response.headers ?? {});
1418
+ existing.responseHeadersCaptured = true;
1397
1419
  }
1398
1420
  if (entry.method === "Network.loadingFinished") {
1399
1421
  const params = entry.params;
@@ -1418,8 +1440,8 @@ function projectNetworkAuditItems(items) {
1418
1440
  const transferSize = typeof item.transferSize === "number" ? item.transferSize : void 0;
1419
1441
  const resourceSize = typeof item.resourceSize === "number" ? item.resourceSize : void 0;
1420
1442
  const protocol = typeof item.protocol === "string" && item.protocol ? item.protocol : void 0;
1421
- const startedAt = typeof item.startTime === "number" ? item.startTime : void 0;
1422
- const completedAt = typeof item.endTime === "number" ? item.endTime : void 0;
1443
+ const startedAt = typeof item.startTime === "number" ? item.startTime / 1e3 : void 0;
1444
+ const completedAt = typeof item.endTime === "number" ? item.endTime / 1e3 : void 0;
1423
1445
  const resourceType = typeof item.resourceType === "string" ? item.resourceType : void 0;
1424
1446
  return [{
1425
1447
  requestId: `audit_network_${index}`,
@@ -1433,7 +1455,8 @@ function projectNetworkAuditItems(items) {
1433
1455
  ...startedAt === void 0 ? {} : { startedAt },
1434
1456
  ...completedAt === void 0 ? {} : { completedAt },
1435
1457
  requestHeaders: {},
1436
- responseHeaders: mimeType ? { "content-type": mimeType } : {}
1458
+ responseHeaders: mimeType ? { "content-type": mimeType } : {},
1459
+ responseHeadersCaptured: false
1437
1460
  }];
1438
1461
  });
1439
1462
  }
@@ -1445,7 +1468,7 @@ function median(sorted) {
1445
1468
  // ../browser/dist/session-broker.js
1446
1469
  import { randomUUID as randomUUID2 } from "node:crypto";
1447
1470
  import { existsSync as existsSync2 } from "node:fs";
1448
- import { mkdir as mkdir2, rm } from "node:fs/promises";
1471
+ import { mkdir as mkdir2, readlink, rm } from "node:fs/promises";
1449
1472
  import { join as join2 } from "node:path";
1450
1473
  async function detectVisibleBrowserCapability(options = {}) {
1451
1474
  const env = options.env ?? process.env;
@@ -1507,17 +1530,56 @@ var CoreVisibleLoginLauncher = class {
1507
1530
  });
1508
1531
  return {
1509
1532
  kill: async () => {
1510
- await chrome.kill();
1533
+ await terminateChromeGracefully(chrome);
1511
1534
  }
1512
1535
  };
1513
1536
  }
1514
1537
  };
1538
+ function isProcessAlive(pid) {
1539
+ try {
1540
+ process.kill(pid, 0);
1541
+ return true;
1542
+ } catch (error) {
1543
+ return error.code === "EPERM";
1544
+ }
1545
+ }
1546
+ async function terminateChromeGracefully(chrome, gracefulTimeoutMs = 2500) {
1547
+ if (process.platform !== "win32" && chrome.pid && isProcessAlive(chrome.pid)) {
1548
+ try {
1549
+ process.kill(-chrome.pid, "SIGTERM");
1550
+ } catch {
1551
+ }
1552
+ const deadline = Date.now() + gracefulTimeoutMs;
1553
+ while (Date.now() < deadline && isProcessAlive(chrome.pid)) {
1554
+ await new Promise((resolve11) => setTimeout(resolve11, 25));
1555
+ }
1556
+ }
1557
+ await chrome.kill();
1558
+ }
1559
+ async function readStaleLockPid(singletonLockPath) {
1560
+ try {
1561
+ const target = await readlink(singletonLockPath);
1562
+ const match = /-(\d+)$/.exec(target);
1563
+ if (!match)
1564
+ return void 0;
1565
+ const pid = Number(match[1]);
1566
+ return Number.isInteger(pid) && pid > 0 ? pid : void 0;
1567
+ } catch {
1568
+ return void 0;
1569
+ }
1570
+ }
1515
1571
  async function waitForProfileLockRelease(profileDirectory, timeoutMs = 5e3, pollIntervalMs = 25) {
1516
1572
  const lockFiles = ["SingletonLock", "SingletonCookie", "SingletonSocket"].map((name) => join2(profileDirectory, name));
1573
+ const singletonLockPath = lockFiles[0];
1517
1574
  const deadline = Date.now() + timeoutMs;
1518
1575
  while (Date.now() < deadline) {
1519
1576
  if (lockFiles.every((file) => !existsSync2(file)))
1520
1577
  return;
1578
+ const lockPid = await readStaleLockPid(singletonLockPath);
1579
+ if (lockPid !== void 0 && !isProcessAlive(lockPid)) {
1580
+ await Promise.all(lockFiles.map((file) => rm(file, { force: true })));
1581
+ return;
1582
+ }
1521
1583
  await new Promise((resolve11) => setTimeout(resolve11, pollIntervalMs));
1522
1584
  }
1523
1585
  if (lockFiles.some((file) => existsSync2(file))) {
@@ -1632,6 +1694,53 @@ function compareScenarios(baseline, candidate) {
1632
1694
  }
1633
1695
 
1634
1696
  // ../browser/dist/retest.js
1697
+ var HIGHER_IS_BETTER_METRICS = /* @__PURE__ */ new Set(["performanceScore"]);
1698
+ function isMetricImproved(metric, baseline, retest) {
1699
+ const delta = retest - baseline;
1700
+ return HIGHER_IS_BETTER_METRICS.has(metric) ? delta > 0 : delta < 0;
1701
+ }
1702
+ function isMetricRegressed(metric, baseline, retest) {
1703
+ const delta = retest - baseline;
1704
+ return HIGHER_IS_BETTER_METRICS.has(metric) ? delta < 0 : delta > 0;
1705
+ }
1706
+ function checkProtectionRegression(metric) {
1707
+ if (metric.direction !== "regressed")
1708
+ return void 0;
1709
+ if (HIGHER_IS_BETTER_METRICS.has(metric.metric)) {
1710
+ const drop = metric.baseline - metric.retest;
1711
+ if (drop > 5)
1712
+ return `${metric.metric} regressed by ${Math.round(drop)} points`;
1713
+ return void 0;
1714
+ }
1715
+ if (metric.metric === "cls") {
1716
+ if (metric.retest - metric.baseline > 0.02 && metric.retest > 0.05) {
1717
+ return `cls regressed by ${(metric.retest - metric.baseline).toFixed(2)}`;
1718
+ }
1719
+ return void 0;
1720
+ }
1721
+ if (metric.delta > 50 && metric.retest > metric.baseline * 1.1) {
1722
+ return `${metric.metric} regressed by more than 10%`;
1723
+ }
1724
+ return void 0;
1725
+ }
1726
+ function isMeaningfulImprovement(metric, baselineRange, retestRange) {
1727
+ if (metric.direction !== "improved")
1728
+ return false;
1729
+ const gain = Math.abs(metric.delta);
1730
+ const baselineHalfSpread = baselineRange ? (baselineRange.max - baselineRange.min) / 2 : 0;
1731
+ const retestHalfSpread = retestRange ? (retestRange.max - retestRange.min) / 2 : 0;
1732
+ const noiseFloor = Math.max(baselineHalfSpread, retestHalfSpread);
1733
+ if (noiseFloor > 0 && gain <= noiseFloor)
1734
+ return false;
1735
+ if (metric.metric === "performanceScore")
1736
+ return metric.retest - metric.baseline >= 3;
1737
+ if (metric.metric === "cls")
1738
+ return metric.baseline - metric.retest >= 0.02;
1739
+ if (["lcpMs", "fcpMs", "tbtMs", "speedIndexMs"].includes(metric.metric)) {
1740
+ return gain >= 50 || metric.baseline > 0 && gain / metric.baseline >= 0.05;
1741
+ }
1742
+ return false;
1743
+ }
1635
1744
  function compareRetest(baselineScenario, retestScenario, baseline, retest) {
1636
1745
  const scenario = compareScenarios(baselineScenario, retestScenario);
1637
1746
  const empty = (status, protectionFailures2 = []) => ({
@@ -1650,23 +1759,36 @@ function compareRetest(baselineScenario, retestScenario, baseline, retest) {
1650
1759
  return empty("RETEST_INSUFFICIENT");
1651
1760
  if (baseline.measurementIds.some((id) => retest.measurementIds.includes(id)))
1652
1761
  return empty("MEASUREMENT_FAILED", ["Baseline and retest must reference distinct measurements."]);
1653
- const before = new Map(baseline.metrics.map((metric) => [metric.metric, metric.representative]));
1762
+ const beforeMap = new Map(baseline.metrics.map((metric) => [metric.metric, metric]));
1763
+ const afterMap = new Map(retest.metrics.map((metric) => [metric.metric, metric]));
1654
1764
  const metrics = retest.metrics.flatMap((metric) => {
1655
- const previous = before.get(metric.metric);
1656
- if (previous === void 0)
1765
+ const previous = beforeMap.get(metric.metric);
1766
+ if (!previous)
1657
1767
  return [];
1658
- const delta = metric.representative - previous;
1659
- return [{ metric: metric.metric, baseline: previous, retest: metric.representative, delta, direction: delta < 0 ? "improved" : delta > 0 ? "regressed" : "unchanged" }];
1768
+ const delta = metric.representative - previous.representative;
1769
+ const direction = isMetricImproved(metric.metric, previous.representative, metric.representative) ? "improved" : isMetricRegressed(metric.metric, previous.representative, metric.representative) ? "regressed" : "unchanged";
1770
+ return [{ metric: metric.metric, baseline: previous.representative, retest: metric.representative, delta, direction }];
1660
1771
  }).sort((a, b) => a.metric.localeCompare(b.metric));
1661
- const protectionFailures = metrics.filter((metric) => metric.delta > 0 && metric.retest > metric.baseline * 1.1).map((metric) => `${metric.metric} regressed by more than 10%`);
1662
- const improvement = metrics.some((metric) => ["lcpMs", "fcpMs", "tbtMs", "speedIndexMs"].includes(metric.metric) && metric.direction === "improved");
1772
+ const protectionFailures = metrics.map(checkProtectionRegression).filter((item) => Boolean(item));
1773
+ const uncertaintyReasons = [];
1774
+ if (baseline.sampleCount < 3 || !baseline.stabilityVerified) {
1775
+ uncertaintyReasons.push("Baseline stability is not verified (fewer than 3 samples or high variance).");
1776
+ }
1777
+ if (retest.sampleCount < 3 || !retest.stabilityVerified) {
1778
+ uncertaintyReasons.push("Retest stability is not verified (fewer than 3 samples or high variance).");
1779
+ }
1780
+ const improvement = metrics.some((metric) => isMeaningfulImprovement(metric, beforeMap.get(metric.metric), afterMap.get(metric.metric)));
1781
+ if (!improvement && metrics.some((m) => m.direction === "improved")) {
1782
+ uncertaintyReasons.push("Observed metric improvement did not exceed measurement variability or minimum significance threshold.");
1783
+ }
1663
1784
  return {
1664
1785
  status: "COMPARABLE",
1665
1786
  scenarioMismatches: [],
1666
1787
  measurements: { baseline: baseline.measurementIds, retest: retest.measurementIds },
1667
1788
  metrics,
1668
1789
  protectionFailures,
1669
- conclusion: improvement && protectionFailures.length === 0 ? "PROVEN_IMPROVEMENT" : "LIMITED_COMPARISON"
1790
+ ...uncertaintyReasons.length > 0 ? { uncertaintyReasons } : {},
1791
+ conclusion: improvement && protectionFailures.length === 0 && uncertaintyReasons.length === 0 ? "PROVEN_IMPROVEMENT" : "LIMITED_COMPARISON"
1670
1792
  };
1671
1793
  }
1672
1794
 
@@ -1994,9 +2116,10 @@ function looksLikeBroadComponentSplit(task) {
1994
2116
  ...task.currentCodeFacts,
1995
2117
  ...task.requiredChanges.map((change) => `${change.action} ${change.description}`)
1996
2118
  ].join(" ").toLowerCase();
1997
- const broadSplit = /split|lazy|code[-\s]?split|component/.test(text) && /large|big|route|landing|first[-\s]?route/.test(text);
1998
- const causal = /render delay|main[-\s]?thread|css[-\s]?blocking|hydration/.test(text);
1999
- return broadSplit && !causal;
2119
+ const broadSplitEn = /split|lazy|code[-\s]?split|component/.test(text) && /large|big|route|landing|first[-\s]?route/.test(text);
2120
+ const broadSplitZh = /(拆分|重构|懒加载).{0,8}(整页|大组件|首页组件|页面组件)/.test(text) && !/(弹窗|抽屉|tab|首屏外|非首屏|路由级|第三方)/.test(text);
2121
+ const causal = /render delay|main[-\s]?thread|css[-\s]?blocking|hydration|渲染延迟|主线程|长任务|阻塞渲染|水合/.test(text);
2122
+ return (broadSplitEn || broadSplitZh) && !causal;
2000
2123
  }
2001
2124
  function findConflicts(task, existing) {
2002
2125
  const currentFiles = new Set(task.allowedFiles.map((file) => file.path));
@@ -2005,6 +2128,9 @@ function findConflicts(task, existing) {
2005
2128
  const otherIsCode = other.kind === "execution" || other.kind === "code-execution";
2006
2129
  if (task.conflicts.includes(other.taskId) || other.conflicts.includes(task.taskId))
2007
2130
  return [`Task explicitly conflicts with ${other.taskId}`];
2131
+ const hasExplicitOrder = task.dependencies.includes(other.taskId) || other.dependencies.includes(task.taskId);
2132
+ if (hasExplicitOrder)
2133
+ return [];
2008
2134
  const overlap = other.allowedFiles.find((file) => currentFiles.has(file.path));
2009
2135
  return overlap && isCode && otherIsCode ? [`Task overlaps execution scope with ${other.taskId}: ${overlap.path}`] : [];
2010
2136
  });
@@ -2044,7 +2170,9 @@ function compileReport(input, acceptedTasks) {
2044
2170
  const parity = input.sourceAnalysis?.versionParity;
2045
2171
  const deviceLabel = input.scenario.device.mobile ? "\u79FB\u52A8\u7AEF" : "\u684C\u9762\u7AEF";
2046
2172
  const dateLabel = input.createdAt.slice(0, 10);
2047
- const sampleDesc = input.aggregate.stabilityVerified ? `\u5B9E\u6D4B ${input.aggregate.sampleCount} \u6B21\u53D6\u4E2D\u4F4D\u6570` : `\u5355\u6B21\u6D4B\u91CF\uFF08${input.aggregate.sampleCount} \u6B21\uFF0C\u7A33\u5B9A\u6027\u672A\u9A8C\u8BC1\uFF09`;
2173
+ const sampleDesc = input.aggregate.stabilityVerified ? `\u5B9E\u6D4B ${input.aggregate.sampleCount} \u6B21\u53D6\u4E2D\u4F4D\u6570` : input.aggregate.sampleCount >= 3 ? `\u5B9E\u6D4B ${input.aggregate.sampleCount} \u6B21\u53D6\u4E2D\u4F4D\u6570\uFF08\u6837\u672C\u6CE2\u52A8\u8F83\u5927\uFF0C\u7A33\u5B9A\u6027\u672A\u9A8C\u8BC1\uFF09` : `\u5355\u6B21/\u5C11\u91CF\u6D4B\u91CF\uFF08${input.aggregate.sampleCount} \u6B21\uFF0C\u7A33\u5B9A\u6027\u672A\u9A8C\u8BC1\uFF09`;
2174
+ const varianceLine = input.aggregate.highVarianceMetrics?.length ? `
2175
+ - **\u6CE2\u52A8\u63D0\u9192**\uFF1A\u26A0\uFE0F \u591A\u6B21\u91C7\u6837\u5B58\u5728\u8F83\u5927\u6CE2\u52A8\uFF08${input.aggregate.highVarianceMetrics.map((m) => `${m.metric} \u533A\u95F4 ${formatMetricValue(m.metric, m.min)}\u2013${formatMetricValue(m.metric, m.max)}`).join("\u3001")}\uFF09\uFF0C\u590D\u6D4B\u65F6\u5EFA\u8BAE\u4FDD\u6301\u76F8\u540C\u7F51\u7EDC\u73AF\u5883\u5E76\u5173\u6CE8\u533A\u95F4\u53D8\u5316\u3002` : "";
2048
2176
  const parityLine = parity?.status === "mismatch" ? `- **\u7248\u672C\u63D0\u9192**\uFF1A\u26A0\uFE0F **\u7EBF\u4E0A\u8FD0\u884C\u7248\u672C\u4E0E\u672C\u5730\u4EE3\u7801\u4ED3\u5E93\u4E0D\u4E00\u81F4**\uFF08${parity.summary}\uFF09\u3002\u4E0B\u9762\u628A\u201C\u7EBF\u4E0A\u95EE\u9898\u201D\u548C\u201C\u672C\u5730\u4EE3\u7801\u95EE\u9898\u201D\u5206\u5F00\u5217\u51FA\u3002` : parity?.status === "matched" ? `- **\u7248\u672C\u4E00\u81F4\u6027**\uFF1A\u2705 \u7EBF\u4E0A\u4EA7\u7269\u4E0E\u672C\u5730\u4ED3\u5E93\u4E00\u81F4\uFF08${parity.summary}\uFF09\u3002` : `- **\u7248\u672C\u4E00\u81F4\u6027**\uFF1A\u5C1A\u672A\u6838\u9A8C\u7EBF\u4E0A\u4E0E\u672C\u5730\u6784\u5EFA\u54C8\u5E0C\u662F\u5426\u4E00\u81F4\u3002`;
2049
2177
  const metricsMap = new Map(input.aggregate.metrics.map((m) => [m.metric, m]));
2050
2178
  const headline = input.sourceAnalysis?.executiveSummary?.headline ?? buildDefaultHeadline(metricsMap);
@@ -2070,7 +2198,7 @@ ${sopChecklist.map((item) => `| ${item.dimension} | ${sopStatusLabel(item.status
2070
2198
 
2071
2199
  - **\u6D4B\u8BD5\u5730\u5740**\uFF1A\`${input.scenario.requestedUrl}\`
2072
2200
  - **\u5BF9\u5E94\u4EE3\u7801\u4ED3\u5E93**\uFF1A\`${repoPath}\`
2073
- - **\u6D4B\u8BD5\u6761\u4EF6**\uFF1A${deviceLabel}\u6A21\u62DF ${input.scenario.network.id} \u7F51\u7EDC\uFF0C${sampleDesc}\uFF08${dateLabel}\uFF09
2201
+ - **\u6D4B\u8BD5\u6761\u4EF6**\uFF1A${deviceLabel}\u6A21\u62DF ${input.scenario.network.id} \u7F51\u7EDC\uFF0C${sampleDesc}\uFF08${dateLabel}\uFF09${varianceLine}
2074
2202
  ${parityLine}
2075
2203
 
2076
2204
  ---
@@ -2435,6 +2563,25 @@ function describeDiagnosticStatus(diag) {
2435
2563
  const totalKbText = totalBytes > 0 ? `${Math.round(totalBytes / 1024)} KB` : "";
2436
2564
  const durText = sumDurationMs > 0 ? formatMsHuman(sumDurationMs) : diag.numericValue ? formatMsHuman(diag.numericValue) : "";
2437
2565
  switch (diag.auditId) {
2566
+ case "server-response-time":
2567
+ return `\u4E3B\u6587\u6863\u670D\u52A1\u7AEF\u9996\u5B57\u8282\u54CD\u5E94\uFF08TTFB\uFF09\u504F\u6162${diag.numericValue ? `\uFF08\u7EA6 ${formatMsHuman(diag.numericValue)}\uFF09` : ""}\uFF0C\u76F4\u63A5\u63A8\u8FDF\u6240\u6709\u540E\u7EED\u8D44\u6E90\u53D1\u73B0\u4E0E\u7ED8\u5236`;
2568
+ case "redirects":
2569
+ return `\u5165\u53E3\u9875\u9762\u5B58\u5728\u591A\u6B21 HTTP \u91CD\u5B9A\u5411\uFF0C\u767D\u767D\u589E\u52A0\u989D\u5916\u7F51\u7EDC\u5F80\u8FD4\u8017\u65F6`;
2570
+ case "lcp-discovery-insight":
2571
+ case "prioritize-lcp-image":
2572
+ return `LCP \u4E3B\u56FE\u672A\u88AB\u6D4F\u89C8\u5668\u5C3D\u65E9\u53D1\u73B0\u6216\u7F3A\u5C11\u9AD8\u4F18\u5148\u7EA7\u58F0\u660E\uFF08\u5982 fetchpriority="high"\uFF09\uFF0C\u6216\u8BEF\u7528\u4E86\u61D2\u52A0\u8F7D`;
2573
+ case "network-dependency-tree-insight":
2574
+ case "critical-request-chains":
2575
+ return `\u5173\u952E\u9996\u5C4F\u8D44\u6E90\u5B58\u5728\u8F83\u6DF1\u7684\u4E32\u884C\u8BF7\u6C42\u4F9D\u8D56\u94FE\uFF0C\u62C9\u957F\u4E86\u9996\u5C4F\u6574\u4F53\u52A0\u8F7D\u65F6\u95F4`;
2576
+ case "font-display-insight":
2577
+ case "font-display":
2578
+ return `\u81EA\u5B9A\u4E49 Web \u5B57\u4F53\u52A0\u8F7D\u671F\u95F4\u53EF\u80FD\u963B\u585E\u6587\u5B57\u6E32\u67D3\uFF08FOIT\uFF09\uFF0C\u5EFA\u8BAE\u914D\u7F6E font-display: swap/optional`;
2579
+ case "image-delivery-insight":
2580
+ return `${count || "\u591A"} \u5F20\u56FE\u7247\u5B58\u5728\u683C\u5F0F\u3001\u538B\u7F29\u6216\u5206\u8FA8\u7387\u5197\u4F59${totalKbText ? `\uFF08\u5F53\u524D\u4F53\u79EF ${totalKbText}\uFF09` : ""}\uFF0C\u53EF\u663E\u8457\u51CF\u5C11\u56FE\u7247\u4F20\u8F93\u4F53\u79EF`;
2581
+ case "unsized-images":
2582
+ return `${count || "\u591A"} \u5F20\u56FE\u7247\u7F3A\u5C11\u663E\u5F0F width/height \u6216\u7A33\u5B9A\u5BBD\u9AD8\u6BD4\uFF0C\u52A0\u8F7D\u5B8C\u6210\u524D\u540E\u6613\u89E6\u53D1\u5E03\u5C40\u504F\u79FB\uFF08CLS\uFF09`;
2583
+ case "forced-reflow-insight":
2584
+ return `\u811A\u672C\u5728\u9996\u5C4F\u6267\u884C\u671F\u95F4\u89E6\u53D1\u4E86\u5F3A\u5236\u540C\u6B65\u5E03\u5C40\uFF08Forced Reflow\uFF09\uFF0C\u589E\u52A0\u4E3B\u7EBF\u7A0B\u6837\u5F0F\u4E0E\u6392\u7248\u5F00\u9500`;
2438
2585
  case "render-blocking-insight":
2439
2586
  case "render-blocking-resources":
2440
2587
  return `\u9996\u5C4F\u6E32\u67D3\u524D\u540C\u6B65\u52A0\u8F7D ${count || "\u591A"} \u4E2A\u8D44\u6E90${totalKbText ? `\uFF08\u603B\u4F53\u79EF ${totalKbText}\uFF09` : ""}${durText ? `\uFF0C\u963B\u585E\u8017\u65F6\u7EA6 ${durText}` : ""}\uFF0C\u6D4F\u89C8\u5668\u5FC5\u987B\u7B49\u5B83\u4EEC\u4E0B\u8F7D\u6267\u884C\u5B8C\u624D\u5F00\u59CB\u7ED8\u5236`;
@@ -2502,6 +2649,17 @@ function shortAssetName(name) {
2502
2649
  }
2503
2650
  function translateAuditTitle(auditId, fallback) {
2504
2651
  const map = {
2652
+ "server-response-time": "\u670D\u52A1\u7AEF\u9996\u5B57\u8282\u54CD\u5E94\uFF08TTFB\uFF09\u504F\u6162",
2653
+ "redirects": "\u5165\u53E3\u5B58\u5728\u591A\u4F59\u91CD\u5B9A\u5411\u8DF3\u8F6C",
2654
+ "lcp-discovery-insight": "LCP \u4E3B\u56FE\u53D1\u73B0\u8FC7\u665A\u6216\u7F3A\u5C11\u9AD8\u4F18\u5148\u7EA7\u52A0\u8F7D",
2655
+ "prioritize-lcp-image": "LCP \u4E3B\u56FE\u53D1\u73B0\u8FC7\u665A\u6216\u7F3A\u5C11\u9AD8\u4F18\u5148\u7EA7\u52A0\u8F7D",
2656
+ "network-dependency-tree-insight": "\u5173\u952E\u9996\u5C4F\u8D44\u6E90\u5B58\u5728\u8FC7\u957F\u4E32\u884C\u4F9D\u8D56\u94FE",
2657
+ "critical-request-chains": "\u5173\u952E\u9996\u5C4F\u8D44\u6E90\u5B58\u5728\u8FC7\u957F\u4E32\u884C\u4F9D\u8D56\u94FE",
2658
+ "font-display-insight": "Web \u5B57\u4F53\u52A0\u8F7D\u963B\u585E\u9996\u5C4F\u6587\u5B57\u6E32\u67D3",
2659
+ "font-display": "Web \u5B57\u4F53\u52A0\u8F7D\u963B\u585E\u9996\u5C4F\u6587\u5B57\u6E32\u67D3",
2660
+ "image-delivery-insight": "\u9996\u5C4F\u56FE\u7247\u4F20\u8F93\u4F53\u79EF\u4E0E\u683C\u5F0F\u5F85\u4F18\u5316",
2661
+ "unsized-images": "\u56FE\u7247\u7F3A\u5C11\u663E\u5F0F\u5BBD\u9AD8\u5BFC\u81F4\u5E03\u5C40\u504F\u79FB\u98CE\u9669",
2662
+ "forced-reflow-insight": "\u9996\u5C4F\u5B58\u5728\u5F3A\u5236\u540C\u6B65\u5E03\u5C40\uFF08Forced Reflow\uFF09",
2505
2663
  "uses-text-compression": "\u672A\u5F00\u542F\u6587\u672C\u538B\u7F29\uFF08gzip/brotli\uFF09",
2506
2664
  "render-blocking-insight": "\u963B\u585E\u9996\u5C4F\u6E32\u67D3\u7684\u8D44\u6E90",
2507
2665
  "render-blocking-resources": "\u963B\u585E\u9996\u5C4F\u6E32\u67D3\u7684\u8D44\u6E90",
@@ -2529,9 +2687,19 @@ var MEASURED_COST_AUDIT_IDS = /* @__PURE__ */ new Set([
2529
2687
  "bootup-time",
2530
2688
  "third-party-summary",
2531
2689
  "mainthread-work-breakdown",
2532
- "dom-size"
2690
+ "dom-size",
2691
+ "server-response-time",
2692
+ "forced-reflow-insight"
2533
2693
  ]);
2534
2694
  function formatDiagnosticImpact(diag) {
2695
+ if (diag.auditId === "server-response-time") {
2696
+ const ms = diag.numericValue ?? diag.wastedMs;
2697
+ return ms !== void 0 && ms > 0 ? `TTFB \u8017\u65F6 ${formatMsHuman(ms)}` : diag.displayValue || "\u670D\u52A1\u7AEF\u54CD\u5E94\u504F\u6162";
2698
+ }
2699
+ if (diag.auditId === "forced-reflow-insight") {
2700
+ const ms = diag.numericValue ?? diag.wastedMs;
2701
+ return ms !== void 0 && ms > 0 ? `\u91CD\u6392\u8017\u65F6 ${formatMsHuman(ms)}` : diag.displayValue || "\u5B58\u5728\u5F3A\u5236\u91CD\u6392";
2702
+ }
2535
2703
  if (diag.auditId === "bootup-time") {
2536
2704
  const ms = diag.numericValue ?? diag.wastedMs;
2537
2705
  return ms !== void 0 && ms > 0 ? `\u811A\u672C\u6267\u884C\u8017\u65F6 ${formatMsHuman(ms)}` : diag.displayValue || "\u811A\u672C\u8017\u65F6\u504F\u9AD8";
@@ -3726,7 +3894,7 @@ var ActiveRunRegistry2 = class {
3726
3894
  try {
3727
3895
  const parsed = JSON.parse(await readFile5(this.activeRunsFile, "utf8"));
3728
3896
  const runs = Array.isArray(parsed.runs) ? parsed.runs : [];
3729
- return runs.filter((item) => Date.parse(item.expiresAt) > nowMs && isProcessAlive(item.pid));
3897
+ return runs.filter((item) => Date.parse(item.expiresAt) > nowMs && isProcessAlive2(item.pid));
3730
3898
  } catch {
3731
3899
  return [];
3732
3900
  }
@@ -3762,7 +3930,7 @@ var ActiveRunRegistry2 = class {
3762
3930
  }
3763
3931
  }
3764
3932
  };
3765
- function isProcessAlive(pid) {
3933
+ function isProcessAlive2(pid) {
3766
3934
  if (!Number.isInteger(pid) || pid <= 0) return false;
3767
3935
  try {
3768
3936
  process.kill(pid, 0);
@@ -4246,7 +4414,7 @@ var CoreRuntime = class {
4246
4414
  payload: { measurementId: measurement.measurementId, artifactId: reportArtifact.manifest.artifactId, metrics: measurement.metrics }
4247
4415
  });
4248
4416
  }
4249
- data.issues.push(...createIssues(runId, scenario, data.graph, aggregate.metrics, selectRepresentativeMeasurement(batch.successful)));
4417
+ data.issues.push(...createIssues(runId, scenario, data.graph, aggregate.metrics, batch.successful));
4250
4418
  data.runtimeEvidence = createRuntimeEvidenceSummaries(data.issues, batch.successful);
4251
4419
  await this.persistRunData(runId);
4252
4420
  this.metrics.recordMeasurement(runId, aggregate.sampleCount, aggregate.stabilityVerified);
@@ -5210,7 +5378,7 @@ function projectEvidenceItems(kind, data, representative) {
5210
5378
  case "network-requests":
5211
5379
  return network.map((req) => projectResourceEvidence(req));
5212
5380
  case "render-blocking":
5213
- return network.filter((req) => ["css", "script"].includes(resourceKind(req))).map(projectResourceEvidence);
5381
+ return selectRenderBlockingRequests(representative).requests.map(projectResourceEvidence);
5214
5382
  case "lcp-breakdown":
5215
5383
  return data.issues.filter((issue) => issue.causalEvidence?.lcp).map((issue) => ({ issueId: issue.issueId, lcp: issue.causalEvidence.lcp }));
5216
5384
  case "long-tasks": {
@@ -5228,8 +5396,9 @@ function projectEvidenceItems(kind, data, representative) {
5228
5396
  protocol: req.protocol ?? "unknown",
5229
5397
  status: req.status,
5230
5398
  transferSize: req.transferSize,
5231
- cacheControl: headerValue(req.responseHeaders, "cache-control") ?? "missing",
5232
- contentEncoding: headerValue(req.responseHeaders, "content-encoding") ?? "missing",
5399
+ responseHeadersCaptured: req.responseHeadersCaptured !== false,
5400
+ cacheControl: resolveHeaderStatus(req, "cache-control"),
5401
+ contentEncoding: resolveHeaderStatus(req, "content-encoding"),
5233
5402
  contentType: headerValue(req.responseHeaders, "content-type") ?? "unknown"
5234
5403
  }));
5235
5404
  case "top-assets": {
@@ -5242,13 +5411,13 @@ function projectEvidenceItems(kind, data, representative) {
5242
5411
  ...req.resourceSize === void 0 ? {} : { resourceSize: req.resourceSize },
5243
5412
  sharePct: totalBytes > 0 ? Number(((req.transferSize ?? 0) / totalBytes * 100).toFixed(1)) : 0,
5244
5413
  protocol: req.protocol ?? "unknown",
5245
- cacheControl: headerValue(req.responseHeaders, "cache-control") ?? "missing",
5246
- contentEncoding: headerValue(req.responseHeaders, "content-encoding") ?? "missing"
5414
+ cacheControl: resolveHeaderStatus(req, "cache-control"),
5415
+ contentEncoding: resolveHeaderStatus(req, "content-encoding")
5247
5416
  }));
5248
5417
  }
5249
5418
  case "image-audit": {
5250
5419
  const imageDiagnostics = (representative?.diagnostics ?? []).filter(
5251
- (d) => ["offscreen-images", "modern-image-formats", "uses-responsive-images", "uses-optimized-images"].includes(d.auditId)
5420
+ (d) => ["image-delivery-insight", "offscreen-images", "modern-image-formats", "uses-responsive-images", "uses-optimized-images", "unsized-images"].includes(d.auditId)
5252
5421
  );
5253
5422
  const imageRequests = network.filter((req) => resourceKind(req) === "image").sort((a, b) => (b.transferSize ?? 0) - (a.transferSize ?? 0)).map((req) => ({
5254
5423
  kind: "image-request",
@@ -5267,7 +5436,7 @@ function projectEvidenceItems(kind, data, representative) {
5267
5436
  }
5268
5437
  case "script-and-third-party": {
5269
5438
  const scriptDiagnostics = (representative?.diagnostics ?? []).filter(
5270
- (d) => ["bootup-time", "third-party-summary", "unused-javascript", "duplicated-javascript", "legacy-javascript", "dom-size", "mainthread-work-breakdown"].includes(d.auditId)
5439
+ (d) => ["bootup-time", "third-party-summary", "unused-javascript", "duplicated-javascript", "legacy-javascript", "dom-size", "mainthread-work-breakdown", "forced-reflow-insight"].includes(d.auditId)
5271
5440
  );
5272
5441
  const topScripts = network.filter((req) => resourceKind(req) === "script").sort((a, b) => (b.transferSize ?? 0) - (a.transferSize ?? 0)).map((req) => ({
5273
5442
  kind: "script-request",
@@ -5329,7 +5498,7 @@ function projectEvidenceItems(kind, data, representative) {
5329
5498
  totalBytes: d.totalBytes,
5330
5499
  protocols: [...d.protocols]
5331
5500
  }));
5332
- const preconnectDiag = (representative?.diagnostics ?? []).filter((d) => d.auditId === "uses-rel-preconnect").map((d) => ({ kind: "preconnect-diagnostic", ...d }));
5501
+ const preconnectDiag = (representative?.diagnostics ?? []).filter((d) => ["uses-rel-preconnect", "server-response-time", "redirects", "network-dependency-tree-insight", "critical-request-chains", "font-display-insight", "font-display"].includes(d.auditId)).map((d) => ({ kind: "network-diagnostic", ...d }));
5333
5502
  return [...domains, ...duplicateRequests, ...preconnectDiag, ...apiRequests];
5334
5503
  }
5335
5504
  }
@@ -5341,20 +5510,21 @@ function isInside(parent, candidate) {
5341
5510
  function capabilityDigest(capabilities) {
5342
5511
  return createHash8("sha256").update(JSON.stringify(capabilities, Object.keys(capabilities).sort())).digest("hex");
5343
5512
  }
5344
- function createIssues(runId, scenario, graph, metrics, representative) {
5513
+ function createIssues(runId, scenario, graph, metrics, measurements = []) {
5345
5514
  const thresholds = { fcpMs: 1800, lcpMs: 2500, cls: 0.1, tbtMs: 200, speedIndexMs: 3400 };
5346
5515
  return metrics.flatMap((metric) => {
5347
5516
  const threshold = thresholds[metric.metric];
5348
5517
  if (threshold === void 0 || metric.representative <= threshold) return [];
5349
5518
  const evidenceId = createEvidenceId();
5350
- const causalEvidence = representative ? createCausalEvidence(metric.metric, representative) : void 0;
5351
- graph.addNode({ id: evidenceId, runId, scenarioId: scenario.scenarioId, type: "Observation", schemaVersion: "1.0.0", revision: 0, producer: "observation-rule", upstreamIds: [], payload: { metric, threshold, causalEvidence } });
5519
+ const metricRepresentative = selectRepresentativeMeasurementForMetric(measurements, metric.metric);
5520
+ const causalEvidence = metricRepresentative ? createCausalEvidence(metric.metric, metricRepresentative) : void 0;
5521
+ graph.addNode({ id: evidenceId, runId, scenarioId: scenario.scenarioId, type: "Observation", schemaVersion: "1.0.0", revision: 0, producer: "observation-rule", upstreamIds: [], payload: { metric, threshold, causalEvidence, ...metricRepresentative ? { measurementId: metricRepresentative.measurementId } : {} } });
5352
5522
  return [createConfirmedRuntimeIssue({
5353
5523
  issueId: `issue_${metric.metric}`,
5354
5524
  category: metric.metric,
5355
5525
  severity: metric.representative > threshold * 1.5 ? "P0" : "P1",
5356
5526
  target: metric.metric,
5357
- observations: [{ observationId: `obs_${metric.metric}`, metric: metric.metric, observedValue: metric.representative, unit: "ms", threshold, thresholdSource: "reference", target: metric.metric, scenarioId: scenario.scenarioId, evidenceIds: [evidenceId], reproduction: "Repeat the frozen diagnostic scenario." }],
5527
+ observations: [{ observationId: `obs_${metric.metric}`, metric: metric.metric, observedValue: metric.representative, unit: metric.metric === "cls" ? "score" : "ms", threshold, thresholdSource: "reference", target: metric.metric, scenarioId: scenario.scenarioId, evidenceIds: [evidenceId], reproduction: "Repeat the frozen diagnostic scenario." }],
5358
5528
  scenarioId: scenario.scenarioId,
5359
5529
  limitations: causalEvidenceLimitations(causalEvidence),
5360
5530
  ...causalEvidence ? { causalEvidence } : {}
@@ -5429,13 +5599,34 @@ function createCausalEvidence(metric, measurement) {
5429
5599
  if (metric === "fcpMs" || metric === "speedIndexMs") {
5430
5600
  return { loading: createLoadingEvidence(measurement), ...diagnostics.length > 0 ? { diagnostics } : {} };
5431
5601
  }
5602
+ if (metric === "cls") {
5603
+ return { cls: createClsEvidence(measurement), ...diagnostics.length > 0 ? { diagnostics } : {} };
5604
+ }
5432
5605
  return diagnostics.length > 0 ? { diagnostics } : void 0;
5433
5606
  }
5607
+ function createClsEvidence(measurement) {
5608
+ const diagnostics = measurement.diagnostics ?? [];
5609
+ const shiftDiag = diagnostics.find((d) => d.auditId === "layout-shift-elements");
5610
+ const unsizedDiag = diagnostics.find((d) => d.auditId === "unsized-images");
5611
+ const shiftElements = (shiftDiag?.items ?? []).slice(0, 8).map((item) => ({
5612
+ ...item.label ? { label: item.label, selector: item.label } : {},
5613
+ ...item.score === void 0 ? {} : { score: item.score }
5614
+ }));
5615
+ const unsizedImages = (unsizedDiag?.items ?? []).slice(0, 8).map((item) => ({
5616
+ ...item.url ? { url: item.url } : {},
5617
+ ...item.label ? { label: item.label } : {}
5618
+ }));
5619
+ const unavailableReasons = [];
5620
+ if (shiftElements.length === 0 && unsizedImages.length === 0) {
5621
+ unavailableReasons.push("No layout shift element details available in Lighthouse artifacts");
5622
+ }
5623
+ return { shiftElements, unsizedImages, unavailableReasons };
5624
+ }
5434
5625
  function createLcpEvidence(measurement) {
5435
5626
  const audits = getAudits(measurement);
5436
5627
  const element = projectLcpElement(audits?.["largest-contentful-paint-element"], audits?.["lcp-breakdown-insight"]);
5437
5628
  const phases = projectLcpPhases(audits?.["largest-contentful-paint-element"], audits?.["lcp-breakdown-insight"]);
5438
- const resource = findLikelyLcpResource(element, measurement.network);
5629
+ const resource = findLikelyLcpResource(element, measurement.network, audits);
5439
5630
  const serverResponseMs = phases.serverResponseMs ?? getAuditNumericValue(audits?.["server-response-time"]);
5440
5631
  const resourceLoadDelayMs = phases.resourceLoadDelayMs;
5441
5632
  const resourceLoadDurationMs = phases.resourceLoadDurationMs ?? resource?.timingMs?.duration;
@@ -5450,12 +5641,14 @@ function createLcpEvidence(measurement) {
5450
5641
  const completeForMedia = Boolean(element && resource?.url && serverResponseMs !== void 0 && resourceLoadDurationMs !== void 0);
5451
5642
  const executionPlanningEligible = completeForText || completeForMedia;
5452
5643
  const breakdownStatus = executionPlanningEligible ? "complete" : element || serverResponseMs !== void 0 ? "partial" : "unavailable";
5644
+ const bottlenecks = inferLcpBottlenecks(serverResponseMs, resourceLoadDelayMs, resourceLoadDurationMs, elementRenderDelayMs);
5453
5645
  const result = {
5454
5646
  resource: resource ?? {
5455
5647
  unavailableReason: isTextLcp ? "LCP element is a text node (no image resource); bottleneck is server response or render delay" : "No image/font/resource request could be tied to the LCP element"
5456
5648
  },
5457
5649
  breakdownStatus,
5458
- likelyBottleneck: inferLcpBottleneck(serverResponseMs, resourceLoadDurationMs, elementRenderDelayMs),
5650
+ likelyBottleneck: bottlenecks.primary,
5651
+ ...bottlenecks.contributing.length > 0 ? { contributingBottlenecks: bottlenecks.contributing } : {},
5459
5652
  executionPlanningEligible,
5460
5653
  unavailableReasons: [...new Set(unavailableReasons)]
5461
5654
  };
@@ -5466,13 +5659,56 @@ function createLcpEvidence(measurement) {
5466
5659
  if (elementRenderDelayMs !== void 0) result.elementRenderDelayMs = elementRenderDelayMs;
5467
5660
  return result;
5468
5661
  }
5662
+ function isPreCompressedAsset(request) {
5663
+ const kind = resourceKind(request);
5664
+ if (kind === "image") return true;
5665
+ if (kind === "font") {
5666
+ const lowerUrl = request.url.toLowerCase();
5667
+ const ct = (headerValue(request.responseHeaders, "content-type") ?? "").toLowerCase();
5668
+ return lowerUrl.includes(".woff2") || ct.includes("woff2");
5669
+ }
5670
+ return false;
5671
+ }
5672
+ function resolveHeaderStatus(request, name) {
5673
+ const value = headerValue(request.responseHeaders, name);
5674
+ if (value) return value;
5675
+ return request.responseHeadersCaptured === false ? "unavailable" : "missing";
5676
+ }
5677
+ function selectRenderBlockingRequests(measurement) {
5678
+ if (!measurement) return { requests: [], verified: false };
5679
+ const audits = getAudits(measurement);
5680
+ const rawAudit = audits?.["render-blocking-insight"] ?? audits?.["render-blocking-resources"];
5681
+ const blockingDiag = (measurement.diagnostics ?? []).find(
5682
+ (d) => d.auditId === "render-blocking-insight" || d.auditId === "render-blocking-resources"
5683
+ );
5684
+ if (rawAudit || blockingDiag) {
5685
+ const blockingUrls = new Set((blockingDiag?.items ?? []).map((item) => item.url).filter((u) => Boolean(u)));
5686
+ if (blockingUrls.size === 0) return { requests: [], verified: true };
5687
+ return { requests: measurement.network.filter((req) => blockingUrls.has(req.url)), verified: true };
5688
+ }
5689
+ const cssOnly = measurement.network.filter((request) => resourceKind(request) === "css");
5690
+ return { requests: cssOnly, verified: false };
5691
+ }
5469
5692
  function createLoadingEvidence(measurement) {
5470
5693
  const document = measurement.network.find((request) => resourceKind(request) === "document");
5471
- const renderBlocking = measurement.network.filter((request) => ["css", "script"].includes(resourceKind(request))).slice(0, 20).map(projectResourceEvidence);
5472
- const staticDelivery = measurement.network.filter((request) => ["css", "script", "font", "image"].includes(resourceKind(request))).filter((request) => !headerValue(request.responseHeaders, "cache-control") || !headerValue(request.responseHeaders, "content-encoding")).slice(0, 20).map(projectResourceEvidence);
5694
+ const blockingSelection = selectRenderBlockingRequests(measurement);
5695
+ const renderBlocking = blockingSelection.requests.slice(0, 20).map(projectResourceEvidence);
5696
+ const headersUnavailable = measurement.network.length > 0 && measurement.network.every((req) => req.responseHeadersCaptured === false);
5697
+ const staticDelivery = measurement.network.filter((request) => request.responseHeadersCaptured !== false).filter((request) => ["css", "script", "font", "image"].includes(resourceKind(request))).filter((request) => {
5698
+ const missingCache = !headerValue(request.responseHeaders, "cache-control");
5699
+ const missingEncoding = !isPreCompressedAsset(request) && !headerValue(request.responseHeaders, "content-encoding");
5700
+ return missingCache || missingEncoding;
5701
+ }).slice(0, 20).map(projectResourceEvidence);
5473
5702
  const unavailableReasons = [];
5474
5703
  if (!document) unavailableReasons.push("Document request timing unavailable");
5475
- if (renderBlocking.length === 0) unavailableReasons.push("No render-blocking stylesheet/script candidates captured");
5704
+ if (renderBlocking.length === 0) {
5705
+ unavailableReasons.push(
5706
+ blockingSelection.verified ? "Lighthouse confirmed no render-blocking stylesheet/script resources" : "Render-blocking audit unavailable in Lighthouse artifacts"
5707
+ );
5708
+ }
5709
+ if (headersUnavailable) {
5710
+ unavailableReasons.push("Response headers were not captured (fallback network audit lacks Cache-Control/Content-Encoding)");
5711
+ }
5476
5712
  const canDistinguishNetworkFromRenderCost = Boolean(document && renderBlocking.length > 0);
5477
5713
  if (!canDistinguishNetworkFromRenderCost) unavailableReasons.push("Evidence cannot distinguish network delivery from client rendering cost");
5478
5714
  const result = {
@@ -5545,7 +5781,27 @@ function projectLcpPhases(lcpAudit, insightAudit) {
5545
5781
  }
5546
5782
  return result;
5547
5783
  }
5548
- function findLikelyLcpResource(element, requests) {
5784
+ function extractLcpResourceUrlFromAudits(audits) {
5785
+ if (!audits) return void 0;
5786
+ for (const auditId of ["lcp-discovery-insight", "prioritize-lcp-image", "lcp-breakdown-insight"]) {
5787
+ const details = audits[auditId]?.details;
5788
+ const items = Array.isArray(details?.items) ? details.items : [];
5789
+ for (const entry of items) {
5790
+ if (typeof entry.url === "string" && entry.url.trim()) return entry.url.trim();
5791
+ const nested = Array.isArray(entry.items) ? entry.items : [];
5792
+ for (const row of nested) {
5793
+ if (typeof row.url === "string" && row.url.trim()) return row.url.trim();
5794
+ }
5795
+ }
5796
+ }
5797
+ return void 0;
5798
+ }
5799
+ function findLikelyLcpResource(element, requests, audits) {
5800
+ const exactUrl = extractLcpResourceUrlFromAudits(audits);
5801
+ if (exactUrl) {
5802
+ const exactMatch = requests.find((request) => request.url === exactUrl) ?? requests.find((request) => basename2(request.url) === basename2(exactUrl));
5803
+ if (exactMatch) return projectResourceEvidence(exactMatch);
5804
+ }
5549
5805
  if (!element) return void 0;
5550
5806
  const snippet = `${element?.selector ?? ""} ${element?.description ?? ""} ${element?.textExcerpt ?? ""}`;
5551
5807
  const resource = requests.find((request) => resourceKind(request) === "image" && snippet.includes(basename2(request.url))) ?? requests.find((request) => resourceKind(request) === "font" && snippet.includes(basename2(request.url)));
@@ -5574,8 +5830,8 @@ function projectResourceEvidence(request) {
5574
5830
  ...request.transferSize === void 0 ? {} : { transferSize: request.transferSize, encodedSize: request.transferSize },
5575
5831
  ...request.status === void 0 ? {} : { status: request.status },
5576
5832
  ...start === void 0 && end === void 0 && duration === void 0 ? {} : { timingMs: { ...start === void 0 ? {} : { start }, ...end === void 0 ? {} : { end }, ...duration === void 0 ? {} : { duration } } },
5577
- cacheControl: headerValue(request.responseHeaders, "cache-control") ?? "missing",
5578
- contentEncoding: headerValue(request.responseHeaders, "content-encoding") ?? "missing"
5833
+ cacheControl: resolveHeaderStatus(request, "cache-control"),
5834
+ contentEncoding: resolveHeaderStatus(request, "content-encoding")
5579
5835
  };
5580
5836
  }
5581
5837
  function getAudits(measurement) {
@@ -5590,11 +5846,19 @@ function stringValue(value) {
5590
5846
  function numberValue(value) {
5591
5847
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
5592
5848
  }
5593
- function inferLcpBottleneck(serverResponseMs, resourceLoadDurationMs, elementRenderDelayMs) {
5594
- if (elementRenderDelayMs !== void 0 && elementRenderDelayMs > 500) return "render-delay";
5595
- if (resourceLoadDurationMs !== void 0 && resourceLoadDurationMs > 800) return "resource-discovery-load";
5596
- if (serverResponseMs !== void 0 && serverResponseMs > 600) return "server-response";
5597
- return "unknown";
5849
+ function inferLcpBottlenecks(serverResponseMs, resourceLoadDelayMs, resourceLoadDurationMs, elementRenderDelayMs) {
5850
+ const discoveryAndLoadMs = (resourceLoadDelayMs ?? 0) + (resourceLoadDurationMs ?? 0);
5851
+ const candidates = [
5852
+ ...serverResponseMs !== void 0 ? [{ kind: "server-response", ms: serverResponseMs, threshold: 600 }] : [],
5853
+ ...resourceLoadDelayMs !== void 0 || resourceLoadDurationMs !== void 0 ? [{ kind: "resource-discovery-load", ms: discoveryAndLoadMs, threshold: 800 }] : [],
5854
+ ...elementRenderDelayMs !== void 0 ? [{ kind: "render-delay", ms: elementRenderDelayMs, threshold: 500 }] : []
5855
+ ].filter((item) => item.ms > item.threshold);
5856
+ if (candidates.length === 0) return { primary: "unknown", contributing: [] };
5857
+ candidates.sort((a, b) => b.ms - a.ms);
5858
+ return {
5859
+ primary: candidates[0].kind,
5860
+ contributing: candidates.map((item) => item.kind)
5861
+ };
5598
5862
  }
5599
5863
  async function writeEvidenceBundle(outputDirectory, payload) {
5600
5864
  const evidenceDir = join9(resolve8(outputDirectory), "evidence");
@@ -5635,28 +5899,35 @@ function createEvidenceIndex(runId, graph, runtimeEvidence) {
5635
5899
  });
5636
5900
  }
5637
5901
  function selectRepresentativeMeasurement(measurements) {
5902
+ return selectRepresentativeMeasurementForMetric(measurements, "lcpMs");
5903
+ }
5904
+ function selectRepresentativeMeasurementForMetric(measurements, metric) {
5638
5905
  if (measurements.length === 0) return void 0;
5639
- const valid = measurements.filter((m) => Object.keys(m.metrics).length > 0 && (m.network.length > 0 || (m.diagnostics?.length ?? 0) > 0));
5640
- const pool = valid.length > 0 ? valid : measurements;
5906
+ const withMetric = measurements.filter((m) => Number.isFinite(m.metrics[metric]));
5907
+ const valid = (withMetric.length > 0 ? withMetric : measurements).filter(
5908
+ (m) => Object.keys(m.metrics).length > 0 && (m.network.length > 0 || (m.diagnostics?.length ?? 0) > 0)
5909
+ );
5910
+ const pool = valid.length > 0 ? valid : withMetric.length > 0 ? withMetric : measurements;
5641
5911
  const sorted = [...pool].sort((a, b) => {
5642
- const scoreA = a.metrics.lcpMs ?? a.metrics.fcpMs ?? a.metrics.speedIndexMs ?? 0;
5643
- const scoreB = b.metrics.lcpMs ?? b.metrics.fcpMs ?? b.metrics.speedIndexMs ?? 0;
5912
+ const scoreA = a.metrics[metric] ?? a.metrics.lcpMs ?? a.metrics.fcpMs ?? a.metrics.speedIndexMs ?? 0;
5913
+ const scoreB = b.metrics[metric] ?? b.metrics.lcpMs ?? b.metrics.fcpMs ?? b.metrics.speedIndexMs ?? 0;
5644
5914
  return scoreA - scoreB;
5645
5915
  });
5646
5916
  return sorted[Math.floor(sorted.length / 2)];
5647
5917
  }
5648
5918
  function createRuntimeEvidenceSummaries(issues, measurements) {
5649
- const representative = selectRepresentativeMeasurement(measurements);
5650
- if (!representative) return [];
5919
+ if (measurements.length === 0) return [];
5651
5920
  return issues.flatMap((issue) => {
5652
5921
  const metric = issue.observations[0]?.metric ?? issue.category;
5922
+ const representative = selectRepresentativeMeasurementForMetric(measurements, metric);
5923
+ if (!representative) return [];
5653
5924
  const observed = issue.observations[0]?.observedValue;
5654
5925
  const threshold = issue.observations[0]?.threshold;
5655
5926
  const evidenceId = issue.evidenceIds[0] ?? "";
5656
5927
  const requests = representative.network;
5657
5928
  const assetFacts = summarizeImportantRequests(requests);
5658
5929
  const staticFacts = summarizeStaticDelivery(requests);
5659
- const metricFact = `${metric}=${formatMs(observed)} threshold=${formatMs(threshold)}`;
5930
+ const metricFact = metric === "cls" ? `${metric}=${observed !== void 0 ? observed.toFixed(2) : "n/a"} threshold=${threshold !== void 0 ? threshold.toFixed(2) : "n/a"}` : `${metric}=${formatMs(observed)} threshold=${formatMs(threshold)}`;
5660
5931
  if (metric === "lcpMs") {
5661
5932
  return [{
5662
5933
  evidenceId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@perf-engineer/web",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Strictly read-only web performance diagnosis and task planning MCP server & installer for AI coding hosts.",
@@ -45,5 +45,6 @@
45
45
  "@modelcontextprotocol/sdk": "^1.12.1",
46
46
  "chrome-launcher": "^1.1.2",
47
47
  "lighthouse": "^12.6.0"
48
- }
48
+ },
49
+ "mcpName": "io.github.perf-engineer/perf-engineer"
49
50
  }
@@ -19,9 +19,10 @@
19
19
  - 是否因 `.browserslistrc` 过于宽泛或全量 `transpileDependencies: true` 导致打入大量 `core-js-pure` 等旧版 polyfill?
20
20
  - 是否存在重复功能库(例如同时引入 `normalize.css` + `reset.css`、或两套日期/图标库)?
21
21
 
22
- ### 1.2 `vendors` 膨胀与 `splitChunks` 精细拆包
22
+ ### 1.2 `vendors` 膨胀、路由级懒加载与 `splitChunks` 精细拆包
23
23
  - **运行时依据**:对比公共 `vendors` 包大小与首屏实际使用的字节占比。
24
- - **源码排查**:检查构建配置(`vue.config.js` / `webpack.config.*` / `vite.config.*`)的 `splitChunks` / `manualChunks`:
24
+ - **源码排查**:检查路由表与构建配置(`vue.config.js` / `webpack.config.*` / `vite.config.*`)的 `splitChunks` / `manualChunks`:
25
+ - SPA 路由表是否同步静态 `import` 了大量非首屏页面组件?应将非首屏路由改为动态 `() => import(...)` 按需加载。
25
26
  - 是否把仅局部页面或非首屏用到的重型依赖(如 `lottie-web`、`swiper`、图表库、富文本、地图、二维码等)塞进了全站共享的 `vendors.js`?
26
27
  - 建议将重型局部依赖单独拆包并配合动态 `import()` 按需加载,让每个页面只加载自己真正需要的包。
27
28
 
@@ -46,9 +47,12 @@
46
47
 
47
48
  ## 3. 图片全链路优化
48
49
 
49
- ### 3.1 首屏外大图与轮播非首帧未懒加载
50
- - **运行时依据**:调用 `perf_get_evidence("image-audit")`,查看 `offscreen-images` 与首屏图片并发请求数量/体积。
51
- - **源码排查**:检查首屏下方区块的 `<img>`、背景图及轮播图组件,确认是否开启了 `loading="lazy"` 或视口懒加载,避免非首屏图片与关键 JS/CSS 抢占并发连接。
50
+ ### 3.1 LCP 主图优先发现、首屏外懒加载与固定宽高防 CLS
51
+ - **运行时依据**:调用 `perf_get_evidence("image-audit")` 与 `perf_get_evidence("lcp-breakdown")`,查看 `lcp-discovery-insight`、`offscreen-images`、`unsized-images` 与首屏图片并发请求数量/体积。
52
+ - **源码排查**:
53
+ - **LCP 主图反向检查**:严禁给首屏 LCP 主图添加 `loading="lazy"`;优先以原生 `<img>`(而非 JS 注入或 CSS `background-image`)输出并设置 `fetchpriority="high"`,让浏览器预加载扫描器尽早发现。
54
+ - **首屏外懒加载**:检查首屏下方区块的 `<img>`、背景图及轮播非首帧,开启 `loading="lazy"` 或视口懒加载,避免与关键 JS/CSS 抢占并发连接。
55
+ - **固定尺寸防 CLS**:检查首屏及 Banner 图片是否声明了显式 `width`/`height` 或稳定 `aspect-ratio`,避免图片加载前后挤压布局。
52
56
 
53
57
  ### 3.2 CDN 图片未转 WebP 与未按展示尺寸裁剪
54
58
  - **运行时依据**:在 `image-audit` 中检查 `modern-image-formats`(是否仍是 PNG/JPG 而非 WebP/AVIF)和 `uses-responsive-images`(原图尺寸是否远大于实际渲染宽度)。
@@ -77,9 +81,12 @@
77
81
  - **运行时依据**:在 `script-and-third-party` 中检查 `third-party-summary` 与 `bootup-time`,识别统计、埋点、错误监控、APM、客服、广告等非核心业务脚本是否在首屏加载并占用主线程。
78
82
  - **源码排查**:检查入口 HTML 与 `main.js`/`App`,确认这类非核心 SDK 是否同步引入或首屏立即初始化;建议推迟到 `window.onload`(或 `requestIdleCallback`)之后动态加载与上报。
79
83
 
80
- ### 4.4 首屏元素人为延迟展示与高开销视觉特效
81
- - **运行时依据**:查看 `lcp-breakdown` 的 `elementRenderDelayMs` 与 `mainthread-work-breakdown` 的 `Style & Layout` / `Rendering` 耗时。
82
- - **源码排查**:检查首屏主视觉区域(Hero / LCP 元素)是否存在初始 `opacity: 0` + 延迟入场动画拖慢首帧可见性,或存在大面积 `filter: blur(...)` / `backdrop-filter` / 常驻无限粒子动画导致持续重绘。
84
+ ### 4.4 首屏元素延迟展示、字体阻塞、高开销特效与 SSR 数据膨胀
85
+ - **运行时依据**:查看 `lcp-breakdown` 的 `elementRenderDelayMs`、`font-display-insight`、`forced-reflow-insight` 与 `mainthread-work-breakdown` 的 `Style & Layout` / `Rendering` 耗时。
86
+ - **源码排查**:
87
+ - 检查首屏主视觉区域(Hero / LCP 元素)是否存在初始 `opacity: 0` + 延迟入场动画拖慢首帧可见性,或存在大面积 `filter: blur(...)` / `backdrop-filter` / 常驻无限粒子动画导致持续重绘。
88
+ - 检查自定义 Web 字体是否配置 `font-display: swap` / `optional`,中文字体是否过大未做子集化或 WOFF2 压缩。
89
+ - 若为 SSR/SSG 项目(Next.js / Nuxt 等),检查注入 HTML 的初始序列化数据(如 `__NEXT_DATA__` / `__INITIAL_STATE__`)是否携带了大量首屏不需要的冗余字段,拖慢 HTML 下载与客户端 Hydration。
83
90
 
84
91
  ### 4.5 纯静态展示页过度框架化(架构级参考建议)
85
92
  - 若页面属于纯文案/规则说明等几乎无交互的静态页,但首屏却承载了沉重的 SPA 框架运行时,可在报告中作为**架构建议**提出静态 HTML 化或预渲染选项(不强行发高风险重构任务)。