Files
document-haness/scripts/verify-pipeline-run.py
T

1063 lines
50 KiB
Python

#!/usr/bin/env python3
"""파이프라인 런 원장이 절차를 지켰는지 본다.
이 검사기는 글의 품질을 보지 않는다. **절차의 준수**를 본다 — 단계가 빠졌는지, 그 단계가
자기 스킬을 실제로 열었는지, 관문이 돌았고 종료 코드가 0 이었는지, 적어 낸 산출물이
디스크에 있는지.
python3 scripts/verify-pipeline-run.py --init runs/<프로젝트>/<runId>/run.json \\
--project <프로젝트> --record <기록 경로>
python3 scripts/verify-pipeline-run.py runs/<프로젝트>/<runId>/run.json
**`skillEcho` 가 이 검사기의 핵심이다.** 단계마다 그 SKILL.md 에서 한 줄을 원문 그대로
옮겨 오게 하고, 그 문자열이 실제로 그 파일 안에 있는지 대조한다. 스킬을 안 읽고 결과만
그럴듯하게 낸 단계는 여기서 걸린다.
**스킬은 고쳐진다.** 그러면 그 전에 돈 런의 영수증이 현재 SKILL.md 에서 사라진다. 그
영수증은 사실이다 — 그때 그 문장이 거기 있었다. 원장을 고쳐 쓰는 것은 위조이고 틀린
문장을 스킬에 되살리는 것은 검사기에 답하는 것이라, 둘 다 하지 않고 **검사기가 가른다.**
git 이 그 스킬의 과거 본문을 갖고 있으므로 그것으로 본다 — 현재에 있으면 통과, 과거
판에만 있으면 warn, 어느 판에도 없으면 error. 볼 수 없었던 것(git 이 없다 · 이력 상한에
걸렸다)은 또 따로 warn 이다. 못 본 것을 「없다」로 세면 위조와 같은 칸에 들어간다.
계약은 `.agents/skills/running-tech-log-pipeline/references/stage-contracts.md` 다.
"""
from __future__ import annotations
import argparse
import datetime as dt
import hashlib
import json
import os
import re
import subprocess
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from techlog import Report # noqa: E402
from command_pedagogy import ( # noqa: E402
analyze_commands,
validate_command_patch_set,
validate_command_plan,
)
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SKILLS = os.path.join(ROOT, ".agents", "skills")
TEMPLATE = os.path.join(SKILLS, "running-tech-log-pipeline", "templates", "run.json")
STATUSES = ("PENDING", "RUNNING", "DONE", "SKIPPED", "FAILED")
# 단계마다 어떤 스킬이 맡고, **어느 에이전트가 돌리고**, 관문에 어떤 명령이 있어야 하는가.
# 관문은 명령 문자열에 이 토큰이 들어 있는지로 본다 — 호출형이 조금씩 달라도 같은 검사다.
#
# `agent` 는 `.claude/agents/<이름>.md` 다. 단계마다 새 에이전트를 띄우면 어떤 규칙으로
# 일했는지가 어디에도 안 남는다 — 원장의 `runBy` 가 `"subagent"` 라는 상수였던 동안이
# 그 상태였고, 그때는 스킬을 열었는지(`skillEcho`)만 남고 **누가 열었는지는 안 남았다.**
STAGES = {
"S1": {"skill": "analyzing-codebase-for-tech-log", "agent": "ssot-analyst",
"gates": ["verify-project-layout.py"], "skippable": True},
"S2": {"skill": "deriving-tech-log-root-tree", "agent": "tree-deriver",
"gates": ["build-tech-log-tree.py", "verify-tech-log-tree.py"], "skippable": True},
"S3": {"skill": "writing-tech-log-records", "agent": "record-writer",
"gates": ["check_body.mjs", "check_prose.mjs", "check_evidence.mjs"],
"skippable": False},
"S4": {"skill": "technical-visualizer", "agent": "diagram-maker",
"gates": ["lint", "check-figure-text.py", "check-figure-overlap.py",
"preview-figure.py"],
"skippable": True},
# S5·S6 은 문장을 고친 뒤라 S3 관문을 다시 돈다 (stage-contracts.md 「관문 요약」)
"S5": {"skill": "rewriting-technical-prose-naturally", "agent": "prose-rewriter",
"gates": ["check_prose.mjs", "style_profile.mjs", "check_body.mjs",
"check_evidence.mjs"],
"skippable": False},
"S6": {"skill": "writing-as-the-person-who-did-it", "agent": "voice-writer",
"gates": ["check_voice.mjs", "check_prose.mjs", "check_body.mjs",
"check_evidence.mjs"],
"skippable": False},
"S7": {"skill": "publishing-tech-log-to-studio", "agent": "studio-validator",
"gates": ["저장됨", "build-tech-log-tree.py", "verify-tech-log-tree.py"],
"skippable": True},
}
AGENTS_DIR = os.path.join(ROOT, ".claude", "agents")
# 에이전트 이름을 적기 전의 원장이 쓰던 값. 위조가 아니라 **그때의 계약**이다.
LEGACY_RUNBY = "subagent"
# `runBy` 가 에이전트 이름을 담기 시작한 원장 판. 이보다 낮은 판은 그 칸이 상수였다.
#
# 관문 쪽은 이 유예를 git 으로 가르지만(`_gate_required_since`), 여기서는 **원장이 스스로
# 밝힌 판**으로 가른다. 까닭은 git 이 작업 트리를 못 보기 때문이다 — 요구를 더한 커밋이
# 아직 안 들어갔으면 `git log -S` 가 빈손으로 돌아오고, 그러면 지난 런이 전부 error 로
# 뒤집힌다. 「요구가 언제 생겼나」를 커밋 시각으로 재는 대신 **이 원장이 어느 계약으로
# 쓰였나**를 읽으면 커밋 전후로 판정이 흔들리지 않는다.
AGENT_RUNBY_SCHEMA = 2
# v3부터 S3 안의 command-pedagogy 보조 흐름과 S6 뒤 독립 검토를 원장에 남긴다.
# 과거 v1/v2 원장은 그때 없던 영수증을 소급해 요구하지 않는다.
QUALITY_REVIEW_SCHEMA = 3
COMMAND_ARTIFACT_SCHEMA = 4
EVIDENCE_RECONCILIATION_SCHEMA = 5
CURRENT_RUN_SCHEMA = EVIDENCE_RECONCILIATION_SCHEMA
COMMAND_REVIEW_SKILL = "writing-practitioner-guides"
COMMAND_REVIEW_AGENTS = {
"planner": "command-pedagogy-planner",
"editor": "command-pedagogy-editor",
"reviewer": "command-pedagogy-reviewer",
}
FACT_REVIEW_AGENT = "fact-reviewer"
# 측정 관문 — 돌았다는 것은 요구하지만 종료 코드 0 은 요구하지 않는다.
# 문서 계약이 「error 0」을 붙인 것은 check_prose 뿐이고 style_profile 은 문체 수치를 보여 주는
# 측정이다 (stage-contracts.md:178·:252). 여기에 0 을 요구하면 정직하게 적은 원장이 실패하고,
# 0 으로 고쳐 적으면 그건 지어낸 것이 된다.
MEASUREMENT_GATES = ("style_profile.mjs",)
EVIDENCE_GATE_STAGES = {"S3", "S5", "S6"}
EVIDENCE_GATE_ID = "evidence-repo"
ORDER = ["S1", "S2", "S3", "S4", "S5", "S6", "S7"]
# 영수증을 못 찾았을 때 과거 본문을 몇 커밋까지 거슬러 보는가.
# 상한에 걸려 못 찾은 것은 「없다」가 아니라 「못 봤다」로 센다.
HISTORY_LIMIT = 200
# 원장이 단계마다 적는, 그 시점 스킬의 커밋. 이 칸이 있으면 이력을 훑지 않고 그것부터 본다.
# 없는 옛 원장은 이력 훑기로 떨어진다 — 칸이 없다고 error 를 내지 않는다.
REVISION_FIELD = "skillRevision"
# 영수증의 판정. 셋이 아니라 넷이다 — 「대조하지 못했다」가 따로 있다.
CURRENT, PAST, UNSEEN, ABSENT = "CURRENT", "PAST", "UNSEEN", "ABSENT"
def _known_projects() -> set[str]:
docs = os.path.join(ROOT, "docs")
if not os.path.isdir(docs):
return set()
return {d for d in os.listdir(docs)
if os.path.isdir(os.path.join(docs, d)) and not d.startswith(("_", "."))}
def _wrong_target(cmd: str, project: str, known: set[str]) -> str | None:
"""이 관문이 **다른 프로젝트**에 돌지 않았는지 본다 (R5).
원장은 관문의 명령 문자열과 종료 코드를 적는다. 그런데 그 명령이 어느 대상에 돌았는지는
아무도 안 봤다 — 다른 프로젝트에 돌려 exit 0 을 받아 적어도 통과로 셌다.
`docs/<이름>/` 경로와 명령 인자로 오는 프로젝트 이름 둘 다 본다.
**유효 범위 — 「다른 프로젝트」만 본다.** 같은 프로젝트 안의 **다른 기록**에 돌린 관문은
안 잡는다. `docs/<프로젝트>/` 가 같으면 통과한다. 기록 단위까지 보려면 원장의 `record` 와
대조해야 하고, 그러면 프로젝트 단위로 도는 관문(`verify-tech-log-tree.py <프로젝트>`)이
전부 걸리므로 관문마다 대상 단위를 따로 적어야 한다. 그것은 이 검사기가 아니라 계약이
먼저 정할 일이다.
"""
for m in re.finditer(r"docs/([A-Za-z0-9_.+-]+)/", cmd):
if m.group(1) != project:
return f"docs/{m.group(1)}/"
for other in known:
if other == project:
continue
if re.search(rf"(?<![\w/.-]){re.escape(other)}(?![\w/.-])", cmd):
return other
return None
def _norm(text: str) -> str:
"""공백을 하나로 접는다. 인용을 줄바꿈까지 똑같이 옮기라고 요구하지 않는다."""
return re.sub(r"\s+", " ", text).strip()
def _skill_text(skill: str) -> str | None:
"""스킬 폴더 전체(SKILL.md 와 references)의 글자. 영수증을 여기서 찾는다."""
base = os.path.join(SKILLS, skill)
if not os.path.isdir(base):
return None
out = []
for dirpath, _, names in os.walk(base):
for name in sorted(names):
if name.endswith(".md"):
try:
out.append(open(os.path.join(dirpath, name), encoding="utf-8").read())
except OSError:
pass
return _norm("\n".join(out))
def _git(*args: str) -> str | None:
"""저장소에 묻는다.
**실패는 빈 문자열이 아니라 `None` 이다.** git 이 없어서 못 본 것과 정말 비어 있는
것은 다른 답이고, 여기서 둘을 섞으면 위에서 「없다」와 「못 봤다」를 못 가른다.
"""
try:
p = subprocess.run(["git", "-C", ROOT, *args], capture_output=True,
encoding="utf-8", errors="replace", timeout=30)
except (OSError, subprocess.SubprocessError):
return None
return p.stdout if p.returncode == 0 else None
_TEXT_AT: dict[tuple[str, str], str | None] = {}
def _skill_text_at(skill: str, commit: str) -> str | None:
"""그 커밋에서의 스킬 폴더 글자. 지금 본문을 읽는 `_skill_text` 와 같은 모양으로 잇는다.
한 런에서 같은 커밋을 여러 번 보게 되므로 기억해 둔다. `-z` 를 쓰는 것은 경로에
한글이 있으면 git 이 따옴표로 감싸 내놓기 때문이다.
"""
key = (skill, commit)
if key in _TEXT_AT:
return _TEXT_AT[key]
listing = _git("ls-tree", "-r", "-z", commit, "--", f".agents/skills/{skill}")
if listing is None:
_TEXT_AT[key] = None
return None
chunks = []
for entry in listing.split("\0"):
meta, _, path = entry.partition("\t")
fields = meta.split()
if len(fields) < 3 or fields[1] != "blob" or not path.endswith(".md"):
continue
blob = _git("cat-file", "blob", fields[2])
if blob is not None:
chunks.append(blob)
_TEXT_AT[key] = _norm("\n".join(chunks))
return _TEXT_AT[key]
def _skill_commits(skill: str, limit: int = HISTORY_LIMIT):
"""그 스킬을 건드린 커밋을 최근 것부터. 두 번째 값이 상한에 걸렸는가다.
git 이 답하지 못하면 `None` — 「이력이 없다」가 아니라 「이력을 못 봤다」다.
"""
out = _git("log", f"--max-count={limit + 1}", "--format=%H",
"--", f".agents/skills/{skill}")
if out is None:
return None
commits = out.split()
return commits[:limit], len(commits) > limit
def _skill_revision(skill: str) -> str | None:
"""지금 이 스킬의 글자를 담고 있는 커밋.
작업 트리가 그 커밋과 다르면 `None` 이다 — 모르는 리비전을 지어내지 않는다.
그런 원장은 나중에 이력 훑기로 떨어지고, 그것이 맞는 결과다.
"""
rel = f".agents/skills/{skill}"
dirty = _git("status", "--porcelain", "--", rel)
if dirty is None or dirty.strip():
return None
out = _git("log", "-n", "1", "--format=%H", "--", rel)
return (out or "").strip() or None
def _echo_verdict(skill: str, echo: str, revision: str | None = None) -> tuple[str, str]:
"""영수증이 지금 그 스킬에 있나, 과거 판에만 있나, 어디에도 없나, 아니면 못 봤나.
스킬을 고치면 그 전에 쓴 원장의 영수증이 현재 본문에서 사라진다. **고친 쪽이 맞아도
그 영수증은 위조가 아니다.** 그래서 현재 본문에 없으면 과거 본문을 본다.
찾지 못한 것과 볼 수 없었던 것을 또 가른다 — git 이 없거나, 이력 상한에 걸렸거나,
스킬이 아직 커밋되지 않았으면 `ABSENT` 가 아니라 `UNSEEN` 이다.
"""
text = _skill_text(skill)
if text is not None and echo in text:
return CURRENT, ""
# 원장이 그 시점 리비전을 적어 두었으면 이력을 훑지 않고 그 커밋만 본다.
# 못 찾으면 이력으로 넘어간다 — 그 커밋 뒤에 고친 작업 트리를 읽은 원장도 있다
if revision:
past = _skill_text_at(skill, str(revision))
if past and echo in past:
return PAST, f"{str(revision)[:12]} (원장이 적은 리비전)"
history = _skill_commits(skill)
if history is None:
return UNSEEN, "git 이 없거나 이 저장소의 이력을 읽지 못했다"
commits, truncated = history
if not commits:
return UNSEEN, "이 스킬이 아직 커밋되지 않아 견줄 과거 본문이 없다"
blind = False
for commit in commits:
past = _skill_text_at(skill, commit)
if past is None:
blind = True
elif echo in past:
return PAST, commit[:12]
if truncated:
return UNSEEN, f"이력 상한 {HISTORY_LIMIT} 커밋까지 보고 못 찾았다"
if blind:
return UNSEEN, "이력의 일부를 읽지 못했다"
return ABSENT, f"커밋 {len(commits)}개를 다 봤다"
def _gate_required_since(token: str) -> tuple[str, str] | None:
"""이 관문을 요구하기 시작한 커밋과 날짜. 못 보면 None.
검사기에 관문을 더하면 **그 전에 돈 런이 전부 error 가 된다.** 그 런은 그때 요구되지
않은 것을 안 돌렸을 뿐이다. 원장에 없던 관문을 적어 넣는 것은 영수증 위조이고, 요구를
빼는 것은 검사기에 답하는 것이라, `skillEcho` 와 같은 자리를 git 으로 가른다.
"""
out = _git("log", "--reverse", "--format=%H %ad", "--date=short",
"-S", token, "--", "scripts/verify-pipeline-run.py")
if not out:
return None
first = out.splitlines()[0].split()
return (first[0], first[1]) if len(first) >= 2 else None
def _run_finished_before(run: dict, date: str) -> bool:
"""런이 그 날짜보다 먼저 끝났나. 시각을 못 읽으면 False — 모르면 봐주지 않는다."""
stamp = str(run.get("finishedAt") or run.get("startedAt") or "")[:10]
return bool(stamp) and stamp < date
def _judge_echo(rep: Report, skill: str, echo: str, revision, where: str,
prefix: str = "") -> int:
"""영수증을 판정해 보고에 적는다. 대조하지 **못한** 것이면 1 을 돌려준다.
warn 이지 통과가 아니다. 요약 줄이 그 수를 따로 세는 것은 그래서다 — 초록으로
보이면 안 된다.
"""
subject = "곁증명의 영수증" if prefix else "영수증"
kind, detail = _echo_verdict(skill, echo, revision)
if kind == CURRENT:
if not prefix and len(echo) < 20:
rep.warn("스킬 영수증이 너무 짧다", f"{where}{echo}")
return 0
if kind == PAST:
rep.warn(f"그 뒤에 스킬이 고쳐져 {subject}을 대조할 수 없다",
f"{where}{detail} 에는 있었다 · {echo[:40]}…")
return 1
if kind == UNSEEN:
rep.warn(f"스킬의 과거 본문을 못 봐서 {subject}을 대조하지 못했다",
f"{where}{detail} · {echo[:40]}…")
return 1
rep.error(f"{prefix}스킬 영수증이 그 스킬의 문장이 아니다", f"{where}{echo[:60]}…")
return 0
def _judge_run_by(rep: Report, run: dict, run_by, agent: str, where: str) -> int:
"""이 단계를 **누가** 돌렸는가. 계약이 배정한 관리 에이전트여야 한다.
`skillEcho` 는 「스킬을 열었다」를 증명하지만 **누가 열었는지는 증명하지 않는다.**
매번 새로 띄운 일반 에이전트도 SKILL.md 를 읽고 한 줄을 옮겨 적을 수 있다. 그래서
이름을 적게 하고 그 이름이 `.claude/agents/` 에 실재하는지까지 본다 — 안 그러면
「관리 에이전트를 쓴다」가 원장에서 확인되지 않는 약속으로만 남는다.
옛 판(`schemaVersion` < 2)의 원장은 이 칸이 `"subagent"` 라는 상수였다. **위조가 아니라
그때의 계약이다.** 고쳐 쓰지 않고 warn 으로 세고, 요약 줄이 그 수를 따로 적는다 —
「누가 돌렸는지 안 적혀 있다」가 「맞는 에이전트가 돌렸다」로 읽히면 안 된다.
대조하지 **못한** 것이면 1 을 돌려준다.
"""
if run_by == agent:
if not os.path.exists(os.path.join(AGENTS_DIR, f"{agent}.md")):
rep.error("그 에이전트의 정의가 없다",
f"{where} — .claude/agents/{agent}.md 가 없다")
return 0
schema = run.get("schemaVersion")
if run_by == LEGACY_RUNBY and isinstance(schema, int) and schema < AGENT_RUNBY_SCHEMA:
rep.warn("옛 판의 원장이라 누가 돌렸는지 적혀 있지 않다",
f"{where} — schemaVersion={schema} · runBy={run_by!r} 는 그때의 상수다")
return 1
rep.error("단계를 맡은 에이전트가 계약과 다르다",
f"{where} — runBy={run_by!r} · 계약은 {agent!r}")
return 0
def init(path: str, project: str, record: str, run_id: str | None) -> int:
if os.path.exists(path):
print(f"이미 있다: {path}", file=sys.stderr)
return 1
run = json.load(open(TEMPLATE, encoding="utf-8"))
now = dt.datetime.now()
run["runId"] = run_id or now.strftime("%Y-%m-%d-%H%M")
run["project"] = project
run["record"] = record
run["startedAt"] = now.astimezone().isoformat(timespec="seconds")
# 그 시점 스킬의 커밋을 단계마다 적어 둔다. 나중에 스킬이 고쳐져도 이 런의 영수증은
# 이력을 훑지 않고 이 커밋 하나로 대조된다. 작업 트리가 커밋과 다르면 null 이다
for st in run.get("stages") or []:
st[REVISION_FIELD] = _skill_revision(str(st.get("skill") or ""))
# `runBy` 도 여기서 계약에서 박는다. 틀에만 적어 두면 STAGES 와 갈리고, 갈린 뒤에는
# 「검사기가 요구하니까」 틀을 맞추게 된다 — 계약이 둘이 되는 자리다
spec = STAGES.get(str(st.get("id") or ""))
if spec:
st["runBy"] = spec["agent"]
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "w", encoding="utf-8") as fh:
json.dump(run, fh, ensure_ascii=False, indent=2)
fh.write("\n")
print(f"런을 열었다: {path} (runId={run['runId']} · project={project})")
return 0
def _side_proof(rep: Report, st: dict, sid: str, spec: dict, where: str) -> int:
"""건너뛴 단계의 곁증명(`sideProof`)을 본 단계와 같은 잣대로 검사한다.
`outputs` 가 가리키는 `*stage-report.json` 중 `"stage"` 가 이 단계인 것을 곁증명으로
본다. 곁증명이 없는 것은 정상이다 — 있는데 엉터리인 것만 잡는다.
돌려주는 값은 **대조하지 못한 영수증의 수**다. 본 단계와 같은 잣대로 센다.
"""
unverifiable = 0
for out in st.get("outputs") or []:
if not out.endswith(".json"):
continue
full = os.path.join(ROOT, out)
if not os.path.exists(full):
continue
try:
proof = json.load(open(full, encoding="utf-8"))
except (OSError, json.JSONDecodeError):
rep.error("곁증명을 읽지 못했다", f"{where}{out}")
continue
stage_of = str(proof.get("stage") or "")
if stage_of != sid and not stage_of.startswith(sid + "-"):
continue
if proof.get("skill") != spec["skill"]:
rep.error("곁증명이 다른 스킬을 썼다",
f"{where}{proof.get('skill')!r} · 계약은 {spec['skill']!r}")
echo = _norm(proof.get("skillEcho") or "")
if not echo:
rep.error("곁증명에 스킬 영수증이 없다", f"{where}{out}")
elif _skill_text(spec["skill"]) is not None:
unverifiable += _judge_echo(rep, spec["skill"], echo,
proof.get(REVISION_FIELD) or st.get(REVISION_FIELD),
where, "곁증명의 ")
gates = proof.get("gates") or []
if not gates:
rep.error("곁증명에 관문이 없다", f"{where}{out}")
for g in gates:
cmd = str(g.get("cmd") or "")
if any(tok in cmd for tok in MEASUREMENT_GATES):
if g.get("exit") is None:
rep.error("곁증명의 측정 관문에 종료 코드가 없다", f"{where}{cmd[:70]}")
continue
if g.get("exit") not in (0, "0"):
rep.error("곁증명의 관문이 통과하지 못했다",
f"{where}{cmd[:70]} → exit {g.get('exit')}")
rep.facts.setdefault("곁증명", []).append(f"{sid}:{os.path.basename(out)}")
return unverifiable
def _evidence_gate_v5(rep: Report, run: dict, sid: str, gates: list[dict], where: str) -> dict | None:
"""v5부터 live source reconciliation을 이름 있는 관문으로 검증한다.
예전 원장은 command 문자열에 `check_evidence.mjs`만 있으면 통과했다. 그러면 `--repo`를
빼서 live source 대조를 하지 않은 명령도 exit 0만 적으면 같은 초록색이 된다. v5에서는
S3/S5/S6마다 semanticId가 `evidence-repo`인 관문을 하나 요구하고 실제 `--repo` 호출인지
확인한다.
source checkout이 현재 기계에 없을 수 있다. 그 경우 실패를 0으로 바꾸지 않는다. 실제
exit 3을 `UNVERIFIABLE`로 적고 이유와 프로젝트 리뷰 수용 여부를 남긴 경우에만 절차를
정직하게 수행한 것으로 인정한다.
"""
schema = run.get("schemaVersion")
if not isinstance(schema, int) or schema < EVIDENCE_RECONCILIATION_SCHEMA:
return None
if sid not in EVIDENCE_GATE_STAGES:
return None
matches = [g for g in gates if g.get("semanticId") == EVIDENCE_GATE_ID]
if len(matches) != 1:
rep.error("필수 evidence semantic gate가 정확히 하나가 아니다",
f"{where} — semanticId={EVIDENCE_GATE_ID!r} · count={len(matches)}")
return None
gate = matches[0]
cmd = str(gate.get("cmd") or "")
if "check_evidence.mjs" not in cmd:
rep.error("evidence semantic gate가 check_evidence를 실행하지 않았다",
f"{where}{cmd[:90]}")
if not re.search(r"(?:^|\s)--repo(?:\s|$)", cmd):
rep.error("live source evidence gate에서 --repo가 빠졌다",
f"{where}{cmd[:90]}")
project = str(run.get("project") or "")
if project and not re.search(rf"(?<![\w/.-]){re.escape(project)}(?![\w/.-])", cmd):
rep.error("evidence semantic gate가 현재 프로젝트를 가리키지 않는다",
f"{where} — project={project} · {cmd[:90]}")
status = gate.get("status")
exit_code = gate.get("exit")
if status == "PASS":
if exit_code not in (0, "0"):
rep.error("PASS evidence gate의 종료 코드가 0이 아니다",
f"{where} — exit={exit_code}")
elif status == "UNVERIFIABLE":
if exit_code not in (3, "3"):
rep.error("UNVERIFIABLE evidence gate는 실제 대조 불가 exit 3이어야 한다",
f"{where} — exit={exit_code}")
if not str(gate.get("reason") or "").strip():
rep.error("UNVERIFIABLE evidence gate에 이유가 없다", where)
if gate.get("acceptedByProjectReview") is not True:
rep.error("UNVERIFIABLE evidence gate가 프로젝트 리뷰에서 수용되지 않았다", where)
rep.facts.setdefault("live source UNVERIFIABLE", []).append(sid)
else:
rep.error("evidence semantic gate status가 계약 밖이다",
f"{where} — status={status!r} · PASS|UNVERIFIABLE만 허용")
return gate
def _sha256_file(path: str) -> str:
digest = hashlib.sha256()
with open(path, "rb") as fh:
for chunk in iter(lambda: fh.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _publication_sha256(run: dict) -> str | None:
rel = str(run.get("record") or "")
if not rel or os.path.isabs(rel):
return None
full = os.path.realpath(os.path.join(ROOT, rel))
try:
if os.path.commonpath([ROOT, full]) != os.path.realpath(ROOT):
return None
except ValueError:
return None
if not os.path.isfile(full):
return None
return _sha256_file(full)
def _command_artifact(
rep: Report,
receipt,
where: str,
*,
missing_error: str = "command artifact 영수증이 없다",
) -> dict | None:
"""repo-relative path + sha256 영수증을 실제 JSON artifact와 대조한다."""
if not isinstance(receipt, dict):
rep.error(missing_error, where)
return None
rel = receipt.get("path")
expected = receipt.get("sha256")
if not isinstance(rel, str) or not rel.strip() or os.path.isabs(rel):
rep.error("command artifact path가 계약 밖이다", f"{where}{rel!r}")
return None
if not isinstance(expected, str) or not re.fullmatch(r"[0-9a-f]{64}", expected):
rep.error("command artifact sha256 형식이 잘못됐다", f"{where}{expected!r}")
return None
full = os.path.realpath(os.path.join(ROOT, rel))
try:
inside = os.path.commonpath([os.path.realpath(ROOT), full]) == os.path.realpath(ROOT)
except ValueError:
inside = False
if not inside:
rep.error("command artifact가 repository 밖을 가리킨다", f"{where}{rel}")
return None
if not os.path.isfile(full):
rep.error("command artifact 파일이 없다", f"{where}{rel}")
return None
actual = _sha256_file(full)
if actual != expected:
rep.error(
"command artifact sha256이 실제 파일과 다르다",
f"{where} — expected={expected[:12]} actual={actual[:12]} · {rel}",
)
return None
try:
with open(full, encoding="utf-8") as fh:
value = json.load(fh)
except (OSError, json.JSONDecodeError) as exc:
rep.error("command artifact JSON을 읽지 못했다", f"{where}{rel}{exc}")
return None
if not isinstance(value, dict):
rep.error("command artifact가 JSON object가 아니다", f"{where}{rel}")
return None
return value
def _review_agent(rep: Report, role: dict, expected: str, where: str) -> None:
"""품질 검토 역할이 지정된 독립 에이전트를 실제로 가리키는지 본다."""
actual = role.get("runBy")
if actual != expected:
rep.error("품질 검토 agent가 계약과 다르다",
f"{where} — runBy={actual!r} · 계약은 {expected!r}")
if not os.path.exists(os.path.join(AGENTS_DIR, f"{expected}.md")):
rep.error("품질 검토 agent 정의가 없다",
f"{where} — .claude/agents/{expected}.md 가 없다")
def _analysis_counts(
rep: Report, value, where: str, *, require_artifact: bool
) -> dict[str, object] | None:
"""결정론적 command 분석 영수증과 frozen JSON artifact를 함께 검증한다."""
if not isinstance(value, dict):
rep.error("command analysis 영수증이 없다", where)
return None
cmd = str(value.get("cmd") or "")
if "check-command-pedagogy.py" not in cmd:
rep.error("command analysis가 결정론적 검사기를 쓰지 않았다",
f"{where}{cmd or 'cmd 없음'}")
if value.get("exit") not in (0, "0"):
rep.error("command analysis를 끝내지 못했다",
f"{where} — exit {value.get('exit')}")
out: dict[str, object] = {}
for key in ("shellBlocks", "findings", "majorFindings"):
raw = value.get(key)
if isinstance(raw, bool) or not isinstance(raw, int) or raw < 0:
rep.error("command analysis 수치가 계약 밖이다",
f"{where}{key}={raw!r}")
return None
out[key] = raw
if int(out["majorFindings"]) > int(out["findings"]):
rep.error("major command finding 수가 전체 finding보다 크다", where)
receipt = value.get("artifact")
artifact = (
_command_artifact(rep, receipt, where)
if require_artifact or isinstance(receipt, dict)
else None
)
out["artifact"] = artifact
if artifact is not None:
blocks = artifact.get("blocks")
findings = artifact.get("findings")
if not isinstance(blocks, list) or not isinstance(findings, list):
rep.error("command analysis artifact 구조가 잘못됐다", where)
else:
actual_major = sum(
1 for finding in findings
if isinstance(finding, dict) and finding.get("severity") == "major"
)
expected_counts = (len(blocks), len(findings), actual_major)
receipt_counts = (
int(out["shellBlocks"]), int(out["findings"]), int(out["majorFindings"])
)
if expected_counts != receipt_counts:
rep.error(
"command analysis 영수증과 artifact 수치가 다르다",
f"{where} — receipt={receipt_counts} artifact={expected_counts}",
)
if artifact.get("authority") != "deterministic":
rep.error("command analysis artifact authority가 deterministic이 아니다", where)
return out
def _command_role(
rep: Report,
role,
*,
name: str,
required: bool,
required_error: str,
verdict: bool = False,
artifact_kind: str | None = None,
analysis: dict | None = None,
publication_sha256: str | None = None,
require_artifact: bool = True,
) -> int:
"""planner/editor/reviewer receipt와 first-class artifact를 검사한다."""
where = f"qualityReviews.commandPedagogy.{name}"
if not isinstance(role, dict):
rep.error(required_error if required else "command role 영수증이 없다", where)
return 0
expected = COMMAND_REVIEW_AGENTS[name]
_review_agent(rep, role, expected, where)
status = role.get("status")
if required and status != "DONE":
rep.error(required_error, f"{where} — status={status!r}")
elif not required and status not in ("DONE", "SKIPPED"):
rep.error("선택적 command role의 상태가 끝나지 않았다",
f"{where} — status={status!r}")
if status == "SKIPPED":
if not str(role.get("skipReason") or "").strip():
rep.error("command role을 건너뛴 사유가 없다", where)
return 0
if status != "DONE":
return 0
if role.get("skill") != COMMAND_REVIEW_SKILL:
rep.error("command role이 다른 스킬을 썼다",
f"{where}{role.get('skill')!r} · 계약은 {COMMAND_REVIEW_SKILL!r}")
echo = _norm(role.get("skillEcho") or "")
unverifiable = 0
if not echo:
rep.error("command role에 스킬 영수증이 없다", where)
elif _skill_text(COMMAND_REVIEW_SKILL) is None:
rep.error("command role의 스킬 폴더가 없다", COMMAND_REVIEW_SKILL)
else:
unverifiable += _judge_echo(
rep,
COMMAND_REVIEW_SKILL,
echo,
role.get(REVISION_FIELD),
where,
"품질 검토의 ",
)
if verdict and role.get("verdict") != "PASS":
rep.error("command-pedagogy review가 통과하지 못했다",
f"{where} — verdict={role.get('verdict')!r}")
artifact_receipt = role.get("artifact")
artifact = (
_command_artifact(
rep,
artifact_receipt,
where,
missing_error="command role artifact 영수증이 없다",
)
if require_artifact or isinstance(artifact_receipt, dict)
else None
)
if artifact is not None and artifact_kind == "plan":
try:
validate_command_plan(artifact, analysis=analysis)
except ValueError as exc:
rep.error("CommandPlan artifact가 계약과 다르다", f"{where}{exc}")
elif artifact is not None and artifact_kind == "patch":
try:
validate_command_patch_set(artifact, analysis=analysis)
except ValueError as exc:
rep.error("CommandPatchSet artifact가 계약과 다르다", f"{where}{exc}")
elif artifact is not None and artifact_kind == "review":
if artifact.get("reviewer") != expected or artifact.get("verdict") != role.get("verdict"):
rep.error("command review artifact와 reviewer 영수증이 다르다", where)
if publication_sha256 and artifact.get("source_sha256") != publication_sha256:
rep.error("command review artifact가 최종 publication hash와 다르다", where)
if require_artifact and artifact_kind == "review" and publication_sha256:
if role.get("sourceSha256") != publication_sha256:
rep.error("command review가 최종 publication hash와 다르다", where)
return unverifiable
def _verify_quality_reviews(
rep: Report,
run: dict,
*,
check_current_publication: bool = True,
) -> int:
"""v3의 command-pedagogy + 최종 technical-evidence review 계약을 검사한다.
historical/superseded run도 당시 artifact 자체의 영수증과 stage 계약은 계속 검증한다.
다만 같은 Record에 더 최신 run이 있으면 그 옛 run을 *현재* publication hash와 다시
맞추지는 않는다. 현재 publication 대조는 authoritative latest run 하나가 맡는다.
"""
schema = run.get("schemaVersion")
if not isinstance(schema, int) or schema < QUALITY_REVIEW_SCHEMA:
return 0
reviews = run.get("qualityReviews")
if not isinstance(reviews, dict):
rep.error("품질 검토 원장이 없다", "schemaVersion 3부터 qualityReviews가 필요하다")
return 0
command = reviews.get("commandPedagogy")
if not isinstance(command, dict):
rep.error("command-pedagogy 원장이 없다", "qualityReviews.commandPedagogy")
command = {}
publication_sha = _publication_sha256(run)
artifact_required = schema >= COMMAND_ARTIFACT_SCHEMA
initial = _analysis_counts(
rep, command.get("initialAnalysis"), "command initial analysis",
require_artifact=artifact_required,
)
final = _analysis_counts(
rep, command.get("finalAnalysis"), "command final analysis",
require_artifact=artifact_required,
)
unverifiable = 0
initial_findings = int(initial["findings"]) if initial else 0
final_blocks = int(final["shellBlocks"]) if final else 0
initial_artifact = initial.get("artifact") if initial else None
final_artifact = final.get("artifact") if final else None
if initial and final:
if int(initial["shellBlocks"]) > 0 and int(final["shellBlocks"]) == 0:
rep.error("command repair가 모든 shell block을 없앴다",
f"initial={initial['shellBlocks']} · final=0")
if int(final["majorFindings"]) > 0:
rep.error("major command finding이 남았다",
f"final major findings={final['majorFindings']}")
if artifact_required and publication_sha and isinstance(final_artifact, dict):
if final_artifact.get("source_sha256") != publication_sha:
rep.error("final command analysis가 최종 publication hash와 다르다", "command final analysis")
record = str(run.get("record") or "")
try:
with open(os.path.join(ROOT, record), encoding="utf-8") as fh:
publication_text = fh.read()
mode = str(final_artifact.get("mode") or "operator")
rerun = analyze_commands(
str(final_artifact.get("section_id") or record), publication_text, mode=mode
)
if (
rerun.get("source_sha256") != final_artifact.get("source_sha256")
or len(rerun.get("blocks", [])) != len(final_artifact.get("blocks", []))
or len(rerun.get("findings", [])) != len(final_artifact.get("findings", []))
):
rep.error("final command analysis artifact를 현재 publication에서 재현할 수 없다", record)
except (OSError, ValueError) as exc:
rep.error("final command analysis를 재검증하지 못했다", str(exc))
needs_edit = initial_findings > 0
unverifiable += _command_role(
rep,
command.get("planner"),
name="planner",
required=needs_edit,
required_error="명령 finding이 있는데 planner가 끝나지 않았다",
artifact_kind="plan" if needs_edit else None,
analysis=initial_artifact if isinstance(initial_artifact, dict) else None,
require_artifact=artifact_required,
)
unverifiable += _command_role(
rep,
command.get("editor"),
name="editor",
required=needs_edit,
required_error="명령 finding이 있는데 editor가 끝나지 않았다",
artifact_kind="patch" if needs_edit else None,
analysis=initial_artifact if isinstance(initial_artifact, dict) else None,
require_artifact=artifact_required,
)
unverifiable += _command_role(
rep,
command.get("reviewer"),
name="reviewer",
required=final_blocks > 0,
required_error="shell/CLI가 있는데 command reviewer가 끝나지 않았다",
verdict=True,
artifact_kind="review" if final_blocks > 0 else None,
publication_sha256=publication_sha,
require_artifact=artifact_required,
)
fact = reviews.get("technicalEvidence")
where = "qualityReviews.technicalEvidence"
if not isinstance(fact, dict):
rep.error("technical-evidence review 영수증이 없다", where)
else:
_review_agent(rep, fact, FACT_REVIEW_AGENT, where)
if fact.get("status") != "DONE":
rep.error("technical-evidence review가 끝나지 않았다",
f"{where} — status={fact.get('status')!r}")
if fact.get("verdict") != "PASS":
rep.error("technical-evidence review가 통과하지 못했다",
f"{where} — verdict={fact.get('verdict')!r}")
if artifact_required and publication_sha and fact.get("sourceSha256") != publication_sha:
rep.error("technical-evidence review가 최종 publication hash와 다르다", where)
schema = run.get("schemaVersion")
if isinstance(schema, int) and schema >= EVIDENCE_RECONCILIATION_SCHEMA:
evidence_gates = []
for st in run.get("stages") or []:
if st.get("id") not in EVIDENCE_GATE_STAGES:
continue
evidence_gates.extend(
g for g in (st.get("gates") or [])
if g.get("semanticId") == EVIDENCE_GATE_ID
)
states = {g.get("status") for g in evidence_gates}
expected = "UNVERIFIABLE" if "UNVERIFIABLE" in states else "VERIFIED"
if fact.get("liveSourceReconciliation") != expected:
rep.error("technical-evidence review의 live source 상태가 stage evidence와 다르다",
f"{where} — expected={expected} · got={fact.get('liveSourceReconciliation')!r}")
if expected == "UNVERIFIABLE":
if not str(fact.get("liveSourceReason") or "").strip():
rep.error("technical-evidence review에 live source 대조 불가 이유가 없다", where)
if fact.get("acceptedByProjectReview") is not True:
rep.error("technical-evidence review의 UNVERIFIABLE이 프로젝트 리뷰에서 수용되지 않았다",
where)
identities = []
for name in ("planner", "editor", "reviewer"):
role = command.get(name)
if isinstance(role, dict) and role.get("status") == "DONE":
identities.append(role.get("runBy"))
if isinstance(fact, dict) and fact.get("status") == "DONE":
identities.append(fact.get("runBy"))
present = [identity for identity in identities if identity]
if len(present) != len(set(present)):
rep.error("품질 검토 역할은 독립된 agent여야 한다", " · ".join(map(str, present)))
return unverifiable
def verify(path: str) -> Report:
rel = os.path.relpath(path, ROOT)
rep = Report(rel)
try:
run = json.load(open(path, encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
rep.error("원장을 읽지 못했다", f"{rel}{exc}")
return rep
for key in ("project", "record", "stages"):
if not run.get(key):
rep.error("원장에 칸이 없다", key)
project = run.get("project") or ""
rep.facts["project"] = project or "—"
known_projects = _known_projects()
stages = {s.get("id"): s for s in run.get("stages") or []}
missing = [sid for sid in ORDER if sid not in stages]
if missing:
rep.error("단계가 원장에 없다", " · ".join(missing))
counts: dict[str, int] = {}
unverifiable = 0 # 위조는 아니고 대조를 못 한 영수증. 0 으로 뭉개지 않는다
unattributed = 0 # 누가 돌렸는지 원장에 없는 단계. 영수증과 다른 것이라 따로 센다
for sid in ORDER:
st = stages.get(sid)
if st is None:
continue
spec = STAGES[sid]
status = st.get("status") or "PENDING"
counts[status] = counts.get(status, 0) + 1
where = f"{sid} {st.get('name') or ''}".strip()
if status not in STATUSES:
rep.error("status 값이 계약 밖이다", f"{where}{status}")
continue
if st.get("skill") != spec["skill"]:
rep.error("단계가 다른 스킬을 썼다",
f"{where}{st.get('skill')!r} · 계약은 {spec['skill']!r}")
unattributed += _judge_run_by(rep, run, st.get("runBy"), spec["agent"], where)
if status in ("PENDING", "RUNNING"):
rep.error("끝나지 않은 단계가 있다", f"{where}{status}")
continue
if status == "FAILED":
rep.error("단계가 실패했다", f"{where}{st.get('notes') or '사유 없음'}")
continue
if status == "SKIPPED":
if not spec["skippable"]:
rep.error("건너뛸 수 없는 단계를 건너뛰었다", where)
elif not (st.get("skipReason") or "").strip():
rep.error("건너뛴 사유가 없다",
f"{where} — 판단해서 건너뛴 것과 빠뜨린 것을 구분해야 한다")
# 이 기록에서는 건너뛰었지만 그 단계가 도는지 따로 증명했으면 그것도 검사한다.
# 안 그러면 곁증명은 아무도 읽지 않는 파일이 된다
unverifiable += _side_proof(rep, st, sid, spec, where)
continue
# ── 여기부터 DONE ────────────────────────────────────────────
echo = _norm(st.get("skillEcho") or "")
if not echo:
rep.error("스킬 영수증이 없다",
f"{where} — SKILL.md 를 열었다는 증거가 원장에 없다")
elif _skill_text(spec["skill"]) is None:
rep.error("스킬 폴더가 없다", f"{where}{spec['skill']}")
else:
unverifiable += _judge_echo(rep, spec["skill"], echo,
st.get(REVISION_FIELD), where)
gates = st.get("gates") or []
evidence_gate = _evidence_gate_v5(rep, run, sid, gates, where)
cmds = " ; ".join(str(g.get("cmd") or "") for g in gates)
for g in gates:
other = _wrong_target(str(g.get("cmd") or ""), project, known_projects)
if other:
rep.error("관문이 다른 대상에 돌았다",
f"{where}{str(g.get('cmd'))[:60]}{other} (원장은 {project})")
for token in spec["gates"]:
if token in cmds:
continue
since = _gate_required_since(token)
if since and _run_finished_before(run, since[1]):
# 그때는 요구되지 않은 관문이다. warn 이지 통과가 아니다 —
# 요약 줄이 따로 세서 초록으로 보이지 않게 한다
rep.warn("그 뒤에 관문이 늘어 이 런에는 요구되지 않았다",
f"{where}{token} · {since[0][:12]} ({since[1]}) 부터 요구한다")
unverifiable += 1
else:
rep.error("관문이 빠졌다", f"{where}{token}")
for g in gates:
cmd = str(g.get("cmd") or "")
if evidence_gate is g:
# semantic evidence gate는 위에서 PASS/UNVERIFIABLE 두 상태를 따로 검증했다.
continue
if any(tok in cmd for tok in MEASUREMENT_GATES):
# 측정 관문 — 돌았는지만 본다. exit 칸이 아예 없으면 안 돌린 것이다
if g.get("exit") is None:
rep.error("측정 관문의 종료 코드가 없다",
f"{where}{cmd[:70]} — 돌렸다는 기록이 없다")
continue
if g.get("exit") not in (0, "0"):
rep.error("관문이 통과하지 못했다",
f"{where}{cmd[:70]} → exit {g.get('exit')}")
for out in st.get("outputs") or []:
if not os.path.exists(os.path.join(ROOT, out)):
rep.error("적어 낸 산출물이 디스크에 없다", f"{where}{out}")
# 한 단계를 두 번 돌렸으면 두 번째 것도 같은 잣대로 본다
unverifiable += _side_proof(rep, st, sid, spec, where)
# v3부터는 S3의 command repair와 S6 이후 독립 review도 같은 원장에서 검증한다.
unverifiable += _verify_quality_reviews(rep, run)
rep.facts["stages"] = counts
if unverifiable:
# 「위조가 아니다」와 「맞다」는 다른 말이다. 대조를 못 한 것은 수로 남긴다
rep.facts["대조 못 한 영수증"] = unverifiable
if unattributed:
# 스킬은 대조됐는데 **누가 열었는지**는 안 적힌 단계. 초록으로 보이면 안 된다
rep.facts["누가 돌렸는지 모르는 단계"] = unattributed
record = run.get("record")
if record and not os.path.exists(os.path.join(ROOT, record)):
rep.error("런이 만든다는 기록이 없다", record)
return rep
def render(rep: Report, samples: int) -> None:
facts = " · ".join(
f"{k}={json.dumps(v, ensure_ascii=False) if isinstance(v, dict) else v}"
for k, v in rep.facts.items())
print(f" [{rep.project}] {facts or '—'}")
for label, bucket, mark in (("error", rep.errors, "✗"), ("warn", rep.warns, "!")):
for rule, details in sorted(bucket.items(), key=lambda kv: -len(kv[1])):
print(f" {mark} {label} {len(details):>4} {rule}")
for d in details[:samples]:
if d:
print(f" · {d}")
if samples and len(details) > samples:
print(f" … 외 {len(details) - samples}건")
def main() -> int:
ap = argparse.ArgumentParser(description="파이프라인 런 원장이 절차를 지켰는지 본다.")
ap.add_argument("ledgers", nargs="*", help="run.json 경로")
ap.add_argument("--init", metavar="PATH", help="틀에서 런 원장을 만든다")
ap.add_argument("--project")
ap.add_argument("--record", default="")
ap.add_argument("--run-id")
ap.add_argument("--samples", type=int, default=3)
ap.add_argument("--strict", action="store_true")
args = ap.parse_args()
if args.init:
if not args.project:
print("--init 에는 --project 가 필요하다", file=sys.stderr)
return 2
return init(args.init, args.project, args.record, args.run_id)
if not args.ledgers:
print("검사할 run.json 을 달라", file=sys.stderr)
return 2
reports = [verify(p) for p in args.ledgers]
e = sum(r.error_count for r in reports)
w = sum(r.warn_count for r in reports)
# 대조를 못 한 영수증은 error 도 아니고 「봤고 괜찮다」도 아니다. 따로 센다.
# 「누가 돌렸는지 모른다」도 같은 자리인데 **다른 것**이라 칸을 나눈다 — 스킬을 열었다는
# 증거가 없는 것과, 증거는 있는데 연 사람이 안 적힌 것은 고치는 방법이 다르다
u = sum(int(r.facts.get("대조 못 한 영수증") or 0) for r in reports)
a = sum(int(r.facts.get("누가 돌렸는지 모르는 단계") or 0) for r in reports)
print(f"PIPELINE RUN: {'FAIL' if e or (args.strict and w) else 'PASS'}"
f" — 런 {len(reports)} · error {e} · warn {w}"
f" · 대조 못 한 영수증 {u} · 누가 돌렸는지 모르는 단계 {a}")
for r in reports:
render(r, args.samples)
return 1 if e or (args.strict and w) else 0
if __name__ == "__main__":
raise SystemExit(main())