Peach: Local-first video metadata scraper and media manager.
perf(tooling): 精简验证流程并移除资源槽位
longmeidao7720fe6fef8b
diff --git a/.claude/skills/peach-shell-commands/SKILL.md b/.claude/skills/peach-shell-commands/SKILL.mdindex 3ae89e07c..b29b42e86 100644--- a/.claude/skills/peach-shell-commands/SKILL.md+++ b/.claude/skills/peach-shell-commands/SKILL.md@@ -5,7 +5,7 @@ description: 在写 PowerShell 或 Bash 命令、交给用户在终端跑命令# 命令与路径的形态-最后复核:2026-09-27+最后复核:2026-10-13证据来源:`tests/test_agent_worktree.py` 与 `tests/test_scripts.py` 里临时目录 `.resolve()`和正斜杠路径的注释、`scripts/test.ps1` 与 `scripts/test.sh` 的编码约定、Git 历史里被heredoc 转义损坏的那几次补丁、`scripts/test_runner.py` 的外部工具预检,以及 2026-07 至 09@@ -50,8 +50,7 @@ Claude 与 Codex 会话记录里交给用户、被贴回报错截图的 39 条不改断言、不跳过用例。`scripts/test.ps1` 会在分片前报告无法启动的外部工具。- `danger-full-access` 是取消隔离,不是「提权沙箱」。除非用户明确要求承担全局风险,否则保留沙箱,只给当前项目入口所需的命令授权。-- 测试入口自带机器级四槽位重任务限制(`docs/TESTING.md`「验证频率」),不要再外套资源守卫;- npm/PyInstaller、FFmpeg 与媒体批处理仍按资源预算使用外层守卫。+- 测试、构建与媒体任务直接使用项目入口,不外套 CPU、内存、进程数或重任务槽位守卫;任务范围与取消按本机 `resource-budget.md`,进程清理只按本任务 PID。## 多行内容一律先写成文件diff --git a/.claude/skills/peach-worktree/SKILL.md b/.claude/skills/peach-worktree/SKILL.mdindex e03040731..2814d0fa3 100644--- a/.claude/skills/peach-worktree/SKILL.md+++ b/.claude/skills/peach-worktree/SKILL.md@@ -5,13 +5,14 @@ description: 在用户说并行、工作树、暂存、提交、ready、集成# 并行 worktree 与提交边界-最后复核:2026-10-02+最后复核:2026-10-13证据来源:`docs/HANDOFF.md`「并行智能体与 Git 工作树」、`README.md`、ADR-0015、ADR-0017、本机工作树与沙箱工具记录。## 是否委派与何时使用单一功能域、局部改动或预计 30 分钟内完成的任务,由协调者在自己的隔离工作树直接完成;只有任务可独立并行、需要隔离环境,或长跑过程能明确缩短总耗时才委派。默认最多一个工作者;多个工作者只用于彼此无依赖的任务。委派只传目标、相关文件、边界和验收命令,不转交完整对话。协调者只在完成、阻塞或至少五分钟的检查点读取状态,不做分钟级轮询,也不重复工作者完成的搜索、浏览器检查和测试。+跨对话消息仅用于对方需要处理的具体依赖;发送前核对状态与职责。授权不等于同步义务,不唤醒已结束对话只为报进度或收确认;交付以 Git 和共享证据为准。任何会写入当前机器 `peach-app` 的代码任务都使用隔离工作树。主目录只做集成,不做并行编辑;worktree 本机重建,不跨机器复制目录。## 流程@@ -28,11 +29,12 @@ description: 在用户说并行、工作树、暂存、提交、ready、集成安装依赖和构建完成后再验证;测试期间不改变环境。主检出与隔离工作树均默认自动选测。PowerShell 读 UTF-8 日志显式加 `-Encoding utf8`;编码在输出端固定,不能只给读取端指定编码。记录绑定完整代码内容、依赖环境和范围,24 小时有效;失败、验证期间改动使记录无效。- 有同环境全量基线时,`auto` 对比文件清单,只补跑新增差异的影响域;共享设施或未知文件仍跑全量。+ 用 `-Focus` / `--focus` 先验证相关 Python 或浏览器用例,调试不签记录;冻结改动后只运行一次 `auto`,不另写逐域循环。失败先定向修复,再让 `auto` 复用未受影响的记录,详见 `docs/TESTING.md`。+ 同环境基线按文件差异补测;局部记录只保留未受影响的已验证域,不升级成全量;共享设施或未知文件仍跑全量。差异补测不延长全量基线有效期;版本号行单独变化归 tooling,包内其他逻辑变化仍按源码判断。相同状态复用记录;Windows `-Fresh`、POSIX 第二参数 `--fresh` 强制重跑;显式 `full` 总是实际执行。4. `ready` 前将当前 `master` 纳入工作树并运行 `auto`。相同内容可复用记录;目标变化重算影响域。`ready` / `integrate` 拒绝缺记录、范围不足或目标分支未纳入的提交。-5. 协调者统一运行 `integrate`:锁内复查、合并固定提交。锁忙就等待后重试,禁止直接 merge;测试锁与集成锁被占时提示里带持锁方的 pid、开始时间与范围,看那一行判断,不要数进程。同一批任务由协调者整理 `STATUS`,工作者按文件分工;共享文件安排顺序。+5. 协调者统一运行 `integrate`:锁内复查、合并固定提交。取得成功退出状态并核对主线提交后才重启;锁忙交给入口等待,禁止直接 merge;提示带持锁方的 pid、开始时间与范围,不反复数进程。同一批任务由协调者整理 `STATUS`,工作者按文件分工;共享文件安排顺序。版本号不在这里动,`integrate` 只报当前值:推进与打标签都走 `scripts/release_tag.py`,它是唯一入口。`--bump auto --apply` 推版本、定版变更日志并把那一节带在输出里给人确认,确认后 `--ship --apply` 一次做完提交、推送、等 Test 转绿、打标签(ADR-0012 修订)。@@ -83,10 +85,7 @@ description: 在用户说并行、工作树、暂存、提交、ready、集成那一轮里智能体一直报告「还没推」,实际上提交已经被另一个智能体的 push 顺带到了 origin。判据不看目录名,只看 `git rev-parse --show-toplevel`;等于 `peach-app` 就是在主检出里。实测入口:`git worktree list` 里没有你那一行,就是已经没了。-- 健康检查端点是 `/healthz`,不是 `/health`。- Windows 源码改动生效时,禁止用 Computer Use 操作系统托盘。只用与托盘「重启服务」等价的项目命令;入口必须让现有托盘执行重启,或完整重启托盘并重新取得子服务所有权。直接强杀/另启 `.venv\Scripts\peach.exe` 会让 `_owned` 失真,不算等价;仓库缺少安全命令时先补入口,不能退回托盘 UI。-- PowerShell 变量必须用任务专属名称,禁止声明 `$HOME`、`$home`、`$CODEX_HOME` 的任何大小写- 变体;`foreach {}` 结果先存入任务专属数组再单独接管道,禁止在闭合花括号后直接写管道。- 工作者报 `ready` 前必须 rebase 到当前 `master`。落后十天的分支不要指望协调者去 merge:共享文件上你那一侧是旧的,冲突解错就会把已上线的修复回退掉。2026-08-25 清理时有 7 条这样的分支,最后是把各自独有的那几个文件移植到当前 master,而不是 merge 分支本体。diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 533bb03b1..2288c779d 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -41,6 +41,7 @@- 改变运行事实的任务同时更新 [docs/STATUS.md](STATUS.md);长期规则更新本文件、[docs/REUSE.md](REUSE.md) 或 ADR;可执行流程写成 `.claude/skills/<name>/SKILL.md`。分层判据见 ADR-0015,步骤见 `peach-context-rules`。- 触发是概率性的:必须每次成立的规则要由脚本、测试或 hook 强制,不能只写成技能。- 结论、进度、待办和证据写进共享文档或机器可读产物,不靠人转述。+- 任务耗时与重复验证的项目记忆见 [执行效率](VERIFICATION_EFFICIENCY.md);定向调试与记录复用见 [测试](TESTING.md)。跨对话协调只处理实际依赖,已结束对话不承担收件确认职责。## 并行智能体与 Git 工作树diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 54566939a..dfe51f48b 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -168,6 +168,8 @@ JAV 默认封面(官方封面/预览图)与视频默认大小(大图/测试与集成用 `test_runner.py`、`agent_worktree.py`,进程互斥用开发依赖 `filelock` 的 [`FileLock`](https://py-filelock.readthedocs.io/en/stable/tutorials.html)。全量验证与集成共用一把锁、最多等待 30 分钟;验证持锁至记录写入完成。临时 Git 仓库回归覆盖互斥、等待和释放;代码、环境和范围记录属于 Peach 的集成约束。记录失效返回 `4`,Windows 托盘据此最多重试三轮,用例失败返回 `1`。两端测试入口通过 `test_environment.py` 复用现有 `find_uv` 与主检出 `Dependencies.check`;隔离工作树使用 uv 官方锁文件同步,不新增包管理实现或运行依赖。同步失败停止测试,主检出只读检查;策略与行为回归见 `test_test_environment.py`。+定向调试复用标准库 unittest 的按名字加载与现有浏览器夹具,记录复用沿用文件清单、影响域和 FileLock,不新增测试框架或缓存服务。局部成功记录保留未受影响域的原验证时间,失败域不能从历史基线恢复;浏览器失败即停。回归覆盖过期、环境差异、未知与共享文件、失败后再次验证、路径越界及不签调试证明,详见 [测试](TESTING.md#定向调试与局部记录)。+提交消息复用 Git 的 [`interpret-trailers --parse`](https://git-scm.com/docs/git-interpret-trailers),署名与 README 声明判据由 `co_author.py`、`check_readme_impact.py` 共用;`check_commit_message.py` 接到仓库 `commit-msg` 钩子。Git 自身处理注释与多行 trailer,Peach 只检查字段形态和分段。Windows Git 2.55.0.windows.3 的临时仓库回归覆盖拒绝提交、保留暂存、多署名、amend 和合并消息;不新增解析依赖。具体触发范围见 [README 维护](README_MAINTENANCE.md)。### 播放、采集、发布与打包diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 1052c3aaa..afb040497 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -47,13 +47,14 @@ Dependabot 的 PR 一律在本地接管,不在网页上合:## 验证频率-整台机器同时最多跑四个测试重任务:一个分片子进程,或不分片时的整轮测试,各占一个槽位。槽位是 `build/agent-verification/heavy-slot-*.lock` 文件锁,所有工作树与会话共用;槽位全忙时入口排队,等待上限同 `--lock-timeout`,超时以 `2` 退出且不开跑。槽位只限并发,不改变测试内容,不进记录指纹。取消时按已创建的 PID 清理子进程树并归还槽位。+测试直接使用项目入口,不设置机器级资源槽位、CPU、内存或进程数限额。每轮并发由 `-Jobs` / `--jobs` 选择,默认按本机核数取最多四路,显式正整数不设机器级上限。取消时只按已创建的 PID 清理本轮子进程树;全量测试与集成仍按代码一致性要求互斥。Python 静态检查使用开发依赖 Ruff,随每个正式测试域扫描全仓自有 Python 文件,覆盖应用、脚本、测试和打包入口。规则为 Pyflakes(`F`)、Ruff 支持的 Pylint 错误规则(`PLE`),以及可变默认参数、`finally` 跳转、无效表达式和循环闭包规则(`B006`、`B012`、`B018`、`B023`)。生成的 `downloads_clouddrive_pb2.py` 排除;公开导出的导入用显式同名别名声明。命名、行数、空行和复杂度偏好不属于这套 lint 门槛。文档与文案检查包含 seiso 稳定规则和最终状态检查,随正式入口执行。分类、范围、独立检查与预览规则用法见 [文档与界面文案](WRITING.md#检查与复核)。seiso 由开发依赖与锁文件固定,运行 Peach 不需要它。不是每次都跑全量:本机按改动涉及的域选测,CI 按提交类型决定覆盖多宽。+调试先跑相关用例,冻结代码后运行一次 `auto`;不要手写逐域循环重复执行公共用例。测试失败先定向复现,修复后由 `auto` 判断哪些域需要补测。| 场景 | 验证 || --- | --- |@@ -69,11 +70,11 @@ Python 静态检查使用开发依赖 Ruff,随每个正式测试域扫描全浏览器冒烟与设计决定断言(`tests/test_web_e2e.py`)由 `web-e2e` job 在 `windows-latest` 上执行 `web` 域。它装 Node 24、`frontend/node_modules`、ffmpeg,并经 `PEACH_E2E_CHROME` 指定 runner 自带的 Chrome。矩阵扩成全量(`plan` 输出的 `wide`)时,Windows 全量行本身就跑 `web` 域,这个 job 按条件跳过;`verified` 只在这种情况接受它的 skipped,别的 job 跳过照样算红。-浏览器用例覆盖 `frontend/e2e` 下全部 `*.test.ts`,包括子目录,按文件并发、文件内串行。并发数取 `PEACH_E2E_CONCURRENCY`;未设时本机取逻辑核数的四分之一、上限 4,CI(`GITHUB_ACTIONS=true`)为 1。并发时分两批:其余文件一次并发跑完,断言帧数或动画中途位置的文件(`tests/test_web_e2e.py` 的 `CPU_SENSITIVE_SUITES`)随后串行;并发为 1 时按设计决定、交互回归和路由冒烟分组,每批最多 12 个文件。每批限时 600 秒,任一批失败,整轮验证失败。并发的文件共用一个服务和演示库:用例触发的写请求只能落在别的用例不断言的状态上,否则用 `page.route` 拦下或归进串行批。完整 TAP 日志与服务访问日志 `serve.log` 保存在 `build/agent-verification/browser/`,CI 在测试结束后上传其中的 TAP 日志。+浏览器用例覆盖 `frontend/e2e` 下全部 `*.test.ts`,包括子目录,按文件并发、文件内串行。并发数取 `PEACH_E2E_CONCURRENCY`;未设时本机取逻辑核数的四分之一、上限 4,CI(`GITHUB_ACTIONS=true`)为 1。并发时分两批:其余文件一次并发跑完,测量动画、密度切换与等待态替换的文件(`tests/test_web_e2e.py` 的 `TIMING_SENSITIVE_SUITES`)随后串行;并发为 1 时按设计决定、交互回归和路由冒烟分组,每批最多 12 个文件。每批限时 600 秒,任一批失败,整轮验证失败。并发的文件共用一个服务和演示库:用例触发的写请求只能落在别的用例不断言的状态上,否则用 `page.route` 拦下或归进串行批。完整 TAP 日志与服务访问日志 `serve.log` 保存在 `build/agent-verification/browser/`,CI 在测试结束后上传其中的 TAP 日志。需要外部前置条件(Node、ffmpeg、Chrome 等)的用例,本机缺条件时跳过,在 CI(`GITHUB_ACTIONS=true`)里判失败,判定集中在 `tests/support/conditions.py` 的 `missing_prerequisite`。所以 `python` 矩阵里 `core` 以外的行也装 Node,Windows 行另装 ffmpeg 与 Chrome。-本机默认并行:入口传 `--jobs auto`(Windows `-Jobs`),运行器按同一套稳定分片切成并发数四倍的片,最多四个子进程各领一片、先完成的接着领下一片,父进程汇总成败、用例数与逐用例耗时后按原口径签发一份记录,一片红整轮红。`-Jobs 1` 退回串行。测试之间没有共享的端口或全局目录,账本与仓库夹具都在各自的临时目录里,并行才是安全的;新增测试保持这一点。+本机默认并行:入口传 `--jobs auto`(Windows `-Jobs`),运行器按同一套稳定分片切成并发数四倍的片,每个子进程各领一片、先完成的接着领下一片,父进程汇总成败、用例数与逐用例耗时后按原口径签发一份记录,一片红整轮红。`-Jobs 1` 退回串行。测试之间没有共享的端口或全局目录,账本与仓库夹具都在各自的临时目录里,并行才是安全的;新增测试保持这一点。Windows 的路径、挂载、托盘、证书、进程编码、更新、认证及迁移属于 `core`。构建和工作流修改选择 `packaging` 与 `tooling`;测试调度自身仍全量。仅 uv 工具版本或项目展示字段变化不算依赖图变化;无法解析时全量。@@ -133,6 +134,32 @@ macOS 按影响域验证:ffmpeg 起不来是事实,但它不该挡住一次只改文档的 `checks`。域由选中的测试源码推出来。确认本次无关时用 `PEACH_SKIP_PREFLIGHT=1` 整体跳过预检;分片子进程不重复预检。+## 定向调试与局部记录++Windows 的 `-Focus` 接受 Python 模块、类、方法或仓库相对路径,可传数组;macOS/Linux 对每个选择器重复传 `--focus`。入口准备隔离依赖并核对源码。选择器不存在、浏览器路径超出 `frontend/e2e` 或与分片混用时拒绝执行。++定向调试 Python 回归:++```powershell+& .\scripts\test.ps1 -Focus test_test_evidence+```++定向调试一个浏览器文件,包括它的桌面和手机用例:++```powershell+& .\scripts\test.ps1 -Focus frontend/e2e/jav-detail.test.ts+```++macOS/Linux 的相同入口:++```sh+./scripts/test.sh auto --focus frontend/e2e/jav-detail.test.ts+```++定向调试不签发记录,不能作为 `ready` / `integrate` 的验收证明。浏览器文件选择只在调试环境生效;正式入口拒绝残留的 `PEACH_TEST_FOCUS` / `PEACH_E2E_FILES`,防止局部运行被签成整域。某个浏览器批次失败或超时后立即结束该轮浏览器检查,保留完整 TAP 与服务日志。++`auto` 从同环境、24 小时内的记录计算差异:有效全量基线保留原时间戳;有效局部基线只复用未受差异影响且本次需要的域。相同代码状态补跑缺少的域。新增、删除与修改文件均参与比较;共享设施、未知影响面和环境差异不能复用局部记录。局部记录不会变成全量,继承时间戳不延长有效期。单域失败撤销该域与全量证明,保留其他域的原成功时间;失败域必须补测,不能从旧基线恢复。全量失败撤销所有证明。`-Fresh` 与显式 `full` 始终实际执行。+## 记录的环境身份记录只在「代码、环境、范围」三项都匹配时可复用,环境那一项由 `scripts/test_evidence.py`diff --git a/docs/VERIFICATION_EFFICIENCY.md b/docs/VERIFICATION_EFFICIENCY.mdnew file mode 100644index 000000000..475b5eef3--- /dev/null+++ b/docs/VERIFICATION_EFFICIENCY.md@@ -0,0 +1,40 @@+# 执行效率与项目记忆++这份记录用于判断该读什么、该验证多少、何时协调。测试行为的唯一说明在 [TESTING.md](TESTING.md),执行步骤在 [peach-worktree](../.claude/skills/peach-worktree/SKILL.md)。测试覆盖与真实账本授权保留,资源预算按主机入口及用户明确选择执行。++## 可核对的会话证据++2026-10-13 核查六个本机 Codex 对话及相关测试日志。时间采用已结束轮次的客户端记录,跨轮次停顿不算执行;缺少结束事件的轮次不推算。下表列举可以直接定位的失败模式,不把工具调用次数当成实际测试轮数。++| 对话与 ID | 核查发现 |+| --- | --- |+| 评估新作头像与 JAVDB 详情页,`01a12b94-e3ba-7eb3-8a49-324065fdca55` | 最后一轮 115 分钟中,完整回归与等结果约 52 分钟;同一圆点布局断言在桌面和手机失败,修复后四域重跑。消息唤醒已结束对话,只得到收件确认。 |+| 重构 JAV 入库入口,`01a129a1-8f60-7371-bdbf-5fe66f0e407e` | 多次显式串行验证、外层资源入口和跨对话同步;同步、状态读取与代码修改混在同一个执行流程。 |+| 修正设置页与按钮样式,`01a12a25-e455-7c30-bf4b-2b3cf333415e` | 一个已结束轮次约 65 分钟,存在反复等待和读取测试状态。 |+| 查找版本未合并原因,`01a123cb-4f2a-7d32-9b9c-b948195ea1e3` | 多轮任务涉及测试、集成与状态核查;应按提交和证据定位,不能把整段跨日时间归为修改。 |+| 统一关注页与首页交互,`01a123da-311d-7ab3-901a-5265b30a898f` | 多次指定 `-Jobs 1`,用稳定分片编号定位浏览器,文件集合变化会让这种定位失效。 |+| 查明封面头像优先原因,`01a12b63-2bf4-7c03-a9b8-5885c0ec1795` | 调查任务也出现串行 `auto`;先区分只读判断与需要改行为的范围。 |++第一项的原始证据在主检出 `build/jav-lightbox-alignment/`:`web-first.log`、`browser-first.tap`、`final-web.log`、`integrate.json` 和 `time-audit.md`。两轮 web 分别耗时 972.991 秒与 1122.798 秒,浏览器时间包含其中,不能重复累加。来源大小单位的探索约 8 分钟仍未取得;集成与等待约 6 分半;提前重启及监听检查误纳入其他地址造成额外排查。++## 当前执行原则++- 先核对范围与实际差异,按最小必要文档定位问题;有明确文件和失败信息时不重新扫描整个项目。来源探索达到无法改变实现判断的程度就报告「未取得」,不重复翻来源脚本。+- 局部行为先用正式入口的定向调试,按文件或用例名定位;禁止猜分片编号。界面覆盖所有适用页面和视口,同一个失败模式不重复写多层断言。+- 安装、编辑和构建结束后运行一次 `auto`,让入口处理域并集、去重、并发和有效记录。测试失败只修对应问题,然后按差异补测;不另写逐域循环,不因一次局部失败重复所有已通过域。+- 测试期间不改冻结的源码、依赖和文档。测试、构建与媒体任务直接使用项目入口,不自行恢复机器级资源限额;取消只清理本任务,不影响他人工作。+- 一个运行会话对应一个结果。用支持的等待工具取得退出状态;不用反复读取同一日志尾部确认没有变化。共享锁交给入口等待,不同时另起同状态验证。+- 集成成功退出且主线提交核对后,按项目约定重启并核验运行态。验收聚焦实际变化,测试设施修改不重复应用交互的手工取证。+- 有协调授权仍须有实际依赖和处理者。已结束对话不承担状态接收或确认职责;当前任务能自主完成的集成、验证和收尾直接执行,持久交付由 Git 与项目证据承载。++## 衡量优化++用户于 2026-10-13 明确要求移除 CPU、内存、进程数、启动余量、线程限额和机器级重任务槽位。项目直接运行原生测试入口,保留按需选测、测试覆盖、代码快照证明与 Git 集成互斥。资源限额与代码一致性锁不是同一类约束,不把移除资源限额解释为跳过验收。++资源问题的证据:受限验证出现 `WinError 1816` 和 Git 启动失败;中止前采样最多 18 个进程(含入口父进程),私有提交内存峰值 1.410 GiB、单进程 1.110 GiB。该采样只覆盖中止前阶段,不能代表整套回归的峰值,也不能归因于内存不足。++原生并行浏览器验证中,紧凑密度即时样式与关注标题过渡期 DOM 各出现一次失败;相同文件分别运行均通过。相关时序测量文件进入串行批,保留全部行为断言,其余文件继续并行。不能把定向通过直接当作全量通过,也不以扩大超时或删断言处理取样竞争。++定向入口实测:`jav-detail.test.ts` 的 8 个浏览器用例全部通过,入口墙钟耗时 26.491 秒,其中浏览器 TAP 为 14.525 秒,Python 夹具与运行为 25.399 秒。这个数只说明相关文件可以快速复现,不能替代约 18 分钟的整域验收。记录复用回归确认三域基线发生前端差异时只调用 web,catalog 与 metadata 保留原验证时间;环境不一致、过期、共享变化与失败域仍需实际验证。++分别记录定向调试、正式验证、失败重跑、锁等待与集成耗时。纯工具写文件时间不能代表修改工时;并行测试用墙钟时间,不相加分片耗时。局部通过不代表完整验收通过;静态门槛只证明结构成立,不证明后续智能体已减少读取或消息。性能收益需要对应实际调用或行为回归,不把计划中的收益写成已取得。diff --git a/scripts/test.ps1 b/scripts/test.ps1index b4b268ef1..21a5c6ca9 100644--- a/scripts/test.ps1+++ b/scripts/test.ps1@@ -3,6 +3,7 @@ param([ValidateSet('full', 'auto', 'follow', 'catalog', 'media', 'sync', 'metadata', 'tooling', 'web', 'checks', 'core', 'packaging')][string]$Scope = 'auto',[switch]$Fresh,+ [string[]]$Focus = @(),[string]$Base = 'master',[int]$ShardIndex = 0,[int]$ShardCount = 1,@@ -65,6 +66,7 @@ try {Write-Host "Peach source: $LoadedPath"$PeachTestExtra = @()if ($Fresh) { $PeachTestExtra += '--fresh' }+ foreach ($PeachFocusSelector in $Focus) { $PeachTestExtra += @('--focus', $PeachFocusSelector) }& $Python scripts\test_runner.py --scope $Scope --base $Base --shard-index $ShardIndex --shard-count $ShardCount --jobs $Jobs @PeachTestExtraexit $LASTEXITCODE} finally {diff --git a/scripts/test_evidence.py b/scripts/test_evidence.pyindex e76365145..d4fa0f887 100644--- a/scripts/test_evidence.py+++ b/scripts/test_evidence.py@@ -182,10 +182,11 @@ def recent_records(folder: Path, limit: int = 32) -> list[Path]:return [path for _, path in sorted(found, reverse=True)[:limit]]-def baselines(root: Path, current: dict):+def baselines(root: Path, current: dict, *, partial: bool = False):for path in recent_records(evidence_dir(root)):record = read(root, path.stem)- if "full" not in record.get("passed", ()) or record.get("environment") != current["environment"]:+ if not record.get("passed") or (not partial and "full" not in record["passed"]) \+ or record.get("environment") != current["environment"]:continueold = record.get("manifest", {})new = current["manifest"]@@ -227,13 +228,22 @@ def write(root: Path, state: str, scopes: tuple[str, ...], *, success: bool,folder = evidence_dir(root)folder.mkdir(parents=True, exist_ok=True)prior = previous if previous is not None else read(root, state)- validated = dict(prior.get("validated", {})) if success else {}+ failed = set(prior.get("failed_scopes", ()))+ if success:+ failed = set() if "full" in scopes else failed - set(scopes)+ else:+ failed.update(scopes)+ validated = dict(prior.get("validated", {}))+ if not success:+ validated = {scope: stamp for scope, stamp in validated.items()+ if "full" not in scopes and scope != "full" and scope not in scopes}if success:- validated.update({scope: time.time() for scope in scopes})if baseline:- validated["full"] = baseline["validated"]["full"]+ validated.update(baseline["validated"])+ validated.update({scope: time.time() for scope in scopes})record = {**(context or inputs(root)), "state": state, "validated": validated, "finished": time.time(),"baseline": baseline.get("state") if baseline else None,+ "failed_scopes": sorted(failed),"elapsed": elapsed, "count": count, "slowest": slowest}temporary = folder / f"{state}.{os.getpid()}.tmp"temporary.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")diff --git a/scripts/test_focus.py b/scripts/test_focus.pynew file mode 100644index 000000000..c6841380d--- /dev/null+++ b/scripts/test_focus.py@@ -0,0 +1,52 @@+"""统一测试入口的定向调试;不签发正式验收记录。"""+from __future__ import annotations++import json+import os+import re+import sys+import unittest+from pathlib import Path+from unittest import mock+++def selection(root: Path, selectors: list[str]) -> tuple[unittest.TestSuite, tuple[str, ...]]:+ suite = unittest.TestSuite()+ browsers = []+ names = []+ for selector in dict.fromkeys(selectors):+ if selector.startswith("frontend/e2e/") and selector.endswith(".test.ts"):+ path = (root / selector).resolve()+ if not path.is_relative_to((root / "frontend/e2e").resolve()) or not path.is_file():+ raise ValueError(f"浏览器用例不存在或超出 e2e 目录:{selector}")+ browsers.append(path.relative_to(root / "frontend").as_posix())+ else:+ name = selector.removeprefix("tests/").removesuffix(".py")+ if not re.fullmatch(r"test_\w+(?:\.\w+)*", name, flags=re.ASCII) \+ or not (root / "tests" / (name.split(".")[0] + ".py")).is_file():+ raise ValueError(f"用例必须是 tests/test_*.py、Python 用例名或 frontend/e2e/*.test.ts:{selector}")+ names.append(name)+ if "e2e/setup.test.ts" in browsers:+ names.append("test_web_e2e.SetupE2ETests")+ if any(name != "e2e/setup.test.ts" for name in browsers):+ names.append("test_web_e2e.WebE2ESmokeTests")+ sys.path[:0] = [str(root), str(root / "tests")]+ try:+ for name in dict.fromkeys(names):+ suite.addTests(unittest.defaultTestLoader.loadTestsFromName(name))+ finally:+ del sys.path[:2]+ return suite, tuple(browsers)+++def run(runner, args) -> int:+ try:+ suite, browsers = selection(runner.ROOT, args.focus)+ except ValueError as error:+ print(error, file=sys.stderr)+ return 2+ print("定向调试:只运行指定用例,不签发正式记录;提交前仍需 auto。", flush=True)+ flags = {"PEACH_TEST_FOCUS": "1", "PEACH_E2E_FILES": json.dumps(browsers)} if browsers else {}+ with mock.patch.dict(os.environ, flags):+ result = unittest.TextTestRunner(verbosity=2, resultclass=runner.TimedResult).run(suite)+ return 0 if result.wasSuccessful() and result.testsRun > 0 else 1diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex b7467e23c..37e17f190 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -15,7 +15,7 @@ import timeimport tomllibimport unittestfrom collections.abc import Iterable-from contextlib import ExitStack, nullcontext+from contextlib import nullcontextfrom pathlib import Path@@ -512,20 +512,13 @@ class TimedResult(unittest.TextTestResult):super().stopTest(test)-#: 整台机器同时跑的测试重任务上限。一个分片子进程、或不分片时的整轮测试,各占一个槽位;-#: 槽位是共用 Git 目录下的文件锁,所有工作树、所有会话共用这几个,用户定的是四个。-HEAVY_TASK_SLOTS = 4-#: 一轮测试自己的并发上限,不超过机器的槽位数:多开的子进程只会排队等槽位。-MAX_JOBS = HEAVY_TASK_SLOTS-#: 最多切多少片。CI 两片是因为每片一台 runner;本机每片只是一个子进程,切细一点-#: 才能让重文件(`test_agent_worktree.py` 一个就 80 秒)不把整片拖成长尾。-MAX_SHARDS = 16+DEFAULT_JOBS = 4def resolve_jobs(value: str) -> int:- """`--jobs` 的取值:正整数照收,`auto` 按核数定、不超过 `MAX_JOBS`。"""+ """`--jobs` 的取值:正整数照收,`auto` 使用本机默认并发;显式值无机器级上限。"""if value == "auto":- return max(1, min(MAX_JOBS, (os.cpu_count() or 1) // 2))+ return max(1, min(DEFAULT_JOBS, (os.cpu_count() or 1) // 2))try:jobs = int(value)except ValueError:@@ -543,89 +536,39 @@ def shard_command(scopes: tuple[str, ...], index: int, count: int, timings: Pathreturn command-def heavy_slot_paths(slots: Path | None = None) -> list[Path]:- """机器级重任务槽位的锁文件;默认在共用 Git 目录旁,所有工作树看到的是同一组。"""- folder = slots if slots is not None else test_evidence.evidence_dir(ROOT)- return [folder / f"heavy-slot-{index}.lock" for index in range(1, HEAVY_TASK_SLOTS + 1)]-def try_heavy_slot(paths: list[Path], **note: object) -> ExitStack | None:- """不等待地拿一个空闲槽位;全忙返回 None。拿到的槽位随返回的 ExitStack 关闭而释放。"""- for path in paths:- stack = ExitStack()- try:- stack.enter_context(test_evidence.held(path, **note))- except test_evidence.Timeout:- stack.close()- continue- return stack- return None---def wait_heavy_slot(paths: list[Path], *, wait_seconds: float, poll: float = 0.2,- **note: object) -> ExitStack:- """等到一个槽位空出来;超过 `wait_seconds` 抛 `Timeout`,锁文件取最后一个槽位。"""- deadline = time.monotonic() + wait_seconds- announced = False- while True:- slot = try_heavy_slot(paths, **note)- if slot is not None:- return slot- if time.monotonic() >= deadline:- raise test_evidence.Timeout(str(paths[-1]))- if not announced:- holders = ";".join(test_evidence.describe_holder(path) for path in paths)- print(f"{len(paths)} 个测试重任务槽位都在用({holders}),最长等待 {wait_seconds:g} 秒。",- flush=True)- announced = True- time.sleep(poll)-def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,- spawn=subprocess.Popen, slots: Path | None = None,- slot_wait: float = 1800) -> tuple[bool, int, list]:- """把选中的文件按 CI 同一套稳定分片切开,同时最多 `jobs` 个子进程各跑一片。- 每片是一次 `--shard-count` 子进程:它自己从不签发记录,只把成败、用例数和逐个- 用例的耗时写进 `--timings` 那个文件,父进程汇总后签发一份记录,口径与串行相同。- 片数比并发数多,是为了让先跑完的进程接着领下一片,重文件不至于把墙钟拖成它- 一家的长度。子进程的输出各自落盘,哪片结束就整段打印哪片,不交错。- 每片启动前先拿一个机器级重任务槽位(`HEAVY_TASK_SLOTS`),该片结束就还。别的- 工作树或会话占着槽位时,这里排队,最长 `slot_wait` 秒。- """+++def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,+ spawn=subprocess.Popen) -> tuple[bool, int, list]:+ """运行独立分片并汇总证明;并发取调用方的 jobs,取消时清理自己的子进程。"""folder = Path(tempfile.mkdtemp(prefix="peach-shards-"))- paths = heavy_slot_paths(slots)pending = list(range(shard_count))- running: dict[int, tuple[object, object, ExitStack]] = {}+ running = {}passed, count, timings = True, 0, []try:while pending or running:while pending and len(running) < jobs:- if running:- slot = try_heavy_slot(paths, scope=" ".join(scopes), root=str(ROOT))- if slot is None:- break- else:- slot = wait_heavy_slot(paths, wait_seconds=slot_wait,- scope=" ".join(scopes), root=str(ROOT))index = pending.pop(0)+ log = open(folder / f"{index}.log", "w+", encoding="utf-8", errors="replace")try:- log = open(folder / f"{index}.log", "w+", encoding="utf-8", errors="replace")process = spawn(shard_command(scopes, index, shard_count, folder / f"{index}.json"),stdout=log, stderr=subprocess.STDOUT, cwd=str(ROOT))except BaseException:- slot.close()+ log.close()raise- running[index] = (process, log, slot)- finished = [index for index, (process, _, _) in running.items()- if process.poll() is not None]+ running[index] = (process, log)+ finished = [index for index, (process, _) in running.items() if process.poll() is not None]if not finished:time.sleep(0.2)continuefor index in finished:- process, log, slot = running.pop(index)- slot.close()+ process, log = running.pop(index)log.flush()log.seek(0)sys.stdout.write(log.read())@@ -640,18 +583,15 @@ def run_shards(scopes: tuple[str, ...], *, jobs: int, shard_count: int,print(f"分片 {index + 1}/{shard_count} {'通过' if ok else '失败'}"f"({report.get('count', 0)} 个用例)", flush=True)finally:- for process, log, slot in running.values():- try:- if process.poll() is None:- if os.name == 'nt':- subprocess.run(['taskkill', '/PID', str(process.pid), '/T', '/F'],- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)- else:- process.terminate()- process.wait(timeout=15)- log.close()- finally:- slot.close()+ for process, log in running.values():+ if process.poll() is None:+ if os.name == 'nt':+ subprocess.run(['taskkill', '/PID', str(process.pid), '/T', '/F'],+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=15)+ else:+ process.terminate()+ process.wait(timeout=15)+ log.close()shutil.rmtree(folder, ignore_errors=True)return passed, count, timings@@ -710,20 +650,14 @@ def environment_preflight(scopes: tuple[str, ...], timings: Path | None = None,raise SystemExit(3)-def run_local_suite(scopes: tuple[str, ...], jobs: int, *,- slot_wait: float = 1800) -> tuple[bool, int, list]:- """按并发预算执行本机测试;全量分片可逐批释放模块与测试缓存。-- 分片时每片各占一个重任务槽位;不分片时整轮在本进程里跑,同样先占一个。- """+def run_local_suite(scopes: tuple[str, ...], jobs: int) -> tuple[bool, int, list]:+ """按调用方选择的并发运行,串行全量通过分片释放测试缓存。"""chosen = {path for scope in scopes for path in selected_files(scope)}if (jobs > 1 or "full" in scopes) and len(chosen) > 1:- shard_count = min(len(chosen), 4 * jobs, MAX_SHARDS)+ shard_count = min(len(chosen), 4 * jobs)print(f"本机分片:{shard_count} 片、同时 {min(jobs, shard_count)} 个子进程", flush=True)- return run_shards(scopes, jobs=jobs, shard_count=shard_count, slot_wait=slot_wait)- with wait_heavy_slot(heavy_slot_paths(), wait_seconds=slot_wait,- scope=" ".join(scopes), root=str(ROOT)):- result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(build_suite(*scopes))+ return run_shards(scopes, jobs=jobs, shard_count=shard_count)+ result = unittest.TextTestRunner(verbosity=2, resultclass=TimedResult).run(build_suite(*scopes))return result.wasSuccessful() and result.testsRun > 0, result.testsRun, result.timings@@ -733,6 +667,7 @@ def main(argv: list[str] | None = None) -> int:parser.add_argument("--scope", action="append", dest="scopes",choices=("full", "auto", *SCOPES))parser.add_argument("--fresh", action="store_true", help="实际重跑,不复用本机记录")+ parser.add_argument("--focus", action="append", default=[], help="定向调试指定 Python/浏览器用例,不签发记录")parser.add_argument("--lock-timeout", type=float, default=1800,help="全量锁等待秒数;0 表示锁忙时立即返回")parser.add_argument("--base", default="master", help="CI 选测的已验证 Git 基线")@@ -746,11 +681,18 @@ def main(argv: list[str] | None = None) -> int:args = parser.parse_args(argv)if not 0 <= args.lock_timeout <= 1800:parser.error("锁等待时间必须在 0~1800 秒之间")- if not 1 <= args.shard_count <= MAX_SHARDS or not 0 <= args.shard_index < args.shard_count:- parser.error(f"分片总数为 1~{MAX_SHARDS},编号从 0 开始且小于总数")+ if args.shard_count < 1 or not 0 <= args.shard_index < args.shard_count:+ parser.error("分片总数必须为正数,编号从 0 开始且小于总数")if args.list_scopes:print("\n".join(("full", "auto", *SCOPES)))return 0+ if args.focus:+ if args.shard_count != 1:+ parser.error("定向调试不能与分片一起使用")+ from . import test_focus+ return test_focus.run(sys.modules[__name__], args)+ if os.environ.get("PEACH_TEST_FOCUS") or os.environ.get("PEACH_E2E_FILES"):+ parser.error("定向调试环境不能签发正式记录;请清除 PEACH_TEST_FOCUS 与 PEACH_E2E_FILES")requested: tuple[str, ...] = tuple(dict.fromkeys(args.scopes or ("auto",)))if "auto" in requested and len(requested) > 1:parser.error("auto 不能与别的域同时指定")@@ -783,31 +725,42 @@ def main(argv: list[str] | None = None) -> int:return verified_run(args, requested, scopes, files)except test_evidence.Timeout as error:lock = Path(error.lock_file)- if lock.name.startswith("heavy-slot-"):- print(f"{HEAVY_TASK_SLOTS} 个测试重任务槽位一直被占用,本次未开跑;"- "等其他工作树或会话的测试结束后重试。", flush=True)- return 2what = "本仓库全量测试" if lock.name == "full-suite.lock" else "相同状态的验证"print(f"{what}正在运行({test_evidence.describe_holder(lock)}),请等待该次结果。",flush=True)return 2-def incremental_scopes(context, scopes, files):- """从有效全量基线中选择需要补测文件最少的范围。"""+def incremental_scopes(context, scopes, files, *, failed=()):+ """选择有效基线,只补测受差异影响或缺少记录的域。"""choices = []- for record, delta, version_only in test_evidence.baselines(ROOT, context):- needed, _ = scopes_for_changes(delta)+ if "full" in failed:+ return None, scopes+ for record, delta, version_only in test_evidence.baselines(ROOT, context, partial=True):+ needed, _ = scopes_for_changes(delta) if delta else ((), "")if version_only and "full" not in needed:needed = tuple(dict.fromkeys((*needed, "tooling")))- if "full" not in needed:- weight = len({p for scope in needed for p in selected_files(scope)})- if weight <= len(files):- choices.append((weight, record, needed))+ needed = tuple(dict.fromkeys((*needed, *failed)))+ if "full" in needed:+ continue+ if "full" in record["passed"]:+ retained = {"full": record["validated"]["full"]}+ else:+ if "full" in scopes:+ continue+ retained = {scope: record["validated"][scope] for scope in scopes+ if scope in record["passed"] and scope not in needed}+ if not retained:+ continue+ needed = tuple(scope for scope in scopes if scope not in retained)+ weight = len({p for scope in needed for p in selected_files(scope)})+ if weight <= len(files):+ choices.append((weight, {**record, "validated": retained}, needed))if not choices:return None, scopes_, baseline, scopes = min(choices, key=lambda item: item[0])- print(f"复用全量基线 {baseline['state'][:12]};新增差异补测:{' '.join(scopes)}", flush=True)+ print(f"复用基线 {baseline['state'][:12]}({' '.join(baseline['validated'])});"+ f"差异补测:{' '.join(scopes) or '无'}", flush=True)return baseline, scopes@@ -822,12 +775,13 @@ def verified_run(args, requested, scopes, files) -> int:return 0previous = test_evidence.read(ROOT, state)baseline = None- if requested == ("auto",) and not args.fresh and not previous:- baseline, scopes = incremental_scopes(context, scopes, files)+ if requested == ("auto",) and not args.fresh and (not previous or previous.get("passed")):+ baseline, scopes = incremental_scopes(context, scopes, files, failed=previous.get("failed_scopes", ()))folder = test_evidence.evidence_dir(ROOT)(folder / f"{state}.json").unlink(missing_ok=True)started = time.monotonic()- passed, count, timings = run_local_suite(scopes, args.jobs, slot_wait=args.lock_timeout)+ passed, count, timings = run_local_suite(scopes, args.jobs) \+ if scopes else (True, 0, [])stable = state == test_evidence.key(ROOT)success = passed and stableslowest = sorted(timings, reverse=True)[:20]diff --git a/tests/test_test_evidence.py b/tests/test_test_evidence.pyindex ab424d056..cce121215 100644--- a/tests/test_test_evidence.py+++ b/tests/test_test_evidence.py@@ -9,7 +9,7 @@ import tempfileimport threadingimport unittestfrom concurrent.futures import ThreadPoolExecutor-from contextlib import ExitStack, redirect_stderr, redirect_stdout+from contextlib import redirect_stderr, redirect_stdoutfrom pathlib import Pathfrom unittest import mock@@ -19,78 +19,31 @@ from scripts import test_runner as runnerfrom support.gitrepo import seed_repository-def holding(paths) -> ExitStack:- """同时占住给定的每个槽位,扮演别的会话。"""- stack = ExitStack()- for path in paths:- stack.enter_context(evidence.held(path))- return stack-class HeavyTaskSlotTests(unittest.TestCase):- """机器级重任务槽位:别的会话占着的槽位,本轮分片不能再用。"""-- def setUp(self):- temporary = tempfile.TemporaryDirectory()- self.addCleanup(temporary.cleanup)- self.slots = Path(temporary.name)-- def launcher(self):- live, peak, commands = set(), [0], []-+class ParallelShardTests(unittest.TestCase):+ def test_requested_parallelism_has_no_machine_slot_ceiling(self):+ live, peak = set(), [0]class Shard:def __init__(self, command):report = Path(command[command.index('--timings') + 1])- report.write_text(json.dumps({'success': True, 'count': 1, 'timings': []}),- encoding='utf-8')+ report.write_text(json.dumps({'success': True, 'count': 1, 'timings': []}), encoding='utf-8')self.polls, self.returncode = 0, Nonelive.add(self)peak[0] = max(peak[0], len(live))-def poll(self):self.polls += 1if self.polls >= 2:live.discard(self)self.returncode = 0return self.returncode-- def spawn(command, *, stdout, stderr, cwd):- commands.append(command)+ def spawn(command, **kwargs):return Shard(command)- return spawn, peak, commands-- def test_slots_held_elsewhere_leave_this_run_one_shard_at_a_time(self):- spawn, peak, commands = self.launcher()- busy = runner.heavy_slot_paths(self.slots)[1:]- with holding(busy), redirect_stdout(io.StringIO()), \- mock.patch.dict(os.environ, {'PEACH_TEST_RESOURCE_RUNNER': str(self.slots / 'gone.py')}):- passed, count, _ = runner.run_shards(('checks',), jobs=runner.HEAVY_TASK_SLOTS, shard_count=3,- spawn=spawn, slots=self.slots)- self.assertTrue(passed)- self.assertEqual(count, 3)- self.assertEqual(peak[0], 1)- for command in commands:- self.assertEqual(command[:2], [sys.executable, str(runner.ROOT / 'scripts' / 'test_runner.py')])-- def test_free_slots_let_the_run_use_every_one(self):- spawn, peak, _ = self.launcher()with redirect_stdout(io.StringIO()):- passed, _, _ = runner.run_shards(('checks',), jobs=runner.HEAVY_TASK_SLOTS,- shard_count=2 * runner.HEAVY_TASK_SLOTS,- spawn=spawn, slots=self.slots)+ passed, count, _ = runner.run_shards(('checks',), jobs=6, shard_count=12, spawn=spawn)self.assertTrue(passed)- self.assertEqual(peak[0], runner.HEAVY_TASK_SLOTS)- for path in runner.heavy_slot_paths(self.slots):- with evidence.held(path):- pass # 分片结束后每个槽位都还回去了,才能不等待地再拿到-- def test_all_slots_busy_times_out_without_starting_a_shard(self):- spawn, _, commands = self.launcher()- with holding(runner.heavy_slot_paths(self.slots)), redirect_stdout(io.StringIO()):- with self.assertRaises(evidence.Timeout):- runner.run_shards(('checks',), jobs=2, shard_count=2, spawn=spawn,- slots=self.slots, slot_wait=0)- self.assertEqual(commands, [])+ self.assertEqual(count, 12)+ self.assertEqual(peak[0], 6)class VerificationTests(unittest.TestCase):@@ -358,15 +311,6 @@ class VerificationTests(unittest.TestCase):self.assertIn("scope full", reader.result(timeout=5))self.assertFalse(note.exists())- def test_busy_heavy_slots_stop_an_unsharded_run_before_any_test(self):- output = io.StringIO()- with holding(runner.heavy_slot_paths(evidence.evidence_dir(self.repo))), \- redirect_stderr(io.StringIO()), redirect_stdout(output), \- mock.patch.object(runner, "ROOT", self.repo), \- mock.patch.object(runner, "build_suite", side_effect=AssertionError("不该开跑")):- self.assertEqual(runner.main(["--scope", "checks", "--lock-timeout", "0"]), 2)- self.assertIn("测试重任务槽位一直被占用", output.getvalue())- self.assertFalse(evidence.covers(evidence.read(self.repo, evidence.key(self.repo)), ("checks",)))def test_the_waiting_runner_names_the_holder_of_the_full_suite_lock(self):lock = evidence.evidence_dir(self.repo) / "full-suite.lock"@@ -542,7 +486,7 @@ class VerificationTests(unittest.TestCase):mock.patch.object(runner, "resolve_auto_scope", return_value=(("full",), "fixture")), \mock.patch.object(runner, "run_local_suite", return_value=(True, 1, [])) as run:self.assertEqual(runner.main(["--scope", "auto"]), 0)- run.assert_called_once_with(("full",), 1, slot_wait=1800)+ run.assert_called_once_with(("full",), 1)def test_baseline_does_not_expand_a_small_requested_scope(self):self.certify(self.repo, ("full",))@@ -600,6 +544,108 @@ class VerificationTests(unittest.TestCase):self.assertEqual(runner.main(["--scope", "checks"]), 4)self.assertFalse(evidence.covers(evidence.read(self.repo, evidence.key(self.repo)), ("checks",)))+ def test_partial_baseline_preserves_unaffected_scopes_and_their_age(self):+ original = self.certify(self.repo, ("catalog", "metadata", "web"))+ stamps = evidence.read(self.repo, original)["validated"]+ changed = self.repo / "frontend/src/react/example.tsx"+ changed.parent.mkdir(parents=True)+ changed.write_text("export const value = 1;\n", encoding="utf-8")+ with redirect_stdout(io.StringIO()), mock.patch.object(runner, "ROOT", self.repo), \+ mock.patch.object(runner, "environment_preflight"), \+ mock.patch.object(runner, "resolve_auto_scope", return_value=(("catalog", "metadata", "web"), "fixture")), \+ mock.patch.object(runner, "run_local_suite", return_value=(True, 1, [])) as run:+ self.assertEqual(runner.main(["--scope", "auto"]), 0)+ run.assert_called_once_with(("web",), 1)+ record = evidence.read(self.repo, evidence.key(self.repo))+ self.assertTrue(evidence.covers(record, ("catalog", "metadata", "web")))+ self.assertNotIn("full", record["validated"])+ self.assertEqual(record["validated"]["catalog"], stamps["catalog"])+ self.assertEqual(record["validated"]["metadata"], stamps["metadata"])++ def test_partial_baseline_cannot_cover_shared_changes_or_full_validation(self):+ self.certify(self.repo, ("catalog", "web"))+ changed = self.repo / "scripts/test_runner.py"+ changed.parent.mkdir(parents=True)+ changed.write_text("# fixture\n", encoding="utf-8")+ with redirect_stdout(io.StringIO()), mock.patch.object(runner, "ROOT", self.repo), \+ mock.patch.object(runner, "environment_preflight"), \+ mock.patch.object(runner, "resolve_auto_scope", return_value=(("full",), "fixture")), \+ mock.patch.object(runner, "run_local_suite", return_value=(True, 1, [])) as run:+ self.assertEqual(runner.main(["--scope", "auto"]), 0)+ run.assert_called_once_with(("full",), 1)++ def test_same_state_only_runs_missing_scopes_and_failed_state_runs_all(self):+ self.certify(self.repo, ("catalog",))+ with redirect_stdout(io.StringIO()), mock.patch.object(runner, "ROOT", self.repo), \+ mock.patch.object(runner, "environment_preflight"), \+ mock.patch.object(runner, "resolve_auto_scope", return_value=(("catalog", "web"), "fixture")), \+ mock.patch.object(runner, "run_local_suite", return_value=(True, 1, [])) as run:+ self.assertEqual(runner.main(["--scope", "auto"]), 0)+ run.assert_called_once_with(("web",), 1)+ run.reset_mock()+ self.certify(self.repo, ("full",), success=False)+ self.assertEqual(runner.main(["--scope", "auto"]), 0)+ run.assert_called_once_with(("catalog", "web"), 1)++ def test_partial_baseline_requires_live_timestamps_and_matching_environment(self):+ original = self.certify(self.repo, ("catalog",))+ path = evidence.evidence_dir(self.repo) / f"{original}.json"+ record = json.loads(path.read_text(encoding="utf-8"))+ for changes in ({"validated": {"catalog": 0}}, {"environment": "another"}):+ path.write_text(json.dumps({**record, **changes}), encoding="utf-8")+ self.assertEqual(list(evidence.baselines(self.repo, evidence.inputs(self.repo), partial=True)), [])++ def test_failed_domain_preserves_other_domains_and_requires_its_own_revalidation(self):+ self.certify(self.repo, ("catalog", "metadata", "web"))+ state = evidence.key(self.repo)+ stamps = evidence.read(self.repo, state)["validated"]+ self.certify(self.repo, ("web",), success=False)+ failed = evidence.read(self.repo, state)+ self.assertTrue(evidence.covers(failed, ("catalog", "metadata")))+ self.assertFalse(evidence.covers(failed, ("web",)))+ with redirect_stdout(io.StringIO()), mock.patch.object(runner, "ROOT", self.repo), \+ mock.patch.object(runner, "environment_preflight"), \+ mock.patch.object(runner, "resolve_auto_scope", return_value=(("catalog", "metadata", "web"), "fixture")), \+ mock.patch.object(runner, "run_local_suite", return_value=(True, 1, [])) as run:+ self.assertEqual(runner.main(["--scope", "auto"]), 0)+ run.assert_called_once_with(("web",), 1)+ self.assertEqual(evidence.read(self.repo, state)["validated"]["catalog"], stamps["catalog"])++ def test_success_of_another_domain_cannot_restore_a_failed_domain_from_an_older_baseline(self):+ self.certify(self.repo, ("full",))+ (self.repo / "README.md").write_text("fixture difference\n", encoding="utf-8")+ self.certify(self.repo, ("catalog", "web"))+ self.certify(self.repo, ("web",), success=False)+ self.certify(self.repo, ("checks",))+ record = evidence.read(self.repo, evidence.key(self.repo))+ self.assertEqual(record["failed_scopes"], ["web"])+ with redirect_stdout(io.StringIO()), mock.patch.object(runner, "ROOT", self.repo), \+ mock.patch.object(runner, "environment_preflight"), \+ mock.patch.object(runner, "resolve_auto_scope", return_value=(("checks", "catalog", "web"), "fixture")), \+ mock.patch.object(runner, "run_local_suite", return_value=(True, 1, [])) as run:+ self.assertEqual(runner.main(["--scope", "auto"]), 0)+ run.assert_called_once_with(("web",), 1)++ def test_focus_never_publishes_evidence_and_formal_run_rejects_focus_environment(self):+ selector = self.repo / "tests/test_focus_sample.py"+ selector.parent.mkdir(parents=True)+ selector.write_text("import unittest\nclass Sample(unittest.TestCase):\n def test_value(self): self.assertEqual(1,1)\n", encoding="utf-8")+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()), \+ mock.patch.object(runner, "ROOT", self.repo), mock.patch.object(evidence, "write") as write:+ self.assertEqual(runner.main(["--focus", "test_focus_sample"]), 0)+ write.assert_not_called()+ with mock.patch.dict(os.environ, {"PEACH_E2E_FILES": "[]"}):+ with self.assertRaises(SystemExit) as stopped:+ runner.main(["--scope", "checks"])+ self.assertEqual(stopped.exception.code, 2)++ def test_focus_rejects_missing_files_and_path_escape(self):+ from scripts import test_focus+ for selector in ("test_missing", "frontend/e2e/../../other.test.ts", "scripts/test_runner.py"):+ with self.subTest(selector=selector), self.assertRaises(ValueError):+ test_focus.selection(self.repo, [selector])++if __name__ == "__main__":unittest.main()diff --git a/tests/test_test_planning.py b/tests/test_test_planning.pyindex 4a866d209..b2203e42d 100644--- a/tests/test_test_planning.py+++ b/tests/test_test_planning.py@@ -207,7 +207,7 @@ class TestPlanningTests(unittest.TestCase):launched, spawn = launcher(failing=None)with contextlib.redirect_stdout(io.StringIO()) as output:passed, count, timings = runner.run_shards(('follow', 'tooling'), jobs=2, shard_count=3,- spawn=spawn, slots=Path(slots.name))+ spawn=spawn)self.assertTrue(passed)self.assertEqual(count, 10 + 11 + 12)self.assertEqual(sorted(name for _, name in timings), ['test_0', 'test_1', 'test_2'])@@ -222,13 +222,13 @@ class TestPlanningTests(unittest.TestCase):_, spawn = launcher(failing=2)with contextlib.redirect_stdout(io.StringIO()):passed, count, _ = runner.run_shards(('checks',), jobs=4, shard_count=3,- spawn=spawn, slots=Path(slots.name))+ spawn=spawn)self.assertFalse(passed)self.assertEqual(count, 10 + 11 + 12, '失败那片的用例数也要算进总数,记录里的 count 才是实跑数')def test_jobs_accepts_auto_or_a_positive_integer(self):self.assertEqual(runner.resolve_jobs('3'), 3)- self.assertTrue(1 <= runner.resolve_jobs('auto') <= runner.MAX_JOBS)+ self.assertTrue(1 <= runner.resolve_jobs('auto') <= runner.DEFAULT_JOBS)for bad in ('0', '-1', 'many'):with self.subTest(bad=bad), self.assertRaises(runner.argparse.ArgumentTypeError):runner.resolve_jobs(bad)diff --git a/tests/test_web_e2e.py b/tests/test_web_e2e.pyindex d9cb98177..3bfc48218 100644--- a/tests/test_web_e2e.py+++ b/tests/test_web_e2e.py@@ -89,11 +89,13 @@ def refuse_network(*args, **kwargs):raise AssertionError("演示库的 process 不应向任何外部来源发请求")-#: 断言帧数或动画中途位置的用例文件。别的文件并发跑时 CPU 被几个浏览器分走,-#: 300ms 的过渡里出不了中间帧,就会误报「主线程整段被占住」或「瞬移过去」。-CPU_SENSITIVE_SUITES = frozenset({+#: 测量动画中间帧、密度切换和等待态替换的文件。独立测量这些时序,避免其他浏览器+#: 的渲染与共享设置请求影响取值时刻;其余文件保留并行。+TIMING_SENSITIVE_SUITES = frozenset({"e2e/sidebar-motion.test.ts", # 开合过渡 300ms 里的帧数"e2e/sidebar.test.ts", # 当前项那块玻璃 900ms 内要经过中间位置+ "e2e/design-cards.test.ts", # 紧凑密度切换的即时样式+ "e2e/design-follow-alignment.test.ts", # 等待标题与内容标题的替换})@@ -117,16 +119,21 @@ def e2e_command(node: str, concurrency: int, files: tuple[str, ...]) -> list[strreturn [node, "--test", f"--test-concurrency={concurrency}", "--test-reporter=tap", *files]-def e2e_batches(frontend: Path, concurrency: int) -> tuple[tuple[tuple[str, ...], int], ...]:+def e2e_batches(frontend: Path, concurrency: int, selected: tuple[str, ...] = ()) -> tuple[tuple[tuple[str, ...], int], ...]:"""把 `frontend/e2e` 下全部 `*.test.ts`(含子目录)分批,每批带自己的并发数,限时 600 秒。- 并发时分两批:其余文件一次并发跑完,CPU 敏感的文件随后串行。并发为 1 时整轮是串行的,+ 并发时分两批:其余文件一次并发跑完,时序敏感的文件随后串行。并发为 1 时整轮是串行的,按设计决定、交互回归与路由冒烟分组,每批最多 12 个文件。"""files = tuple(sorted(path.relative_to(frontend).as_posix()for path in (frontend / "e2e").rglob("*.test.ts")))if not files:raise AssertionError("frontend/e2e 没有浏览器用例")+ if selected:+ missing = set(selected) - set(files)+ if missing:+ raise AssertionError(f"浏览器用例不存在:{sorted(missing)}")+ files = tuple(path for path in files if path in selected)if concurrency == 1:design = tuple(path for path in files if path.startswith("e2e/design-"))routes = tuple(path for path in files if path == "e2e/smoke.test.ts")@@ -134,7 +141,7 @@ def e2e_batches(frontend: Path, concurrency: int) -> tuple[tuple[tuple[str, ...]return tuple((group[start:start + SERIAL_E2E_BATCH_FILES], 1)for group in (design, interactions, routes)for start in range(0, len(group), SERIAL_E2E_BATCH_FILES))- sensitive = tuple(path for path in files if path in CPU_SENSITIVE_SUITES)+ sensitive = tuple(path for path in files if path in TIMING_SENSITIVE_SUITES)shared = tuple(path for path in files if path not in sensitive)return tuple(batch for batch in ((shared, concurrency), (sensitive, 1)) if batch[0])@@ -301,26 +308,25 @@ class WebE2ESmokeTests(unittest.TestCase):for stale in BROWSER_LOGS.glob("batch-*.tap"):stale.unlink()concurrency = e2e_concurrency(os.environ.get("PEACH_E2E_CONCURRENCY", "").strip())- for index, (batch, lanes) in enumerate(e2e_batches(FRONTEND, concurrency), 1):+ selected = tuple(json.loads(os.environ.get("PEACH_E2E_FILES", "[]")))+ for index, (batch, lanes) in enumerate(e2e_batches(FRONTEND, concurrency, selected), 1):log_path = BROWSER_LOGS / f"batch-{index}.tap"- with self.subTest(files=batch, concurrency=lanes):- try:- completed = subprocess.run(- e2e_command(self.node, lanes, batch),- capture_output=True, text=True, encoding="utf-8", errors="replace",- cwd=str(FRONTEND), env=env, timeout=E2E_SECONDS, check=False)- except subprocess.TimeoutExpired as expired:- # TAP 行指出超时前的最后一条用例。- partial = expired.stdout or ""- if isinstance(partial, bytes):- partial = partial.decode("utf-8", errors="replace")- log_path.write_text(partial, encoding="utf-8")- self.fail(f"本批 {E2E_SECONDS} 秒内没跑完,完整日志:{log_path}\n{partial[-4000:]}")- output = f"{completed.stdout}\n{completed.stderr}"- log_path.write_text(output, encoding="utf-8")- self.assertEqual(completed.returncode, 0, f"{output}\n--- serve.log ---\n{self._server_log()}")- self.assertRegex(output, r"# pass [1-9]\d*", output)- self.assertRegex(output, r"# fail 0\b", output)+ try:+ completed = subprocess.run(+ e2e_command(self.node, lanes, batch),+ capture_output=True, text=True, encoding="utf-8", errors="replace",+ cwd=str(FRONTEND), env=env, timeout=E2E_SECONDS, check=False)+ except subprocess.TimeoutExpired as expired:+ partial = expired.stdout or ""+ if isinstance(partial, bytes):+ partial = partial.decode("utf-8", errors="replace")+ log_path.write_text(partial, encoding="utf-8")+ self.fail(f"本批 {E2E_SECONDS} 秒内没跑完,完整日志:{log_path}\n{partial[-4000:]}")+ output = f"{completed.stdout}\n{completed.stderr}"+ log_path.write_text(output, encoding="utf-8")+ self.assertEqual(completed.returncode, 0, f"{output}\n--- serve.log ---\n{self._server_log()}")+ self.assertRegex(output, r"# pass [1-9]\d*", output)+ self.assertRegex(output, r"# fail 0\b", output)class SetupE2ETests(unittest.TestCase):@@ -480,12 +486,12 @@ class MissingPrerequisiteTests(unittest.TestCase):flattened = tuple(path for files, _ in batches for path in files)self.assertCountEqual(flattened, self.PATHS)- def test_concurrent_run_puts_cpu_sensitive_suites_in_a_trailing_serial_batch(self):+ def test_concurrent_run_puts_timing_sensitive_suites_in_a_trailing_serial_batch(self):batches = self.batches_for(4)self.assertEveryFileOnce(batches)(shared, lanes), (serial, serial_lanes) = batchesself.assertEqual(lanes, 4)- self.assertEqual(serial, ("e2e/sidebar-motion.test.ts",))+ self.assertEqual(serial, ("e2e/design-cards.test.ts", "e2e/sidebar-motion.test.ts"))self.assertEqual(serial_lanes, 1)self.assertIn("e2e/nested/feature.test.ts", shared)@@ -513,6 +519,36 @@ class MissingPrerequisiteTests(unittest.TestCase):with self.assertRaisesRegex(AssertionError, "没有浏览器用例"):e2e_batches(Path(folder).resolve(), 4)+ def test_focused_batches_only_collect_named_browser_files(self):+ with tempfile.TemporaryDirectory() as folder:+ frontend = Path(folder).resolve()+ for name in self.PATHS:+ path = frontend / name+ path.parent.mkdir(parents=True, exist_ok=True)+ path.touch()+ chosen = ("e2e/nested/feature.test.ts",)+ self.assertEqual(e2e_batches(frontend, 1, chosen), ((chosen, 1),))+ with self.assertRaisesRegex(AssertionError, "不存在"):+ e2e_batches(frontend, 1, ("e2e/missing.test.ts",))++ def test_failed_browser_batch_stops_following_batches_and_keeps_its_log(self):+ with tempfile.TemporaryDirectory() as folder:+ log_root = Path(folder).resolve()+ case = WebE2ESmokeTests("test_every_route_holds_the_layout_and_runtime_invariants")+ case.origin, case.item, case.chrome, case.node = "http://fixture", 1, "chrome", "node"+ failed = subprocess.CompletedProcess([], 1, "# pass 1\n# fail 1\n", "failure")+ batches = ((("e2e/first.test.ts",), 1), (("e2e/second.test.ts",), 1))+ with mock.patch.dict(os.environ, {"PEACH_E2E_FILES": "[]"}), \+ mock.patch(__name__ + ".BROWSER_LOGS", log_root), \+ mock.patch(__name__ + ".e2e_batches", return_value=batches), \+ mock.patch.object(case, "_server_log", return_value="serve fixture"), \+ mock.patch("subprocess.run", return_value=failed) as run:+ with self.assertRaises(AssertionError):+ case.test_every_route_holds_the_layout_and_runtime_invariants()+ self.assertEqual(run.call_count, 1)+ self.assertIn("# fail 1", (log_root / "batch-1.tap").read_text(encoding="utf-8"))+ self.assertFalse((log_root / "batch-2.tap").exists())+def test_concurrency_is_serial_on_ci_bounded_locally_and_overridable(self):local = {key: value for key, value in os.environ.items() if key != "GITHUB_ACTIONS"}with mock.patch.dict(os.environ, local, clear=True):