// scripts/ci/run-affected-tests.mjs // TDD v2.0 Phase 3 — 변경 파일 기반 영향 테스트 선택 실행기 (Affected Test Runner). // // 사용법: // node scripts/ci/run-affected-tests.mjs # git working tree + HEAD 변경 감지 후 실행 // node scripts/ci/run-affected-tests.mjs --dry-run # 실행할 스위트·명령 JSON 만 출력 // node scripts/ci/run-affected-tests.mjs --files a.ts,b.tsx # 명시적 파일 목록 기준 // node scripts/ci/run-affected-tests.mjs --base origin/main # 기준 커밋 대비 변경 감지 // node scripts/ci/run-affected-tests.mjs --self-test # 매핑·안전 폴백 자체 테스트 // // 안전 원칙: // - 루트 설정(package.json, tsconfig*, eslint*) 또는 미분류 경로가 포함되면 전체 스위트(full)로 폴백한다. // - CI 는 항상 전체 스위트를 실행하며, 이 스크립트는 로컬 개발 루프(<60초) 가속 전용이다. import { spawnSync } from 'node:child_process' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' const root = join(dirname(fileURLToPath(import.meta.url)), '..', '..') const SUITE_COMMANDS = { hygiene: 'npm run test:hygiene', core: 'npm run test --workspace=@d3ro/core', i18n: 'npm run test --workspace=@d3ro/i18n', 'check:i18n': 'npm run check:i18n', ui: 'npm run test --workspace=@d3ro/ui', 'check:ds-contract': 'npm run check:ds-contract', 'api-client': 'npm run test --workspace=@d3ro/api-client', 'desktop:unit': 'npm --prefix apps/desktop run test -- --mode unit', 'desktop:service': 'npm --prefix apps/desktop run test -- --mode service', desktop: 'npm run test --workspace=@d3ro/desktop', web: 'npm run test --workspace=@d3ro/web', admin: 'npm run test --workspace=@d3ro/admin', mobile: 'npm run test:mobile', dotnet: 'dotnet test apps/api-server.Tests/D3ROVoice.Api.Tests.csproj', 'check:migrations': 'npm run check:migrations', site: 'npm run typecheck:site && npm run lint:site', 'ci-self-tests': 'npm run test:hygiene:test && npm run check:i18n:test && npm run check:ds-contract:test && npm run release:metadata:test' } const SUITE_ORDER = [ 'hygiene', 'check:i18n', 'check:ds-contract', 'check:migrations', 'ci-self-tests', 'core', 'i18n', 'ui', 'api-client', 'desktop:unit', 'desktop:service', 'desktop', 'web', 'admin', 'mobile', 'dotnet', 'site' ] function normalizePath(filePath) { return filePath.replace(/\\/g, '/').replace(/^\.\//, '').trim() } function isDocsOnlyPath(path) { return ( path.startsWith('docs/') || path.startsWith('memory/') || path.endsWith('.md') || path === 'LICENSE' || path === '.gitignore' ) } function isGlobalFallbackTrigger(path) { return ( path === 'package.json' || path === 'package-lock.json' || /^tsconfig(\..+)?\.json$/.test(path) || path.startsWith('.eslintrc') || path === '.eslintignore' ) } export function planAffectedSuites(rawFiles) { const files = [...new Set(rawFiles.map(normalizePath).filter(Boolean))] if (files.length === 0) { return { mode: 'none', files, suites: [], commands: [] } } if (files.every(isDocsOnlyPath)) { return { mode: 'docs-only', files, suites: ['hygiene'], commands: [SUITE_COMMANDS.hygiene] } } const suites = new Set(['hygiene']) let fallbackFull = false for (const file of files) { if (isDocsOnlyPath(file)) continue if (isGlobalFallbackTrigger(file)) { fallbackFull = true break } if (file.startsWith('packages/core/')) { suites.add('core') suites.add('desktop') suites.add('web') suites.add('admin') suites.add('mobile') } else if (file.startsWith('packages/i18n/')) { suites.add('i18n') suites.add('check:i18n') suites.add('desktop') suites.add('web') suites.add('mobile') } else if (file.startsWith('packages/ui/')) { suites.add('ui') suites.add('check:ds-contract') suites.add('desktop') suites.add('web') suites.add('admin') } else if (file.startsWith('packages/ui-native/')) { suites.add('mobile') } else if (file.startsWith('packages/api-client/')) { suites.add('api-client') suites.add('web') suites.add('admin') suites.add('mobile') } else if (file.startsWith('apps/desktop/sidecar/')) { suites.add('desktop:unit') } else if (file.startsWith('apps/desktop/src/main/')) { suites.add('desktop:service') suites.add('desktop:unit') } else if ( file.startsWith('apps/desktop/src/renderer/') || file.startsWith('apps/desktop/src/preload/') ) { suites.add('desktop:unit') } else if (file.startsWith('apps/desktop/')) { suites.add('desktop') } else if (file.startsWith('apps/web/')) { suites.add('web') } else if (file.startsWith('apps/admin/')) { suites.add('admin') } else if (file.startsWith('apps/mobile-rn/')) { suites.add('mobile') } else if (file.startsWith('apps/api-server/') || file.startsWith('apps/api-server.Tests/')) { suites.add('dotnet') } else if (file.startsWith('server/supabase/migrations/')) { suites.add('check:migrations') } else if (file.startsWith('server/')) { suites.add('hygiene') } else if (file.startsWith('site/')) { suites.add('site') } else if ( file.startsWith('scripts/ci/') || file.startsWith('.forgejo/') || file.startsWith('release/') ) { suites.add('ci-self-tests') } else { fallbackFull = true break } } if (fallbackFull) { return { mode: 'full', files, suites: ['hygiene', 'full'], commands: ['npm run test:hygiene', 'npm run test', 'npm run test:mobile'] } } if (suites.has('desktop')) { suites.delete('desktop:unit') suites.delete('desktop:service') } const orderedSuites = SUITE_ORDER.filter((name) => suites.has(name)) const commands = orderedSuites.map((name) => SUITE_COMMANDS[name]) return { mode: 'affected', files, suites: orderedSuites, commands } } function detectChangedFiles(baseRef) { const collected = new Set() const addLines = (stdout) => { for (const line of (stdout ?? '').split(/\r?\n/)) { const trimmed = line.trim() if (trimmed) collected.add(trimmed) } } if (baseRef) { const diffBase = spawnSync('git', ['diff', '--name-only', `${baseRef}...HEAD`], { cwd: root, encoding: 'utf8' }) if (diffBase.status === 0) addLines(diffBase.stdout) } const diffWorktree = spawnSync('git', ['diff', '--name-only', 'HEAD'], { cwd: root, encoding: 'utf8' }) if (diffWorktree.status === 0) addLines(diffWorktree.stdout) const untracked = spawnSync('git', ['ls-files', '--others', '--exclude-standard'], { cwd: root, encoding: 'utf8' }) if (untracked.status === 0) addLines(untracked.stdout) return [...collected] } function runSelfTest() { const assertEqual = (actual, expected, label) => { const a = JSON.stringify(actual) const b = JSON.stringify(expected) if (a !== b) { throw new Error(`affected_self_test_failed:${label}:expected=${b},actual=${a}`) } } assertEqual(planAffectedSuites([]).mode, 'none', 'empty') assertEqual( planAffectedSuites(['docs/map/10-feature-catalog.md', 'CHANGELOG.md']).mode, 'docs-only', 'docs_only' ) assertEqual( planAffectedSuites(['packages/core/src/guards.ts']).suites, ['hygiene', 'core', 'desktop', 'web', 'admin', 'mobile'], 'core_fanout' ) assertEqual( planAffectedSuites(['apps/desktop/src/main/services/SuggestionService.ts']).suites, ['hygiene', 'desktop:unit', 'desktop:service'], 'desktop_main_scoped' ) assertEqual( planAffectedSuites(['packages/ui/src/components/ds/SegmentControl.tsx']).suites, ['hygiene', 'check:ds-contract', 'ui', 'desktop', 'web', 'admin'], 'ui_fanout' ) assertEqual( planAffectedSuites(['apps/mobile-rn/src/screens/HomeScreen.tsx']).suites, ['hygiene', 'mobile'], 'mobile_isolated' ) assertEqual( planAffectedSuites(['apps/api-server/Controllers/SttController.cs']).suites, ['hygiene', 'dotnet'], 'dotnet_isolated' ) assertEqual( planAffectedSuites(['unknown-top-level-dir/foo.ts']).mode, 'full', 'unknown_fallback_full' ) process.stdout.write('[test:affected] self-test GREEN (8 cases)\n') } const args = process.argv.slice(2) if (args.includes('--self-test')) { runSelfTest() process.exit(0) } const filesIdx = args.indexOf('--files') const baseIdx = args.indexOf('--base') const dryRun = args.includes('--dry-run') const inputFiles = filesIdx !== -1 && args[filesIdx + 1] ? args[filesIdx + 1].split(',') : detectChangedFiles(baseIdx !== -1 ? args[baseIdx + 1] : null) const plan = planAffectedSuites(inputFiles) if (dryRun) { process.stdout.write(`${JSON.stringify(plan, null, 2)}\n`) process.exit(0) } if (plan.commands.length === 0) { process.stdout.write('[test:affected] 변경된 코드 파일이 없습니다 — 실행할 스위트 없음.\n') process.exit(0) } process.stdout.write(`[test:affected] mode=${plan.mode} suites=[${plan.suites.join(', ')}]\n`) for (const command of plan.commands) { process.stdout.write(`[test:affected] $ ${command}\n`) const res = spawnSync(command, { cwd: root, stdio: 'inherit', shell: true }) if (res.status !== 0) { process.stderr.write(`[test:affected] 실패: ${command} (exit ${res.status ?? 'null'})\n`) process.exit(res.status ?? 1) } } process.stdout.write('[test:affected] GREEN\n')