# 자동화 & CI/CD

Claude Code는 사람의 개입 없이 스크립트, CI/CD 파이프라인, 자동화 워크플로에서 사용할 수 있는 헤드리스 모드를 지원해요. 이 문서에서는 전체 플래그 레퍼런스와 몇 가지 실제 시나리오를 다뤄요.

---

## 1. 기본 사용법

### 단일 실행 (-p 모드)

```bash
# Basic run
claude -p "Analyse this project's architecture"

# JSON output
claude -p "List every TODO comment" --output-format json

# Cap the number of turns
claude -p "Write unit tests for UserService" --max-turns 5

# Pick a model (claude-sonnet-5-5 for everyday work; 4.x is still on sale)
claude -p "Review the code for security issues" --model claude-opus-5-5
```

### 사용 가능한 도구 제한하기

```bash
# Read-only analysis (no writes, no command execution)
claude -p "Analyse code quality" --permission-mode dontAsk --allowedTools Read,Glob,Grep

# Read and write (no command execution)
claude -p "Refactor this file" --permission-mode dontAsk --allowedTools Read,Write,Edit,Glob,Grep

# All tools (controlled environment)
claude -p "Fix the lint errors" --permission-mode dontAsk --allowedTools Read,Write,Edit,Bash,Glob,Grep
```

> `--allowedTools`는 "이 도구들은 묻지 않고 실행한다"는 뜻이며, 그 자체로는 다른 도구를 **제한하지 않아요**.
> 위 예시에서 나열한 도구만 노출되는 것은 `--permission-mode dontAsk`와 함께 쓰기 때문이에요. 이 모드는 나열되지 않은
> 모든 것을 거부해요. 다른 내장 도구를 Claude에게 아예 보이지 않게 하려면 `--tools`를 사용하세요. 예를 들어 `--tools "Read,Edit,Bash"`를 쓰면 이 세 가지 내장 도구만 제공돼요.

### 권한 모드를 명시적으로 설정하기 (기본값에 의존하지 마세요)

Claude Code 2.1.285부터, 기능 플래그를 가져올 수 없는 세션에서 `claude -p`와 Agent SDK는 **권한 모드가 설정되지 않으면 `auto`로 시작해요**.
분류기가 승인이 필요한 작업을 검토하고, 분류기 요청(모델 `claude-sonnet-5`)은 사용량에 포함돼요. `ANTHROPIC_AUTH_TOKEN`으로
QCode에 연결하면 Claude Code는 기능 플래그를 가져올 자격 증명을 받지 못해요(매 실행마다 새로 시작하는 CI 컨테이너도 마찬가지예요).
따라서 이것이 CI의 기본 동작이에요. 고정되고 재현 가능한 CI 동작을 원한다면 모드를 명시적으로 설정하세요:

```bash
# only allow-listed tools run; everything else is denied without asking
claude -p "Fix the lint errors" --permission-mode dontAsk --allowedTools "Read,Edit,Bash(npm run lint:*)"
```

QCode를 통해 auto 모드가 어떻게 동작하는지는 [기능 가용성](/docs/reference/feature-availability)을 참고하세요.

### 권한 프롬프트 건너뛰기

```bash
# Only in a safe, isolated environment!
claude -p "Fix every lint error and commit" --dangerously-skip-permissions
```

> **보안 경고**: `--dangerously-skip-permissions`는 모든 권한 확인을 건너뛰어요. **Docker 컨테이너나 격리된 CI 환경 안에서만 사용하세요.**

---

## 2. 전체 플래그 레퍼런스

### 실행 제어

| 플래그 | 기능 | 예시 |
|------|------|------|
| `-p "prompt"` | 헤드리스 모드, 단일 작업 실행 | `claude -p "analyse the architecture"` |
| `--bare` | 최소 모드, hooks/LSP/플러그인 건너뜀 | `claude --bare -p "..."` |
| `--max-turns N` | 상호작용 턴 수 제한 | `--max-turns 5` |
| `--model MODEL` | 모델 선택 | `--model claude-opus-5-5` |
| `--permission-mode MODE` | 권한 모드 설정 (`default` / `acceptEdits` / `plan` / `auto` / `dontAsk` / `bypassPermissions`) | `--permission-mode dontAsk` |
| `--dangerously-skip-permissions` | 모든 권한 확인 건너뜀 | 격리된 환경에서만 |

### 출력 형식

| 플래그 | 기능 | 사용 시점 |
|------|------|---------|
| `--output-format text` | 일반 텍스트 (기본값) | 사람이 읽을 때 |
| `--output-format json` | 구조화된 JSON | 스크립트용 |
| `--output-format stream-json` | 스트리밍 JSON | 실시간 처리 |

### 도구 제한

| 플래그 | 기능 |
|------|------|
| `--allowedTools Tool1,Tool2` | 사전 승인: 나열한 도구는 묻지 않고 실행 (다른 도구는 제한되지 않음) |
| `--permission-mode dontAsk` | 사전 승인되지 않은 것은 묻지 않고 거부. `--allowedTools`와 함께 쓰면 허용 목록으로 동작 |
| `--tools Tool1,Tool2` | Claude에게 나열한 내장 도구만 제공 (실질적 제한) |
| `--disallowedTools Tool1` | 사용 가능한 도구에서 나열한 도구 제거 |

**사용 가능한 도구 이름**: `Read`, `Write`, `Edit`, `Bash`, `Glob`, `Grep`, `WebFetch`, `WebSearch`, `Agent`, `NotebookEdit`

### 세션 관리

| 플래그 | 기능 |
|------|------|
| `--session-id ID` | 세션 id 설정 |
| `--resume` | 이전 세션 재개 |

### 환경 변수

| 변수 | 기능 |
|------|------|
| `ANTHROPIC_BASE_URL` | API 엔드포인트 (QCode.cc: `https://api.qcode.cc/api`) |
| `ANTHROPIC_AUTH_TOKEN` | API 키 (`cr_`로 시작) |
| `CLAUDE_CODE_MAX_TURNS` | 기본 최대 턴 수 |
| `CLAUDE_CODE_OUTPUT_FORMAT` | 기본 출력 형식 |
| `CLAUDE_MODEL` | 기본 모델 |

---

## 3. CI/CD 레시피

### 레시피 1: GitHub Actions — AI 코드 리뷰

```yaml
name: AI Code Review
on: [pull_request]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # full history, needed for the diff

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: AI Code Review
        env:
          ANTHROPIC_BASE_URL: "https://api.qcode.cc/api"
          ANTHROPIC_AUTH_TOKEN: ${{ secrets.QCODE_API_KEY }}
        run: |
          # Collect the files changed in this PR
          FILES=$(git diff --name-only origin/${{ github.base_ref }}...HEAD)

          claude -p "Review the code changes in the following files, focusing on:
          1. Security vulnerabilities (SQL injection, XSS, leaked secrets)
          2. Performance problems (N+1 queries, memory leaks)
          3. Logic errors
          4. Code style issues

          Changed files:
          $FILES" \
            --output-format json \
            --max-turns 3 \
            --model claude-sonnet-5-5 \
            --permission-mode dontAsk \
            --allowedTools Read,Glob,Grep \
            > review.json

          echo "Review completed"
          cat review.json | jq -r '.result' || cat review.json
```

### 레시피 2: 테스트 자동 생성

```yaml
name: Auto Generate Tests
on:
  push:
    paths: ['src/**/*.ts', '!src/**/*.test.ts']

jobs:
  generate-tests:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '22'

      - name: Install dependencies
        run: |
          npm ci
          npm install -g @anthropic-ai/claude-code

      - name: Generate missing tests
        env:
          ANTHROPIC_BASE_URL: "https://api.qcode.cc/api"
          ANTHROPIC_AUTH_TOKEN: ${{ secrets.QCODE_API_KEY }}
        run: |
          claude -p "Look at the .ts files under src/ and write unit tests for the ones that have none.
          Use Vitest + Testing Library.
          Name test files xxx.test.ts and put them next to the source file.
          Target 80%+ coverage." \
            --max-turns 10 \
            --permission-mode dontAsk \
            --allowedTools Read,Write,Glob,Grep,Bash

      - name: Run tests
        run: npx vitest --run

      - name: Create PR with tests
        if: success()
        run: |
          git config user.name "claude-bot"
          git config user.email "bot@qcode.cc"
          git checkout -b auto-tests-$(date +%s)
          git add '*.test.ts'
          git commit -m "test: auto-generated unit tests" || exit 0
          git push origin HEAD
```

> **보안 참고**: 이 레시피는 에이전트에게 제한 없는 `Bash`를 주고 자동으로 푸시해요. 따라서 에이전트가 접근할 수 있는 것은 무엇이든 푸시할 수 있어요. 허용 도구를 제한하고(예: 작업에 필요한 명령만 담아 `--allowedTools` 추가) 푸시 전에 diff를 검토하세요.

### 레시피 3: 코드 품질 게이트

```yaml
name: Code Quality Gate
on: [pull_request]

jobs:
  quality:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: '22'

      - run: npm install -g @anthropic-ai/claude-code

      - name: Quality Analysis
        env:
          ANTHROPIC_BASE_URL: "https://api.qcode.cc/api"
          ANTHROPIC_AUTH_TOKEN: ${{ secrets.QCODE_API_KEY }}
        run: |
          claude -p "Analyse code quality and output JSON:
          {
            \"score\": 0-100,
            \"issues\": [{\"severity\": \"high|medium|low\", \"file\": \"...\", \"description\": \"...\"}],
            \"summary\": \"one-line summary\"
          }

          Scoring:
          - Type safety (20 points)
          - Error handling (20 points)
          - Test coverage (20 points)
          - Readability (20 points)
          - Security (20 points)" \
            --output-format json \
            --max-turns 3 \
            --model claude-sonnet-5-5 \
            --permission-mode dontAsk \
            --allowedTools Read,Glob,Grep \
            > quality.json

      - name: Check score
        run: |
          SCORE=$(cat quality.json | jq -r '.result' | jq -r '.score // 0')
          echo "Quality score: $SCORE"
          if [ "$SCORE" -lt 60 ]; then
            echo "Quality gate failed: score $SCORE < 60"
            exit 1
          fi
```

### 레시피 4: 체인지로그 생성

```bash
#!/bin/bash
# generate-changelog.sh — build a changelog from git commits

export ANTHROPIC_BASE_URL="https://api.qcode.cc/api"
# ANTHROPIC_AUTH_TOKEN comes from your environment or CI secret

# Commits since the last tag
LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
if [ -z "$LAST_TAG" ]; then
  COMMITS=$(git log --oneline -20)
else
  COMMITS=$(git log --oneline ${LAST_TAG}..HEAD)
fi

claude -p "Produce a structured changelog from these git commits:

$COMMITS

Format:
## [version] - $(date +%Y-%m-%d)
### Added
### Fixed
### Changed
### Breaking changes (if any)

Write in English, concise and professional." \
  --output-format text \
  --max-turns 2 \
  --model claude-sonnet-5-5 \
  --permission-mode dontAsk \
  --allowedTools Read,Glob,Grep
```

### 레시피 5: 문서 최신 상태 유지

```bash
#!/bin/bash
# update-docs.sh — refresh the API docs after code changes

export ANTHROPIC_BASE_URL="https://api.qcode.cc/api"
# ANTHROPIC_AUTH_TOKEN comes from your environment or CI secret

claude -p "Look at the route files under src/api/ and compare them with the documentation in docs/api.md.
Find API descriptions that are missing or out of date and update docs/api.md.
Keep the existing document format and style." \
  --max-turns 8 \
  --permission-mode dontAsk \
  --allowedTools Read,Write,Edit,Glob,Grep
```

---

## 4. Docker 격리

CI/CD에서 `--dangerously-skip-permissions`를 사용할 때는 Docker 컨테이너 안에서 실행하는 것을 강력히 권장해요:

```dockerfile
FROM node:22-slim

# Install Claude Code
RUN npm install -g @anthropic-ai/claude-code

# Install project dependencies
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .

# QCode.cc environment
ENV ANTHROPIC_BASE_URL=https://api.qcode.cc/api
# ANTHROPIC_AUTH_TOKEN is injected at runtime

# Run as a non-root user
RUN useradd -m claude
USER claude

CMD ["claude", "-p", "Run a code review", "--dangerously-skip-permissions", "--max-turns", "5"]
```

실행은 이렇게 해요:

```bash
docker build -t claude-ci .
docker run --rm -e ANTHROPIC_AUTH_TOKEN="$ANTHROPIC_AUTH_TOKEN" claude-ci
```

---

## 5. 세션 재개와 다단계 파이프라인

### 다단계 작업

```bash
# Step 1: analyse
claude -p "Analyse the project architecture" \
  --session-id "pipeline-42" \
  --output-format json \
  --max-turns 3 \
  --permission-mode dontAsk \
  --allowedTools Read,Glob,Grep

# Step 2: build a plan from that analysis
claude -p "Based on the previous analysis, draft a refactoring plan" \
  --resume --session-id "pipeline-42" \
  --max-turns 3

# Step 3: execute the plan
claude -p "Carry out the first step of the refactoring plan" \
  --resume --session-id "pipeline-42" \
  --max-turns 10 \
  --permission-mode dontAsk \
  --allowedTools Read,Write,Edit,Bash,Glob,Grep
```

---

## 6. 비용 제어

### 전략 1: 턴 수 제한

```bash
# Three turns is enough for a simple task
claude -p "Quick analysis" --max-turns 3

# Ten at most for a complex one
claude -p "Full refactor" --max-turns 10
```

### 전략 2: 알맞은 모델 선택

| 시나리오 | 권장 | 이유 |
|------|---------|------|
| 코드 리뷰 | Sonnet | 충분히 좋고 저렴해요 |
| 보안 스캔 | Opus | 깊은 분석이 필요해요 |
| 대량 포매팅 | Haiku | 가장 저렴해요 |
| 테스트 생성 | Sonnet | 가성비가 가장 좋아요 |

```bash
claude -p "Format the code" --model claude-haiku-5-5 --max-turns 3
```

### 전략 3: 도구 제한으로 토큰 사용량 절감

```bash
# Read-only analysis → no repeated write/test cycles to pay for
claude -p "Analyse the code" --permission-mode dontAsk --allowedTools Read,Glob,Grep --max-turns 3
```

---

## 7. Codex Headless와 비교

| | Claude Code -p | Codex headless |
|------|---------------|----------------|
| 플래그 | `-p "prompt"` | `codex -q "prompt"` |
| 샌드박스 | Docker 격리 필요 | 커널 수준 샌드박스 내장 |
| 출력 형식 | text/json/stream-json | text/json |
| 세션 재개 | `--resume --session-id` | 지원하지 않음 |
| 도구 제한 | `--tools` / `--permission-mode dontAsk` + `--allowedTools` | `--approval-mode` |
| 병렬 실행 | 지원하지 않음 | `codex cloud exec` |

**함께 사용하기**: Claude Code는 분석과 계획(읽기 전용)에, Codex는 실행(완전 자동)에 사용하세요.

> QCode.cc 플랜은 한도를 공유하므로, CI에서 두 도구를 오가도 비용이 들지 않아요.

---

## 8. 모범 사례 체크리스트

1. **항상 턴 수를 제한하세요**: CI에서는 `--max-turns`로 폭주 실행을 막아요
2. **도구를 제한하세요**: `--permission-mode dontAsk` + `--allowedTools`로 작업에 필요한 도구만 허용하세요 (또는 `--tools`로 사용 가능한 도구를 제한하세요)
3. **Docker로 격리하세요**: `--dangerously-skip-permissions`는 반드시 컨테이너에서 실행해야 해요
4. **JSON 출력**: 자동화에서는 `--output-format json`을 선호하면 결과를 파싱하기 쉬워요
5. **비용 제어**: 분석에는 Sonnet, 단순한 작업에는 Haiku를 사용하세요
6. **멱등성**: 반복 실행에 부작용이 없도록 하세요
7. **타임아웃**: 파이프라인에 작업 타임아웃을 설정하세요 (예: 10분)
8. **시크릿 관리**: API 키는 CI 시크릿에 보관하고 절대 하드코딩하지 마세요

---

## 다음 단계

- [Hooks 시스템](/docs/advanced/hooks) — 동작을 자동으로 트리거
- [CLI 팁](/docs/usage/cli-tips) — 더 많은 명령줄 사용법
- [비용 최적화](/docs/usage/cost-optimization) — 지출을 제어하는 기법
- [Claude Code 완전 튜토리얼](/docs/getting-started/claude-code-tutorial) — 처음부터 능숙하게