# html-explainer

Adopt this skill: https://proskills.md/skills/other/onemoh-html-explainer

Page: https://proskills.md/skills/other/onemoh-html-explainer
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 54354
sha: d082bc3916e849611be6e2be49a1d97f82ce2287
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/SKILL.md
truncated: true

````text
---
name: html-explainer
version: 2.0.9
description: 把任意主题做成讲解/科普视频并渲染成 MP4（HTML/CSS/GSAP 画面 + 确定性逐帧渲染 + 配音 + 词级硬字幕）。触发场景：要做科普/讲解/教学/知识/产品类视频、「讲一下 X 做成视频」、要挑某种视觉风格（极简/数据/赛博/电影感/品牌）出片、要出抖音封面/竖版封面/9:16 封面、要用 html-video 那种模板化画面但更稳的音画同步、anything2explainer 换 HTML 渲染，或提到 html-explainer / HTML 讲解视频 / explainer video / MG 视频。内置 23 个模板风格（8 类）与 40+ 动作词汇的动效库，主题驱动模板编排；支持 4K60、快门运动模糊、多进程提速、断点续渲；流程含六个用户确认点（渲染通道是硬闸门）。独立可移植，不依赖 html-video / anything2explainer。
agent_created: true
---

# html-explainer

> **定位**：`anything2explainer` 的流程与音画同步 + `html-video` 的 **23 个模板风格库**，
> 渲染层独立实现。作者 **Moh**，MIT 许可（第三方声明见 `THIRD_PARTY_NOTICES.md`）。
>
> **零外部依赖**：不需要 Remotion/npm 工程，不需要 html-video 仓库/Studio/pnpm/agent 后端。
> 技能自带：GSAP（离线）、playwright-core、渲染器、TTS/字幕/时间轴/主题/QC/封面全套脚本。
> 对两个来源项目的引用**只存在于注释署名里**，运行时不读它们的任何文件。
> 风格库是**抄下来的设计规范文本**（`references/style-catalog.md`），来源 `html-video`（Apache-2.0），
> 类比：把菜谱抄回家，之后做菜不需要原餐厅营业。

**v2.0 新增能力（全部可选、向下兼容；不用就是 v1.4 行为）**

| 能力 | 入口 | 文档 |
|---|---|---|
| **动效库**（40+ 动作词汇） | `assets/motion.js` → `window.HXM` | `references/motion-library.md` |
| **主题驱动模板编排**（挑风格 / 混用 / 动态开头） | `scripts/style_director.py` | `references/style-director.md` |
| **画质帧率档位 + 快门运动模糊 + 提速** | `scripts/render_video.mjs --profile/--quality/--fps/--shutter-only/--motion-hold` | `references/render-profiles.md` |
| **渲染基准测试**（优化前后对比） | `scripts/bench_render.py` | `references/render-profiles.md` |
| **宣传片范式**（去模板化：模板只吸纳配色/字体/时序三层） | 设计方法 | `references/showcase-mode.md` |
| **库全量演示编排**（统一舞台 + 节拍网格 + 标签常驻） | 设计方法 | `references/library-showcase.md` |
| **确认闸门**（六个确认点由用户拍板才放行） | `scripts/gate_check.py` | `SKILL.md` 流程第 3 步 |
| **★ 渲染通道确认**（渲染前必问：`png-fast` / `jpeg q95` / `png` / `jpeg q82`，**默认推荐 `png-fast`**，附速度与描述） | `consent.json` 的 `render_channel` + `gate_check.py --phase render` | `SKILL.md` 确认点 5 · `references/render-profiles.md` §0 |

把一个主题做成**原创**讲解视频：任意风格的 MG 画面（HTML/CSS/GSAP，1920×1080 或竖版）、
配音（edge-tts）、词级对齐硬字幕、全局进度条。一句话一个场景，画面节拍直接锚在
吐字时刻上（`B('块文本')` 节拍器）。

## ★ 画面风格库（23 个模板 / 8 个类别）

**不要自己从零想画面 —— 先从风格库里挑；多个风格要混用时用编排器自动挑（见下）。**
挑出候选后交用户拍板（见**确认点 0**），不许静默自选。
完整目录（含每种的画布/字体/时间轴/配色纪律）
见 **`references/style-catalog.md`**；怎么改编成合规帧见 **`references/template-guide.md`**。

**两种用法的深度不同，先分清在做哪一种**：

| 你在做 | 怎么用风格库 | 读这篇 |
|---|---|---|
| **讲解片**（默认） | 从 23 个模板里**挑一个**，按 `template-guide.md` 改编成帧 | `references/template-guide.md` |
| **宣传片 / 发布片**（去模板化） | 只从模板**吸纳配色 / 字体 / 时序骨架三层**，画面语言用 `assets/motion.js` 重写 —— **不搬模板画面** | **`references/showcase-mode.md`** |
| **要全量展示某个库**（40+ 动效 / 23 个模板） | 统一舞台 + 节拍网格 + 标签常驻，把「N 个动作」演成「一个动作语言的 N 拍」 | **`references/library-showcase.md`** |

> 判据：成片能被认出「这是 bold-signal 模板」= 吸纳过头；只能说「颜色像 xx、节奏像 yy」= 深度对了。

> **★ v2.0：不要一片只用一个模板。** 用 `scripts/style_director.py` 读解说词，
> 自动给每场挑主风格（按角色/时长/关键词打分）、按需搭次风格做**局部替换**、
> 决定**动态开头变体**与**场间转场**、并算出每场的**动效强度**。
> 详见 `references/style-director.md`。核心价值：**让模板服务于主题，而不是让主题被模板限制**。

| 类别 | 可用风格 |
|---|---|
| 演示 / 标题卡 | 大胆海报帧、大胆信号卡帧、奢华极简留白帧、创意电压分屏帧、电光工作室分屏帧、故障艺术标题帧、Kinetic Type、Swiss Grid、Warm Grain |
| 数据可视化 | NYT 风数据图表帧、数据滚动帧、NYT Graph、瑞士网格数据帧 |
| 图解 / 流程 | 东方柔和有机帧、Decision Tree |
| 氛围 / 空镜 | 胶片漏光电影帧 |
| 营销 / Hero | 流体背景 Hero 帧 |
| 片头片尾 | 品牌 Logo 收尾帧 |
| 社媒竖版 | Play Mode、Vignelli（9:16）|
| 产品演示 | Product Promo、Product Promo · 30s |
| 特效 | VFX 文字光标 |

**两类模板、两种改编成本**（速查表「类型」列）：

| 类型 | 数量 | 处理 |
|---|---|---|
| **★ rich** | 12 | 单文件 + 纯 CSS `@keyframes`。**零改动可渲染** —— 只需①换系统字体栈（删 Google Fonts）②让出底部字幕带③填真实内容 |
| **gsap** | 11 | 多 composition + CDN GSAP（或 Remotion）。**不要搬代码**，只取视觉 DNA 用 CSS keyframes 重写（搬进来会得到静止首帧且零报错，见 `lessons.md` #9）|

> 时长档要匹配内容：`frame-bold-signal` 是 3–6s 的短片花，拉长到 20s 会空。
> 长段（>10s）优先选 3–30s 档的（Swiss Grid / Kinetic Type / NYT Graph / Warm Grain）。

## 何时用 / 不用

- 用：给主题/文章/文档做讲解视频；要挑某种视觉风格出片；要 html-video 那种模板化画面但要求音画稳；要 anything2explainer 流程但不想装 Remotion。
- 不用：复刻现有视频、真人口播、实拍为主；要 Remotion/React 代码动画本体（那是 anything2explainer 的领域）。

## 环境（首台机器跑一次）

```bash
bash <skill>/setup_env.sh            # 自检；--install 联网补装
```

依赖：Python≥3.9（edge-tts==7.2.8 钉死 / numpy / pillow / imageio-ffmpeg）、Node≥18、
**火山引擎零额外依赖**（`tts_volcano.py` 只用标准库 `urllib`，不需要装任何 SDK）。
Chrome 或 Edge（几乎必有；都没有才下载 playwright chromium ~115MB）、ffmpeg（PATH 或
imageio-ffmpeg 静态二进制自动回退）。Windows 注意：项目路径全 ASCII；给 Node/Python
传 `C:/...` 正斜杠路径；别用 heredoc 给 Python 传正则。

## 命令流水线（项目目录内，顺序不能乱）

```bash
PY=<venv python 绝对路径>          # 派子 agent 时必须展开成绝对路径写进 prompt
"$PY" <skill>/scripts/new_project.py <dir> <slug> --topic "主题"   # 阶段 0 建项目
"$PY" <skill>/scripts/tts_setup.py      --project .   # ★ 先定配音方案 + 音色（问用户：edge / 火山）
"$PY" <skill>/scripts/tts_build.py      --project .   # 配音：audio/*.mp3 + manifest
"$PY" <skill>/scripts/timeline_build.py --project .   # 全局时间轴：layout.json + narration-full.mp3
"$PY" <skill>/scripts/subs.py           --project .   # 字幕：subs.json + beats.js + srt/vtt
"$PY" <skill>/scripts/check_beats_refs.py --project . # ★ 节拍引用校验：B()/Be() 是否都能解析（前缀匹配，失配秒级报出可用块）
"$PY" <skill>/scripts/style_director.py --project .   # ★ v2.0 风格编排：读解说词给每场挑主/次风格 + 开场变体 + 转场 + 动效强度 → style-plan.json
"$PY" <skill>/scripts/gate_check.py     --project .   # ★★ 确认闸门：六个确认点未由用户拍板 → 拒绝放行（缺 consent.json 用 --init 生成）
"$PY" <skill>/scripts/gate_check.py     --project . --phase render   # ★★ 渲染前必过：render_channel（渲染通道）未拍板 → 拒绝渲染
"$PY" <skill>/scripts/lint_frames.py    --project .   # 静态体检：八条契约违规（渲染前一秒出结果，比渲完再发现便宜得多）
node <skill>/scripts/check_layout.mjs   .             # ★ 几何体检：越界 / 侵入字幕带 / 元素互相遮挡（lint 看不见几何）
node <skill>/scripts/render_video.mjs   . [--audio audio/narration-full.mp3] [--profile draft|balanced|final|master] [--quality 1080p|2k|4k] [--fps 30|60] [--shutter 180] [--shutter-flush 4] [--shutter-only <场景id,场景id>] [--motion-hold 1] [--preview 30] [--keep-frames] [--only <场景id>] [--mux-only] [--png-fast|--jpeg --jpeg-quality 95] [--workers N] [--concurrency N] [--resume]   # 渲染：out/<slug>.mp4（★ 通道/档位先按确认点 5 问过用户；★ 通道与档位必须一起报——`--jpeg` 与默认快门同时用，中间帧扩展名要一路贯穿到积分器；★ 快门覆盖面也要问：全片开还是 `--shutter-only` 点名几场）
"$PY" <skill>/scripts/qc_check.py       --project .   # 体检 + 抽帧速览图
node <skill>/scripts/cover_build.mjs    .             # 封面：out/cover_169.png + cover_34.png（竖版再加 cover_916.png）
node <skill>/scripts/check_cover.mjs    .             # 封面终态几何实测：边距/钩子字号/行宽/孤字/文字重叠/9:16 禁两栏（FAIL 清零再交）
```

配音引擎（**跑之前必须先问用户**，见确认点 3）：`edge`（默认，免费免密钥）或
`volcano`（火山引擎语音合成 2.0，音质更好，需 API Key）。两者产出的 manifest 结构一致，
下游零改动。切换：`--provider edge|volcano` 或 `TTS_PROVIDER` 环境变量。
**火山密钥只存 `tts.env`（已 gitignore）—— agent 只调 `tts_volcano.py`，不读该文件。**
详见 `references/volcano-tts.md`。

### ★ 确认点 5 —— 渲染通道：**动手渲染前必须问用户选哪条，不许默认开工**

**硬规则：任何一次真正的渲染（打样 / 全片 / 局部补渲）之前，先把下表摆给用户让他挑通道。
不许凭「上次用的 png-fast」或「PNG 是默认」就静默开工。** 用户在打样阶段选定后，
同一轮的重复渲染可沿用；**换通道或换档位要重新确认一次**。

| 通道 | 参数 | 相对速度（纯 CSS 图形帧并行 / 满幅照片帧） | 画质（客观口径） | 中间帧体积（1080p · 纯图形帧实测） | 定位 |
|---|---|---|---|---|---|
| **PNG-fast** ★**默认推荐** | `--png-fast` | **×1.02 / ×4.4** | 逐像素无损（PSNR 99 dB、最大差 0） | **0.10 MB/帧**（8525 帧 ≈ **0.85 GB**） | 纯 CSS/MG 图形帧上**与 JPEG q95 同速、体积更小、还是无损** → 默认就用它 |
| **JPEG q95** | `--jpeg --jpeg-quality 95` | ×1.00 / **×13** | PSNR **41.65 dB**，低于 x264 crf18 成片自身失真 | 0.12 MB/帧 | **含满幅照片 / 重合成帧、或 4K 终稿**时的首选（照片帧上 PNG 是 582ms/帧的黑洞） |
| **PNG**（1.4.x 默认） | 不带开关 | ×1.16 / ×1.0（基准） | 逐像素无损 | 0.08 MB/帧 | 仅 `--profile legacy` 逐位复现旧成片、或 `master` 极限档 |
| **JPEG q82** | `--jpeg --jpeg-quality 82` | 最快 | 略低于 q95，仍高于多数成片编码失真 | ~0.08 MB/帧 | 只做打样/迭代预览，不用于交付 |

> **体积口径提醒**：上表体积是**纯 CSS/MG 图形帧**（大面积平色 + 文字）实测。同一批通道在
> **满幅照片 / 重合成帧**上会整体抬高一到两个数量级（精细 PNG 单帧可达 1.6–2.0 MB），
> 表格里的相对关系不变，但绝对量级不可直接套用。

**为什么默认改成 PNG-fast（2026-10-05 口径修订）**：原表把 JPEG q95 列为默认推荐，
依据是「×13 编码速度」—— 但那组倍率测的是**满幅照片帧**。本技能绝大多数片子是
**纯 CSS/MG 图形帧**，PNG 的 deflate 对平色块极其高效，本机 6 进程并行实测：

| 通道 | 吞吐 | 相对 | 体积 |
|---|---|---|---|
| JPEG q95 | 27.14 帧/秒 | ×1.00 | 0.12 MB/帧 |
| **PNG-fast** | **26.65 帧/秒** | **×1.02** | **0.10 MB/帧** |
| PNG 精细 | 23.41 帧/秒 | ×1.16 | 0.08 MB/帧 |

→ **纯图形帧上 PNG-fast 与 JPEG q95 基本同速、体积更小、且逐像素无损**，默认场景下全面占优。
而「**JPEG q95 不是降质**」这句依然成立：中间帧还要再被 x264 压一次，q95 的 PSNR 41.65 dB
低于 crf18 成片自身失真，所以它在**照片帧 / 4K 终稿**里依旧是对的默认。

**怎么问（照抄这句，四条都要列全 —— 这是硬要求）**：
> 渲染通道你要哪条？
````

## File: README.md
size: 18125
sha: 9fe9b16cd0b9afce8b583bbe47ca5d5b11786434
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/README.md

````text
<div align="center">

# html-explainer

**一个 Agent Skill：给任意主题，产出一条带配音、硬字幕、封面的讲解视频。**

**不需要视频生成模型。** 画面是 agent 现写的 HTML/CSS，确定性逐帧渲染成**真 MP4**（不是录屏）：
动效库是 `t → 数字` 的纯函数，可任意 seek；风格由主题编排；渲染支持 **4K60 · 180° 快门运动模糊 · 多进程并行**。

**全本地跑，核心链路零 API key、零按次计费。**

一条 **2 分钟的片子，全流程最快约 30 分钟**（调研 → 解说词 → 配音字幕 → 写画面 → 渲染 → 封面）。

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Version](https://img.shields.io/badge/version-2.0.9-blue.svg)](CHANGELOG.md)
[![Stars](https://img.shields.io/github/stars/OneMoh/html-explainer?style=flat&logo=github)](https://github.com/OneMoh/html-explainer/stargazers)
[![Agent Skill](https://img.shields.io/badge/Agent%20Skill-SKILL.md-8A2BE2.svg)](SKILL.md)
[![Claude Code](https://img.shields.io/badge/Claude%20Code-%E2%9C%93-D97757.svg)](#安装)
[![Codex](https://img.shields.io/badge/Codex-%E2%9C%93-000000.svg)](#安装)
[![WorkBuddy](https://img.shields.io/badge/WorkBuddy-%E2%9C%93-1f6feb.svg)](#安装)
[![Python](https://img.shields.io/badge/Python-3.9%2B-3776AB.svg?logo=python&logoColor=white)](#环境要求)
[![Node](https://img.shields.io/badge/Node-18%2B-339933.svg?logo=node.js&logoColor=white)](#环境要求)

[简体中文](README.md) · [English](README.en.md)

<br/>

两条用本技能生成的成片——画面、配音、字幕、封面全部由流水线产出，无手工后期。
封面等素材托管在[演示仓库](https://github.com/OneMoh/html-explainer-demos)，本仓库零体积。

| 港股创新药 · 早盘 | 量化简史 |
|---|---|
| https://github.com/user-attachments/assets/8007843c-088d-457c-8550-81ec912e0add | https://github.com/user-attachments/assets/28949988-449b-4c4e-8d0f-6706af6f64ee |

</div>

---

## 它是什么

`html-explainer` 把一个主题做成**带配音、带硬字幕、带进度条**的讲解视频，画面用
HTML/CSS/GSAP 写。

它**是一个 Agent Skill**（`SKILL.md` + `scripts/` + `references/`），遵循
[Agent Skills](https://code.claude.com/docs/en/skills) 约定，Claude Code / OpenAI Codex /
WorkBuddy / Cursor / Gemini CLI 等都能直接加载。内部是普通的 Python 与 Node 脚本，
手工跑也完全没问题。

你只需要说一句：

> 把「为什么天空是蓝色的」做成一条 1 分钟的讲解视频。

技能会带着智能体走完：调研 → 解说词 → 配音 → 字幕与节拍 → **编排风格并写画面** → 渲染 → 体检 → 封面。

**与「文生视频」模型的区别**：那条路线要模型把画面像素生成出来，代价是算力、按次计费、
以及不可复现的文字（画面上的中文经常是糊的）。这里要模型**写代码**，像素由浏览器画 ——
所以文字永远清晰、同一帧永远长一样，画面是一份可读的文件，能改也能 diff。

## 30 分钟是怎么来的

一条 2 分钟的片子约 3600 帧（1080p30）。最快档的典型耗时：

| 阶段 | 约 | 说明 |
|---|---|---|
| 调研 + 解说词 | 14 分钟 | 每个数字带出处；解说词按 `\|` 切成字幕块 |
| 配音 + 字幕 + 时间轴 | 2 分钟 | edge-tts 免费免密钥；词级时间戳直接出硬字幕 |
| 写画面 | 8 分钟 | 从 23 个风格里挑、用动效库拼；一句一场景 |
| 渲染 | 4 分钟 | 1080p30 实测 **16.4 帧/秒**，3600 帧 ≈ 3.7 分钟 |
| 封面 + 体检 | 2 分钟 | 16:9 与 3:4 各排一次版，几何实测把关 |

> 量级参考，不是承诺：真正吃时间的是「调研深度」和「画面迭代次数」。渲染这一环很便宜 ——
> 一条 5982 帧的真实片子端到端 7 分 49 秒，**换 4K60 才是数倍代价**（见[渲染实测](DESIGN.md#渲染性能实测)）。

---

## 安装

### 一句话安装（推荐）

把下面这句发给你的智能体：

```text
给当前本地环境安装该 Skill：https://github.com/OneMoh/html-explainer.git
安装到你的技能目录，并检测安装必要的运行环境（Python 3.9+ / Node 18+ / Chrome 或 Edge / ffmpeg）
```

它会自己 clone 到对应目录、跑环境自检、把缺的东西装上。装完**新开一个会话**，让智能体重新
扫描技能目录。

### 手动安装

仓库根目录**就是**技能目录（`SKILL.md` 在根），直接 clone 进技能目录即可，不用再拷子目录：

```bash
git clone https://github.com/OneMoh/html-explainer.git ~/.workbuddy/skills/html-explainer
bash ~/.workbuddy/skills/html-explainer/setup_env.sh --install
```

Windows 上 `~` 就是 `C:\Users\<你的用户名>`。

> **Windows 注意**：上面的 `bash` 指 **Git Bash**（装了 Git for Windows 就有），PowerShell / cmd
> 里直接跑 `bash setup_env.sh --install` 会找不到命令 —— 用 `& "C:\Program Files\Git\bin\bash.exe" setup_env.sh --install`，
> 或先开一个 Git Bash 窗口。
> 另外，不少宿主会在技能目录名后加命名空间后缀（例如 WorkBuddy 装出来的是
> `~/.workbuddy/skills/html-explainer__skillhub`），照实际目录改路径即可，技能本身不认名字。
> 项目路径请保持**全 ASCII** —— Windows 的 ffmpeg 把 UTF-8 当 ANSI 读，中文路径会在渲染阶段炸。

### 环境要求

| 项 | 最低 | 说明 |
|---|---|---|
| Python | 3.9+ | `edge-tts==7.2.8`（刻意钉死）、`numpy`、`pillow`、`imageio-ffmpeg`；火山引擎**零额外依赖**（只用标准库 `urllib`） |
| Node.js | 18+ | 渲染器与封面器用 |
| 浏览器 | Chrome 或 Edge | 自动探测；都没有才下载 playwright chromium（约 115MB，只需一次） |
| ffmpeg | 任意版本 | 先在 `PATH` 找；没有则用 `imageio-ffmpeg` 自带的静态二进制 |
| 磁盘 | 每条成片约 2GB | 帧 PNG 体积大，合成后可删 |

`bash setup_env.sh` 只检查并报告缺什么，`--install` 才会装。全程不需要管理员权限。
**没有 GPU 要求，没有模型权重要下载** —— 依赖就是上面这几样。

---

## 核心特性

| | |
|---|---|
| **不需要视频模型** | 画面是 HTML/CSS/GSAP，浏览器逐帧渲染。零 API key、零按次计费、可离线 |
| **节拍锚定解说词** | 动画按**字幕文本**定位（`B('块文本')`），不硬编码帧号。改解说词，全片自动重排，画面代码零改动 |
| **词边界字幕** | 时序来自 TTS 的**字级时间戳**，不按字数插值 —— 中文里同字数的短语时长能差 3 倍 |
| **两个配音引擎** | `edge-tts`（免费免密钥，默认）或**火山引擎语音合成 2.0**（音质更好）。manifest 结构一致，下游零改动 |
| **23 种画面风格** | 8 个类别，每种都记录了画布、字阶、时间轴与配色纪律。不用对着空白页从零设计 |
| **动效库（40+ 动作词汇）** | `assets/motion.js`：入场 / 承接 / 接触 / 运镜 / 环境五组，全是「`t` → 一组数字」的纯函数，天生可 seek |
| **主题驱动模板编排** | `style_director.py` 读解说词推断每场角色，挑主风格 + 搭次风格 + 决定开场与转场。**不是「一片一模板」** |
| **4K60 + 快门运动模糊** | `--profile` 四档；快门在**线性光下做多样本积分**（不是 blur 滤镜）；`--workers N` 多进程并行、`--resume` 断点续渲 |
| **多画幅封面** | 16:9 与**独立重排**的 3:4（不是裁切 —— 裁切会丢掉 57.8% 的画面宽度），竖版再加 9:16 |
| **三道渲染前体检** | `check_beats_refs.py`（`B()` 能否解析）、`lint_frames.py`（八条契约）、`check_layout.mjs`（越界 / 侵入字幕带 / 遮挡） |
| **结构性离线** | GSAP 内置；浏览器自动探测；ffmpeg 缺失回退静态二进制；网络字体被契约禁止 |

> 原理（为什么不用录屏、动效库怎么设计、封面怎么重排）单独成篇 → [**DESIGN.md**](DESIGN.md)。

---

## 流水线

```mermaid
flowchart LR
    A["主题"] --> B["调研<br/><i>每个数字带出处</i>"]
    B -->     C["narration.json<br/><i>竖线切字幕块</i>"]
    C --> S["tts_setup.py<br/><i>问 TTS 方案 · 配密钥 · 选音色</i>"]
    S --> D["tts_build.py<br/><i>edge-tts / 火山引擎 → MP3 + 词边界</i>"]
    D --> E["timeline_build.py<br/><i>全局轴 + 拼接音轨</i>"]
    E --> F["subs.py<br/><i>subs.json · srt/vtt · beats.js</i>"]
    F --> CB["check_beats_refs.py<br/><i>B()/Be() 能否解析</i>"]
    CB --> SD["style_director.py<br/><i>读解说词挑风格 → style-plan.json</i>"]
    SD --> G["frames/*.html<br/><i>一句一场景 · 动效库 HXM</i>"]
    G --> H{"lint_frames.py<br/>八条契约"}
    H -->|不过| G
    H -->|通过| CL["check_layout.mjs<br/><i>几何：越界 · 侵入字幕带 · 遮挡</i>"]
    CL --> GC{"gate_check.py<br/>通道已由用户拍板？"}
    GC -->|未定| Q["问用户选通道"]
    Q --> GC
    GC -->|已定| I["render_video.mjs<br/><i>逐帧 seek → png-fast / jpeg</i>"]
    I --> J["ffmpeg<br/><i>H.264 + AAC 合成</i>"]
    J --> K[("out/slug.mp4")]
    I --> L["qc_check.py<br/><i>响度 · 漂移 · 抽帧速览</i>"]
    K --> M["cover_build.mjs<br/><i>cover_169.png · cover_34.png · cover_916.png</i>"]
    M --> N["check_cover.mjs<br/><i>终态几何实测</i>"]

    style K fill:#1f6feb,color:#fff
    style H fill:#8957e5,color:#fff
    style CL fill:#8957e5,color:#fff
    style GC fill:#8957e5,color:#fff
    style SD fill:#bf8700,color:#fff
    style CB fill:#6e7781,color:#fff
    style M fill:#238636,color:#fff
    style N fill:#238636,color:#fff
```

完整命令序列（含每个脚本的参数）见 [`SKILL.md`](SKILL.md) 的「命令流水线」。

---

## 两个要你拍板的决定

智能体不会替你选这两件事 —— 选择被写进 `consent.json`，`gate_check.py` 挡在渲染之前。

### 1. 配音引擎

| | `edge-tts` | 火山引擎语音合成 2.0 |
|---|---|---|
| 你要做什么 | 什么都不用做 | 填一次 API Key |
| 费用 | 免费 | 按字符计费 |
| 音色 | 内置中英文若干 | 豆包 2.0 音色库，含声音复刻 |
| 额外依赖 | `edge-tts==7.2.8`、`imageio-ffmpeg` | **零** —— 只用标准库 `urllib` |
| 什么时候选它 | 默认。开箱可用、够用 | 想要更自然的语气与更好音质 |

选火山时，技能会生成 `tts.env` 并**停下来**让你把 Key 填进去 —— 这一步刻意不经过对话窗口：
密钥不发给智能体、不进对话、不进仓库、不进日志。音色清单与密钥纪律的完整说明见
[`DESIGN.md`](DESIGN.md#配音细节)。

### 2. 渲染档位与中间帧通道

```bash
node <skill>/scripts/render_video.mjs . --list-profiles   # 看全部档位
```

| 档位 | 画质 | 帧率 | 快门 | 中间帧 | 用途 |
|---|---|---|---|---|---|
| `draft` | 1080p | 30 | 关 | `png-fast` | 打样 / 迭代，最快 |
| `balanced` | 1080p | 30 | 180° | `png-fast` | **默认推荐**（质量/速度平衡） |
| `final` | 4K | 60 | 180° | `png-fast` | 终稿（工作量约 1080p30 的 8–12×） |
| `master` | 4K | 60 | 180° | 精细 PNG | 极限画质（很慢） |
| `legacy` | 1080p | 项目 fps | 关 | 精细 PNG | 逐位复现 v1.4.x 旧成片 |

中间帧通道四条，**渲染前必须问你选哪条**：

| 通道 | 定位 |
|---|---|
| **`--png-fast`** ★默认 | 逐像素无损；纯 CSS/MG 图形帧上与 JPEG q95 同速、体积更小 |
| `--jpeg --jpeg-quality 95` | **含满幅照片 / 4K 终稿**时首选（照片帧上精细 PNG 是 582ms/帧的黑洞） |
| `--png` | 只有 `legacy` 复现 / `master` 极限档用 |
| `--jpeg --jpeg-quality 82` | 只做打样预览 |

档位只改 `deviceScaleFactor`，**布局逐像素不变**。速度实测、快门积分原理与完整参数见
[`references/render-profiles.md`](references/render-profiles.md)。

---

## 视频项目结构

产物落在 `out/`：`slug.mp4`、`cover_169.png`、`cover_34.png`、`slug.srt`、`slug.vtt`，
外加 `qc_report.md` 与 `qc_sheet.jpg`；做竖版投放时再加一张 `cover_916.png`。

```
my-video/
├── project.json      # slug、fps、尺寸、音色、语速、场景顺序、章节
├── narration.json    # [{ id, text }] —— 用 "|" 切字幕块
├── theme.css         # 所有颜色，以 CSS 变量形式
├── style-plan.json   # 每场的主/次风格、角色、转场、动效强度（编排器产出）
├── consent.json      # 六个确认点（含渲染通道）由用户拍板才放行
├── frames/           # 一个场景一个 HTML；<id>.beats.js 自动生成，绝不手改
├── audio/  render/  research/  script/
└── out/              # MP4、封面、SRT/VTT、QC 报告
```

---

## 疑难排查

| 症状 | 原因 | 处理 |
|---|---|---|
| 每一帧都是静止首帧，且不报错 | 时间轴没注册到 `window.__tl`；或 `page.evaluate` 传了**字符串**而非函数字面量（Playwright 只求值一次，函数体根本不执行） | 传真正的函数字面量 |
| 视频变成 1280×720 | `viewport` 传给了 `browser.launch()` —— 它是 *context* 级选项 | 传给 `newPage()` |
| 封面出成 1 倍图 | 同上，`deviceScaleFactor` 的孪生坑 | 传 `newPage()` + `screenshot({ scale: 'device' })` |
| 数字能渲染但永远不动 | seek 抑制了 `onUpdate` 回调 | 渲染器已修（`pause(t, false)`）；帧里改用 transform 数字卷轴 |
| `--jpeg` 通道下 ffmpeg 首帧即崩（`unsupported coding type`） | 「hold 帧」被写成「后缀 `.jpg`、内容 PNG」的脏帧 | 升级到 v2.0.4 或更高（该版本已修） |
| Windows 上 `No such file or directory` | 非 ASCII 路径 —— Windows 的 ffmpeg 把 UTF-8 当 ANSI 读 | 路径保持 ASCII |
| 字幕开始飘 / 位置对不上 | TTS 没返回字级时间戳，`subs.py` 退回**按字数插值** | 看 `tts_build` 有没有打 `⚠ 未返回字级时间戳`；换个受支持的音色（中英文 2.0） |
| 火山报 `resource ID is mismatched with speaker related resource` | `speaker` 收到了中文显示名而不是音色 ID；或复刻音色配了预置资源 ID | 音色用内置名/ID（接口包会解析）；复刻音色配 `VOLC_RESOURCE_ID=seed-icl-2.0` |
| 火山报 `HTTP 401/403` | `tts.env` 里的 key 不对，或该服务未开通 | 核对 `VOLC_API_KEY`；`tts_setup.py --status` 看脱敏状态 |
| 火山报 `网络不可达` | 本包默认**绕过系统代理直连**（境内端点） | 确实需要代理时设 `VOLC_PROXY=http://127.0.0.1:<port>` |
| 重跑后字幕整体晚一帧 | 命中缓存时丢掉了首裁量（历史 bug，已修） | 升级到 v1.3.0+；缓存格式已带 `lead_cut_sec` |

**先读 [`references/lessons.md`](references/lessons.md) 再 debug。** 133 条编号记录，每一条都是
「成片看着挺正常、其实是错的」的 bug —— 包括它一开始是怎么被误判的。

---

## 深入阅读

| 想看什么 | 去哪里 |
|---|---|
| **原理**：为什么不用录屏、seek 怎么保证逐像素一致 | [`DESIGN.md`](DESIGN.md#渲染原理为什么不用录屏) |
| **`B()` 节拍系统**：为什么改一句词不用重新对位 | [`DESIGN.md`](DESIGN.md#b-节拍系统) |
| **23 个风格**的画布 / 字阶 / 时间轴规范 | [`references/style-catalog.md`](references/style-catalog.md) |
| **动效库** 40+ 动作词汇与分层设计 | [`DESIGN.md`](DESIGN.md#动效库) · [`references/motion-library.md`](references/motion-library.md) |
| **模板编排**怎么挑风格、怎么混用 | [`references/style-director.md`](references/style-director.md) |
| **封面**三画幅的重排规则与自检清单 | [`DESIGN.md`](DESIGN.md#封面多画幅) · [`references/cover-guide.md`](references/cover-guide.md) |
| **渲染**档位、快门积分、性能实测 | [`DESIGN.md`](DESIGN.md#渲染性能实测) · [`references/render-profiles.md`](references/render-profiles.md) |
| 完整命令序列与确认点 | [`SKILL.md`](SKILL.md) |
| 踩过的坑（133 条） | [`references/lessons.md`](references/lessons.md) |
| 版本变更 | [`CHANGELOG.md`](CHANGELOG.md) |

---

## 适合谁

**适合**：想成规模地把文章 / 文档 / 某个主题做成带解说的视频；已经在用 AI 编程智能体，
且宁愿用 HTML 描述画面也不想学动效软件；需要可复现的输出；需要离线跑或拒绝按次计费。

**不适合**：实拍剪辑、真人口播、复刻已有视频；想要图形化拖拽编辑器（画面是代码，这是刻意
选择）；想用文生视频模型「一句话出片」（本项目要模型写代码，不生成像素）。

---

## 参与贡献

欢迎提 issue 和 PR。最有价值的贡献，是一条**已被定位的静默失败**，加进
`references/lessons.md` —— 写下它一开始是怎么误导你的、证明病因的证据、修法，以及由此得出的
通用规则。请先读 [`CONTRIBUTING.md`](CONTRIBUTING.md)。

## 许可与致谢

[MIT](LICENSE) © 2026 Moh

MIT 覆盖原创代码与文档。第三方组件与衍生出的风格规范仍适用其各自的条款；GSAP 按 GreenSock
的 [standard "no charge" 许可](https://gsap.com/standard-license) 内置。本项目的方法论有两处
明确的思想来源（`anything2explainer` 与 `html-video`），**不打包、运行时不依赖它们的任何代码** ——
完整的署名与逐风格对应关系见 [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md)，
叙事版见 [`DESIGN.md`](DESIGN.md#思想来源)。

---

## Star 曲线

<a href="https://star-history.com/#OneMoh/html-explainer&Date">
  <img src="https://api.star-history.com/svg?repos=OneMoh/html-explainer&type=Date" alt="Star History Chart" width="720">
</a>

---

<div align="center">

如果这个项目对你有帮助，欢迎请作者喝杯咖啡 ☕

<img src="https://raw.githubusercontent.com/OneMoh/html-explainer-demos/main/images/wechat-reward-qr.jpg" width="340" alt="Moh 的赞赏码">

</div>
````

## File: tests/geometry-fixture/README.md
size: 1673
sha: 0d46a31b4a099fe78c7bd385e7017519bd1c6f33
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/tests/geometry-fixture/README.md

````text
# 几何体检的证伪样本（geometry-fixture）

**用途**：验证 `scripts/check_layout.mjs` 真的能抓到错 —— 不是「跑通了」，是「抓得准」。

一个检查类工具拿合格项目跑出「0 ERROR」是**待证实**，不是**通过**：
第一版 `check_layout.mjs` 就在真实项目上报 0 ERROR，其实重叠检查因为传错参数
（`inter(a, b)` 而不是 `inter(a.r, b.r)`，`a.rr` 恒为 `undefined`）**从来没运行过**
（见 `references/lessons.md` #76）。

## 怎么用

```bash
node ../scripts/check_layout.mjs .       # 站在本目录，或在技能根传路径
```

**期望输出：ERROR 2 · WARN 0 · INFO 1**，逐条对应 issue #1 里用户报的三类症状：

| 期望条目 | 对应症状 |
|---|---|
| `侵入字幕禁区` — `.intrude` 底边 y=1040，侵入 130px | 内容压进字幕带 |
| `文字被遮挡` — `.axis`「700nm · 红光450nm · 蓝光」被 `.evidence` 盖住 | issue #1 的「遮挡」 |
| `疑似未对齐` — `.dot` 中心距 SVG 内容中心 63px | issue #1 的「元素错位」 |

数字（130px / 63px）是刻意留的余量，不是精确到像素的断言 —— 校验时看**级别和条目**
是否齐，别把具体像素当回归基线。

## 改动这个样本时注意

`frames/broken.html` 里的三处「坏」是**故意**的，不是待修的 bug：

- `.chart` 容器高度只算柱区、`.axis` 溢出到容器外 → 被 `.evidence` 压住；
- `.intrude` 钉在 `bottom:40px`；
- `.dot` 是 HTML 绝对定位、与 SVG 内画的射线**不共坐标系**。

把任一处「修好」都会让对应条目消失 —— 那正是这个文件存在的意义。
````

## File: scripts/bench_render.py
size: 14508
sha: be6a6ba1c07a04fcdc9151862e3dee4be9ba6482
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/bench_render.py

```text
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""bench_render.py —— 渲染管线基准测试工装。

【为什么要它】
「优化了多少」不能靠感觉。这个脚本先合成一个**复杂度可控**的项目（N 场 × M 个动元素），
然后在同一台机器上用不同档位各渲一遍，把「截图耗时 / 帧率 / 成片体积」拉成一张表。
优化前（--profile legacy = 1.4.x 行为）与优化后（draft/balanced/final）就在同一张表里。

【合成项目长什么样】
  每场一帧 HTML，含：GSAP 时间轴（平移+旋转+缩放）、CSS @keyframes、逐帧 onUpdate 计数器、
  一个 window.__motion(t0,t1)（告诉渲染器快门开合期间屏幕最远移动了多少 px）。
  --heavy 打开「满幅渐变 + 多重 shadow + 半透明叠加」，用于模拟高熵帧（照片/复杂合成），
  这是 PNG 截图最慢的场景 —— 也是 --png-fast / --jpeg 收益最大的场景。

【怎么读结果】
  fps  = 渲染帧数 / 截图耗时（不含编码、不含积分）
  相对 legacy 的加速比才是重点；绝对值随机器和帧内容变化很大。

用法：
  python scripts/bench_render.py --out .scratch/bench [--scenes 6] [--sec 2.0]
      [--configs legacy,draft,balanced,shutter,4k30,4k60] [--preview 4]
      [--heavy] [--json]
"""
from __future__ import annotations

import argparse
import json
import os
import shutil
import subprocess
import sys
import time

SKILL_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
HERE = os.path.dirname(os.path.abspath(__file__))

def node_exe():
    if os.environ.get("NODE_BIN"):
        return os.environ["NODE_BIN"]
    home = os.environ.get("USERPROFILE") or os.environ.get("HOME") or ""
    cands = []
    if home:
        base = os.path.join(home, ".workbuddy", "binaries", "node", "versions")
        if os.path.isdir(base):
            for d in sorted(os.listdir(base), reverse=True):
                p = os.path.join(base, d, "node.exe" if os.name == "nt" else "bin/node")
                if os.path.exists(p):
                    cands.append(p)
    return (cands + ["node"])[0]

FRAME = """<!DOCTYPE html>
<html lang="zh"><head><meta charset="utf-8">
<style>
  html,body{{margin:0;padding:0;overflow:hidden;background:#0b0b12;
    font-family:'Microsoft YaHei','PingFang SC',sans-serif;}}
  .stage{{position:absolute;inset:0;{bg}}}
  .card{{position:absolute;left:120px;top:180px;width:1200px;color:#fff;
    {cardextra}}}
  h1{{font-size:96px;margin:0 0 20px;letter-spacing:-2px;}}
  .sub{{font-size:34px;opacity:.82;}}
  .bars{{position:absolute;left:120px;bottom:200px;display:flex;gap:18px;align-items:flex-end;}}
  .bar{{width:{barw}px;background:linear-gradient(180deg,#ff5f6d,#ffc371);border-radius:6px;}}
  .num{{position:absolute;right:140px;top:150px;font-size:220px;font-weight:800;
    color:rgba(255,255,255,.92);}}
  @keyframes spinpulse {{ from{{transform:rotate(0) scale(1)}} to{{transform:rotate(360deg) scale(1.06)}} }}
  .orb{{position:absolute;right:320px;bottom:300px;width:200px;height:200px;border-radius:50%;
    background:radial-gradient(circle at 35% 30%,#a78bfa,#4c1d95);
    animation:spinpulse {orbs} linear infinite;{orbextra}}}
</style></head>
<body>
<div class="stage"></div>
<div class="card"><h1 id="t">场景 {i}</h1><div class="sub">deterministic frame · bench</div></div>
<div class="num" id="num">0</div>
<div class="orb"></div>
<div class="bars">{bars}</div>
<script src="../assets/gsap.min.js"></script>
<script>
  var tl = gsap.timeline({{ paused: true }});
  tl.to('#t', {{ x: {dx}, rotation: {rot}, scale: 1.18, duration: {dur}, ease: 'power2.inOut' }}, 0);
  tl.from('.bar', {{ scaleY: 0, transformOrigin: 'bottom', stagger: 0.08, duration: {dur0} }}, 0);
  tl.to('.orb', {{ x: -{dx2}, y: -80, duration: {dur} }}, 0);
  var numEl = document.getElementById('num');
  var obj = {{ v: 0 }};
  // onUpdate 写 DOM：这是 seek(t, false) 那个坑的现场 —— 若渲染器掐掉回调，数字会永远停在 0
  tl.to(obj, {{ v: {numv}, duration: {dur}, ease: 'none',
      onUpdate: function () {{ numEl.textContent = Math.round(obj.v); }} }}, 0);
  window.__tl = tl;
  // 快门自适应采样用：报告 t0..t1 之间屏幕最远位移（px）
  window.__motion = function (t0, t1) {{
    var d = Math.min(1, Math.abs(t1 - t0) / {dur});
    return {motion} * d;
  }};
  window.__SEG__ = {{ id: 's{i}', duration: {dur}, speech_end: {dur0}, tail: 0 }};
</script>
</body></html>
"""

def make_project(out, n_scenes, sec, heavy, fps, w, h):
    # ★ 不删除已有目录：沙箱/OS 对「批量删除」有保护，而且删掉上一次的基准数据也没好处。
    #   目录已存在且非空时，自动加 -2 / -3 … 后缀，每次都留一份可比对的现场。
    base = out
    k = 1
    while os.path.isdir(out) and os.listdir(out):
        if not os.path.exists(os.path.join(out, "project.json")):
            break            # 是别人的目录，别往里写
        k += 1
        out = f"{base}-{k}"
    for d in ("frames", "assets", "audio", "render", "out", "script"):
        os.makedirs(os.path.join(out, d), exist_ok=True)
    # 只清掉本次要重写的两类产物（逐文件删，不做递归批量删除）
    for sub in ("render/frames", "render/shutter", "out"):
        p = os.path.join(out, sub)
        if os.path.isdir(p):
            for name in os.listdir(p):
                q = os.path.join(p, name)
                try:
                    if os.path.isfile(q):
                        os.remove(q)
                    elif os.path.isdir(q):
                        shutil.rmtree(q, ignore_errors=True)
                except OSError:
                    pass
    shutil.copy(os.path.join(SKILL_ROOT, "assets", "gsap.min.js"),
                os.path.join(out, "assets", "gsap.min.js"))

    dur0 = max(0.5, sec * 0.55)
    layout = {"_total": {"total_frames": int(round(sec * n_scenes * fps))}}
    subs = {"fps": fps, "segments": []}
    order = []
    for i in range(1, n_scenes + 1):
        sid = f"s{i}"
        order.append(sid)
        h1 = {
            "bg": ("background:linear-gradient(135deg,#1e1b4b,#4c1d95 40%,#be123c);"
                   if i % 2 else "background:linear-gradient(135deg,#052e16,#065f46 45%,#0e7490);"),
            "cardextra": "text-shadow:0 12px 40px rgba(0,0,0,.55);" if heavy else "",
            "orbextra": "box-shadow:0 0 120px 40px rgba(167,139,250,.45);" if heavy else "",
            "barw": 70 + (i * 7) % 40,
            "bars": "".join(f'<div class="bar" style="height:{120 + ((i*53 + k*97) % 420)}px"></div>'
                            for k in range(5 if heavy else 3)),
            "i": i,
            "dx": 380 + i * 12,
            "dx2": 220 + i * 9,
            "rot": 8 + i,
            "dur": sec,
            "dur0": sec * 0.8,
            "numv": 1200 + i * 137,
            "motion": 300 + i * 20,
            "orbs": f"{sec * 0.6:.2f}s",
        }
        open(os.path.join(out, "frames", f"{sid}.html"), "w", encoding="utf-8", newline="\n"
             ).write(FRAME.format(**h1))
        layout[sid] = {"duration_sec": sec}
        subs["segments"].append({"id": sid, "blocks": [
            {"from": int(0.15 * fps), "to": int(0.55 * fps * sec / 2), "text": f"第{i}场的第一个字幕块"},
            {"from": int(0.6 * fps * sec / 2), "to": int(0.9 * fps * sec), "text": "第二个块"},
        ]})
    json.dump({"slug": "bench", "lang": "zh", "fps": fps, "width": w, "height": h,
               "gap": 0.0, "order": order, "progress": True},
              open(os.path.join(out, "project.json"), "w", encoding="utf-8"),
              ensure_ascii=False, indent=2)
    json.dump(layout, open(os.path.join(out, "layout.json"), "w", encoding="utf-8"),
              ensure_ascii=False, indent=1)
    json.dump(subs, open(os.path.join(out, "subs.json"), "w", encoding="utf-8"),
              ensure_ascii=False, indent=1)
    return out, n_scenes * sec

CONFIGS = {
    "legacy":   ["--profile", "legacy"],
    "draft":    ["--profile", "draft"],
    "balanced": ["--profile", "balanced"],
    "shutter":  ["--profile", "balanced", "--shutter", "180"],
    "4k30":     ["--quality", "4k", "--fps", "30", "--shutter", "180", "--workers", "8"],
    "4k60":     ["--quality", "4k", "--fps", "60", "--shutter", "180", "--workers", "8"],
    "master":   ["--profile", "master"],
}

def run_cfg(out, name, extra, preview, keep_frames, total_sec, quiet=True):
    node = node_exe()
    cmd = [node, os.path.join(HERE, "render_video.mjs"), out] + extra
    if preview:
        cmd += ["--preview", str(preview)]
    if keep_frames:
        cmd += ["--keep-frames"]
    cmd += ["--out", os.path.join("out", f"{name}.mp4")]

    # ★ 档位若覆盖了 fps，声明的总帧数（layout._total.total_frames）也得跟着变。
    #   渲染器**采信声明帧数**（这是有意的：避免帧数分歧导致 QC 假截断），所以只改 --fps
    #   而不改声明值，会让 4k60 这种档位按旧 fps 的帧数渲染 —— 时长少一半，基准就不可比了。
    layout_p = os.path.join(out, "layout.json")
    orig_layout = open(layout_p, encoding="utf-8").read() if os.path.exists(layout_p) else None
    eff_fps = None
    if "--fps" in extra:
        try:
            eff_fps = float(extra[extra.index("--fps") + 1])
        except (ValueError, IndexError):
            eff_fps = None
    try:
        if eff_fps and orig_layout is not None and not preview:
            lay = json.loads(orig_layout)
            lay.setdefault("_total", {})["total_frames"] = int(round(total_sec * eff_fps))
            json.dump(lay, open(layout_p, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
        t0 = time.time()
        r = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace")
        wall = time.time() - t0
    finally:
        if orig_layout is not None:
            open(layout_p, "w", encoding="utf-8").write(orig_layout)

    meta_p = os.path.join(out, "out", f"{name}.render.json")
    meta = json.load(open(meta_p, encoding="utf-8")) if os.path.exists(meta_p) else None
    mp4 = os.path.join(out, "out", f"{name}.mp4")
    size = os.path.getsize(mp4) if os.path.exists(mp4) else None
    return {
        "config": name, "ok": r.returncode == 0, "wall_sec": round(wall, 2),
        "capture_sec": (meta or {}).get("seconds", {}).get("capture"),
        "integrate_sec": (meta or {}).get("seconds", {}).get("integrate"),
        "frames": (meta or {}).get("frames"),
        "size_mb": round(size / 1048576, 2) if size else None,
        "size": (meta or {}).get("size"), "fps_out": (meta or {}).get("fps"),
        "shot_mode": (meta or {}).get("shot_mode"), "parallel": (meta or {}).get("parallel"),
        "workers": (meta or {}).get("workers"), "shutter": (meta or {}).get("shutter"),
        "still_frames": (meta or {}).get("still_frames"),
        "log_tail": r.stderr.strip().splitlines()[-3:] if r.returncode else [],
    }

def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default=".scratch/bench")
    ap.add_argument("--scenes", type=int, default=6)
    ap.add_argument("--sec", type=float, default=2.0)
    ap.add_argument("--fps", type=int, default=30)
    ap.add_argument("--width", type=int, default=1920)
    ap.add_argument("--height", type=int, default=1080)
    ap.add_argument("--preview", type=float, default=0.0, help="只渲前 N 秒（0=全片）")
    ap.add_argument("--configs", default="legacy,draft,balanced,shutter")
    ap.add_argument("--heavy", action="store_true")
    ap.add_argument("--keep-frames", action="store_true")
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args()

    out = os.path.abspath(a.out)
    out, total = make_project(out, a.scenes, a.sec, a.heavy, a.fps, a.width, a.height)
    names = [c.strip() for c in a.configs.split(",") if c.strip()]
    print(f"合成项目：{out}")
    print(f"  {a.scenes} 场 × {a.sec}s @{a.fps}fps = {total:.1f}s"
          f"{' · heavy（高熵帧）' if a.heavy else ''}"
          f"{f' · 只渲前 {a.preview}s' if a.preview else ''}\n")

    results = []
    base_fps = None
    for n in names:
        if n not in CONFIGS:
            print(f"⚠ 未知档位 {n}（可选 {', '.join(CONFIGS)}）")
            continue
        print(f"▶ {n:9} {' '.join(CONFIGS[n])}")
        r = run_cfg(out, n, CONFIGS[n], a.preview, a.keep_frames, total)
        results.append(r)
        if not r["ok"]:
            print(f"  ✗ 失败：{r['log_tail']}")
            continue
        cap = r["capture_sec"] or 0
        fpsr = (r["frames"] / cap) if (cap and r["frames"]) else 0
        if n == "legacy":
            base_fps = fpsr
        tag = ""
        if base_fps and fpsr:
            tag = f"  ×{fpsr / base_fps:.2f} vs legacy"
        print(f"  ✓ {r['frames'] if r['frames'] is not None else '?'} 帧 · 截图 {cap}s"
              f" · 积分 {r['integrate_sec']}s · 总 {r['wall_sec']}s · {fpsr:.1f} 帧/秒{tag}"
              f" · 成片 {r['size_mb']}MB")

    print("\n" + "=" * 104)
    print(f"{'档位':10} {'输出':11} {'fps':>4} {'帧数':>6} {'截图s':>7} {'积分s':>6} "
          f"{'总s':>7} {'帧/秒':>7} {'加速':>6} {'体积MB':>7} 截图模式")
    print("-" * 104)
    for r in results:
        if not r["ok"]:
            print(f"{r['config']:10} 失败")
            continue
        cap = r["capture_sec"] or 0
        fpsr = (r["frames"] / cap) if (cap and r["frames"]) else 0
        sp = f"×{fpsr / base_fps:.2f}" if (base_fps and fpsr) else "—"
        sz = "x".join(str(x) for x in (r["size"] or [])) or "?"
        print(f"{r['config']:10} {sz:11} {str(r['fps_out'] or '?'):>4} "
              f"{str(r['frames'] if r['frames'] is not None else '?'):>6} "
              f"{cap:>7.2f} {r['integrate_sec'] or 0:>6.2f} {r['wall_sec']:>7.2f} "
              f"{fpsr:>7.1f} {sp:>6} {str(r['size_mb']):>7} {r['shot_mode'] or '?'}")
    print("=" * 104)

    rep = {"project": out, "scenes": a.scenes, "sec_per_scene": a.sec, "fps": a.fps,
           "heavy": a.heavy, "preview": a.preview, "results": results}
    rp = os.path.join(out, "bench-report.json")
    json.dump(rep, open(rp, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    print(f"\n报告：{rp}")
    if a.json:
        print(json.dumps(rep, ensure_ascii=False, indent=1))
    return 0

if __name__ == "__main__":
    raise SystemExit(main())
```

## File: scripts/blur_integrate.py
size: 14051
sha: cc49ec3186dcc03fa04002ce881b15e0e89a7ea1
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/blur_integrate.py

```text
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""blur_integrate.py —— 快门运动模糊的积分器（渲染管线第 2 段，Node 侧只负责抓帧）。

为什么单独成段：
  运动模糊的本质是「快门开着的时候，把光积分起来」。截图是一个**瞬间**，
  所以快动作会重影成一串。做法是：同一帧在快门开合区间里 seek 若干次、
  各自截图，再把它们在**线性光**下平均 —— 这才是真的积分，不是 blur 滤镜。
  积分要逐像素算，Node 侧没有图像库，所以这一段交给 numpy/PIL（本来就是本技能的依赖）。

  分成「抓帧（Node，多进程）」+「积分（Python，多进程）」两段还有两个好处：
    · 抓帧阶段才能被 --workers 进程级并行拉满（Chrome 截图是 CPU 活，多进程各自一个浏览器）；
    · --resume 天然可用：已经积分出成品的帧直接跳过，只补缺的。

输入目录约定（render_video.mjs 写出来的）：
  <project>/render/shutter/f_000123/00.png … 0K.png     一帧的 K 个快门样本
输出：
  <project>/render/frames/f_000123.png                  积分后的成片帧
  （若该帧是 hold，Node 侧已直接落盘、不留 shutter 目录，这里不会碰到它）

用法
  "$PY" scripts/blur_integrate.py --project . [--workers 8] [--json]
  "$PY" scripts/blur_integrate.py --project . --report     # 只看统计
"""
from __future__ import annotations

import argparse
import json
import multiprocessing as mp
import os
import shutil
import sys
import tempfile
import time
from concurrent.futures import ProcessPoolExecutor

import numpy as np
from PIL import Image

# sRGB ↔ 线性光 查表（8bit → float32；16bit → uint8）
_u = np.arange(256) / 255.0
SRGB_TO_LIN = np.where(_u <= 0.04045, _u / 12.92, ((_u + 0.055) / 1.055) ** 2.4).astype(np.float32)
_l = np.arange(65536) / 65535.0
LIN_TO_SRGB = np.clip(np.rint(np.where(_l <= 0.0031308, _l * 12.92,
                                       1.055 * np.power(_l, 1 / 2.4) - 0.055) * 255.0),
                      0, 255).astype(np.uint8)
# sRGB → 线性光 的 uint16 版（积分累加专用：uint32 累加比 float32 省一半内存带宽）
SRGB_TO_LIN_U16 = np.clip(np.rint(SRGB_TO_LIN.astype(np.float64) * 65535.0), 0, 65535).astype(np.uint16)

def _probe_grey(rgb, step=8):
    """抽样灰度图 —— 只用来判断「有没有动 / 有没有切」。

    ★ 不解整图、也不做 BOX 降采样：判切只需要「相邻样本的相对变化量」，
      step=8 抽样（240×135）足够，且**不产生任何大中间数组**
      （旧版对每张样本 reshape+mean，会分配 6.2M 元素的临时数组 —— 这是积分段主要开销之一）。
    luma 系数与 PIL 的 convert('L') 一致（ITU-R 601-2）。
    """
    a = rgb[::step, ::step]
    return (a[..., 0] * 0.299 + a[..., 1] * 0.587 + a[..., 2] * 0.114).astype(np.int16)

def cut_side(small):
    """决定要积分哪几张。

    默认全要。但如果相邻两张之间**某一步的变化远大于其它步**（≥3×），那不是运动而是
    不连续 —— 硬切、一个词蹦出来、打出一个字、素材翻页。这时候只保留「帧时刻所在的那一侧」，
    否则硬切会被积成一帧的溶解（Pocket Weather 11.5s 那个切点实测变成了一帧溶解）。
    """
    n = len(small)
    if n < 4:
        return list(range(n))
    d = np.array([np.abs(small[k + 1] - small[k]).mean() for k in range(n - 1)])
    j = int(d.argmax())
    rest = np.delete(d, j)
    if d[j] <= 0 or rest.size == 0 or d[j] < 3 * rest.max():
        return list(range(n))
    # j 在左半 → 保留右半（帧时刻一侧）；否则保留左半
    return list(range(j + 1, n)) if j < n // 2 else list(range(j + 1))

def _save(img, path, ext='png', quality=95, tries=4):
    """写中间帧成品。ext=='jpg' 走 JPEG，否则走 PNG。两者都带重试。

    ★ 为什么必须按 ext 分叉（不是「顺手加个开关」）：`--jpeg` 通道下 Node 侧把静帧直接写成
      `.jpg`，如果积分器仍写 `.png`，`render/frames/` 里就会同时存在两种扩展名 ——
      ffmpeg 的输入是 `f_%06d.jpg`，会**静默漏掉全部动帧**（片子里所有带运动模糊的帧消失），
      而完整性闸门只按一种扩展名点号，两边永远对不上。通道必须一路贯穿到积分器。

    ★ 为什么要重试：在启用实时文件扫描的环境里，刚写出的文件会被扫描线程短暂占用，
      再次覆盖就可能拿到 Permission denied（实测 24 帧里偶发 3 帧）。
      这不是逻辑错误，等几十毫秒即可 —— 但如果不重试，整帧就被判失败。
    """
    for i in range(tries):
        try:
            if ext == 'jpg':
                img.save(path, 'JPEG', quality=quality, subsampling=0)
            else:
                img.save(path, compress_level=1)
            return
        except (PermissionError, OSError):
            if i == tries - 1:
                raise
            time.sleep(0.2 * (i + 1))

def integrate_dir(d, out, ext='png', quality=95, box=8):
    """积分一个 shutter 目录 → 一张成品帧（按 ext 写 png 或 jpg）。返回 (kept, total, cut)

    ★ 每张样本只解码一次：小图（判动/判切）由已解码的 RGB 数组就地降采样得到。
    """
    names = sorted(f for f in os.listdir(d) if f.lower().endswith('.png'))
    if not names:
        return 0, 0, False
    if len(names) == 1:
        # 只有一张样本：目标也是 PNG 时直接拷贝原始字节（逐位无损，不必过一遍编解码）；
        # 目标是 JPEG 就必须真转一次，否则会出现「.jpg 文件名装着 PNG 内容」的脏帧。
        src = os.path.join(d, names[0])
        if ext == 'png':
            shutil.copyfile(src, out)
        else:
            _save(Image.open(src).convert('RGB'), out, ext, quality)
        return 1, 1, False
    arrs = [np.asarray(Image.open(os.path.join(d, n)).convert('RGB')) for n in names]
    if len(arrs) == 1:
        _save(Image.fromarray(arrs[0]), out, ext, quality)
        return 1, 1, False
    keep = cut_side([_probe_grey(a, box) for a in arrs]) if len(arrs) >= 4 else list(range(len(arrs)))
    # ★ uint16 查表 + uint32 累加：与 float32 累加数值等价（实测 8bit 往返差 0），
    #   但内存带宽减半（float32 临时数组 25MB/张 → uint16 12MB/张）
    acc = None
    for k in keep:
        u = SRGB_TO_LIN_U16[arrs[k]]
        acc = u.astype(np.uint32) if acc is None else acc + u
    n = len(keep)
    idx = np.clip((acc + n // 2) // n, 0, 65535).astype(np.uint16)
    _save(Image.fromarray(LIN_TO_SRGB[idx]), out, ext, quality)
    return n, len(arrs), n < len(arrs)

def _work(job):
    d, out, ext, quality = job
    try:
        kept, tot, cut = integrate_dir(d, out, ext, quality)
        # ★ 这里**不删样本目录**：删除文件的开销在不少环境（沙箱 / 实时扫描 / 网络盘）里
        #   远高于积分本身 —— 实测 24 帧样本的目录删除要 120s+，而积分只要 1.6s。
        #   清理统一挪到积分全部完成后（main 里并行做），且可 --keep-shutter 跳过。
        return {'ok': True, 'frame': os.path.basename(out), 'kept': kept, 'total': tot,
                'cut': cut, 'dir': d}
    except Exception as e:  # noqa: BLE001
        return {'ok': False, 'frame': os.path.basename(out),
                'err': f'{type(e).__name__}: {e}', 'dir': d}

def _rm(d):
    """并行清理一个样本目录（失败不致命）"""
    try:
        shutil.rmtree(d, ignore_errors=True)
    except Exception:  # noqa: BLE001
        pass
    return 1

def _clean_via_temp(shutter_root):
    """把整个样本目录**整体 rename 到系统临时目录**再删。返回耗时（秒）。

    ★ 为什么要绕这一下：在启用了实时文件扫描 / 云同步 / 企业策略的环境里，
      **用户目录下**逐个删文件是致命慢的 —— 本机实测删 96 个文件要 121s，
      而同一批文件在系统临时目录里删除只要 0.06s。同盘 rename 是纯元数据操作（0.03s），
      因此「整体搬走 + 在临时目录删」把清理成本从 121s 压到 0.08s（≈1400×）。
      跨盘或权限失败时退回原地删（慢，但功能不缺）。
    """
    if not os.path.isdir(shutter_root):
        return 0.0
    t = time.time()
    tmp = os.path.join(tempfile.gettempdir(), 'hx-shutter-%d' % os.getpid())
    try:
        if os.path.isdir(tmp):
            shutil.rmtree(tmp, ignore_errors=True)
        os.replace(shutter_root, tmp)
    except OSError:
        shutil.rmtree(shutter_root, ignore_errors=True)
        return time.time() - t
    shutil.rmtree(tmp, ignore_errors=True)
    return time.time() - t

def pending(project, ext='png', quality=95):
    """列出还没积分的帧（shutter 目录还在、且成品帧还没生成）"""
    sd = os.path.join(project, 'render', 'shutter')
    fd = os.path.join(project, 'render', 'frames')
    if not os.path.isdir(sd):
        return []
    jobs = []
    for name in sorted(os.listdir(sd)):
        d = os.path.join(sd, name)
        if not os.path.isdir(d):
            continue
        # ★ 成品帧的扩展名必须与渲染通道一致（Node 侧 --jpeg → 'jpg'）。写死 .png 的后果：
        #   `render/frames/` 里动帧是 .png、静帧是 .jpg，而 ffmpeg 的输入是 `f_%06d.<ext>`，
        #   会**静默漏掉全部动帧**；完整性闸门只按一种扩展名点号，两边永远对不上。
        out = os.path.join(fd, name + '.' + ext)
        # 成品已存在且不比方样本旧 → 是上一轮留下的样本，跳过（--resume 语义）
        if os.path.exists(out):
            try:
                if os.path.getmtime(out) >= os.path.getmtime(d):
                    continue
            except OSError:
                pass
        jobs.append((d, out, ext, quality))
    return jobs

def main():
    ap = argparse.ArgumentParser(description='快门运动模糊积分器')
    ap.add_argument('--project', default='.')
    ap.add_argument('--workers', type=int, default=max(1, min(16, (os.cpu_count() or 4) - 2)))
    ap.add_argument('--keep-shutter', action='store_true',
                    help='积分后保留 shutter 样本目录（默认清理；样本可用于复查）')
    ap.add_argument('--ext', choices=['png', 'jpg'], default='png',
                    help="成品帧扩展名 —— 必须与渲染通道一致（Node 侧 --jpeg 就传 jpg）")
    ap.add_argument('--jpeg-quality', type=int, default=95,
                    help='ext=jpg 时的 JPEG 质量（与 Node 侧 --jpeg-quality 保持一致）')
    ap.add_argument('--json', action='store_true')
    ap.add_argument('--report', action='store_true')
    a = ap.parse_args()
    project = os.path.abspath(a.project)
    os.makedirs(os.path.join(project, 'render', 'frames'), exist_ok=True)

    jobs = pending(project, a.ext, a.jpeg_quality)
    if a.report:
        n_samp = sum(len([f for f in os.listdir(d) if f.endswith('.png')]) for d, *_ in jobs)
        print(f'待积分 {len(jobs)} 帧 · 共 {n_samp} 张快门样本'
              f'（平均 {n_samp / len(jobs):.1f} 张/帧）' if jobs else '没有待积分的帧')
        return 0
    if not jobs:
        print('blur_integrate：没有待积分的帧（全部已是成品或 shutter 关闭）')
        return 0

    t0 = time.time()
    done = 0
    kept_total = 0
    samp_total = 0
    cut_total = 0
    errs = []
    with ProcessPoolExecutor(max_workers=a.workers) as ex:
        futs = [ex.submit(_work, j) for j in jobs]
        for f in futs:
            r = f.result()
            if r['ok']:
                done += 1
                kept_total += r['kept']
                samp_total += r['total']
                cut_total += 1 if r['cut'] else 0
            else:
                errs.append(r)
    dt = time.time() - t0
    out = {'frames': len(jobs), 'integrated': done, 'errors': len(errs),
           'samples': samp_total, 'kept_samples': kept_total, 'cut_protected_frames': cut_total,
           'seconds': round(dt, 2), 'workers': a.workers,
           'fps_integrate': round(done / dt, 1) if dt > 0 else None}

    # ---- 清理样本目录：★ 在关键路径之外 ----
    # 删除文件的开销在沙箱 / 实时扫描 / 网络盘上可以远高于积分本身（本机用户目录下实测
    # 删 96 个文件要 121s，而积分只要 1.6s）。所以：① 先出成品、再清理；
    # ② 全部样本都处理完时走「整体 rename 到 Temp 再删」的快路径。
    dirs = [j[0] for j in jobs]
    shutter_root = os.path.join(project, 'render', 'shutter')
    all_dirs = []
    if os.path.isdir(shutter_root):
        all_dirs = [x for x in os.listdir(shutter_root) if os.path.isdir(os.path.join(shutter_root, x))]
    if a.keep_shutter:
        out['clean_seconds'] = None
    else:
        t1 = time.time()
        if jobs and len(all_dirs) == len(jobs):
            _clean_via_temp(shutter_root)
        elif dirs:
            with ProcessPoolExecutor(max_workers=a.workers) as ex:
                list(ex.map(_rm, dirs))
        out['clean_seconds'] = round(time.time() - t1, 2)

    if a.json:
        print(json.dumps(out, ensure_ascii=False))
    else:
        print(f'积分完成：{done}/{len(jobs)} 帧 · 保留 {kept_total} 张样本 · '
              f'{cut_total} 帧保住了硬切 · {dt:.1f}s（{out["fps_integrate"]} 帧/秒, {a.workers} 进程）')
        for e in errs[:5]:
            print(f'  ✗ {e["frame"]}: {e["err"]}')
        if a.keep_shutter:
            print(f'  样本目录已保留：{os.path.join(project, "render", "shutter")}')
        else:
            print(f'  清理样本目录：{len(dirs)} 个 / {out["clean_seconds"]}s')
    return 0 if not errs else 1

if __name__ == '__main__':
    raise SystemExit(main())
```

## File: scripts/check_beats_refs.py
size: 4619
sha: 24828b174520cbf7c723fd7d947cb7091b1fc3b6
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/check_beats_refs.py

```text
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
check_beats_refs.py —— B()/Be() 节拍引用的**构建期校验**（渲染前跑，秒级出结果）。

为什么需要它
------------
`B()` 的匹配规则是**前缀匹配**：
    bt === t  ||  bt.startsWith(t)  ||  t.startsWith(bt)      （归一化后）
也就是 text 必须是**块文本的开头**，或者块文本本身以 text 开头。取中间一段会抛错：

    块文本「一位父亲写下《被网游毁掉的孩子》」→  B('一位父亲写下') ✓    B('被网游毁掉的孩子') ✗

归一化会去掉 ，。、！？；：,.!?;:| 与空白（**保留数字里的小数点**、**不去《》「」**）。
拿不准就抄块文本的前 6–10 个字。

而 `B()` 抛错**只在渲染到那一帧时才发生** —— 前面几百帧白渲，长片要等十几分钟才炸。
这类「只在运行时才炸的静态错误」应当有一个构建期出口，这就是本脚本。

用法：
    python check_beats_refs.py --project .                  # 全量
    python check_beats_refs.py --project . --only hook_q,r1_data
退出码：有失配 = 1，全绿 = 0（可直接串进 CI / 流水线 && 链）。
"""
from __future__ import annotations

import argparse
import json
import os
import re
import sys
from typing import List, Tuple

# 同时抓 B('…') 与 Be('…')，单双引号、内部可含转义
CALL = re.compile(r"\bB(?:e)?\(\s*(['\"])((?:\\.|(?!\1).)*)\1\s*\)")
BEATS_DATA = re.compile(r"window\.__BEATS__\s*=\s*(\[.*?\])\s*;", re.S)

def norm(s: str) -> str:
    """与 subs.py 生成的 beats.js 里的 norm() 逐字对齐（改一处等于没改）。"""
    s = re.sub(r"(\d)\.(\d)", lambda m: m.group(1) + "" + m.group(2), s)
    s = re.sub(r"[\s，。、！？；：,.!?;:|]", "", s)
    return s.replace("", ".")

def unescape(q: str) -> str:
    """把 JS 字符串字面量里的 \\' \\" \\\\ 还原成原字符，否则带撇号的查询会假失配。"""
    return re.sub(r"\\(.)", lambda m: {"n": "\n", "t": "\t"}.get(m.group(1), m.group(1)), q)

def load_beats(path: str) -> List[dict]:
    if not os.path.exists(path):
        return []
    m = BEATS_DATA.search(open(path, encoding="utf-8").read())
    return json.loads(m.group(1)) if m else []

def check_one(fdir: str, sid: str) -> Tuple[int, List[str]]:
    """返回 (失配数, 报告行)。"""
    hp = os.path.join(fdir, sid + ".html")
    if not os.path.exists(hp):
        return 0, [f"  ?  {sid:<14} 无帧文件（跳过）"]

    beats = load_beats(os.path.join(fdir, sid + ".beats.js"))
    nb = [norm(b.get("text", "")) for b in beats]
    src = open(hp, encoding="utf-8").read()
    calls = [unescape(q) for _, q in CALL.findall(src)]

    lines: List[str] = []
    errs: List[str] = []

    if calls and not nb:
        errs.append("本帧有 B() 调用，但 frames/%s.beats.js 不存在或为空 —— 先跑 subs.py" % sid)
    for q in calls:
        t = norm(q)
        if not any(bt == t or bt.startswith(t) or t.startswith(bt) for bt in nb):
            errs.append(
                "B('%s') 在本帧块表里解析不到（前缀匹配失败）\n"
                "          本帧可用块：%s" % (q, [b.get("text") for b in beats])
            )

    tag = "OK " if not errs else "ERR"
    lines.append(
        f"  {tag} {sid:<14} B()/Be() 调用 {len(calls):2d} · 命中 {len(calls) - len(errs):2d} · 失配 {len(errs):2d}"
    )
    for e in errs:
        lines.append(f"        ✗ {e}")
    return len(errs), lines

def main() -> int:
    ap = argparse.ArgumentParser(description="构建期校验 B()/Be() 节拍引用")
    ap.add_argument("--project", default=".")
    ap.add_argument("--only", default="", help="逗号分隔的场景 id；缺省 = 全量")
    args = ap.parse_args()

    fdir = os.path.join(args.project, "frames")
    if not os.path.isdir(fdir):
        print(f"[beats] 找不到 {fdir}", file=sys.stderr)
        return 2

    want = [s.strip() for s in args.only.split(",") if s.strip()]
    ids = want or sorted(
        f[:-5] for f in os.listdir(fdir)
        if f.endswith(".html") and not f.startswith("_")
    )

    bad = 0
    for sid in ids:
        n, lines = check_one(fdir, sid)
        bad += n
        for ln in lines:
            print(ln)

    if bad:
        print(f"\n[beats] ✗ 失配 {bad} 处 —— B() 只在前缀处命中，改抄块文本的前 6–10 个字")
    else:
        print(f"\n[beats] ✓ {len(ids)} 个场景的节拍引用全部可解析")
    return 1 if bad else 0

if __name__ == "__main__":
    raise SystemExit(main())
```

## File: scripts/check_cover.mjs
size: 25306
sha: 8c99775e7377143c6f4156721016f1dd7ede5e9e
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/check_cover.mjs

```text
#!/usr/bin/env node
/**
 * check_cover.mjs —— 封面终态几何实测（三画幅通用）
 *
 * 为什么需要它：`cover-guide.md` 的自检清单要求「钩子字号 / 边距 / 每行字数 /
 * 是否左右两栏」逐条过，但这些都是**渲染后才知道的量**。肉眼看得出的只有明显问题，
 * 差 20px 的贴边、多出一个字的孤行，肉眼经常放过。这个脚本用真实浏览器把
 * 终态几何量出来，一次判完。
 *
 * 用法：
 *   node <skill>/scripts/check_cover.mjs <项目>              # 量全部存在的封面
 *   node <skill>/scripts/check_cover.mjs <项目> --only 916   # 只量 1080×1920
 *   node <skill>/scripts/check_cover.mjs <项目> --json       # 机器可读
 *
 * 判据（与 references/cover-guide.md 一致）：
 *   · 画布四边安全边距：16:9 ≥96px、3:4 ≥110px、9:16 左右 ≥90px
 *   · 9:16 特例：上边 ≥180px、下边 ≥160px（平台 UI 层，不是可裁区）
 *   · 钩子字号：16:9 ≥96px、3:4 ≥120px、9:16 ≥130px
 *   · 钩子必须是画面最大字号（否则视觉焦点不在钩子上）
 *   · 钩子每行字数上限：16:9 ≤7、3:4 ≤5、9:16 ≤6（防孤字断行 / 放不下）
 *   · 9:16 禁止左右两栏（量「同一水平带内是否出现并排放置的块级元素」）
 *   · 无元素越出画布
 *   · **两个不同元素的文字互不重叠**（量字墨、不量元素框 —— 见 PAGE_PROBE 第 5 节说明）
 *
 * 退出码：0 = 全 PASS；1 = 有 FAIL（可进 CI / 流水线门禁）
 */
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath, pathToFileURL } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const SKILL_ROOT = path.resolve(__dirname, '..');
const require = createRequire(path.join(SKILL_ROOT, 'node', 'package.json'));

const log = (m) => process.stderr.write(`[cover-check] ${m}\n`);
const die = (m) => { process.stderr.write(`[cover-check] ✗ ${m}\n`); process.exit(1); };

// ---------- 规格（与 cover_build.mjs 的 SPECS 对齐） ----------
const SPECS = {
  '169': {
    key: '169', file: 'cover_169.html', width: 1920, height: 1080,
    label: '16:9 · 抖音主封面',
    margin: 96,              // 四边统一
    marginTop: 96, marginBottom: 96, marginX: 96,
    hookMin: 96, hookMaxChars: 8,   // 钩子容器 1060px ÷ (130px×0.97) ≈ 8.4
    noColumns: false,
  },
  '34': {
    key: '34', file: 'cover_34.html', width: 1440, height: 1080,
    label: '3:4 · 主页栅格兼容',
    margin: 110,
    marginTop: 110, marginBottom: 110, marginX: 110,
    hookMin: 120, hookMaxChars: 8,  // 钩子容器 1220px ÷ (130px×0.97) ≈ 9.7
    noColumns: false,
  },
  '916': {
    key: '916', file: 'cover_916.html', width: 1080, height: 1920,
    label: '9:16 · 竖版全屏',
    margin: 90,
    marginTop: 180, marginBottom: 160, marginX: 90,   // ★ 上下是平台 UI 层，不是可裁区
    hookMin: 130, hookMaxChars: 6,  // 钩子容器 900px ÷ (150px×0.97) ≈ 6.2
    noColumns: true,                                  // ★ 窄画幅禁止左右两栏
  },
};

function parseArgs(argv) {
  const a = { _: [] };
  for (let i = 0; i < argv.length; i++) {
    const t = argv[i];
    if (t === '--only') a.only = argv[++i];
    else if (t === '--json') a.json = true;
    else if (t === '--browser') a.browser = argv[++i];
    else if (t === '--shot') a.shot = true;           // 顺手出一张 1x 预览图
    else a._.push(t);
  }
  return a;
}

function resolveBrowserExec() {
  const isWin = process.platform === 'win32';
  const cands = isWin ? [
    path.join(process.env['PROGRAMFILES'] || 'C:/Program Files', 'Google/Chrome/Application/chrome.exe'),
    path.join(process.env['PROGRAMFILES(X86)'] || 'C:/Program Files (x86)', 'Google/Chrome/Application/chrome.exe'),
    path.join(process.env['PROGRAMFILES(X86)'] || 'C:/Program Files (x86)', 'Microsoft/Edge/Application/msedge.exe'),
    path.join(process.env['PROGRAMFILES'] || 'C:/Program Files', 'Microsoft/Edge/Application/msedge.exe'),
  ] : [
    '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
    '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
    '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/microsoft-edge',
  ];
  return cands.find(p => { try { return fs.existsSync(p); } catch { return false; } }) || null;
}

// 在页面里量：所有"可见内容块"的包围盒 + 钩子行切分
const PAGE_PROBE = `(() => {
  const W = document.documentElement.clientWidth, H = document.documentElement.clientHeight;
  const vis = (el) => {
    const cs = getComputedStyle(el);
    if (cs.display === 'none' || cs.visibility === 'hidden' || parseFloat(cs.opacity) === 0) return false;
    const b = el.getBoundingClientRect();
    return b.width > 0.5 && b.height > 0.5;
  };
  const rnd = (n) => Math.round(n);

  // ── 1) 找钩子：在"句子级"文本元素里取字号最大的（排掉 6.02 / 4 这类纯数字）──
  //     判据与判"钩子是否最大"必须分开，否则「钩子最大」永远自证成立。
  let hookEl = null, hookFs = 0, maxFsAny = 0;
  // ★ 这个正则必须写成双层反斜杠。只写一层时，模板字符串会把「反斜杠 + s」吃成 s ——
  //   正则退化成 /s+/g，**剥掉的是字母 s、空格全留着**，于是「空格计入字位权重」
  //   与「纯数字串判不出来」全部静默失效（实测 norm('a b') 原样返回 'a b'）。
  const norm = (s) => (s || '').replace(/\\s+/g, '');
  for (const el of document.querySelectorAll('div, span, p, h1, h2')) {
    if (!vis(el)) continue;
    // ★ 用**完整文本**（含 em/span 等后代）判「句子级」，不能用直接子文本节点：
    //   钩子常写成「家长<em>不骂</em>游戏了」，只取直接子文本就剩「家长」+「游戏了」共 5 字位，
    //   过不了门槛 → 真正的钩子被跳过、退而选中 28px 的数值标签，
    //   于是「钩子字号 / 钩子是最大的文字 / 末行孤字」整条链全部误判。
    //   （实测：三张封面全部把 .val「2018 → 2026几乎消失」认成钩子。）
    //   父容器也会因完整文本通过门槛，但它 font-size 小，最终按 fs 取最大者，赢不了。
    const full = norm(el.textContent || '');
    if (!full) continue;
    const fs = parseFloat(getComputedStyle(el).fontSize) || 0;
    if (fs > maxFsAny) maxFsAny = fs;
    // 句子级：完整文本 ≥6 个"字位"（CJK 记 1，拉丁/数字记 0.55），且不是纯数字串
    const t = full;
    const wide = (t.match(/[㐀-鿿豈-﫿　-〿＀-￯]/g) || []).length;
    const narrow = t.length - wide;
    const weight = wide + narrow * 0.55;
    const pureNumber = /^[\d.,%$¥+\-–—:：]+$/.test(t);
    if (weight < 6 || pureNumber) continue;
    if (fs > hookFs) { hookFs = fs; hookEl = el; }
  }

  // ── 2) 钩子按视觉行切分（Range client rects 的 top 分桶） ──
  const lines = [];
  if (hookEl) {
    const rg = document.createRange();
    rg.selectNodeContents(hookEl);
    const rects = Array.from(rg.getClientRects())
      .filter(r => r.width > 1 && r.height > 1)
      .sort((a, b) => a.top - b.top || a.left - b.left);
    for (const r of rects) {
      const row = lines.find(L => Math.abs(L.top - r.top) < r.height * 0.55);
      if (row) { row.left = Math.min(row.left, r.left); row.right = Math.max(row.right, r.right); row.chars += 1; }
      else lines.push({ top: r.top, left: r.left, right: r.right, chars: 1 });
    }
  }

  // ── 3) 全画布内容包围盒（用于四边边距与越界）──
  let box = null;
  const offenders = [];
  for (const el of document.body.querySelectorAll('*')) {
    const cs = getComputedStyle(el);
    if (cs.position === 'fixed' || el.classList.contains('bg') || el.classList.contains('grain')) continue;
    if (!vis(el)) continue;
    const b = el.getBoundingClientRect();
    if (b.width < 1 || b.height < 1) continue;
    // 只统计"有自己文字/边框/背景"的叶子块，避免父容器把边距吃光
    const hasOwnText = Array.from(el.childNodes).some(n => n.nodeType === 3 && n.textContent.trim());
    const hasPaint = cs.backgroundColor !== 'rgba(0, 0, 0, 0)' || cs.borderTopWidth !== '0px';
    if (!hasOwnText && !hasPaint) continue;
    if (!box) box = { l: b.left, t: b.top, r: b.right, b: b.bottom };
    else { box.l = Math.min(box.l, b.left); box.t = Math.min(box.t, b.top); box.r = Math.max(box.r, b.right); box.b = Math.max(box.b, b.bottom); }
    if (b.left < -1 || b.top < -1 || b.right > W + 1 || b.bottom > H + 1) {
      const nm = el.className && typeof el.className === 'string' ? '.' + el.className.trim().split(/\\s+/).join('.') : el.tagName.toLowerCase();
      if (offenders.length < 6) offenders.push(nm + ' x' + rnd(b.left) + '→' + rnd(b.right) + ' y' + rnd(b.top) + '→' + rnd(b.bottom));
    }
  }

  // ── 4) 左右两栏探测：同一水平带内是否有两组块级内容左右分离 ──
  //     找 top 重叠 >60% 且水平间隙 > 画布宽 8% 的一对叶子块
  const leaves = [];
  for (const el of document.body.querySelectorAll('div, p, h1, h2, span')) {
    const cs = getComputedStyle(el);
    if (!vis(el)) continue;
    if (el.classList.contains('bg') || el.classList.contains('grain')) continue;
    const hasOwnText = Array.from(el.childNodes).some(n => n.nodeType === 3 && n.textContent.trim());
    if (!hasOwnText) continue;
    const b = el.getBoundingClientRect();
    // fs 是给「9:16 禁两栏」用的字号门槛（见第 4 节）
    const fs = parseFloat(getComputedStyle(el).fontSize) || 0;
    leaves.push({ b, el, fs, nm: el.className && typeof el.className === 'string' ? '.' + el.className.trim().split(/\\s+/)[0] : el.tagName.toLowerCase() });
  }
  const pairs = [];
  for (let i = 0; i < leaves.length; i++) {
    for (let j = i + 1; j < leaves.length; j++) {
      const A = leaves[i].b, B = leaves[j].b;
      // 小字号短标签（柱状图左右两个数值标注）天然就左右分布，不算「两栏文字」——
      // 不加这道门槛，9:16 的两个 .val 会被误报（实测）。
      if (Math.max(leaves[i].fs, leaves[j].fs) < 40) continue;
      const ovTop = Math.min(A.bottom, B.bottom) - Math.max(A.top, B.top);
      const minH = Math.min(A.height, B.height);
      if (minH <= 0 || ovTop / minH < 0.6) continue;                 // 必须在同一水平带
      const gap = Math.max(A.left, B.left) - Math.min(A.right, B.right);
      if (gap < W * 0.08) continue;                                   // 必须真的左右分离
      const span = Math.max(A.right, B.right) - Math.min(A.left, B.left);
      if (span < W * 0.72) continue;                                  // 合起来要铺满画布
      pairs.push(leaves[i].nm + ' ↔ ' + leaves[j].nm + ' (间隙 ' + rnd(gap) + 'px, 合宽 ' + rnd(span) + 'px)');
    }
  }

  // ── 5) 字墨重叠：两个不同元素的文字矩形相交 ──
  //     量「字墨」而不是「元素框」，三个理由：
  //     ① 元素框在「文字溢出容器」时还是容器那么大，看不出溢出到谁身上
  //        （下面的第 6 节用元素框，抓不到这一类）；
  //     ② Range 返回的是**行框**（含 leading，比字墨高），直接比会把
  //        「相邻两行」「line-height:1 的字形溢出」全报成重叠（实测 15 个假阳性）；
  //        把高度收窄到 fontSize 后，剩下的才是真压字；
  //     ③ 判据绑定「不同元素」且排除父子 —— 同一元素的多行折行不是压字。
  //     阈值 4px²：抗锯齿/字距造成的 1–2px 接触不算，真压字动辄上千 px²。
  const inks = [];
  const eid = new Map();
  for (const el of document.body.querySelectorAll('*')) {
    if (!vis(el)) continue;
    const tns = Array.from(el.childNodes).filter(n => n.nodeType === 3 && n.textContent.trim());
    if (!tns.length) continue;
    if (!eid.has(el)) eid.set(el, eid.size + 1);
    const id = eid.get(el);
    const fs = parseFloat(getComputedStyle(el).fontSize) || 0;
    const cls = (el.className && typeof el.className === 'string') ? el.className.trim() : '';
    const nm = cls ? '.' + cls.split(' ')[0] : el.tagName.toLowerCase();
    const rg = document.createRange();
    for (const tn of tns) {
      rg.selectNodeContents(tn);
      for (const r of rg.getClientRects()) {
        if (r.width <= 0.5 || r.height <= 0.5) continue;
        const h = fs > 0 ? Math.min(r.height, fs) : r.height;
        inks.push({ x: r.left, y: r.top + (r.height - h) / 2, w: r.width, h, el, id, nm,
                    text: norm(tn.textContent).slice(0, 14) });
      }
    }
  }
  const overlaps = [];
  for (let i = 0; i < inks.length; i++) {
    for (let j = i + 1; j < inks.length; j++) {
      const A = inks[i], B = inks[j];
      if (A.id === B.id) continue;                                    // 同一元素的多行不算
      if (A.el.contains(B.el) || B.el.contains(A.el)) continue;        // 父子不算
      const ow = Math.min(A.x + A.w, B.x + B.w) - Math.max(A.x, B.x);
      const oh = Math.min(A.y + A.h, B.y + B.h) - Math.max(A.y, B.y);
      if (ow <= 0 || oh <= 0) continue;
      const area = ow * oh;
      if (area <= 4) continue;
      overlaps.push(A.nm + '「' + A.text + '」 × ' + B.nm + '「' + B.text + '」 ' + rnd(area) + 'px²');
    }
  }
  overlaps.sort((a, b) => parseFloat(b.split(' ').pop()) - parseFloat(a.split(' ').pop()));

  // ── 6) 钩子与其它文本块的重叠（旧版的漏检点）──
  //     钩子行高一旦撑到统计块上，字会直接压字，但四边边距/行宽全部照样 PASS。
  //     实测案例：9:16 钩子 3 行 ×132px 顶到 1646px，与 bottom:196px 的信息行
  //     压了 34px，旧判据全绿。所以必须把"块间垂直重叠"独立成一条。
  const hookOverlap = [];
  if (hookEl) {
    const hb = hookEl.getBoundingClientRect();
    for (const L of leaves) {
      if (L.el === hookEl || hookEl.contains(L.el) || L.el.contains(hookEl)) continue;
      const A = hb, B = L.b;
      const ox = Math.min(A.right, B.right) - Math.max(A.left, B.left);
      const oy = Math.min(A.bottom, B.bottom) - Math.max(A.top, B.top);
      if (ox <= 1 || oy <= 1) continue;
      if ((ox * oy) / Math.min(A.width * A.height, B.width * B.height) < 0.06) continue;
      hookOverlap.push(L.nm + ' 压住钩子 ' + rnd(ox) + '×' + rnd(oy) + 'px');
    }
  }

  // ── 7) 比钩子还大的其它元素（纯数字另算）──
  const biggerThanHook = [];
  for (const el of document.body.querySelectorAll('*')) {
    const own = Array.from(el.childNodes).filter(n => n.nodeType === 3).map(n => n.textContent).join('');
    if (!norm(own) || !vis(el)) continue;
    const fs = parseFloat(getComputedStyle(el).fontSize) || 0;
    if (fs <= hookFs + 0.5) continue;
    const t = norm(own);
    const nm = el.className && typeof el.className === 'string' ? '.' + el.className.trim().split(/\\s+/)[0] : el.tagName.toLowerCase();
    biggerThanHook.push({ sel: nm, fontSize: rnd(fs * 10) / 10, pureNumber: /^[\\d.,%$¥+\\-–—:：]+$/.test(t), text: t.slice(0, 12) });
  }
  biggerThanHook.sort((a, b) => b.fontSize - a.fontSize);

  return {
    canvas: { W, H },
    hook: hookEl ? {
      sel: hookEl.className && typeof hookEl.className === 'string' ? '.' + hookEl.className.trim().split(/\\s+/).join('.') : hookEl.tagName.toLowerCase(),
      fontSize: hookFs,
      text: (hookEl.textContent || '').replace(/\\s+/g, ' ').trim(),
      lines: lines.map(L => ({ top: rnd(L.top), left: rnd(L.left), right: rnd(L.right), width: rnd(L.right - L.left), segments: L.chars })),
    } : null,
    box: box ? { l: rnd(box.l), t: rnd(box.t), r: rnd(box.r), b: rnd(box.b) } : null,
    offenders,
    maxFsAny: rnd(maxFsAny * 10) / 10,
    // 比钩子还大的"其它"元素。纯数字（悖论数字）单列 —— 它比钩子大是允许的，
    // 非数字的比钩子大才是"焦点被抢"。
    biggerThanHook: biggerThanHook.slice(0, 5),
    columnPairs: pairs.slice(0, 4),
    overlaps: overlaps.slice(0, 8),
    hookOverlap: hookOverlap.slice(0, 4),
  };
})()`;

async function main() {
  const args = parseArgs(process.argv.slice(2));
  const projectDir = path.resolve(args._[0] || '.');
  if (!fs.existsSync(path.join(projectDir, 'frames'))) die(`不是项目目录（没有 frames/）：${projectDir}`);

  let specs;
  if (args.only) {
    specs = String(args.only).split(',').map(s => s.trim()).map(k => {
      if (!SPECS[k]) die(`未知规格 --only ${k}（可用：${Object.keys(SPECS).join(' / ')}）`);
      return SPECS[k];
    });
  } else {
    specs = Object.values(SPECS);
  }
  const present = specs.filter(s => fs.existsSync(path.join(projectDir, 'frames', s.file)));
  if (!present.length) die(`frames/ 下没有封面帧（找 ${specs.map(s => s.file).join(' / ')}）`);

  let chromium;
  try { ({ chromium } = require('playwright-core')); }
  catch { die('playwright-core 缺失：在技能目录 node/ 下 npm install playwright-core'); }

  const browserExec = args.browser || resolveBrowserExec();
  const launchOpts = {};
  if (browserExec) launchOpts.executablePath = browserExec;

  const browser = await chromium.launch(launchOpts);
  const report = [];
  let anyFail = false, anyWarn = false;

  // ★ 必须量「终态」而不是「中间态」（lessons #30）：页内若有 GSAP 时间轴，
  //   先把它 seek 到轴末再量。否则量到的是入场起始值 —— 边距 / 行数 / 字号全错，
  //   而且**看起来像真错误**（本次实测：3:4 版轴长 1.54s，等 0.65s 就量，
  //   钩子还在 opacity:0，脚本把悖论数字 112px 误判成钩子并报「钩子字号不足」）。
  const FREEZE = `(() => {
    const t = window.__tl;
    if (t && typeof t.duration === 'function') {
      try { t.pause(t.duration(), false); return { frozen: true, dur: t.duration() }; }
      catch (e) { return { frozen: false, err: String(e) }; }
    }
    return { frozen: false };
  })()`;

  for (const spec of present) {
    const fileUrl = pathToFileURL(path.join(projectDir, 'frames', spec.file)).href;
    const page = await browser.newPage({ viewport: { width: spec.width, height: spec.height }, deviceScaleFactor: 1 });
    await page.goto(fileUrl);
    await page.waitForTimeout(300);
    const fr = await page.evaluate(FREEZE);
    if (!fr.frozen) await page.waitForTimeout(1600 + 600);   // 无时间轴：等 CSS 动画自然结束
    await page.waitForTimeout(120);
    const m = await page.evaluate(PAGE_PROBE);
    if (args.shot) {
      const shotDir = path.join(projectDir, 'out');
      fs.mkdirSync(shotDir, { recursive: true });
      await page.screenshot({ path: path.join(shotDir, `check_${spec.key}.png`) });
    }
    await page.close();

    const checks = [];
    // level: 'fail' 计入退出码；'warn' 只提示
    const add = (name, ok, detail, level = 'fail') => {
      checks.push({ name, ok, detail, level: ok ? 'ok' : level });
      if (!ok) { if (level === 'fail') anyFail = true; else anyWarn = true; }
    };

    // ① 画布
    add('画布尺寸', m.canvas.W === spec.width && m.canvas.H === spec.height,
      `${m.canvas.W}×${m.canvas.H}（应 ${spec.width}×${spec.height}）`);

    // ② 边距（只在有内容包围盒时判）
    if (m.box) {
      const [ml, mt, mr, mb] = [m.box.l, m.box.t, spec.width - m.box.r, spec.height - m.box.b];
      add(`左边距 ≥${spec.marginX}`, ml >= spec.marginX - 1, `${ml}px`);
      add(`右边距 ≥${spec.marginX}`, mr >= spec.marginX - 1, `${mr}px`);
      add(`上边距 ≥${spec.marginTop}`, mt >= spec.marginTop - 1, `${mt}px${spec.key === '916' ? '（9:16 让开平台顶部信息层）' : ''}`);
      add(`下边距 ≥${spec.marginBottom}`, mb >= spec.marginBottom - 1, `${mb}px${spec.key === '916' ? '（9:16 让开底部标题栏）' : ''}`);
    } else {
      add('内容包围盒', false, '未找到任何可见内容块');
    }

    // ③ 越界
    add('无元素越出画布', m.offenders.length === 0, m.offenders.length ? m.offenders.join(' ; ') : 'OK');

    // ③b 文字互不压字（字墨级）。实测三张封面首版全命中：长标签折行后压住上面的数字 ——
    //     这类问题在缩略图里几乎看不出来，但「块框」也照不出来（文字溢出了容器框）→ 必须量字墨。
    add('文字无重叠', (m.overlaps || []).length === 0,
      (m.overlaps || []).length ? m.overlaps.join(' ; ') : 'OK');

    // ④ 钩子
    if (m.hook) {
      add(`钩子字号 ≥${spec.hookMin}`, m.hook.fontSize >= spec.hookMin - 0.5,
        `${m.hook.fontSize}px  「${m.hook.text}」`);

      // 钩子是否仍是最大焦点：纯数字（悖论数字）比钩子大是允许的 → WARN；文字比钩子大 → FAIL
      const bigger = m.biggerThanHook || [];
      const textBigger = bigger.filter(b => !b.pureNumber);
      const numBigger = bigger.filter(b => b.pureNumber);
      add('钩子是最大的文字', textBigger.length === 0,
        textBigger.length ? textBigger.map(b => `${b.sel} ${b.fontSize}px「${b.text}」`).join(' ; ')
                          : `钩子 ${m.hook.fontSize}px 为最大文字` + (numBigger.length ? `（悖论数字 ${numBigger.map(b => b.fontSize + 'px').join('/')} 更大，允许）` : ''));
      if (numBigger.length) {
        add('悖论数字未压过钩子', numBigger.every(b => b.fontSize <= m.hook.fontSize * 1.35),
          `${numBigger.map(b => b.sel + ' ' + b.fontSize + 'px').join(' ; ')}（上限 钩子×1.35 = ${Math.round(m.hook.fontSize * 1.35)}px）`, 'warn');
      }

      // 钩子与其它文本块的重叠 —— 旧版漏检：字压字，但边距/行宽/字数全绿
      add('钩子不与其它文字重叠', (m.hookOverlap || []).length === 0,
        (m.hookOverlap || []).length ? m.hookOverlap.join(' ; ') : 'OK');

      const maxW = spec.width - spec.marginX * 2;
      const over = m.hook.lines.filter(L => L.width > maxW + 1);
      add(`钩子行宽 ≤${maxW}`, over.length === 0,
        over.length ? over.map(L => `${L.width}px`).join(' ; ')
                    : `最大 ${Math.max(...m.hook.lines.map(L => L.width))}px / ${m.hook.lines.length} 行`);

      // 每行字数：参考值，超了只是提醒（硬判据是上面的行宽）
      const em = m.hook.fontSize;
      const est = m.hook.lines.map(L => Math.round(L.width / (em * 0.93)));   // 0.93 ≈ 中文字宽×字距实测系数
      add(`钩子每行 ≲${spec.hookMaxChars} 字`, Math.max(...est) <= spec.hookMaxChars + 1,
        `估 ${est.join(' / ')} 字（本画幅参考上限 ${spec.hookMaxChars}；硬判据是行宽 ≤${maxW}px）`, 'warn');

      const lastLineNarrow = m.hook.lines.length >= 2 &&
        m.hook.lines[m.hook.lines.length - 1].width < m.hook.lines[0].width * 0.42;
      add('末行不是孤字', !lastLineNarrow,
        lastLineNarrow ? `末行仅 ${m.hook.lines[m.hook.lines.length - 1].width}px（首行 ${m.hook.lines[0].width}px）—— 疑似孤字断行` : 'OK');
    } else {
      add('找到钩子', false, '未找到句子级文字元素（自身文本 ≥6 字位）—— 检查钩子是否真的存在');
    }

    // ⑤ 9:16 禁左右两栏
    if (spec.noColumns) {
      add('9:16 无左右两栏', m.columnPairs.length === 0,
        m.columnPairs.length ? m.columnPairs.join(' ; ') : 'OK');
    }

    report.push({ spec, checks, m, frozen: fr });
  }

  await browser.close();

  if (args.json) {
    console.log(JSON.stringify(report.map(r => ({
      spec: r.spec.key, label: r.spec.label, frozen: r.frozen,
      checks: r.checks, hook: r.m.hook, box: r.m.box,
    })), null, 2));
    process.exit(anyFail ? 1 : 0);
  }

  // ---------- 人读报告 ----------
  for (const r of report) {
    const fails = r.checks.filter(c => c.level === 'fail').length;
    const warns = r.checks.filter(c => c.level === 'warn').length;
    const tag = fails ? `✗ ${fails} 项未过${warns ? ` / ${warns} 提醒` : ''}`
                      : (warns ? `✓ 通过（${warns} 项提醒）` : '✓ 全部通过');
    console.log(`\n=== ${r.spec.label}  ${r.spec.width}×${r.spec.height}  ${tag} ===`);
    console.log(`    量测状态：${r.frozen.frozen ? `时间轴已 seek 到轴末 ${r.frozen.dur.toFixed(2)}s（终态）` : '无时间轴，静态'}`);
    for (const c of r.checks) {
      console.log(`  ${c.level === 'ok' ? '✓' : c.level === 'warn' ? '!' : '✗'} ${c.name.padEnd(22)} ${c.detail}`);
    }
    if (r.m.hook) {
      console.log(`  · 钩子 ${r.m.hook.lines.length} 行 / ${r.m.hook.fontSize}px，各行宽：` +
        r.m.hook.lines.map(L => `${L.width}px`).join(' / '));
    }
  }
  console.log(`\n${anyFail ? '✗ 有未通过项 —— 按 references/cover-guide.md 的自检清单修版后重跑'
                            : (anyWarn ? '✓ 通过（提醒项属参考值，肉眼判断即可）' : '✓ 全部通过')}`);
  process.exit(anyFail ? 1 : 0);
}

main().catch(e => die(e.stack || String(e)));
```

## File: scripts/check_integrity.py
size: 14077
sha: 5f2b4dc7c0c728507f853985e48fea3b4479c163
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/check_integrity.py

```text
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
check_integrity.py —— 仓库自洽性检查（CI 与本地都能跑，零第三方依赖）。

检查项都对应真实发生过的漂移风险：
  1. SKILL.md 的 version 与 CHANGELOG.md 最新版本号一致
     —— 发布时最容易漏：改了 SKILL.md 忘写 CHANGELOG（或反之）。
  2. style-catalog.json 与 style-catalog.md 的风格 ID 集合完全一致
     —— 两者由 import_styles.py 同时生成，不一致 = 有人只手改了其中一个。
  3. style-catalog.json 的条目数 == SKILL.md 里声明的风格数
     —— 更新风格库时 SKILL.md 的硬编码数字最容易忘记同步。
  4. JSON 每条都有 id / license 字段，且 id 唯一
     —— 授权信息缺失会让 THIRD_PARTY_NOTICES 失真。
  5. 帧模板 / 封面模板不得出现外链字体或 CDN 资源
     —— 离线渲染硬要求，见 frame-contract.md 契约 2。
  6. 密钥防线：.gitignore 必须忽略 tts.env / *.env / *.key，且仓库内不得出现
     真实的火山引擎密钥（非空赋值 / AKLT 形态 token）
     —— 火山 TTS 是本技能唯一需要密钥的功能，泄露即永久失守。
  7. SKILL.md frontmatter 的 description 不得超过加载器的 1024 字符上限
     —— 超限时部分加载器（Claude Code / ZCode 等）**静默丢弃整个 skill**：
     不报错、列表里没有、也永远触发不了。本地完全看不出来，见 issue #3。

用法：
  python scripts/check_integrity.py            # 以脚本所在技能的根目录为准
  python scripts/check_integrity.py --root .   # 指定仓库根
退出码：0 = 全过，1 = 有失败项。
"""
from __future__ import annotations

import argparse
import json
import os
import re
import sys

OK = "  ✓"
BAD = "  ✗"

# 外链资源（离线渲染禁止）
REMOTE = re.compile(r"""(?:<link[^>]+href|@import\s+url\(|<script[^>]+src)\s*=?\s*["'(]?https?://""", re.I)

# frontmatter description 的硬上限：Claude Code / ZCode 等加载器都按 1024 字符卡严。
# 超限时它们的做法是**静默丢弃整个 skill**（不是截断、不报错）：技能列表里查无此项，
# 也永远触发不了 —— 在本地怎么测都看不出来。详见 issue #3。
DESC_LIMIT = 1024
# 建议上限：description 是「什么时候该用我」的一句话索引，不是第二份功能清单。
DESC_ADVISE = 700

def read(path: str) -> str:
    with open(path, encoding="utf-8") as fh:
        return fh.read()

def check_version(root: str, fails: list[str]) -> None:
    """SKILL.md version 必须与 CHANGELOG.md 最新版本号一致。"""
    skill = os.path.join(root, "SKILL.md")
    changelog = os.path.join(root, "CHANGELOG.md")
    if not os.path.isfile(skill) or not os.path.isfile(changelog):
        fails.append("version: 找不到 SKILL.md 或 CHANGELOG.md")
        return

    m = re.search(r"^version:\s*([0-9]+\.[0-9]+\.[0-9]+)\s*$", read(skill), re.M)
    if not m:
        fails.append("version: SKILL.md 里没有合法的 version 字段")
        return
    skill_ver = m.group(1)

    # CHANGELOG 的第一个 "## [x.y.z]" 标题即最新发布版本
    m2 = re.search(r"^##\s*\[([0-9]+\.[0-9]+\.[0-9]+)\]", read(changelog), re.M)
    if not m2:
        fails.append("version: CHANGELOG.md 里找不到 '## [x.y.z]' 标题")
        return
    log_ver = m2.group(1)

    if skill_ver == log_ver:
        print(f"{OK} 版本一致：{skill_ver}")
    else:
        fails.append(
            f"version: SKILL.md 是 {skill_ver}，CHANGELOG.md 最新是 {log_ver} —— 发布前必须同步"
        )

def check_description_length(root: str, fails: list[str]) -> None:
    """SKILL.md frontmatter 的 description 必须在加载器上限以内（issue #3）。

    这条检查的价值全在「本地不可观测」上：description 太长时技能照常能跑、
    单元测试全绿、CI 全绿 —— 只有换到按 1024 字符规则扫描的加载器里，
    整个技能才会消失，而且不报任何错。所以只能靠构建期把它钉住。
    """
    skill = os.path.join(root, "SKILL.md")
    if not os.path.isfile(skill):
        return
    text = read(skill)
    m = re.match(r"^---\r?\n(.*?)\r?\n---\r?\n", text, re.S)
    if not m:
        fails.append("skillmd: SKILL.md 没有合法的 frontmatter（应为 --- 开头的一段 YAML）")
        return
    fm = m.group(1)
    dm = re.search(r"^description:[ \t]*(.*)$", fm, re.M)
    if not dm:
        fails.append("skillmd: frontmatter 缺 description 字段"
                     " —— 加载器靠它判断何时触发，缺了等于技能不可被发现")
        return

    desc = dm.group(1).strip()
    n = len(desc)
    nb = len(desc.encode("utf-8"))

    # YAML 平面标量的两个坑：`a: b` 里的冒号会被解析成新键；以引号开头会变成另一种标量。
    if ": " in desc:
        fails.append("skillmd: description 里有 ASCII 的「冒号+空格」"
                     " —— 会让 YAML 把它切成新字段（全角「：」不受影响）")

    if n > DESC_LIMIT:
        fails.append(
            f"skillmd: description 有 {n} 字符（{nb} 字节），超过 {DESC_LIMIT} 字符上限 —— "
            f"部分加载器会**静默丢弃整个 skill**（列表里没有、也触发不了）。"
            f"把风格目录 / 版本能力 / 渲染档位等细节移进 SKILL.md 正文，"
            f"只留「触发场景」的措辞，并把触发词放在最前面"
        )
        return

    if n > DESC_ADVISE:
        print(f"{OK} skillmd: description {n} 字符（{nb} 字节）—— 未超 {DESC_LIMIT}，"
              f"但超过建议值 {DESC_ADVISE}，可再精简")
    else:
        print(f"{OK} skillmd: description {n} 字符（{nb} 字节），在 {DESC_LIMIT} 上限内")

def check_catalog(root: str, fails: list[str]) -> int | None:
    """两个风格目录必须描述同一组风格。"""
    md_path = os.path.join(root, "references", "style-catalog.md")
    js_path = os.path.join(root, "references", "style-catalog.json")
    if not os.path.isfile(md_path) or not os.path.isfile(js_path):
        fails.append("catalog: 找不到 references/style-catalog.md 或 .json")
        return None

    try:
        entries = json.loads(read(js_path))
    except Exception as exc:  # noqa: BLE001
        fails.append(f"catalog: style-catalog.json 解析失败 —— {exc}")
        return None
    if not isinstance(entries, list):
        fails.append("catalog: style-catalog.json 顶层应为数组")
        return None

    # ---- 结构完整性 ----
    ids: list[str] = []
    for i, e in enumerate(entries):
        if not isinstance(e, dict):
            fails.append(f"catalog: 第 {i} 条不是对象")
            continue
        eid = e.get("id")
        if not eid:
            fails.append(f"catalog: 第 {i} 条缺少 id")
            continue
        if not e.get("license"):
            fails.append(f"catalog: {eid} 缺少 license 字段（授权信息不完整）")
        ids.append(eid)

    dupes = sorted({x for x in ids if ids.count(x) > 1})
    if dupes:
        fails.append(f"catalog: id 重复 —— {', '.join(dupes)}")

    # ---- .md 与 .json 的 ID 集合比对（md 用反引号包 id）----
    md_ids = set(re.findall(r"`((?:frame|vfx)-[a-z0-9-]+|frame-product-promo-30s)`", read(md_path)))
    json_ids = set(ids)
    only_md = sorted(md_ids - json_ids)
    only_json = sorted(json_ids - md_ids)
    if only_md or only_json:
        if only_md:
            fails.append(f"catalog: 只在 .md 里出现 —— {', '.join(only_md)}")
        if only_json:
            fails.append(f"catalog: 只在 .json 里出现 —— {', '.join(only_json)}")
    else:
        print(f"{OK} 风格目录一致：{len(json_ids)} 个风格，.md 与 .json 同步")

    return len(json_ids)

def check_catalog_count(root: str, count: int | None, fails: list[str]) -> None:
    """SKILL.md 里声明的风格数必须等于实际条数。"""
    if count is None:
        return
    skill = os.path.join(root, "SKILL.md")
    if not os.path.isfile(skill):
        return
    body = read(skill)
    # 匹配「共 23 种风格」/「23 个模板」；用后顾断言排除「2–4 种风格轮换」这类区间
    nums = {int(n) for n in re.findall(r"(?<![\d–—-])(\d+)\s*(?:个|种)\s*(?:模板|风格)", body)}
    if not nums:
        print(f"  · 计数：SKILL.md 未声明风格数量，跳过（实际 {count}）")
        return
    if count in nums:
        print(f"{OK} 计数一致：SKILL.md 声明 {sorted(nums)}，实际 {count}")
    else:
        fails.append(
            f"count: SKILL.md 声明 {sorted(nums)} 个风格，实际 {count} 个 —— 更新风格库后忘记同步文案"
        )

def check_no_remote_assets(root: str, fails: list[str]) -> None:
    """模板里不得有外链资源（离线渲染硬要求）。"""
    targets = []
    assets = os.path.join(root, "assets")
    if os.path.isdir(assets):
        targets += [os.path.join(assets, f) for f in sorted(os.listdir(assets))
                    if f.endswith((".html", ".htm"))]
    bad = []
    for p in targets:
        for m in REMOTE.finditer(read(p)):
            bad.append(f"{os.path.basename(p)}: {m.group(0)[:70]}")
    if bad:
        for b in bad:
            fails.append(f"remote: 模板含外链资源（离线渲染会失败/退化）—— {b}")
    elif targets:
        print(f"{OK} 模板无外链资源：{len(targets)} 个模板检查通过")

def check_no_secrets(root: str, fails: list[str]) -> None:
    """密钥防线：tts.env 必须被忽略，且仓库里不得出现真实密钥。

    对应 2026-09-23 加入的火山引擎 TTS 支持 —— 那是本技能唯一需要密钥的功能。
    密钥纪律是「agent 不读、仓库不记」，所以这里做两道自动化检查：
      a) .gitignore 覆盖 tts.env / *.env / *.key，且 tts.env.example 模板仍被跟踪；
      b) 草签文件里不得出现非空的密钥赋值或 AKLT 形态的 token。
    """
    gi = os.path.join(root, ".gitignore")
    if os.path.isfile(gi):
        text = read(gi)
        need = ["tts.env", "*.env", "*.key"]
        missing = [n for n in need if n not in text]
        if missing:
            fails.append(f"secret: .gitignore 未忽略 {', '.join(missing)}"
                         f" —— 密钥可能被提交进公开仓库")
        else:
            print(f"{OK} 密钥防线：.gitignore 已忽略 tts.env / *.env / *.key")
    else:
        fails.append("secret: 没有 .gitignore —— 密钥无保护")

    example = os.path.join(root, "tts.env.example")
    if not os.path.isfile(example):
        if os.path.isfile(os.path.join(root, "tts.env")):
            # 实证过这种踩法：用户把仓库里的 tts.env.example **改名**成 tts.env 去填 key，
            # 于是模板没了、仓库里多了一份（被忽略的）密钥文件。给个能指向原因的说法。
            fails.append("secret: 缺 tts.env.example 模板，但同目录有 tts.env —— "
                         "疑似把模板文件改名成了 tts.env。请恢复 tts.env.example"
                         "（模板要留在仓库），tts.env 另行复制")
        else:
            fails.append("secret: 缺 tts.env.example 模板（用户没有可照抄的密钥模板）")

    # 真实密钥形态：非空赋值 / AKLT 前缀
    SECRET_ASSIGN = re.compile(
        r"^\s*(VOLC_API_KEY|VOLC_ACCESS_KEY|X_Api_Key|X-Api-Key)\s*[=:]\s*[\"']?([^\s\"'#]+)",
        re.M)
    AKLT = re.compile(r"AKLT[A-Za-z0-9_\-]{8,}")
    SKIP_DIRS = {".git", "node_modules", "__pycache__", "dist", ".venv", "venv"}
    SKIP_EXT = {".mp4", ".mp3", ".wav", ".png", ".jpg", ".jpeg", ".ttf", ".otf",
                ".woff", ".woff2", ".zip", ".ico"}
    hits: list[str] = []
    for dirpath, dirnames, filenames in os.walk(root):
        dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
        for fn in filenames:
            if os.path.splitext(fn)[1].lower() in SKIP_EXT:
                continue
            p = os.path.join(dirpath, fn)
            rel = os.path.relpath(p, root)
            # tts.env 本体跳过：它是用户本地文件，本检查只保证它不入库
            if fn in ("tts.env",) or rel in ("tts.env",):
                continue
            try:
                body = read(p)
            except (UnicodeDecodeError, OSError):
                continue
            for m in AKLT.finditer(body):
                hits.append(f"{rel}: AKLT 形态 token")
            if fn.endswith(".example"):
                continue
            for m in SECRET_ASSIGN.finditer(body):
                if m.group(2).strip():          # 有值才算泄露，空模板是合规的
                    hits.append(f"{rel}: {m.group(1)} 有非空值")
    if hits:
        for h in sorted(set(hits)):
            fails.append(f"secret: 疑似真实密钥 —— {h}")
    else:
        print(f"{OK} 密钥防线：仓库内未发现真实密钥（模板里的空赋值不算）")

def main() -> int:
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", default=None, help="仓库根目录（默认 = 本脚本所在技能的根）")
    args = ap.parse_args()

    root = args.root or os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    root = os.path.abspath(root)
    print(f"== html-explainer 自洽性检查 ==\n根目录：{root}\n")

    fails: list[str] = []
    check_version(root, fails)
    check_description_length(root, fails)
    count = check_catalog(root, fails)
    check_catalog_count(root, count, fails)
    check_no_remote_assets(root, fails)
    check_no_secrets(root, fails)

    print("-" * 40)
    if fails:
        print(f"✗ {len(fails)} 项失败：\n")
        for f in fails:
            print(f"  · {f}")
        return 1
    print("全部检查通过 ✓")
    return 0

if __name__ == "__main__":
    sys.exit(main())
```

## File: scripts/check_layout.mjs
size: 27100
sha: 2e634b5c3211433517d37090b0369c841c900466
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/check_layout.mjs

```text
#!/usr/bin/env node
/**
 * check_layout.mjs —— 终态几何体检：越界 / 侵入字幕禁区 / 元素互相遮挡。
 *
 * 为什么需要它：`lint_frames.py` 是**静态文本**检查（禁色值字面量、禁 transition、
 * 中文字体族…），它完全看不见几何。而画面里最常见的两类「静默出错」恰恰是几何问题，
 * 且两者都不报错、lint 全绿、渲完几千帧才被人眼发现：
 *   ① **遮挡** —— 图表轴标签被底部证据条压住、两段文字打架（issue #1 的症状之一）
 *   ② **越界** —— 内容溢出画布、压进字幕带
 * 这个脚本把「终态帧里谁和谁重叠、谁越界」变成可枚举的清单。
 *
 * ★ 判据是**终态**，不是中途帧。入场动画跑到一半时元素本来就在半路，
 *   拿中途帧判「对齐/遮挡」必然误判（见 frame_at.py 同款说明）。
 *
 * 用法：
 *   node scripts/check_layout.mjs <项目目录>
 *   node scripts/check_layout.mjs . --only 20_shape,22_holiday
 *   node scripts/check_layout.mjs . --json          # 机读输出到 out/layout.json
 *   node scripts/check_layout.mjs . --ignore "my-wide-band"
 * 退出码：有 ERROR → 1（可直接挂进流水线）
 *
 * 产出：out/layout_report.md（人读）+ out/layout.json（机读）
 */
import { createRequire } from 'node:module';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

// 本脚本既可能被从技能目录直接调用，也可能被脚本自己复制进项目 script/ 下，
// 因此不能靠相对路径找技能根。解析顺序：env → 向上逐级 → 各智能体技能目录。
const SKILL_SUBDIRS = [
  ['.workbuddy', 'skills'],   // WorkBuddy
  ['.claude', 'skills'],      // Claude Code
  ['.codex', 'skills'],       // OpenAI Codex
  ['.gemini', 'skills'],      // Gemini CLI
  ['.cursor', 'skills'],      // Cursor
  ['.agents', 'skills'],      // 通用约定
];
function resolveSkillRoot() {
  const cands = [];
  if (process.env.HTML_EXPLAINER_ROOT) cands.push(process.env.HTML_EXPLAINER_ROOT);
  let d = __dirname;
  for (let i = 0; i < 6; i++) {
    cands.push(d);
    const p = path.dirname(d);
    if (p === d) break;
    d = p;
  }
  const homes = [process.env.USERPROFILE, process.env.HOME].filter(Boolean);
  for (const home of homes) {
    for (const seg of SKILL_SUBDIRS) cands.push(path.join(home, ...seg, 'html-explainer'));
  }
  for (const c of cands) {
    try {
      if (fs.existsSync(path.join(c, 'node', 'node_modules', 'playwright-core', 'package.json'))) return c;
    } catch { /* ignore */ }
  }
  return null;
}

const SKILL_ROOT = resolveSkillRoot();
const require = createRequire(SKILL_ROOT
  ? path.join(SKILL_ROOT, 'node', 'package.json')
  : path.join(__dirname, 'package.json'));

const log = (m) => process.stderr.write(`[layout] ${m}\n`);
const die = (m) => { process.stderr.write(`[layout] ✗ ${m}\n`); process.exit(2); };

function parseArgs(argv) {
  const a = { _: [] };
  for (let i = 0; i < argv.length; i++) {
    const t = argv[i];
    if (t === '--only') a.only = String(argv[++i]).split(',').map((s) => s.trim()).filter(Boolean);
    else if (t === '--ignore') a.ignore = String(argv[++i]).split(',').map((s) => s.trim()).filter(Boolean);
    else if (t === '--safe-bottom') a.safeBottom = parseFloat(argv[++i]);
    else if (t === '--safe-side') a.safeSide = parseFloat(argv[++i]);
    else if (t === '--json') a.json = true;
    else if (t === '--strict') a.strict = true;
    else if (!t.startsWith('--')) a._.push(t);
  }
  return a;
}

function resolveBrowserExec() {
  if (process.env.BROWSER_PATH && fs.existsSync(process.env.BROWSER_PATH)) return process.env.BROWSER_PATH;
  const cands = process.platform === 'win32' ? [
    'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
    'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
    path.join(process.env.LOCALAPPDATA || '', 'Google\\Chrome\\Application\\chrome.exe'),
    'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',
    'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe',
  ] : ['/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/microsoft-edge'];
  for (const p of cands) { try { if (p && fs.existsSync(p)) return p; } catch { /* ignore */ } }
  return null;
}

const FONT_WAIT = `new Promise(function (resolve) {
  var cap = setTimeout(resolve, 5000);
  try {
    var links = Array.prototype.slice.call(document.querySelectorAll('link[rel="stylesheet"]'));
    Promise.all(links.map(function (l) {
      return new Promise(function (r) {
        l.addEventListener('load', r, { once: true });
        l.addEventListener('error', r, { once: true });
        try { if (l.sheet) r(); } catch (e) {}
      });
    })).then(function () {
      var step = function () { requestAnimationFrame(function () { requestAnimationFrame(resolve); }); };
      if (document.fonts && document.fonts.ready && document.fonts.ready.then) {
        document.fonts.ready.then(function () { clearTimeout(cap); step(); });
      } else { clearTimeout(cap); step(); }
    });
  } catch (e) { clearTimeout(cap); resolve(); }
})`;

// ★ 真函数字面量（传字符串只会被求值不执行 → 每帧静止且零报错）
const seekEnd = async () => {
  const tl = window.__tl || (window.__timelines && Object.values(window.__timelines)[0]) || null;
  let dur = 0;
  if (tl && typeof tl.duration === 'function') {
    dur = tl.duration() || 0;
    tl.pause(0, false);
    tl.pause(dur, false);          // ← 第二参必须 false
  }
  if (document.getAnimations) {
    document.getAnimations().forEach((a) => {
      try {
        const t = Number.isFinite(a.effect && a.effect.getTiming ? a.effect.getTiming().duration : NaN)
          ? null : null;
        a.pause();
        // 循环关键帧（呼吸光等）拖到很后面，让它落在稳定相位
        a.currentTime = Math.round((dur * 1000) + 1000 * 60 * 5) || 0;
        void t;
      } catch (e) { /* ignore */ }
    });
  }
  await new Promise((r) => { requestAnimationFrame(() => { requestAnimationFrame(r); }); });
  return dur;
};

/**
 * 页面内几何审计。返回 { items, findings, skipped }。
 * 判定分三级：ERROR（一定是 bug）· WARN（可疑，多半是 bug）· INFO（算术提示，供人判断）
 */
const audit = (o) => {
  const W = o.W, H = o.H;
  const SAFE_BOTTOM = o.safeBottom;     // 硬底线：内容底边必须 ≥ 这里
  const SAFE_SIDE = o.safeSide;         // 左右安全边（含卡片外边距）
  const IGNORE = (o.ignore || []).map((s) => s.toLowerCase());
  const STRICT = !!o.strict;
  const TOL = 2;

  // 装饰层白名单：整幅幕底／网格／柔光／幽灵大字，它们本来就满屏或该被文字压住
  const DECO_TOKENS = new Set([
    'bg', 'grid', 'paperbg', 'stage', 'vignette', 'noise', 'grain', 'glow', 'halo', 'aura',
    'anchor', 'ghost', 'watermark', 'wm', 'no', 'scan', 'beam', 'streak', 'dust',
  ]);
  const DECO_MAX_OPACITY = 0.16;   // 透明度低于此值视为装饰（幽灵大字/柔光）

  const tokens = (el) => String(el.className && el.className.baseVal !== undefined
    ? el.className.baseVal : (el.className || ''))
    .split(/[\s_-]+/).filter(Boolean).map((s) => s.toLowerCase());

  const isDeco = (el) => tokens(el).some((t) => DECO_TOKENS.has(t))
    || IGNORE.some((ig) => (el.getAttribute('class') || '').toLowerCase().includes(ig));

  const effOpacity = (el) => {
    let op = 1, cur = el;
    while (cur && cur.nodeType === 1) {
      const v = parseFloat(getComputedStyle(cur).opacity);
      if (Number.isFinite(v)) op *= v;
      cur = cur.parentElement;
    }
    return op;
  };

  const colorAlpha = (c) => {
    const m = String(c || '').match(/rgba?\(([^)]+)\)/);
    if (!m) return 1;
    const p = m[1].split(',').map((s) => parseFloat(s));
    return p.length >= 4 ? p[3] : 1;
  };
  const hasBg = (cs) => {
    const b = cs.backgroundColor || '';
    if (!b || b === 'transparent' || b === 'rgba(0, 0, 0, 0)') return false;
    return colorAlpha(b) >= 0.08;
  };
  const hasBorder = (cs) => {
    for (const s of ['Top', 'Right', 'Bottom', 'Left']) {
      const w = parseFloat(cs['border' + s + 'Width']) || 0;
      if (w <= 0 || cs['border' + s + 'Style'] === 'none') continue;
      if (colorAlpha(cs['border' + s + 'Color']) < 0.08) continue;
      return true;
    }
    return false;
  };

  const SVGNS = 'http://www.w3.org/2000/svg';
  const INLINEISH = new Set(['SPAN', 'B', 'EM', 'I', 'SMALL', 'STRONG', 'U', 'BR', 'SUB', 'SUP', 'MARK', 'TIME']);

  // 「文本叶」：整棵子树里的元素后代全是行内标签 → 渲染上就是一块文本。
  // ★ 文本可能全在 <span> 里（`<div class="axis"><span>700nm</span><span>450nm</span></div>`），
  //   所以「有没有自己的直接文本节点」不能作为判据 —— 第一版就是这么漏掉 issue #1 的遮挡的。
  const ownTextOf = (el) => {
    const out = [];
    for (const n of el.childNodes) {
      if (n.nodeType === 3) out.push(n.nodeValue);
      else if (n.nodeType === 1 && n.namespaceURI === SVGNS
               && ['tspan', 'text'].includes(n.tagName.toLowerCase())) out.push(n.textContent);
    }
    return out.join('').replace(/\s+/g, ' ').trim();
  };
  const paintOf = (el) => hasBg(getComputedStyle(el)) || hasBorder(getComputedStyle(el))
    || ['IMG', 'CANVAS', 'VIDEO'].includes(el.tagName);
  const isTextLeaf = (el) => {
    if (el.namespaceURI === SVGNS) {
      const t = el.tagName.toLowerCase();
      return (t === 'text' || t === 'tspan') && el.textContent.replace(/\s+/g, ' ').trim().length > 0;
    }
    if (!el.textContent || !el.textContent.replace(/\s+/g, ' ').trim()) return false;
    for (const d of el.querySelectorAll('*')) {
      if (d.namespaceURI === SVGNS && d.tagName.toLowerCase() === 'svg') return false;
      if (!INLINEISH.has(d.tagName)) return false;
      if (paintOf(d)) return false;          // 里面有带底色的小胶囊 → 那是块，不是纯文本
    }
    // 自己有直接文本 = 纯文本块；全靠行内子元素 = 也当文本块，但只在自己**没**底色时
    return ownTextOf(el).length > 0 || !paintOf(el);
  };

  // ★ 量**字墨范围**，不量元素框。块级文本元素的 rect 是整块宽度（左对齐的 96px 大标题
  //   元素宽 1800，字形只占左边 600），拿元素框算重叠会把「印章贴在标题右侧空白处」
  //   误报成「印章压住了标题」。Range 的 client rects 是逐行、贴合字形的 ——
  //   浏览器划词高亮用的就是这套，与肉眼看到的一致。
  // ★ 纵向还要再收一次：Range 给的是**行盒**，行盒 = 字体 em 盒 + 上下留白。
  //   大字号紧排时（标题 180px / line-height 1.18），上一行的行盒底会与下一行的行盒顶
  //   擦边十几像素 —— 肉眼毫无重叠，工具却报「文字重叠」。字体在行盒里是垂直居中的，
  //   所以把每行的纵向范围收成 `中心 ± em/2`，这才是字形真正占的地方。
  const inkRect = (el) => {
    if (el.namespaceURI === SVGNS) return null;
    let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity, hit = false;
    const w = document.createTreeWalker(el, 4 /* SHOW_TEXT */, null);
    let n;
    while ((n = w.nextNode())) {
      if (!n.nodeValue || !n.nodeValue.replace(/\s+/g, '')) continue;
      const rg = document.createRange();
      rg.selectNodeContents(n);
      const fs = parseFloat(getComputedStyle(n.parentElement || el).fontSize) || 0;
      for (const cr of rg.getClientRects()) {
        if (cr.width < 0.5 || cr.height < 0.5) continue;
        hit = true;
        const cy = (cr.top + cr.bottom) / 2;
        const half = fs > 0 ? Math.min(fs, cr.height) / 2 : cr.height / 2;
        x0 = Math.min(x0, cr.left); y0 = Math.min(y0, cy - half);
        x1 = Math.max(x1, cr.right); y1 = Math.max(y1, cy + half);
      }
    }
    return hit ? { l: x0, t: y0, rr: x1, b: y1 } : null;
  };
  const items = [];
  const skipped = [];
  for (const el of document.body.querySelectorAll('*')) {
    const tag = el.tagName.toUpperCase();
    if (['SCRIPT', 'STYLE', 'LINK', 'META', 'TITLE', 'HEAD', 'BR', 'TEMPLATE'].includes(tag)) continue;
    if (el.closest && !el.closest('body')) continue;
    const cs = getComputedStyle(el);
    if (cs.display === 'none' || cs.visibility === 'hidden') continue;
    const r = el.getBoundingClientRect();
    if (r.width < 1 || r.height < 1) continue;
    if (r.right < 0 || r.bottom < 0 || r.left > W || r.top > H) continue;

    const texty = isTextLeaf(el);
    const svgRoot = el.namespaceURI === SVGNS && tag === 'SVG';
    const painted = hasBg(cs) || hasBorder(cs) || ['IMG', 'CANVAS', 'VIDEO'].includes(tag);
    if (!texty && !svgRoot && !painted) continue;

    const cls = el.getAttribute('class') || '';
    if (isDeco(el) && !STRICT) { skipped.push({ id: label(el), why: '装饰层（类名白名单）' }); continue; }
    if (effOpacity(el) < DECO_MAX_OPACITY) { skipped.push({ id: label(el), why: '有效透明度 < 0.16' }); continue; }

    const box = { l: r.left, t: r.top, rr: r.right, b: r.bottom };
    // 带底色的元素用**元素框**（它靠底色遮挡）；纯文本用**字墨**（它只占字形）。
    const ink = texty && !painted ? inkRect(el) : null;
    items.push({
      el, tag, cls, texty, svgRoot, painted, r: box,
      m: ink || box,                       // m = 参与判定的矩形（文本用字墨，块用元素框）
      id: label(el),
      text: (el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 40),
    });
  }
  // 文本叶只留**最外层**：`<div class="axis"><span>A</span><span>B</span></div>` 会同时
  // 采到 .axis 和两个 span，同一次遮挡被报三遍。留最外层 = 一条问题一条记录。
  const textSet = new Set(items.filter((i) => i.texty).map((i) => i.el));
  const kept = items.filter((i) => {
    if (!i.texty) return true;
    for (let p = i.el.parentElement; p; p = p.parentElement) if (textSet.has(p)) return false;
    return true;
  });
  items.length = 0;
  items.push(...kept);
  function label(el) {
    const c = el.getAttribute('class') || '';
    return (c ? '.' + c.split(/\s+/).slice(0, 2).join('.') : '') + '|' + el.tagName.toLowerCase();
  }

  const findings = [];
  const add = (level, kind, msg, a, b) => findings.push({
    level, kind, msg,
    a: a ? side(a) : null,
    b: b ? side(b) : null,
  });
  function side(it) {
    const o = { id: it.id, rect: rectStr(it.m) };
    const d = Math.max(Math.abs(it.r.l - it.m.l), Math.abs(it.r.t - it.m.t),
                       Math.abs(it.r.rr - it.m.rr), Math.abs(it.r.b - it.m.b));
    if (d > 2) o.box = rectStr(it.r) + '（元素框；判定用的是字墨范围）';
    return o;
  }
  function rectStr(r) {
    return `x ${Math.round(r.l)}→${Math.round(r.rr)} / y ${Math.round(r.t)}→${Math.round(r.b)}`;
  }

  // ── A. 越界 / 侵入字幕禁区 ──────────────────────────────────
  const SAFE_LINE = H - SAFE_BOTTOM;
  for (const it of items) {
    const r = it.m;
    if (r.b > H + TOL || r.rr > W + TOL || r.l < -TOL || r.t < -TOL) {
      add('ERROR', '出画', `${it.id} 越出画布（${rectStr(r)}）`, it);
      continue;
    }
    if (r.b > SAFE_LINE + TOL) {
      add('ERROR', '侵入字幕禁区',
        `${it.id} 底边 y=${Math.round(r.b)} 低于安全线 ${SAFE_LINE}（侵入 ${Math.round(r.b - SAFE_LINE)}px）${it.text ? ' — 「' + it.text + '」' : ''}`, it);
      continue;
    }
    if (r.b > SAFE_LINE - 6) {
      add('INFO', '贴线', `${it.id} 底边 y=${Math.round(r.b)} 距安全线只剩 ${Math.round(SAFE_LINE - r.b)}px`, it);
    }
    if (r.l < SAFE_SIDE - TOL || r.rr > W - SAFE_SIDE + TOL) {
      add('WARN', '越安全边', `${it.id} 距左右边 ${Math.round(Math.min(r.l, W - r.rr))}px < ${SAFE_SIDE}px（${rectStr(r)}）`, it);
    }
  }

  // ── B. 互相遮挡（跳过祖孙关系：卡片里放文字是合法的）──────────
  const inter = (ra, rb) => {
    const w = Math.min(ra.rr, rb.rr) - Math.max(ra.l, rb.l);
    const h = Math.min(ra.b, rb.b) - Math.max(ra.t, rb.t);
    return w > 0 && h > 0 ? w * h : 0;
  };
  const area = (r) => (r.rr - r.l) * (r.b - r.t);
  // 谁的视觉高度更高：z-index 优先，其次 DOM 顺序
  const zOf = (it) => { const z = parseInt(getComputedStyle(it.el).zIndex, 10); return Number.isFinite(z) ? z : 0; };
  for (let i = 0; i < items.length; i++) {
    for (let j = i + 1; j < items.length; j++) {
      const a = items[i], b = items[j];
      if (a.el.contains(b.el) || b.el.contains(a.el)) continue;
      const ov = inter(a.m, b.m);
      if (ov <= 0) continue;
      const ratioMin = ov / Math.min(area(a.m), area(b.m));
      const bothText = a.texty && b.texty;
      const minArea = bothText ? 200 : 400;
      const minRatio = bothText ? 0.06 : 0.10;
      if (ov < minArea || ratioMin < minRatio) continue;
      const pct0 = Math.round(ratioMin * 100);
      // 「盖住百分之多少」要相对**文字自己的面积**算 —— 相对一条 6px 细线算会得到
      // 无意义的 100%（细线本来就只有那么高），而那些数字是给人判断用的。
      const pctText = (t) => Math.round(100 * ov / Math.max(1, area(t.m)));
      // 谁盖住谁：z-index 优先，其次 DOM 顺序
      const above = (x, y) => zOf(x) + (x.el.compareDocumentPosition(y.el) & 2 ? 0.5 : 0);
      // 文字 vs 文字（含「带底色的文字条」）：一律是问题，但要分清是不是被实心块盖住
      if (bothText) {
        const solid = a.painted ? a : (b.painted ? b : null);
        if (solid) {
          const other = solid === a ? b : a;
          if (above(solid, other) >= above(other, solid)) {
            add('ERROR', '文字被遮挡',
              `${other.id}「${other.text}」被 ${solid.id} 盖住 ${pctText(other)}%（按文字自身面积算，读不全）`, solid, other);
            continue;
          }
        }
        add('ERROR', '文字重叠',
          `${a.id}「${a.text}」与 ${b.id}「${b.text}」重叠 ${pct0}%（按较小一块算）`, a, b);
        continue;
      }
      // 色块 vs 色块：常常是刻意的（描边套填充、光影、图上的标签）。
      // SVG 的框是「画布」不是「实心块」—— 图元画到 HTML 元素上面是常态，直接跳过。
      if (!a.texty && !b.texty) {
        if (a.svgRoot || b.svgRoot) continue;
        add('WARN', '色块重叠', `${a.id} 与 ${b.id} 重叠 ${pct0}%（确认是刻意的）`, a, b);
        continue;
      }
      // 文字 vs 色块
      const textIt = a.texty ? a : b;
      const blkIt = textIt === a ? b : a;
      if (above(blkIt, textIt) >= above(textIt, blkIt)) {
        add('ERROR', '文字被遮挡',
          `${blkIt.id} 压住了 ${textIt.id}「${textIt.text}」${pctText(textIt)}%（按文字自身面积算，读不全）`, blkIt, textIt);
      } else {
        add('WARN', '文字压色块',
          `${textIt.id}「${textIt.text}」压在 ${blkIt.id} 上 ${pctText(textIt)}%（确认是刻意的）`, textIt, blkIt);
      }
      continue;
      continue;
    }
  }

  // ── C. SVG 画的东西在不在它自己的框中央 ─────────────────────
  const svgInfo = [];
  for (const it of items) {
    if (!it.svgRoot) continue;
    try {
      const svg = it.el;
      const bb = svg.getBBox();
      const ctm = svg.getScreenCTM();
      const cor = (x, y) => ({
        x: ctm.a * x + ctm.c * y + ctm.e,
        y: ctm.b * x + ctm.d * y + ctm.f,
      });
      const p1 = cor(bb.x, bb.y), p2 = cor(bb.x + bb.width, bb.y + bb.height);
      const cx = (p1.x + p2.x) / 2, cy = (p1.y + p2.y) / 2;
      const boxCx = (it.r.l + it.r.rr) / 2, boxCy = (it.r.t + it.r.b) / 2;
      const dx = cx - boxCx, dy = cy - boxCy;
      svgInfo.push({ id: it.id, contentCx: Math.round(cx), contentCy: Math.round(cy),
                     boxCx: Math.round(boxCx), boxCy: Math.round(boxCy),
                     dx: Math.round(dx), dy: Math.round(dy) });
      if (Math.hypot(dx, dy) > 24) {
        add('WARN', 'SVG 内容偏心',
          `${it.id} 画的内容中心 (${Math.round(cx)},${Math.round(cy)}) 与自身框中心 ` +
          `(${Math.round(boxCx)},${Math.round(boxCy)}) 差 ${Math.round(Math.hypot(dx, dy))}px ` +
          `（dx ${Math.round(dx)} / dy ${Math.round(dy)}）—— viewBox 与元素框比例不一致，` +
          `或图形本身没画在 viewBox 中心`, it);
      }
    } catch (e) { /* ignore */ }
  }

  // ── D. 疑似「该跟图形对齐却差了」的 HTML 部件（issue #1 那类错位）──
  // 判据刻意收得很窄，宁可漏也不误报 —— 报告里全是噪声，人就不看了：
  //   基准只认 **SVG 内容中心**（不认幕布中心：网格/列表里的点离幕布中心几十上百像素
  //   是常态，拿它当基准等于每帧都报）；候选件要小（≤160px，是「点/标记」不是卡片）；
  //   偏差 4–200px；**同一类名在一帧里命中 ≥3 次就整组丢弃**（那是网格/日历/刻度，
  //   不是「一个该居中的部件」）。
  const hitByClass = new Map();
  for (const it of items) {
    if (it.texty || it.svgRoot) continue;
    const w = it.r.rr - it.r.l, h = it.r.b - it.r.t;
    if (w > 160 || h > 160) continue;
    const cx = (it.r.l + it.r.rr) / 2, cy = (it.r.t + it.r.b) / 2;
    let best = null;
    for (const s of svgInfo) {
      const d = Math.hypot(cx - s.contentCx, cy - s.contentCy);
      if (!best || d < best.d) best = { d, an: s.id + ' 的内容中心' };
    }
    if (!best || best.d <= 4 || best.d > 200) continue;
    const key = it.cls || it.tag;
    const rec = hitByClass.get(key) || { n: 0, rows: [] };
    rec.n++;
    rec.rows.push({ it, d: best.d, an: best.an, cx, cy, w, h });
    hitByClass.set(key, rec);
  }
  for (const [key, rec] of hitByClass) {
    if (rec.n >= 3) {
      add('INFO', '疑似未对齐（整组忽略）',
        `${key} 在一帧里命中 ${rec.n} 次 —— 按网格/列表处理，不作为错位报出`, null);
      continue;
    }
    for (const r of rec.rows) {
      add('INFO', '疑似未对齐',
        `${r.it.id}（${Math.round(r.w)}×${Math.round(r.h)}）中心 (${Math.round(r.cx)},${Math.round(r.cy)}) ` +
        `距「${r.an}」${Math.round(r.d)}px —— 若本意是对齐，这就是 issue #1 那类错位`, r.it);
    }
  }

  return { items: items.map((i) => ({ id: i.id, rect: rectStr(i.r), text: i.text })),
           findings, skipped, svgInfo, safeLine: SAFE_LINE };
};

async function main() {
  const args = parseArgs(process.argv.slice(2));
  const projectDir = path.resolve(args._[0] || '.');
  const pj = JSON.parse(fs.readFileSync(path.join(projectDir, 'project.json'), 'utf8'));
  const W = pj.width || 1920, H = pj.height || 1080;
  const safeBottom = args.safeBottom || 170;
  const safeSide = args.safeSide || 64;

  const framesDir = path.join(projectDir, 'frames');
  let ids = (pj.order || []).filter((id) => fs.existsSync(path.join(framesDir, `${id}.html`)));
  if (args.only) ids = ids.filter((id) => args.only.includes(id));
  if (!ids.length) die('没有可检查的帧（检查 project.json 的 order 与 frames/*.html）');

  let chromium;
  try { ({ chromium } = require('playwright-core')); }
  catch { die('playwright-core 缺失：技能目录 node/ 下 npm install playwright-core'); }

  const launchOpts = {};
  const be = resolveBrowserExec();
  if (be) launchOpts.executablePath = be;

  const browser = await chromium.launch(launchOpts);
  const report = [];
  for (const id of ids) {
    const page = await browser.newPage({ viewport: { width: W, height: H }, deviceScaleFactor: 1 });
    try {
      await page.addInitScript('window.__MG_RENDER__ = true;');
      await page.goto(pathToFileURL(path.join(framesDir, `${id}.html`)).href, { waitUntil: 'domcontentloaded' });
      await page.evaluate(FONT_WAIT);
      const dur = await page.evaluate(seekEnd);
      const r = await page.evaluate(audit, { W, H, safeBottom, safeSide, ignore: args.ignore || [], strict: !!args.strict });
      r.id = id; r.duration = dur;
      report.push(r);
      const errs = r.findings.filter((f) => f.level === 'ERROR').length;
      const warns = r.findings.filter((f) => f.level === 'WARN').length;
      log(`${errs ? '✗' : (warns ? '!' : '✓')} ${id.padEnd(16)} 元素 ${String(r.items.length).padStart(3)} · ERROR ${errs} · WARN ${warns}`);
    } catch (e) {
      log(`✗ ${id}: ${e.message}`);
      report.push({ id, error: e.message, findings: [], items: [], skipped: [], svgInfo: [] });
    } finally {
      await page.close();
    }
  }
  await browser.close();

  // ── 报告 ───────────────────────────────────────────────────
  const total = { ERROR: 0, WARN: 0, INFO: 0 };
  for (const r of report) for (const f of (r.findings || [])) total[f.level]++;

  const lines = [`# 几何体检 · ${path.basename(projectDir)}`, '',
    `画布 ${W}×${H} · 安全线：内容底边 ≤ **y ${H - safeBottom}**（字幕带禁区上方）· 左右安全边 ±${safeSide}px`,
    '', `帧数 ${report.length} · **ERROR ${total.ERROR} · WARN ${total.WARN} · INFO ${total.INFO}**`, ''];

  for (const lv of ['ERROR', 'WARN', 'INFO']) {
    const rows = [];
    for (const r of report) for (const f of (r.findings || [])) if (f.level === lv) rows.push([r.id, f]);
    if (!rows.length) continue;
    lines.push(`## ${lv}（${rows.length}）`, '');
    for (const [id, f] of rows) {
      lines.push(`- \`${id}\` **${f.kind}** — ${f.msg}`);
      if (f.a) lines.push(`  - A：\`${f.a.id}\` ${f.a.rect}`);
      if (f.b) lines.push(`  - B：\`${f.b.id}\` ${f.b.rect}`);
    }
    lines.push('');
  }
  const clean = report.filter((r) => !r.error && !(r.findings || []).some((f) => f.level === 'ERROR'));
  lines.push(`## 无 ERROR 的帧（${clean.length}/${report.length}）`, '',
    clean.length ? clean.map((r) => '`' + r.id + '`').join(' · ') : '（无）', '');

  const outDir = path.join(projectDir, 'out');
  fs.mkdirSync(outDir, { recursive: true });
  fs.writeFileSync(path.join(outDir, 'layout_report.md'), lines.join('\n'), 'utf8');
  if (args.json) {
    fs.writeFileSync(path.join(outDir, 'layout.json'), JSON.stringify(report, null, 2), 'utf8');
  }
  log(`ERROR ${total.ERROR} · WARN ${total.WARN} · INFO ${total.INFO} → out/layout_report.md`);
  if (total.ERROR) log('★ ERROR 是「一定是 bug」级别：对照 messages 里的 rect 改 frames/<id>.html 后重跑');
  process.exit(total.ERROR ? 1 : 0);
}

main().catch((e) => die(e.stack || String(e)));
```

## File: scripts/cover_build.mjs
size: 14150
sha: b7e1373cd90a58f9d4328845423c4eb6faf6d27a
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/cover_build.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/cover_build.mjs

## File: scripts/frame_at.py
size: 13111
sha: 1e34d77d1e8939b78b5141d0186e65aac3489856
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/frame_at.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/frame_at.py

## File: scripts/gate_check.py
size: 7712
sha: 0b4d5d8e082e0def28f878ea10eed5eb932f36f4
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/gate_check.py

```text
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""gate_check.py —— 六个确认点的硬闸门（v2.0）

为什么需要它
------------
SKILL.md 里写了「确认点必须停下等用户回话」，但**纸面规则会被静默跳过**——
agent 直接跑 style_director.py 就自选了风格，用户事后才发现「你没问过我」；
渲染同理：默认 PNG 一路渲完，用户才发现「你没问过我用哪条通道」。

本脚本把那条规则变成**挡在流水线前面的闸门**：
    进「场景构建」之前必须跑一次；不过就不许写 frames/。
    渲染之前必须再跑一次 `--phase render`；render_channel 没拍板就不许渲染。

用法
----
    python gate_check.py --project .                  # 校验（缺项即 ERROR，退出码 1）
    python gate_check.py --project . --init           # 生成 consent.json 模板（不含任何默认选择）
    python gate_check.py --project . --show           # 打印当前确认记录
    python gate_check.py --project . --phase render   # 只查渲染前必须拍板的那几项

判据（全部为 ERROR 即退出 1）
---------------------------
1. 项目根存在 `consent.json`
2. 下列每一项都有 `choice`（非空）且 `decided_by == "user"`
   - `theme`           配色方向（色号 + 气质描述）
   - `style`           风格候选的最终选定（可含 style_director 的建议，但选择权在用户）
   - `form`            影片形态（纯视觉 / 主视觉+章节讲解 / …）
   - `voice`           配音方案 + 音色
   - `duration_sec`    目标时长
   - `cover`           封面规格（哪几张）
   - `render_channel`  渲染通道（**默认推荐 png-fast** / jpeg q95 / png / jpeg q82）★ 渲染前必问
3. 若某项 `decided_by != "user"` → **停下**，把候选列给用户，拿到答复再改这个字段

设计原则：**脚本不替用户做任何选择**，`--init` 生成的模板里 choice 全为空字符串。
"""

from __future__ import annotations

import argparse
import json
import os
import sys

REQUIRED = [
    ("theme", "配色方向（色号 + 一句气质描述）"),
    ("style", "风格候选的最终选定（可含建议，但选择权在用户）"),
    ("form", "影片形态（纯视觉 / 主视觉+章节讲解 / …）"),
    ("voice", "配音方案 + 音色（edge / 火山，及具体音色 ID）"),
    ("duration_sec", "目标时长（秒）"),
    ("cover", "封面规格（16:9 / 3:4 / 9:16 各几张）"),
    ("render_channel", "渲染通道（**默认推荐 png-fast** / jpeg q95 / png / jpeg q82）—— 渲染前必须问，见 SKILL.md 确认点 5"),
]

# --phase render 只查这几项（其余早已在场景构建前定下）
RENDER_PHASE = ["render_channel"]

TEMPLATE = {
    "_note": "确认点的记录。choice 必须由用户给出；decided_by 只能是 'user'。缺任何一项 gate_check 会拒绝放行。",
    "theme": {"choice": "", "decided_by": "", "at": ""},
    "style": {"choice": "", "decided_by": "", "at": ""},
    "form": {"choice": "", "decided_by": "", "at": ""},
    "voice": {"choice": "", "decided_by": "", "at": ""},
    "duration_sec": {"choice": "", "decided_by": "", "at": ""},
    "cover": {"choice": "", "decided_by": "", "at": ""},
    "render_channel": {"choice": "", "decided_by": "", "at": ""},
}

# 渲染通道的候选（仅用于提示，选择权在用户）
CHANNEL_HINT = (
    "渲染通道候选（★推荐第 1 条）：png-fast（中间帧逐像素无损 —— 纯 CSS/MG 图形帧上实测与 "
    "jpeg q95 同速、体积还更小，默认就用它）· jpeg q95（×13、体积 1/5 —— 含满幅照片/重合成帧 "
    "或 4K 终稿时的首选；失真低于成片自身编码失真，成片里不可观测）"
    "· png（最慢，只在要逐位复现 1.4.x 老成片时选）· jpeg q82（最快，只适合打样）"
)

def _path(proj: str) -> str:
    return os.path.join(proj, "consent.json")

def cmd_init(proj: str) -> int:
    p = _path(proj)
    if os.path.exists(p):
        print(f"consent.json 已存在，未覆盖：{p}")
        return 0
    with open(p, "w", encoding="utf-8") as f:
        json.dump(TEMPLATE, f, ensure_ascii=False, indent=2)
    print(f"已生成确认模板：{p}")
    print("→ 请把每个 choice 与用户确认后填入，decided_by 写 'user'。")
    return 0

def cmd_show(proj: str) -> int:
    p = _path(proj)
    if not os.path.exists(p):
        print(f"缺 {p}")
        return 1
    with open(p, encoding="utf-8") as f:
        data = json.load(f)
    for key, label in REQUIRED:
        v = data.get(key, {})
        mark = "OK " if (v.get("choice") and v.get("decided_by") == "user") else "!! "
        print(f"[{mark}] {key:<14} {v.get('choice') or '(未确认)'}")
        print(f"        └ {label}")
    return 0

def cmd_check(proj: str, phase: str = "all") -> int:
    p = _path(proj)
    errs: list[str] = []

    if not os.path.exists(p):
        print(f"ERROR  缺确认记录 {p}")
        print("       先跑：python gate_check.py --project . --init")
        print("       再逐项与用户确认后填入（脚本不替你选）。")
        return 1

    try:
        with open(p, encoding="utf-8") as f:
            data = json.load(f)
    except Exception as e:  # noqa: BLE001
        print(f"ERROR  consent.json 解析失败：{e}")
        return 1

    keys = REQUIRED if phase == "all" else [r for r in REQUIRED if r[0] in RENDER_PHASE]

    for key, label in keys:
        item = data.get(key)
        if not isinstance(item, dict):
            errs.append(f"缺字段 {key}（{label}）")
            continue
        choice = str(item.get("choice", "")).strip()
        by = str(item.get("decided_by", "")).strip().lower()
        if not choice:
            errs.append(f"{key} 未做选择 —— {label}")
        elif by != "user":
            errs.append(
                f"{key} 的 decided_by='{item.get('decided_by')}'，必须是 'user' —— "
                f"{label}。把候选列给用户，拿到答复再改这一项。"
            )

    if data.get("_override") == "user-said-you-decide":
        print("NOTE   用户已明确授权 agent 决定（_override=user-said-you-decide），放行。")
        return 0

    if errs:
        print("确认闸门未通过（%d 项）：" % len(errs))
        for e in errs:
            print("  ERROR  " + e)
        if phase == "render":
            print("\n→ " + CHANNEL_HINT)
            print("→ 渲染前必须先问用户选通道（SKILL.md 确认点 5），不得用默认值静默开工。")
        else:
            print("\n→ 确认点必须由用户拍板；不得凭记忆或偏好替他选（SKILL.md 确认点 0）。")
        return 1

    scope = "渲染前确认项" if phase == "render" else "全部确认点"
    print(f"确认闸门通过：{scope}均已由用户拍板。")
    return 0

def main() -> int:
    ap = argparse.ArgumentParser(description="确认点的硬闸门")
    ap.add_argument("--project", default=".")
    ap.add_argument("--phase", choices=["all", "render"], default="all",
                    help="all=全量确认点；render=只查渲染前必须拍板的项")
    g = ap.add_mutually_exclusive_group()
    g.add_argument("--init", action="store_true", help="生成 consent.json 模板")
    g.add_argument("--show", action="store_true", help="打印当前确认记录")
    args = ap.parse_args()

    proj = os.path.abspath(args.project)
    if args.init:
        return cmd_init(proj)
    if args.show:
        return cmd_show(proj)
    return cmd_check(proj, args.phase)

if __name__ == "__main__":
    sys.exit(main())
```

## File: scripts/import_styles.py
size: 15935
sha: 1d4544fe4954bfa6ebcb29629859e0af298ff1ef
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/import_styles.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/import_styles.py

## File: scripts/lint_frames.py
size: 7034
sha: 3949b40a15f8dc32725124ddf097c1ef3efe742b
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/lint_frames.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/lint_frames.py

## File: scripts/make_theme.py
size: 13337
sha: 49a971fd2b5c7f8200e522fef4a9ed8bd7187741
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/make_theme.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/make_theme.py

## File: scripts/new_project.py
size: 9503
sha: 60a92dfb48b96bc74fb7e23f38f111ff952a80be
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/new_project.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/new_project.py

## File: scripts/peek_frame.mjs
size: 11948
sha: 9d223946979f3d3fc33ce8af3cf262ba6511e1f2
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/peek_frame.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/peek_frame.mjs

## File: scripts/qc_check.py
size: 14860
sha: 5ec161da979fa9b3361559ed5e425bdaee6d5cda
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/qc_check.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/qc_check.py

## File: scripts/render_video.mjs
size: 65459
sha: c7a29e2d9c6d68d4cdc5a0d889468ca503e71575
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/render_video.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/render_video.mjs

## File: scripts/style_director.py
size: 35463
sha: b5d966a9bf2c7c6b708e5e424fd30a5ad3a64960
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/style_director.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/style_director.py

## File: scripts/subs.py
size: 17116
sha: d79c665b8c9778b9d9eb83bae1833ad781e24d9e
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/subs.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/subs.py

## File: scripts/timeline_build.py
size: 5303
sha: aed5630f7960b287766bfdb59698e6dfa28ac3c1
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/timeline_build.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/timeline_build.py

## File: scripts/tts_build.py
size: 18518
sha: eab66e98652d0f9a6f70a7c03437cb753a2c2025
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/tts_build.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/tts_build.py

## File: scripts/tts_setup.py
size: 15067
sha: a1f1c7f21a35a471d682d5e9e7823ae193f5c356
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/tts_setup.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/tts_setup.py

## File: scripts/tts_volcano.py
size: 27797
sha: c8a6a06d361ae37f71d3aa99b5b2f01e124e32a4
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/tts_volcano.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/scripts/tts_volcano.py

## File: references/cover-guide.md
size: 11586
sha: 0cd028f2b2b98ddf68e6667aabf676f12b56fa92
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/cover-guide.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/cover-guide.md

## File: references/frame-contract.md
size: 11010
sha: 4e59b23dfddcb3e78dbddb8ac304dd6b524e6bd3
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/frame-contract.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/frame-contract.md

## File: references/lessons.md
size: 156276
sha: 81922a801702ba2ed5aec17cce62b0ad3e5dec76
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/lessons.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/lessons.md

## File: references/library-showcase.md
size: 5346
sha: f48ecbe7bc7963a9edb2c4107406f224faa196dd
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/library-showcase.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/library-showcase.md

## File: references/motion-library.md
size: 11684
sha: 9c05ba81ed6a2fd6db1f7109b124d28a4450e94c
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/motion-library.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/motion-library.md

## File: references/render-profiles.md
size: 29470
sha: 8e11b3c79670e9b29219b12f55829f8e1e2fc3e1
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/render-profiles.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/render-profiles.md

## File: references/showcase-mode.md
size: 6558
sha: afb99e041a813418353d0247c4d377857ee92ac0
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/showcase-mode.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/showcase-mode.md

## File: references/style-catalog.json
size: 30927
sha: 8c6e0409a87d025ebf025d33341cddba824f5513
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/style-catalog.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/style-catalog.json

## File: references/style-catalog.md
size: 29592
sha: 53386848caa651ff3ea85707329d7e82f9d04ecc
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/style-catalog.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/style-catalog.md

## File: references/style-director.md
size: 7808
sha: b357290166f2cd1252f0e8515fb50afb3ebbfaa7
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/style-director.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/style-director.md

## File: references/template-guide.md
size: 4305
sha: 385ea276914aacaa728c4500aabfdd750f4324ba
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/template-guide.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/template-guide.md

## File: references/v2-capabilities.md
size: 9933
sha: 762a43bcc40d1817f4abd4872d93eb1801fa8143
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/v2-capabilities.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/v2-capabilities.md

## File: references/volcano-tts.md
size: 11182
sha: a2c685ea075005bb486c57a05b11fe88180ab2b8
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/volcano-tts.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/volcano-tts.md

## File: references/workflow-guide.md
size: 14305
sha: b566fdc0b187c92336d5c2e86dc2e436382b82a4
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/references/workflow-guide.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/references/workflow-guide.md

## File: assets/cover-template.html
size: 8545
sha: d5bb46ef8c1bb8985049b095aeab8609575d948f
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/assets/cover-template.html

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/assets/cover-template.html

## File: assets/frame-template.html
size: 8337
sha: 3dd4150c5443ed2ebcb5e66b7f49f485b352c16b
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/assets/frame-template.html

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/assets/frame-template.html

## File: assets/gsap-README.md
size: 6194
sha: 6578f2458c12c2abc920a16f6ee9fd771c9c9ecb
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/assets/gsap-README.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/assets/gsap-README.md

## File: assets/gsap.min.js
size: 72435
sha: 3bb5803f8511319a6900b1723ffc14c6dc6940c8
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/assets/gsap.min.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/assets/gsap.min.js

## File: assets/motion.js
size: 35204
sha: b4c368103483955d1b993fbd67a3d87b0787ebc7
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/assets/motion.js

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/assets/motion.js

## File: .gitattributes
size: 741
sha: 55e1a6817d74e702b6da7220d98bb7b77fbb93c9
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/.gitattributes

```text
# Normalize line endings on commit; check out with LF everywhere.
# This matters because setup_env.sh is a bash script and the .mjs/.py
# toolchain is run from Git Bash / WSL / macOS as often as from PowerShell.
* text=auto eol=lf

# Explicit for scripts people execute directly
*.sh   text eol=lf
*.py   text eol=lf
*.mjs  text eol=lf
*.js   text eol=lf
*.py   text eol=lf
*.json text eol=lf
*.md   text eol=lf
*.css  text eol=lf
*.html text eol=lf
*.yml  text eol=lf
*.yaml text eol=lf

# Windows-only helpers keep CRLF
*.bat  text eol=crlf
*.cmd  text eol=crlf
*.ps1  text eol=crlf

# Binary assets: never touch
*.png  binary
*.jpg  binary
*.jpeg binary
*.ico  binary
*.zip  binary
*.mp3  binary
*.mp4  binary
*.ttf  binary
*.wasm binary
```

## File: .github/ISSUE_TEMPLATE/bug_report.yml
size: 3275
sha: 403e03ecb33cd7ea56a48a94a410f8f3e69604e2
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/.github/ISSUE_TEMPLATE/bug_report.yml

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/.github/ISSUE_TEMPLATE/bug_report.yml

## File: .github/ISSUE_TEMPLATE/config.yml
size: 658
sha: ff93386ae5fdba3316b6153db1b72ed34548e4bb
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/.github/ISSUE_TEMPLATE/config.yml

```text
blank_issues_enabled: false
contact_links:
  - name: 先读画面契约
    url: https://github.com/OneMoh/html-explainer/blob/main/references/frame-contract.md
    about: 绝大多数「我的画面能渲但看着不对」都能被八条契约规则解释。
  - name: 先查踩坑台账
    url: https://github.com/OneMoh/html-explainer/blob/main/references/lessons.md
    about: 已知的静默失败模式及其定位方法。提 issue 之前值得先搜一遍。
  - name: 安装与环境问题
    url: https://github.com/OneMoh/html-explainer/blob/main/README.md
    about: 先跑 `bash setup_env.sh`，再对照 README 的「疑难排查」一节。
```

## File: .github/ISSUE_TEMPLATE/feature_request.yml
size: 1280
sha: 13835779d9d51580a4d15bd9e18c82fdb8b74643
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/.github/ISSUE_TEMPLATE/feature_request.yml

```text
name: 功能建议
description: 提议一个新能力、新风格，或流程改进。
title: "[Feature] "
labels: ["enhancement"]
body:
  - type: markdown
    attributes:
      value: |
        本项目刻意保持很小的接口面：HTML 帧进，MP4 出，音画同步稳得住。会增加构建系统、
        插件 API 或云依赖的提议，一般都在范围之外 —— 但如果你认为有重要的例外，请说明。

  - type: textarea
    id: problem
    attributes:
      label: 它解决什么问题？
      description: 描述你处的场景，而不是你想要的 API。
    validations:
      required: true

  - type: textarea
    id: proposal
    attributes:
      label: 你建议的做法
    validations:
      required: true

  - type: dropdown
    id: area
    attributes:
      label: 涉及范围
      options:
        - 画面风格 / 模板
        - 解说 / TTS
        - 字幕 / 节拍同步
        - 渲染
        - QC / 体检
        - 封面
        - 文档
        - 其它
    validations:
      required: true

  - type: textarea
    id: alternatives
    attributes:
      label: 考虑过的替代方案
      description: 包括「干脆手工做」—— 这也是个有效答案。
    validations:
      required: false
```

## File: .github/PULL_REQUEST_TEMPLATE.md
size: 1165
sha: 6f0aef67a03d0cb3e329f809c1bd1c1572609913
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/.github/PULL_REQUEST_TEMPLATE.md

```text
## 这次改了什么

<!-- 一两句话。原来错在哪，这个改动做了什么？ -->

## 为什么要改

<!--
如果这修的是一个静默失败，请说明它原来表现成什么样、你又是怎么证明病因的。
「我试了 X，还是坏的；改了 Y，就好了」在这里是真正有用的信息 ——
这条流水线的输出经常看着挺像样，其实是错的。
-->

## 怎么验证的

<!--
不要写「应该能跑」。你实际跑了什么？
例如 `node scripts/peek_frame.mjs . hook --at 25,50,85`，并检查了 50% 那一帧
-->

## 检查清单

- [ ] `python scripts/lint_frames.py --project <project>` 对我动过的帧没有 FAIL
- [ ] 我真的渲染过这次改动，并看过输出
- [ ] 没有引入外部字体、CDN 链接或硬编码颜色字面量
- [ ] 新增的踩坑记录（如果有）已按下一个编号追加到 `references/lessons.md`
- [ ] `python scripts/check_integrity.py` 通过
- [ ] 涉及使用者可见行为的改动，`README.md` 与 `README.en.md` 已同步更新
- [ ] 如果新增或再衍生了第三方内容，`THIRD_PARTY_NOTICES.md` 已更新

## 相关 issue

<!-- Closes #... -->
```

## File: .github/workflows/ci.yml
size: 3713
sha: 9c595645b9443862366d7ef3e3ab849ddb3e484d
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/.github/workflows/ci.yml

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/.github/workflows/ci.yml

## File: .gitignore
size: 1126
sha: 7290409d9a8e945f4bae6eaade0a27e2d6a8bb66
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/.gitignore

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/.gitignore

## File: CHANGELOG.md
size: 72562
sha: 861a988c6e9fffc9e9be21c32a9bf2939e747090
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/CHANGELOG.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/CHANGELOG.md

## File: CONTRIBUTING.md
size: 6278
sha: 9955d071b51e71ab3d61ac712f075a35024d47e7
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/CONTRIBUTING.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/CONTRIBUTING.md

## File: DESIGN.en.md
size: 17726
sha: 10bb78baa0e71edb626ca7219f680c5658e70f06
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/DESIGN.en.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/DESIGN.en.md

## File: DESIGN.md
size: 16047
sha: ed87335e950c3707c119aade3bded99507398155
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/DESIGN.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/DESIGN.md

## File: LICENSE
size: 1060
sha: 81825539ef318a25245de31ff0034c93b20497c7
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/LICENSE

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/LICENSE

## File: licenses/Apache-2.0.txt
size: 11358
sha: d645695673349e3947e8e5ae42332d0ac3164cd7
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/licenses/Apache-2.0.txt

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/licenses/Apache-2.0.txt

## File: node/package-lock.json
size: 705
sha: 0e314ef650d56f46d79974d97d93870b2513a685
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/node/package-lock.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/node/package-lock.json

## File: node/package.json
size: 205
sha: 07e0bb162b34f3aa9ad8db627de6c0af653b6d7a
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/node/package.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/node/package.json

## File: package_skill.py
size: 4896
sha: 31125fb22d4ac5a54e34366aa130f95fc3b3d429
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/package_skill.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/package_skill.py

## File: README.en.md
size: 20303
sha: a3adac610dfbb4e4391e45d4c0b58b86716d3f01
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/README.en.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/README.en.md

## File: setup_env.sh
size: 6019
sha: d61e5f8c64b23c99c67ce19a966fbea6cc225d6a
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/setup_env.sh

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/setup_env.sh

## File: tests/geometry-fixture/frames/broken.html
size: 2910
sha: 2bbb4aca5e52eda4b4b13674a90856ca026e99c6
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/tests/geometry-fixture/frames/broken.html

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/tests/geometry-fixture/frames/broken.html

## File: tests/geometry-fixture/project.json
size: 132
sha: dc421f420c9b9ba98fa68a231381ec6139f77e14
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/tests/geometry-fixture/project.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/tests/geometry-fixture/project.json

## File: tests/test_beats_norm.mjs
size: 3819
sha: 24a2bafa44b7f9cb4ce7c3a3d25df2d6afd49224
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/tests/test_beats_norm.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/tests/test_beats_norm.mjs

## File: tests/test_motion.mjs
size: 17042
sha: 97a045a43c7724b0872c60c99e3ee81ee722a929
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/tests/test_motion.mjs

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/tests/test_motion.mjs

## File: tests/test_skill_frontmatter.py
size: 6732
sha: f8293d6d2e714a9be072cf1b256a1e3c3246d13e
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/tests/test_skill_frontmatter.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/tests/test_skill_frontmatter.py

## File: tests/test_style_director.py
size: 15537
sha: b888c1115abe02a9211427a5d0365cecd100d025
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/tests/test_style_director.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/tests/test_style_director.py

## File: tests/test_subs_text.py
size: 4404
sha: cb886139cf7fc8317f9b1ab6df6a6a481dbdc5d7
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/tests/test_subs_text.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/tests/test_subs_text.py

## File: THIRD_PARTY_NOTICES.md
size: 9858
sha: 3fd4f8fb7dbc96f27938dfc6292ffe67df7c496e
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/THIRD_PARTY_NOTICES.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/THIRD_PARTY_NOTICES.md

## File: tts.env.example
size: 1123
sha: 4a7c02a23cfe45eb33b55962dcdcc9c2a60b073e
upstream: https://github.com/onemoh/html-explainer/blob/HEAD/tts.env.example

Content is not inlined in the catalog. Read the upstream file: https://github.com/onemoh/html-explainer/blob/HEAD/tts.env.example
