Files
claude-harness/plugins/harness/scripts/ledger.py
T
DongHyeonka cdde857adb feat(ledger): 하네스 판 비교를 eval 줄로 남기고 시작 컨텍스트를 잰다
문제: 하네스 v2(분야 전문가 협업)를 v1과 견주려면 같은 과제를 판마다
돌린 실행을 한 줄씩 남기고 비교해야 하는데, 장부에는 예측·실측만 있다.
실측도 시간·호출·토큰뿐이라 모든 세션의 시작 비용(첫 호출 입력 토큰)과
서브에이전트가 메인에 돌려준 양(컨텍스트 비용)을 볼 수 없다.

고른 방법:
- usage에 start_context(본 기록 첫 호출), subagents·subagent_output_tokens,
  agent_calls(Agent·Task 호출), agent_return_chars를 더한다. 반환 글자는
  Agent 도구 결과와, 백그라운드 결과가 들어오는 대기열 알림
  (queued_command의 <agent-message·<task-notification 머리)을 센다.
  2026-11-11 세션 기록에서 백그라운드 결과가 tool_result가 아니라
  알림으로 오는 것을 확인했다.
- 새 줄 종류 eval(arm·case 필수)과 명령 eval(초안)·compare(과제·판별
  중앙값, 마지막 판/첫 판 비율). precedents는 eval만 있는 작업을 세지 않는다.
- Stop 훅이 0.2.0이 저장한 상태 파일을 이어 읽어도 깨지지 않게 새 칸은
  setdefault로 채운다.
- 버린 대안: eval을 actual 줄에 arm 칸으로 붙이기. 같은 작업의 판 여럿이
  by_task에서 덮이고 회고 대기 계산에 섞인다.

위험: 대기열 알림 모양은 앱 내부 형식이다. 바뀌면 agent_return_chars가
조용히 줄어든다(시험이 지금 모양을 고정한다).

검증: python3 -m unittest discover -s plugins/harness/tests → 24건 통과
(알려진 실패 1). 조건을 하나씩 끈 변이 9개가 모두 시험에 걸렸다.
2026-11-11 22:04:24 +09:00

591 lines
26 KiB
Python
Executable File

#!/usr/bin/env python3
"""예측·실측 장부 도구. 훅 둘과 `estimate`·`retro` 스킬이 부르는 명령을 한 파일에 둔다.
훅(출력 없음 → 컨텍스트 비용 0, 실패해도 작업을 막지 않는다)
session-start SessionStart 입력의 session_id·transcript_path·cwd를 <상태 폴더>/sessions.jsonl에 한 줄 더한다
stop Stop 때마다 세션 기록을 이어 읽어 <상태 폴더>/usage/<session_id>.json에 누적 실측을 덮어쓴다
넛지(장부 훅과 따로 건다)
nudge SessionStart(startup)에 회고 대기·판정 대기가 있으면 repo마다 하루 한 번 한 줄
명령
current 지금 폴더의 세션 기록 경로
usage [기록 경로|uuid] 세션 기록의 실측(JSON). 하위 에이전트 기록(<uuid>/subagents/)을 더한다
actual --task T [기록] T의 예측과 견준 actual 줄 초안(JSON). 쓰지는 않는다
eval --task E --arm A --case C [기록] 평가 E의 한 실행(판 A, 과제 C) eval 줄 초안(JSON). 쓰지는 않는다
compare --task E 평가 E의 과제·판별 중앙값 표와 마지막 판/첫 판 비율
precedents [--kind K] [--size S] 장부의 지난 예측·실측 표와 보정 줄(실측/p50 중앙값). --ledger를 여러 번 줘도 된다
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 statistics
import subprocess
import sys
import time
GAP_SECONDS = 300
KINDS = ("estimate", "actual", "retro", "verdict", "eval")
REQUIRED = {
"estimate": ("minutes", "basis"),
"actual": ("active_minutes",),
"eval": ("arm", "case", "active_minutes"),
"retro": ("cause", "level"),
"verdict": ("fix", "effect"),
}
CAUSES = ("지시 모호", "착수 전 조사 부족", "아키텍처 경직", "검증 대기", "외부 대기", "범위 변경", "예측 근거 없음")
LEVELS = ("architecture", "gate", "instructions", "user")
EFFECTS = ("effective", "reverted")
AGENT_TOOLS = ("Agent", "Task") # 서브에이전트를 띄우는 도구 이름(옛 이름 Task)
HANDBACK_PREFIXES = ("<agent-message", "<task-notification") # 백그라운드 결과가 대기열로 들어올 때의 머리
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():
# first_id: 첫 호출의 message.id(시작 컨텍스트). agents: Agent 호출 id → 결과를 셌나. agent_chars: 돌려받은 글자
return {"offset": 0, "ids": {}, "first": None, "last": None, "active": 0.0,
"first_id": None, "agents": {}, "agent_chars": 0}
def result_chars(content):
if isinstance(content, str):
return len(content)
if isinstance(content, list):
return sum(len(b.get("text") or "") for b in content if isinstance(b, dict) and b.get("type") == "text")
return 0
def scan(path, st):
"""path를 st["offset"]부터 마지막 완전한 줄까지 읽어 st를 갱신한다."""
for key, value in new_file_state().items(): # 옛 판이 저장한 상태에 없는 칸
st.setdefault(key, value)
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
if st["first_id"] is None:
st["first_id"] = msg["id"]
queued = d.get("attachment") if d.get("type") == "attachment" else None
if isinstance(queued, dict) and queued.get("type") == "queued_command" and isinstance(queued.get("prompt"), str) \
and queued["prompt"].lstrip().startswith(HANDBACK_PREFIXES):
st["agent_chars"] += len(queued["prompt"]) # 백그라운드 서브에이전트의 결과·완료 알림
blocks = (d.get("message") or {}).get("content") if isinstance(d.get("message"), dict) else None
for b in blocks if isinstance(blocks, list) else ():
if not isinstance(b, dict):
continue
if b.get("type") == "tool_use" and b.get("name") in AGENT_TOOLS and b.get("id"):
st["agents"].setdefault(b["id"], False)
elif b.get("type") == "tool_result" and st["agents"].get(b.get("tool_use_id")) is False:
st["agents"][b["tool_use_id"]] = True
st["agent_chars"] += result_chars(b.get("content"))
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()]
subs = [st for p, st in files.items() if p != transcript and st["ids"]]
sub_calls = sum(len(st["ids"]) for st in subs)
first, last = main["first"], main["last"]
start = main["ids"].get(main.get("first_id")) or [0, 0, 0, 0]
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),
"start_context": start[0] + start[1] + start[2],
"subagents": len(subs),
"subagent_output_tokens": sum(v[3] for st in subs for v in st["ids"].values()),
"agent_calls": len(main.get("agents") or {}),
"agent_return_chars": main.get("agent_chars") or 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 not e and not a: # 평가 줄만 있는 작업
continue
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
EVAL_COLUMNS = (("작업 중 분", "active_minutes"), ("호출", "calls"), ("출력 토큰", "output_tokens"),
("시작 컨텍스트", "start_context"), ("최대 컨텍스트", "max_context"), ("발견", "findings"),
("틀린 발견", "false_findings"))
EVAL_RATIOS = (("작업 중 분", "active_minutes"), ("호출", "calls"), ("출력", "output_tokens"),
("시작 컨텍스트", "start_context"), ("발견", "findings"), ("최대 컨텍스트", "max_context"))
def num(v):
return "-" if v is None else ("%d" % v if float(v).is_integer() else "%.1f" % v)
def med(rows, key):
vals = [r[key] for r in rows if isinstance(r.get(key), (int, float))]
return statistics.median(vals) if vals else None
def cmd_compare(args):
rows = [r for r in read_ledger(ledger_path(args.ledger)) if r.get("kind") == "eval" and r.get("task") == args.task]
if not rows:
print("평가 줄 없음: %s. 실행마다 `ledger.py eval` 초안을 채워 append한다." % args.task)
return 0
groups, arms = {}, []
for r in rows:
groups.setdefault((r.get("case"), r.get("arm")), []).append(r)
if r.get("arm") not in arms:
arms.append(r.get("arm"))
print("| 과제 | 판 | 실행 | %s |" % " | ".join(label for label, _ in EVAL_COLUMNS))
print("|---|---|---|%s" % "---|" * len(EVAL_COLUMNS))
for (case, arm), rs in groups.items():
print("| %s | %s | %d | %s |" % (case, arm, len(rs), " | ".join(num(med(rs, k)) for _, k in EVAL_COLUMNS)))
if len(arms) < 2:
return 0
base, cand = arms[0], arms[-1]
parts = []
for label, key in EVAL_RATIOS:
ratios = []
for case in dict.fromkeys(c for c, _ in groups):
b, c = med(groups.get((case, base), []), key), med(groups.get((case, cand), []), key)
if b and c is not None:
ratios.append(c / b)
if ratios:
parts.append("%s %.2f" % (label, statistics.median(ratios)))
print("\n%s/%s 중앙값: %s. 과제마다 비율을 내고 그 중앙값이다. 발견은 리뷰가 찾은 결함 수다(클수록 좋다)." % (
cand, base, " · ".join(parts)))
return 0
def cmd_eval(args):
transcript = resolve_transcript(args.transcript)
if not transcript:
print("세션 기록을 찾지 못했다. 기록 경로나 uuid를 넘긴다.", file=sys.stderr)
return 1
summary, _ = usage(transcript)
row = {"schema": 1, "kind": "eval", "task": args.task, "arm": args.arm, "case": args.case,
"recorded_at": now_iso(), "transcript": summary["transcript"]}
row.update({k: summary[k] for k in ("active_minutes", "calls", "output_tokens", "input_tokens_total",
"start_context", "max_context", "subagents", "subagent_calls",
"agent_calls", "agent_return_chars")})
row.update({"findings": None, "false_findings": None, "result": "done", "note": ""})
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")
ev = sub.add_parser("eval")
ev.add_argument("--task", required=True)
ev.add_argument("--arm", required=True)
ev.add_argument("--case", required=True)
ev.add_argument("transcript", nargs="?")
cp = sub.add_parser("compare")
cp.add_argument("--task", required=True)
cp.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", "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,
"eval": cmd_eval, "compare": cmd_compare}[args.cmd](args)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))