#!/usr/bin/env python3 """예측·실측 장부 도구. 훅 둘과 `estimate`·`retro` 스킬이 부르는 명령을 한 파일에 둔다. 훅(출력 없음 → 컨텍스트 비용 0, 실패해도 작업을 막지 않는다) session-start SessionStart 입력의 session_id·transcript_path·cwd를 <상태 폴더>/sessions.jsonl에 한 줄 더한다 stop Stop 때마다 세션 기록을 이어 읽어 <상태 폴더>/usage/.json에 누적 실측을 덮어쓴다 넛지(장부 훅과 따로 건다) nudge SessionStart(startup)에 회고 대기·판정 대기가 있으면 repo마다 하루 한 번 한 줄 명령 current 지금 폴더의 세션 기록 경로 usage [기록 경로|uuid] 세션 기록의 실측(JSON). 하위 에이전트 기록(/subagents/)을 더한다 actual --task T [기록] T의 예측과 견준 actual 줄 초안(JSON). 쓰지는 않는다 precedents [--kind K] [--size S] 장부의 지난 예측·실측 표와 보정 줄(실측/p50 중앙값). --ledger를 여러 번 줘도 된다 pending 예측 밖인데 회고가 없는 작업, 효과 판정이 없는 개선 append stdin의 JSON 한 줄을 검사해 장부 끝에 더한다 상태 폴더: $HARNESS_STATE_DIR, 없으면 ~/.claude/harness. 장부: /docs/ledger/estimates.jsonl(--ledger로 바꿈). 실측 규칙: assistant 줄의 message.usage, 같은 message.id는 한 번만(값은 가장 큰 것). 작업 중 시간은 기록 사이 빈틈을 5분까지만 더한 시간이다(끝 보고 뒤 다음 지시를 기다린 시간이 빠진다). """ import argparse import datetime import glob import json import os import re import statistics import subprocess import sys import time GAP_SECONDS = 300 KINDS = ("estimate", "actual", "retro", "verdict") REQUIRED = { "estimate": ("minutes", "basis"), "actual": ("active_minutes",), "retro": ("cause", "level"), "verdict": ("fix", "effect"), } CAUSES = ("지시 모호", "착수 전 조사 부족", "아키텍처 경직", "검증 대기", "외부 대기", "범위 변경", "예측 근거 없음") LEVELS = ("architecture", "gate", "instructions", "user") EFFECTS = ("effective", "reverted") VERDICT_AFTER = 2 # 개선 뒤에 예측한 다른 작업의 실측이 이만큼 쌓이면 효과를 판정한다 NUDGE_EVERY = 20 * 3600 # 같은 repo에 넛지를 다시 내기까지(초) 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_rev_parse(start, *args): try: r = subprocess.run(["git", "-C", start, "rev-parse", *args], capture_output=True, text=True, timeout=5) except (OSError, subprocess.SubprocessError): return None return r.stdout.strip() if r.returncode == 0 else None def git_toplevel(start): return git_rev_parse(start, "--show-toplevel") 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 hook_nudge(data): """회고 대기·판정 대기가 있으면 한 줄. 같은 repo(worktree를 묶어)에는 NUDGE_EVERY에 한 번만.""" if data.get("source") not in (None, "startup"): return top = git_toplevel(data.get("cwd") or os.getcwd()) if not top: return rows = read_ledger(os.path.join(top, "docs", "ledger", "estimates.jsonl")) parts = [] retro = len(retro_due(by_task(rows))) if retro: parts.append("회고 안 한 빗나간 예측 %d건" % retro) verdict = sum(1 for _, later in open_fixes(rows) if later >= VERDICT_AFTER) if verdict: parts.append("효과를 판정할 개선 %d건" % verdict) if not parts: return key = git_rev_parse(top, "--path-format=absolute", "--git-common-dir") or top path = os.path.join(state_dir(), "nudge.json") try: with open(path, encoding="utf-8") as f: seen = json.load(f) except (OSError, ValueError): seen = {} if time.time() - seen.get(key, 0) < NUDGE_EVERY: return seen[key] = time.time() os.makedirs(state_dir(), exist_ok=True) with open(path + ".tmp", "w", encoding="utf-8") as f: json.dump(seen, f) os.replace(path + ".tmp", path) print("harness: 이 repo 장부에 %s이 있다. 회고는 `retro` 스킬로 한다. 맡은 일이 회고가 아니면 넘긴다." % ", ".join(parts)) # ---------------------------------------------------------------- 장부 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 missed(t): """실측이 p30보다 짧거나 p80보다 길었거나, 실측 줄에 틀린 이유가 적힌 작업.""" a, m = t.get("actual") or {}, (t.get("estimate") or {}).get("minutes") or {} if not a: return False if a.get("why"): return True act = a.get("active_minutes") return isinstance(act, (int, float)) and "p30" in m and "p80" in m and not m["p30"] <= act <= m["p80"] def retro_due(tasks): return [(n, t) for n, t in tasks.items() if missed(t) and "retro" not in t] def open_fixes(rows): """효과 판정 줄이 없는 개선(retro 줄의 fix)과, 적용 뒤에 예측 줄을 쓰고 실측까지 끝난 다른 작업 수. 적용 전에 예측한 작업은 그 개선의 영향을 받지 않았으니 세지 않는다.""" judged = {r.get("fix") for r in rows if r.get("kind") == "verdict"} fixes = {r["fix"]: r for r in rows if r.get("kind") == "retro" and r.get("fix") and r["fix"] not in judged} tasks = by_task(rows) out = [] for r in fixes.values(): since = epoch(r.get("applied_at") or r.get("recorded_at")) or 0 later = sum(1 for n, t in tasks.items() if n != r.get("task") and "actual" in t and (epoch((t.get("estimate") or {}).get("recorded_at")) or 0) > since) out.append((r, later)) return out def bias(tasks): """예측과 실측이 둘 다 있는 작업의 실측/p50 중앙값. 1보다 작으면 크게 예측해 온 것이다.""" out = [] for label, ek, ak in (("시간", "minutes", "active_minutes"), ("호출", "calls", "calls"), ("출력", "output_tokens", "output_tokens")): ratios = [t["actual"][ak] / t["estimate"][ek]["p50"] for t in tasks.values() if isinstance((t.get("actual") or {}).get(ak), (int, float)) and isinstance((t.get("estimate") or {}).get(ek), dict) and t["estimate"][ek].get("p50")] if ratios: out.append("%s %.2f(%d건)" % (label, statistics.median(ratios), len(ratios))) return out 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([r for p in (args.ledger or [None]) for r in read_ledger(ledger_path(p))]) 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)) ratios = bias(tasks) if ratios: done = [((t.get("estimate") or {}).get("minutes") or {}, t["actual"]["active_minutes"]) for t in tasks.values() if isinstance((t.get("actual") or {}).get("active_minutes"), (int, float))] below = sum(1 for m, act in done if "p30" in m and act < m["p30"]) above = sum(1 for m, act in done if "p80" in m and act > m["p80"]) print("\n보정: 실측/p50 중앙값 %s. 시간 실측이 p30 아래 %d건, p80 위 %d건. 중앙값이 0.8 아래나 1.25 위면 " "새 예측의 세 값에 그 칸의 중앙값을 곱한다." % (" · ".join(ratios), below, above)) return 0 def cmd_pending(args): rows = read_ledger(ledger_path(args.ledger)) todo = retro_due(by_task(rows)) 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") or "-")) if not todo: print("회고할 줄 없음.") for r, later in open_fixes(rows): print("- 판정 대기 %s(%s, %s 적용): 뒤 실측 %d건%s" % ( r["fix"], r.get("task"), str(r.get("applied_at") or r.get("recorded_at"))[:10], later, ". 판정할 때다" if later >= VERDICT_AFTER else "")) 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))) path = ledger_path(args.ledger) rows = read_ledger(path) if row.get("kind") == "verdict": if row.get("effect") not in EFFECTS: problems.append("effect는 %s 중 하나" % "·".join(EFFECTS)) if row.get("fix") not in {r.get("fix") for r in rows if r.get("kind") == "retro"}: problems.append("fix %s인 retro 줄이 장부에 없다" % row.get("fix")) if problems: print("장부에 쓰지 않았다: " + "; ".join(problems), file=sys.stderr) return 1 row = {"schema": 1, **row} row.setdefault("recorded_at", now_iso()) if row["kind"] == "retro" and row.get("fix"): row.setdefault("applied_at", row["recorded_at"]) 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"])) if row["kind"] == "actual": rows.append(row) t = by_task(rows).get(row["task"], {}) due = sum(1 for _, later in open_fixes(rows) if later >= VERDICT_AFTER) if missed(t): print("예측 밖이다(예측 %s분, 실측 %s분). `retro` 스킬로 이유를 나눈다." % ( triple(t.get("estimate", {}).get("minutes")), row.get("active_minutes"))) if due: print("효과를 판정할 개선 %d건: ledger.py pending" % due) 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", "nudge", "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", action="append") for name in ("pending", "append"): sub.add_parser(name).add_argument("--ledger") args = p.parse_args(argv) if args.cmd in ("session-start", "stop", "nudge"): try: data = json.loads(sys.stdin.read() or "{}") {"session-start": hook_session_start, "stop": hook_stop, "nudge": hook_nudge}[args.cmd](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:]))