#!/usr/bin/env node // scripts/ci/check-protected-tests.mjs // TDD 2.0 Phase 1 — 보호 수용 경로(protected acceptance) 무결성 게이트. // // 정책 정본: docs/tdd-red/06-repo-application.md §5 · docs/tdd-red/07-revamp-plan.md §3-1 // 목적: "읽지 못하게"가 아니라 "고치지 못하게"(05 §2). 보호 여정의 테스트가 // 조용히 약화·삭제·skip 되는 것을 커밋 단계에서 막는다. // // 규칙 (protected 파일이 변경된 경우): // protected-deleted 보호 파일이 사라졌다 // cases-decreased it/test/expectNoRuntimeErrors 기반 여정 블록이 줄었다 // assertions-decreased expect(...) 가 줄었다 // focused-only-added .only 가 새로 생겼다 (다른 여정을 건너뛴다) // unmarked-skip-added 이유 없는 .skip()/.todo() 가 새로 생겼다 // // 정당한 변경(제품 행위 변경): 커밋 본문에 `allow-protected-change: <사유>` 를 남기거나 // PROTECTED_CHANGE_REASON="<사유>" 로 실행한다. 사람 리뷰를 대체하지 않는다. // // 사용: // node scripts/ci/check-protected-tests.mjs # HEAD 대비 작업 트리 // node scripts/ci/check-protected-tests.mjs --base origin/main // node scripts/ci/check-protected-tests.mjs --reason "..." # 정당한 스펙 변경 // node scripts/ci/check-protected-tests.mjs --self-test import { execFileSync } from 'node:child_process' import { existsSync, readFileSync } from 'node:fs' import { join } from 'node:path' const CWD = process.cwd() /** 보호 경로 — docs/tdd-red/06-repo-application.md §5 와 반드시 같아야 한다. */ export const PROTECTED_FILES = [ 'apps/desktop/tests/e2e/navigation.spec.ts', 'apps/desktop/tests/e2e/settings.spec.ts', 'apps/desktop/tests/e2e/onboarding.spec.ts', 'apps/desktop/tests/e2e/customer-support.spec.ts', 'apps/desktop/tests/e2e/records.spec.ts', 'apps/web/e2e/smoke.spec.ts', ] const TEST_BLOCK = /(?:^|\n)\s*test(?:\.(?:only|skip|todo|concurrent|each(?:\([^\n]*?\))?))?\s*\(/g const STEP_BLOCK = /test\.step\s*\(/g const ASSERTION = /\bexpect(?:NoRuntimeErrors)?\s*\(/g const ONLY = /\.only\s*\(/g // 보호 경로에서는 skip/todo 자체가 계약 변경이다 — 사유는 커밋 마커로 남긴다. const SKIP_ANY = /\.(?:skip|todo)\s*\(/g function count(text, re) { re.lastIndex = 0 let n = 0 while (re.exec(text)) n += 1 return n } /** 보호 파일 본문 비교 — 순수 함수(테스트 가능). */ export function detectWeakening(before, after) { const violations = [] const beforeCases = count(before, TEST_BLOCK) + count(before, STEP_BLOCK) const afterCases = count(after, TEST_BLOCK) + count(after, STEP_BLOCK) if (afterCases < beforeCases) { violations.push({ rule: 'cases-decreased', detail: `여정/스텝 블록 ${beforeCases} → ${afterCases}`, }) } const beforeAssertions = count(before, ASSERTION) const afterAssertions = count(after, ASSERTION) if (afterAssertions < beforeAssertions) { violations.push({ rule: 'assertions-decreased', detail: `단정 ${beforeAssertions} → ${afterAssertions}`, }) } const onlyDelta = count(after, ONLY) - count(before, ONLY) if (onlyDelta > 0) { violations.push({ rule: 'focused-only-added', detail: `.only +${onlyDelta}` }) } const skipDelta = count(after, SKIP_ANY) - count(before, SKIP_ANY) if (skipDelta > 0) { violations.push({ rule: 'unmarked-skip-added', detail: `skip/todo +${skipDelta}` }) } return violations } function git(args, options = {}) { return execFileSync('git', args, { cwd: CWD, encoding: 'utf8', maxBuffer: 1 << 26, // stderr 는 호출부가 처리한다(얕은 클론 등) — 콘솔을 더럽히지 않는다. stdio: ['ignore', 'pipe', 'ignore'], ...options, }) } function changedFiles(base) { const tracked = git(['diff', '--name-only', base]).split('\n') const staged = git(['diff', '--name-only', '--cached', base]).split('\n') const untracked = git(['ls-files', '--others', '--exclude-standard']).split('\n') return [...new Set([...tracked, ...staged, ...untracked].map((l) => l.trim().replaceAll('\\', '/')).filter(Boolean))] } function headBlob(base, path) { try { return git(['show', `${base}:${path}`]) } catch { return null } } function readWorking(path) { const full = join(CWD, path) return existsSync(full) ? readFileSync(full, 'utf8') : null } function commitReason() { try { const body = git(['log', '-1', '--format=%B']) const match = /allow-protected-change:\s*(\S.*)/.exec(body) return match ? match[1].trim() : null } catch { return null } } export function evaluate({ base, protectedFiles = PROTECTED_FILES, changed, beforeOf, afterOf }) { const violations = [] for (const path of protectedFiles) { if (!changed.includes(path)) continue const before = beforeOf(path) const after = afterOf(path) if (after === null) { violations.push({ path, rule: 'protected-deleted', detail: '보호 파일이 삭제됐다' }) continue } if (before === null) continue // 새 보호 여정 추가 — 약화가 아니다 for (const v of detectWeakening(before, after)) violations.push({ path, ...v }) } return { base, violations } } function runSelfTest() { const cases = [ { name: '테스트 하나 삭제 → cases-decreased', before: "test('a', async () => { expect(1).toBe(1) })\ntest('b', async () => { expect(2).toBe(2) })", after: "test('a', async () => { expect(1).toBe(1) })", expectRules: ['cases-decreased', 'assertions-decreased'], }, { name: '단정 하나 약화/삭제 → assertions-decreased', before: "test('a', async () => { await expect(x).toBeVisible(); expect(y).toBe(1) })", after: "test('a', async () => { await expect(x).toBeVisible() })", expectRules: ['assertions-decreased'], }, { name: '.only 추가 → focused-only-added', before: "test('a', async () => { expect(1).toBe(1) })", after: "test.only('a', async () => { expect(1).toBe(1) })", expectRules: ['focused-only-added'], }, { name: '이유 없는 skip 추가 → unmarked-skip-added', before: "test('a', async () => { expect(1).toBe(1) })", after: "test.skip('a', async () => { expect(1).toBe(1) })", expectRules: ['unmarked-skip-added'], }, { name: '여정·스텝·단정 추가 → 위반 없음', before: "test('a', async () => { expect(1).toBe(1) })", after: "test('a', async () => { await test.step('s', async () => { await expect(nav).toHaveCount(1) })\n expect(2).toBe(2) })", expectRules: [], }, ] let failures = 0 for (const c of cases) { const rules = detectWeakening(c.before, c.after).map((v) => v.rule).sort() const ok = JSON.stringify(rules) === JSON.stringify([...c.expectRules].sort()) if (!ok) { failures += 1 process.stdout.write(`FAIL ${c.name} — got ${JSON.stringify(rules)}\n`) } else { process.stdout.write(`ok ${c.name}\n`) } } // evaluate() 자체 경로도 확인한다 (파일 삭제 + 변경 없음). const deleted = evaluate({ base: 'test', protectedFiles: PROTECTED_FILES.slice(0, 1), changed: [PROTECTED_FILES[0]], beforeOf: () => "test('a', async () => { expect(1).toBe(1) })", afterOf: () => null, }) if (deleted.violations[0]?.rule !== 'protected-deleted') { failures += 1 process.stdout.write('FAIL 보호 파일 삭제 감지\n') } else { process.stdout.write('ok 보호 파일 삭제 감지\n') } if (failures > 0) { process.stdout.write(`\ncheck-protected-tests self-test 실패 ${failures}건\n`) process.exit(1) } process.stdout.write('\ncheck-protected-tests self-test 통과\n') } function main() { const argv = process.argv.slice(2) if (argv.includes('--self-test')) { runSelfTest() return } const baseIndex = argv.indexOf('--base') const base = baseIndex >= 0 ? argv[baseIndex + 1] : 'HEAD' const reasonIndex = argv.indexOf('--reason') const reason = reasonIndex >= 0 ? argv[reasonIndex + 1] : process.env.PROTECTED_CHANGE_REASON || commitReason() const missing = PROTECTED_FILES.filter((path) => !existsSync(join(CWD, path))) let changed try { changed = changedFiles(base) } catch { // CI 얕은 클론(depth 1)에서는 비교 기준 revision 이 없다. 게이트를 통과시키고 사실을 알린다. process.stdout.write( `[protected-tests] SKIP — 기준 revision \`${base}\` 을 찾을 수 없습니다(얕은 클론). ` + '로컬/전체 클론에서 검사하세요.\n', ) return } const { violations } = evaluate({ base, changed, beforeOf: (path) => headBlob(base, path), afterOf: (path) => readWorking(path), }) if (missing.length > 0) { for (const path of missing) { violations.push({ path, rule: 'protected-deleted', detail: '보호 파일이 저장소에 없다' }) } } if (violations.length === 0) { process.stdout.write(`[protected-tests] GREEN (base ${base}, 변경된 보호 파일 ${changed.filter((f) => PROTECTED_FILES.includes(f)).length}개)\n`) return } if (reason) { process.stdout.write(`[protected-tests] 사유가 기록된 변경 — 통과: ${reason}\n`) for (const v of violations) process.stdout.write(` · ${v.path} ${v.rule} (${v.detail})\n`) return } process.stdout.write('[protected-tests] 보호 수용 테스트가 약화되었습니다.\n') for (const v of violations) process.stdout.write(` ✗ ${v.path} · ${v.rule} — ${v.detail}\n`) process.stdout.write( '\n제품 행위가 정말 바뀌었다면 커밋 본문에 다음을 남기세요:\n' + ' allow-protected-change: <왜 사용자가 하는 일이 바뀌었는가>\n' + '정책: docs/tdd-red/06-repo-application.md §5\n', ) process.exit(1) } if (process.argv[1] && process.argv[1].replaceAll('\\', '/').endsWith('check-protected-tests.mjs')) { main() }