Peach: Local-first video metadata scraper and media manager.
fix(testing): 补齐直接消费者并缩小文档选测
longmeidaoa69d5d1cf57b
diff --git a/.github/workflows/test.yml b/.github/workflows/test.ymlindex a9d6c8d25..41ccbe9b5 100644--- a/.github/workflows/test.yml+++ b/.github/workflows/test.yml@@ -38,6 +38,7 @@ jobs:runs-on: ubuntu-latesttimeout-minutes: 10outputs:+ base: ${{ steps.plan.outputs.base }}matrix: ${{ steps.plan.outputs.matrix }}wheel_matrix: ${{ steps.plan.outputs.wheel_matrix }}wide: ${{ steps.plan.outputs.wide }}@@ -59,6 +60,7 @@ jobs:id: planenv:EVENT_NAME: ${{ github.event_name }}+ GH_TOKEN: ${{ github.token }}BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before || github.sha }}run: uv run --locked --python 3.14 scripts/ci_plan.py --event "$EVENT_NAME" --base "$BASE_SHA"@@ -135,7 +137,7 @@ jobs:fail-fast: falsematrix: ${{ fromJSON(needs.plan.outputs.matrix) }}env:- BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before || github.sha }}+ BASE_SHA: ${{ needs.plan.outputs.base }}steps:- uses: actions/checkout@v7with:diff --git a/README.md b/README.mdindex c09674188..d1f46d125 100644--- a/README.md+++ b/README.md@@ -6,6 +6,13 @@ A local-first video metadata scraper and media manager.[Website](https://peach.video) · [Download](https://peach.video/#download) · [Live demo](https://demo.peach.video) · [Documentation](#documentation) · [简体中文](README.zh-CN.md)+[](https://gitgud.io/peach-mitao/peach/-/releases)+[](https://gitgud.io/peach-mitao/peach/-/pipelines?ref=master)+[](LICENSE)+[](docs/TESTING_DESKTOP.md)+[](docs/OPERATIONS.md#macos-独立测试包)+[](#license)+## Screenshots[](https://peach.video/assets/screenshots/home-wide-20261025-2.png)diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 093277910..9d02fdfaa 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -6,6 +6,13 @@[官网](https://peach.video) · [下载](https://peach.video/#download) · [在线演示](https://demo.peach.video) · [文档](#文档) · [English](README.md)+[](https://gitgud.io/peach-mitao/peach/-/releases)+[](https://gitgud.io/peach-mitao/peach/-/pipelines?ref=master)+[](LICENSE)+[](docs/TESTING_DESKTOP.md)+[](docs/OPERATIONS.md#macos-独立测试包)+[](#许可证)+## 截图[](https://peach.video/assets/screenshots/home-wide-20261025-2.png)diff --git a/docs/TESTING.md b/docs/TESTING.mdindex 197144036..f842af497 100644--- a/docs/TESTING.md+++ b/docs/TESTING.md@@ -82,7 +82,7 @@ Python 静态检查使用开发依赖 Ruff,随每个正式测试域扫描全| --- | --- || 本机修改 | 正式入口默认 `auto`,按影响域取并集;同代码、环境与范围的有效记录可复用 || 普通 PR | Python 3.14:macOS 与 Windows 均按影响域验证 |-| 普通主线提交 | Python 3.14:macOS、Windows、前端、浏览器与 wheel 完整回归 |+| 普通主线提交 | Python 3.14:相对最近成功且属于当前祖先的主线 Test,选择 macOS、Windows 的影响域及适用前端、浏览器与 wheel || 实际依赖、迁移、共享测试设施、未知影响面 | Windows 与 macOS 的 Python 3.14 全量 || 手动 CI | 完整系统矩阵 || wheel | Windows 与 macOS 各一次 Python 3.14 独立最小安装 |@@ -94,7 +94,7 @@ Test 工作流的 `web-bundle` 在 Ubuntu 上统一执行 tsc、lint、Vitest、浏览器用例由 `web-e2e` 的六个 Windows runner 分担,每片有自己的服务、演示库与日志。`ci_plan.py` 按 `ci-browser-timings.json` 的实测秒数分配文件,新文件使用默认权重;每个文件恰好执行一次。每片经项目入口的 `-Focus` 运行分配的浏览器文件,首启文件始终归首次设置服务。它装 Node 24、前端依赖、ffmpeg,并经 `PEACH_E2E_CHROME` 指定 Chrome。本机浏览器入口与并发语义保持完整。-PR 计划按改动选择前端、vendor、wheel 与浏览器任务,文档 PR 只执行适用检查;主线、依赖、未知影响与手动验证包含全部任务。`frontend-ready` 汇总所选前端检查,失败时不启动后续完整回归;未选择前端任务的计划可正常执行。产物差异以文件统计显示。`verified` 根据计划核对必需任务,缺失、失败、取消及必需任务跳过均判失败。Actions 工作流本身由固定版 actionlint 检查语法、表达式、依赖与脚本。PR 更新取消同 PR 的过期运行,主线 Test 按提交各自保留结果。+PR 与普通主线计划按改动选择前端、vendor、wheel 与浏览器任务,文档只执行适用检查;实际依赖、未知影响、无已验证基线与手动验证包含全部任务。`frontend-ready` 汇总所选前端检查,失败时不启动后续完整回归;未选择前端任务的计划可正常执行。产物差异以文件统计显示。`verified` 根据计划核对必需任务,缺失、失败、取消及必需任务跳过均判失败。Actions 工作流本身由固定版 actionlint 检查语法、表达式、依赖与脚本。PR 更新取消同 PR 的过期运行,主线 Test 按提交各自保留结果。GitHub 的计划任务与 Python 任务使用同一个已验证基线,不以最近一次失败的推送提交代替。Python 分片上传完整测试输出;浏览器分片上传 TAP、服务日志及已脱敏网络日志,保留 14 天。npm 审计遇到 high 或 critical 漏洞直接失败;只有临时网络错误最多请求三次,在前两次失败后分别等待 15 与 30 秒,未知响应不当成通过。@@ -250,7 +250,9 @@ GitGud 的三平台验证使用正式恢复入口,通过 GitLab 原生缓存新增、删除文件按所属功能域选测;已有文件的执行权限变化和符号链接保持 `full`。-`src/peach/` 下按名字推不出测试文件的模块,取直接导入它的测试所在的域,并上直接导入它的源码文件按同一套规则推出的域;互相导入的一组模块合起来算。导入者推不出域、谁都不导入它,或共享测试设施 `tests/support` 用到它时仍 `full`。不沿导入链一路扩散:函数里的延迟导入把几乎所有模块连成一团,传递闭包等于全量。随应用分发的 `resources/` 按加载它的模块与打包面选域;`.gitlab-ci.yml` 与 `MANIFEST.in` 在本机选 `packaging` 与 `tooling`(主线流水线改 `.gitlab-ci.yml` 时三平台仍跑全量);只登记在 `core` 或 `packaging` 的测试文件改动时跑登记它的那个域。+`src/peach/` 的已知模块合并直接导入它的测试所在域,名称或显式映射不排除直接消费者。按名字推不出测试文件的模块,还并上直接导入它的源码文件按同一套规则推出的域;互相导入的一组模块合起来算。导入者推不出域、谁都不导入它,或未知模块被共享测试设施 `tests/support` 使用时仍 `full`。不沿导入链一路扩散:函数里的延迟导入把几乎所有模块连成一团,传递闭包等于全量。随应用分发的 `resources/` 按加载它的模块与打包面选域;`.gitlab-ci.yml` 与 `MANIFEST.in` 在本机选 `packaging` 与 `tooling`(主线流水线改 `.gitlab-ci.yml` 时三平台仍跑全量);只登记在 `core` 或 `packaging` 的测试文件改动时跑登记它的那个域。++README 的 Python 下限和双语入口由 checks 的安装契约检查,普通文档不选择整个 tooling。静态文件输入识别以仓库根及其别名为依据,临时夹具的同名写入不属于仓库读取。缺失文件不进入当前快照,删除由前后文件集合识别,暂存或提交相同删除不会改变内容证明。运行中输入改变时,无论该批次是否全部通过,都按差异保留未受影响的成功结果和原时间;退出 `4`,随后 `auto` 补齐缺少项。独立 Python 测试文件的逻辑变化使该文件、直接或间接导入它的测试及公共门槛失效;浏览器测试文件变化使该文件及相应容器检查失效。共享设施、未知范围、执行模式或环境变化仍按完整影响范围重新验证。@@ -258,7 +260,7 @@ GitGud 的三平台验证使用正式恢复入口,通过 GitLab 原生缓存测试记录格式升级时,主检出的入口可能无法识别新格式。先在工作树通过 `ready`,再由主检出调用该工作树中已验收的 `scripts/agent_worktree.py`,用 `--repo` 指定主检出并执行 `integrate`。该方式仍检查测试记录、README 声明、目标分支和集成锁;不要手工改写记录或跳过门槛。集成后主检出使用同一版本的入口。-PR 的浏览器 CI 根据界面、Web API、认证与浏览器用例选择;普通后端单测不单独触发浏览器任务。工作流按职责选测,发布工作流触发打包验证,看板等管理工作流只触发工具检查。主线推送与手动完整验证继续覆盖全部 CI 任务。+PR 与普通主线的浏览器 CI 根据界面、Web API、认证与浏览器用例选择;普通后端单测不单独触发浏览器任务。工作流按职责选测,发布工作流触发打包验证,看板等管理工作流只触发工具检查。无可用基线、未知影响与手动完整验证覆盖全部 CI 任务,发布演练和制品验收按其独立门槛执行。## 记录的环境身份diff --git a/docs/adr/0128-test-selection-contracts-and-verified-mainline.md b/docs/adr/0128-test-selection-contracts-and-verified-mainline.mdnew file mode 100644index 000000000..962f921d5--- /dev/null+++ b/docs/adr/0128-test-selection-contracts-and-verified-mainline.md@@ -0,0 +1,23 @@+# ADR-0128:按直接消费者与已验证主线选择回归++- 状态:已采纳+- 日期:2026-10-27+- 关系:将 ADR-0119 的已验证基线用于 GitHub Test;不改变 ADR-0127 的发行制品验收与晋级++## 背景++README 修改固定选择整个 tooling 域,双语文件改名还需修改调度器并触发全量。运行模块按名称取得功能域后,不再补入直接测试消费者,导致 HTTP 逻辑变化选不到已有的下载流量统计回归。未提交的删除状态在提交后退出快照,也会使内容相同的已验证结果无法直接交付。++## 决策++1. README 的 Python 下限与双语入口由 checks 中的安装契约核对。文档改动不选择整个 tooling;工具实现与工作流仍按其真实影响选测。+2. 已知运行模块的功能域与直接导入它的测试所属域取并集;未知范围、依赖、迁移、共享验证设施和执行模式变化保留全量。不无界遍历所有间接源码导入。+3. 测试文件的静态路径依赖以仓库根和已知别名为依据,不把临时仓库的同名写入当成真实输入。缺失文件不进入当前内容快照,删除仍由前后文件集合差异识别。+4. 正式入口不取得机器级资源锁。保留仓库全量证明与 Git 集成互斥、单轮分片及容器阶段,保护代码一致性与其他任务。+5. GitHub push 从最近成功且属于当前提交祖先的主线 Test 取基线,并把同一基线传给全部选测任务。失败后尚未验证的区间继续纳入差异;取证失败、无可用基线、未知影响和手动验证均全量。PR 继续相对其基线选测;发布演练与制品验收不缩减。++## 后果++普通文档提交仍检查文档契约、仓库规范和链接,不运行无关媒体与浏览器回归。共享模块可能选择更多业务域,这是补齐真实消费者的必要成本。直接导入分析不替代动态调用的显式登记;后续新增动态消费者须在对应回归中核对选测。++测试框架自身本批仍须全量验证;README 的可视化确认和提交声明继续适用。已公开提交保留历史,不为补充格式或来源关联改写远端。diff --git a/scripts/adopt_dependency_bump.py b/scripts/adopt_dependency_bump.pyindex c5644d17d..e3fac9999 100644--- a/scripts/adopt_dependency_bump.py+++ b/scripts/adopt_dependency_bump.py@@ -248,6 +248,7 @@ def commit_message(key: str, versions: list[str], pr: str | None,"所以接管到本地分支。")return (f"chore(deps): 接管 {recipe['label']} 的升级\n\n{why}\n\n"+ ("升级:" + "、".join(versions) + "\n\n" if versions else "")+ + (f"Refs #{pr}\n\n" if pr else "")+ "README-Impact: none; 依赖版本与派生产物,README 不涉及。\n"+ f"Co-Authored-By: {signature}\n")diff --git a/scripts/check_readme_impact.py b/scripts/check_readme_impact.pyindex 7676f720c..03e67e1b5 100644--- a/scripts/check_readme_impact.py+++ b/scripts/check_readme_impact.py@@ -3,6 +3,8 @@from __future__ import annotationsimport subprocess+import re+import tomllibfrom pathlib import PathREADMES = {"README.md", "README.zh-CN.md"}@@ -15,6 +17,21 @@ FILES = {}+def installation_contracts(repo: Path) -> list[str]:+ """README 的 Python 下限与语言入口须和安装声明一致。"""+ project = tomllib.loads((repo / 'pyproject.toml').read_text(encoding='utf-8'))['project']+ floor = project['requires-python'].removeprefix('>=')+ problems = []+ for name in sorted(READMES):+ text = (repo / name).read_text(encoding='utf-8')+ if not re.search(rf'\bPython {re.escape(floor)}(?:\+| or newer| 或更高)', text):+ problems.append(f'{name}: Python 下限须为 {floor}')+ counterpart, = READMES - {name}+ if counterpart not in re.findall(r'\]\(([^)\s]+)\)', text):+ problems.append(f'{name}: 缺少语言入口 {counterpart}')+ return problems++#: 已经推到 GitHub 的提交。它的署名与主题改不了:改写 hash 只能强推覆盖远端。PUBLISHED_REF = "origin/master"diff --git a/scripts/ci_plan.py b/scripts/ci_plan.pyindex a5477f048..7e3da38d6 100644--- a/scripts/ci_plan.py+++ b/scripts/ci_plan.py@@ -1,4 +1,4 @@-"""按提交影响生成 CI 矩阵;主线全量、Windows 系统回归与独立安装共同验收。"""+"""按已验证基线与提交影响生成 CI 矩阵,未知范围与手动验证使用全量。"""from __future__ import annotationsimport argparse@@ -72,7 +72,7 @@ def browser_input(path: str) -> bool:def plan(event: str, paths: list[str], contents: dict | None = None) -> dict:from . import test_runner as runnerscopes, _ = runner.scopes_for_changes(paths, contents=contents)- wide = event in {"push", "workflow_dispatch"} or "full" in scopes+ wide = event == "workflow_dispatch" or "full" in scopesrows = []for system in ("macos-latest", "windows-latest"):scope = "full" if wide else "auto"@@ -102,6 +102,23 @@ def plan(event: str, paths: list[str], contents: dict | None = None) -> dict:"vendor": vendor, "wheel": wheel, "required_jobs": required}+def github_verified_base(root: Path) -> str:+ """最近成功的主线 Test 必须属于当前祖先,失败区间继续包含在差异内。"""+ from .ci_scope import ancestor_of_head, verified_base+ repo = os.environ['GITHUB_REPOSITORY']+ payload = subprocess.check_output(+ ['gh', 'api', f'repos/{repo}/actions/workflows/test.yml/runs?branch=master&event=push&status=success&per_page=20'],+ text=True, encoding='utf-8')+ runs = json.loads(payload)['workflow_runs']+ rows = [{'sha': run['head_sha'], 'status': 'success'} for run in runs+ if run.get('conclusion') == 'success' and run.get('event') == 'push' and run.get('head_branch') == 'master']+ current = subprocess.check_output(['git', '-C', str(root), 'rev-parse', 'HEAD'], text=True).strip()+ base = verified_base(rows, current, ancestor_of_head(root))+ if base is None:+ raise ValueError('最近成功的主线 Test 中没有当前提交的祖先')+ return base++def main() -> None:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("--event", choices=("push", "pull_request", "workflow_dispatch"))@@ -117,12 +134,17 @@ def main() -> None:parser.error("生成计划需要 --event 与 --base")from . import test_runner as runnerroot = Path(__file__).resolve().parents[1]+ base = args.basetry:- paths = runner.changed_files(root, args.base)- result = plan(args.event, paths, runner.changed_contents(root, args.base, paths))- except subprocess.CalledProcessError:+ if args.event == 'push':+ base = github_verified_base(root)+ paths = runner.changed_files(root, base)+ result = plan(args.event, paths, runner.changed_contents(root, base, paths))+ except (OSError, KeyError, ValueError, subprocess.CalledProcessError) as error:# 首次推送、浅克隆或已删除基线:扩大验证,不能把无 diff 当成无需测试。+ print(f'已验证基线未取得,使用全量:{error}', file=sys.stderr)result = plan("workflow_dispatch", [])+ result['base'] = baseprint(json.dumps(result, ensure_ascii=False, indent=2))if output := os.environ.get("GITHUB_OUTPUT"):with Path(output).open("a", encoding="utf-8") as stream:diff --git a/scripts/test_evidence.py b/scripts/test_evidence.pyindex b0971946d..f9c6ef39a 100644--- a/scripts/test_evidence.py+++ b/scripts/test_evidence.py@@ -65,7 +65,7 @@ def manifest(root: Path) -> dict:except UnicodeError:passelif not path.exists():- files[name] = "deleted"+ continueelse:raise ValueError(f"无法为文件生成验证快照:{name}")version = root / "src/peach/__init__.py"@@ -367,17 +367,6 @@ def holder_path(lock_path: Path) -> Path:return lock_path.with_name(lock_path.name + ".holder.json")-def machine_lock_path() -> Path:- """整台机器共用的重负载锁:所有工作树、所有会话和本机 CI runner 的作业都排这一把。-- 放在用户目录而不是仓库里:runner 的作业检出在别处,仓库级的全量锁管不到它;- 浏览器、vitest 与构建同时跑会把机器压满,固定时限的用例随之偶发超时。- """- base = os.environ.get("LOCALAPPDATA") or str(Path.home() / ".local" / "state")- # 不放进应用自己的 `%LOCALAPPDATA%\Peach`:那是已装 Peach 的目录,测试设施不往里写。- return Path(base) / "peach-test-locks" / "test-machine.lock"--QUEUE_POLL_SECONDS = 0.1#: 没有 psutil 判不了票主是否还活着时,票的最长寿命。QUEUE_TICKET_SECONDS = 7200diff --git a/scripts/test_inputs.py b/scripts/test_inputs.pynew file mode 100644index 000000000..40ec9100f--- /dev/null+++ b/scripts/test_inputs.py@@ -0,0 +1,40 @@+"""识别测试中以仓库根目录拼出的静态文件输入。"""+from __future__ import annotations++import ast+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+WRITES = frozenset({'write_text', 'write_bytes', 'unlink', 'mkdir', 'touch', 'rmdir'})+++def repository_paths_read_by(source: str) -> tuple[str, ...]:+ """仅认仓库根和其静态别名;临时夹具中的同名路径不属于仓库输入。"""+ tree = ast.parse(source)+ aliases: dict[str, str] = {'ROOT': ''}++ def relative(node):+ if isinstance(node, ast.Name):+ return aliases.get(node.id)+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Div):+ prefix = relative(node.left)+ if prefix is not None and isinstance(node.right, ast.Constant) and isinstance(node.right.value, str):+ return '/'.join(filter(None, (prefix, node.right.value.strip('/'))))+ return None++ for node in tree.body:+ if isinstance(node, ast.Assign):+ value = relative(node.value)+ if value is not None:+ aliases.update({target.id: value for target in node.targets if isinstance(target, ast.Name)})+ parents = {child: parent for parent in ast.walk(tree) for child in ast.iter_child_nodes(parent)}+ found = set()+ for node in ast.walk(tree):+ name = relative(node)+ if not name or not (ROOT / name).is_file():+ continue+ parent = parents.get(node)+ if isinstance(parent, ast.Attribute) and parent.attr in WRITES:+ continue+ found.add(name)+ return tuple(sorted(found))diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex a476ed3a7..bed494e63 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -28,11 +28,12 @@ if not __package__:sys.path.insert(0, str(ROOT))__package__ = "scripts"from . import change_impact, test_evidence, test_history, test_resume, test_run_progress, test_shard_results+from .test_inputs import repository_paths_read_by as repository_paths_read_byCOMMON_PATTERNS = ("test_context_budget.py", "test_test_collection.py", "test_complexity_ratchet.py","test_source_assertion_ratchet.py", "test_python_lint.py")SCOPES: dict[str, tuple[str, ...]] = {- "checks": ("test_copy_final_state.py", "test_dependency_policy.py", "test_repo_hygiene.py", "test_test_planning.py", "test_reference_updates.py",+ "checks": ("test_copy_final_state.py", "test_dependency_policy.py", "test_repo_hygiene.py", "test_test_planning.py", "test_reference_updates.py", "test_readme_contracts.py","test_complexity_ratchet.py", "test_source_assertion_ratchet.py", "test_python_lint.py"),"follow": ("test_follow*.py", "test_http.py", "test_migrations.py", "test_wants_web.py"),"catalog": ("test_ad_judgement.py", "test_composite_name_split.py", "test_media_libraries.py", "test_media_folders.py",@@ -266,8 +267,6 @@ AUTO_SCOPE_FILES: dict[str, tuple[str, ...]] = {# 入口页共用件的测试住在首启与配置来源那两份 tooling 测试里。"src/peach/web_entry.py": ("catalog", "tooling", "web"),# 这几份文档有测试在读它们的正文:改文档也要跑到那条测试。- "README.md": ("checks", "tooling"),- "README.zh-CN.md": ("checks", "tooling"),# 差异表是 token 判据的另一半:偏离上游的每一条都要在那张表里写明原因,所以# `test_frontend_build.py` 读它——改表就得跑到 web。"frontend/src/react/boardui/ORIGIN.md": ("checks", "web"),@@ -380,7 +379,7 @@ FULL_ONLY_PREFIXES: tuple[str, ...] = ("scripts/ci_plan.py", "scripts/test_environment.py", "scripts/change_impact.py", "scripts/test_focus.py","scripts/test_history.py", "uv.lock","scripts/test_resume.py", "scripts/test_run_progress.py", "scripts/test_environment_identity.py",- "scripts/test_shard_results.py",+ "scripts/test_shard_results.py", "scripts/test_inputs.py","migrations/","tests/support/","package.json",@@ -486,32 +485,6 @@ def scopes_of_importers(stem: str, seen: frozenset[str] = frozenset()) -> tuple[return tuple(scope for scope in SCOPES if scope in found)-#: `<某个 Path> / "a" / "b/c.js"` 这种拼接。要求左边有个 `/`,是为了把「路径当字符串-#: 参数传进去」的写法排除掉:`scopes_for_changes(["web/app.js"])` 喂的是假清单,-#: 不读真文件,不该因为字面量长得像路径就被算成读了它。-_PATH_CHAIN = re.compile(r"""/\s*((?:["'][^"'\n]+["']\s*/\s*)*["'][^"'\n]+["'])""")-_SEGMENT = re.compile(r"""["']([^"'\n]+)["']""")-#: 测试文件顶上的 `FRONTEND = ROOT / "frontend"` 这类别名,用来还原下面链式拼接的前缀。-_ROOT_ALIAS = re.compile(r"""^\w+\s*=\s*\w+(?:\[\d+\])?\s*/\s*["']([\w./-]+)["']\s*$""", re.M)---def repository_paths_read_by(source: str) -> tuple[str, ...]:- """一段测试源码实际读到的仓库文件,仓库相对路径。-- 只认拼在某个 Path 后面、且在仓库里真的存在的那一档。判据是「文件存在」而不是- 「长得像路径」:不存在的字面量是别的东西,存在的才是这个测试真正依赖的输入。- """- prefixes = {"", *(alias.strip("/") for alias in _ROOT_ALIAS.findall(source))}- found: set[str] = set()- for chain in _PATH_CHAIN.findall(source):- joined = "/".join(segment.strip("/") for segment in _SEGMENT.findall(chain))- for prefix in prefixes:- candidate = f"{prefix}/{joined}".strip("/")- if (ROOT / candidate).is_file():- found.add(candidate)- return tuple(sorted(found))--def dependency_inputs(source: str) -> dict:"""提取依赖输入,供调用方比较构建与运行环境。"""return change_impact.dependency_inputs(source)@@ -597,6 +570,13 @@ def scopes_for_changes(paths: Iterable[str], *, contents: dict | None = None,scopes = special_scopes(path, kind)if scopes is None:scopes = mapped_scopes(path)+ if kind not in {"unsafe", "prose"} and path.startswith("src/peach/") and path.endswith(".py") \+ and scopes and "full" not in scopes:+ stem = path.removeprefix("src/peach/").split("/", 1)[0].removesuffix(".py")+ tests, _, _ = _import_index()+ consumers = {scope for name, modules in tests.items() if stem in modules+ for scope in scopes_of_test_file(name)}+ scopes = tuple(scope for scope in SCOPES if scope in {*scopes, *consumers})if not scopes:full_reasons.append(f"{path} 映射不到任何域")elif "full" in scopes:@@ -950,6 +930,9 @@ def tools_needed_by(scopes: tuple[str, ...]) -> frozenset[str]:新测试引入新工具时,手写的表会静静过期,而过期的表比没有表更坏——它会拿一个本次根本不启动的工具去挡住一次只改文档的 `checks`。"""+ if scopes == ('checks',):+ # 文档与仓库契约仅启动 Git 和依赖入口;业务工具名也会出现在调度器的模拟用例中。+ return frozenset({'git', 'uv'})names = tuple(name for name, _ in test_evidence.TOOL_PROBES)needed: set[str] = set()for path in {path for scope in scopes for path in selected_files(scope)}:@@ -1048,7 +1031,7 @@ def rerun_failures(rows: list[dict], spawn=subprocess.run) -> bool:if not selectors:return Falseprint(f"单独重跑失败的 {len(selectors)} 项,排除负载造成的偶发:{', '.join(selectors)}", flush=True)- command = [sys.executable, str(ROOT / "scripts" / "test_runner.py"), "--machine-lock-held",+ command = [sys.executable, str(ROOT / "scripts" / "test_runner.py"),*(item for selector in selectors for item in ("--focus", selector))]if spawn(command, cwd=str(ROOT), check=False).returncode != 0:print("单独重跑仍失败:按真实失败处理。", flush=True)@@ -1196,7 +1179,6 @@ def main(argv: list[str] | None = None) -> int:parser.add_argument("--jobs", type=resolve_jobs, default=1,help="本机同时跑几个分片子进程;auto 按核数定。默认串行,正式入口传 auto")parser.add_argument("--list-scopes", action="store_true")- parser.add_argument("--machine-lock-held", action="store_true", help=argparse.SUPPRESS)args = parser.parse_args(argv)if not 0 <= args.lock_timeout <= 1800:parser.error("锁等待时间必须在 0~1800 秒之间")@@ -1232,56 +1214,32 @@ def main(argv: list[str] | None = None) -> int:print("CI 前端工具检查由 web-bundle 验证;本次不签发本机测试记录。", flush=True)success, count, _ = run_local_suite(scopes, args.jobs, f"{' '.join(requested)}:{' '.join(scopes)}")return 0 if success and count > 0 else 1- heavy = "full" in scopes or any(path.stem in HEAVY_FILES for path in files)try:- # 先拿整机的重负载锁,再拿仓库的全量锁;`integrate` 只拿后者,顺序固定就不会互相等死。- with machine_guard(args, heavy, scope=" ".join(scopes)):- guard = test_evidence.held(test_evidence.evidence_dir(ROOT) / "full-suite.lock",- wait_seconds=args.lock_timeout,- scope=" ".join(scopes), root=str(ROOT)) \- if "full" in scopes else nullcontext()- with guard:- return verified_run(args, requested, scopes, files)+ guard = test_evidence.held(test_evidence.evidence_dir(ROOT) / "full-suite.lock",+ wait_seconds=args.lock_timeout,+ scope=" ".join(scopes), root=str(ROOT)) \+ if "full" in scopes else nullcontext()+ with guard:+ return verified_run(args, requested, scopes, files)except test_evidence.Timeout as error:return busy(error)def run_focus(parser, args) -> int:- """定向调试:不签发记录;浏览器与 vitest 文件起浏览器或 node,同样排整机的重负载锁。"""+ """定向调试不签发记录,不取得机器级资源锁。"""if args.shard_count != 1:parser.error("定向调试不能与分片一起使用")from . import test_focus- heavy = any(selector.startswith("frontend/") for selector in args.focus)- try:- with machine_guard(args, heavy):- return test_focus.run(sys.modules[__name__], args)- except test_evidence.Timeout as error:- return busy(error)+ return test_focus.run(sys.modules[__name__], args)-#: 会起浏览器或整套 vitest 的测试文件。选中它们的运行与全量一样要排整机的重负载锁。+#: 内部并行的前端与浏览器容器,和普通分片按阶段执行。HEAVY_FILES = frozenset({"test_web_e2e", "test_frontend_build"})-def machine_guard(args, heavy: bool, **note):- """重负载运行排整机锁;父进程已持有时(全量里的隔离重跑)不再重复等待。-- 用例里调用运行器(测运行器自己的那些用例)时外层正式运行已持有这把锁,不能再去等它。- """- if not heavy or args.machine_lock_held or test_history.nested():- return nullcontext()- # CI 作业(GitLab 与 GitHub 都设 CI=true)有自己的时限(Windows 验收 90 分钟),排在本机两轮全量- # 后面也要等得到;本机交互仍按 --lock-timeout,最长 30 分钟。- wait = CI_MACHINE_LOCK_SECONDS if os.environ.get("CI") == "true" else args.lock_timeout- return test_evidence.held(test_evidence.machine_lock_path(), wait_seconds=wait, root=str(ROOT), **note)---CI_MACHINE_LOCK_SECONDS = 3600--def busy(error) -> int:lock = Path(error.lock_file)- what = {"full-suite.lock": "本仓库全量测试", "test-machine.lock": "本机另一项重负载测试或 CI 作业"}.get(+ what = {"full-suite.lock": "本仓库全量测试"}.get(lock.name, "相同状态的验证")print(f"{what}正在运行({test_evidence.describe_holder(lock)}),请等待该次结果。", flush=True)return 2diff --git a/tests/test_dependency_policy.py b/tests/test_dependency_policy.pyindex 5dd32c653..5980779d6 100644--- a/tests/test_dependency_policy.py+++ b/tests/test_dependency_policy.py@@ -475,6 +475,7 @@ class DependencyPolicyTests(unittest.TestCase):message = adopt.commit_message("web", ["lucide-static 1.38.0 → 1.40.0"],"4", signature)self.assertIn("\nREADME-Impact: none; ", message)+ self.assertIn("\nRefs #4\n", message)self.assertRegex(message, r"README-Impact: none; [^\n]+\nCo-Authored-By: ")self.assertIn("PR #4", message)self.assertIn("npm run vendor:web", message)diff --git a/tests/test_readme_contracts.py b/tests/test_readme_contracts.pynew file mode 100644index 000000000..e37404ab4--- /dev/null+++ b/tests/test_readme_contracts.py@@ -0,0 +1,26 @@+"""README 的安装要求与双语入口。"""+from pathlib import Path+import tempfile+import unittest++from scripts.check_readme_impact import READMES, installation_contracts++ROOT = Path(__file__).resolve().parents[1]+++class ReadmeContractsTests(unittest.TestCase):+ def test_repository_readmes_satisfy_installation_contracts(self):+ self.assertEqual(installation_contracts(ROOT), [])++ def test_installation_check_accepts_equivalent_floor_notation_and_reports_missing_links(self):+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ (root / 'pyproject.toml').write_text('[project]\nrequires-python = ">=3.14"\n', encoding='utf-8')+ for suffix in ('+', ' or newer', ' 或更高'):+ for name in READMES:+ counterpart, = READMES - {name}+ (root / name).write_text(f'Python 3.14{suffix}\n[Language]({counterpart})\n', encoding='utf-8')+ self.assertEqual(installation_contracts(root), [])+ (root / 'README.md').write_text('Python 3.13+\n', encoding='utf-8')+ self.assertEqual(installation_contracts(root), ['README.md: Python 下限须为 3.14',+ 'README.md: 缺少语言入口 README.zh-CN.md'])diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex a3ad23dde..4a32f5d0f 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -1908,7 +1908,7 @@ class OperationalScriptTests(unittest.TestCase):self.assertEqual(json.loads(done.stdout), expected)def test_python_floor_matches_runtime_and_ci(self):- """正式运行版本、CI 与 README 共同覆盖声明的 Python 下限。"""+ """正式运行版本与 CI 共同覆盖声明的 Python 下限。"""project = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))["project"]floor = project["requires-python"].removeprefix(">=")self.assertEqual(floor, "3.14")@@ -1918,11 +1918,6 @@ class OperationalScriptTests(unittest.TestCase):self.assertIn("fromJSON(needs.plan.outputs.matrix)", workflow)from scripts.ci_plan import planself.assertEqual({row["python"] for row in plan("workflow_dispatch", [])["matrix"]["include"]}, {floor})- for readme, suffix in (("README.md", r"(?:\+| or newer)"),- ("README.zh-CN.md", r"(?:\+| 或更高)")):- with self.subTest(readme=readme):- self.assertRegex((ROOT / readme).read_text(encoding="utf-8"),- rf"\bPython {re.escape(floor)}{suffix}")def test_functional_test_scopes_are_explicit(self):runner = load_script("test_runner")@@ -1952,14 +1947,16 @@ class OperationalScriptTests(unittest.TestCase):def test_auto_scope_maps_changed_files_and_falls_back_to_full(self):"""`auto` 的选域是纯函数:喂文件清单,不碰 git。"""runner = load_script("test_runner")- pick = runner.scopes_for_changes+ def pick(paths):+ with mock.patch.object(runner, '_import_index', return_value=({}, {}, frozenset())):+ return runner.scopes_for_changes(paths)# 前缀表:多个文件取并集,反斜杠路径也认。self.assertEqual(pick(["src/peach/follow_store.py", "web/app.js"])[0], ("follow", "web"))self.assertEqual(pick(["src\\peach\\tray.py"])[0], ("sync", "tooling"))self.assertEqual(pick(["scripts/probe.py", "pyproject.toml", ".github/workflows/test.yml"])[0],("full",))self.assertEqual(pick(["README.md", "docs/STATUS.md", ".claude/skills/x/SKILL.md"])[0],- ("checks", "tooling"))+ ("checks",))self.assertEqual(pick(["src/peach/web_entity.py", "src/peach/routes_pages.py"])[0],("catalog", "tooling", "web"))self.assertEqual(pick(["src/peach/web_follow.py"])[0], ("follow",))diff --git a/tests/test_source_assertion_ratchet.py b/tests/test_source_assertion_ratchet.pyindex 2f594e427..fb2e6d7ed 100644--- a/tests/test_source_assertion_ratchet.py+++ b/tests/test_source_assertion_ratchet.py@@ -44,7 +44,7 @@ BASELINE: dict[str, int] = {"test_job_status.py": 1,"test_metadata_library.py": 5,"test_repo_hygiene.py": 1,- "test_scripts.py": 12,+ "test_scripts.py": 11,"test_social_avatar_harvest.py": 2,"test_studio_icon_variants.py": 2,"test_studio_site_harvest.py": 1,diff --git a/tests/test_test_evidence.py b/tests/test_test_evidence.pyindex 94d3d8e86..1cb37b5c6 100644--- a/tests/test_test_evidence.py+++ b/tests/test_test_evidence.py@@ -792,15 +792,13 @@ class SubprocessResumeTests(unittest.TestCase):def check_resume_after_failure(self, scope, *options, check_full_modes=False):source = Path(__file__).resolve().parents[1]modules = ('test_runner', 'test_evidence', 'test_history', 'test_resume', 'test_run_progress',- 'test_shard_results', 'test_environment_identity', 'test_focus', 'change_impact')+ 'test_shard_results', 'test_environment_identity', 'test_focus', 'change_impact', 'test_inputs')files = {'scripts/__init__.py': '', '.gitignore': 'build/\nruntime/\n__pycache__/\n*.pyc\n','.gitattributes': '* text=auto eol=lf\n'}files.update({'scripts/' + name + '.py': (source / 'scripts' / (name + '.py')).read_text(encoding='utf8')for name in modules})files['entry.py'] = (- 'from pathlib import Path\nfrom unittest import mock\nfrom scripts import test_runner as runner\n'- 'with mock.patch.object(runner.test_evidence, "machine_lock_path", '- 'return_value=Path.cwd()/"runtime/machine.lock"):\n raise SystemExit(runner.main())\n')+ 'from scripts import test_runner as runner\nraise SystemExit(runner.main())\n')sample = ('from pathlib import Path\nimport unittest\nclass Suite(unittest.TestCase):\n'' def test_value(self):\n root=Path(__file__).resolve().parents[1]/"runtime"\n'' with (root/(__name__+".calls")).open("a", encoding="utf8") as output:\n'@@ -1075,6 +1073,16 @@ class VerificationTests(unittest.TestCase):(self.repo / "README.md").unlink()self.assertNotEqual(baseline, evidence.snapshot(self.repo))+ def test_committing_a_deleted_file_preserves_the_verified_snapshot(self):+ original = evidence.manifest(self.repo)+ (self.repo / 'README.md').unlink()+ removed = evidence.manifest(self.repo)+ paths, _ = runner.change_impact.delta(original, removed)+ self.assertIn('README.md', paths)+ self.git('add', '--', 'README.md')+ self.git('commit', '-m', 'test: remove fixture document')+ self.assertEqual(removed, evidence.manifest(self.repo))+def test_git_execute_mode_changes_require_full_even_without_content_changes(self):original = evidence.manifest(self.repo)self.git("update-index", "--chmod=+x", "README.md")@@ -1089,11 +1097,13 @@ class VerificationTests(unittest.TestCase):path.write_text("value = 1\n", encoding="utf-8")self.git("add", "--", name)contents = runner.changed_contents(self.repo, "HEAD", [name])- self.assertEqual(runner.scopes_for_changes([name], contents=contents)[0], ("follow",))+ with mock.patch.object(runner, '_import_index', return_value=({}, {}, frozenset())):+ self.assertEqual(runner.scopes_for_changes([name], contents=contents)[0], ("follow",))self.git("commit", "-m", "test: fixture")path.unlink()contents = runner.changed_contents(self.repo, "HEAD", [name])- self.assertEqual(runner.scopes_for_changes([name], contents=contents)[0], ("follow",))+ with mock.patch.object(runner, '_import_index', return_value=({}, {}, frozenset())):+ self.assertEqual(runner.scopes_for_changes([name], contents=contents)[0], ("follow",))def test_known_python_file_execute_mode_requires_full(self):name = "src/peach/web_follow.py"@@ -1530,7 +1540,7 @@ class VerificationTests(unittest.TestCase):mock.patch.object(runner, "build_suite", side_effect=self.scope_suite) as build:self.assertEqual(runner.main(["--scope", "auto"]), 0)self.assertTrue(build.called)- self.assertTrue(all(call.args == ('checks', 'tooling') for call in build.call_args_list))+ self.assertTrue(all(call.args == ('checks',) for call in build.call_args_list))record = evidence.read(self.repo, evidence.key(self.repo))self.assertEqual(record["baseline"], original)self.assertEqual(record["validated"]["full"], stamp)diff --git a/tests/test_test_planning.py b/tests/test_test_planning.pyindex f788470f1..71400d6a5 100644--- a/tests/test_test_planning.py+++ b/tests/test_test_planning.py@@ -204,8 +204,8 @@ class TestPlanningTests(unittest.TestCase):self.assertEqual(scopes, expected)self.assertEqual(runner.scopes_for_changes(['pyproject.toml'])[0], ('full',))- def test_matrix_keeps_full_mainline_and_platform_coverage(self):- result = ci_plan.plan('push', ['web/app.js'])+ def test_matrix_keeps_full_manual_and_platform_coverage(self):+ result = ci_plan.plan('workflow_dispatch', ['web/app.js'])rows = result['matrix']['include']self.assertEqual(len([r for r in rows if r['scope'] == 'full']), 6)self.assertEqual({r['os'] for r in rows}, {'windows-latest', 'macos-latest'})@@ -232,9 +232,12 @@ class TestPlanningTests(unittest.TestCase):self.assertLessEqual({'web-e2e', 'web-bundle', 'web-vendor', 'wheel-smoke'},set(unknown['required_jobs']))mainline = ci_plan.plan('push', ['docs/TESTING.md'])- self.assertTrue(mainline['wide'])+ self.assertFalse(mainline['wide'])+ self.assertEqual(mainline['required_jobs'], documents['required_jobs'])+ manual = ci_plan.plan('workflow_dispatch', ['docs/TESTING.md'])+ self.assertTrue(manual['wide'])self.assertLessEqual({'web-e2e', 'web-bundle', 'web-vendor', 'wheel-build', 'wheel-smoke'},- set(mainline['required_jobs']))+ set(manual['required_jobs']))def test_result_gate_rejects_missing_failed_cancelled_or_required_skipped_jobs(self):required = ['plan', 'python', 'workflow-lint', 'frontend-ready', 'web-e2e']@@ -292,7 +295,7 @@ class TestPlanningTests(unittest.TestCase):self.assertFalse(any(r['scope'] == 'full' for r in rows))self.assertEqual(runner.scopes_for_changes(['scripts/localize_performer_names.py'])[0],('metadata', 'tooling'))- self.assertEqual(runner.scopes_for_changes(['README.md'])[0], ('checks', 'tooling'))+ self.assertEqual(runner.scopes_for_changes(['README.md'])[0], ('checks',))for document in ('docs/TESTING.md', 'docs/CLOUDDRIVE.md', 'docs/OPERATIONS.md'):with self.subTest(document=document):self.assertEqual(runner.scopes_for_changes([document])[0], ('checks',))@@ -305,18 +308,41 @@ class TestPlanningTests(unittest.TestCase):映射缺了这一条,改处理任务就整轮退化成 `full`。"""scopes, _ = runner.scopes_for_changes(['src/peach/library_processing.py'])- self.assertEqual(scopes, ('metadata', 'web'))+ self.assertLessEqual({'metadata', 'web'}, set(scopes))selected = {path.name for scope in scopes for path in runner.selected_files(scope)}self.assertLessEqual({'test_metadata_library.py', 'test_stale_candidates.py','test_web_e2e.py'}, selected)def test_missing_git_base_selects_wide_matrix(self):- with patch.object(sys, 'argv', ['ci_plan.py', '--event', 'push', '--base', 'missing']), \+ with patch.object(sys, 'argv', ['ci_plan.py', '--event', 'pull_request', '--base', 'missing']), \patch.object(runner, 'changed_files', side_effect=subprocess.CalledProcessError(1, 'git')), \patch.dict(ci_plan.os.environ, {}, clear=True), contextlib.redirect_stdout(io.StringIO()) as output:ci_plan.main()self.assertTrue(ci_plan.json.loads(output.getvalue())['wide'])+ def test_mainline_plan_passes_the_verified_baseline_to_test_jobs_and_falls_back_when_missing(self):+ for baseline, wide in (('verified', False), (ValueError('未取得'), True)):+ with self.subTest(baseline=baseline), \+ patch.object(sys, 'argv', ['ci_plan.py', '--event', 'push', '--base', 'unverified']), \+ patch.object(ci_plan, 'github_verified_base', **({'side_effect': baseline} if isinstance(baseline, Exception) else {'return_value': baseline})), \+ patch.object(runner, 'changed_files', return_value=['README.md']) as changed, \+ patch.object(runner, 'changed_contents', return_value={}), \+ contextlib.redirect_stdout(io.StringIO()) as output:+ ci_plan.main()+ result = json.loads(output.getvalue())+ self.assertEqual(result['wide'], wide)+ if not wide:+ self.assertEqual(result['base'], 'verified')+ self.assertEqual(changed.call_args.args[1], 'verified')++ def test_github_baseline_accepts_only_successful_push_ancestors(self):+ runs = [{'head_sha': sha, 'conclusion': result, 'event': 'push', 'head_branch': 'master'}+ for sha, result in (('failed', 'failure'), ('diverged', 'success'), ('ancestor', 'success'))]+ with patch.dict(os.environ, {'GITHUB_REPOSITORY':'peach-mitao/peach'}), \+ patch.object(ci_plan.subprocess, 'check_output', side_effect=[json.dumps({'workflow_runs':runs}), 'head']), \+ patch('scripts.ci_scope.ancestor_of_head', return_value=lambda sha:sha=='ancestor'):+ self.assertEqual(ci_plan.github_verified_base(runner.ROOT), 'ancestor')+def test_venv_interpreter_path_keeps_environment_identity(self):with tempfile.TemporaryDirectory() as directory:root = Path(directory).resolve()@@ -679,21 +705,30 @@ class GateAndFlakyRerunTests(unittest.TestCase):self.assertEqual(sorted(name for shard in plans[1] for name in shard), ['test_media.py', 'test_scan.py'],'门槛里的文件不再进后面的分片')- def test_heavy_runs_queue_on_the_machine_lock_except_nested_or_already_held(self):- args = runner.argparse.Namespace(machine_lock_held=False, lock_timeout=5)- for ci, wait in (('', 5), ('true', runner.CI_MACHINE_LOCK_SECONDS)):- with self.subTest(ci=ci), patch.object(runner.test_evidence, 'held') as held, \- patch.object(runner.test_history, 'nested', return_value=False), \- patch.dict(os.environ, {'CI': ci}):- runner.machine_guard(args, True, scope='full')- self.assertEqual(held.call_args.args[0], runner.test_evidence.machine_lock_path())- self.assertEqual(held.call_args.kwargs['wait_seconds'], wait, 'CI 作业按自己的时限等,本机按 --lock-timeout')- for light, nested, already in ((True, False, False), (False, True, False), (False, False, True)):- with self.subTest(light=light, nested=nested, already=already), \- patch.object(runner.test_evidence, 'held') as held, \- patch.object(runner.test_history, 'nested', return_value=nested):- runner.machine_guard(runner.argparse.Namespace(machine_lock_held=already, lock_timeout=5), not light)- held.assert_not_called()+ def test_focus_runs_without_serializing_other_worktrees(self):+ from scripts import test_focus+ with patch.object(runner.test_evidence, 'held', side_effect=AssertionError('定向调试不取得共享锁')), \+ patch.object(test_focus, 'run', return_value=0) as focused:+ self.assertEqual(runner.main(['--focus', 'frontend/e2e/design-people.test.ts']), 0)+ self.assertEqual(focused.call_count, 1)++ def test_named_modules_include_their_direct_behavior_consumers(self):+ for module, consumers in (+ ('http', {'test_processing_traffic.py', 'test_metadata_sources.py'}),+ ('ffmpeg', {'test_frame_capture.py', 'test_hardware_transcode.py'}),+ ):+ with self.subTest(module=module):+ scopes, _ = runner.scopes_for_changes([f'src/peach/{module}.py'])+ selected = {path.name for scope in scopes for path in runner.selected_files(scope)}+ self.assertLessEqual(consumers, selected)++ def test_repository_reads_exclude_fixture_paths_and_write_operations(self):+ source = ('from pathlib import Path\nROOT = Path(__file__).resolve().parents[1]\n'+ 'DOCS = ROOT / "docs"\n'+ '(worker / "README.zh-CN.md").write_text("fixture")\n'+ '(ROOT / "README.md").write_text("fixture")\n'+ '(DOCS / "TESTING.md").read_text()\n')+ self.assertEqual(runner.repository_paths_read_by(source), ('docs/TESTING.md',))def test_focus_accepts_vitest_files_and_hands_them_to_the_island_suite(self):from scripts import test_focus