Files
clean-architecture-frontend…/scripts/verify.sh
T
DongHyeonka 1d3eb901d2 ci(gates): FE-GATE-013을 일회용 systemd 컨테이너 안에서 돌린다
문제: FE-GATE-013의 test:system은 provider sandbox를 실제로 띄운다.
systemd user manager(systemd-run --user --scope)와 cgroup v2 위임,
bubblewrap(--unshare-net 등)이 필요하다. runner의 job 컨테이너는
entrypoint가 sleep이라 systemd가 없고 bwrap도 없어 사전 점검에서 실패한다
(run 56·80·81). desktop 호스트는 다 있지만 Ubuntu 24.04의
apparmor_restrict_unprivileged_userns=1이 비특권 bwrap을 막는다.
그래서 이 게이트는 runner와 desktop 어디서도 초록인 적이 없다.

고른 방법(소유자 결정 2026-11-11 5절 e: 조건이 되는 실행 환경을 찾는다):
- config/ci/system-container.Dockerfile: Ubuntu 24.04(digest 고정) +
  systemd PID 1 + root linger + bubblewrap 등 hostRequirements의 도구.
- scripts/run-in-system-container.sh: 이미지(Dockerfile 해시 태그)가 없으면
  만들고, privileged·자체 cgroup namespace로 띄워 systemd와 root user
  manager를 기다린 뒤, 작업 트리·git 이력·호출한 쪽의 node와 corepack을
  복사해 명령을 root로 돌리고 artifacts/를 되가져온 다음 지운다. root는
  호스트의 userns 제한을 받지 않는다.
- gates.json 게이트 필드 hostEnvironment: "system-container"(FE-GATE-013).
  생성기는 그 게이트의 run 줄에 래퍼를 붙이고, 실행 검사
  (workflowGateExecutionFailures)는 계약이 정한 접두어로 돈 줄만 센다.
  scripts/verify.sh gate·parts·stage도 같은 래퍼로 돌린다.
- CI에서는 runner의 Docker proxy로 안쪽 dind daemon을 쓴다(platform-core
  gitea-runner README가 「남은 위험」으로 적은 길: proxy가 privileged
  컨테이너를 막지 않는다).
- 버린 대안: 전용 VM runner(문서 조건을 그대로 만족하지만 platform-core
  변경과 VM 자원·runner 등록이 필요), 호스트 AppArmor profile(호스트
  userns 제한을 푸는 보안 설정 변경, 소유자 sudo).

위험·한계:
- root로 돌아 「비특권 runner에서 bwrap userns」 조건 자체는 증명하지
  않는다. release 단계 provider job 둘은 아직 job 컨테이너에서 돈다(범위
  밖, 같은 래퍼나 VM runner가 필요).
- runner가 rootless dind로 바뀌면 privileged 컨테이너를 못 띄워 깨진다.
- 래퍼 준비(이미지 확인·기동·복사)에 desktop에서 50~60초가 든다.

검증(desktop): 래퍼로 check-system-test-prerequisites → PASS(root),
tests/system/ci-runner/provider-process-group.test.ts 1개 통과.
python3 -m unittest scripts.tests.test_verify 통과, check:ci PASS(게이트 28),
ci-workflow-generation 시험 통과. 게이트 전체(test:system 116개 포함)는 이
브랜치 끝의 merge 단계에서 돈다.
2026-11-12 00:04:05 +09:00

343 lines
14 KiB
Bash
Executable File

#!/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 <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), 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 == "host":
gate = next((gate for gate in contract["gates"] if gate["id"] == names[0]), None)
if gate is None:
sys.exit(1)
print(gate.get("hostEnvironment", ""))
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]
# \x1f between fields keeps an empty exit code a field; \x1e between the command's args.
args = "\x1e".join(command.get("args", []))
print(f'{command["script"]}\x1f{command.get("expect", "pass")}\x1f{command.get("expectedExitCode", "")}\x1f{args}')
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))" \
SOURCE_DATE_EPOCH="$(git log -1 --format=%ct)"
# ci:gate makes SOURCE_DATE_EPOCH from HEAD itself; parts and script call the commands directly.
}
# 한 줄 결과: "<이름> rc=<n> <초>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"
}
# 계약이 hostEnvironment를 정한 게이트(FE-GATE-013)는 workflow와 같이 그 환경에서 돈다.
host_prefix() {
case "$(gates_json host "$1")" in
system-container) echo scripts/run-in-system-container.sh ;;
esac
}
run_gates() {
local failed=0 gate prefix
[ "$DRY_RUN" = 1 ] || ci_env
for gate in "$@"; do
gates_json gate "$gate" || { echo "verify: config/ci/gates.json에 없는 게이트: $gate" >&2; return 2; }
prefix=$(host_prefix "$gate")
# shellcheck disable=SC2086 # 접두어는 공백 없는 경로 하나이거나 비어 있다
step "$gate" $prefix corepack pnpm -s ci:gate "$gate" || failed=1
done
return "$failed"
}
run_parts() {
local gate=$1 failed=0 script expect code argtext rc args prefix
[ "$DRY_RUN" = 1 ] || ci_env
gates_json scripts "$gate" > /dev/null || { echo "verify: config/ci/gates.json에 없는 게이트: $gate" >&2; return 2; }
prefix=$(host_prefix "$gate")
while IFS=$'\x1f' read -r script expect code argtext; do
rc=0
args=()
# The command's args, as run-ci-gate.ts passes them (`pnpm <script> ...args`).
[ -z "$argtext" ] || IFS=$'\x1e' read -r -a args <<< "$argtext"
# shellcheck disable=SC2086
step "$gate $script" $prefix corepack pnpm -s "$script" ${args[@]+"${args[@]}"} || 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 <<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
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 "$@"