ai-rules handbook ai-governance → ai-rules 통합 계획

ai-governance → ai-rules 통합 계획

`d:/dev/ai-governance`를 `ai-rules` sync 시스템에 통합하여 모든 프로젝트에 배포 가능하게 만들기

guide 2026-04-01 docs/guide/GOVERNANCE_INTEGRATION_PLAN.md

작성일: 2026-04-01
목적: d:/dev/ai-governanceai-rules sync 시스템에 통합하여 모든 프로젝트에 배포 가능하게 만들기
관련 분석: AI_RULES_IMPROVEMENT_ANALYSIS.md


핵심 목표

"모델이 바뀌어도 코드는 안 건드린다. sync 한 번으로 모든 프로젝트에 배포된다."


현재 상태

d:/dev/
  ai-governance/          ← 독립 프레임워크, AITEM에만 수동 연결
    orchestrator/         ← Claude Worker + GPT-4o Leader 하드코딩
    scripts/
    templates/
  ai-rules/               ← sync 시스템 (profile → 모든 프로젝트 배포)
    core/, extensions/    ← rule 블록
    agents/               ← agent 정의
    adapters/             ← claude-code, cursor, windsurf 등
    profiles/             ← aitem.yaml, global.yaml 등
    scripts/sync.mjs      ← 메인 sync 스크립트
  AITEM/
    .ai-governance/       ← 수동 복사된 config, agents.yaml 등

문제:

  • ai-governance가 AITEM에만 묶여 있음
  • 모델 변경 시 각 프로젝트 config.yaml 직접 수정 필요
  • ai-governance 개선사항을 각 프로젝트에 수동 배포해야 함

통합 후 구조

ai-rules/
  governance/                        ← ai-governance 소스 이동
    orchestrator/                    ← Provider-Agnostic으로 리팩터링
      llm-client.mjs                 ← Anthropic + OpenAI + Google (config-driven)
      round-1-independent.mjs
      round-2-cross-check.mjs        ← 다른 모델 독립 검증으로 개선
      round-3-consensus.mjs
      confidence-calculator.mjs
      deadlock-handler.mjs
      context-collector.mjs
    scripts/
      cross-verify.mjs               ← npm run verify 단축 진입점
      gate-health-check.mjs          ← API 키 + 모델 가용성 체크 (신규)
      eval-runner.mjs                ← 리포트 히스토리 비교 (신규)
    templates/
      .ai-governance/
        agents.yaml                  ← 기본 에이전트 정의
        thresholds.yaml              ← 기본 임계값
  
  governance-presets/               ← 프로젝트 타입별 governance 설정
    solo.yaml                        ← 1인 개발 (Round 1만)
    team.yaml                        ← 팀 개발 (Round 1~3 full)
    saas.yaml                        ← SaaS 서비스 (결제/인증 임계값 강화)
  
  adapters/
    claude-code.mjs                  ← 기존
    governance.mjs                   ← 신규: .ai-governance/ 파일 생성 담당
  
  profiles/
    aitem.yaml                       ← governance 설정 추가
    ai-saas-main.yaml               ← governance 설정 추가
    global.yaml                      ← 변경 없음 (governance는 프로젝트별)

sync 실행 후 각 프로젝트에 생성되는 파일:

{project}/
  .ai-governance/
    config.yaml          ← profile의 governance 설정으로 자동 생성
    agents.yaml          ← 공통 기본값 + 프로젝트 오버라이드
    thresholds.yaml      ← preset 기본값 + 프로젝트 오버라이드
  scripts/
    cross-verify.mjs     ← ai-rules/governance/scripts/ 심볼릭/복사
  package.json           ← "verify" 스크립트 자동 추가 (merge)

Phase 1 — ai-governance 소스 이전 + Provider-Agnostic 리팩터링

우선순위 최고. 이것만 해도 "모델 교체 = yaml 수정"이 달성됨.

1-1. governance/ 디렉토리 생성 및 소스 이전

# PowerShell 예시
# ai-rules에 governance/ 디렉토리 생성
New-Item -ItemType Directory -Force -Path "D:/dev/ai-rules/governance/orchestrator"
New-Item -ItemType Directory -Force -Path "D:/dev/ai-rules/governance/scripts"
New-Item -ItemType Directory -Force -Path "D:/dev/ai-rules/governance/templates/.ai-governance"

# ai-governance 소스 복사 (원본 유지)
Copy-Item "D:/dev/ai-governance/orchestrator/*" "D:/dev/ai-rules/governance/orchestrator/" -Recurse -Force
Copy-Item "D:/dev/ai-governance/scripts/*" "D:/dev/ai-rules/governance/scripts/" -Recurse -Force
Copy-Item "D:/dev/ai-governance/templates/*" "D:/dev/ai-rules/governance/templates/" -Recurse -Force
Copy-Item "D:/dev/ai-governance/schemas" "D:/dev/ai-rules/governance/" -Recurse -Force

1-2. llm-client.mjs — Provider-Agnostic 리팩터링

핵심 변경: createWorkerClient() / createLeaderClient() 제거
createVerifierClients(config) / createJudgeClient(config, releaseMode) 로 교체

// 변경 전 (하드코딩)
export function createWorkerClient(crossVerConfig) {
  const model = crossVerConfig?.worker?.model ?? 'claude-sonnet-4-20250514'
  return createLlmClient({ provider: 'anthropic', model })
}

export function createLeaderClient(crossVerConfig) {
  // GPT-4o 하드코딩, fallback Claude Opus 하드코딩
}

// 변경 후 (config-driven)
export function createVerifierClients(crossVerConfig) {
  const verifiers = crossVerConfig?.verifiers ?? [
    { id: 'claude-worker', provider: 'anthropic', model: 'claude-sonnet-4-6',
      agents: ['structure', 'convention', 'domain'] }
  ]
  return verifiers.map(v => ({
    id: v.id,
    agents: v.agents,
    client: createLlmClient({ provider: v.provider, model: v.model }),
  }))
}

export function createJudgeClient(crossVerConfig, releaseMode) {
  const judgeConf = releaseMode === 'SAFE'
    ? (crossVerConfig?.judge?.safe_mode_override ?? crossVerConfig?.judge?.primary)
    : crossVerConfig?.judge?.primary ?? { provider: 'openai', model: 'gpt-4o' }
  const fallbackConf = crossVerConfig?.judge?.fallback
    ?? { provider: 'anthropic', model: 'claude-opus-4-6' }
  try {
    return { ...createLlmClient(judgeConf), degraded: false }
  } catch {
    console.warn(`⚠️  ${judgeConf.provider} 키 없음. fallback: ${fallbackConf.model}`)
    return { ...createLlmClient(fallbackConf), degraded: true }
  }
}

// Gemini 추가 시 이것만 추가
function geminiProvider(model) { ... }

export function createLlmClient({ provider, model }) {
  switch (provider) {
    case 'anthropic': return anthropicProvider(model)
    case 'openai':    return openaiProvider(model)
    case 'google':    return geminiProvider(model)  // ← 한 줄 추가로 끝
    default: throw new Error(`지원하지 않는 provider: ${provider}`)
  }
}

1-3. config.yaml 구조 변경

# 변경 전 (templates/.ai-governance/config.yaml)
cross_verification:
  enabled: false
  rounds: 1

# 변경 후
cross_verification:
  enabled: true
  
  verifiers:
    - id: claude-worker
      provider: anthropic
      model: claude-sonnet-4-6          # ← 버전 관리 여기서만
      agents: [structure, convention, domain]
    # 다중 검증 시 추가 (Round 2에 다른 모델 투입)
    # - id: gpt-worker
    #   provider: openai
    #   model: gpt-4o-mini
    #   agents: [domain]                # 비즈니스 로직만 집중
  
  judge:
    primary:
      provider: openai
      model: gpt-4o
    fallback:
      provider: anthropic
      model: claude-opus-4-6
    safe_mode_override:                 # SAFE 모드일 때 더 강력한 모델
      provider: anthropic
      model: claude-opus-4-6

1-4. Round 2 개선 — 진짜 다른 모델 독립 검증

현재 Round 2:
  Claude × 3가 서로의 결과를 교차 지적 → 같은 모델이라 의미 약함

개선 Round 2:
  verifiers에 2개 이상 정의된 경우:
    → verifier-B(GPT-4o-mini)가 verifier-A(Claude) 결과 독립 검증
    → 진짜 다른 모델 관점 확보
  
  verifiers가 1개인 경우:
    → 기존 3에이전트 교차 지적 유지 (현재와 동일)

Phase 2 — governance adapter + profile 통합

sync 시스템에 연결. node scripts/sync.mjs --apply로 모든 프로젝트에 배포.

2-1. adapters/governance.mjs 신규 생성

sync.mjs가 호출하는 adapter. profile의 governance 설정을 읽어서 .ai-governance/ 파일들을 생성.

// adapters/governance.mjs
export function generate(governanceConfig, profile) {
  if (!governanceConfig?.enabled) return []

  const preset = governanceConfig.preset ?? 'solo'

  return [
    {
      path: '.ai-governance/config.yaml',
      content: buildConfigYaml(preset, governanceConfig, timestamp, profile),
    },
    {
      path: '.ai-governance/agents.yaml',
      content: readAgentsTemplate(),
    },
    {
      path: '.ai-governance/thresholds.yaml',
      content: buildThresholdsYaml(
        preset,
        timestamp,
        governanceConfig.overrides?.thresholds ?? governanceConfig.thresholds
      ),
    },
  ]
}

2-2. profile에 governance 블록 추가

# profiles/aitem.yaml 추가
governance:
  enabled: true
  preset: saas                    # solo | team | saas
  overrides:
    cross_verification:
      verifiers:
        - id: claude-worker
          provider: anthropic
          model: claude-sonnet-4-6
          agents: [structure, convention, domain]
        - id: gpt-reviewer        # AITEM은 다중 검증 활성화
          provider: openai
          model: gpt-4o-mini
          agents: [domain]
      judge:
        provider: openai
        model: gpt-4o
        fallback_provider: anthropic
        fallback_model: claude-opus-4-6
    thresholds:
      payment: 92                 # AITEM 결제 임계값 더 엄격하게
      auth: 88

# profiles/ai-saas-main.yaml 추가
governance:
  enabled: true
  preset: solo                    # 혼자 개발 → Round 1만
  # overrides 없음 → preset 기본값 그대로

2-3. governance-presets/ 파일

# governance-presets/solo.yaml
# 1인 개발, 빠른 피드백 중심
cross_verification:
  rounds: 1                       # Round 1만 (Claude 독립 분석)
  verifiers:
    - id: claude-worker
      provider: anthropic
      model: claude-sonnet-4-6
      agents: [structure, convention, domain]
  judge: null                     # Judge 없음 (비용 절감)
  budget:
    max_cost_usd: 0.10

# governance-presets/team.yaml
# 팀 개발, 전체 3라운드
cross_verification:
  rounds: 3
  verifiers:
    - id: claude-worker
      provider: anthropic
      model: claude-sonnet-4-6
      agents: [structure, convention, domain]
  judge:
    primary: { provider: openai, model: gpt-4o }
    fallback: { provider: anthropic, model: claude-opus-4-6 }
  budget:
    max_cost_usd: 0.50

# governance-presets/saas.yaml
# SaaS 서비스, 결제/인증 강화
cross_verification:
  rounds: 3
  verifiers:
    - id: claude-worker
      provider: anthropic
      model: claude-sonnet-4-6
      agents: [structure, convention, domain]
    - id: gpt-worker              # 다중 검증
      provider: openai
      model: gpt-4o-mini
      agents: [domain]
  judge:
    primary: { provider: openai, model: gpt-4o }
    fallback: { provider: anthropic, model: claude-opus-4-6 }
    safe_mode_override: { provider: anthropic, model: claude-opus-4-6 }
  budget:
    max_cost_usd: 1.00
thresholds:
  payment: 90
  auth: 85
  personal_data: 88

2-4. sync.mjs 수정 — governance adapter 호출 추가

// sync.mjs 기존 흐름에 추가 (4.9 governance 파일 생성)
import * as governanceAdapter from '../adapters/governance.mjs'

// main() 내부
const govFiles = governanceAdapter.generate(profile.governance, profile)
outputFiles.push(...govFiles.map(f => ({ ...f, tool: 'governance' })))

Phase 3 — 누락 스크립트 구현 + 실행 편의성

3-1. 누락 스크립트 3개 구현

gate-health-check.mjs — API 키 + 모델 가용성 체크

node scripts/gate-health-check.mjs --target D:/dev/AITEM

출력:
   ANTHROPIC_API_KEY: 설정됨
   OPENAI_API_KEY: 설정됨
   claude-sonnet-4-6: 응답 정상 (latency: 1.2s)
   gpt-4o: 응답 정상 (latency: 0.8s)
  예상 비용/회: ~$0.15

eval-runner.mjs — 리포트 히스토리 비교

node scripts/eval-runner.mjs --target D:/dev/AITEM

출력:
  최근 5회 결과:
  2026-03-01  CONDITIONAL  overall:83  $0.10  38s
  2026-03-15  PASS         overall:91  $0.12  41s
  2026-03-28  PASS         overall:88  $0.09  35s
  
  트렌드: ↑ business_logic 64→78, ↓ naming 50→45 (주의)

cross-verify.mjs — 실행 편의 단축 진입점

# 현재 — 번거로움 (PowerShell 예시)
New-Item -ItemType Directory -Force -Path ".tmp" | Out-Null
git diff HEAD~1 | Out-File -Encoding utf8 ".tmp/changes.diff"
node D:/dev/ai-rules/governance/orchestrator/index.mjs --target D:/dev/AITEM --diff ".tmp/changes.diff"

# 개선 후 — 프로젝트 내에서 바로
npm run verify                    # 마지막 커밋 자동 diff
npm run verify -- --pr 123        # PR diff 자동 fetch
npm run verify -- --staged        # staged 변경사항만
npm run verify -- --rounds 1      # 빠른 검증 (Round 1만)

3-2. Markdown 리포트 자동 생성

JSON 저장과 함께 .ai-governance/reports/YYYY-MM-DD_HHmmss.md 자동 생성.

# 교차 검증 결과 — 2026-04-01 14:05

**판정: CONDITIONAL** | Worker: claude-sonnet-4-6 | Judge: gpt-4o | $0.12 | 38s

## 핵심 발견 (warning 이상)

| ID | 파일 | 심각도 | 내용 | 합의 |
|----|------|--------|------|------|
| DOM-002 | src/pages/Pricing.tsx | ⚠️ warning | 로그인 후 결제 재개 로직 제거 | 2/3 동의 |
| CON-001 | src/pages/Pricing.tsx | ⚠️ warning | 에러 피드백 없음 | 2/3 동의 |

## 조건부 통과 조건
1. src/pages/Pricing.tsx에 사용자 에러 피드백 추가
2. 로그인 후 결제 재개 로직 재구현 또는 안내 메시지 추가

## Confidence Score
| 도메인 | 점수 | 임계값 | 결과 |
|--------|------|--------|------|
| business_logic | 64 | 75 |  |
| error_handling | 79 | 70 |  |
| dependencies | 100 | 70 |  |

Phase 4 — 모델 확장 (Gemini 등)

Phase 1~3 완료 후. config만 바꾸면 즉시 전환 가능한 구조가 이미 완성된 상태.

// governance/orchestrator/llm-client.mjs에 추가
function geminiProvider(model) {
  const apiKey = process.env.GOOGLE_API_KEY
  if (!apiKey) throw new Error('GOOGLE_API_KEY 미설정')
  // Google Gemini API 호출 구현
}

// createLlmClient()에 case 추가
case 'google': return geminiProvider(model)
# profiles/aitem.yaml governance.overrides에서 바로 전환
verifiers:
  - id: gemini-worker             # Claude → Gemini 전환
    provider: google
    model: gemini-2.0-flash
    agents: [domain]

실행 체크리스트

Phase 1 (이번 작업)

  • ai-rules/governance/ 디렉토리 생성
  • ai-governance/ 소스 → ai-rules/governance/ 복사
  • governance/orchestrator/llm-client.mjs Provider-Agnostic 리팩터링
  • governance/templates/.ai-governance/config.yaml verifiers/judge 구조로 변경
  • governance/orchestrator/index.mjs createVerifierClients/createJudgeClient 사용으로 업데이트
  • 기존 모델 버전 최신화 (claude-sonnet-4-20250514claude-sonnet-4-6)
  • AITEM에서 테스트 실행 확인

Phase 2 (다음 작업)

  • governance-presets/ 디렉토리 + solo.yaml, team.yaml, saas.yaml 생성
  • adapters/governance.mjs 신규 생성
  • scripts/sync.mjs governance adapter 호출 추가
  • profiles/aitem.yaml governance 블록 추가
  • profiles/ai-saas-main.yaml governance 블록 추가
  • node scripts/sync.mjs --apply --project aitem 테스트

Phase 3 (그 다음)

  • governance/scripts/gate-health-check.mjs 구현
  • governance/scripts/eval-runner.mjs 구현
  • governance/scripts/cross-verify.mjs 단축 진입점 구현
  • Markdown 리포트 자동 생성 추가
  • package.json verify 스크립트 자동 주입 구현

Phase 4 (모델 확장 시)

  • geminiProvider() 구현
  • createLlmClient() google case 추가
  • 테스트 후 config.yaml에서 전환

브랜치 전략

feature/260401-governance-integration
  ├─ commit: governance/ 소스 이전
  ├─ commit: llm-client provider-agnostic 리팩터링
  ├─ commit: config.yaml verifiers/judge 구조 변경
  └─ commit: AITEM 테스트 통과 확인

→ PR → develop 병합 후

feature/260401-governance-sync-adapter
  ├─ commit: governance-presets/ 추가
  ├─ commit: adapters/governance.mjs 신규
  ├─ commit: sync.mjs governance 연동
  └─ commit: profiles aitem/ai-saas-main governance 블록 추가