diff --git a/scripts/hooks/README.md b/scripts/hooks/README.md index 1197c975..e361a48e 100644 --- a/scripts/hooks/README.md +++ b/scripts/hooks/README.md @@ -23,10 +23,11 @@ Bash 직후 ──> post-bash ──> desktop에서 pnpm·게이트를 돌 | N6 | 같은 때, 테스트 파일(`tests/**`, `*.test.*`·`*.spec.*`·`*.stories.*`) | 마지막 커밋(`git show HEAD:`)보다 `.skip`·`.only`·`.fixme`·`.todo`가 늘었는지 센다 | 늘어난 수와 「꼭 지킬 것 4」 | | N6 | 같은 때, 게이트 기준 파일(`config/performance/budgets.json`, `config/scale/`, `config/testing/`, `config/ci/ungated-*.json`, `config/**/*baseline*.json`, `vitest.config.ts`, 스냅숏) | 편집 자체를 알린다 | 「게이트의 기준 파일」 한 줄과 「꼭 지킬 것 4」 | | N2 | 같은 때, `*.md` | `scripts/check-work-docs.py`를 돌린다(작업 매뉴얼의 분량·이력 ID·뼈대·상대 링크) | 실패 줄. 고친 문서를 가리키는 줄이 있으면 그것만 | -| N5 | Stop | 이 세션에서 desktop만 확인할 수 있는 파일(아래 밖의 모든 파일)을 고친 뒤 desktop 실행이 없으면 턴을 한 번 막고 이유를 준다 | `decision: block`, 다음 편집 전까지 한 번 | +| N5 | Stop | 이 세션에서 desktop만 확인할 수 있는 파일(이 repo 파일 가운데 아래 밖의 모든 파일)을 고친 뒤 desktop 실행이 없으면 턴을 한 번 막고 이유를 준다 | `decision: block`, 다음 편집 전까지 한 번 | - N5가 "desktop 실행"으로 치는 것: `ssh …`로 pnpm·`ci:gate`·`verify.sh`·vitest·playwright·`node scripts/…`를 돌린 명령(로그를 읽기만 하는 `cat`·`grep`·`tail` 등은 빼고), 또는 `scripts/verify.sh`를 명령으로 `docs`·`hooks` 밖 단계로(`--on here`·`--dry-run` 없이) 돌린 명령. 앞의 `VAR=값`과 `timeout`·`nohup`·`bash` 같은 감싸는 낱말, ssh 옵션과 그 값(`-o BatchMode=yes`, `-p 22`)은 건너뛴다. `verify.sh`를 읽는 명령(`sed`, `grep`, `git log -- scripts/verify.sh`)은 세지 않는다. - N5가 세지 않는 파일(노트북에서 확인되는 것): `.claude/`의 설정·훅 상태, `scripts/hooks/`·`scripts/tests/`의 코드, `scripts/check-work-docs.py`, `docs/ledger/`의 장부. 이것들은 `scripts/verify.sh docs`·`hooks`가 노트북에서 본다. 그 폴더의 문서(`.md`)와 `CLAUDE.md`, `src/**/AGENTS.md`·`CLAUDE.md`는 desktop `verify:documentation`도 보므로 센다. +- N5는 checkout 안에 있어도 다른 git repo의 파일(예: 카드 저장소 사본) 가운데 `scripts/verify.sh`가 desktop에 보내는 트리(추적 파일과 무시되지 않는 새 파일)에 없는 것은 세지 않는다. 그 트리에 드는 파일이면 안쪽에 다른 `.git`이 있어도 센다. 같은 repo의 worktree는 다른 repo로 보지 않는다(`.claude/` 아래면 위 규칙대로 `.md`만 센다). git이 답하지 못하면 센다. - N5가 기억하는 것은 `.claude/hook-state/.json`이다(git이 무시한다). - 권한 쪽 차단: `.claude/settings.json`의 `permissions.deny`가 실제 `.env`·`.env.local`·`.env.*.local`·`.env.` 읽기·쓰기를 막는다. `.env.example`은 막지 않는다. diff --git a/scripts/hooks/hooks.py b/scripts/hooks/hooks.py index 03dc4a63..1e93923a 100755 --- a/scripts/hooks/hooks.py +++ b/scripts/hooks/hooks.py @@ -288,6 +288,42 @@ def needs_desktop(path: str) -> bool: return not any(pattern.search(path) for pattern in LAPTOP_ONLY) +def ask_git(folder: Path, *args: str) -> subprocess.CompletedProcess | None: + """git's answer in the folder, or None when none came that can be read.""" + try: + return subprocess.run(["git", *args], cwd=folder, capture_output=True, text=True, timeout=5) + except (OSError, subprocess.TimeoutExpired, UnicodeDecodeError): + return None + + +def common_git_dir(folder: Path) -> Path | None: + """The git directory every worktree of the folder's repository shares, or None when git cannot tell.""" + result = ask_git(folder, "rev-parse", "--path-format=absolute", "--git-common-dir") + if result is None or result.returncode != 0: + return None + found = result.stdout.strip() + # git before 2.31 echoes the option back and answers relative to the folder. + return Path(found).resolve() if os.path.isabs(found) else None + + +def in_another_repository(root: Path, path: str) -> bool: + """A file of a repository nested in this checkout that is not in the tree verify.sh sends to the desktop. + + A worktree shares this repository's common git dir, so it is not another repository. A git directory is + not enough to leave a file out: `git add -A` goes on into a folder that has tracked files, new files too. + Whenever git cannot tell, the file counts. + """ + ours = common_git_dir(root) + if ours is None: + return False + theirs = common_git_dir((root / path).parent) + if theirs is None or theirs == ours: + return False + # What that `git add -A` takes, for the whole checkout: limited to the path, git stops at the nested .git. + sent = ask_git(root, "ls-files", "-z", "--cached", "--others", "--exclude-standard") + return sent is not None and sent.returncode == 0 and path not in sent.stdout.split("\0") + + def split_words(text: str) -> list[str]: try: return shlex.split(text) @@ -371,15 +407,16 @@ def post_edit(payload: dict) -> int: source = (root / path).read_text(encoding="utf-8") except (OSError, UnicodeDecodeError): source = "" - lines = boundary_findings(root, path, source) + standard_findings(root, path, source) - if wants_doc_check(path): - lines += doc_findings(root, path) - if needs_desktop(path): + if needs_desktop(path) and not in_another_repository(root, path): + # Recorded first: the document check below may take long enough for the hook's time limit. state = load_state(root, payload.get("session_id", "")) if path not in state["pending"]: state["pending"].append(path) state["reminded"] = False save_state(root, payload.get("session_id", ""), state) + lines = boundary_findings(root, path, source) + standard_findings(root, path, source) + if wants_doc_check(path): + lines += doc_findings(root, path) if lines: print(context("PostToolUse", lines)) return 0 diff --git a/scripts/tests/test_hooks.py b/scripts/tests/test_hooks.py index ac1563e9..80d361a8 100644 --- a/scripts/tests/test_hooks.py +++ b/scripts/tests/test_hooks.py @@ -284,6 +284,131 @@ class TurnEndNudgeTest(RepositoryTestCase): self.edit(path, "x\n") self.assertIsNotNone(self.stop()) + def test_a_file_of_another_repository_inside_the_checkout_does_not_need_the_desktop(self) -> None: + # The desktop gates never see a nested clone (a project-docs copy): verify.sh sends this repository's tree. + path = "cards-copy/projects/x/card.md" + self.repo.write(path, "# card\n") + self.repo.git("init", "-q", "cards-copy") + run_event("post-edit", self.repo.payload(path)) + self.assertIsNone(self.stop()) + + def test_another_repository_does_not_hide_an_edit_of_this_one(self) -> None: + self.repo.write("cards-copy/card.md", "# card\n") + self.repo.git("init", "-q", "cards-copy") + run_event("post-edit", self.repo.payload("cards-copy/card.md")) + self.edit("src/domain/order.ts", "export const a = 7;\n") + reason = self.stop()["reason"] + self.assertIn("src/domain/order.ts", reason) + self.assertNotIn("cards-copy", reason) + + def test_an_ignored_worktree_of_this_repository_still_needs_the_desktop(self) -> None: + self.repo.write(".git/info/exclude", "lanes/\n") + self.repo.git("worktree", "add", "-q", "--detach", "lanes/wt") + self.edit("lanes/wt/src/domain/order.ts", "export const a = 8;\n") + self.assertIsNotNone(self.stop()) + + def test_a_folder_git_cannot_read_still_needs_the_desktop(self) -> None: + self.repo.write("broken/.git", "gitdir: /nonexistent/gitdir\n") + self.edit("broken/note.md", "# note\n") + self.assertIsNotNone(self.stop()) + + def test_a_root_git_cannot_read_still_needs_the_desktop(self) -> None: + self.repo.git("init", "-q", "cards-copy") + (self.repo.root / ".git").rename(self.repo.root / "git-moved-away") + # A TMPDIR inside some checkout must not answer for the root. + with mock.patch.dict(os.environ, {"GIT_CEILING_DIRECTORIES": str(self.repo.root.parent)}): + self.edit("cards-copy/card.md", "# card\n") + self.assertIsNotNone(self.stop()) + + def test_a_tracked_file_below_a_stray_git_directory_still_needs_the_desktop(self) -> None: + # `git add -A` in verify.sh still sends it: this repository's index has the path. + self.repo.git("init", "-q", "src/domain") + self.edit("src/domain/order.ts", "export const a = 10;\n") + self.assertIsNotNone(self.stop()) + + def test_a_new_file_below_a_stray_git_directory_still_needs_the_desktop(self) -> None: + # verify.sh's `git add -A` goes on into a folder that has tracked files, stray .git or not. + self.repo.git("init", "-q", "src") + for path in ("src/domain/new.ts", "src/features/a/index.ts", "src/*.md"): + with self.subTest(path=path): + self.edit(path, "export const a = 10;\n") + self.assertIsNotNone(self.stop()) + + def test_an_ignored_file_is_not_taken_for_the_tracked_one_its_name_starts(self) -> None: + self.repo.write("cards-copy/card.md", "# tracked before the copy\n") + self.repo.git("add", "cards-copy/card.md") + self.repo.git("init", "-q", "cards-copy") + self.repo.write(".git/info/exclude", "card.m\n") + self.edit("cards-copy/card.m", "ignored\n") + self.assertIsNone(self.stop()) + + def test_an_index_git_cannot_read_still_needs_the_desktop(self) -> None: + self.repo.git("init", "-q", "cards-copy") + self.repo.write(".git/index", "not an index\n") + self.edit("cards-copy/card.md", "# card\n") + self.assertIsNotNone(self.stop()) + + def test_an_answer_that_is_not_an_absolute_path_still_needs_the_desktop(self) -> None: + # Before git 2.31 rev-parse echoes the option it does not know, exits 0 and answers relative to the folder. + run = subprocess.run + + def older_git(command, **options): + return run([word.replace("--path-format=", "--unknown-format=") for word in command], **options) + + # An ignored file: only the comparison of the two git dirs can keep it counted. + self.repo.write(".git/info/exclude", "*.local\n") + with mock.patch.object(hooks.subprocess, "run", side_effect=older_git): + self.edit("src/domain/new.local", "export const a = 11;\n") + self.assertIsNotNone(self.stop()) + + def test_an_answer_git_cannot_give_in_time_or_in_utf8_still_needs_the_desktop(self) -> None: + run = subprocess.run + timeout = subprocess.TimeoutExpired("git", 5) + undecodable = UnicodeDecodeError("utf-8", b"\xff", 0, 1, "invalid start byte") + for name, failing_call, error in (("root timeout", 1, timeout), ("file timeout", 2, timeout), + ("index timeout", 3, timeout), ("root not utf-8", 1, undecodable), + ("file not utf-8", 2, undecodable)): + with self.subTest(name): + copy = f"copy-{failing_call}-{type(error).__name__}" + self.repo.git("init", "-q", copy) + waits = [] + + def failing_git(command, **options): + waits.append(options.get("timeout")) + if len(waits) == failing_call: + raise error + return run(command, **options) + + self.repo.write(f"{copy}/card.txt", "card\n") + with mock.patch.object(hooks.subprocess, "run", side_effect=failing_git): + run_event("post-edit", self.repo.payload(f"{copy}/card.txt")) + # No further git call once one has not answered, each within the hook's own limit. + self.assertEqual(waits, [5] * failing_call) + self.assertIsNotNone(self.stop()) + + def test_the_edit_is_recorded_before_the_slower_document_check(self) -> None: + pending = [] + + def document_check(root, path): + pending.extend(hooks.load_state(root, "s1")["pending"]) + return [] + + with mock.patch.object(hooks, "doc_findings", side_effect=document_check): + self.edit("docs/work/improve.md", "# x\n") + self.assertEqual(pending, ["docs/work/improve.md"]) + + def test_a_worktree_under_dot_claude_follows_that_folders_rule(self) -> None: + self.repo.git("worktree", "add", "-q", "--detach", ".claude/worktrees/wt") + self.edit(".claude/worktrees/wt/src/domain/order.ts", "export const a = 12;\n") + self.assertIsNone(self.stop()) + self.edit(".claude/worktrees/wt/README.md", "# x\n") + self.assertIsNotNone(self.stop()) + + def test_without_a_git_command_an_edit_still_needs_the_desktop(self) -> None: + with mock.patch.object(hooks.subprocess, "run", side_effect=FileNotFoundError("git")): + self.edit("src/domain/order.ts", "export const a = 9;\n") + self.assertIsNotNone(self.stop()) + def test_a_new_edit_after_the_reminder_reminds_again(self) -> None: self.edit("src/domain/order.ts", "export const a = 4;\n") self.stop()