# 작업: 집단지성 채팅 코드 읽기 모드 구현

## 개요
집단지성 채팅(3봇: Gemini/Codex/Claude)에서 자연어로 코드 분석이 필요한 메시지를 감지하고,
Claude를 1번으로 지정하여 파일을 읽은 뒤 다른 봇들과 토론하는 기능 구현.

## 수정 대상 파일
1. `/home/jay/workspace/services/multimodel-bot/discussion_manager.py`
2. `/home/jay/workspace/services/multimodel-bot/engine.py`
3. `/home/jay/workspace/services/multimodel-bot/main_bot.py` (필요시)

## 구현 상세

### 1. discussion_manager.py — 코드 분석 감지 + Claude 우선 로직

#### 1-1. 키워드 감지 함수 추가
```python
CODE_ANALYSIS_KEYWORDS = [
    "코드", "파일", "소스", "함수", "클래스", "컴포넌트", "구현", "로직",
    "아키텍처", "구조", "읽어", "분석해", "소스코드", "디렉토리", "모듈",
    "라이브러리", "패키지", "import", "설정파일", "config",
    "code", "file", "source", "function", "class", "architecture",
    "structure", "analyze", "implementation", "directory"
]

def detect_code_analysis(message_text: str) -> bool:
    """유저 메시지에서 코드 분석 필요 여부를 감지."""
    text_lower = message_text.lower()
    # 키워드 2개 이상 매칭 OR 프로젝트 경로 언급
    keyword_count = sum(1 for kw in CODE_ANALYSIS_KEYWORDS if kw in text_lower)
    has_path = bool(re.search(r'(/home/|\.py|\.js|\.ts|\.tsx|\.json|\.md)', text_lower))
    return keyword_count >= 2 or has_path
```

#### 1-2. on_user_message() 수정
- `detect_code_analysis()` 결과가 True면:
  - `state.code_analysis_mode = True` 플래그 설정
  - `state.current_turn = "claude_view_bot"` (Claude 강제 1번)
  - `_start_index`는 변경하지 않음 (다음 일반 토론에는 영향 없음)
- False면 기존 라운드 로빈 유지

#### 1-3. DiscussionState에 필드 추가
```python
@dataclass
class DiscussionState:
    ...
    code_analysis_mode: bool = False  # 코드 분석 모드 활성 여부
```

#### 1-4. is_code_analysis_mode() 공개 메서드 추가
```python
def is_code_analysis_mode(self, chat_id: int) -> bool:
    """해당 채팅이 코드 분석 모드인지 반환."""
    state = self._states.get(chat_id)
    return state.code_analysis_mode if state else False
```

### 2. engine.py — call_claude()에 allowedTools 파라미터 추가

#### 현재 코드 (line 196):
```python
cmd = ["/home/jay/.local/bin/claude", "-p", prompt, "--output-format", "text", "--model", "sonnet"]
```

#### 변경:
```python
async def call_claude(prompt: str, timeout: int = 180, code_analysis: bool = False) -> str:
    cmd = ["/home/jay/.local/bin/claude", "-p", prompt, "--output-format", "text", "--model", "sonnet"]
    if code_analysis:
        cmd.extend(["--allowedTools", "Read,Grep,Glob"])
    ...
```

- `code_analysis=True`면 `--allowedTools Read,Grep,Glob` 추가
- Claude가 파일 시스템에 접근하여 코드를 읽을 수 있게 됨
- cwd를 `/tmp` → `/home/jay/workspace`로 변경 (code_analysis 모드에서만)

### 3. main_bot.py — Claude 봇 응답 시 code_analysis 플래그 전달

#### Claude 봇의 응답 생성 부분에서:
- `discussion_manager.is_code_analysis_mode(chat_id)` 체크
- True면 `call_claude(prompt, code_analysis=True)` 호출
- Claude의 첫 응답에 코드 내용이 포함되면, 이후 봇들은 그 컨텍스트로 토론
- code_analysis_mode는 해당 토론의 첫 턴(Claude)에서만 적용, 이후 턴은 일반 모드

### 4. 프롬프트 보강
Claude가 코드 분석 모드일 때, 프롬프트 앞에 다음 지시를 추가:
```
[코드 분석 모드] 사용자가 코드/파일 분석을 요청했습니다.
Read, Grep, Glob 도구를 사용하여 관련 파일을 읽고 분석하세요.
분석 결과를 다른 참여자(잼민이, 코덱스)가 이해할 수 있도록 핵심 내용을 정리하여 공유하세요.
프로젝트 경로: /home/jay/workspace/ (시스템), /home/jay/projects/ (프로젝트)
```

## 테스트 방법
1. 집단지성 채팅에서 "인슈위키 코드 구조를 분석해줘" 입력
2. Claude가 1번으로 응답하고 파일을 읽어서 분석 결과 공유
3. 잼민이(Gemini), 코덱스(GPT)가 해당 분석 기반으로 토론
4. 일반 대화("오늘 날씨 어때?")에서는 기존 라운드 로빈 유지 확인

## 주의사항
- `--allowedTools`에 Edit, Write 등 쓰기 도구는 **절대 포함 금지** (읽기 전용)
- code_analysis 모드에서도 timeout은 180초 유지
- 기존 라운드 로빈 `_start_index` 회전 로직은 건드리지 않음
- 봇 재시작 필요 (완료 후 보고서에 명시)