From 327800798ae1d4fd68a22e50697a07936e5de66f Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 07:05:04 +0900 Subject: [PATCH] =?UTF-8?q?fix(harness):=20main=20checkout=20=EC=95=88=20w?= =?UTF-8?q?orktree=EB=A5=BC=20=ED=86=B5=EC=A7=B8=EB=A1=9C=20=EC=A7=80?= =?UTF-8?q?=EC=9A=B0=EB=8A=94=20rm=EC=9D=84=20=EB=A7=89=EB=8A=94=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: H12는 cwd의 main checkout도 rm 허용 폴더에 넣는다. 그래서 main checkout 안 worktree(.claude/worktrees/…)에서 worktree 자신 (`rm -rf ./*`), 옆 worktree(`rm -rf ../w2`), 그 안(`../w2/src`)을 지우는 것이 통과한다(docs/retro/2026-11-08.md C6). 앱은 worktree 세션의 CLAUDE_PROJECT_DIR를 main checkout으로 주므로 실제 세션이 이 경우다. 고친 방법: 허용 폴더는 그대로 두고 지킬 checkout을 따로 센다. 작업 폴더와 그 repo에 `git worktree list`로 등록된 모든 worktree다. /tmp·앱 임시 작업 폴더 밖에서는 checkout 자신이나 그것을 품은 폴더를 통째로 지우면 막는다. 이 세션 작업 폴더와 같지도, 품지도, 그 안에 있지도 않은 checkout(옆 worktree)은 그 안을 지워도 막는다. 「이 세션 작업 폴더」는 cwd의 checkout을 먼저 본다. 프로젝트 폴더를 먼저 보면 main checkout이 내 것이 되어 옆 worktree 안이 열린다(실제 세션에서 확인). main checkout 안 다른 자리(worktree 밖)와 main checkout 세션이 worktree 안을 치우는 일은 전처럼 통과한다. 버린 대안: worktree 세션에서 main checkout을 허용 폴더에서 빼기(설계 문구에는 맞지만 지금 통과하는 일을 더 많이 막는다. 근거 없이 넓히지 않았다), `.claude/worktrees` 이름으로 판정(다른 곳에 둔 worktree를 놓친다). 위험: 판정마다 git을 한 번 더 부른다(`worktree list`, 시간 제한 5초). 등록되지 않은 폴더(지운 worktree의 남은 폴더)는 지켜지지 않는다. /tmp 아래 worktree는 일부러 그대로 허용한다. 훅 동작이 바뀌어 harness 0.3.1로 올린다. 같은 판정이 전역 ~/.claude/hooks/guard_bash.py 에도 있어 같이 고쳤다. 이 repo가 병합되고 main checkout을 받고 플러그인을 0.3.1로 올리기 전까지 전역 훅 시험의 사본 비교 2줄은 다르다고 나온다. 검증: 새 시험을 main 훅에 돌려 실패를 먼저 봤다(worktree `./*`, main checkout `.claude/worktrees`, 프로젝트 폴더가 main일 때 `../w2/src`). 고친 뒤 scripts/check.sh 통과(harness 28·redteam 21· 템플릿 11, expectedFailure 없음). 새 규칙 둘을 하나씩 끄면 각각 시험이 실패한다. 소유자 기계 세션 기록의 rm -r 647개를 프로젝트 폴더 없이, 또 main checkout으로 주고 옛·새 판정을 비교해 바뀐 것은 이 작업의 확인 명령 1개뿐이었다. Refs: docs/retro/2026-11-08.md C6 --- README.md | 2 +- docs/README.md | 1 + docs/retro/2026-11-08.md | 2 +- plugins/harness/.claude-plugin/plugin.json | 2 +- plugins/harness/scripts/guard_bash.py | 47 +++++++++++++++++++--- plugins/harness/tests/test_hooks.py | 42 ++++++++++++++----- 6 files changed, 77 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 5377c5f..6c2ef96 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ claude-harness ─┬─ 플러그인 harness ──(claude plugin install)─ | 장치 | 때 | 하는 일 | |---|---|---| -| H12 차단 | Bash 실행 직전 | 되돌릴 수 없는 명령을 막는다: 호스팅 원격으로 force push·`--mirror`·보호 브랜치 지우기, 작업 폴더·/tmp 밖이나 너무 넓은 `rm -r`, DB·볼륨·migration 삭제(DROP·TRUNCATE, flyway clean, `-p` 없는 `compose down -v`, `volume rm`, `kubectl delete pvc·ns`). `ssh '…'` 안도 본다 | +| H12 차단 | Bash 실행 직전 | 되돌릴 수 없는 명령을 막는다: 호스팅 원격으로 force push·`--mirror`·보호 브랜치 지우기, 작업 폴더·/tmp 밖이나 너무 넓은 `rm -r`, 작업 폴더 안이라도 git checkout(등록된 worktree 포함)을 통째로 지우거나 옆 worktree 안을 지우는 `rm -r`, DB·볼륨·migration 삭제(DROP·TRUNCATE, flyway clean, `-p` 없는 `compose down -v`, `volume rm`, `kubectl delete pvc·ns`). `ssh '…'` 안도 본다 | | N4 알림 | 파일을 쓴 직후 | 비밀 값처럼 보이는 것(개인 키, 토큰, 값이 있는 password 등)을 몇 줄로 알린다. 막지 않는다 | | 장부 기록 | 세션 시작·턴 끝 | 세션 id와 기록 경로를 `~/.claude/harness/sessions.jsonl`에, 누적 실측(시간·호출·토큰)을 `~/.claude/harness/usage/<세션>.json`에 쓴다. 출력이 없어 컨텍스트 비용이 0이다 | | 회고 넛지 | 세션 시작 | repo 장부에 회고 안 한 빗나간 예측이나 효과 판정할 개선이 있으면, repo마다 하루 한 번 한 줄로 알린다. 없으면 출력이 없다 | diff --git a/docs/README.md b/docs/README.md index d3df5f7..6109fef 100644 --- a/docs/README.md +++ b/docs/README.md @@ -18,6 +18,7 @@ | 12 | 플러그인은 분야 전문가 협업 장치(`lead`·`new-expert`·`harness-eval`, 장부 `eval`)만 싣고, 분야 전문가(스킬·서브에이전트)는 각 템플릿 `.claude/`에 둔다 | 설계(v1)에 없음. v2 설계는 `docs/experts.md` | 기준이 스택마다 다르다. 플러그인 에이전트는 `harness:` 아래 이름이라 템플릿 것과 둘 다 목록에 떠 설명 비용과 고르기 혼란만 는다 | | 13 | 새 스킬 셋(`lead`·`new-expert`·`harness-eval`)도 모델 호출형이고 설명에 발동 조건을 쓴다. `harness-eval`은 설명에 "시킬 때만"을 쓴다 | 13절 Q9와 같음 | 비싼 평가가 저절로 돌지 않게 하는 것은 설명 문장이다. 사용자 호출 전용으로 바꾸려면 Q9를 다시 정해야 한다 | | 14 | `ledger.py usage`의 `agent_return_chars`는 Agent 도구 결과와, 대기열로 들어온 백그라운드 결과(`queued_command`의 `` 밖」을 막는다. 구현이 main checkout도 허용 폴더에 넣어서 그 안의 worktree 자신·옆 worktree가 열려 있었다 | `docs/retro/2026-11-08.md` C6. main checkout 안을 치우는 일(main checkout 세션이 worktree 안을 비우기 등)은 그대로 둔다. 「이 세션 작업 폴더」는 cwd의 checkout으로 먼저 잡는다. 앱이 worktree 세션의 프로젝트 폴더(`CLAUDE_PROJECT_DIR`)를 main checkout으로 주므로, 프로젝트 폴더를 먼저 보면 옆 worktree 안이 열린다(실제 세션에서 확인). 소유자 기계 세션 기록의 `rm -r` 647개(지금 있는 worktree 35곳에서 실행한 338개 포함)를 프로젝트 폴더 없이, 또 main checkout으로 주고 옛 판정과 새 판정으로 돌렸다. 바뀐 것은 이 작업의 확인 명령 1개뿐이었다 | ## 확인한 것과 못 한 것 diff --git a/docs/retro/2026-11-08.md b/docs/retro/2026-11-08.md index 68e4604..737530a 100644 --- a/docs/retro/2026-11-08.md +++ b/docs/retro/2026-11-08.md @@ -133,7 +133,7 @@ | C3 | architecture | 사용자 전역 설정 | 응답 언어를 설정으로 고정할 수 있는지 확인한다. H11 뒤에도 영어 초안이 9번 막혔다 | 5절 | | C4 | user(권한) | 소유자 권한 설정 | 리뷰를 마친 PR 병합, 공개 repo 만들기처럼 분류기가 막는 일을 소유자가 미리 허락하는 규칙. 총괄 세션의 승인은 하위 세션에 넘어가지 않는다 | h2 약 10시간 대기, p1 소유자 개입 2, x2 PR 병합 막힘 | | C5 | instructions | 백엔드 템플릿 장부 | 아래 7절의 retro 줄 3개를 더한다. 그래야 그 repo의 넛지가 멈추고 `calib-median` 판정이 그 장부에서도 돈다 | 3절 | -| C6 | gate | 사용자 전역 훅과 이 repo `guard_bash.py`(둘을 같이) | main checkout 안 worktree(`.claude/worktrees/…`)에서 `rm -rf ./*`(worktree 자신)와 `rm -rf ../옆-worktree`가 통과한다. H12 허용 폴더에 main checkout이 들어가서다. 이 repo 시험에 알려진 빈틈(`expectedFailure`)으로 표시했다. 고치면 그 시험이 「뜻밖의 통과」로 실패해 표시를 지우게 한다 | 이번 `check.sh` | +| C6 | gate | 사용자 전역 훅과 이 repo `guard_bash.py`(둘을 같이) | main checkout 안 worktree(`.claude/worktrees/…`)에서 `rm -rf ./*`(worktree 자신)와 `rm -rf ../옆-worktree`가 통과한다. H12 허용 폴더에 main checkout이 들어가서다. 이 repo 시험에 알려진 빈틈(`expectedFailure`)으로 표시했다. 고치면 그 시험이 「뜻밖의 통과」로 실패해 표시를 지우게 한다. **2026-11-13 고침**: 등록된 worktree를 통째로 지우거나 옆 worktree 안을 지우면 막는다(플러그인 0.3.1과 전역 훅의 같은 절, `docs/README.md` 15번) | 이번 `check.sh` | | C7 | instructions | design-docs 위임 매뉴얼 8절 | 위임 장부에는 회고했는지 적는 자리가 없다. `estimate_ref`가 있는 줄은 그 repo 장부의 retro 줄로, 없는 줄은 이 문서 같은 회고 기록으로 닫는다고 한 줄 | 회고 0 | ## 7. 백엔드 장부에 더할 retro 줄 (C5) diff --git a/plugins/harness/.claude-plugin/plugin.json b/plugins/harness/.claude-plugin/plugin.json index 9403388..7ca45c9 100644 --- a/plugins/harness/.claude-plugin/plugin.json +++ b/plugins/harness/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "harness", "displayName": "Harness", - "version": "0.3.0", + "version": "0.3.1", "description": "프로젝트와 상관없는 공통 하네스: 되돌릴 수 없는 명령 차단(H12), 비밀 값 알림(N4), 예측·실측 장부 훅, 회고 넛지, estimate·retro·techdebt 스킬, 분야 전문가 협업(lead·new-expert)과 하네스 판 비교(harness-eval)", "author": { "name": "donghyeon.kang" diff --git a/plugins/harness/scripts/guard_bash.py b/plugins/harness/scripts/guard_bash.py index 5aeaf14..d653869 100755 --- a/plugins/harness/scripts/guard_bash.py +++ b/plugins/harness/scripts/guard_bash.py @@ -7,6 +7,9 @@ 보내는 force push는 운반이라 통과하되, 보호 브랜치를 덮거나 대상 ref가 없으면 막는다. - `rm -r`: 대상이 이 세션의 git 작업 폴더·/tmp·앱 임시 작업 폴더 밖이거나, 너무 넓다 (`/`, `~`, `~/workspace/<묶음>`, `.git`, 빈 변수로 `/`가 되는 경로, `폴더/*`로 작업 폴더를 통째 비움). + 작업 폴더 안이라도 git checkout(등록된 worktree 포함)이나 그것을 품은 폴더를 통째로 지우거나, 옆 worktree + 안을 지우면 막는다(main checkout 안 worktree에서 `rm -rf ./*`, `rm -rf ../옆-worktree`, `rm -rf ../옆-worktree/src`). + /tmp·앱 임시 작업 폴더 아래는 예외다. - DB·볼륨·migration 삭제: SQL 클라이언트의 DROP DATABASE·SCHEMA·TABLE·TRUNCATE, redis FLUSHALL·FLUSHDB, flyway clean·flywayClean, liquibase drop-all, `-p` 없는 compose `down -v`, `volume rm|prune`, `system prune --volumes`, `kubectl delete pvc|pv|ns`. @@ -410,6 +413,7 @@ VAR_RE = re.compile(r"\$(?:\{([A-Za-z_][A-Za-z0-9_]*)([^}]*)\}|([A-Za-z_][A-Za-z OPAQUE = "\x00" # 명령 치환처럼 값을 알 수 없지만 비지 않는 값 H12_HOME = os.path.expanduser("~") H12_TMP = "/tmp/claude-%d" % os.getuid() +H12_TEMP_ROOTS = ("/tmp", os.path.join(H12_HOME, ".config", "Claude", "scratch-workspaces")) H12_HOME_KEEP = {".ssh", ".config", ".local", ".claude", ".gradle", ".m2", ".cache", ".kube", ".docker", "workspace", "Documents", "Desktop", "Downloads"} @@ -517,10 +521,12 @@ class H12Visitor: remote가 참이면 ssh 원격 명령이다. 원격은 작업 폴더를 모르므로 너무 넓은 대상만 막는다. """ - def __init__(self, cwd, roots, remote=False): + def __init__(self, cwd, roots, checkouts=(), foreign=(), remote=False): self.home = "~" if remote else H12_HOME self.cwd = cwd self.roots = roots + self.checkouts = checkouts + self.foreign = foreign self.remote = remote self.vars = {} self.raw = self.remember @@ -586,6 +592,16 @@ class H12Visitor: return "rm -r %s(너무 넓은 대상: %s)" % (t, path) if not self.remote and not any(under_root(path, r) for r in self.roots): return "rm -r %s(이 작업 폴더·scratchpad 밖: %s)" % (t, path) + if not any(under_root(path, r) for r in H12_TEMP_ROOTS): + # 허용 폴더(main checkout) 안이라도 checkout 자신이나 그것을 품은 폴더는 통째로 지우지 않고, + # 옆 worktree 안도 지우지 않는다. main checkout 안 worktree에서 worktree 자신(`./*`), + # 옆 worktree(`../x`), 그 안(`../x/src`)을 지우는 것을 막는다 + hit = next((c for c in self.checkouts if path == c or under_root(c, path)), None) + if hit: + return "rm -r %s(git checkout 통째: %s)" % (t, hit) + hit = next((c for c in self.foreign if under_root(path, c)), None) + if hit: + return "rm -r %s(다른 worktree 안: %s)" % (t, hit) return None def __call__(self, argv, heredocs): @@ -656,8 +672,15 @@ def data_violation(argv, heredocs): def h12_roots(cwd): - """rm -r을 허용하는 폴더: 프로젝트와 cwd의 git 작업 폴더(와 그 main checkout), /tmp, 앱 임시 작업 폴더.""" - roots = ["/tmp", os.path.join(H12_HOME, ".config", "Claude", "scratch-workspaces")] + """(rm -r을 허용하는 폴더, 지킬 checkout, 옆 worktree). + + 허용 폴더: 프로젝트와 cwd의 git 작업 폴더(와 그 main checkout), /tmp, 앱 임시 작업 폴더. + 지킬 checkout: 그 작업 폴더들과, 그 repo에 등록된 모든 worktree. 허용 폴더 안에 있어도 통째로 지우지 못한다. + 옆 worktree: 지킬 checkout 중 이 세션 작업 폴더와 같지도, 그것을 품지도, 그 안에 있지도 않은 것. 그 안도 못 지운다. + 이 세션 작업 폴더는 cwd의 checkout이고, cwd가 git 밖일 때만 프로젝트 폴더의 checkout이다. 세션의 프로젝트 폴더가 + main checkout이고 cwd가 그 안 worktree일 때 옆 worktree를 남의 것으로 보기 위해서다. + """ + roots, checkouts, tops = list(H12_TEMP_ROOTS), set(), {} for start in {os.environ.get("CLAUDE_PROJECT_DIR"), cwd} - {None, ""}: if not os.path.isdir(start): continue @@ -671,7 +694,20 @@ def h12_roots(cwd): out = os.path.dirname(out) if out and not too_broad(os.path.realpath(out), H12_HOME): roots.append(os.path.realpath(out)) - return roots + checkouts.add(os.path.realpath(out)) + if args[-1] == "--show-toplevel": + tops[start] = os.path.realpath(out) + try: + r = subprocess.run(["git", "-C", start, "worktree", "list", "--porcelain"], + capture_output=True, text=True, timeout=5) + except (OSError, subprocess.SubprocessError): + continue + if r.returncode == 0: + checkouts.update(os.path.realpath(line[len("worktree "):]) for line in r.stdout.splitlines() + if line.startswith("worktree ")) + mine = tops.get(cwd) or tops.get(os.environ.get("CLAUDE_PROJECT_DIR")) + foreign = [c for c in checkouts if mine and not (c == mine or under_root(mine, c) or under_root(c, mine))] + return roots, sorted(checkouts), sorted(foreign) H12_HINTS = { @@ -694,7 +730,8 @@ def check_h12(command, cwd=None): """H12 막을 이유(메시지). 통과면 None.""" if not re.search(r"(?i)push|rm|drop|truncate|flush|clean|down|volume|prune|delete", command): return None - what = walk(command, H12Visitor(os.path.realpath(cwd) if cwd else None, h12_roots(cwd))) + roots, checkouts, foreign = h12_roots(cwd) + what = walk(command, H12Visitor(os.path.realpath(cwd) if cwd else None, roots, checkouts, foreign)) if not what: return None return H12_MESSAGE.format(what=what, hint=H12_HINTS[what.split(":", 1)[0]]) diff --git a/plugins/harness/tests/test_hooks.py b/plugins/harness/tests/test_hooks.py index 71a1cd8..3ae830d 100644 --- a/plugins/harness/tests/test_hooks.py +++ b/plugins/harness/tests/test_hooks.py @@ -50,13 +50,13 @@ def outside_tmp_base(): class H12Asserts: ALWAYS = {"HARNESS_H12": "always"} - def assert_blocked(self, command, cwd=REPO): - r = run("guard_bash.py", payload=bash(command, cwd), env=self.ALWAYS) + def assert_blocked(self, command, cwd=REPO, env=None): + r = run("guard_bash.py", payload=bash(command, cwd), env={**self.ALWAYS, **(env or {})}) self.assertEqual(r.returncode, 2, "막혀야 한다: %s\n%s" % (command, r.stderr)) self.assertIn("[H12", r.stderr) - def assert_passed(self, command, cwd=REPO): - r = run("guard_bash.py", payload=bash(command, cwd), env=self.ALWAYS) + def assert_passed(self, command, cwd=REPO, env=None): + r = run("guard_bash.py", payload=bash(command, cwd), env={**self.ALWAYS, **(env or {})}) self.assertEqual(r.returncode, 0, "통과해야 한다: %s\n%s" % (command, r.stderr)) @@ -136,24 +136,44 @@ class GuardRmCheckoutTest(H12Asserts, unittest.TestCase): git(base, "init", "-q", cls.checkout) git(cls.checkout, "commit", "-q", "--allow-empty", "-m", "init") cls.worktree = os.path.join(cls.checkout, ".claude", "worktrees", "w") - git(cls.checkout, "worktree", "add", "-q", "--detach", cls.worktree) + cls.sibling = os.path.join(cls.checkout, ".claude", "worktrees", "w2") + for wt in (cls.worktree, cls.sibling): + git(cls.checkout, "worktree", "add", "-q", "--detach", wt) + # scratchpad처럼 /tmp 아래 둔 worktree. /tmp 아래는 일부러 허용하므로 통째로 지워도 통과해야 한다 + cls.tmp_worktree = os.path.join(tempfile.mkdtemp(prefix="h12-test-", dir="/tmp"), "wt") + cls.addClassCleanup(shutil.rmtree, os.path.dirname(cls.tmp_worktree), True) + git(cls.checkout, "worktree", "add", "-q", "--detach", cls.tmp_worktree) def test_rm_inside_checkout_and_worktree_passes(self): # 둘 다 허용 폴더로 잡힌다. 아래 시험이 막히는 것은 위치를 몰라서가 아니라 대상이 넓어서다 for cwd in (self.checkout, self.worktree): - self.assert_passed("rm -rf build", cwd=cwd) + for c in ("rm -rf build", "rm -rf build dist node_modules/.cache", "rm -rf ./out/*"): + self.assert_passed(c, cwd=cwd) + self.assert_passed("rm -rf ../../build", cwd=self.worktree) # main checkout 안, worktree 밖(.claude/build) + self.assert_passed("rm -rf .claude/worktrees/w/build", cwd=self.checkout) # main checkout이 worktree 안을 치운다 + + def test_rm_tmp_worktree_passes(self): + for cwd in (self.checkout, self.worktree): + self.assert_passed("rm -rf %s" % self.tmp_worktree, cwd=cwd) def test_rm_whole_checkout_or_sibling_is_blocked(self): - for c in ("rm -rf ./*", "rm -rf ../other-repo/src"): + for c in ("rm -rf ./*", "rm -rf ../other-repo/src", "rm -rf .claude/worktrees", "rm -rf .claude/worktrees/w"): self.assert_blocked(c, cwd=self.checkout) - @unittest.expectedFailure def test_rm_nested_worktree_itself_or_sibling_is_blocked(self): - """알려진 빈틈: main checkout 안의 worktree에서는 허용 폴더에 main checkout이 들어가 worktree 자신이나 - 옆 worktree를 지우는 것이 통과한다. 전역 훅과 같이 고친다. 고치면 이 시험의 expectedFailure를 뗀다.""" - for c in ("rm -rf ./*", "rm -rf ../other-worktree"): + """main checkout 안 worktree에서 worktree 자신, 옆 worktree, 그 안, 둘을 품은 폴더를 지우지 못한다.""" + for c in ("rm -rf ./*", "rm -rf ../w2", "rm -rf ../w2/src", "rm -rf ..", "rm -rf ../.."): self.assert_blocked(c, cwd=self.worktree) + def test_project_dir_main_checkout_still_guards_nested_worktree(self): + """앱이 worktree 세션의 CLAUDE_PROJECT_DIR를 main checkout으로 줄 때도 같은 판정이다(세션 cwd가 먼저다).""" + env = {"CLAUDE_PROJECT_DIR": self.checkout} + for c in ("rm -rf ./*", "rm -rf ../w2", "rm -rf ../w2/src"): + self.assert_blocked(c, cwd=self.worktree, env=env) + for c in ("rm -rf build", "rm -rf ../../build"): + self.assert_passed(c, cwd=self.worktree, env=env) + self.assert_passed("rm -rf .claude/worktrees/w/build", cwd=self.checkout, env=env) + class NudgeSecretsTest(unittest.TestCase): def nudge(self, content, tool="Write"):