# task-938.1: 작업별 토큰 사용량 추적 엔진 + 워크플로우 통합 (한정위임)

## 배경
- 제이회장님이 각 작업(task)별 토큰 사용량을 추적하여 대시보드에서 한눈에 확인하고 싶어함
- "이상하게 토큰이 많이 소모된 작업이 있는지 한눈에 보여야 해"
- 현재 task-timers.json에는 소요 시간만 기록되고 토큰 정보 없음

## ★ 핵심 발견 (아누 사전 리서치)

Claude Code 세션 JSONL 파일에 **메시지별 토큰 사용량이 기록**되어 있음:

**JSONL 위치**: `/home/jay/.claude/projects/-home-jay-workspace/<session-id>.jsonl`

**usage 필드 구조** (각 assistant 메시지에 포함):
```json
{
  "input_tokens": 10,
  "cache_creation_input_tokens": 12721,
  "cache_read_input_tokens": 18784,
  "output_tokens": 6,
  "service_tier": "standard"
}
```

**세션 ID → 태스크 매핑**:
- dispatch.py가 cokacdir --cron으로 스케줄 등록 시, cron_response에 id가 포함됨
- 세션 JSONL 파일명이 세션 ID
- task-timers.json의 task_id와 매핑 필요

## 작업 범위 (한정위임 — 끝까지 진행)

### Phase 1: 토큰 파싱 엔진 구현

**파일**: `scripts/token-tracker.py` (신규)

**기능:**
1. **JSONL 파싱**: 세션 JSONL 파일을 읽어 총 토큰 사용량 집계
   - total_input_tokens (input + cache_creation + cache_read)
   - total_output_tokens
   - total_tokens (합계)
   - message_count (총 메시지 수)
   - cache_hit_ratio (cache_read / total_input 비율)

2. **세션 → 태스크 매핑**:
   - JSONL 파일 내 첫 메시지의 content에서 task_id 패턴 매칭 (task-xxx.x)
   - 또는 task-timers.json의 시간대와 세션 시간대 매칭
   - dispatch.py가 반환하는 cron_response.id로 매칭 검토

3. **토큰 원장(ledger) 저장**: `memory/token-ledger.json`
   ```json
   {
     "tasks": {
       "task-930.1": {
         "session_id": "xxx",
         "team_id": "dev1-team",
         "input_tokens": 150000,
         "output_tokens": 45000,
         "cache_tokens": 80000,
         "total_tokens": 195000,
         "message_count": 42,
         "model": "claude-sonnet-4-6",
         "duration_seconds": 180,
         "tokens_per_second": 1083,
         "timestamp": "2026-03-25T00:30:00",
         "cost_estimate_usd": 1.23
       }
     },
     "summary": {
       "total_tokens": 5000000,
       "total_tasks": 50,
       "avg_tokens_per_task": 100000,
       "top_consumers": ["task-xxx", "task-yyy"]
     }
   }
   ```

**CLI 인터페이스:**
```
# 전체 세션 스캔하여 원장 갱신
python3 scripts/token-tracker.py scan

# 특정 태스크 토큰 확인
python3 scripts/token-tracker.py get --task task-930.1

# 요약 보고
python3 scripts/token-tracker.py summary

# 이상치 감지 (평균 대비 2배 이상 소모)
python3 scripts/token-tracker.py anomaly
```

### Phase 2: task-timer 연동

task-timers.json에 토큰 데이터 추가:
- task-timer.py의 `end` 명령 실행 시 자동으로 토큰 데이터 수집
- 또는 별도 `token-tracker.py enrich` 명령으로 기존 task-timers.json에 토큰 필드 추가

**task-timers.json 확장 스키마:**
```json
{
  "task_id": "task-930.1",
  "team_id": "dev1-team",
  "duration_seconds": 222,
  "status": "completed",
  "token_usage": {
    "input_tokens": 150000,
    "output_tokens": 45000,
    "total_tokens": 195000,
    "cost_estimate_usd": 1.23
  }
}
```

### Phase 3: 워크플로우/보고서 통합

1. **DIRECT-WORKFLOW.md 수정** (또는 QC-RULES.md):
   - 작업 완료 시 토큰 사용량 자동 기록하는 단계 추가
   - 보고서에 토큰 사용량 섹션 포함하도록 지시

2. **SCQA 보고서 템플릿 수정** (`memory/specs/scqa-report-template.md`):
   - 보고서 하단에 "토큰 사용량" 섹션 추가
   - 입력/출력/총 토큰, 비용 추정치

3. **team_prompts.py 수정** (해당되는 경우):
   - 봇 프롬프트에 토큰 보고 지시 추가

### Phase 4: 대시보드 API 엔드포인트

dashboard/server.py에 토큰 데이터 API 추가:
- `GET /api/token-usage` — 전체 토큰 원장 반환
- `GET /api/token-usage?task=task-930.1` — 특정 태스크
- `GET /api/token-anomaly` — 이상치 목록
- 기존 `/api/tasks` 응답에 token_usage 필드 추가

### Phase 5: 비용 추정 로직

모델별 토큰 비용 계산:
- claude-opus-4-6: input $15/M, output $75/M
- claude-sonnet-4-6: input $3/M, output $15/M
- claude-haiku-4-5: input $0.80/M, output $4/M
- cache_read: input 비용의 10%
- cache_creation: input 비용의 25%

### Phase 6: 테스트

```
scripts/tests/test_token_tracker.py
```
- JSONL 파싱 정확도
- 태스크 매핑 정확도
- 이상치 감지 로직
- 비용 계산 정확도
- CLI 전체 명령

## JSONL 파일 경로
- 아누 세션: `/home/jay/.claude/projects/-home-jay--cokacdir-workspace-autoset/*.jsonl`
- 봇 세션: `/home/jay/.claude/projects/-home-jay-workspace/*.jsonl`

## 기존 파일 참조
- task-timers.json: `/home/jay/workspace/memory/task-timers.json`
- task-timer.py: `/home/jay/workspace/memory/task-timer.py`
- dashboard server.py: `/home/jay/workspace/dashboard/server.py`
- DIRECT-WORKFLOW.md: `/home/jay/workspace/prompts/DIRECT-WORKFLOW.md`
- SCQA 템플릿: `/home/jay/workspace/memory/specs/scqa-report-template.md`

## 제약사항
- JSONL 파일은 읽기 전용 (Claude Code가 관리)
- task-timers.json 구조는 하위 호환 유지 (기존 필드 삭제 금지)
- 200줄/파일 제한
- dashboard/ API 엔드포인트는 추가만 (기존 API 변경 금지)
- 비용 추정치는 참고용이며 정확한 청구 금액이 아님을 명시

## 산출물
1. `scripts/token-tracker.py`
2. `scripts/tests/test_token_tracker.py`
3. `memory/token-ledger.json` (초기 스캔 결과)
4. 수정된 server.py (API 추가)
5. 수정된 SCQA 템플릿 (토큰 섹션 추가)
6. 보고서: `memory/reports/task-938.1.md`
