---
name: jira-task-done
description: Complete a Jira task. Generates a completion summary, transitions the issue, and posts the summary to Jira. Use when user says "done", "complete task", "finish task", "jira-task done", "작업 완료", "태스크 완료", or wants to wrap up work on a Jira issue.
user-invocable: false
argument-hint: "<TASK-ID>"
allowed-tools:
  - Read
  - Write
  - Bash
  - Glob
  - Grep
  - mcp__atlassian__jira_get_issue
  - mcp__atlassian__jira_transition_issue
  - mcp__atlassian__jira_get_transitions
  - mcp__atlassian__jira_add_comment
---

# jira-task-done: Complete a Jira Task

**Language Rule**: 프로젝트 CLAUDE.md의 Conventions 섹션 참고 (한국어 출력, Jira 코멘트 제목은 영어).

## Prerequisites
- A feature branch `feature/<TASK-ID>` must exist with commits
- Jira MCP server must be connected

## Workflow

### Step 1: Verify Context

Check for `.jira-context.json` to get the active task context.
If TASK-ID is provided as argument, use that instead.

Verify the feature branch exists:
```bash
git branch --list "feature/<TASK-ID>"
```

### Step 2: Fetch Current Issue Status

**Cache-first**: `.jira-context.json`의 `cachedIssue`를 먼저 확인 (CLAUDE.md "Issue Cache" 참고). hit이면 호출 생략하고 캐시된 `status`만 사용. miss이면 `mcp__atlassian__jira_get_issue` 호출 (`fields="summary,status,issuetype,assignee"`, `comment_limit=0`) 후 cache 갱신. **단 done 단계는 상태 전이 직전이므로 사용자가 신선도가 의심되면 cache 무시하고 재조회할 수 있음**.

### Step 3: Summarize Changes

Get the diff summary against the base branch:
```bash
git log --oneline <base-branch>..feature/<TASK-ID>
git diff --stat <base-branch>..feature/<TASK-ID>
```

### Step 4: Generate Completion Summary

git diff/log 정보와 PDCA 문서들을 기반으로 완료 요약 생성:

1. `docs/plan/<TASK-ID>.plan.md` 존재 시 기획 요약 추출
2. `docs/design/<TASK-ID>.design.md` 존재 시 설계 요약 추출
3. git log/diff로 실제 변경사항 요약

### Step 5: Post Completion Report to Jira

Step 5의 요약을 기반으로 `mcp__atlassian__jira_add_comment`에 게시:

```
## Task Completed: <TASK-ID>

**브랜치**: feature/<TASK-ID>
**커밋 수**: <count>개
**변경 파일**: <count>개 (+<추가> -<삭제>)

### Summary
- **Plan**: <기획 요약>
- **Design**: <설계 요약>
- **Changes**: <구현 변경사항 요약>

### Key Changes
<구현된 내용 간단 설명>
```

### Step 6: Transition Issue

Use `mcp__atlassian__jira_get_transitions` to fetch available transitions, then use `mcp__atlassian__jira_transition_issue` to move the issue:
- Try "In Review" first (common for PR-based workflows)
- If "In Review" is not available, try "Done"
- If both fail, inform the user of available transitions

**Important**: Do NOT pass a `comment` parameter to `jira_transition_issue`. The `comment` field requires Atlassian Document Format (ADF) JSON — passing plain text will cause an error. Add comments separately using `jira_add_comment`.

### Step 7: Cleanup MCP Config from Worktree Entry

`.jira-context.json`의 `worktreePath`를 읽어 `~/.claude.json`에서 해당 경로의 `mcpServers`를 제거한다.
entry 전체는 삭제하지 않고 `mcpServers` 키만 제거하여 Claude Code의 다른 메타데이터는 보존한다.

```bash
python - "<worktreePath from .jira-context.json>" << 'PYEOF'
import json, os, sys

worktree_path = sys.argv[1]
claude_json_path = os.path.expanduser("~/.claude.json")
with open(claude_json_path, "r", encoding="utf-8") as f:
    data = json.load(f)

def norm(p):
    return p.replace("\\", "/").rstrip("/")

wt = norm(worktree_path)
projects = data.get("projects", {})

matched_key = None
for k in list(projects.keys()):
    if norm(k) == wt:
        matched_key = k
        break

if matched_key and isinstance(projects[matched_key], dict):
    projects[matched_key].pop("mcpServers", None)
    with open(claude_json_path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    print(f"MCP config removed from {wt}")
else:
    print(f"No entry found for {wt}, skipping")
PYEOF
```

- `.jira-context.json`에 `worktreePath`가 없으면 스킵
- `~/.claude.json`에 해당 경로 entry가 없어도 스킵 (오류 아님)

### Step 8: Update Context & Completion Summary

기존 `.jira-context.json`을 읽고, 다음 필드를 업데이트하여 저장:
- `completedSteps` 배열에 `"done"` 추가 (중복 방지)
- `status`를 `"Done"`으로 변경
- `completedAt`에 현재 ISO 8601 타임스탬프 추가
- **`cachedIssue.status`도 갱신**: Step 6에서 transition한 결과 status명(예: `"완료"`, `"Done"`)으로 변경하고 `cachedIssue.fetchedAt`도 현재 시각으로 업데이트. 이게 빠지면 dashboard 같은 캐시 소비자가 stale 상태("진행 중")를 계속 보여준다 (cachedIssue가 없는 경우엔 생성하지 않고 skip).

아래 형식으로 완료 요약 출력:

```
---
✅ **Task Done** — <TASK-ID>

- Jira 상태: Done (또는 In Review)
- 완료 리포트 Jira에 게시됨
- `.jira-context.json` 업데이트됨
- 워크트리 MCP config 정리됨 (`~/.claude.json`)

**Progress**: init → start → plan → design → impl → test → review → merge → pr → **done ✓**

🎉 모든 단계가 완료되었습니다!
---
```
