d3ro-voice/scripts/ci/check-protected-tests.mjs
Yun Chan d3d6f34bfa test(infra): gate protected acceptance tests and ratchet test quality (TDD 2.0 Phase 1)
docs/tdd-red/07-revamp-plan.md Phase 1 — v1.1이 문서로만 선언한 것을 게이트로 옮긴다.

보호 수용 경로 게이트 (check-protected-tests.mjs):
- 06 §5 의 보호 6경로를 base revision 과 비교한다.
- 실패 조건: 테스트/스텝 블록 감소, expect 감소, .only 추가, skip/todo 추가,
  보호 파일 삭제.
- 정당한 스펙 변경은 커밋 본문 `allow-protected-change: <사유>` 또는 --reason 으로만
  통과한다(사람 리뷰 대체 아님). CI quality 잡이 --base HEAD^ 로 실행하며
  체크아웃이 depth 2 로 바뀐다. 얕은 클론에서는 SKIP 사유를 출력한다.

품질 래칫 (check-test-quality.mjs + test-quality-baseline.json):
- 파일별 weak-assertion(toBeDefined/toBeTruthy/toBeFalsy/toBeNull)과
  ambient-time(Date.now/Math.random/performance.now) 수치를 동결하고 증가만 막는다.
- 128 / 203 건을 한 번에 고치지 않고 회귀만 차단한다. --update 는 리뷰 후 실행.

배선: verify:all 에 두 게이트 편입, CI quality 잡 단계 추가,
map/02 §10 · tdd-red/06 §5·§6 · 07 Phase 0-1 상태 갱신.

검증:
- self-test: check-protected-tests 6케이스, check-test-quality 6케이스 통과
- 실제 약화 주입 시 두 게이트가 exit 1 (smoke.spec.ts .only, 약한 단정 추가) 후 원복
- npm run test:hygiene / check:design GREEN, npm test GREEN (2800+605+31+24)
2026-11-08 21:11:12 +09:00

271 lines
9.9 KiB
JavaScript

#!/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()
}