Prhub

#25443 Add mechanical-refactor-verify skill from miles

原始 PR 作者 fzyzcjy 合并时间 2026-05-16 09:23 文件变更 2 提交数 1 评论 1 代码增减 +214 / -0

执行摘要

导入机械重构验证的 Claude Code skill

PR body 指明:该技能用于强化 sprint 的机械重构约定——每个文件拆分/函数移动/模块提取的提交必须附带一个可重现的转换脚本(gist),且该脚本(而非 diff)是 review 交付物。这使得机械重构可审计、可复现。

值得精读。该 PR 展示了如何通过工具强制保证重构的可复现性和可审计性,对于大型代码库的工程实践有借鉴意义。verify_mechanical_refactor 函数中 git worktree + diff 校验的设计值得参考。

讨论亮点

无 review 讨论。仅有一个来自 gemini-code-assist[bot] 的评论提醒 quota 限制,与 PR 内容无关。

实现拆解

  1. 创建技能目录:在 .claude/skills/mechanical-refactor-verify/ 下存放两个文件。
  2. 编写核心工具函数mechanical_refactor_verify_utils.py):提供 exec_command 执行 shell 命令、git_add_and_commit 执行 git 提交、dedent 辅助缩进处理、以及 verify_mechanical_refactor 主函数,该函数基于 git worktree 创建独立工作副本,运行 transform 回调,diff 对比,如果结果非空则失败。
  3. 编写技能描述文档SKILL.md):定义技能名称、描述、调用方式,并给出完整的 transform 脚本模板和分步说明。
  4. 无其他变更:未修改 python/ 下任意源码,无测试配套,仅工具流程新增。
文件 模块 状态 重要度
.claude/skills/mechanical-refactor-verify/mechanical_refactor_verify_utils.py 工具脚本 added 8.21
.claude/skills/mechanical-refactor-verify/SKILL.md 文档 added 5.22

关键符号

exec_command git_add_and_commit dedent verify_mechanical_refactor transform

关键源码片段

.claude/skills/mechanical-refactor-verify/mechanical_refactor_verify_utils.py core-logic

核心工具模块,提供 `verify_mechanical_refactor` 等函数,是技能的可执行逻辑。

"""Utilities for mechanical refactor verification scripts.See SKILL.md for usage and transform script template.
"""import shlex
import subprocess
import sys
import tempfile
from collections.abc import Callable
from pathlib import Path
​
​
def exec_command(cmd: str, cwd: str | None = None, check: bool = True) -> str:
    # 打印执行的命令,方便追踪
    print(f"  $ {cmd}", flush=True)
    result = subprocess.run(
        cmd,
        shell=True,
        cwd=cwd,
        capture_output=True,
        text=True,
    )
    if check and result.returncode != 0:
        # 命令失败时打印 stderr 并直接退出
        print(f"FAILED: {result.stderr}", file=sys.stderr)
        sys.exit(1)
    return result.stdout.strip()
​
​
def git_add_and_commit(message: str, cwd: str) -> None:
    # 封装 git 提交,自动处理消息引号
    exec_command(f"git add -A && git commit -m {shlex.quote(message)}", cwd=cwd)
​
​
def dedent(text: str, n: int) -> str:
    """Remove exactly n leading spaces from each line."""
    lines = text.splitlines(keepends=True)
    return "".join(line[n:] if line[:n] == " " * n else line for line in lines)
​
​
def verify_mechanical_refactor(
    base_commit: str,
    target_commit: str,
    transform: "Callable[[Path], None]",
) -> None:
    # 主验证流程:创建 worktree -> 运行 transform -> diff 校验
    repo_root = exec_command("git rev-parse --show-toplevel")
    worktree_dir = tempfile.mkdtemp(prefix="verify-mechanical-")
    branch_name = f"verify-mechanical-{base_commit[:8]}"
    try:
        print(f"[1/4] Creating worktree at {base_commit[:8]}...")
        exec_command(
            f"git worktree add -b {branch_name} {worktree_dir} {base_commit}",
            cwd=repo_root,
        )
        print("[2/4] Running transformation...")
        transform(Path(worktree_dir))
        print("[3/4] Running pre-commit...")
        exec_command("pre-commit run --all-files", cwd=worktree_dir, check=False)
        if exec_command("git status --porcelain", cwd=worktree_dir):
            git_add_and_commit("pre-commit fixes", cwd=worktree_dir)
        print(f"[4/4] Diffing against {target_commit[:8]}...")
        diff = exec_command(
            f"git diff {target_commit} -- .",
            cwd=worktree_dir,
            check=False,
        )
        if diff:
            print(f"\nFAIL: diff is non-empty:\n{diff}")
            sys.exit(1)
        else:
            print("\nPASS: transform reproduces the commit exactly.")
    finally:
        # 清理提示,不自动删除 worktree 以便调试
        print(f"\nWorktree left at: {worktree_dir}")
        print(f"Branch: {branch_name}")
        print("To clean up manually:")
        print(f"  git worktree remove {worktree_dir} && git branch -D {branch_name}")

评论区精华

没有提炼出高价值讨论线程

当前评论区没有形成足够清晰的争议点或结论,后续有更多讨论时会体现在这里。

风险与影响

无直接风险。变更仅限于 .claude/skills/ 下的工具脚本和文档,不涉足任何运行时逻辑、配置或测试。技能本身仅当开发者显式调用 /mechanical-refactor-verify 时才生效,不会自动执行。潜在风险极小。

影响范围:主要影响参与机械重构(文件拆分、函数移动、模块提取)的开发者,要求他们为每次机械提交附带可重现脚本。团队整体代码 review 流程将更可审计。影响程度:中低度,因为强制约束仅针对特定类型的重构,不影响日常功能开发。对用户无影响(非产品变更)。

关联 Issue

未识别关联 Issue

当前没有检测到明确关联的 Issue 链接,后续同步到相关引用后会出现在这里。

完整报告

参与讨论