feat(plugin): 하네스 플러그인과 마켓을 더한다

문제: 되돌릴 수 없는 명령 차단, 비밀 값 알림, 예측·실측 장부가 소유자
기계의 ~/.claude에만 있거나 아예 없다. 다른 기계·파생 서비스·새 프로젝트는
받을 길이 없고, 훅 코드에 이력과 리뷰도 없다.

고른 방법: 이 repo를 플러그인 마켓으로 두고 공통 플러그인 harness 하나를
싣는다(설계 harness/01-harness-design.md 11절, 결정 Q13 (c)·Q15).
- H12(PreToolUse Bash): 호스팅 원격 force push·--mirror·보호 브랜치 지우기,
  작업 폴더·/tmp 밖이나 너무 넓은 rm -r, DB·볼륨·migration 삭제를 막는다.
  셸 파서는 소유자 전역 guard_bash.py와 정의가 같은 사본이다. 사용자 전역
  설정에 guard_bash.py H12가 있으면 건너뛰어 두 번 막지 않는다.
- N4(PostToolUse Write·Edit): 비밀 값 모양을 몇 줄로 알리고 막지 않는다.
- 장부 SessionStart·Stop 훅: ~/.claude/harness/에 세션 기록 경로와 누적
  실측을 쓴다. 출력이 없어 컨텍스트 비용이 0이다.
- 스킬 estimate·retro·techdebt: 모두 모델이 부르고 발동 조건을 설명에
  문단으로 적었다(결정 Q9).
버린 대안: H12에 git reset --hard·clean·checkout -- .를 넣는 것(설계
5.1절). 이 기계 세션 기록의 Bash 명령 43,078개에서 정당한 사용이
61·32·31건이라 거짓 양성이 크다. 전역 훅을 플러그인으로 옮기는 것은
Q13대로 안정된 뒤에 한다.

위험: H12 판정이 전역 훅과 두 벌이다. 소유자 기계의 전역 훅 시험이 두
사본의 정의를 비교한다. 원격(ssh) rm은 작업 폴더를 몰라 너무 넓은
대상만 막는다.

검증:
- python3 -m unittest discover -s plugins/harness/tests: 17개 통과.
  조건을 하나씩 끈 사본 12개에서 모두 실패를 확인했다.
- 같은 판정을 이 기계 세션 기록 명령 43,078개에 돌려 5건이 막힘:
  의도한 막힘 3(desktop 작업 폴더 통째 rm 2, -p 없는 down -v 1),
  시험용 볼륨 rm 1, 당시 프로젝트 폴더를 알 수 없는 rm 1.
- claude plugin validate --strict: 마켓·플러그인 모두 통과.
- 로컬 경로 마켓으로 설치(--scope local) 뒤 새 세션에서 스킬 셋이 보이고
  SessionStart·Stop 훅이 기록을 썼다. 항상 드는 비용 약 698토큰.
This commit is contained in:
DongHyeonka
2026-11-08 00:02:22 +09:00
commit ddbfc3dcc3
11 changed files with 1700 additions and 0 deletions
+736
View File
@@ -0,0 +1,736 @@
#!/usr/bin/env python3
"""하네스 플러그인 PreToolUse(Bash) 가드 — H12 되돌릴 수 없는 명령.
막는 것
- 호스팅 원격으로 force push(`-f`, `--force`, `--force-with-lease`, `+ref`), `--mirror`·`--prune`,
보호 브랜치(main·master·develop·trunk·release) 지우기. 다른 기계 작업 사본 경로(`host:/abs/path`)로
보내는 force push는 운반이라 통과하되, 보호 브랜치를 덮거나 대상 ref가 없으면 막는다.
- `rm -r`: 대상이 이 세션의 git 작업 폴더·/tmp·앱 임시 작업 폴더 밖이거나, 너무 넓다
(`/`, `~`, `~/workspace/<묶음>`, `.git`, 빈 변수로 `/`가 되는 경로, `폴더/*`로 작업 폴더를 통째 비움).
- 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`.
`ssh host '…'` 안의 명령도 본다. 원격은 작업 폴더를 모르므로 너무 넓은 대상만 막는다.
heredoc 본문(커밋 메시지, 파일 내용)은 데이터로 보고 명령으로 읽지 않는다.
두 번 막지 않기: 사용자 전역 `~/.claude/settings.json`에 `guard_bash.py … H12` 훅이 등록돼 있으면
이 플러그인은 아무것도 하지 않는다(같은 판정을 전역 훅이 한다). `HARNESS_H12=always`면 그래도 돈다.
종료 코드 2 = 막음(stderr가 Claude에게 간다). 0 = 통과. 그 밖(이 스크립트의 버그)은 경고만 뜨고 통과한다.
시험: `python3 -m unittest discover -s plugins/harness/tests`
"""
import json
import os
import re
import subprocess
import sys
SHELLS = {"bash", "sh", "zsh", "dash", "ksh"}
RESERVED = {"!", "{", "}", "if", "then", "else", "elif", "fi", "do", "done", "while", "until", "function", "coproc"}
SKIP_SEGMENT = {"for", "case", "select", "esac"}
ASSIGN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\[[^]]*\])?\+?=")
HEREDOC_RE = re.compile(r"(?<!<)<<(-?)[ \t]*(['\"]?)([A-Za-z_][\w.-]*)\2")
OPS = ["&&", "||", ";;", "|&", ";", "|", "&", "\n", "(", ")"]
REDIRS = ["&>>", "&>", "<<<", "<<-", "<<", "<>", "<&", ">&", ">>", ">|", "<", ">"]
SSH_ARG_OPTS = set("bcDEeFIiJLlmOopQRSWwB")
MAX_DEPTH = 6
# ---------------------------------------------------------------- 셸 문자열 읽기
def strip_heredocs(s, bodies):
"""heredoc 본문을 떼어 bodies에 넣고, 자리에 `<<__HD{n}__` 표시를 남긴다.
본문은 보통 데이터(커밋 메시지 등)라 명령으로 읽으면 거짓 양성이 난다.
셸·ssh가 본문을 스크립트로 받는 경우만 따로 다시 읽는다.
"""
lines = s.split("\n")
out = []
i = 0
while i < len(lines):
pending = []
def mark(m):
pending.append((m.group(1) == "-", m.group(3)))
return "<<__HD%d__" % (len(bodies) + len(pending) - 1)
out.append(HEREDOC_RE.sub(mark, lines[i]))
i += 1
for dash, delim in pending:
body = []
while i < len(lines):
line = lines[i]
i += 1
if (line.lstrip("\t") if dash else line) == delim:
break
body.append(line)
bodies.append("\n".join(body))
return "\n".join(out)
def read_paren(s, i):
"""s[i:]에서 짝이 맞는 `)`까지 읽는다. (안쪽 글, `)` 다음 위치)."""
depth = 1
start = i
n = len(s)
while i < n:
c = s[i]
if c == "\\":
i += 2
continue
if c == "'":
j = s.find("'", i + 1)
i = n if j < 0 else j + 1
continue
if c == '"':
i += 1
while i < n and s[i] != '"':
i += 2 if s[i] == "\\" else 1
i += 1
continue
if c == "(":
depth += 1
elif c == ")":
depth -= 1
if depth == 0:
return s[start:i], i + 1
i += 1
return s[start:], n
def find_backtick(s, i):
n = len(s)
while i < n:
if s[i] == "\\":
i += 2
continue
if s[i] == "`":
return i
i += 1
return n
def tokenize(s):
"""따옴표·치환을 고려해 토큰으로 나눈다.
돌려주는 것: (토큰 목록, 명령 치환 안쪽 글 목록)
토큰: ("W", 단어) / ("O", 연산자) / ("R", 리다이렉션)
작은따옴표 안은 치환이 일어나지 않으므로 그대로 단어로 둔다.
"""
toks, subs = [], []
cur, inword = [], False
i, n = 0, len(s)
def flush():
nonlocal cur, inword
if inword:
toks.append(("W", "".join(cur)))
cur, inword = [], False
while i < n:
c = s[i]
if c == "\\":
if i + 1 < n and s[i + 1] == "\n":
i += 2
continue
if i + 1 < n:
cur.append(s[i + 1])
inword = True
i += 2
continue
if c == "'":
j = s.find("'", i + 1)
j = n if j < 0 else j
cur.append(s[i + 1:j])
inword = True
i = j + 1
continue
if c == '"':
inword = True
i += 1
while i < n and s[i] != '"':
if s[i] == "\\" and i + 1 < n:
cur.append(s[i + 1])
i += 2
elif s.startswith("$(", i):
inner, i = read_paren(s, i + 2)
subs.append(inner)
cur.append("$(…)")
elif s[i] == "`":
j = find_backtick(s, i + 1)
subs.append(s[i + 1:j])
cur.append("`…`")
i = j + 1
else:
cur.append(s[i])
i += 1
i += 1
continue
if c == "`":
j = find_backtick(s, i + 1)
subs.append(s[i + 1:j])
cur.append("`…`")
inword = True
i = j + 1
continue
if s.startswith("$(", i):
inner, i = read_paren(s, i + 2)
subs.append(inner)
cur.append("$(…)")
inword = True
continue
if c in "<>" and i + 1 < n and s[i + 1] == "(" and not inword:
inner, i = read_paren(s, i + 2)
subs.append(inner)
continue
if c == "#" and not inword:
j = s.find("\n", i)
i = n if j < 0 else j
continue
if c in " \t\r":
flush()
i += 1
continue
if c in "<>&" and (not inword or "".join(cur).isdigit()):
red = next((r for r in REDIRS if s.startswith(r, i)), None)
if red:
cur, inword = [], False # 2>&1의 2 같은 fd 번호는 버린다
toks.append(("R", red))
i += len(red)
continue
op = next((o for o in OPS if s.startswith(o, i)), None)
if op:
flush()
toks.append(("O", op))
i += len(op)
continue
cur.append(c)
inword = True
i += 1
flush()
return toks, subs
class Command:
def __init__(self):
self.argv = []
self.heredocs = []
def simple_commands(script, bodies):
"""스크립트를 단순 명령 단위로 나눈다. (명령 목록, 명령 치환 안쪽 글 목록)."""
toks, subs = tokenize(strip_heredocs(script, bodies))
cmds, cur = [], Command()
i = 0
while i < len(toks):
kind, val = toks[i]
if kind == "O":
cmds.append(cur)
cur = Command()
elif kind == "R":
if i + 1 < len(toks) and toks[i + 1][0] == "W":
target = toks[i + 1][1]
m = re.fullmatch(r"__HD(\d+)__", target)
if val in ("<<", "<<-") and m and int(m.group(1)) < len(bodies):
cur.heredocs.append(bodies[int(m.group(1))])
i += 1
else:
cur.argv.append(val)
i += 1
cmds.append(cur)
return [c for c in cmds if c.argv or c.heredocs], subs
def skip_opts(argv, j, arg_opts):
while j < len(argv) and argv[j].startswith("-") and argv[j] != "-":
if argv[j] == "--":
return j + 1
j += 2 if argv[j] in arg_opts else 1
return j
def unwrap(argv):
"""앞의 변수 대입·예약어·감싸는 명령(sudo, env, timeout, flock …)을 벗긴다.
돌려주는 것: ("exec", 실제 argv) 또는 ("script", 셸 문자열) 또는 ("none", [])
"""
i = 0
while i < len(argv):
w = argv[i]
name = os.path.basename(w)
if ASSIGN_RE.match(w) or w in RESERVED:
i += 1
elif w in SKIP_SEGMENT:
return ("none", [])
elif name in ("nohup", "builtin", "time", "caffeinate"):
i = skip_opts(argv, i + 1, set())
elif name == "exec":
i = skip_opts(argv, i + 1, {"-a"})
elif name == "command":
if i + 1 < len(argv) and argv[i + 1] in ("-v", "-V"):
return ("none", [])
i = skip_opts(argv, i + 1, set())
elif name == "sudo":
i = skip_opts(argv, i + 1, {"-u", "-g", "-h", "-p", "-C", "-D", "-r", "-t", "-U", "-T"})
elif name == "nice":
i = skip_opts(argv, i + 1, {"-n", "--adjustment"})
elif name == "stdbuf":
i = skip_opts(argv, i + 1, {"-i", "-o", "-e"})
elif name == "ionice":
i = skip_opts(argv, i + 1, {"-c", "-n", "-p", "-P", "-u"})
elif name == "timeout":
i = skip_opts(argv, i + 1, {"-s", "--signal", "-k", "--kill-after"}) + 1
elif name == "xargs":
i = skip_opts(argv, i + 1, {"-I", "-L", "-n", "-P", "-s", "-d", "-E", "-a"})
elif name == "env":
j = i + 1
while j < len(argv):
a = argv[j]
if a in ("-S", "--split-string"):
return ("script", " ".join(argv[j + 1:]))
if a in ("-u", "--unset", "-C", "--chdir"):
j += 2
elif a.startswith("-") or ASSIGN_RE.match(a):
j += 1
else:
break
i = j
elif name == "flock":
j = skip_opts(argv, i + 1, {"-w", "--wait", "--timeout", "-E", "--conflict-exit-code"}) + 1
if j < len(argv) and argv[j] in ("-c", "--command"):
return ("script", argv[j + 1] if j + 1 < len(argv) else "")
i = j
elif name == "watch":
j = skip_opts(argv, i + 1, {"-n", "--interval", "-q", "--equexit"})
return ("script", " ".join(argv[j:]))
elif name == "eval":
return ("script", " ".join(argv[i + 1:]))
else:
return ("exec", argv[i:])
return ("none", [])
def shell_script(argv, heredocs):
"""bash/sh/zsh 호출이 실행하는 것. ("script", 글) / ("file", 경로) / None."""
j = 1
while j < len(argv) and argv[j][:1] in "-+" and argv[j] not in ("-", "--"):
a = argv[j]
if not a.startswith("--") and "c" in a[1:]:
return ("script", argv[j + 1] if j + 1 < len(argv) else "")
j += 2 if a in ("-o", "+o", "-O", "+O", "--rcfile", "--init-file") else 1
if j < len(argv) and argv[j] == "--":
j += 1
if j < len(argv):
return ("file", argv[j])
if heredocs:
return ("script", "\n".join(heredocs))
return None
def ssh_remote(argv, heredocs):
"""ssh가 원격에서 실행할 스크립트. 원격 명령이 없으면 heredoc 본문."""
j = 1
while j < len(argv) and argv[j].startswith("-") and argv[j] != "--":
a = argv[j]
j += 2 if (len(a) == 2 and a[1] in SSH_ARG_OPTS) else 1
if j < len(argv) and argv[j] == "--":
j += 1
j += 1 # 호스트
remote = " ".join(argv[j:])
if heredocs:
remote = (remote + "\n" + "\n".join(heredocs)).strip()
return remote
# ---------------------------------------------------------------- 판정
def walk(script, visit, bodies=None, depth=0):
"""스크립트 안의 모든 실행 지점에 visit(argv, heredocs)를 부른다.
visit가 문자열을 돌려주면 막을 이유로 보고 바로 돌려준다.
visit가 ("recurse", 글)을 돌려주면 그 글을 이어서 본다(ssh 원격 등).
visit에 raw 속성이 있으면 벗기기 전 argv(앞쪽 변수 대입 포함)로 먼저 부른다.
"""
if depth > MAX_DEPTH:
return None
bodies = [] if bodies is None else bodies
cmds, subs = simple_commands(script, bodies)
for sub in subs:
found = walk(sub, visit, bodies, depth + 1)
if found:
return found
raw_visit = getattr(visit, "raw", None)
for cmd in cmds:
found = raw_visit(cmd.argv) if raw_visit else None
if found:
return found
kind, argv = unwrap(cmd.argv)
if kind == "script":
found = walk(argv, visit, bodies, depth + 1)
if found:
return found
continue
if kind == "none" or not argv:
continue
name = os.path.basename(argv[0])
if name in SHELLS:
run = shell_script(argv, cmd.heredocs)
if run and run[0] == "script":
found = walk(run[1], visit, bodies, depth + 1)
if found:
return found
continue
result = visit(argv, cmd.heredocs)
if isinstance(result, tuple) and result[0] == "recurse":
found = walk(result[1], visit, bodies, depth + 1)
if found:
return found
elif result:
return result
return None
GIT_ARG_OPTS = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path", "--config-env",
"--super-prefix", "--list-cmds", "--attr-source"}
# ---------------------------------------------------------------- H12 되돌릴 수 없는 명령
# 이 절과 위의 셸 파서는 소유자 기계의 전역 훅 ~/.claude/hooks/guard_bash.py와 정의가 같다(주석 제외).
# 고치면 두 곳을 같이 고친다. 소유자 기계의 전역 훅 시험이 두 사본을 비교한다.
PROTECTED_REF_RE = re.compile(r"^(refs/heads/)?(main|master|develop|trunk|release([/-].*)?|HEAD)$")
PUSH_OPTS_WITH_ARG = {"-o", "--push-option", "--repo", "--receive-pack", "--exec"}
PATH_REMOTE_RE = re.compile(r"^(/|\./|\.\./|file://|[A-Za-z0-9._-]+:/(?!/))")
SQL_CLIENTS = {"psql", "mysql", "mariadb", "sqlite3", "sqlcmd", "clickhouse-client", "cqlsh"}
SQL_DROP_RE = re.compile(r"(?i)\b(drop\s+(database|schema|table)\b|truncate\b)")
CONTAINER_TOOLS = {"docker", "podman", "nerdctl"}
COMPOSE_TOOLS = {"docker-compose", "podman-compose"}
KUBE_DATA_KIND_RE = re.compile(r"(?i)^(pvc|pv|ns|persistentvolumeclaims?|persistentvolumes?|namespaces?)$")
VAR_RE = re.compile(r"\$(?:\{([A-Za-z_][A-Za-z0-9_]*)([^}]*)\}|([A-Za-z_][A-Za-z0-9_]*))")
OPAQUE = "\x00" # 명령 치환처럼 값을 알 수 없지만 비지 않는 값
H12_HOME = os.path.expanduser("~")
H12_TMP = "/tmp/claude-%d" % os.getuid()
H12_HOME_KEEP = {".ssh", ".config", ".local", ".claude", ".gradle", ".m2", ".cache", ".kube", ".docker",
"workspace", "Documents", "Desktop", "Downloads"}
def push_violation(args):
"""git push 인자에서 force push·보호 브랜치 지우기를 찾는다. 통과면 None.
다른 기계 작업 사본 경로(`desktop:/home/…`)로 보내는 force push는 운반이라 통과한다.
다만 보호 브랜치(main 등)를 덮거나, 대상 ref를 적지 않았으면 막는다.
"""
force = delete = False
words = []
k = 0
while k < len(args):
a = args[k]
if a == "--":
words += args[k + 1:]
break
if a.startswith("--"):
name = a.split("=", 1)[0]
if name in ("--force", "--force-with-lease"):
force = True
elif name in ("--mirror", "--prune"):
return "git push %s(원격 ref를 통째로 덮거나 지운다)" % name
elif name == "--delete":
delete = True
elif name == "--dry-run":
return None
k += 2 if (name in PUSH_OPTS_WITH_ARG and "=" not in a) else 1
continue
if a.startswith("-") and len(a) > 1:
for idx, ch in enumerate(a[1:]):
if ch == "f":
force = True
elif ch == "d":
delete = True
elif ch == "n":
return None
elif ch == "o":
if idx == len(a) - 2:
k += 1 # 값이 다음 단어다
break
k += 1
continue
words.append(a)
k += 1
remote, specs = (words[0], words[1:]) if words else (None, [])
deleted, forced = [], []
for spec in specs:
plus = spec.startswith("+")
src, sep, dst = (spec[1:] if plus else spec).partition(":")
dst = dst if sep else src
if delete or (sep and not src):
deleted.append(dst)
elif force or plus:
forced.append(dst)
for ref in deleted:
if PROTECTED_REF_RE.match(ref):
return "git push로 보호 브랜치 %s 지우기" % ref
if force and not specs:
forced.append("(대상 ref를 적지 않음)")
if not forced:
return None
if not (remote and PATH_REMOTE_RE.match(remote)):
return "force push(원격 %s)" % (remote or "기본값")
for ref in forced:
if not ref or PROTECTED_REF_RE.match(ref) or ref.startswith("("):
return "force push로 %s 덮어쓰기" % (ref or "(빈 ref)")
return None
def rm_targets(args):
"""rm 인자에서 (재귀 삭제인가, 대상 목록)."""
recursive, targets, opts_done = False, [], False
for a in args:
if not opts_done and a == "--":
opts_done = True
elif not opts_done and a.startswith("--"):
recursive = recursive or a == "--recursive"
elif not opts_done and a.startswith("-") and len(a) > 1:
recursive = recursive or "r" in a or "R" in a
else:
targets.append(a)
return recursive, targets
def under_root(path, root):
"""path가 root 아래인가(root 자신은 아니다)."""
return path.startswith(root.rstrip("/") + "/")
def too_broad(path, home):
"""통째로 지우면 되돌릴 수 없는 넓은 경로인가."""
if path in ("/", home, H12_TMP) or os.path.dirname(path) == "/":
return True
if os.path.dirname(path) == home and os.path.basename(path) in H12_HOME_KEEP:
return True
parts = os.path.relpath(path, home).split(os.sep) if under_root(path, home) else []
return len(parts) <= 2 and parts[:1] == ["workspace"] # ~/workspace/<repo 묶음> 통째
class H12Visitor:
"""walk가 부르는 H12 판정기. cd·변수 대입을 따라가며 rm 대상의 실제 위치를 어림한다.
remote가 참이면 ssh 원격 명령이다. 원격은 작업 폴더를 모르므로 너무 넓은 대상만 막는다.
"""
def __init__(self, cwd, roots, remote=False):
self.home = "~" if remote else H12_HOME
self.cwd = cwd
self.roots = roots
self.remote = remote
self.vars = {}
self.raw = self.remember
def expand(self, word):
"""변수를 아는 값으로 바꾼다. 모르는 변수는 빈 값(가장 나쁜 경우), 명령 치환은 OPAQUE."""
if "$(…)" in word or "`…`" in word:
return OPAQUE
def sub(m):
name, rest = (m.group(1), m.group(2)) if m.group(1) else (m.group(3), "")
if name in self.vars:
return self.vars[name]
if name == "HOME":
return self.home
if name == "PWD" and self.cwd:
return self.cwd
if rest.startswith((":?", "?")):
return OPAQUE # 비면 셸이 멈춘다
if rest.startswith((":-", "-")):
return self.expand(rest.lstrip(":")[1:])
return ""
out = VAR_RE.sub(sub, word)
if out == "~" or out.startswith("~/"):
out = self.home + out[1:]
return OPAQUE if OPAQUE in out else out
def remember(self, raw):
"""벗기기 전 argv에서 변수 대입과 for 변수를 기억한다."""
if len(raw) > 1 and raw[0] in ("for", "select"):
self.vars[raw[1]] = OPAQUE
for w in raw:
if w in RESERVED:
continue
if not ASSIGN_RE.match(w):
break
name, _, value = w.partition("=")
self.vars[re.sub(r"\[.*|\+$", "", name)] = self.expand(value)
return None
def locate(self, word):
"""대상 단어의 절대 경로. 모르면 None."""
path = self.expand(word)
if path == OPAQUE or path == "":
return path if path == "" else None
if not path.startswith("/") and not (self.remote and (path == "~" or path.startswith("~/"))):
if not self.cwd:
return None
path = os.path.join(self.cwd, path)
return os.path.normpath(path) if path else ""
def rm_violation(self, targets):
for t in targets:
if os.path.basename(t.rstrip("/")) == ".git":
return "rm -r %s(git 저장소 자체)" % t
path = self.locate(t)
if not path:
continue # 빈 값(rm이 아무것도 안 함)이거나 위치를 모름
if any(c in os.path.basename(path) for c in "*?["):
path = os.path.dirname(path) # `폴더/*`는 그 폴더를 통째로 지우는 것과 같다
if too_broad(path, self.home):
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)
return None
def __call__(self, argv, heredocs):
name = os.path.basename(argv[0])
args = argv[1:]
if name == "ssh":
return walk(ssh_remote(argv, heredocs), H12Visitor(None if self.remote else "~", [], remote=True))
if name in ("cd", "pushd"):
dest = args[0] if args else "~"
self.cwd = None if dest == "-" else (self.locate(dest) or None)
return None
if name in ("export", "declare", "typeset", "local", "readonly"):
self.remember([a for a in args if not a.startswith("-")])
return None
if name == "read":
for a in args:
if not a.startswith("-"):
self.vars[a] = OPAQUE
return None
what = " ".join(argv)
if name == "git":
j = 1
while j < len(argv) and argv[j].startswith("-"):
j += 2 if argv[j] in GIT_ARG_OPTS else 1
if j < len(argv) and argv[j] == "push":
why = push_violation(argv[j + 1:])
return "force push: %s (`%s`)" % (why, what) if why else None
return None
if name == "rm":
recursive, targets = rm_targets(args)
why = self.rm_violation(targets) if recursive else None
return "rm: %s (`%s`)" % (why, what) if why else None
return data_violation(argv, heredocs)
def data_violation(argv, heredocs):
"""DB·볼륨·migration을 지우는 명령. 다른 명령 안(docker exec, kubectl exec)의 클라이언트도 본다."""
names = [os.path.basename(w) for w in argv]
what = " ".join(argv)
for i, n in enumerate(names):
rest = argv[i + 1:]
if n in SQL_CLIENTS and SQL_DROP_RE.search(" ".join(rest + heredocs)):
return "db: DROP·TRUNCATE (`%s`)" % what
if n == "redis-cli" and any(w.lower() in ("flushall", "flushdb") for w in rest):
return "db: redis FLUSHALL·FLUSHDB (`%s`)" % what
if n in ("gradle", "gradlew", "mvn", "mvnw") and any(re.search(r"(^|:)(flywayClean|flyway:clean)$", w)
for w in rest):
return "db: flyway clean(migration 초기화) (`%s`)" % what
if (n == "flyway" and "clean" in rest) or (n == "liquibase" and ({"drop-all", "dropAll"} & set(rest))):
return "db: migration 초기화 (`%s`)" % what
compose = n in COMPOSE_TOOLS or (n in CONTAINER_TOOLS and "compose" in rest)
if compose and "down" in rest:
before, after = rest[:rest.index("down")], rest[rest.index("down") + 1:]
scoped = any(w in ("-p", "--project-name") or w.startswith("--project-name=") or "$" in w
for w in before) # 변수(`${F[*]}`) 안의 -p는 알 수 없어 막지 않는다
if not scoped and any(w == "--volumes" or (w.startswith("-") and not w.startswith("--") and "v" in w) for w in after):
return "volume: compose down -v(-p 없이 기본 프로젝트) (`%s`)" % what
if n in CONTAINER_TOOLS and rest[:1] == ["volume"] and rest[1:2] and rest[1] in ("rm", "prune"):
return "volume: %s volume %s (`%s`)" % (n, rest[1], what)
if n in CONTAINER_TOOLS and rest[:2] == ["system", "prune"] and "--volumes" in rest:
return "volume: system prune --volumes (`%s`)" % what
if n == "kubectl" and "delete" in rest:
kinds = [w for w in rest[rest.index("delete") + 1:] if not w.startswith("-")][:1]
for kind in (kinds[0].split("/")[0].split(",") if kinds else []):
if KUBE_DATA_KIND_RE.match(kind):
return "volume: kubectl delete %s (`%s`)" % (kind, what)
return None
def h12_roots(cwd):
"""rm -r을 허용하는 폴더: 프로젝트와 cwd의 git 작업 폴더(와 그 main checkout), /tmp, 앱 임시 작업 폴더."""
roots = ["/tmp", os.path.join(H12_HOME, ".config", "Claude", "scratch-workspaces")]
for start in {os.environ.get("CLAUDE_PROJECT_DIR"), cwd} - {None, ""}:
if not os.path.isdir(start):
continue
for args in (["rev-parse", "--show-toplevel"], ["rev-parse", "--path-format=absolute", "--git-common-dir"]):
try:
r = subprocess.run(["git", "-C", start, *args], capture_output=True, text=True, timeout=5)
except (OSError, subprocess.SubprocessError):
continue
out = r.stdout.strip() if r.returncode == 0 else ""
if out.endswith("/.git"):
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
H12_HINTS = {
"force push": "이력을 고칠 일이면 새 커밋으로 고쳐 push한다. 원격 이력을 꼭 덮어야 하면 사용자에게 묻는다.",
"rm": "이 작업 폴더나 scratchpad 안의 정확한 경로만 지운다. worktree는 `git worktree remove`로 지운다. "
"변수로 경로를 만들면 같은 명령 안에서 값을 정하거나 `${X:?}`로 빈 값을 막는다.",
"db": "개발 DB를 새로 만들려면 repo의 초기화 스크립트를 쓴다. 운영·공유 DB는 사용자가 직접 한다.",
"volume": "볼륨을 남기고 내린다(`down`만). 시험용 환경은 `-p <고유 이름>`으로 띄우고 같은 `-p`로 `down -v`한다. "
"개발·공유 데이터를 지워야 하면 사용자에게 묻는다.",
}
H12_MESSAGE = """[H12 되돌릴 수 없는 명령] 막은 명령: {what}
원격 이력 덮어쓰기, 작업 폴더 밖 삭제, DB·볼륨·migration 삭제는 되돌릴 수 없어 사용자가 직접 합니다.
대신: {hint}
막은 것이 틀렸다고 보이면 우회하지 말고 사용자에게 알린다."""
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)))
if not what:
return None
return H12_MESSAGE.format(what=what, hint=H12_HINTS[what.split(":", 1)[0]])
def global_h12_registered():
"""사용자 전역 설정에 guard_bash.py H12 훅이 등록돼 있나."""
path = os.path.join(os.path.expanduser("~"), ".claude", "settings.json")
try:
with open(path, encoding="utf-8") as f:
matchers = (json.load(f).get("hooks") or {}).get("PreToolUse") or []
except (OSError, ValueError, AttributeError):
return False
return any(re.search(r"guard_bash\.py\S*\s+H12\b", str(h.get("command", "")))
for m in matchers if isinstance(m, dict) for h in m.get("hooks") or [] if isinstance(h, dict))
def main():
data = json.load(sys.stdin)
if data.get("tool_name") not in (None, "Bash"):
return 0
if os.environ.get("HARNESS_H12") != "always" and global_h12_registered():
return 0
command = (data.get("tool_input") or {}).get("command") or ""
message = check_h12(command, data.get("cwd"))
if message:
print(message, file=sys.stderr)
return 2
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except SystemExit:
raise
except Exception as exc: # 훅 버그는 막지 않고 알리기만 한다
print("harness guard_bash 내부 오류로 검사를 건너뜀: %r" % (exc,), file=sys.stderr)
sys.exit(1)
+361
View File
@@ -0,0 +1,361 @@
#!/usr/bin/env python3
"""예측·실측 장부 도구. 훅 둘과 `estimate`·`retro` 스킬이 부르는 명령을 한 파일에 둔다.
훅(출력 없음 → 컨텍스트 비용 0, 실패해도 작업을 막지 않는다)
session-start SessionStart 입력의 session_id·transcript_path·cwd를 <상태 폴더>/sessions.jsonl에 한 줄 더한다
stop Stop 때마다 세션 기록을 이어 읽어 <상태 폴더>/usage/<session_id>.json에 누적 실측을 덮어쓴다
명령
current 지금 폴더의 세션 기록 경로
usage [기록 경로|uuid] 세션 기록의 실측(JSON). 하위 에이전트 기록(<uuid>/subagents/)을 더한다
actual --task T [기록] T의 예측과 견준 actual 줄 초안(JSON). 쓰지는 않는다
precedents [--kind K] [--size S] 장부의 지난 예측·실측 표
pending 실측은 있고 회고가 없는 작업
append stdin의 JSON 한 줄을 검사해 장부 끝에 더한다
상태 폴더: $HARNESS_STATE_DIR, 없으면 ~/.claude/harness. 장부: <git 최상위>/docs/ledger/estimates.jsonl(--ledger로 바꿈).
실측 규칙: assistant 줄의 message.usage, 같은 message.id는 한 번만(값은 가장 큰 것). 작업 중 시간은 기록 사이
빈틈을 5분까지만 더한 시간이다(끝 보고 뒤 다음 지시를 기다린 시간이 빠진다).
"""
import argparse
import datetime
import glob
import json
import os
import re
import subprocess
import sys
GAP_SECONDS = 300
KINDS = ("estimate", "actual", "retro")
REQUIRED = {
"estimate": ("minutes", "basis"),
"actual": ("active_minutes",),
"retro": ("cause", "level"),
}
CAUSES = ("지시 모호", "착수 전 조사 부족", "아키텍처 경직", "검증 대기", "외부 대기", "범위 변경", "예측 근거 없음")
LEVELS = ("architecture", "gate", "instructions", "user")
def state_dir():
return os.environ.get("HARNESS_STATE_DIR") or os.path.join(os.path.expanduser("~"), ".claude", "harness")
def now_iso():
return datetime.datetime.now().astimezone().isoformat(timespec="minutes")
def epoch(ts):
try:
return datetime.datetime.fromisoformat(ts.replace("Z", "+00:00")).timestamp()
except (AttributeError, ValueError):
return None
def local_iso(seconds):
return datetime.datetime.fromtimestamp(seconds).astimezone().isoformat(timespec="seconds") if seconds else None
# ---------------------------------------------------------------- 세션 기록 읽기
def new_file_state():
return {"offset": 0, "ids": {}, "first": None, "last": None, "active": 0.0}
def scan(path, st):
"""path를 st["offset"]부터 마지막 완전한 줄까지 읽어 st를 갱신한다."""
try:
with open(path, "rb") as f:
f.seek(st["offset"])
chunk = f.read()
except OSError:
return st
end = chunk.rfind(b"\n") + 1
for raw in chunk[:end].split(b"\n"):
if not raw.strip():
continue
try:
d = json.loads(raw)
except ValueError:
continue
t = epoch(d.get("timestamp"))
if t is not None:
if st["first"] is None:
st["first"] = t
if st["last"] is not None and t >= st["last"]:
st["active"] += min(t - st["last"], GAP_SECONDS)
st["last"] = t if st["last"] is None else max(st["last"], t)
msg = d.get("message") if d.get("type") == "assistant" else None
if isinstance(msg, dict) and msg.get("id") and isinstance(msg.get("usage"), dict):
u = msg["usage"]
vals = [int(u.get(k) or 0) for k in
("input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens", "output_tokens")]
old = st["ids"].get(msg["id"])
st["ids"][msg["id"]] = [max(a, b) for a, b in zip(old, vals)] if old else vals
st["offset"] += end
return st
def subagent_files(transcript):
return sorted(glob.glob(os.path.join(transcript[:-len(".jsonl")], "subagents", "*.jsonl")))
def summarize(transcript, files):
"""files: 경로 → 상태. 본 기록의 시간과 모든 기록의 토큰을 합친다."""
main = files.get(transcript) or new_file_state()
ids = [v for st in files.values() for v in st["ids"].values()]
sub_calls = sum(len(st["ids"]) for p, st in files.items() if p != transcript)
first, last = main["first"], main["last"]
return {
"transcript": os.path.basename(transcript)[:-len(".jsonl")],
"started_at": local_iso(first),
"updated_at": local_iso(last),
"minutes": round((last - first) / 60) if first and last else 0,
"active_minutes": round(main["active"] / 60),
"calls": len(ids),
"subagent_calls": sub_calls,
"output_tokens": sum(v[3] for v in ids),
"cache_read_tokens": sum(v[2] for v in ids),
"input_tokens_total": sum(v[0] + v[1] + v[2] for v in ids),
"max_context": max((v[0] + v[1] + v[2] for v in ids), default=0),
}
def usage(transcript, files=None):
files = files if files is not None else {}
for path in [transcript] + subagent_files(transcript):
files[path] = scan(path, files.get(path) or new_file_state())
return summarize(transcript, files), files
def project_dir_name(path):
return re.sub(r"[^A-Za-z0-9-]", "-", path)
def git_toplevel(start):
try:
r = subprocess.run(["git", "-C", start, "rev-parse", "--show-toplevel"], capture_output=True, text=True,
timeout=5)
except (OSError, subprocess.SubprocessError):
return None
return r.stdout.strip() if r.returncode == 0 else None
def current_transcript(cwd=None):
"""지금 폴더의 세션 기록. SessionStart 기록이 먼저, 없으면 ~/.claude/projects/<폴더>/의 가장 새 기록."""
cwd = os.path.realpath(cwd or os.getcwd())
candidates = [cwd] + [p for p in [git_toplevel(cwd)] if p]
try:
with open(os.path.join(state_dir(), "sessions.jsonl"), encoding="utf-8") as f:
rows = [json.loads(line) for line in f if line.strip()]
except (OSError, ValueError):
rows = []
for row in reversed(rows):
if os.path.realpath(row.get("cwd") or "") in candidates and os.path.exists(row.get("transcript_path") or ""):
return row["transcript_path"]
for c in candidates:
files = glob.glob(os.path.join(os.path.expanduser("~"), ".claude", "projects", project_dir_name(c), "*.jsonl"))
if files:
return max(files, key=os.path.getmtime)
return None
def resolve_transcript(arg):
if not arg:
return current_transcript()
if os.path.exists(arg):
return os.path.realpath(arg)
found = glob.glob(os.path.join(os.path.expanduser("~"), ".claude", "projects", "*", arg + ".jsonl"))
return found[0] if found else None
# ---------------------------------------------------------------- 훅
def hook_session_start(data):
os.makedirs(state_dir(), exist_ok=True)
row = {"session_id": data.get("session_id"), "transcript_path": data.get("transcript_path"),
"cwd": data.get("cwd"), "source": data.get("source"), "recorded_at": now_iso()}
with open(os.path.join(state_dir(), "sessions.jsonl"), "a", encoding="utf-8") as f:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
def hook_stop(data):
transcript, session = data.get("transcript_path"), data.get("session_id")
if not transcript or not session or not os.path.exists(transcript):
return
folder = os.path.join(state_dir(), "usage")
os.makedirs(folder, exist_ok=True)
path = os.path.join(folder, re.sub(r"[^A-Za-z0-9_-]", "_", session) + ".json")
try:
with open(path, encoding="utf-8") as f:
saved = json.load(f)
files = saved["files"] if saved.get("transcript_path") == transcript else {}
except (OSError, ValueError, KeyError):
files = {}
summary, files = usage(transcript, files)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump({"session_id": session, "transcript_path": transcript, "cwd": data.get("cwd"),
"summary": summary, "files": files}, f, ensure_ascii=False)
os.replace(tmp, path)
# ---------------------------------------------------------------- 장부
def ledger_path(arg):
if arg:
return arg
top = git_toplevel(os.getcwd()) or os.getcwd()
return os.path.join(top, "docs", "ledger", "estimates.jsonl")
def read_ledger(path):
try:
with open(path, encoding="utf-8") as f:
return [json.loads(line) for line in f if line.strip()]
except OSError:
return []
def by_task(rows):
tasks = {}
for r in rows:
t = tasks.setdefault(r.get("task"), {})
t[r.get("kind")] = {**t.get(r.get("kind"), {}), **r} # correction 줄은 앞 줄을 덮는다
return tasks
def within(estimate, active):
for k in ("p30", "p50", "p80"):
v = (estimate.get("minutes") or {}).get(k)
if v is not None and active <= v:
return k
return "over"
def triple(d):
d = d or {}
return "/".join(str(d.get(k, "-")) for k in ("p30", "p50", "p80"))
def cmd_precedents(args):
tasks = by_task(read_ledger(ledger_path(args.ledger)))
rows = []
for name, t in tasks.items():
e, a = t.get("estimate", {}), t.get("actual", {})
if args.kind and args.kind not in str(e.get("task_kind", "")):
continue
if args.size and args.size != e.get("size"):
continue
rows.append("| %s | %s | %s | %s | %s | %s | %s | %s |" % (
name, e.get("task_kind", "-"), e.get("size", "-"), triple(e.get("minutes")),
a.get("active_minutes", "-"), a.get("calls", "-"), a.get("output_tokens", "-"), a.get("within", "-")))
if not rows:
print("선례 없음. 근거는 손으로 판단할 결정 수, 검증 실행 횟수와 대기, 바꿀 파일 수로 쓴다.")
return 0
print("| 작업 | 종류 | 크기 | 예측 분 p30/p50/p80 | 실측 작업 중 분 | 호출 | 출력 토큰 | 들어간 칸 |")
print("|---|---|---|---|---|---|---|---|")
print("\n".join(rows))
return 0
def cmd_pending(args):
tasks = by_task(read_ledger(ledger_path(args.ledger)))
todo = [(n, t) for n, t in tasks.items() if "actual" in t and "retro" not in t]
for name, t in todo:
a = t["actual"]
print("- %s: 예측 %s분, 실측 %s분(%s). 이유: %s" % (
name, triple(t.get("estimate", {}).get("minutes")), a.get("active_minutes"), a.get("within", "-"),
a.get("why", "-")))
if not todo:
print("회고할 줄 없음.")
return 0
def cmd_actual(args):
transcript = resolve_transcript(args.transcript)
if not transcript:
print("세션 기록을 찾지 못했다. 기록 경로나 uuid를 넘긴다.", file=sys.stderr)
return 1
summary, _ = usage(transcript)
estimate = by_task(read_ledger(ledger_path(args.ledger))).get(args.task, {}).get("estimate", {})
row = {"schema": 1, "kind": "actual", "task": args.task, "recorded_at": now_iso(),
"transcript": summary["transcript"]}
row.update({k: summary[k] for k in ("minutes", "active_minutes", "calls", "output_tokens",
"cache_read_tokens", "max_context")})
row["within"] = within(estimate, summary["active_minutes"]) if estimate else "-"
row.update({"result": "done", "commits": [], "why": ""})
print(json.dumps(row, ensure_ascii=False))
return 0
def cmd_append(args):
row = json.loads(sys.stdin.read())
problems = []
if row.get("kind") not in KINDS:
problems.append("kind는 %s 중 하나" % "·".join(KINDS))
if not row.get("task"):
problems.append("task가 비었다")
for key in REQUIRED.get(row.get("kind"), ()):
if key not in row:
problems.append("%s 줄에는 %s가 있어야 한다" % (row.get("kind"), key))
if row.get("kind") == "estimate" and not all(k in (row.get("minutes") or {}) for k in ("p30", "p50", "p80")):
problems.append("minutes는 p30·p50·p80 셋")
if row.get("kind") == "retro" and (row.get("cause") not in CAUSES or row.get("level") not in LEVELS):
problems.append("cause는 %s, level은 %s 중 하나" % ("·".join(CAUSES), "·".join(LEVELS)))
if problems:
print("장부에 쓰지 않았다: " + "; ".join(problems), file=sys.stderr)
return 1
row = {"schema": 1, **row}
row.setdefault("recorded_at", now_iso())
path = ledger_path(args.ledger)
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "a", encoding="utf-8") as f:
f.write(json.dumps(row, ensure_ascii=False) + "\n")
print("%s에 한 줄 더함: %s %s" % (path, row["kind"], row["task"]))
return 0
def main(argv):
p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
sub = p.add_subparsers(dest="cmd", required=True)
for name in ("session-start", "stop", "current"):
sub.add_parser(name)
u = sub.add_parser("usage")
u.add_argument("transcript", nargs="?")
a = sub.add_parser("actual")
a.add_argument("--task", required=True)
a.add_argument("transcript", nargs="?")
a.add_argument("--ledger")
pr = sub.add_parser("precedents")
pr.add_argument("--kind")
pr.add_argument("--size", choices=("small", "medium", "large"))
pr.add_argument("--ledger")
for name in ("pending", "append"):
sub.add_parser(name).add_argument("--ledger")
args = p.parse_args(argv)
if args.cmd in ("session-start", "stop"):
try:
data = json.loads(sys.stdin.read() or "{}")
(hook_session_start if args.cmd == "session-start" else hook_stop)(data)
except Exception as exc: # 장부 훅은 작업을 막지 않는다
print("harness ledger %s 건너뜀: %r" % (args.cmd, exc), file=sys.stderr)
return 0
if args.cmd == "current":
path = current_transcript()
print(path or "찾지 못함")
return 0 if path else 1
if args.cmd == "usage":
transcript = resolve_transcript(args.transcript)
if not transcript:
print("세션 기록을 찾지 못했다. 기록 경로나 uuid를 넘긴다.", file=sys.stderr)
return 1
print(json.dumps(usage(transcript)[0], ensure_ascii=False, indent=1))
return 0
return {"actual": cmd_actual, "precedents": cmd_precedents, "pending": cmd_pending,
"append": cmd_append}[args.cmd](args)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""하네스 플러그인 PostToolUse(Write·Edit·MultiEdit) 넛지 — N4 비밀 값 알림.
방금 쓴 내용에 비밀 값처럼 보이는 것이 있으면 모델에게 몇 줄 알린다. 막지 않는다(종료 코드 0).
- 모양으로 아는 것: 개인 키 머리, AWS 접근 키, GitHub·GitLab·Slack 토큰, sk- API 키, Google API 키
- 값이 있는 대입: password·secret·token·api_key 같은 이름에 예시가 아닌 값(따옴표 안이거나 6자 이상)
값이 `example`·`dummy`·`changeme`·`${…}`·`<…>`처럼 예시나 참조이면 알리지 않는다.
알림에는 값의 앞 4자만 쓴다(값 전체를 컨텍스트에 다시 넣지 않는다).
시험: `python3 -m unittest discover -s plugins/harness/tests`
"""
import json
import re
import sys
PATTERNS = [
("개인 키", re.compile(r"-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----")),
("AWS 접근 키", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),
("GitHub 토큰", re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})\b")),
("GitLab 토큰", re.compile(r"\bglpat-[A-Za-z0-9_-]{20,}")),
("Slack 토큰", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}")),
("API 키(sk-)", re.compile(r"\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{32,}")),
("Google API 키", re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b")),
]
ASSIGN_RE = re.compile(
r"(?i)\b([A-Za-z0-9_.-]*(?:password|passwd|secret|api[_-]?key|access[_-]?key|private[_-]?key|token))"
r"\s*[:=]\s*(?:(['\"])([^'\"\n]{4,})\2|([^\s'\"#,;]{6,}))")
PLACEHOLDER_RE = re.compile(
r"(?i)example|dummy|sample|changeme|change-me|placeholder|your[-_ ]|xxx|\*\*\*|redacted|fake|test|"
r"^(none|null|true|false|secret|password|token)$|localhost")
REFERENCE_CHARS = set("$<>{}()[]%")
MAX_LINES = 5
def written_text(tool_input):
"""도구 입력에서 새로 쓴 글만 모은다."""
parts = [tool_input.get("content"), tool_input.get("new_string")]
parts += [e.get("new_string") for e in tool_input.get("edits") or [] if isinstance(e, dict)]
return "\n".join(p for p in parts if isinstance(p, str))
def mask(value):
return value[:4] + "…" if len(value) > 4 else "…"
def findings(text):
out = []
for line_no, line in enumerate(text.split("\n"), 1):
for label, pattern in PATTERNS:
m = pattern.search(line)
if m and not PLACEHOLDER_RE.search(m.group(0)):
out.append("%d줄: %s 모양 `%s`" % (line_no, label, mask(m.group(0))))
for m in ASSIGN_RE.finditer(line):
value = m.group(3) or m.group(4)
if value.isdigit() or REFERENCE_CHARS & set(value) or PLACEHOLDER_RE.search(value):
continue
out.append("%d줄: `%s`에 값 `%s`" % (line_no, m.group(1), mask(value)))
return out
def main():
data = json.load(sys.stdin)
if data.get("tool_name") not in ("Write", "Edit", "MultiEdit"):
return 0
tool_input = data.get("tool_input") or {}
found = findings(written_text(tool_input))
if not found:
return 0
path = tool_input.get("file_path", "")
lines = ["[N4 비밀 값 알림] %s에 비밀 값처럼 보이는 것이 있다:" % path] + found[:MAX_LINES - 2]
lines.append("진짜 값이면 지우고 환경 변수·비밀 저장소에서 읽는다. 예시 값이면 `example`·`dummy`로 표시한다.")
print(json.dumps({"hookSpecificOutput": {"hookEventName": "PostToolUse",
"additionalContext": "\n".join(lines)}}, ensure_ascii=False))
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except Exception: # 넛지는 실패해도 작업을 막지 않는다
sys.exit(0)
+88
View File
@@ -0,0 +1,88 @@
#!/usr/bin/env python3
"""이번 브랜치가 남긴 빚과 치울 것을 보여 준다(`techdebt` 스킬이 부른다). 아무것도 고치지 않는다.
python3 techdebt.py [--base <커밋>] 기준이 없으면 origin/main(없으면 main)과 갈라진 곳
보여 주는 것: diff가 더한 줄의 TODO·건너뛴 테스트·검사 끄기·디버그 출력, 추적하지 않는 파일,
지울 수 있는 worktree, 이미 합쳐진 로컬 브랜치.
"""
import argparse
import re
import subprocess
import sys
MARKERS = [
("할 일 표시", re.compile(r"\b(TODO|FIXME|XXX|HACK)\b")),
("건너뛴 테스트", re.compile(r"@Disabled\b|\.skip\(|\bx(it|describe)\(|@pytest\.mark\.skip|@unittest\.skip")),
("검사 끄기", re.compile(r"@SuppressWarnings|eslint-disable|@ts-ignore|@ts-expect-error|#\s*noqa|#\s*type:\s*ignore")),
("디버그 출력", re.compile(r"\bconsole\.log\(|System\.out\.println\(|\bdebugger;")),
]
MAX_PER_KIND = 20
def git(*args):
r = subprocess.run(["git", *args], capture_output=True, text=True)
return r.stdout if r.returncode == 0 else ""
def default_base():
for ref in ("origin/main", "main", "origin/master", "master"):
base = git("merge-base", "HEAD", ref).strip()
if base:
return base
return ""
def added_lines(base):
"""(파일, 줄 번호, 내용): base 이후 더한 줄. 커밋 안 된 변경도 포함한다."""
out, path, line_no = [], None, 0
for line in git("diff", "--unified=0", "--no-color", base).splitlines():
if line.startswith("+++ "):
path = line[6:] if line.startswith("+++ b/") else None
elif line.startswith("@@"):
m = re.search(r"\+(\d+)", line)
line_no = int(m.group(1)) if m else 0
elif line.startswith("+") and path:
out.append((path, line_no, line[1:]))
line_no += 1
return out
def main(argv):
p = argparse.ArgumentParser()
p.add_argument("--base")
args = p.parse_args(argv)
if not git("rev-parse", "--git-dir"):
print("git 저장소가 아니다.", file=sys.stderr)
return 1
base = args.base or default_base()
if not base:
print("기준 커밋을 찾지 못했다. --base로 준다.", file=sys.stderr)
return 1
print("기준: %s" % git("log", "-1", "--format=%h %s", base).strip())
found = {label: [] for label, _ in MARKERS}
for path, line_no, text in added_lines(base):
for label, pattern in MARKERS:
if pattern.search(text):
found[label].append("%s:%d %s" % (path, line_no, text.strip()[:100]))
for label, rows in found.items():
print("\n## %s (%d)" % (label, len(rows)))
print("\n".join(rows[:MAX_PER_KIND]) or "없음")
if len(rows) > MAX_PER_KIND:
print("… %d개 더" % (len(rows) - MAX_PER_KIND))
untracked = git("ls-files", "--others", "--exclude-standard").split()
print("\n## 추적하지 않는 파일 (%d)" % len(untracked))
print("\n".join(untracked[:MAX_PER_KIND]) or "없음")
prunable = [b for b in git("worktree", "list", "--porcelain").split("\n\n") if "\nprunable" in b]
print("\n## 지울 수 있는 worktree (%d)" % len(prunable))
print("\n".join(b.split("\n")[0] for b in prunable) or "없음")
current = git("branch", "--show-current").strip()
merged = [b.strip(" *+") for b in git("branch", "--merged", base).splitlines()]
merged = [b for b in merged if b and b != current and b not in ("main", "master")]
print("\n## 기준에 이미 합쳐진 로컬 브랜치 (%d)" % len(merged))
print("\n".join(merged[:MAX_PER_KIND]) or "없음")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))