#!/usr/bin/env python3 """예측·실측 장부 도구. 훅 둘과 `estimate`·`retro` 스킬이 부르는 명령을 한 파일에 둔다. 훅(출력 없음 → 컨텍스트 비용 0, 실패해도 작업을 막지 않는다) session-start SessionStart 입력의 session_id·transcript_path·cwd를 <상태 폴더>/sessions.jsonl에 한 줄 더한다 stop Stop 때마다 세션 기록을 이어 읽어 <상태 폴더>/usage/.json에 누적 실측을 덮어쓴다 명령 current 지금 폴더의 세션 기록 경로 usage [기록 경로|uuid] 세션 기록의 실측(JSON). 하위 에이전트 기록(/subagents/)을 더한다 actual --task T [기록] T의 예측과 견준 actual 줄 초안(JSON). 쓰지는 않는다 precedents [--kind K] [--size S] 장부의 지난 예측·실측 표 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 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:]))