Przejdź do głównej zawartości

Integracja CI/CD i automatyzacja

Twój zespół scala 30 PR-ów tygodniowo i każdy z nich czeka godzinami na pierwszy przegląd wykonany przez człowieka. Niestabilne testy dostają zielone światło na pieczątkę, regresja bezpieczeństwa przemyka niezauważona, a nocna dokumentacja coraz bardziej rozjeżdża się z kodem. Nie potrzebujesz więcej recenzentów - potrzebujesz zautomatyzowanego pierwszego przejścia, które uruchamia się przy każdym PR, oraz sposobu na sterowanie Claude Code z wnętrza potoku.

To właśnie tutaj Claude Code przestaje być narzędziem interaktywnym i staje się częścią Twojego CI/CD. Dzięki akcji GitHub anthropics/claude-code-action@v1 i trybowi headless (claude -p) możesz wpleść AI w zdarzenia, na które i tak już reagujesz: komentarze, etykiety, nieudane buildy i harmonogramy cron.

  • Działający przepływ @claude, który reaguje na komentarze do PR-ów i zgłoszeń
  • Zadanie przeglądu PR przez AI, uruchamiane przy każdym pull requeście za pomocą wbudowanego polecenia /review
  • Zadanie automatycznej naprawy CI, które czyta logi błędów i wypycha poprawkę
  • Nocny aktualizator dokumentacji, który otwiera PR ze zmianami
  • Wyzwalacz z bramką kosztową, który wywołuje Claude tylko przy istotnych zmianach
  • Gotowe do wklejenia prompty dla najbardziej wartościowych automatyzacji CI

Najszybszy sposób na włączenie integracji z GitHub:

  1. Uruchom REPL i wykonaj instalator. Uruchom claude, aby otworzyć interaktywny REPL, a następnie wpisz polecenie ukośnikowe /install-github-app. Przeprowadzi Cię ono przez instalację aplikacji GitHub i utworzenie wymaganych sekretów.
  2. Postępuj zgodnie z instrukcjami
    • Autoryzuj aplikację Claude GitHub
    • Udziel uprawnień do repozytorium
    • Klucz API jest konfigurowany automatycznie
  3. Przetestuj integrację. Utwórz komentarz do zgłoszenia, który wspomina Claude:
    @claude implement this feature based on the issue description

Dla niestandardowych konfiguracji lub dostawców chmury:

.github/workflows/claude.yml
name: Claude Code Actions
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened]
permissions:
contents: write
pull-requests: write
issues: write
jobs:
claude-pr:
if: contains(github.event.comment.body, '@claude')
runs-on: ubuntu-latest
timeout-minutes: 60 # Zegar na poziomie zadania, nie wejście akcji
steps:
- uses: actions/checkout@v4
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
trigger_phrase: '@claude'
claude_args: '--max-turns 30'

Przekształcaj zgłoszenia bezpośrednio w pull requesty:

.github/workflows/issue-to-pr.yml
name: Issue to PR
on:
issues:
types: [labeled]
jobs:
implement-feature:
if: github.event.label.name == 'implement-with-claude'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: anthropics/claude-code-action@v1
with:
prompt: |
Implement the feature described in issue #${{ github.event.issue.number }}:
${{ github.event.issue.title }}
${{ github.event.issue.body }}
Follow our coding standards in CLAUDE.md.
Create comprehensive tests.
Update documentation as needed.
When the change is complete, open a pull request titled
"feat: ${{ github.event.issue.title }}" and reference this issue in the body.
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
claude_args: '--max-turns 30'

Wzbogać przeglądy PR o analizę AI:

.github/workflows/claude-review.yml
name: AI Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # Pełna historia dla lepszej analizy
- uses: anthropics/claude-code-action@v1
with:
# /review to wbudowane polecenie; akcja publikuje komentarze przeglądu w PR.
prompt: '/review'
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
claude_args: '--max-turns 5'

Wbudowane polecenie /review obsługuje typowe przypadki. Gdy chcesz przejść przegląd nastawiony na bezpieczeństwo z ustalonym formatem wyjścia, umieść własne instrukcje bezpośrednio w polu prompt (nie ma wejścia prompt_file):

Automatyczne próby naprawy błędów CI:

.github/workflows/fix-ci.yml
name: Auto-fix CI Failures
on:
workflow_run:
workflows: ['CI']
types: [completed]
jobs:
fix-failures:
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.workflow_run.head_branch }}
- name: Get failure logs
uses: actions/github-script@v7
id: logs
with:
script: |
// workflow_run.id to identyfikator URUCHOMIENIA, więc użyj downloadWorkflowRunLogs (run_id),
// a nie downloadJobLogsForWorkflowRun (które oczekuje job_id).
const logs = await github.rest.actions.downloadWorkflowRunLogs({
owner: context.repo.owner,
repo: context.repo.repo,
run_id: ${{ github.event.workflow_run.id }}
});
return logs.data;
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
claude_args: '--max-turns 20'
prompt: |
The CI build failed with these errors:
${{ steps.logs.outputs.result }}
Fix the issues causing the build to fail.
Focus on test failures, linting errors, and type errors.
Commit the fix to the current branch with the message "fix: resolve CI failures".

Uruchamiaj Claude Code programatycznie:

Okno terminala
# Proste polecenie jednorazowe
claude -p "Update all copyright headers to 2026" --output-format json
# Z określonymi uprawnieniami
claude -p "Fix the failing test in auth.test.js" \
--allowedTools "Edit" "Read" "Bash" \
--output-format json
# Przekazuj dane przez pipe do przetwarzania
cat error.log | claude -p "Analyze these errors and suggest fixes"

Obsługuj migracje na dużą skalę:

migrate-components.sh
#!/bin/bash
# Generuj listę zadań
claude -p "List all React class components that need hooks migration" \
--output-format json > tasks.json
# Przetwarzaj każdy komponent
jq -r '.files[]' tasks.json | while read file; do
echo "Migrating $file..."
claude -p "Convert $file from class component to hooks. Preserve all functionality." \
--allowedTools "Edit"
done

Integruj z istniejącymi narzędziami:

Okno terminala
# Potok jakości kodu
npm run lint 2>&1 | \
claude -p "Fix all linting errors" --allowedTools "Edit" | \
claude -p "Now run tests and fix any failures" --allowedTools "Bash" "Edit" | \
claude -p "Generate a summary of changes" > changes.md
.git/hooks/pre-commit
#!/bin/bash
# Sprawdź komentarze TODO
if git diff --cached --name-only | xargs grep -l "TODO" > /dev/null; then
echo "Found TODO comments. Asking Claude to address them..."
git diff --cached --name-only | xargs grep -l "TODO" | while read file; do
claude -p "In $file, implement any TODO comments or convert them to proper issues" \
--allowedTools "Edit"
done
# Ponownie dodaj zmiany do stage
git add -u
fi
.github/workflows/update-docs.yml
name: Update Documentation
on:
schedule:
- cron: '0 2 * * *' # 2:00 codziennie
workflow_dispatch:
jobs:
update-docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Update API Documentation
run: |
claude -p "Update API documentation in docs/api.md based on current code in src/api/" \
--allowedTools "Edit" "Read" \
--output-format json > result.json
- name: Update README
run: |
claude -p "Update README.md badges, dependencies list, and examples based on package.json and recent changes" \
--allowedTools "Edit" "Read"
- name: Create PR if changes
uses: peter-evans/create-pull-request@v7
with:
title: 'docs: automated documentation updates'
commit-message: 'docs: update API docs and README'
branch: auto-update-docs

Organizuj zmiany w mikrousługach:

.github/workflows/coordinated-update.yml
name: Coordinated Service Update
on:
workflow_dispatch:
inputs:
change_description:
description: 'Describe the change to implement'
required: true
jobs:
plan:
runs-on: ubuntu-latest
outputs:
plan: ${{ steps.create-plan.outputs.plan }}
steps:
- uses: actions/checkout@v4
- id: create-plan
run: |
PLAN=$(claude -p "Create an implementation plan for: ${{ github.event.inputs.change_description }}. List affected services and order of updates." --output-format json)
echo "plan=$PLAN" >> $GITHUB_OUTPUT
update-services:
needs: plan
strategy:
matrix:
service: ${{ fromJson(needs.plan.outputs.plan).services }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
repository: myorg/${{ matrix.service }}
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
claude_args: '--max-turns 30'
prompt: |
Implement this change: ${{ github.event.inputs.change_description }}
This is service: ${{ matrix.service }}
Full plan: ${{ needs.plan.outputs.plan }}
Ensure backward compatibility, then open a pull request against this service's
default branch describing the change and its place in the overall plan.
.github/workflows/security-scan.yml
name: Security Analysis
on:
pull_request:
branches: [main]
jobs:
security-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run Security Scan
run: |
npm audit --json > audit.json
bandit -r . -f json -o bandit.json || true
- name: Analyze and Fix
run: |
claude -p "Analyze security reports and fix critical issues:
NPM Audit: $(cat audit.json)
Bandit: $(cat bandit.json)
Fix only CRITICAL and HIGH severity issues.
Document any issues that require manual review." \
--allowedTools "Edit" "Read"
- name: Generate Security Report
run: |
claude -p "Generate a security assessment report based on the changes made" \
> security-report.md
- name: Comment on PR
uses: actions/github-script@v7
with:
script: |
const report = require('fs').readFileSync('security-report.md', 'utf8');
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: report
});

Uruchamiaj Claude tylko przy istotnych zmianach:

name: Smart Claude Trigger
on:
pull_request:
paths:
- '**.ts'
- '**.tsx'
- '**.js'
- '**.jsx'
jobs:
analyze-complexity:
runs-on: ubuntu-latest
outputs:
should-run-claude: ${{ steps.check.outputs.result }}
steps:
- uses: actions/checkout@v4
- id: check
run: |
# Uruchom Claude tylko dla znaczących zmian
LINES_CHANGED=$(git diff --numstat origin/main..HEAD | awk '{sum+=$1+$2} END {print sum}')
if [ $LINES_CHANGED -gt 50 ]; then
echo "result=true" >> $GITHUB_OUTPUT
else
echo "result=false" >> $GITHUB_OUTPUT
fi
claude-review:
needs: analyze-complexity
if: needs.analyze-complexity.outputs.should-run-claude == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.GITHUB_TOKEN }}
prompt: '/review'
claude_args: '--max-turns 5'

Redukuj redundantne wywołania API:

- name: Cache Claude Analysis
uses: actions/cache@v4
with:
path: .claude-cache
key: claude-${{ hashFiles('**/*.ts', '**/*.tsx') }}
- name: Run Claude Analysis
run: |
if [ -f .claude-cache/analysis.json ]; then
echo "Using cached analysis"
else
claude -p "Analyze codebase for potential improvements" \
--output-format json > .claude-cache/analysis.json
fi
- name: Report Usage Metrics
if: always()
run: |
claude -p "Summarize the work done in this CI run" --output-format json > usage.json
# Wyślij do serwisu monitorowania
curl -X POST https://metrics.company.com/claude-usage \
-H "Content-Type: application/json" \
-d @usage.json
claude-metrics.js
const { execSync } = require('child_process');
function trackClaudePerformance(command, context) {
const start = Date.now();
try {
const result = execSync(`claude -p "${command}" --output-format json`, {
encoding: 'utf8',
maxBuffer: 10 * 1024 * 1024,
});
const duration = Date.now() - start;
const parsed = JSON.parse(result);
// Wyślij do monitorowania
sendMetrics({
command,
context,
duration,
tokensUsed: parsed.usage?.total_tokens,
success: true,
});
return parsed;
} catch (error) {
sendMetrics({
command,
context,
duration: Date.now() - start,
success: false,
error: error.message,
});
throw error;
}
}

Używaj plików CLAUDE.md

Konfiguruj wytyczne specyficzne dla projektu dla spójnego zachowania CI

Ogranicz tury i czas

Ustaw --max-turns w claude_args oraz timeout-minutes: na poziomie zadania, aby zapobiec niekontrolowanym kosztom

Przeglądaj przed merge

Zawsze miej przegląd ludzki dla zmian generowanych przez Claude

Monitoruj koszty

Śledź użycie API i optymalizuj wyzwalacze

Symptomy: Wzmianki @claude są ignorowane

Rozwiązania:

  1. Zweryfikuj instalację aplikacji GitHub
  2. Sprawdź uprawnienia przepływu pracy
  3. Upewnij się, że warunki wyzwalacza się zgadzają
  4. Zweryfikuj, czy klucz API jest ustawiony poprawnie
  5. Sprawdź logi GitHub Actions

Dla niestandardowych integracji poza GitHub Actions:

claude-automation.ts
import { exec } from 'child_process';
import { promisify } from 'util';
import * as fs from 'fs/promises';
const execAsync = promisify(exec);
async function automateCodeReview(prNumber: number) {
// Przygotuj prompt do przeglądu
const prompt = `Review pull request #${prNumber} for:
- Security vulnerabilities
- Performance issues
- Code style violations
- Missing tests
Use the CLAUDE.md file for project context and
.github/review-guide.md for review guidelines.`;
// Zapisz prompt do pliku dla złożonych promptów wieloliniowych
await fs.writeFile('/tmp/review-prompt.txt', prompt);
try {
// Przy `cat file | claude -p` stdin staje się promptem, więc nie jest potrzebny
// żaden argument pozycyjny. Odwzorowuje to oficjalny idiom:
// gh pr diff "$1" | claude -p --append-system-prompt "..." --output-format json
const { stdout } = await execAsync(
`cat /tmp/review-prompt.txt | claude -p --output-format json`,
{
cwd: process.cwd(),
env: { ...process.env }
}
);
return JSON.parse(stdout);
} catch (error) {
console.error('Claude Code review failed:', error);
throw error;
}
}
// Alternatywa: Strumieniowanie wyjścia dla przetwarzania w czasie rzeczywistym
import { spawn } from 'child_process';
function streamCodeReview(prNumber: number): Promise<string[]> {
return new Promise((resolve, reject) => {
const messages: string[] = [];
const claude = spawn('claude', [
'-p',
`Review PR #${prNumber} for security and performance`,
'--output-format', 'json'
]);
claude.stdout.on('data', (data) => {
messages.push(data.toString());
});
claude.on('close', (code) => {
if (code === 0) {
resolve(messages);
} else {
reject(new Error(`Claude Code exited with code ${code}`));
}
});
});
}

Przepływy zespołowe

Skaluj wzorce CI/CD w całej organizacji

Zarządzanie kosztami

Optymalizuj koszty i użycie CI/CD

Wzorce bezpieczeństwa

Implementuj bezpieczne praktyki CI/CD