/** * policy-guard-cli.js — BADA Terminal 자가 치유 Pre-Commit & 정책 가드 CLI * * 설명 문서: /docs/specs/bada_trio_actionable_spec.md (SPEC-ACT-001 v1.0.0) * 관련 규약: AGENTS.md, Zero-Trust DLP, Pre-Commit Hook Security * * 주요 기능: * 1. Git Staged Diff 검사: 커밋 전 staged 상태의 코드 diff를 ValueAnchorEvaluator로 정밀 분석 * 2. 자가 치유 피드백 제공: 위반 발생 시 단순 에러 종료가 아닌 구체적인 교정 가이드 출력 * 3. 원클릭 Git Hook 설치/제거: cross-platform 호환 sh 기반 pre-commit 훅 자동 생성 * 4. 프로그래밍 방식 라이브러리 및 CLI 양용 지원 */ const { execSync } = require('child_process'); const fs = require('fs'); const path = require('path'); const valueAnchorEvaluator = require('../orchestration/value-anchor-evaluator'); /** * Git staged 상태의 변경사항을 수집하여 가치 앵커 정책을 평가합니다. * * @param {Object} [options] * @param {string} [options.cwd=process.cwd()] - 작업 디렉토리 * @returns {Object} 평가 결과 객체 { passed, hardBlocked, score, violations, feedbackPrompt } */ function evaluateStaged(options = {}) { const cwd = options.cwd || process.cwd(); // 1. Staged된 파일 목록 추출 (git diff --cached --name-only) let modifiedFiles = []; try { const filesOutput = execSync('git diff --cached --name-only', { cwd, encoding: 'utf8', timeout: 10000, maxBuffer: 10 * 1024 * 1024 }); modifiedFiles = filesOutput.split('\n').map(f => f.trim()).filter(Boolean); } catch (err) { // git 저장소가 아니거나 staged된 내용이 없는 경우 return { passed: true, hardBlocked: false, score: 100, hardViolations: [], softViolations: [], feedbackPrompt: null, message: 'Git 저장소가 아니거나 staged 변경사항이 없습니다.' }; } if (modifiedFiles.length === 0) { return { passed: true, hardBlocked: false, score: 100, hardViolations: [], softViolations: [], feedbackPrompt: null, message: 'Staged된 파일이 없습니다.' }; } // 2. Staged된 코드 전체 diff 수집 let diff = ''; let diffWarning = null; try { diff = execSync('git diff --cached', { cwd, encoding: 'utf8', timeout: 15000, maxBuffer: 15 * 1024 * 1024 // 15MB 버퍼 (대형 변경 대비) }); } catch (err) { // diff 수집 실패 시 파일 경로 기반 검사만 수행됨을 경고 diffWarning = `[경고] git diff --cached 수집 실패 (${err.message?.slice(0, 80)}). 코드 내용(시크릿 등) 검사가 생략될 수 있습니다.`; diff = ''; } // 3. ValueAnchorEvaluator 실행 const result = valueAnchorEvaluator.evaluate({ diff, modifiedFiles, commands: [] }); return { ...result, modifiedFiles, diffWarning }; } /** * .git/hooks/pre-commit 훅을 원클릭으로 설치합니다. * 크로스 플랫폼(macOS, Linux, Windows Git Bash) 호환 sh 스크립트 작성. * * @param {string} [targetGitDir] - .git 디렉토리 경로 (생략 시 자동 감지) * @returns {boolean} 성공 여부 */ function installHook(targetGitDir = null) { const gitDir = targetGitDir || path.resolve(process.cwd(), '.git'); const hooksDir = path.join(gitDir, 'hooks'); if (!fs.existsSync(hooksDir)) { fs.mkdirSync(hooksDir, { recursive: true }); } const hookPath = path.join(hooksDir, 'pre-commit'); const scriptContent = `#!/bin/sh # BADA Terminal Value Anchor & Policy Guard Pre-Commit Hook # Auto-generated by BADA policy-guard-cli # 프로젝트 루트로 이동 (git hook은 GIT_DIR 기준으로 실행될 수 있음) REPO_ROOT="$(git rev-parse --show-toplevel 2>/dev/null)" if [ -n "$REPO_ROOT" ]; then cd "$REPO_ROOT" || exit 1 fi node src/cli/policy-guard-cli.js --staged STATUS=$? if [ $STATUS -ne 0 ]; then echo "" echo "❌ [BADA-GUARD] 정책 위반으로 인해 커밋이 차단되었습니다." echo "위 가이드를 참조하여 코드를 수정한 뒤 다시 커밋하십시오." exit 1 fi exit 0 `; fs.writeFileSync(hookPath, scriptContent, { encoding: 'utf8', mode: 0o755 }); // POSIX 환경에서 실행 권한 부여 try { fs.chmodSync(hookPath, 0o755); } catch (e) { // Windows에서는 무시 } return true; } /** * .git/hooks/pre-commit 훅을 안전하게 제거합니다. * * @param {string} [targetGitDir] * @returns {boolean} */ function uninstallHook(targetGitDir = null) { const gitDir = targetGitDir || path.resolve(process.cwd(), '.git'); const hookPath = path.join(gitDir, 'hooks', 'pre-commit'); if (fs.existsSync(hookPath)) { fs.unlinkSync(hookPath); return true; } return false; } /** * CLI 메인 진입점 */ function cliMain(args = process.argv.slice(2)) { if (args.includes('--install-hook')) { const ok = installHook(); console.log(ok ? '✅ BADA Policy Guard Git Pre-Commit Hook 설치 완료!' : '❌ 설치 실패'); process.exit(ok ? 0 : 1); } if (args.includes('--uninstall-hook')) { const ok = uninstallHook(); console.log(ok ? '✅ BADA Policy Guard Git Pre-Commit Hook 제거 완료!' : 'ℹ️ 설치된 훅이 없습니다.'); process.exit(0); } if (args.includes('--staged') || args.length === 0) { console.log('🛡️ [BADA Policy Guard] Git Staged 코드 정책 검사 중...'); const result = evaluateStaged(); if (result.passed) { console.log(`✅ [BADA-GUARD PASS] 모든 보안 및 개발 정책 통과! (점수: ${result.score}/100)`); process.exit(0); } else { console.error(`\n🚨 [BADA-GUARD BLOCKED] 치명적 정책 위반이 감지되었습니다! (점수: ${result.score}/100)`); if (result.feedbackPrompt) { console.error('\n' + result.feedbackPrompt + '\n'); } process.exit(1); } } } // CLI 직접 실행 시 실행 if (require.main === module) { cliMain(); } module.exports = { evaluateStaged, installHook, uninstallHook, cliMain };