#!/usr/bin/env bash # 검증 진입점. 사람·CI·에이전트가 같은 명령을 쓴다(docs/work/reference/gates.md). # # scripts/verify.sh <단계> [대상…] [--on here|<호스트>] [--log <이름>] [--apply-back] [--dry-run] [-- 인자…] # # 단계 무엇 기본 위치 # docs 작업 매뉴얼 검사(check-work-docs.py)와 장부 형식 여기 # hooks repo 훅·검사기·장부 시험(python3 unittest) 여기 # gate … 게이트마다 `corepack pnpm ci:gate `, CI env로 desktop # parts 그 게이트의 명령을 하나씩 끝까지(첫 실패에서 멈추지 않음) desktop # script <이름>… [-- 인자] package script를 하나씩. `--` 뒤 인자는 script가 하나일 때만 desktop # exec -- <명령…> 명령 하나(예: node scripts/run-vitest.ts run <파일>) desktop # 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/, 홈 기준), 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), VERIFY_INSTALL(0이면 원격 의존성 설치를 건너뛴다). # 종료 코드: 0 통과, 1 실패, 2 사용법, 4 원격 준비 실패. set -euo pipefail ROOT=$(git rev-parse --show-toplevel) 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,26p' "$0" | sed 's/^# \{0,1\}//' >&2 exit 2 } # ---------------------------------------------------------------- config/ci/gates.json 읽기 gates_json() { python3 - "$@" <<'PY' import json, sys contract = json.load(open("config/ci/gates.json", encoding="utf-8")) kind, *names = sys.argv[1:] if kind == "stages": print("\n".join(stage["id"] for stage in contract["stages"])) elif kind == "stage": found = [stage for stage in contract["stages"] if stage["id"] == names[0]] if not found: sys.exit(1) print("\n".join(found[0]["gateIds"])) elif kind == "gate": if not any(gate["id"] == names[0] for gate in contract["gates"]): sys.exit(1) elif kind == "scripts": gate = next((gate for gate in contract["gates"] if gate["id"] == names[0]), None) if gate is None: sys.exit(1) commands = {command["id"]: command for command in contract["commands"]} for command_id in gate["commandIds"]: command = commands[command_id] print(f'{command["script"]}\t{command.get("expect", "pass")}\t{command.get("expectedExitCode", "")}') PY } is_stage() { gates_json stages | grep -qx -- "$1"; } # ---------------------------------------------------------------- 단계 본문 run_docs() { local rc=0 python3 scripts/check-work-docs.py || rc=1 if [ -s docs/ledger/estimates.jsonl ] && ! python3 -c ' import json, sys for number, line in enumerate(open(sys.argv[1], encoding="utf-8"), 1): if line.strip(): json.loads(line) ' docs/ledger/estimates.jsonl; then echo "docs/ledger/estimates.jsonl에 JSON이 아닌 줄이 있다." >&2 rc=1 fi return "$rc" } run_hooks() { python3 -m unittest discover -s scripts/tests; } # CI workflow의 전역 env(.gitea/workflows/quality-gates.yml)와 같은 꼴. CI=true가 있어야 빌드 식별값을 엄격하게 본다. ci_env() { local sha sha=$(git rev-parse HEAD) export CI=true VITE_COMMIT_SHA="$sha" VITE_BUILD_ID="gitea-${VERIFY_RUN:-1}-1" \ RELEASE_ID="refs/heads/${VERIFY_REF:-verify}-${VERIFY_RUN:-1}-1" \ CI_RUNNER_IMAGE="local/runner@sha256:$(printf 'a%.0s' $(seq 64))" } # 한 줄 결과: "<이름> rc= <초>s". 로그는 VERIFY_STEP_LOGS가 있으면 그 폴더에 이름별로. step() { local name=$1 rc start log shift if [ "$DRY_RUN" = 1 ]; then local shown shown=$(printf '%q ' "$@") echo "$name: ${shown% }" return 0 fi start=$(date +%s) log=${VERIFY_STEP_LOGS:+$VERIFY_STEP_LOGS/$(printf '%s' "$name" | tr ' /:' '___').log} set +e if [ -n "$log" ]; then "$@" > "$log" 2>&1; else "$@"; fi rc=$? set -e echo "$name rc=$rc $(( $(date +%s) - start ))s" | tee -a "${VERIFY_SUMMARY:-/dev/null}" return "$rc" } run_gates() { local failed=0 gate [ "$DRY_RUN" = 1 ] || ci_env for gate in "$@"; do gates_json gate "$gate" || { echo "verify: config/ci/gates.json에 없는 게이트: $gate" >&2; return 2; } step "$gate" corepack pnpm -s ci:gate "$gate" || failed=1 done return "$failed" } run_parts() { local gate=$1 failed=0 script expect code rc [ "$DRY_RUN" = 1 ] || ci_env gates_json scripts "$gate" > /dev/null || { echo "verify: config/ci/gates.json에 없는 게이트: $gate" >&2; return 2; } while IFS=$'\t' read -r script expect code; do rc=0 step "$gate $script" corepack pnpm -s "$script" || rc=$? # expect=fail인 명령(음성 fixture)은 정해진 종료 코드로 실패해야 통과다. if [ "$expect" = fail ]; then [ "$DRY_RUN" = 1 ] || [ "$rc" = "${code:-1}" ] || failed=1 elif [ "$rc" != 0 ]; then failed=1 fi done < <(gates_json scripts "$gate") return "$failed" } # script 이름들, 그 뒤에 `--`와 인자(script가 하나일 때만, check_args가 본다). run_scripts() { 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 ]; } # 원격으로 보내기 전에 여기서 사용법을 본다. 잘못된 단계 때문에 desktop에 worktree를 만들지 않는다. check_args() { local stage=$1 gate shift case "$stage" in docs | hooks) [ $# -eq 0 ] || usage ;; gate) [ $# -gt 0 ] || usage 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) 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 } run_here() { local stage=$1 shift case "$stage" in docs | hooks) [ $# -eq 0 ] || usage; [ "$DRY_RUN" = 1 ] && { echo "$stage"; return 0; }; "run_$stage" ;; 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 # shellcheck disable=SC2046 # 게이트 ID는 공백 없는 낱말이다 run_gates $(gates_json stage "$stage") ;; esac } 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=${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} log_root=${VERIFY_LOG_ROOT:-/tmp/claude-gates} node_bin=${VERIFY_NODE_BIN:-"\$HOME/.nvm/versions/node/v$(tr -d '[:space:]' < .nvmrc)/bin"} base=$(git merge-base HEAD "${VERIFY_BASE_REF:-origin/main}") ref=$(git branch --show-current | tr '/' '-') laptop_stage "$1" && install=0 tmp_index=$(mktemp) patch=$(mktemp) TMP_FILES+=("$tmp_index" "$patch") cp "$(git rev-parse --git-path index)" "$tmp_index" GIT_INDEX_FILE=$tmp_index git add -A tree=$(GIT_INDEX_FILE=$tmp_index git write-tree) git diff --binary "$base" "$tree" > "$patch" id="verify-$(date +%s)-$$" # 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 </dev/null || git fetch -q origin || exit 4 git cat-file -e $base^{commit} || { echo "기준 커밋 ${base:0:12}이 원격에 없다. 그 커밋을 push한다." >&2; exit 4; } wt=\$(mktemp -d /tmp/$id.XXXXXX) 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 } trap cleanup EXIT cd "\$wt" if [ -s /tmp/$id.patch ]; then git apply --binary --index /tmp/$id.patch || exit 4; fi got=\$(git write-tree) if [ "\$got" != "$tree" ]; then echo "트리 해시가 다르다: 원격 \$got, 여기 $tree" >&2; exit 4; fi # 게이트는 깨끗한 HEAD(커밋 식별값 = 트리)를 본다. 훅을 거치지 않는 commit-tree로 이 worktree에만 만든다. commit=\$(git -c user.name=verify -c user.email=verify@localhost commit-tree "\$got" -p HEAD -m "verify $id") git checkout -q --detach "\$commit" mkdir -p "\$(dirname $lock)" "\$logs" : > "\$logs/summary.txt" echo "tree $tree commit \$commit \$(date '+%F %T') load \$(cut -d' ' -f1 /proc/loadavg)" >> "\$logs/summary.txt" if [ $install = 1 ]; then CI=true corepack pnpm install --frozen-lockfile --offline > "\$logs/install.log" 2>&1 \ || CI=true corepack pnpm install --frozen-lockfile >> "\$logs/install.log" 2>&1 \ || { 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 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() { local stage=${1:-} on="" log="" rest=() [ -n "$stage" ] || usage shift while [ $# -gt 0 ]; do case "$1" in --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 done check_args "$stage" ${rest[@]+"${rest[@]}"} if [ -z "$on" ]; then if laptop_stage "$stage"; then on=here; else on=${VERIFY_HOST:-desktop}; fi fi if [ "$on" = here ] || [ "$DRY_RUN" = 1 ]; then run_here "$stage" ${rest[@]+"${rest[@]}"} else log=${log:-"$(git branch --show-current | tr '/' '-')-$stage"} run_remote "$on" "${log:-detached}" "$stage" ${rest[@]+"${rest[@]}"} fi } main "$@"