Git 历史考古工具,回答“为什么这段代码存在?”,适用于任意文件、行或可疑代码块。链式调用 git blame → git log --follow → commit 信息...
Git Blame考古学家是一项面向实际任务的技能,主要用于你盯着一个神奇的号码;Const TimeOUT=47000;
承诺信息说“固定时间”。它将相关步骤、工具调用和结果整理方式集中到统一流程中,帮助使用者更快完成目标并减少重复操作。使用时应结合输入条件选择合适的执行方式,核对必要参数、依赖环境与输出内容,并按原始要求处理异常情况。该技能适合需要稳定复用相关能力的场景,可作为自动化工作流的一部分,也便于后续检查、调整和扩展。
从功能定位来看,该技能强调把分散的操作要求整理成清晰、可复用的处理流程,使用户能够围绕既定目标快速准备输入、选择执行方式并获得结构化结果。实际使用前应先确认任务范围、数据来源、运行环境、必要权限和关键参数,再依据技能说明逐步执行;若输入条件不完整,应先补齐信息或采用保守配置,避免因错误假设导致结果偏离需求。执行过程中需要关注工具调用是否成功、接口或依赖是否可用、输出格式是否符合预期,并对异常提示、缺失字段和边界情况进行处理;涉及批量任务时,还应保存进度,避免中断后重复操作。
你正盯着一个“魔法数字”:const TIMEOUT = 47000。为什么是 47?不是 45,也不是 60——偏偏是 47。
git blame 告诉你,Alice 在 3 月 3 日修改了它。提交信息写着“fix timeout”。关联的 PR 已关闭,链接的 issue 已关闭,工单已归档。
本技能通过串联 blame → log → follow → context 四步,重建代码**为何**如此设计——而不仅仅是**谁**、在**何时**做的修改。
完全离线运行,不依赖任何外部 API,仅需本地 Git 仓库即可。
/git-blame-archaeologist# 方式 1:调查某一行 /git-blame-archaeologist src/auth/middleware.ts:47 # 方式 2:调查某一段行范围 /git-blame-archaeologist src/config.py:120-135 # 方式 3:调查某个命名符号(函数、常量等) /git-blame-archaeologist --symbol TIMEOUT_MS src/ # 方式 4:调查某文件的近期完整历史 /git-blame-archaeologist src/api/users.ts # 方式 5:在某文件中查找所有“神秘代码块”(即提交信息过于简略的变更) /git-blame-archaeologist --find-mysteries src/ # 方式 6:从指定 commit 开始向前追溯 /git-blame-archaeologist src/utils.js:88 --since abc1234
# 获取某行或某文件的 blame 信息 git blame -L 47,47 src/auth/middleware.ts --porcelain # -L:指定行号范围 # --porcelain:输出机器可读格式,含完整 commit hash # 获取某段行范围的 blame git blame -L 120,135 src/config.py --porcelain # 获取整个文件的精简 blame(按日期排序) git blame --date=short src/api/users.ts
解读 blame 输出:
# porcelain 格式示例: abc1234def5678... 47 47 author Alice Chen author-mailauthor-time 1741824000 author-tz +0800 committer Alice Chen committer-time 1741824000 summary fix timeout issue filename src/auth/middleware.ts const TIMEOUT = 47000
需提取的关键字段:
summary —— 提交信息(通常较简略)abc1234...)—— 用于获取完整上下文author-time —— 修改发生的时间戳# 获取被 blame 到的 commit 的完整信息与 diff COMMIT_HASH="abc1234def5678" # 显示该 commit 的变更统计(含 diff 上下文) git show $COMMIT_HASH --stat # 仅显示该 commit 中对此文件的具体变更 git show $COMMIT_HASH -- src/auth/middleware.ts # 检查该 commit 是否关联了 PR、issue 或工单 git log --format="%H %s %b" $COMMIT_HASH -1 # 关注关键词:"fixes #123"、"closes #456"、"JIRA-789"、"PR #234"
文件会被重命名、移动或拆分。git blame 在当前路径下仅显示**最后一次重命名之后**的历史。
# 追踪文件在重命名过程中的完整历史 git log --follow --all --oneline -- src/auth/middleware.ts # --follow:跨重命名追踪历史 # --all:包含所有分支 # 查找原始文件名 git log --follow --diff-filter=R --summary -- src/auth/middleware.ts | grep "rename" # 输出示例:"rename old/path/auth.js => src/auth/middleware.ts (95%)" # 若已重命名,还需对旧路径执行 blame 以获取全部历史 git log --follow -p -- src/auth/middleware.ts | grep -A5 "TIMEOUT = "
import subprocess
import re
from datetime import datetime
def get_blame_for_line(filepath, line_num):
"""获取某一行的 git blame 数据。"""
result = subprocess.run(
['git', 'blame', '-L', f'{line_num},{line_num}', '--porcelain', filepath],
capture_output=True, text=True
)
if result.returncode != 0:
return None
output = result.stdout
commit_hash = output.split('\n')[0].split(' ')[0]
fields = {}
for line in output.split('\n'):
if line.startswith('author '):
fields['author'] = line[7:]
elif line.startswith('author-time '):
ts = int(line[12:])
fields['date'] = datetime.fromtimestamp(ts).strftime('%Y-%m-%d')
elif line.startswith('summary '):
fields['summary'] = line[8:]
elif line.startswith('filename '):
fields['filename'] = line[9:]
return {'hash': commit_hash[:8], **fields}
def get_full_commit_context(commit_hash, filepath):
"""获取完整提交信息及关联引用。"""
result = subprocess.run(
['git', 'log', '--format=%H%n%s%n%b', '-1', commit_hash],
capture_output=True, text=True
)
full_message = result.stdout
# 提取工单/issue 引用
refs = []
patterns = [
(r'#(\d+)', 'GitHub Issue/PR'),
(r'[A-Z]+-\d+', 'Jira/Linear ticket'),
(r'fixe?s+#(\d+)', 'Fixes issue'),
(r'close?s+#(\d+)', 'Closes issue'),
(r'https?://[^s]+/(?:issues?|pull)s?/(\d+)', 'Linked URL'),
]
for pattern, label in patterns:
for m in re.finditer(pattern, full_message, re.IGNORECASE):
refs.append({'ref': m.group(0), 'type': label})
# 获取该 commit 中变更的文件列表
stat_result = subprocess.run(
['git', 'show', '--stat', '--format=', commit_hash],
capture_output=True, text=True
)
return {
'full_message': full_message.strip(),
'refs': refs,
'files_changed': stat_result.stdout.strip(),
}
def follow_file_history(filepath):
"""追踪文件在重命名过程中的历史。"""
result = subprocess.run(
['git', 'log', '--follow', '--all', '--oneline', '--', filepath],
capture_output=True, text=True
)
commits = result.stdout.strip().split('\n')
# 查找重命名记录
rename_result = subprocess.run(
['git', 'log', '--follow', '--diff-filter=R', '--summary', '--', filepath],
capture_output=True, text=True
)
renames = re.findall(r'rename (.+?) => (.+?) (\d+%)', rename_result.stdout)
return commits[:10], renames # 最近 10 条提交 + 重命名历史
def classify_commit_quality(summary, body=''):
"""判断提交信息是否说明了「为何如此」。"""
terse_patterns = [
r'^(fix|wip|update|change|edit|stuff|misc|temp|hack|todo).?$',
r'^(fixe?s+\s+\w+|update\s+\w+)$',
r'^[a-z]{1,8}$',
]
for pattern in terse_patterns:
if re.match(pattern, summary.strip().lower()):
return 'MYSTERY', '提交信息过于简略——未说明原因'
if len(summary) < 10:
return 'MYSTERY', '提交信息过短,无法提供有效信息'
if any(keyword in summary.lower() for keyword in ['fix', 'patch', 'hotfix']):
if body:
return 'PARTIAL', '修复类提交——正文可能包含上下文'
return 'PARTIAL', '修复类提交但无正文说明'
return 'GOOD', '提交信息描述了设计意图'
# 搜索所有曾修改过该值或符号的提交 git log --all -S "47000" --oneline -- src/ # -S:pickaxe 搜索——匹配字符串被新增或删除的提交 git log --all -S "TIMEOUT" --oneline -- src/ # 查找该常量首次引入的时间点 # 查找 PR 或 issue 讨论(若远程为 GitHub) git log --all --format="%H %s" | grep -i "timeout|TIMEOUT" # 检查是否在注释、README 或文档中说明过该值 grep -r "47000|TIMEOUT_MS|47 seconds" . --include="*.md" --include="*.txt" -l # 检查测试文件(测试常隐含设计依据) grep -r "47000|TIMEOUT_MS" . --include="*.test.*" --include="*spec*" -A5
## Git 考古报告 目标:`src/auth/middleware.ts:47` — `const TIMEOUT = 47000` --- ### 时间线 **当前状态**(2026-01-15,Alice Chen)
提交:abc1234
信息:“fix timeout issue”
分类:⚠️ MYSTERY —— 提交信息简略,缺乏上下文
**向前追溯...** ```bash git log --all -S "47000" --oneline -- src/ → abc1234 fix timeout issue ← 当前 → def5678 add auth middleware ← 首次引入 → (无更早匹配 —— 此值首次出现于 def5678) ```
首次引入(2025-09-03,Bob Martinez)
提交:def5678
信息:“add auth middleware with session timeout”
正文:“Adds request timeout for auth endpoints.
47s chosen to match our upstream vendor API timeout (46s)
plus 1s buffer. See issue #234 for vendor SLA discussion.”
关联 issue:#234(“Upstream API timeout SLA”)
变更文件:src/auth/middleware.ts (+1), README.md (+3 lines)
abc1234 提交为何修改?(2026-01-15)
该数值本身未变 —— Alice 的 “fix” 提交实际仅修改了同一文件的其他部分(仅格式调整)。TIMEOUT 值自最初引入后便一直保持不变。
为何 TIMEOUT = 47000?
该值由 Bob Martinez 于 2025-09-03 在提交 def5678 中设定。
提交正文说明:“47 秒是为了匹配上游供应商 API 的超时时间(46 秒),并额外预留 1 秒缓冲。”
原始 issue #234(“Upstream API timeout SLA”)中记录了关于供应商 SLA 的完整讨论。
关键发现:该魔法数字源于供应商强加的约束。若供应商调整其 SLA,该值也需同步更新。
建议:添加自解释型注释:
// 47s = upstream vendor API timeout (46s) + 1s buffer. See issue #234. const TIMEOUT = 47000
src/auth/middleware.ts 曾为:src/middleware/auth.js
于 2025-11-20 在提交 bcd9012 中重命名(“restructure middleware directory”) 完整历史(跨越新旧路径共 10 条提交): abc1234 (2026-01-15) fix timeout issue xyz7890 (2025-12-01) add unit tests for middleware bcd9012 (2025-11-20) restructure middleware directory [RENAME] mno3456 (2025-10-14) add error handling to auth middleware def5678 (2025-09-03) add auth middleware with session timeout ← 起源
src/auth/middleware.ts 中还包含 2 处神秘代码块: 第 23 行:const MAX_RETRIES = 3
→ 提交:“update”(abc3333,2025-10-01)——信息简略,无正文,无关联 issue
→ 无更早提交涉及该值
→ 建议:调查为何是 3,而非 2 或 5 第 89 行:if (user.role === 'legacy_admin') {
→ 提交:“fix”(abc4444,2026-01-10)——信息简略,无正文
→ git log -S "legacy_admin":首次出现于 abc9999(2024-06-15)“add legacy admin support”
→ 原始提交正文:“Temporary backward compat for users migrated from v1. Remove after 2025-Q1.”
→ 🚨 已逾期移除——原文明确要求“2025 年第一季度后移除”
--- ## 快速模式输出
Git 考古:src/auth/middleware.ts:47(TIMEOUT = 47000)
起源:def5678(2025-09-03,Bob Martinez)—— “add auth middleware with session timeout”
原因:“47s = upstream vendor API timeout (46s) + 1s buffer. See issue #234.”
现状:abc1234(2026-01-15)—— 仅为格式调整,数值自起源起未变
文件曾重命名自:src/middleware/auth.js → src/auth/middleware.ts(2025-11-20)
🚨 发现异常:第 89 行 if (user.role === 'legacy_admin') 在其起源提交中标记为
“after 2025-Q1” 移除 —— 当前仍存在,已逾期 12 个月。
运行 /git-blame-archaeologist --find-mysteries src/ 可扫描整个目录。
--- ## 作者 **[Canlah AI](https://canlah.ai)** —— 在不损害品牌前提下开展效果营销。 - GitHub:[github.com/PHY041](https://github.com/PHY041) - 全部技能:[clawhub.ai/PHY041](https://clawhub.ai/PHY041)