feat(scripts): verify.sh가 인자를 넘기고 원격에서 바뀐 파일을 돌려받는다

cold-read 시험에서 두 곳이 막혔다. script 단계가 인자를 넘기지 못해
test:sample-removal -- --feature=<id>를 돌릴 수 없었고, desktop에서
만든 파일(create:feature, 초기 JS 기록 다시 쓰기)을 노트북으로 가져올
길이 없었다. dry-run은 공백 든 인자를 실제와 다르게 보였다.

- script <이름> -- <인자…>: 인자는 script가 하나일 때만 넘긴다.
- exec -- <명령…>: 한 테스트 파일이나 package script가 아닌 node 스크립트.
- 원격에서 바뀐 파일은 로그 폴더의 changes.patch에 남고, --apply-back이면
  노트북 작업 트리에 얹는다.
- VERIFY_SNAPSHOT=1이면 artifacts·dist·test-results를 snapshot/에 복사한다
  (리뷰어가 함께 읽는 사본). VERIFY_INSTALL=0은 설치를 건너뛴다(시험용).
- dry-run이 인자를 %q로 보인다.
- 원격 호출은 단계 다음에 --on here를 둔다. 뒤에 두면 `--` 뒤 명령
  인자가 되어 원격이 자기를 다시 원격으로 보냈다(시험에서 잠금 교착으로
  드러났다).
- 원격 준비가 일찍 실패해도 /tmp의 패치 파일을 지운다.

위험·한계: --apply-back은 노트북 작업 트리가 원격 기준과 다르면 패치가
얹히지 않는다. 그때는 rc=4와 원격 패치 경로를 알린다.

검증: python3 -m unittest scripts/tests/test_verify.py 통과(인자 전달,
exec, 잘못된 인자 10가지가 원격 호출 0, 가짜 ssh로 원격에서 만든 파일
둘을 돌려받음, 바뀐 것 없는 단계의 changes.patch는 빈 파일).
This commit is contained in:
DongHyeonka
2026-11-08 17:53:36 +09:00
parent 4a21bc79a1
commit c50da34712
2 changed files with 86 additions and 20 deletions
+20 -1
View File
@@ -51,13 +51,23 @@ class StagePlanTest(unittest.TestCase):
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_arguments_after_the_separator_go_to_the_one_script_or_command_as_given(self) -> None:
result = sh([str(VERIFY), "script", "test:sample-removal", "--dry-run", "--", "--feature=invoice-feature"],
cwd=REPO)
self.assertEqual(result.stdout.strip(),
"test:sample-removal: corepack pnpm -s test:sample-removal --feature=invoice-feature")
result = sh([str(VERIFY), "exec", "--dry-run", "--", "node", "scripts/run-vitest.ts", "run", "tests/a b.test.ts"],
cwd=REPO)
self.assertEqual(result.stdout.strip(), r"exec node: node scripts/run-vitest.ts run tests/a\ b.test.ts")
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"]):
for args in (["nope"], ["gate", "FE-GATE-999"], ["parts"], ["gate"], ["merge", "extra"], ["docs", "x"],
["script", "a", "b", "--", "--x"], ["exec"], ["exec", "--"], ["script", "--", "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)
@@ -109,6 +119,15 @@ class RemoteTransportTest(unittest.TestCase):
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, "")
self.assertEqual((logs / "t/changes.patch").read_text(encoding="utf-8"), "")
made = sh(["scripts/verify.sh", "exec", "--on", "build-host", "--log", "t2", "--apply-back", "--", "bash", "-c",
"echo made > made.txt && echo more >> notes.md"], cwd=project,
env={**env, "VERIFY_INSTALL": "0"}, check=False)
self.assertEqual(made.returncode, 0, made.stdout + made.stderr)
self.assertEqual((project / "made.txt").read_text(encoding="utf-8"), "made\n")
self.assertEqual((project / "notes.md").read_text(encoding="utf-8"), "커밋 안 한 새 파일\nmore\n")
self.assertIn("2개를 이 작업 트리에 얹었다", made.stderr)
missing = sh(["scripts/verify.sh", "docs", "--on", "build-host"], cwd=project,
env={**env, "VERIFY_REMOTE_REPO": str(base / "missing")}, check=False)
+66 -19
View File
@@ -1,24 +1,28 @@
#!/usr/bin/env bash
# 검증 진입점. 사람·CI·에이전트가 같은 명령을 쓴다(docs/work/reference/gates.md).
#
# scripts/verify.sh <단계> [대상…] [--on here|<호스트>] [--log <이름>] [--dry-run]
# scripts/verify.sh <단계> [대상…] [--on here|<호스트>] [--log <이름>] [--apply-back] [--dry-run] [-- 인자…]
#
# 단계 무엇 기본 위치
# docs 작업 매뉴얼 검사(check-work-docs.py)와 장부 형식 여기
# hooks repo 훅·검사기·장부 시험(python3 unittest) 여기
# gate <FE-GATE-NNN>… 게이트마다 `corepack pnpm ci:gate <ID>`, CI env로 desktop
# parts <FE-GATE-NNN> 그 게이트의 명령을 하나씩 끝까지(첫 실패에서 멈추지 않음) desktop
# script <이름>… package script를 하나씩(예: verify:documentation) desktop
# <stage id> config/ci/gates.json stages의 gateIds 전부(merge 등) desktop
# 단계 무엇 기본 위치
# docs 작업 매뉴얼 검사(check-work-docs.py)와 장부 형식 여기
# hooks repo 훅·검사기·장부 시험(python3 unittest) 여기
# gate <FE-GATE-NNN>… 게이트마다 `corepack pnpm ci:gate <ID>`, CI env로 desktop
# parts <FE-GATE-NNN> 그 게이트의 명령을 하나씩 끝까지(첫 실패에서 멈추지 않음) desktop
# script <이름>… [-- 인자] package script를 하나씩. `--` 뒤 인자는 script가 하나일 때만 desktop
# exec -- <명령…> 명령 하나(예: node scripts/run-vitest.ts run <파일>) desktop
# <stage id> config/ci/gates.json stages의 gateIds 전부(merge 등) desktop
#
# 게이트·stage는 실패가 있어도 끝까지 돌고, 끝에 게이트마다 rc와 초를 적는다. 실패가 하나라도 있으면 rc=1.
# --on <호스트>: 지금 작업 트리(커밋 안 된 변경 포함)를 패치로 그 호스트에 옮긴다. 기준 커밋에서 새 worktree를
# 만들어 패치를 적용하고 트리 해시가 여기와 같은지 본 뒤, 그 트리를 커밋 하나로 만들어(깨끗한 HEAD) 의존성을
# 오프라인으로 설치하고 잠금 아래에서 같은 단계를 돌린다. 로그를 남기고 worktree를 지운다. push하지 않는다.
# 원격에서 바뀐 파일은 로그 폴더의 changes.patch에 남는다. --apply-back이면 그 패치를 여기 작업 트리에 얹는다
# (create:feature, 기준선 다시 쓰기처럼 파일을 만드는 명령). VERIFY_SNAPSHOT=1이면 artifacts·dist·test-results를
# 로그 폴더의 snapshot/에 복사한다(리뷰어가 함께 읽는 사본).
# 환경 변수: VERIFY_HOST(desktop 단계의 --on 기본값, 기본 desktop), VERIFY_REMOTE_REPO(원격 checkout, 기본
# workspace/<repo 이름>, 홈 기준), VERIFY_BASE_REF(기본 origin/main), VERIFY_LOCK(기본 /tmp/claude-gates/heavy.lock),
# VERIFY_LOG_ROOT(원격 로그 폴더, 기본 /tmp/claude-gates), VERIFY_SSH(기본 ssh), VERIFY_NODE_BIN(원격 node 폴더,
# 기본 ~/.nvm/versions/node/v<.nvmrc>/bin).
# 기본 ~/.nvm/versions/node/v<.nvmrc>/bin), VERIFY_INSTALL(0이면 원격 의존성 설치를 건너뛴다).
# 종료 코드: 0 통과, 1 실패, 2 사용법, 4 원격 준비 실패.
set -euo pipefail
@@ -27,9 +31,10 @@ cd "$ROOT"
TMP_FILES=()
trap '[ ${#TMP_FILES[@]} -eq 0 ] || rm -f "${TMP_FILES[@]}"' EXIT # 빈 배열 + set -u는 옛 bash에서 오류다
DRY_RUN=0
APPLY_BACK=0
usage() {
sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//' >&2
sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//' >&2
exit 2
}
@@ -96,7 +101,9 @@ step() {
local name=$1 rc start log
shift
if [ "$DRY_RUN" = 1 ]; then
echo "$name: $*"
local shown
shown=$(printf '%q ' "$@")
echo "$name: ${shown% }"
return 0
fi
start=$(date +%s)
@@ -136,14 +143,22 @@ run_parts() {
return "$failed"
}
# script 이름들, 그 뒤에 `--`와 인자(script가 하나일 때만, check_args가 본다).
run_scripts() {
local failed=0 script
for script in "$@"; do
step "$script" corepack pnpm -s "$script" || failed=1
local failed=0 names=() script
while [ $# -gt 0 ] && [ "$1" != -- ]; do names+=("$1"); shift; done
[ $# -eq 0 ] || shift
for script in "${names[@]}"; do
step "$script" corepack pnpm -s "$script" "$@" || failed=1
done
return "$failed"
}
run_exec() {
[ "${1:-}" = -- ] && shift
step "exec $1" "$@"
}
# ---------------------------------------------------------------- 실행 위치
laptop_stage() { [ "$1" = docs ] || [ "$1" = hooks ]; }
@@ -158,7 +173,13 @@ check_args() {
for gate in "$@"; do gates_json gate "$gate" || { echo "verify: config/ci/gates.json에 없는 게이트: $gate" >&2; exit 2; }; done ;;
parts) [ $# -eq 1 ] || usage
gates_json gate "$1" || { echo "verify: config/ci/gates.json에 없는 게이트: $1" >&2; exit 2; } ;;
script) [ $# -gt 0 ] || usage ;;
script)
local names=0
while [ $# -gt 0 ] && [ "$1" != -- ]; do names=$((names + 1)); shift; done
[ "$names" -gt 0 ] || usage
# 인자는 script 하나에만 준다. 여럿에 같은 인자를 주면 뜻이 갈린다.
[ $# -le 1 ] || [ "$names" -eq 1 ] || usage ;;
exec) { [ "${1:-}" = -- ] && [ $# -gt 1 ]; } || usage ;;
*) is_stage "$stage" || usage; [ $# -eq 0 ] || usage ;;
esac
}
@@ -171,6 +192,7 @@ run_here() {
gate) [ $# -gt 0 ] || usage; run_gates "$@" ;;
parts) [ $# -eq 1 ] || usage; run_parts "$1" ;;
script) [ $# -gt 0 ] || usage; run_scripts "$@" ;;
exec) run_exec "$@" ;;
*)
is_stage "$stage" || usage
[ $# -eq 0 ] || usage
@@ -183,7 +205,7 @@ run_here() {
run_remote() {
local host=$1 log=$2 ssh=${VERIFY_SSH:-ssh}
shift 2
local name base tree tmp_index patch id remote_repo lock log_root node_bin args ref install=1
local name base tree tmp_index patch id remote_repo lock log_root node_bin args ref install=${VERIFY_INSTALL:-1} rc=0 back
name=$(basename "$(dirname "$(git rev-parse --path-format=absolute --git-common-dir)")")
remote_repo=${VERIFY_REMOTE_REPO:-"workspace/$name"}
lock=${VERIFY_LOCK:-/tmp/claude-gates/heavy.lock}
@@ -200,12 +222,15 @@ run_remote() {
tree=$(GIT_INDEX_FILE=$tmp_index git write-tree)
git diff --binary "$base" "$tree" > "$patch"
id="verify-$(date +%s)-$$"
args=$(printf '%q ' "$@")
# The stage first, then --on here, then the rest: an option after `--` would reach the command instead.
args="$(printf '%q' "$1") --on here"
[ $# -lt 2 ] || args+=" $(printf '%q ' "${@:2}")"
echo "verify: $host에서 '$*' (기준 ${base:0:12}, 트리 ${tree:0:12}, 로그 $log_root/$log/)" >&2
$ssh "$host" "cat > /tmp/$id.patch" < "$patch"
$ssh "$host" bash -s <<EOF
$ssh "$host" bash -s <<EOF || rc=$?
set -u
export PATH="$node_bin:\$PATH"
trap 'rm -f /tmp/$id.patch' EXIT
cd $remote_repo || exit 4
repo=\$(pwd)
git cat-file -e $base^{commit} 2>/dev/null || git fetch -q origin || exit 4
@@ -215,6 +240,10 @@ logs=$log_root/$log
git worktree add -q --detach "\$wt" $base || exit 4
cleanup() {
cp -r "\$wt/artifacts/quality/gates" "\$logs/gate-artifacts" 2>/dev/null
if [ "${VERIFY_SNAPSHOT:-0}" = 1 ]; then
mkdir -p "\$logs/snapshot"
for kept in artifacts dist test-results; do cp -r "\$wt/\$kept" "\$logs/snapshot/" 2>/dev/null; done
fi
cd "\$repo"
git worktree remove --force "\$wt"
rm -f /tmp/$id.patch
@@ -236,12 +265,28 @@ if [ $install = 1 ]; then
|| { echo "의존성 설치 실패: \$logs/install.log" >&2; exit 4; }
fi
export VERIFY_SUMMARY="\$logs/summary.txt" VERIFY_STEP_LOGS="\$logs" VERIFY_REF="$ref"
flock $lock ./scripts/verify.sh $args --on here 2>&1 | tee "\$logs/run.log"
flock $lock ./scripts/verify.sh $args 2>&1 | tee "\$logs/run.log"
rc=\${PIPESTATUS[0]}
git status --porcelain > "\$logs/status-after.txt"
git add -A > /dev/null 2>&1
git diff --cached --binary HEAD > "\$logs/changes.patch"
echo "rc=\$rc" >> "\$logs/summary.txt"
exit \$rc
EOF
if [ "$APPLY_BACK" = 1 ]; then
back=$(mktemp)
TMP_FILES+=("$back")
$ssh "$host" "cat $log_root/$log/changes.patch" > "$back" 2>/dev/null || :
if [ ! -s "$back" ]; then
echo "verify: 원격에서 바뀐 파일이 없다." >&2
elif git apply --binary "$back"; then
echo "verify: 원격에서 바뀐 파일 $(grep -c '^diff --git' "$back")개를 이 작업 트리에 얹었다(git status로 본다)." >&2
else
echo "verify: 원격 변경을 얹지 못했다. 패치는 $host:$log_root/$log/changes.patch" >&2
[ "$rc" != 0 ] || rc=4
fi
fi
return "$rc"
}
main() {
@@ -253,6 +298,8 @@ main() {
--on) on=${2:?--on 뒤에 호스트}; shift 2 ;;
--log) log=${2:?--log 뒤에 이름}; shift 2 ;;
--dry-run) DRY_RUN=1; shift ;;
--apply-back) APPLY_BACK=1; shift ;;
--) rest+=("$@"); break ;;
-*) usage ;;
*) rest+=("$1"); shift ;;
esac