desktop에서 게이트를 돌리는 법이 문서와 세션마다 다른 손 절차였다 (checkout 바꾸기·되돌리기, CI env 넣기, runner 스크립트 복사). 같은 빈틈이 되풀이됐고, 공유 checkout의 브랜치를 바꾼 채 두는 위험이 있었다. scripts/verify.sh <단계>는 claude-harness template/scripts/verify.sh의 운반부를 쓰고 단계를 채운다. - 단계: config/ci/gates.json의 stage id(merge·release·production·field· documentation)는 그 gateIds 전부를 ci:gate로, gate <ID>…, parts <ID>(그 게이트의 명령을 하나씩 끝까지, FE-GATE-013 진단용), script <이름>…, docs·hooks(노트북). stage는 실패가 있어도 끝까지 돌고 게이트마다 rc와 초를 남긴다. - desktop: 지금 트리를 기준 커밋에 대한 패치로 보내 공유 checkout에서 새 worktree를 만들고, 트리 해시를 맞춘 뒤 commit-tree로 깨끗한 HEAD를 만든다. CI=true pnpm install --frozen-lockfile --offline 뒤 flock 잠금 아래 CI env(CI, VITE_COMMIT_SHA, VITE_BUILD_ID, RELEASE_ID, CI_RUNNER_IMAGE)로 돌리고, /tmp/claude-gates/<이름>/에 summary·로그·게이트 산출물· status-after를 남긴 뒤 worktree를 지운다. push하지 않는다. - 잘못된 단계·게이트는 desktop에 보내기 전에 노트북에서 거절한다. 버린 대안: 공유 checkout의 브랜치를 잠금 안에서 바꾸고 되돌리기(지금 손 절차). 다른 세션의 checkout을 건드리고, 끝나지 않으면 바뀐 채 남는다. 위험·한계: 새 worktree의 오프라인 설치는 desktop pnpm store에 의존한다. 없으면 온라인 설치로 넘어간다. CI workflow가 아직 이 스크립트를 부르지 않는다(CI 재편 몫). 검증: python3 -m unittest scripts/tests/test_verify.py 통과(stage마다 계약의 gateIds, parts의 명령, 잘못된 인자는 원격 호출 0, 가짜 ssh로 패치 → 같은 트리 해시 → 로그 → worktree 정리, 없는 원격 repo는 rc=4). desktop에서 실제 운반을 한 번 돌려 트리 해시 일치와 worktree 정리를 봤다. Refs: design-docs harness/01-harness-design.md 6절
120 lines
6.6 KiB
Python
120 lines
6.6 KiB
Python
"""scripts/verify.sh의 시험. 단계를 계약 파일에서 읽는지, 잘못된 인자를 원격에 보내기 전에 거절하는지,
|
|
지금 트리를 원격 worktree로 옮겨 같은 트리에서 돌리고 지우는지를 표준 라이브러리와 git·bash·flock으로 본다.
|
|
원격은 가짜 ssh(호스트를 무시하고 이 기계에서 실행)다. pnpm은 돌리지 않는다.
|
|
|
|
python3 -m unittest discover -s scripts/tests
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
REPO = Path(__file__).resolve().parent.parent.parent
|
|
VERIFY = REPO / "scripts/verify.sh"
|
|
GIT_ENV = {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@example.com", "GIT_COMMITTER_NAME": "t",
|
|
"GIT_COMMITTER_EMAIL": "t@example.com", "GIT_CONFIG_COUNT": "1", "GIT_CONFIG_KEY_0": "core.hooksPath",
|
|
"GIT_CONFIG_VALUE_0": "/dev/null"}
|
|
|
|
|
|
def sh(args: list[str], cwd: Path, env: dict | None = None, check: bool = True) -> subprocess.CompletedProcess:
|
|
result = subprocess.run(args, cwd=cwd, env={**os.environ, **GIT_ENV, **(env or {})}, capture_output=True,
|
|
text=True, timeout=60)
|
|
if check and result.returncode != 0:
|
|
raise AssertionError(f"{args} → {result.returncode}\n{result.stdout}\n{result.stderr}")
|
|
return result
|
|
|
|
|
|
def gates() -> dict:
|
|
return json.loads((REPO / "config/ci/gates.json").read_text(encoding="utf-8"))
|
|
|
|
|
|
class StagePlanTest(unittest.TestCase):
|
|
def test_a_stage_runs_every_gate_the_contract_lists(self) -> None:
|
|
for stage in gates()["stages"]:
|
|
with self.subTest(stage=stage["id"]):
|
|
result = sh([str(VERIFY), stage["id"], "--dry-run"], cwd=REPO)
|
|
planned = [line.split(":")[0] for line in result.stdout.splitlines()]
|
|
self.assertEqual(planned, stage["gateIds"])
|
|
self.assertIn(f"ci:gate {stage['gateIds'][0]}", result.stdout)
|
|
|
|
def test_parts_runs_each_command_of_the_gate(self) -> None:
|
|
contract = gates()
|
|
gate = next(g for g in contract["gates"] if g["id"] == "FE-GATE-013")
|
|
scripts = {c["id"]: c["script"] for c in contract["commands"]}
|
|
result = sh([str(VERIFY), "parts", "FE-GATE-013", "--dry-run"], cwd=REPO)
|
|
self.assertEqual([line.split(": ", 1)[1] for line in result.stdout.splitlines()],
|
|
[f"corepack pnpm -s {scripts[c]}" for c in gate["commandIds"]])
|
|
|
|
def test_wrong_arguments_are_refused_here_before_anything_is_sent(self) -> None:
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
calls = Path(folder) / "calls"
|
|
fake_ssh = Path(folder) / "ssh"
|
|
fake_ssh.write_text(f'#!/bin/sh\necho "$@" >> {calls}\n', encoding="utf-8")
|
|
fake_ssh.chmod(0o755)
|
|
for args in (["nope"], ["gate", "FE-GATE-999"], ["parts"], ["gate"], ["merge", "extra"], ["docs", "x"]):
|
|
with self.subTest(args=args):
|
|
result = sh([str(VERIFY), *args], cwd=REPO, env={"VERIFY_SSH": str(fake_ssh)}, check=False)
|
|
self.assertEqual(result.returncode, 2, result.stderr)
|
|
self.assertFalse(calls.exists(), "a refused command must not reach the remote host")
|
|
|
|
|
|
class RemoteTransportTest(unittest.TestCase):
|
|
"""--on <호스트>: the patch lands in a fresh worktree, the tree matches, the run is logged, the worktree goes."""
|
|
|
|
def test_the_working_tree_is_run_remotely_on_the_same_tree_and_cleaned_up(self) -> None:
|
|
with tempfile.TemporaryDirectory() as folder:
|
|
base = Path(folder)
|
|
project, bare, remote, logs = (base / name for name in ("project", "origin.git", "remote", "logs"))
|
|
(project / "scripts").mkdir(parents=True)
|
|
(project / "config/ci").mkdir(parents=True)
|
|
shutil.copy(VERIFY, project / "scripts/verify.sh")
|
|
shutil.copy(REPO / "config/ci/gates.json", project / "config/ci/gates.json")
|
|
shutil.copy(REPO / ".nvmrc", project / ".nvmrc")
|
|
(project / "scripts/check-work-docs.py").write_text("print('docs checked')\n", encoding="utf-8")
|
|
sh(["git", "init", "-q", "-b", "main"], cwd=project)
|
|
sh(["git", "add", "-A"], cwd=project)
|
|
sh(["git", "commit", "-q", "-m", "init"], cwd=project)
|
|
sh(["git", "clone", "-q", "--bare", str(project), str(bare)], cwd=base)
|
|
sh(["git", "remote", "add", "origin", str(bare)], cwd=project)
|
|
sh(["git", "fetch", "-q", "origin"], cwd=project)
|
|
sh(["git", "clone", "-q", str(bare), str(remote)], cwd=base)
|
|
(project / "notes.md").write_text("커밋 안 한 새 파일\n", encoding="utf-8")
|
|
with (project / "scripts/check-work-docs.py").open("a", encoding="utf-8") as handle:
|
|
handle.write("print('changed here')\n")
|
|
fake_ssh = base / "fake-ssh"
|
|
fake_ssh.write_text('#!/bin/sh\nshift\nexec bash -c "$*"\n', encoding="utf-8")
|
|
fake_ssh.chmod(0o755)
|
|
env = {"VERIFY_SSH": str(fake_ssh), "VERIFY_REMOTE_REPO": str(remote), "VERIFY_LOCK": str(base / "lock"),
|
|
"VERIFY_LOG_ROOT": str(logs), "VERIFY_NODE_BIN": "/nonexistent"}
|
|
temp_index = base / "index"
|
|
shutil.copy(project / ".git/index", temp_index)
|
|
sh(["git", "add", "-A"], cwd=project, env={"GIT_INDEX_FILE": str(temp_index)})
|
|
here = sh(["git", "write-tree"], cwd=project, env={"GIT_INDEX_FILE": str(temp_index)}).stdout.strip()
|
|
|
|
result = sh(["scripts/verify.sh", "docs", "--on", "build-host", "--log", "t"], cwd=project, env=env,
|
|
check=False)
|
|
|
|
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
|
summary = (logs / "t/summary.txt").read_text(encoding="utf-8")
|
|
self.assertTrue(summary.startswith(f"tree {here} commit "), summary)
|
|
self.assertIn("rc=0", summary)
|
|
self.assertIn("changed here", (logs / "t/run.log").read_text(encoding="utf-8"))
|
|
self.assertFalse((logs / "t/install.log").exists(), "a laptop stage installs nothing")
|
|
worktrees = sh(["git", "worktree", "list"], cwd=remote).stdout.strip().splitlines()
|
|
self.assertEqual(len(worktrees), 1, worktrees)
|
|
self.assertEqual(sh(["git", "status", "--porcelain"], cwd=remote).stdout, "")
|
|
|
|
missing = sh(["scripts/verify.sh", "docs", "--on", "build-host"], cwd=project,
|
|
env={**env, "VERIFY_REMOTE_REPO": str(base / "missing")}, check=False)
|
|
self.assertEqual(missing.returncode, 4)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|