#!/usr/bin/env python3 """파이프라인 런 원장이 절차를 지켰는지 본다. 이 검사기는 글의 품질을 보지 않는다. **절차의 준수**를 본다 — 단계가 빠졌는지, 그 단계가 자기 스킬을 실제로 열었는지, 관문이 돌았고 종료 코드가 0 이었는지, 적어 낸 산출물이 디스크에 있는지. python3 scripts/verify-pipeline-run.py --init runs/<프로젝트>//run.json \\ --project <프로젝트> --record <기록 경로> python3 scripts/verify-pipeline-run.py runs/<프로젝트>//run.json **`skillEcho` 가 이 검사기의 핵심이다.** 단계마다 그 SKILL.md 에서 한 줄을 원문 그대로 옮겨 오게 하고, 그 문자열이 실제로 그 파일 안에 있는지 대조한다. 스킬을 안 읽고 결과만 그럴듯하게 낸 단계는 여기서 걸린다. 계약은 `.agents/skills/running-tech-log-pipeline/references/stage-contracts.md` 다. """ from __future__ import annotations import argparse import datetime as dt import json import os import re import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from techlog import Report # noqa: E402 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") # 단계마다 어떤 스킬이 맡고, 관문에 어떤 명령이 있어야 하는가. # 관문은 명령 문자열에 이 토큰이 들어 있는지로 본다 — 호출형이 조금씩 달라도 같은 검사다. STAGES = { "S1": {"skill": "analyzing-codebase-for-tech-log", "gates": ["verify-project-layout.py"], "skippable": True}, "S2": {"skill": "deriving-tech-log-root-tree", "gates": ["build-tech-log-tree.py", "verify-tech-log-tree.py"], "skippable": True}, "S3": {"skill": "writing-tech-log-records", "gates": ["check_body.mjs", "check_prose.mjs", "check_evidence.mjs"], "skippable": False}, "S4": {"skill": "technical-visualizer", "gates": ["lint", "check-figure-text.py", "check-figure-overlap.py"], "skippable": True}, "S5": {"skill": "rewriting-technical-prose-naturally", "gates": ["check_prose.mjs", "style_profile.mjs", "check_body.mjs"], "skippable": False}, "S6": {"skill": "writing-as-the-person-who-did-it", "gates": ["check_voice.mjs", "check_prose.mjs"], "skippable": False}, "S7": {"skill": "publishing-tech-log-to-studio", "gates": ["저장됨", "verify-tech-log-tree.py"], "skippable": True}, } ORDER = ["S1", "S2", "S3", "S4", "S5", "S6", "S7"] 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 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") 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) -> None: """건너뛴 단계의 곁증명(`sideProof`)을 본 단계와 같은 잣대로 검사한다. `outputs` 가 가리키는 `*stage-report.json` 중 `"stage"` 가 이 단계인 것을 곁증명으로 본다. 곁증명이 없는 것은 정상이다 — 있는데 엉터리인 것만 잡는다. """ 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 "") text = _skill_text(spec["skill"]) if not echo: rep.error("곁증명에 스킬 영수증이 없다", f"{where} — {out}") elif text is not None and echo not in text: rep.error("곁증명의 스킬 영수증이 그 스킬의 문장이 아니다", f"{where} — {echo[:60]}…") gates = proof.get("gates") or [] if not gates: rep.error("곁증명에 관문이 없다", f"{where} — {out}") for g in gates: if g.get("exit") not in (0, "0"): rep.error("곁증명의 관문이 통과하지 못했다", f"{where} — {str(g.get('cmd'))[:70]} → exit {g.get('exit')}") rep.facts.setdefault("곁증명", []).append(f"{sid}:{os.path.basename(out)}") 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 "—" 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] = {} 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}") if st.get("runBy") != "subagent": rep.warn("서브에이전트가 아닌 것으로 적혀 있다", f"{where} — runBy={st.get('runBy')!r}") 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} — 판단해서 건너뛴 것과 빠뜨린 것을 구분해야 한다") # 이 기록에서는 건너뛰었지만 그 단계가 도는지 따로 증명했으면 그것도 검사한다. # 안 그러면 곁증명은 아무도 읽지 않는 파일이 된다 _side_proof(rep, st, sid, spec, where) continue # ── 여기부터 DONE ──────────────────────────────────────────── echo = _norm(st.get("skillEcho") or "") if not echo: rep.error("스킬 영수증이 없다", f"{where} — SKILL.md 를 열었다는 증거가 원장에 없다") else: text = _skill_text(spec["skill"]) if text is None: rep.error("스킬 폴더가 없다", f"{where} — {spec['skill']}") elif echo not in text: rep.error("스킬 영수증이 그 스킬의 문장이 아니다", f"{where} — {echo[:60]}…") elif len(echo) < 20: rep.warn("스킬 영수증이 너무 짧다", f"{where} — {echo}") gates = st.get("gates") or [] cmds = " ; ".join(str(g.get("cmd") or "") for g in gates) for token in spec["gates"]: if token not in cmds: rep.error("관문이 빠졌다", f"{where} — {token}") for g in gates: if g.get("exit") not in (0, "0"): rep.error("관문이 통과하지 못했다", f"{where} — {str(g.get('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}") # 한 단계를 두 번 돌렸으면 두 번째 것도 같은 잣대로 본다 _side_proof(rep, st, sid, spec, where) rep.facts["stages"] = counts 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) print(f"PIPELINE RUN: {'FAIL' if e or (args.strict and w) else 'PASS'}" f" — 런 {len(reports)} · error {e} · warn {w}") 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())