diff --git a/.githooks/commit-msg b/.githooks/commit-msg index 0c94ed5..4e22c2a 100755 --- a/.githooks/commit-msg +++ b/.githooks/commit-msg @@ -63,22 +63,35 @@ fi # 提交发生在会话中途(Stop hook 尚未跑),故此处**先刷新**再判 printf '{"session_id":"%s"}' "$sid" | SKILL_TRACE=1 "$ROOT/.claude/hooks/skill-trace.sh" 2>/dev/null || true -if grep -q 'test-driven-development' "$TRACE" 2>/dev/null; then +# 【DEC-020 α · 签核 D-29 · 2026-09-24】判据从「**本会话出现过**」改成「**本次改动之前**调过」。 +# 原判据 = `grep -q 'test-driven-development' latest.json`,读的是**会话累计**的 skills 字段 +# ⇒ **开头调一次,之后本会话所有提交永久满足** ⇒ 门退化成"一个永远不失败的检查"。 +# 实测(2026-09-15 那场):TDD 只在早期调 1 次,之后 **4 个编码任务**一次没调,**而门全程未响**。 +# 新判据 = **时序**:见 `tools/check_skill_before_edit.py` 的 docstring(含判不了时的处置)。 +MAIN=$(sed -n 's/.*"main"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$TRACE" 2>/dev/null | head -1) +if [ -z "$MAIN" ]; then + printf '⚠ 门 2 跳过:trace 里没有本会话转录路径,判不了。\n' >&2 + exit 0 +fi +IMPL=$(printf '%s\n' "$CHANGED" \ + | grep -E '^(app|backend|src)/.*\.(py|ts|js)$|^(\.claude/hooks|tools)/.*\.(sh|py)$|^\.githooks/' \ + | paste -sd, -) +if REASON=$(python3 "$ROOT/tools/check_skill_before_edit.py" \ + --transcript "$MAIN" --root "$ROOT" --files "$IMPL" 2>&1); then exit 0 fi cat >&2 </dev/null) + $REASON 二选一: - 1) 调用 'test-driven-development' skill 走一遍(先写会失败的测试),再提交; - 2) 若本次无需(如纯配置/文档性质),提交信息里写 [no-skill: <理由>] —— **必须带理由**。 + 1) 先调用 'test-driven-development'(先写会失败的测试),**再动实现**; + 2) 若本次确实无需(如纯配置/文档性质),提交信息里写 [no-skill: <理由>] —— **必须带理由**。 - (依据:母体 KD-9;本门把"该调用 skill 却跳过"从软约束变成可机器校验 —— - 见 避坑库 02 与 docs/复盘/) + (依据:`DEC-020` 的 α / 签核 **D-29** —— 原判据是"本会话**出现过**", + 那等于**一次调用后本会话永久满足**;避坑库 `A2-R15`:门禁判据不得锚在累计状态上) EOF exit 1 diff --git a/tests/test_hooks.py b/tests/test_hooks.py index 0179635..f1716ee 100644 --- a/tests/test_hooks.py +++ b/tests/test_hooks.py @@ -301,6 +301,24 @@ def test_commit_msg_gate1_rejects_bare_no_test_marker(): shutil.rmtree(d, ignore_errors=True) +def _trace_with_transcript(d: Path, lines: list | None = None) -> None: + """按**新契约**造 trace:门 2 自 `DEC-020` α(签核 D-29)起**要读转录**。 + + 默认转录 = 只有一次对 `app/a.py` 的编辑、**没有 TDD** ⇒ 门 2 应当拒。 + ⚠️ 旧版本的测试只造 `latest.json`(无转录)⇒ 新判据会判"判不了"而放行 —— + 那不是放水,是**契约变了**,故这里按新契约补上。 + """ + tp = d / "sess.jsonl" + body = lines if lines is not None else [ + {"type": "assistant", "timestamp": "2026-09-24T10:00:10.000Z", + "message": {"content": [{"type": "tool_use", "name": "Write", + "input": {"file_path": str(d / "app" / "a.py")}}]}}] + tp.write_text("\n".join(json.dumps(x, ensure_ascii=False) for x in body), encoding="utf-8") + (d / ".claude" / "traces" / "latest.json").write_text( + json.dumps({"session_id": "s", "skills": "grilling(1)", "sources": {"main": str(tp)}}), + encoding="utf-8") + + def test_commit_msg_gate2_blocks_when_tdd_skill_absent(): """门 2:改了实现 + 也改了测试,但本会话没调用过 test-driven-development → 拒。""" d = _tmp_repo() @@ -308,10 +326,8 @@ def test_commit_msg_gate2_blocks_when_tdd_skill_absent(): _write(d, "app/a.py") _write(d, "tests/test_a.py") subprocess.run(["git", "add", "-A"], cwd=d, check=True, capture_output=True) - # 造一份"只有别的 skill"的 trace - (d / ".claude" / "traces" / "latest.json").write_text( - json.dumps({"session_id": "s", "skill_calls": 1, "skills": "grilling(1)"}), - encoding="utf-8") + # 造"只有别的 skill + 一份无 TDD 的转录"的 trace + _trace_with_transcript(d) r = subprocess.run(["sh", str(d / ".githooks" / "commit-msg"), str(_msg(d, "feat: x\n"))], cwd=d, capture_output=True, text=True) assert r.returncode == 1, "门 2 应拒绝" @@ -343,8 +359,7 @@ def test_commit_msg_gate2_rejects_bare_no_skill_marker(): _write(d, "app/a.py") _write(d, "tests/test_a.py") subprocess.run(["git", "add", "-A"], cwd=d, check=True, capture_output=True) - (d / ".claude" / "traces" / "latest.json").write_text( - json.dumps({"session_id": "s", "skills": "grilling(1)"}), encoding="utf-8") + _trace_with_transcript(d) r = subprocess.run(["sh", str(d / ".githooks" / "commit-msg"), str(_msg(d, "feat: x [no-skill]\n"))], cwd=d, capture_output=True, text=True) diff --git a/tests/test_skill_gate_timing.py b/tests/test_skill_gate_timing.py new file mode 100644 index 0000000..3b8d22e --- /dev/null +++ b/tests/test_skill_gate_timing.py @@ -0,0 +1,189 @@ +"""门 2 的**时序**判据(`DEC-020` 的 α,签核 **D-29**,2026-09-24)。 + +原来的洞 +-------- +门 2 原判据是 `grep -q 'test-driven-development' latest.json` —— 读的是 `.claude/traces/latest.json` +里那个**会话累计**的 `skills` 字段 ⇒ **开头调一次,之后本会话所有提交永久满足**。 +实测(2026-09-15 那场会话):TDD 只在早期调 1 次,之后 4 个编码任务(含改判分器输入契约的 A2) +一次没调 —— **而这道门全程一次没响过**。它成了「**一个永远不失败的检查**」。 + +新判据(α) +---------- +> 门 2 通过 ⟺ 存在一次 `test-driven-development` 调用,其时刻落在 +> **`[本轮起点, 本次提交里最早那次实现文件编辑]`** 之间。 +> 「本轮起点」= 该最早编辑**之前最近的那条 user 消息**的时刻。 +> 人话:**在这一轮里、动实现之前,调过 TDD。** + +⚠️ **判不了时不阻断**(记 `undecidable` 并出声)—— 本会话若从未编辑过这些文件 +(如文件是别处改的),拦下来就是**误拦**;而误拦是守卫被关掉的头号原因。 + +⚠️ 同族:`test_evidence_coverage.py` —— 本文件**自造转录**,不依赖真实 session。 +""" +import json +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +TOOL = ROOT / "tools" / "check_skill_before_edit.py" + +IMPL = "app/eval_gate/rules.py" + + +def _line(kind: str, ts: str, **kw) -> dict: + """造一条最小转录行(形态与真实 session JSONL 一致)。""" + if kind == "user": + return {"type": "user", "timestamp": ts, "message": {"content": kw["text"]}} + block = {"type": "tool_use", "name": kw["name"], "input": kw["input"]} + return {"type": "assistant", "timestamp": ts, "message": {"content": [block]}} + + +def _transcript(tmp: Path, lines: list[dict]) -> Path: + tmp.mkdir(parents=True, exist_ok=True) + p = tmp / "sess.jsonl" + p.write_text("\n".join(json.dumps(x, ensure_ascii=False) for x in lines), encoding="utf-8") + return p + + +def _run(transcript: Path, files: str = IMPL) -> subprocess.CompletedProcess: + return subprocess.run( + [sys.executable, str(TOOL), "--transcript", str(transcript), "--files", files], + capture_output=True, text=True) + + +def _tdd(ts): + return _line("asst", ts, name="Skill", input={"skill": "test-driven-development"}) + + +def _edit(ts, path=IMPL): + return _line("asst", ts, name="Edit", input={"file_path": path}) + + +def _commit(ts): + """转录里 `git commit` 是一条 **Bash 工具调用** —— 判据拿它当"上一段工作的结束"。""" + return _line("asst", ts, name="Bash", input={"command": "git commit -m 'x'"}) + + +T = "2026-09-24T10:{:02d}:00.000Z" + + +# ── 该通过 ──────────────────────────────────────────────────────────── + +def test_tdd_before_first_impl_edit_passes(tmp_path): + """本轮先调 TDD、再动实现 ⇒ 通过(这正是 TDD 要求的顺序)。""" + tr = _transcript(tmp_path, [ + _line("user", T.format(0), text="实现 X"), + _tdd(T.format(1)), + _edit(T.format(2)), + ]) + assert _run(tr).returncode == 0 + + +# ── 该拦(原判据会放过的三种) ───────────────────────────────────────── + +def test_tdd_after_the_edit_is_blocked(tmp_path): + """**先动实现、后调 TDD** ⇒ 拦 —— 这是「走后门补的 TDD」,不是 TDD。""" + tr = _transcript(tmp_path, [ + _line("user", T.format(0), text="实现 X"), + _edit(T.format(1)), + _tdd(T.format(2)), + ]) + assert _run(tr).returncode == 1 + + +def test_tdd_before_the_last_commit_is_blocked(tmp_path): + """**上次提交之后没再调 TDD** ⇒ 拦 —— 这就是原来那个洞(一次调用永久满足)。 + + ⚠️ 本判据**不看"回合"**(转录里 `type:"user"` 的行不可靠:混着**工具结果**, + 且真用户消息的时间戳与工具调用互相穿插 —— 实测窗口被压成 49ms ⇒ 一律误拦)。 + 锚改用**「上一次 `git commit`」**:它在转录里是可见的 Bash 调用,且语义就是"上一段工作结束"。 + """ + tr = _transcript(tmp_path, [ + _tdd(T.format(0)), + _edit(T.format(1)), + _commit(T.format(2)), # 上次提交 + _edit(T.format(30)), # 新一轮动手 —— 中间没再调 TDD + ]) + assert _run(tr).returncode == 1 + + +def test_same_file_across_commits_is_still_blocked(tmp_path): + """⚠️ **同一个文件跨两次提交**也要拦 —— 这正是"最早那次编辑"取法的洞。""" + tr = _transcript(tmp_path, [ + _tdd(T.format(0)), + _edit(T.format(1)), # 第一次改这个文件(有 TDD) + _commit(T.format(2)), + _edit(T.format(30)), # 又改同一个文件(没 TDD) + ]) + assert _run(tr).returncode == 1 + + +def test_tdd_after_the_last_commit_passes(tmp_path): + """**上次提交之后又调了一次 TDD** ⇒ 通过(即使同一个文件改了很多次)。""" + tr = _transcript(tmp_path, [ + _tdd(T.format(0)), + _edit(T.format(1)), + _commit(T.format(2)), + _tdd(T.format(20)), # 新一轮动手前又调了 + _edit(T.format(30)), + _edit(T.format(31)), + ]) + assert _run(tr).returncode == 0 + + +def test_no_tdd_at_all_is_blocked(tmp_path): + tr = _transcript(tmp_path, [ + _line("user", T.format(0), text="实现 X"), + _edit(T.format(1)), + ]) + assert _run(tr).returncode == 1 + + +# ── 不误拦(守卫活下来的关键) ───────────────────────────────────────── + +def test_undecidable_when_file_never_edited_in_session(tmp_path): + """本会话从没编辑过这个文件(如文件是别处改的)⇒ **判不了,不阻断**,但要说清。""" + tr = _transcript(tmp_path, [ + _line("user", T.format(0), text="只是提交已有改动"), + _tdd(T.format(1)), + ]) + r = _run(tr) + assert r.returncode == 0, "判不了就拦 = 误拦 ⇒ 守卫会被关掉" + assert "判不了" in r.stderr + r.stdout + + +def test_rule_does_not_depend_on_user_lines(tmp_path): + """⚠️ 判据**不得依赖 user 行** —— 转录里那串时间戳不可靠。 + + 2026-09-24 实测:`type:"user"` 的行里**混着工具结果**,而真用户消息的时间戳又与 + 工具调用**互相穿插**(同一个 Skill 调用 .556、用户行 .604/.605 —— 顺序都乱)。 + 据此定"本轮起点",窗口会被压成 **49 毫秒** ⇒ **一律误拦**(连我自己那次提交都被拦下)。 + ⇒ 本判据只看**实现编辑的时间序**;故**整份转录没有 user 行,也必须判得对**。 + """ + tr = _transcript(tmp_path, [_tdd(T.format(1)), _edit(T.format(2))]) + assert _run(tr).returncode == 0, "没有 user 行也要能判:先调 TDD 再动手 ⇒ 通过" + + tr2 = _transcript(tmp_path / "b", [_edit(T.format(1)), _tdd(T.format(2))]) + assert _run(tr2).returncode == 1, "没有 user 行也要能判:先动手后补 ⇒ 拦" + + +def test_other_skills_do_not_satisfy_the_gate(tmp_path): + """只有 `test-driven-development` 算数 —— 别的 skill 调再多也不行。""" + tr = _transcript(tmp_path, [ + _line("user", T.format(0), text="实现 X"), + _line("asst", T.format(1), name="Skill", input={"skill": "grilling"}), + _edit(T.format(2)), + ]) + assert _run(tr).returncode == 1 + + +def test_tdd_in_the_same_turn_but_before_edit_of_a_partially_staged_file(tmp_path): + """**多条实现文件**:TDD 须早于**最早**那次实现编辑(不是最晚)。""" + tr = _transcript(tmp_path, [ + _line("user", T.format(0), text="两件事"), + _edit(T.format(1), "app/eval_gate/judge.py"), # 先改了 A + _tdd(T.format(2)), # 才补 TDD + _edit(T.format(3), IMPL), # 再改 B + ]) + assert _run(tr, files=f"{IMPL},app/eval_gate/judge.py").returncode == 1, \ + "A 是在 TDD 之前改的 ⇒ 整体应拦" diff --git a/tools/check_skill_before_edit.py b/tools/check_skill_before_edit.py new file mode 100644 index 0000000..23a8b1f --- /dev/null +++ b/tools/check_skill_before_edit.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""门 2 的**时序**判据(`DEC-020` 的 α,签核 **D-29**,2026-09-24)。 + +原来的洞 +-------- +门 2 原判据是 `grep -q 'test-driven-development' .claude/traces/latest.json` —— +读的是那个**会话累计**的 `skills` 字段 ⇒ **开头调一次,之后本会话所有提交永久满足**。 +实测(2026-09-15 那场会话):TDD 只在早期调 1 次,之后 4 个编码任务(含改判分器输入契约的 A2) +一次没调 —— **而这道门全程一次没响过**。它退化成「**一个永远不失败的检查**」, +而它**比没有检查更坏**:让下游(锚点/复盘/签核)相信"这里有结构兜着"。 + +新判据 +------ +> 取 **`lo` = 上一次 `git commit` 的时刻**(转录里它是一条 Bash 调用); +> **通过 ⟺ 存在一次 `test-driven-development` 调用,其时刻落在 `(lo, 本次最早那次实现编辑]`**。 +> 人话:**自上次提交以来、动手之前,调过 TDD。** + +⚠️ **这个判据是第三版** —— 前两版都被**实跑**证伪,过程值得留: +1. **第一版**用「本会话出现过」(原实现)⇒ 开头调一次**永久满足**,门从不响; +2. **第二版**用「本次编辑之前最近的那条 `type:"user"` 行」当"本轮起点" —— + **实测证伪**:`type:"user"` 的**行**里混着**工具结果**,而真用户消息的时间戳又与工具调用 + **互相穿插**(同一 Skill 调用 `.556` vs 用户行 `.604/.605`)⇒ 窗口被压成 **49 毫秒** + ⇒ **一律误拦**(连那次改动自己的提交都被它拦下); +3. **第三版(本版)**改用 `git commit` 作锚。它还顺手堵了一个洞: + 用「最早那次**编辑**」会被**上一段工作的编辑**污染(同一文件跨两次提交时 → 放行); + 而 `git commit` 是"上一段工作结束"的**真实**边界。 + +⚠️ **判不了 ⇒ 不阻断**(打印 `undecidable`)—— `lo` 之后本会话若从未编辑过这些文件 +(如文件是别处改的),拦下来就是**误拦**;而误拦是守卫被关掉的头号原因。 +**代价(认下)**:这条路径**可被利用**,所以它**每次都会出声**,不当成"通过"。 + +⚠️ 已知边界(`D-29` 签核时预登记):**同一件工作分多次提交**时可能被拦 ⇒ +用显式豁免 `[no-skill: <理由>]`(由 `commit-msg` 处理,豁免率可统计)。 + +⚠️ **判不了 ⇒ 不阻断**(打印 `undecidable`)—— 本会话若从未编辑过这些文件(如文件是别处改的), +拦下来就是**误拦**;而误拦是守卫被关掉的头号原因。**代价(认下)**:这条路径**可被利用**, +所以它**每次都会出声**,不当成"通过"。 + +⚠️ 已知边界(`D-29` 签核时预登记):**同一件工作分多次提交**时可能被拦 ⇒ +用显式豁免 `[no-skill: <理由>]`(由 `commit-msg` 处理,豁免率可统计)。 + +用法:`check_skill_before_edit.py --transcript --files a.py,b.py [--root DIR]` +exit 0 = 通过 / 判不了(后者会出声);1 = 拦。 +""" +from __future__ import annotations + +import argparse +import json +import re +import sys +from datetime import datetime +from pathlib import Path + +TDD_SKILL = "test-driven-development" +EDIT_TOOLS = ("Edit", "Write", "NotebookEdit") +# 转录里 `git commit` 是一条 Bash 工具调用 —— 判据拿它当"上一段工作结束"的锚 +COMMIT_RE = re.compile(r"\bgit\b[^\n;&|]*\bcommit\b") + + +def parse_ts(v) -> datetime | None: + if not v: + return None + try: + return datetime.fromisoformat(str(v).replace("Z", "+00:00")) + except ValueError: + return None + + +def events(transcript: Path) -> list[tuple[datetime, str, str]]: + """按时间顺序产出 `(时刻, 类别, 细节)`;类别 ∈ {user, skill, edit}。""" + out: list[tuple[datetime, str, str]] = [] + for raw in transcript.read_text(encoding="utf-8", errors="replace").splitlines(): + raw = raw.strip() + if not raw: + continue + try: + d = json.loads(raw) + except json.JSONDecodeError: + continue # 转录里有非 JSON 行(实测),跳过即可 + ts = parse_ts(d.get("timestamp")) + if ts is None: + continue + if d.get("type") == "user": + continue # ⚠️ user 行**不用** —— 判据不依赖它(见模块 docstring) + content = (d.get("message") or {}).get("content") + if not isinstance(content, list): + continue + for b in content: + if not isinstance(b, dict) or b.get("type") != "tool_use": + continue + name, inp = b.get("name"), (b.get("input") or {}) + if name == "Skill": + out.append((ts, "skill", str(inp.get("skill") or ""))) + elif name in EDIT_TOOLS: + fp = inp.get("file_path") or inp.get("notebook_path") + if fp: + out.append((ts, "edit", str(fp))) + elif name == "Bash" and COMMIT_RE.search(str(inp.get("command") or "")): + out.append((ts, "commit", "")) + out.sort(key=lambda x: x[0]) + return out + + +def _norm(p: str, root: Path) -> str: + """把编辑路径归一到仓库相对(容忍绝对路径 / 软链)。""" + try: + return str(Path(p).resolve().relative_to(root.resolve())) + except (ValueError, OSError): + return p + + +def judge(evs: list[tuple[datetime, str, str]], files: set[str], root: Path): + """返回 `(verdict, 说明)`;verdict ∈ {ok, block, undecidable}。 + + **取 `lo` = 上一次 `git commit` 的时刻** —— 它是"上一段工作结束"的可观测锚, + 且**不受"同一文件跨多次提交"影响**(用"最早那次编辑"会被上一段的编辑污染,已验证是洞)。 + """ + lo = max((ts for ts, k, _ in evs if k == "commit"), default=None) + + edits = [(ts, _norm(f, root)) for ts, k, f in evs if k == "edit"] + after = [(ts, f) for ts, f in edits if lo is None or ts > lo] + hits = [(ts, f) for ts, f in after if f in files] + if not hits: + return "undecidable", ("本会话**上一次提交之后**没有编辑过本次提交里的实现文件" + " ⇒ 判不了 ⇒ 不阻断(请人工看一眼)") + + t_first = min(ts for ts, _ in hits) + tdd = [ts for ts, k, n in evs if k == "skill" and n == TDD_SKILL] + window = [ts for ts in tdd if ts <= t_first and (lo is None or ts > lo)] + if window: + base = f";上次提交在 {lo.isoformat()}" if lo else ";本会话此前无提交" + return "ok", f"TDD 调用于 {min(window).isoformat()},早于首次实现编辑 {t_first.isoformat()}{base}" + + if not tdd: + why = "本会话**从没**调用过 test-driven-development" + elif max(tdd) > t_first: + why = (f"**先改后补** —— 最早的实现编辑在 {t_first.isoformat()}," + f"而 TDD 那次在 {max(tdd).isoformat()}") + else: + why = (f"**上一次提交({lo.isoformat() if lo else '无'})之后没再调 TDD** —— " + f"TDD 最后一次在 {max(tdd).isoformat()},而本次实现编辑在 {t_first.isoformat()}") + return "block", why + + +def main(argv: list[str] | None = None) -> int: + ap = argparse.ArgumentParser(description="门 2:实现改动之前是否调过 TDD") + ap.add_argument("--transcript", required=True, help="本会话的 session JSONL") + ap.add_argument("--files", required=True, help="本次提交的实现文件(逗号分隔)") + ap.add_argument("--root", default=".", help="仓库根,用于把绝对路径归一到相对") + args = ap.parse_args(argv) + + tr = Path(args.transcript) + if not tr.exists(): + print("⚠ 门 2 跳过:找不到本会话转录,判不了。", file=sys.stderr) + return 0 + + files = {f.strip() for f in args.files.split(",") if f.strip()} + verdict, why = judge(events(tr), files, Path(args.root)) + + if verdict == "ok": + return 0 + if verdict == "undecidable": + print(f"⚠ 门 2 {verdict}:{why}", file=sys.stderr) + return 0 + print(why, file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main())