Peach: Local-first video metadata scraper and media manager.
test(tooling): 加「文案只写最终状态」门槛
longmeidao0e99d8115e9d
diff --git a/.claude/skills/peach-context-rules/SKILL.md b/.claude/skills/peach-context-rules/SKILL.mdindex 21d71ebbf..5c56485ed 100644--- a/.claude/skills/peach-context-rules/SKILL.md+++ b/.claude/skills/peach-context-rules/SKILL.md@@ -5,7 +5,7 @@ description: 在用户说加条规则、写进 AGENTS.md、写个技能、文件# 上下文写作与清退-最后复核:2026-08-27+最后复核:2026-09-03证据来源:ADR-0015、`scripts/check_context_budget.py`、`tests/test_context_budget.py`、用户于2026-08-17 提供的 `My AGENTS.md & SKILLS.md Breakdown` 逐字稿。@@ -72,6 +72,22 @@ Claude 只把每个技能的 name+description 预加载进系统提示,读不Codex 完全不自动加载 `.claude/skills`,只能靠 `AGENTS.md` 索引表主动读。所以「必须每次成立」的规则不能只写成技能,必须同时有脚本、测试或 hook 强制。技能写「怎么做」,门槛写「必须做」。+## 文案只写最终状态++界面字串、注释、docstring、测试名与文档只描述现在成立的行为和约束,不叙述被否掉的做法,+也不做改动前后对比——版本演进由 Git 记录,读者要的是当前这一份怎么用。++- 门槛是 `scripts/check_copy_final_state.py`,由 `tests/test_copy_final_state.py` 在 tooling+ 与 web 两个域执行;词表、覆盖面与临时例外文件清单都在脚本顶部,改判据就改那里。+- 覆盖面:`web/` 的字串与注释、`frontend/`,`src`/`scripts`/`tests` 的注释、docstring、+ 字符串字面量与测试函数名,以及 `README.md`、`docs/*.md`(不含 `docs/adr/`)、`AGENTS.md`+ 和各技能正文。ADR 正文按定义要记录决策过程,不在覆盖面内。+- 约束的理由必须留下。把它写成反事实句「这样做的话,会……」,说清失败模式而不点名某一版实现,+ 既保住教训又不需要放行标记。+- 真实事故记录才放行:那一行结尾加 `copy-lint-disable-line`,Markdown 写成 HTML 注释、+ Python 用 `#`、JS 用 `//`;这个标记与用户级 `lint_copy_rules.py` 共用,一处标记两边都认。+ 放行前先试着改写成「现在的规则 + 它防住的后果」,多数记录不需要标记。+## 失败模式审计规则的来源应该是统计,不是印象。定期(每次 minor 发布前,或连续踩同类坑时)让智能体审计diff --git a/AGENTS.md b/AGENTS.mdindex 1152aa523..929be0691 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -2,8 +2,7 @@本文件是 Codex 与 Claude 共用的唯一项目入口,只保留「每个任务都必须成立」的边界与索引。它不是 README:`README.md` 讲这个项目是什么、怎么跑;本文件讲改动它之前必须先知道什么。-分层判据、写作规范与清退机制见 `docs/adr/0015-agent-context-layering.md`;新增规则前先按-`.claude/skills/peach-context-rules/SKILL.md` 判断该写在哪一层,不要默认追加到本文件。+分层判据、写作规范与清退机制见 `docs/adr/0015-agent-context-layering.md`,不要默认追加到本文件。面向用户阅读的 README、项目总览、状态、交接、复用清单、待办和 ADR 正文统一使用中文。代码标识、命令、协议名、库名和无法准确翻译的专有名词保留英文;不要为了智能体处理方便混写英文叙述。@@ -75,8 +74,9 @@- **测试入口**:每个平台只有一个,Windows `& .\scripts\test.ps1`,macOS/Linux `./scripts/test.sh`,只在当前隔离 worktree 根目录运行。局部改动跑对应功能域;跨域、迁移、共享测试设施、依赖、构建/发布或大面积改动跑默认 `full`。两者自动定位主项目 venv、强制 `PYTHONPATH=<当前 worktree>/src`、核对 `peach.__file__` 后运行 `unittest`;禁止手工拼接 venv 路径或调用 pytest。健康检查只使用 `/healthz`。- **上下文预算**:入口文件与技能有行数、字节数和最长行三重预算,由 `scripts/check_context_budget.py` 与 `tests/test_context_budget.py` 强制。写不下就说明该内容属于 `docs/` 或某个技能,不是往本文件加行。- **分层**:新增或删除规则前按 `peach-context-rules` 判层;本文件的技能索引必须与 `.claude/skills/` 一一对应,技能缺 frontmatter、name 不符或缺 `最后复核` 会被拒。-- **工作树**:并发改代码时主检出只做集成。每个智能体在 `scripts/agent_worktree.py create` 建于 `peach-worktrees/` 的隔离工作树里干活,不在别处、也不在主检出;提交前 `git rev-parse --show-toplevel` 必须不是主检出,工作者只交分支、从不自己合并。细节见 `peach-worktree`。+- **工作树**:并发改代码时主检出只做集成。每个智能体在 `scripts/agent_worktree.py create` 建于 `peach-worktrees/` 的隔离工作树里干活;提交前 `git rev-parse --show-toplevel` 必须不是主检出,工作者只交分支、从不自己合并。细节见 `peach-worktree`。- **仓库卫生**:`.claude/worktrees/` 下不得留未在 `git worktree list` 注册的目录(`tests/test_repo_hygiene.py`)。不用 `git add .`、`git add -A`、目录路径或 glob,只暂存本任务拥有的文件再核对 `git diff --cached --name-status`;实现与它的测试原子提交。+- **文案只写最终状态**:界面字串、注释、docstring、测试名与文档不写改动前后对比,例外逐行加 `copy-lint-disable-line`(`tests/test_copy_final_state.py`)。- **依赖策略**:Python 依赖精确固定版本,每个被 import 的外部模块要有声明的归属,前端清单与实际 vendored 路径一致,所有清单都进 Dependabot(`tests/test_dependency_policy.py`)。## 常犯错误(没有自动拦截,都是真实重犯过的)diff --git a/docs/HANDOFF.md b/docs/HANDOFF.mdindex 1052453d4..3653e88d3 100644--- a/docs/HANDOFF.md+++ b/docs/HANDOFF.md@@ -60,9 +60,10 @@- 全部中文内容(README、`docs/`、ADR、技能正文、界面文案)按用户级技能 tech-doc-style-chinese 写作:事实优先、可扫读、不新增原文没有的数字与结论;规则只作用于可见正文,代码、路径、字段和命令原样保留。-- 来源 https://github.com/Fenng/Tech-Doc-Style-Chinese (MIT),本机装在用户级 `skills/tech-doc-style-chinese`(upstream `a6f5b60`,2026-08-07),Claude 按 description 自动加载;Codex 自行安装到 `$CODEX_HOME/skills/` 下的同名目录。-- 检查器是该技能目录下的 `scripts/lint_copy_rules.py`,用主项目 venv 跑,参数 `README.md AGENTS.md docs- .claude\skills`。它只覆盖高频规则,`error` 必须清零,`style` 提示需人工判断,不作为提交门槛。+- 来源 https://github.com/Fenng/Tech-Doc-Style-Chinese (MIT),本机装在用户级 `skills/tech-doc-style-chinese`(upstream `a6f5b60`,2026-08-07);Codex 自行安装到 `$CODEX_HOME/skills/` 同名目录。+- 检查器两层:用户级 `scripts/lint_copy_rules.py` 用主项目 venv 跑,参数 `README.md AGENTS.md docs+ .claude\skills`,`error` 清零、`style` 人工判断,不是门槛;`scripts/check_copy_final_state.py`+ 是门槛,判据与放行标记见 `peach-context-rules`。- Peach 覆盖上游默认三处:智能体入口文件保留称呼「你」(术语表已定义其含义);`DOM/CSS/JS` 是证据 <!-- copy-lint-disable-line -->三元组的固定写法,不展开成 JavaScript;`对齐`、`复盘` 是已注册的项目术语与技能触发词,不替换。其余上游黑话词(兜底、落盘、闭环、链路)一律改写成具体机制。diff --git a/scripts/check_copy_final_state.py b/scripts/check_copy_final_state.pynew file mode 100644index 000000000..e7f05e254--- /dev/null+++ b/scripts/check_copy_final_state.py@@ -0,0 +1,219 @@+"""文案只描述最终状态:界面字串、注释、docstring、测试名与文档的门槛检查。++被否掉的做法和「改动前后对比」不属于交付物。一段写着「以前是 X,现在改成 Y」的注释+要求读者先装载一个已经不存在的版本,才能读懂现在这一版;而它讲的那个 X 在代码里已经+没有任何对应物,无法核对,也无法失效。约束本身(为什么现在是 Y)要留下,走向那里的+路径不要留。++判据落在词表上,逐行报告。合法的例外是**以真实事故为内容**的条目:+`docs/HANDOFF.md` 的事故记录、技能里的「已知陷阱」、`AGENTS.md` 的「常犯错误」。+它们的内容就是那次失败本身,删掉等于丢掉证据。这类行在行尾加放行标记:++ Markdown <!-- copy-lint-disable-line -->+ Python # copy-lint-disable-line+ JavaScript // copy-lint-disable-line++放行必须逐行、显式;没有目录级或词表级豁免。+"""+from __future__ import annotations++import argparse+import ast+import io+import re+import sys+import tokenize+from dataclasses import dataclass+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]++DISABLE_MARKER = "copy-lint-disable-line"++#: 中文词表。收的是**指向先前状态的时间标记**——它们后面跟的一定是一个读者无法+#: 核对、也无法失效的旧版本。功能性否定词不收:`不再抄一份`、`不装配`、`原样返回`+#: 说的是现在成立的约束或现在的行为,2026-09-03 全树校准里它们十次里有七次合法,+#: 收进来只会逼人满树贴放行标记。+CHINESE_RULES: tuple[tuple[str, str], ...] = (+ (r"以前", "只写现在是什么"),+ (r"原来(?!源)", "只写现在是什么"),+ (r"原本|原先|本来是|之前是", "只写现在是什么"),+ (r"曾经|早先", "只写现在成立的事实"),+ (r"第[一二三]版|初版|上一版|换过[两三四]版",+ "只写当前实现,版本演进属于 Git 历史"),+ (r"实测(?:只|下来|发现)", "只写结论本身,不写它是怎么被测出来的"),+ (r"[不别没](?:装|用|要|是|取)原样", "只说现在装的是什么"),+ (r"现在改|改回原", "只写现在的行为,不写改动方向"),+)++#: 英文词表。大小写不敏感。同样只收时间标记。+ENGLISH_RULES: tuple[tuple[str, str], ...] = (+ (r"\bno longer\b", "state the constraint that holds now"),+ (r"\bpreviously\b|\bformerly\b", "state the current behavior"),+ (r"\bused to\b", "state the current behavior"),+)++#: 测试函数名。名字是契约声明,不是变更说明。+#:+#: `_instead_of_` 与 `_not_the_` 不收:`..._takes_the_intersection_not_the_union`+#: 对比的是同一份输入下的另一种可能行为,读者不需要知道任何历史就能核对,是好名字。+TEST_NAME_RULES: tuple[tuple[str, str], ...] = (+ (r"_no_longer_", "名字写现在成立的契约"),+ (r"_previously_|_formerly_|_used_to_", "名字写现在成立的契约"),+)++_ALL_PROSE_RULES = tuple(+ (re.compile(pattern, re.IGNORECASE), message)+ for pattern, message in (*CHINESE_RULES, *ENGLISH_RULES)+)+_TEST_NAME_RULES = tuple(+ (re.compile(pattern), message) for pattern, message in TEST_NAME_RULES+)++#: 临时排除:这些文件正由另一个工作者改,由协调者在合并后删掉本清单。+TEMPORARY_EXCLUSIONS: frozenset[str] = frozenset({+ "src/peach/images.py",+ "scripts/harvest_studio_icons.py",+ "scripts/normalize_studio_logos.py",+ "scripts/fetch_studio_avatar_candidates.py",+ "tests/test_studio_icon_variants.py",+ "docs/SOURCING.md",+ "docs/STATUS.md",+})++#: 词表在这两个文件的正文里必须能被写出来,否则规则无法自我描述。+SELF_DESCRIBING: frozenset[str] = frozenset({+ "scripts/check_copy_final_state.py",+ "tests/test_copy_final_state.py",+})++FENCE_RE = re.compile(r"^\s*(`{3,}|~{3,})")+++@dataclass(frozen=True)+class Finding:+ path: str+ line: int+ term: str+ message: str++ def __str__(self) -> str:+ return f"{self.path}:{self.line}: 「{self.term}」 — {self.message}"+++def _scan_text(path: str, line_no: int, text: str) -> list[Finding]:+ if DISABLE_MARKER in text:+ return []+ return [Finding(path, line_no, match.group(0), message)+ for pattern, message in _ALL_PROSE_RULES+ for match in pattern.finditer(text)]+++def scan_lines(path: str, source: str, *, skip_code_fences: bool) -> list[Finding]:+ """逐行扫描。Markdown 的围栏代码块是命令与输出原文,不适用文案规则。"""+ found: list[Finding] = []+ fence: str | None = None+ for line_no, raw in enumerate(source.splitlines(), start=1):+ if skip_code_fences:+ fence_match = FENCE_RE.match(raw)+ if fence_match:+ delimiter = fence_match.group(1)+ if fence is None:+ fence = delimiter+ elif delimiter[0] == fence[0] and len(delimiter) >= len(fence):+ fence = None+ continue+ if fence is not None:+ continue+ found.extend(_scan_text(path, line_no, raw))+ return found+++def scan_python(path: str, source: str) -> list[Finding]:+ """注释、docstring、字符串字面量与测试函数名,其余标识符不看。++ 按 token 而不是按行,是为了让 `d["summary"]` 这样的下标和 `legacy_id` 这样的+ 变量名不进结果:它们是被执行的值,不是给人读的叙述。+ """+ found: list[Finding] = []+ lines = source.splitlines()+ try:+ tokens = list(tokenize.generate_tokens(io.StringIO(source).readline))+ except (tokenize.TokenError, IndentationError, SyntaxError):+ return scan_lines(path, source, skip_code_fences=False)+ for token in tokens:+ if token.type not in (tokenize.COMMENT, tokenize.STRING):+ continue+ start = token.start[0]+ for offset, piece in enumerate(token.string.splitlines()):+ line_no = start + offset+ physical = lines[line_no - 1] if line_no <= len(lines) else piece+ if DISABLE_MARKER in physical:+ continue+ found.extend(_scan_text(path, line_no, piece))+ try:+ tree = ast.parse(source)+ except SyntaxError:+ return found+ for node in ast.walk(tree):+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):+ continue+ if not node.name.startswith("test"):+ continue+ physical = lines[node.lineno - 1] if node.lineno <= len(lines) else ""+ if DISABLE_MARKER in physical:+ continue+ for pattern, message in _TEST_NAME_RULES:+ if pattern.search(node.name):+ found.append(Finding(path, node.lineno, pattern.pattern, message))+ return found+++def targets(root: Path) -> list[Path]:+ picked: list[Path] = [root / "AGENTS.md", root / "README.md"]+ picked.extend(sorted((root / "docs").glob("*.md")))+ picked.extend(sorted((root / ".claude" / "skills").glob("*/SKILL.md")))+ picked.extend(sorted((root / "web").glob("*.html")))+ picked.append(root / "web" / "app.js")+ picked.extend(sorted((root / "web" / "js").glob("*.js")))+ for suffix in ("*.ts", "*.tsx", "*.js"):+ picked.extend(sorted((root / "frontend" / "src").rglob(suffix)))+ for directory in ("src", "scripts", "tests"):+ picked.extend(sorted((root / directory).rglob("*.py")))+ seen: dict[Path, None] = {}+ for path in picked:+ if path.is_file():+ seen.setdefault(path.resolve(), None)+ return list(seen)+++def scan_repo(root: Path = ROOT) -> list[Finding]:+ found: list[Finding] = []+ for path in targets(root):+ rel = path.relative_to(root).as_posix()+ if rel in TEMPORARY_EXCLUSIONS or rel in SELF_DESCRIBING:+ continue+ source = path.read_text(encoding="utf-8")+ if path.suffix == ".py":+ found.extend(scan_python(rel, source))+ else:+ found.extend(scan_lines(rel, source, skip_code_fences=path.suffix == ".md"))+ return sorted(found, key=lambda item: (item.path, item.line, item.term))+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--root", default=str(ROOT))+ args = parser.parse_args(argv)+ findings = scan_repo(Path(args.root).resolve())+ for finding in findings:+ print(finding)+ if findings:+ print(f"FAIL: {len(findings)} 处文案在叙述被否掉的做法或改动前后对比。")+ return 1+ print("PASS: 文案只描述最终状态。")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 9d2b21a40..b92935efb 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -53,13 +53,16 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_job_status.py", "test_jobs.py", "test_reference_updates.py","test_repo_hygiene.py","test_review_csv.py", "test_jav_code_domain.py",- "test_subprocess_encoding.py", "test_module_layering.py"),+ "test_subprocess_encoding.py", "test_module_layering.py",+ "test_copy_final_state.py"),# 前端 island 层(ADR-0022)。产物与源码的断言不需要 Node;vitest 那部分在没有# npm 时自己跳过,所以这个域在任何机器上都能跑,`full` 也就自动包含它。# `test_web_perf.py` 两个域都登记:压缩与 ETag 是 API 交付(catalog),# 播放器按需加载的断言读 `web/app.js`(web),改任一侧都该被本域拦住。+ # `test_copy_final_state.py` 两个域都登记:它扫全树,而界面字串是它最常拦到的+ # 一面,改 `web/` 的人必须在本域就撞上它。"web": ("test_frontend_build.py", "test_web_ui.py", "test_web_js.py",- "test_web_perf.py"),+ "test_web_perf.py", "test_copy_final_state.py"),}SCOPE_TEST_IDS: dict[str, tuple[str, ...]] = {diff --git a/tests/test_copy_final_state.py b/tests/test_copy_final_state.pynew file mode 100644index 000000000..8c30ae37a--- /dev/null+++ b/tests/test_copy_final_state.py@@ -0,0 +1,76 @@+"""文案只描述最终状态的门槛。判据与放行方式见 `scripts/check_copy_final_state.py`。++写成测试而不是文档里的一条提醒,是因为提醒已经证明拦不住:用户四次要求删掉界面上+「没必要的说明文字和中间态说明」,四次都有遗漏。遗漏的形态是固定的——被要求去掉+某个东西之后,交付物里到处留着「(无那个东西)」:标题、注释、说明都在讲被否掉的+中间状态,而不是只描述最终的成品。+"""+from __future__ import annotations++import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "scripts"))+import check_copy_final_state as checker # noqa: E402+++class CopyFinalStateTests(unittest.TestCase):+ def test_no_copy_narrates_a_rejected_or_superseded_state(self):+ findings = checker.scan_repo(ROOT)+ self.assertEqual(+ findings, [],+ "文案只写最终状态。逐行修掉下列位置,或确认它是真实事故记录后在行尾加"+ f" {checker.DISABLE_MARKER}:\n"+ + "\n".join(str(item) for item in findings))++ def test_the_disable_marker_works_line_by_line(self):+ source = "# 以前这里是另一种做法\n# 以前这里是另一种做法 # copy-lint-disable-line\n"+ found = checker.scan_python("sample.py", source)+ self.assertEqual([item.line for item in found], [1])++ def test_python_identifiers_and_values_are_not_prose(self):+ # 判据落在注释、docstring、字符串字面量和测试函数名上。变量名与下标是被+ # 执行的值,不是给人读的叙述,扫进来只会把 `source='legacy:asset'` 判成违规。+ source = "legacy_id = 1\nrow['以前']\n"+ self.assertEqual(checker.scan_python("sample.py", source), [])++ def test_markdown_code_fences_carry_commands_not_prose(self):+ source = "正文\n```\ngit log --grep 以前\n```\n以前\n"+ found = checker.scan_lines("sample.md", source, skip_code_fences=True)+ self.assertEqual([item.line for item in found], [5])++ def test_every_rule_reports_file_line_and_term(self):+ found = checker.scan_lines("sample.md", "# 曾经有另一种做法\n",+ skip_code_fences=True)+ self.assertEqual(len(found), 1)+ self.assertEqual((found[0].path, found[0].line, found[0].term),+ ("sample.md", 1, "曾经"))+ self.assertIn("sample.md:1", str(found[0]))++ def test_the_scan_covers_every_declared_surface(self):+ """扫描面写死成 glob 就会漏掉新目录,所以直接核对它收到了哪些文件。"""+ picked = {path.relative_to(ROOT).as_posix() for path in checker.targets(ROOT)}+ for required in ("AGENTS.md", "README.md", "docs/HANDOFF.md",+ "web/app.js", "web/index.html", "web/js/routes.js",+ "src/peach/web_entity.py", "scripts/ledger.py",+ "tests/test_web_ui.py",+ ".claude/skills/peach-worktree/SKILL.md"):+ self.assertIn(required, picked)+ self.assertTrue(any(path.startswith("frontend/src/") for path in picked))+ # ADR 正文的内容就是决策与被否掉的备选方案,本门槛不适用。+ self.assertFalse(any(path.startswith("docs/adr/") for path in picked))++ def test_temporary_exclusions_name_files_that_exist(self):+ """排除清单是临时的,由协调者在并行分支合并后删掉。++ 列进来的文件被别的工作者持有,本分支不改它们。文件消失时清单要跟着消失,+ 否则它会变成一份没人核对的永久豁免。+ """+ for rel in checker.TEMPORARY_EXCLUSIONS:+ self.assertTrue((ROOT / rel).is_file(), rel)+++if __name__ == "__main__":+ unittest.main()