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
@@ -0,0 +1,13 @@
{
"name": "harness",
"displayName": "Harness",
"version": "0.1.0",
"description": "프로젝트와 상관없는 공통 하네스: 되돌릴 수 없는 명령 차단(H12), 비밀 값 알림(N4), 예측·실측 장부 훅과 estimate·retro·techdebt 스킬",
"author": {
"name": "donghyeon.kang"
},
"homepage": "https://git.learn.hyeonworks.com/donghyeon.kang/claude-harness",
"repository": "https://git.learn.hyeonworks.com/donghyeon.kang/claude-harness",
"license": "MIT",
"keywords": ["harness", "hooks", "estimate", "ledger"]
}
+34
View File
@@ -0,0 +1,34 @@
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{"type": "command", "command": "python3 -I \"${CLAUDE_PLUGIN_ROOT}/scripts/guard_bash.py\"", "timeout": 10}
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit",
"hooks": [
{"type": "command", "command": "python3 -I \"${CLAUDE_PLUGIN_ROOT}/scripts/nudge_secrets.py\"", "timeout": 10}
]
}
],
"SessionStart": [
{
"hooks": [
{"type": "command", "command": "python3 -I \"${CLAUDE_PLUGIN_ROOT}/scripts/ledger.py\" session-start", "timeout": 10}
]
}
],
"Stop": [
{
"hooks": [
{"type": "command", "command": "python3 -I \"${CLAUDE_PLUGIN_ROOT}/scripts/ledger.py\" stop", "timeout": 30}
]
}
]
}
}
+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:]))
+58
View File
@@ -0,0 +1,58 @@
---
name: estimate
description: Use at the start of any task that comes with a brief, a size (작음·중간·큼 / small·medium·large), or more than a few files of work — before building anything — to write a start report with p30/p50/p80 estimates of active minutes, model calls, and output tokens grounded in this repo's ledger; also use when the user asks how long or how many tokens something will take ("얼마나 걸려?", "예측해 봐", "견적"), and again at the end of the task to record the actual numbers and why the estimate missed. 착수할 때 이해한 것·가정·p30/p50/p80 예측을 쓰고 장부(docs/ledger/estimates.jsonl)에 남기며, 끝날 때 실측과 틀린 이유를 남긴다.
---
# estimate — 착수 보고와 예측·실측 장부
일정은 확률이다. 착수 전에 세 값을 예측하고, 끝나면 실측과 견주고, 틀린 이유로 하네스를 고친다. 질타가 아니라 측정이다.
```text
착수(첫 5분) ──> 착수 보고 + estimate 줄 ──> 기다리지 않고 진행
끝 보고 직전 ──> actual 줄(세션 기록에서 뽑음) ──> 틀렸으면 이유 한 줄
```
장부는 `docs/ledger/estimates.jsonl`이고 형식은 `docs/ledger/README.md`다. 장부가 없는 repo면 터미널 착수 보고만 쓰고 장부 줄은 건너뛴다(만들지 않는다).
## 1. 착수 보고
공유 노트 폴더가 있으면 거기 `<세션 이름>.md` 맨 위에, 없으면 터미널에 한 단락으로 쓴다.
- **이해한 것** 5줄 이하: 목표, 완료 기준, 범위 밖.
- **모호한 점과 고른 가정**: 묻고 기다리지 않는다. 가정을 적고 진행한다. 틀린 가정은 대조에서 잡힌다.
- **예측**: 작업 중 시간(분)·호출 수·출력 토큰을 p30(도전)·p50·p80(안전) 세 값으로.
- **근거**: 아래 2절. 근거 없는 배수는 쓰지 않는다.
## 2. 근거 만들기
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/scripts/ledger.py" precedents # 이 repo 장부의 지난 예측·실측
python3 "${CLAUDE_PLUGIN_ROOT}/scripts/ledger.py" precedents --size large
```
- **시간의 기준은 작업 중 시간**이다(기록 사이 빈틈을 5분까지만 더한 값). 벽시계 시간에는 끝 보고 뒤 다음 지시를 기다린 시간이 섞인다.
- 같은 종류·크기 선례의 실측을 출발점으로 삼고, 이번 일과 다른 점을 숫자로 적는다: **손으로 판단할 결정 수**, **검증 실행 횟수와 대기**, 새로 쓸 코드 양. 파일 수는 약한 근거다(이동·치환은 스크립트 한 번으로 묶인다).
- 선례가 없으면 그렇다고 쓰고, 위 세 숫자로만 예측한다.
## 3. estimate 줄
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/scripts/ledger.py" current # 이 세션의 기록 경로(uuid가 transcript 칸)
echo '{"kind":"estimate","task":"<작업 이름>","transcript":"<uuid>","started_at":"<세션 시작>","base":"<기준 커밋>","task_kind":"<종류>","size":"large","minutes":{"p30":0,"p50":0,"p80":0},"calls":{"p30":0,"p50":0,"p80":0},"output_tokens":{"p30":0,"p50":0,"p80":0},"basis":"<근거 한 줄>"}' \
| python3 "${CLAUDE_PLUGIN_ROOT}/scripts/ledger.py" append
```
`append`가 칸을 검사하고 `schema`·`recorded_at`을 채운다. 장부는 더하기만 한다. 고칠 일이 있으면 같은 `task`로 `"correction": true` 줄을 더한다.
## 4. 끝날 때 actual 줄
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/scripts/ledger.py" actual --task <작업 이름> # 실측과 within을 채운 초안
```
초안의 `result`(`done`·`partial`·`failed`), `commits`, `why`를 채워 `append`로 더한다. 실측이 p80을 넘었거나 p30보다 짧으면 `why`에 틀린 이유를 한 줄로 쓰고, 끝 보고의 「예측과 실측」에도 적는다. 커밋한 뒤에 쓰는 장부 줄은 다음 커밋에 들어가도 된다.
## 하지 않는 것
- 예측을 맞추려고 일을 늘리거나 줄이지 않는다.
- 회고(왜 틀렸나를 모아 하네스를 고치는 일)는 `retro`가 한다. 여기서는 이유 한 줄만.
+53
View File
@@ -0,0 +1,53 @@
---
name: retro
description: Use when reviewing estimate misses in this repo's ledger — when the user asks for a retrospective ("회고해", "retro", "예측이 왜 틀렸나", "장부 정리"), at a weekly review, or when a task just closed with its actual time over p80 or under p30 — to classify why each estimate missed and pick exactly one harness fix in the order architecture → gate → instructions → user behavior. 장부에서 회고가 없는 실측 줄을 모아 틀린 이유를 나누고, 아키텍처 → 게이트 → 지침 → 사용자 행동 순서로 고칠 곳 하나를 고른다.
---
# retro — 예측이 틀린 이유로 하네스 고치기
예측이 틀린 흔한 원인은 맥락 부족이다. 사람을 탓하지 않고 하네스(구조·검사·지침)를 고친다. 앞 단계로 풀리면 뒤 단계는 손대지 않는다.
```text
장부 ──> 회고 안 된 실측 ──> 이유 분류 ──> 고칠 단계 하나 ──> 고친 커밋 ──> retro 줄
```
## 1. 대상 모으기
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/scripts/ledger.py" pending
python3 "${CLAUDE_PLUGIN_ROOT}/scripts/ledger.py" precedents
```
실측이 p30~p80 안이면 회고할 것이 없다(예측이 맞았다). 그 밖이거나 `why`가 있는 줄만 본다.
## 2. 이유 나누기 — 아래 일곱 중 하나
| cause | 보이는 모양 |
|---|---|
| 지시 모호 | 완료 기준·범위가 brief에 없어 중간에 바뀜 |
| 착수 전 조사 부족 | 착수 뒤에야 안 사실(기존 장치, 제약)이 시간을 바꿈 |
| 아키텍처 경직 | 작은 변경이 여러 경계를 건드림 |
| 검증 대기 | 게이트·빌드·원격 실행 대기가 시간 대부분 |
| 외부 대기 | 사람 승인, 권한, 다른 세션 |
| 범위 변경 | 일 도중 요청이 늘거나 줄어듦 |
| 예측 근거 없음 | 선례를 잘못 읽었거나 배수에 근거가 없었음 |
세션 기록이 필요하면 `ledger.py usage <uuid>`로 다시 센다.
## 3. 고칠 곳 하나 — 이 순서로
1. **architecture**: 구조나 도구를 바꿔 같은 일이 다시 안 생기게(스크립트, 경계 정리, 장부 칸).
2. **gate**: 검사·훅이 잡게.
3. **instructions**: `AGENTS.md`·스킬·playbook에 한 줄.
4. **user**: 사용자에게 바꿔 달라고 할 행동(brief 양식 등).
앞 단계로 풀 수 있는데 뒤 단계(지침 한 줄 더하기)를 고르지 않는다. 고친 것은 커밋으로 남긴다.
## 4. retro 줄
```bash
echo '{"kind":"retro","task":"<작업 이름>","cause":"예측 근거 없음","level":"instructions","note":"<무엇을 왜>","ref":"<커밋이나 문서>"}' \
| python3 "${CLAUDE_PLUGIN_ROOT}/scripts/ledger.py" append
```
효과가 없으면(다음 회고에서 같은 이유가 되풀이되면) 그 수정을 되돌리고 다른 단계를 고른다.
+30
View File
@@ -0,0 +1,30 @@
---
name: techdebt
description: Use right before the final report of a task that changed files, or when the user says "정리해", "techdebt", "세션 끝", "남긴 것 없나" — to list what this branch's diff added that someone must pay back later (new TODO/FIXME, skipped or disabled tests, lint/type suppressions, debug prints), what the session left lying around (scratch files, extra worktrees, merged local branches, untracked files), and out-of-scope findings worth handing over. 세션 끝에 이번 diff가 남긴 빚과 치울 것을 모아 「범위 밖에서 본 것」·「남은 문제」 후보를 만든다.
---
# techdebt — 세션 끝 정리
고치는 스킬이 아니다. 남긴 것을 **보이게** 한다. 고칠지는 범위를 보고 정하고, 범위 밖이면 보고의 「범위 밖에서 본 것」이나 공유 노트로 넘긴다.
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/scripts/techdebt.py" # 기준: origin/main과 갈라진 곳
python3 "${CLAUDE_PLUGIN_ROOT}/scripts/techdebt.py" --base <커밋>
```
스크립트가 보여 주는 것:
- 이번 diff가 **더한** 줄 중 TODO·FIXME·XXX·HACK, 건너뛴 테스트(`@Disabled`, `.skip(`, `xit(`, `@pytest.mark.skip`), 검사 끄기(`@SuppressWarnings`, `eslint-disable`, `@ts-ignore`, `# noqa`, `# type: ignore`), 디버그 출력(`console.log`, `System.out.println`, `print(`(테스트 밖)).
- 추적하지 않는 파일, 지울 수 있는 worktree(`prunable`), 이미 합쳐진 로컬 브랜치.
## 할 일
1. 스크립트 결과에서 **이번 작업이 만든 것**만 고른다. 원래 있던 것은 대상이 아니다.
2. 범위 안이고 작으면 지금 고친다(테스트 skip은 이유가 없으면 되돌린다).
3. 나머지는 끝 보고에 적는다: 빚은 「남은 문제」, 남이 고칠 것은 「범위 밖에서 본 것」. 다음 세션에 넘길 상세는 공유 노트에.
4. scratch·worktree는 지우기 전에 무엇인지 보고, 이 세션이 만든 것만 치운다. 남의 것은 알리기만 한다.
## 하지 않는 것
- 다른 사람의 브랜치·worktree를 지우지 않는다.
- 빚을 숨기려고 TODO 문구를 지우지 않는다.
+231
View File
@@ -0,0 +1,231 @@
"""하네스 플러그인 훅과 장부 도구 시험. 표준 라이브러리만 쓴다.
python3 -m unittest discover -s plugins/harness/tests
훅 스크립트에 Claude Code가 주는 것과 같은 JSON을 stdin으로 넣고 종료 코드와 출력을 본다.
"""
import json
import os
import subprocess
import sys
import tempfile
import unittest
SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")
REPO = os.path.dirname(os.path.dirname(os.path.dirname(SCRIPTS)))
def run(script, args=(), payload=None, env=None, cwd=None):
full_env = {k: v for k, v in os.environ.items() if k != "CLAUDE_PROJECT_DIR"}
full_env.update(env or {})
stdin = payload if isinstance(payload, str) else json.dumps(payload or {})
return subprocess.run([sys.executable, "-I", os.path.join(SCRIPTS, script), *args], input=stdin,
capture_output=True, text=True, env=full_env, cwd=cwd, timeout=30)
def bash(command, cwd=REPO):
return {"session_id": "t", "hook_event_name": "PreToolUse", "tool_name": "Bash",
"tool_input": {"command": command}, "cwd": cwd}
class GuardBashTest(unittest.TestCase):
"""H12. 여기 사례는 판정의 대표만 둔다. 많은 사례는 소유자 기계 전역 훅 시험에 있다."""
ALWAYS = {"HARNESS_H12": "always"}
def assert_blocked(self, command, cwd=REPO):
r = run("guard_bash.py", payload=bash(command, cwd), env=self.ALWAYS)
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)
self.assertEqual(r.returncode, 0, "통과해야 한다: %s\n%s" % (command, r.stderr))
def test_force_push_to_hosting_remote_is_blocked(self):
for c in ("git push --force origin main", "git push -f", "git push origin +feature/x",
"git push --force-with-lease origin claude/x", "git push --mirror origin",
"ssh build 'cd ~/w/x && git push -f origin main'"):
self.assert_blocked(c)
def test_path_remote_transport_passes_but_not_onto_main(self):
self.assert_passed("git push -q -f desktop:/home/u/w/x v3/check:refs/heads/v3/check")
self.assert_blocked("git push -f desktop:/home/u/w/x HEAD:main")
def test_normal_push_and_own_branch_delete_pass(self):
self.assert_passed("git push -u origin claude/x")
self.assert_passed("git push origin --delete review/x")
self.assert_blocked("git push origin --delete main")
def test_rm_outside_or_too_broad_is_blocked(self):
for c in ("rm -rf /", "rm -rf ~", "rm -rf .git", 'rm -rf "$UNSET/"', "rm -rf ./*",
"rm -rf ../other-repo/src", "ssh build 'rm -rf ~/workspace/some-repo'"):
self.assert_blocked(c)
def test_rm_inside_project_tmp_and_known_vars_pass(self):
for c in ("rm -rf build dist", "rm -rf /tmp/some-build-x", 'T=$(mktemp -d) && rm -rf "$T"',
"S=/tmp/x; rm -rf $S/out", 'rm -rf "${OUT:?}/build"', "ssh build 'rm -rf ~/x-logs'"):
self.assert_passed(c)
def test_data_deletion_is_blocked(self):
for c in ("psql -c 'DROP DATABASE app'", "redis-cli FLUSHALL", "./gradlew :app:flywayClean",
"ssh build 'docker compose down -v'", "docker volume rm app_db",
"kubectl delete pvc data-0"):
self.assert_blocked(c)
def test_scoped_teardown_and_data_as_text_pass(self):
for c in ("docker compose -p lane-1 -f compose.yml down -v", "docker compose down",
"kubectl delete pod web-1", "grep -rn 'DROP TABLE' docs",
"cat > V2__drop.sql <<'EOF'\nDROP TABLE old;\nEOF"):
self.assert_passed(c)
def test_skips_when_owner_global_hook_has_h12(self):
with tempfile.TemporaryDirectory() as home:
os.makedirs(os.path.join(home, ".claude"))
settings = {"hooks": {"PreToolUse": [{"matcher": "Bash", "hooks": [
{"type": "command", "command": "python3 -I /x/.claude/hooks/guard_bash.py H12"}]}]}}
with open(os.path.join(home, ".claude", "settings.json"), "w") as f:
json.dump(settings, f)
r = run("guard_bash.py", payload=bash("git push --force origin main"), env={"HOME": home})
self.assertEqual(r.returncode, 0, r.stderr)
settings["hooks"]["PreToolUse"][0]["hooks"][0]["command"] = "python3 -I /x/guard_bash.py H1"
with open(os.path.join(home, ".claude", "settings.json"), "w") as f:
json.dump(settings, f)
r = run("guard_bash.py", payload=bash("git push --force origin main"), env={"HOME": home})
self.assertEqual(r.returncode, 2, r.stderr)
def test_broken_input_does_not_block(self):
r = run("guard_bash.py", payload="{not json", env=self.ALWAYS)
self.assertEqual(r.returncode, 1)
class NudgeSecretsTest(unittest.TestCase):
def nudge(self, content, tool="Write"):
key = "content" if tool == "Write" else "new_string"
r = run("nudge_secrets.py", payload={"tool_name": tool, "tool_input": {"file_path": "a.yml", key: content}})
self.assertEqual(r.returncode, 0, r.stderr)
return json.loads(r.stdout)["hookSpecificOutput"]["additionalContext"] if r.stdout.strip() else ""
def test_real_looking_secrets_nudge_and_are_masked(self):
token = "ghp_" + "a1B2" * 9
for content in ("-----BEGIN OPENSSH PRIVATE KEY-----", "token: " + token,
'db:\n password: "s3cr3t-Value"', "AWS_KEY=AKIA" + "ABCDEFGHIJKLMNOP"):
text = self.nudge(content)
self.assertIn("[N4", text, content)
self.assertNotIn(token, text)
def test_edit_new_string_is_checked(self):
self.assertIn("[N4", self.nudge("api_key = 'q8Zr2LmP0xY'", tool="Edit"))
def test_placeholders_and_references_are_quiet(self):
for content in ("password: ${DB_PASSWORD}", "password=changeme", "api_key: <your-key>",
"AWS_KEY=AKIAIOSFODNN7EXAMPLE", "max_tokens: 4096", "TOKEN_TTL=3600",
"password = request.getParameter(\"pw\")", "secret: dummy-secret-value"):
self.assertEqual(self.nudge(content), "", content)
class LedgerTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.dir = self.tmp.name
self.env = {"HARNESS_STATE_DIR": os.path.join(self.dir, "state")}
self.transcript = os.path.join(self.dir, "abc.jsonl")
def tearDown(self):
self.tmp.cleanup()
def write_transcript(self, lines, mode="w"):
with open(self.transcript, mode) as f:
for line in lines:
f.write(json.dumps(line) + "\n")
@staticmethod
def assistant(msg_id, ts, out, cache_read=100, inp=10, created=5):
return {"type": "assistant", "timestamp": ts, "message": {"id": msg_id, "usage": {
"input_tokens": inp, "cache_creation_input_tokens": created, "cache_read_input_tokens": cache_read,
"output_tokens": out}}}
def test_usage_dedupes_message_ids_and_caps_gaps(self):
self.write_transcript([
{"type": "user", "timestamp": "2026-11-07T10:00:00Z"},
self.assistant("m1", "2026-11-07T10:01:00Z", 50),
self.assistant("m1", "2026-11-07T10:01:01Z", 70), # 같은 메시지가 나뉘어 기록됨: 한 번, 큰 값
self.assistant("m2", "2026-11-07T10:31:01Z", 30, cache_read=400), # 30분 빈틈은 5분만
])
sub = os.path.join(self.dir, "abc", "subagents")
os.makedirs(sub)
with open(os.path.join(sub, "agent-1.jsonl"), "w") as f:
f.write(json.dumps(self.assistant("s1", "2026-11-07T10:02:00Z", 20)) + "\n")
r = run("ledger.py", ["usage", self.transcript], env=self.env)
self.assertEqual(r.returncode, 0, r.stderr)
u = json.loads(r.stdout)
self.assertEqual((u["calls"], u["subagent_calls"], u["output_tokens"]), (3, 1, 120))
self.assertEqual(u["cache_read_tokens"], 600)
self.assertEqual(u["max_context"], 415)
self.assertEqual((u["minutes"], u["active_minutes"]), (31, 6))
def test_stop_hook_reads_incrementally_and_matches_full_scan(self):
self.write_transcript([self.assistant("m1", "2026-11-07T10:00:00Z", 10)])
hook = {"session_id": "s-1", "transcript_path": self.transcript, "cwd": self.dir}
self.assertEqual(run("ledger.py", ["stop"], payload=hook, env=self.env).returncode, 0)
self.write_transcript([self.assistant("m2", "2026-11-07T10:02:00Z", 5)], mode="a")
with open(self.transcript, "a") as f:
f.write('{"type": "assistant", "timestamp": "2026-11-07T10:0') # 쓰는 중인 줄은 다음에
self.assertEqual(run("ledger.py", ["stop"], payload=hook, env=self.env).returncode, 0)
with open(os.path.join(self.env["HARNESS_STATE_DIR"], "usage", "s-1.json")) as f:
saved = json.load(f)["summary"]
self.assertEqual((saved["calls"], saved["output_tokens"], saved["active_minutes"]), (2, 15, 2))
def test_session_start_records_and_hooks_never_print(self):
hook = {"session_id": "s-2", "transcript_path": self.transcript, "cwd": self.dir, "source": "startup"}
r = run("ledger.py", ["session-start"], payload=hook, env=self.env)
self.assertEqual((r.returncode, r.stdout), (0, ""))
with open(os.path.join(self.env["HARNESS_STATE_DIR"], "sessions.jsonl")) as f:
self.assertEqual(json.loads(f.readline())["session_id"], "s-2")
r = run("ledger.py", ["stop"], payload="{broken", env=self.env)
self.assertEqual((r.returncode, r.stdout), (0, ""))
def test_append_checks_fields_and_actual_computes_within(self):
ledger = os.path.join(self.dir, "docs", "ledger", "estimates.jsonl")
bad = {"kind": "estimate", "task": "t1", "minutes": {"p30": 1}}
r = run("ledger.py", ["append", "--ledger", ledger], payload=bad, env=self.env)
self.assertEqual(r.returncode, 1)
self.assertFalse(os.path.exists(ledger))
good = {"kind": "estimate", "task": "t1", "task_kind": "docs", "size": "small",
"minutes": {"p30": 1, "p50": 2, "p80": 10}, "basis": "시험"}
self.assertEqual(run("ledger.py", ["append", "--ledger", ledger], payload=good, env=self.env).returncode, 0)
self.write_transcript([self.assistant("m1", "2026-11-07T10:00:00Z", 10),
self.assistant("m2", "2026-11-07T10:03:00Z", 10)])
r = run("ledger.py", ["actual", "--task", "t1", "--ledger", ledger, self.transcript], env=self.env)
row = json.loads(r.stdout)
self.assertEqual((row["active_minutes"], row["within"]), (3, "p80"))
r = run("ledger.py", ["precedents", "--ledger", ledger], env=self.env)
self.assertIn("| t1 | docs | small | 1/2/10 |", r.stdout)
retro = {"kind": "retro", "task": "t1", "cause": "모름", "level": "gate"}
self.assertEqual(run("ledger.py", ["append", "--ledger", ledger], payload=retro, env=self.env).returncode, 1)
class TechdebtTest(unittest.TestCase):
def test_lists_only_added_markers(self):
with tempfile.TemporaryDirectory() as d:
def git(*a):
subprocess.run(["git", "-C", d, *a], check=True, capture_output=True)
git("init", "-q", "-b", "main")
git("config", "user.email", "t@example.com")
git("config", "user.name", "t")
git("config", "core.hooksPath", "/dev/null")
with open(os.path.join(d, "a.py"), "w") as f:
f.write("# TODO old\n")
git("add", ".")
git("commit", "-q", "-m", "base")
with open(os.path.join(d, "a.py"), "a") as f:
f.write("x = 1 # noqa\n# FIXME new\n")
r = run("techdebt.py", ["--base", "HEAD"], cwd=d)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn("a.py:3 # FIXME new", r.stdout)
self.assertIn("a.py:2 x = 1 # noqa", r.stdout)
self.assertNotIn("TODO old", r.stdout)
if __name__ == "__main__":
unittest.main()