이번 파이프라인 작업과 무관하게 작업 트리에 남아 있던 것을 그대로 올린다. 사용자가 「전부 커밋」으로 정했고, 이번 작업과 섞이지 않게 커밋만 나눴다. 대부분은 clean-architecture-backend-template 의 그림 정본 재배치다 — final/assets/diagrams/<이름>/ 에 있던 것이 CLAUDE.md 가 적은 배치인 final/assets/<이름>/ 로 옮겨졌고 .techviz/<이름>/ 이 함께 들어왔다. 삽입 줄의 대부분(3.15M)이 그 .techviz context.json 이다. 그 밖에 ca-tmpl·document-haness 의 정리, .claude/agents/ 열한 개, writing-practitioner-guides 스킬, .playwright-mcp 세션 산출물, scripts/check-ssot-facts.py 와 그 시험이 들어 있다. 이 커밋의 내용은 내가 만든 것이 아니라 이전 세션이 남긴 것이고 검증하지 않았다. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
598 lines
29 KiB
Python
598 lines
29 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 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
|
|
|
|
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
|
|
|
|
# 측정 관문 — 돌았다는 것은 요구하지만 종료 코드 0 은 요구하지 않는다.
|
|
# 문서 계약이 「error 0」을 붙인 것은 check_prose 뿐이고 style_profile 은 문체 수치를 보여 주는
|
|
# 측정이다 (stage-contracts.md:178·:252). 여기에 0 을 요구하면 정직하게 적은 원장이 실패하고,
|
|
# 0 으로 고쳐 적으면 그건 지어낸 것이 된다.
|
|
MEASUREMENT_GATES = ("style_profile.mjs",)
|
|
|
|
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 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 []
|
|
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 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)
|
|
|
|
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())
|