From b0698bfb39bb98b6d5ef2ce41066acd3ff410717 Mon Sep 17 00:00:00 2001 From: Florian BRUNIAUX Date: Fri, 13 Mar 2026 17:19:18 +0100 Subject: [PATCH] docs: add GitHub Actions workflow guide + desloppify + threat-db v2.7.0 - guide/workflows/github-actions.md (new): 5 production patterns with claude-code-action (on-demand @claude, auto push review, issue triage, security review, scheduled maintenance), auth alternatives, cost control - guide/ultimate-guide.md: GitHub Actions cross-ref + desloppify tool (vibe code quality fix-loop, community tool, ~2K stars, Feb 2026) - examples/commands/resources/threat-db.yaml: v2.7.0, +5 threat sources (Azure MCP SSRF CVE-2026-26118, OpenClaw, Taskflow, Codex Security, DryRun Security 87% vulnerability stat) - CLAUDE.md: Behavioral Rules section (5 rules from observed friction) - guide/workflows/README.md: github-actions entry + quick selection row - IDEAS.md: CI/CD Workflows Gallery marked complete - CHANGELOG.md: [Unreleased] entries for all items Co-Authored-By: Claude Sonnet 4.6 --- CHANGELOG.md | 8 + CLAUDE.md | 22 ++ IDEAS.md | 17 +- examples/commands/resources/threat-db.yaml | 93 ++++- guide/ultimate-guide.md | 29 ++ guide/workflows/README.md | 19 + guide/workflows/github-actions.md | 393 +++++++++++++++++++++ 7 files changed, 564 insertions(+), 17 deletions(-) create mode 100644 guide/workflows/github-actions.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 7229122..ac19cc7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### Added +- **`guide/workflows/github-actions.md`** — New workflow guide (5 production-ready patterns using `anthropics/claude-code-action`, 6.2k stars, v1.0). Covers: (1) on-demand PR review via `@claude` mention, (2) automatic review on every push, (3) issue triage and labeling, (4) security-focused review on sensitive path changes, (5) scheduled weekly repo health check. Includes setup via `/install-github-app`, authentication alternatives (OAuth vs API key), cost control (concurrency limits, token caps), and fork safety (`pull_request_target` vs `pull_request`). + +- **`guide/ultimate-guide.md`** — Two additions: (1) Cross-reference callout to `github-actions.md` in the CI/CD section. (2) New "Fighting Vibe Code Degradation" subsection covering **desloppify** ([github.com/peteromallet/desloppify](https://github.com/peteromallet/desloppify)): a community tool that installs a prioritized fix-loop as a Claude Code skill, scanning for dead code, duplication, and structural issues until a quality score target is hit. + +- **`examples/commands/resources/threat-db.yaml`** — Updated to v2.7.0 (2026-03-13). Added 5 new threat intelligence sources: CVE-2026-26118 Azure MCP Server SSRF (THN/Tenable), OpenClaw agentic AI risk analysis (ReversingLabs), Taskflow Agent open-source vulnerability scanner (GitHub Security Lab), OpenAI Codex Security research preview, and DryRun Security research on AI coding agents introducing vulnerabilities in 87% of PRs. + +- **`CLAUDE.md`** — Added "Behavioral Rules" section: 5 rules derived from observed friction patterns (always update CHANGELOG.md, exhaustive first-pass analysis, use absolute paths, closing checklist, bias toward action). + - **`examples/scripts/test-prompt-caching.ts`** — Standalone TypeScript script (zero deps, native fetch) to verify Anthropic prompt caching is active on any API key. Runs 3 identical calls and checks write/read metrics. Documents 4 production gotchas not in official docs: (1) `anthropic-beta: prompt-caching-2024-07-31` header is required even for Claude 4.x, (2) effective token threshold for Claude 4.x is ~2048+ not the documented 1024, (3) cached tokens are excluded from `input_tokens`, (4) new nested `cache_creation` object format with `ephemeral_5m_input_tokens` and `ephemeral_1h_input_tokens`. Usage: `ANTHROPIC_API_KEY=sk-ant-... npx tsx test-prompt-caching.ts`. - **`CLAUDE.md` Behavioral Rules section** — New `## Behavioral Rules` section with 5 rules derived from observed session friction patterns (via `/insights` analysis): (1) always update `CHANGELOG.md` after any modification, (2) be exhaustive on first pass for audits and reviews, (3) use absolute paths in reports and documentation, (4) closing checklist confirming files changed + changelog + commit hash, (5) bias toward action — no extended planning loops without deliverables. diff --git a/CLAUDE.md b/CLAUDE.md index 4a20b53..dde1cdb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -191,6 +191,28 @@ Implicit prefixes used in `.claude/commands/`: When adding a new command, pick the prefix that matches the action type. Avoid creating new prefix categories unless the existing four don't fit. +## Behavioral Rules + +These rules come from observed friction patterns in actual sessions on this repo. + +### Always update CHANGELOG.md +After any file modification or feature implementation, update `CHANGELOG.md` under `[Unreleased]`. Never skip this step unless explicitly told to. This is the most common missed step. + +### Be exhaustive on first pass +When asked to analyze, audit, or review anything — read every relevant file. Do not do a superficial scan. If unsure of scope, ask rather than delivering shallow results. This applies to resource evaluations, doc audits, and codebase reviews. + +### Use absolute paths +When referencing files in documentation, reports, or resource evaluations, always use full absolute paths. Never relative paths. + +### Closing checklist +After completing all requested tasks, always confirm unprompted: +1. Files changed (list them) +2. CHANGELOG.md updated +3. Committed and pushed (if applicable) — include the commit hash + +### Bias toward action +Do not spend extended time in exploration or planning loops. Produce files and concrete output early, then iterate. If stuck for more than 2 attempts on any step, explain the blocker instead of looping. + ## Conventions ### Documentation Style diff --git a/IDEAS.md b/IDEAS.md index f2750ec..180db76 100644 --- a/IDEAS.md +++ b/IDEAS.md @@ -26,22 +26,9 @@ Unified security research covering MCP vulnerabilities, prompt injection, and se ## Medium Priority -### CI/CD Workflows Gallery -Concrete GitHub Actions examples for Claude Code integration. +### CI/CD Workflows Gallery ✅ -**Topics:** -- Automated PR review workflows -- Test generation pipelines -- Cost optimization patterns for API calls in CI -- Pre-commit hooks integration - -**Perplexity Query:** -``` -GitHub Actions workflows for AI coding assistants 2024-2025: -- Automated code review with Claude/GPT -- Cost optimization for API calls in CI/CD -- Real examples from open source projects -``` +**Completed**: [GitHub Actions Workflows](./guide/workflows/github-actions.md) — 5 patterns using `anthropics/claude-code-action` (PR review, auto-review, issue triage, security, scheduled maintenance). Includes cost control, fork safety, Bedrock/Vertex auth alternatives. Cross-linked from section 9.3 of the main guide. ### MCP Server Catalog Exhaustive list of MCP servers with real-world use cases. diff --git a/examples/commands/resources/threat-db.yaml b/examples/commands/resources/threat-db.yaml index ea69e62..c87a02e 100644 --- a/examples/commands/resources/threat-db.yaml +++ b/examples/commands/resources/threat-db.yaml @@ -2,8 +2,8 @@ # For use with /security-check and /security-audit commands # Manually maintained — update after new security advisories -version: "2.6.0" -updated: "2026-03-09" +version: "2.7.0" +updated: "2026-03-13" sources: - name: "Snyk ToxicSkills" url: "https://snyk.io/blog/toxicskills-malicious-ai-agent-skills-clawhub/" @@ -143,6 +143,21 @@ sources: - name: "Brandefense - MCP Server Security: 10 Protocol-Level Attack Scenarios" url: "https://brandefense.io/blog/mcp-server-security-protocol-attack-patterns/" date: "2026-03-02" + - name: "THN / Tenable - CVE-2026-26118 Azure MCP Server SSRF" + url: "https://thehackernews.com/2026/03/microsoft-patches-84-flaws-in-march.html" + date: "2026-03-11" + - name: "ReversingLabs - OpenClaw and agentic AI risk: 3 application security lessons" + url: "https://www.reversinglabs.com/blog/openclaw-agentic-ai-risk" + date: "2026-03-10" + - name: "GitHub Security Lab - Taskflow Agent open-source vulnerability scanner" + url: "https://github.blog/security/how-to-scan-for-vulnerabilities-with-github-security-labs-open-source-ai-powered-framework/" + date: "2026-03-06" + - name: "OpenAI - Codex Security research preview" + url: "https://openai.com/index/codex-security-now-in-research-preview/" + date: "2026-03-05" + - name: "DryRun Security - AI coding agents introduce vulnerabilities in 87% of PRs" + url: "https://markets.businessinsider.com/news/stocks/new-dryrun-security-research-anthropic-s-claude-generates-the-most-unresolved-security-flaws-in-ai-built-applications-1035918593" + date: "2026-03-11" # ═══════════════════════════════════════════════════════════════ # MALICIOUS AUTHORS (confirmed by security researchers) @@ -917,6 +932,17 @@ cve_database: fixed_in: "patch commit 30a6b9e1c7fa6146f51e28d6ab83a2568d9a3488" mitigation: "Apply patch commit 30a6b9e...; replace child_process.exec with execFile() and argument arrays; sanitize all nmap arguments" + # --- Azure MCP Server (Microsoft) --- + - id: "CVE-2026-26118" + component: "Azure MCP Server Tools (Microsoft Azure)" + severity: "high" + cvss: 8.8 + description: "SSRF leading to managed identity token theft and privilege escalation — attacker sends crafted input to exposed Azure MCP Server endpoint; server forwards request to attacker-controlled URL including its managed identity token; attacker captures token and gains all permissions associated with the MCP server's managed identity (can reach Azure resources, management APIs, subscriptions)" + source: "Microsoft Patch Tuesday March 2026 / Tenable / The Hacker News (2026-03-10)" + fixed_in: "March 10, 2026 Patch Tuesday update" + mitigation: "Apply Microsoft March 2026 security update; restrict Azure MCP Server endpoints to trusted callers; audit managed identity permissions (principle of least privilege); monitor for unexpected outbound requests from MCP server processes" + notes: "CWE-918 SSRF; rated 'Exploitation Less Likely' by Microsoft; part of 84-CVE March 2026 Patch Tuesday" + # --- Framelink Figma MCP Server (additional CVE) --- - id: "CVE-2025-15061" component: "Framelink Figma MCP Server (figma-developer-mcp)" @@ -945,6 +971,7 @@ minimum_safe_versions: "mcpjam-inspector": "1.4.3" "mcp-salesforce-connector": "0.1.10" "openclaw": "2026.1.29" + "azure-mcp-server": "March 2026 Patch Tuesday (2026-03-10)" # ═══════════════════════════════════════════════════════════════ # IOCs (Indicators of Compromise) @@ -1260,6 +1287,16 @@ campaigns: - "https://adnanthekhan.com/posts/clinejection/" - "https://thehackernews.com/2026/02/cline-cli-230-supply-chain-attack.html" + - name: "ClawHub Wave 3 / VirusTotal Bypass" + source: "ReversingLabs / Paul McCarty (OpenSourceMalware)" + date: "2026-03-10" + platform: "ClawHub / OpenClaw" + technique: "After OpenClaw integrated VirusTotal scanning, attackers pivoted to hosting malware on lookalike OpenClaw websites; skills are used as decoys with no embedded payload (passing VirusTotal clean), but direct victims to attacker-controlled lookalike domains for 'installation prerequisites'. Bypasses hash-based scanning entirely." + notes: "Tactical evolution from ClawHavoc (direct payload in SKILL.md) and Wave 2 (mixed payloads). Now requires domain-level blocking of lookalike sites, not just skill content scanning. Concurrent with Jamieson O'Reilly research finding worm-friendly XSS in ClawHub marketplace itself enabling one-click account takeover." + sources: + - "https://www.reversinglabs.com/blog/openclaw-agentic-ai-risk" + - "https://www.adminbyrequest.com/en/blogs/openclaw-went-from-viral-ai-agent-to-security-crisis-in-just-three-weeks" + - name: "ClawHub Wave 2 (71 Skills)" source: "Oasis Security / The Hacker News" date: "2026-02-28" @@ -1416,6 +1453,16 @@ attack_techniques: source: "Oasis Security (2026-02-26)" mitigation: "Update OpenClaw to >= v2026.2.26; apply rate limiting to ALL connections including localhost; require explicit user confirmation for device pairing; block WebSocket connections from browser contexts to localhost AI agent ports; use CORS headers to prevent cross-origin WebSocket upgrades" + - id: "T016" + name: "Lookalike Platform / Scanner Evasion" + description: "Attacker hosts malware on lookalike AI agent platform websites (fake ClawHub, fake skills.sh); skills on the real platform are clean decoys that redirect victims to lookalike domains for 'prerequisites' or 'dependencies'. Bypasses hash-based scanner integrations (e.g. VirusTotal) because the skill file itself contains no malicious payload." + examples: + - "Post-VirusTotal-integration ClawHavoc evolution: clean skills instruct users to download from openclaw-tools[.]io or similar lookalike domains" + - "Skills referencing 'official installation docs' hosted on attacker-controlled domains" + campaigns: ["ClawHub Wave 3 / VirusTotal Bypass"] + source: "ReversingLabs / Paul McCarty (OpenSourceMalware) 2026-03-10" + mitigation: "Domain verification for all external links in SKILL.md; never follow SKILL.md instructions to external websites; use network egress filtering; check domain registration dates for 'official' skill installer links" + - id: "T015" name: "Log Poisoning via WebSocket for Prompt Injection" description: "Attacker writes malicious content to publicly exposed AI agent log files via unauthenticated WebSocket requests; since the agent reads its own logs to troubleshoot tasks, the injected content acts as indirect prompt injection, triggering unintended agent actions" @@ -1603,6 +1650,34 @@ scanning_tools: - "Cloud-based — requires sending server metadata to external platform" - "Not open-source" + - name: "GitHub Security Lab Taskflow Agent" + vendor: "GitHub Security Lab" + type: "cli" + url: "https://github.blog/security/how-to-scan-for-vulnerabilities-with-github-security-labs-open-source-ai-powered-framework/" + capabilities: + - "Open-source AI-powered vulnerability scanner for codebases" + - "Effective at Auth Bypasses, IDORs, Token Leaks, and high-impact vulnerabilities" + - "Filters ~50% of low-severity findings while retaining high-impact ones" + - "Agentic reasoning approach — traces data flows and understands component interactions" + limitations: + - "Code-focused security scanner — does not scan SKILL.md or MCP configs" + - "Does not scan ClawHub / skills.sh ecosystems" + notes: "GitHub Security Lab open-source AI framework; launched 2026-03-06" + + - name: "OpenAI Codex Security" + vendor: "OpenAI" + type: "cloud-saas" + url: "https://openai.com/index/codex-security-now-in-research-preview/" + capabilities: + - "AI application security agent combining agentic reasoning with automated validation" + - "Detects and patches complex vulnerabilities with 50%+ false positive reduction" + - "Over 90% reduction in over-reported severity vs traditional tools" + - "Scans 1.2M+ commits at scale (demonstrated on open-source projects)" + limitations: + - "Research preview — not generally available" + - "Code scanning focus — does not scan SKILL.md or agent configurations" + notes: "Complementary to Anthropic Claude Code Security; launched research preview 2026-03-05" + - name: "Mend SAST MCP" vendor: "Mend.io" type: "mcp-server" @@ -1680,3 +1755,17 @@ defensive_resources: url: "https://cycode.com/blog/ai-cybersecurity-tools/" type: "platform" description: "Cycode's AI Governance module enforces MCP usage policies, tracks tool invocations, and provides AI Guardrails that intercept secrets in real time across IDE prompts, file reads, and MCP tool calls before they reach the LLM or external services. Part of broader SAST/SCA/secrets platform." + + - name: "DryRun Security AI Coding Agent Research" + url: "https://markets.businessinsider.com/news/stocks/new-dryrun-security-research-anthropic-s-claude-generates-the-most-unresolved-security-flaws-in-ai-built-applications-1035918593" + type: "research" + description: "March 2026 study by DryRun Security: 87% of AI coding agent PRs (26/30) introduced at least one vulnerability; 143 total security issues across Claude Sonnet 4.6, OpenAI Codex, and Google Gemini builds. Top recurring flaws: broken access control, unauthenticated endpoints on destructive operations, OAuth missing state parameter, WebSocket auth gaps. Takeaway: AI agents accelerate development but do not apply security by default — requires dedicated security review layer." + stats: + prs_with_vulns_pct: 87 + total_issues: 143 + agents_tested: ["Claude Sonnet 4.6", "OpenAI Codex GPT 5.2", "Google Gemini 2.5 Pro"] + + - name: "Qualys TotalAI MCP Asset Governance" + url: "https://blog.qualys.com/product-tech/2026/03/10/from-shadow-models-to-audit-ready-ai-security-a-practical-path-with-qualys-totalai" + type: "platform" + description: "Qualys TotalAI treats MCP servers as first-class security assets alongside models and endpoints. Supports inventory-first visibility across AI environments — discovers MCP server instances, tracks versions, and detects unmanaged/shadow MCP deployments. Available 2026-03-10." diff --git a/guide/ultimate-guide.md b/guide/ultimate-guide.md index e7935dc..0931337 100644 --- a/guide/ultimate-guide.md +++ b/guide/ultimate-guide.md @@ -13300,6 +13300,8 @@ For critical work, combine everything: ## 9.3 CI/CD Integration +> **📖 Complete Workflow Guide**: See [GitHub Actions Workflows](./workflows/github-actions.md) for 5 production-ready patterns using the official `anthropics/claude-code-action` (PR review, triage, security, scheduled maintenance). + ### Headless Mode Run Claude Code without interactive prompts: @@ -14798,6 +14800,33 @@ Claude: [writes handoff to claudedocs/handoffs/oauth-implementation.md] **The insight:** Rusitschka's "Vibe Coding, Level 2" is Claude Code's native workflow — it just needed explicit framing as an anti-pattern antidote. Plan mode prevents context pollution during exploration, fresh context prevents accumulation during implementation, and handoffs enable clean phase transitions. +### Fighting Vibe Code Degradation + +Vibe coding gets things built fast. The codebases it produces tend to rot in ways that are hard to see: abstractions drift, naming becomes inconsistent, error handling gets done three different ways. The code still works, but working in it gets progressively worse. + +**Desloppify** ([github.com/peteromallet/desloppify](https://github.com/peteromallet/desloppify)) is a community tool that directly addresses this. It installs a workflow guide into Claude Code as a skill, then runs a prioritized fix loop: scan → get next issue → fix → resolve → repeat until a quality score target is hit. The scoring is designed to resist gaming — improving the number requires actually improving the code. + +```bash +pip install --upgrade "desloppify[full]" +desloppify update-skill claude # installs workflow as a Claude Code skill + +# Before scanning: exclude generated files, build output, vendored code +desloppify exclude node_modules +desloppify exclude .next + +desloppify scan --path . +desloppify next # get first prioritized fix +# fix it, then: +desloppify resolve +desloppify next # repeat +``` + +The loop handles both mechanical issues (dead code, duplication, complexity) and structural ones (naming clarity, abstraction design, module boundaries). A score above 98 is meant to correlate with what a senior engineer would call a clean codebase. + +> **Status**: Early-stage (released February 2026, ~2K GitHub stars). Promising native Claude Code integration but not yet battle-tested at scale. Evaluate token cost before running on large codebases — multi-pass LLM review across a full codebase can be substantial. + +--- + ### Skeleton Projects Skeleton projects are minimal, working templates that establish patterns before full implementation. diff --git a/guide/workflows/README.md b/guide/workflows/README.md index b3ac3be..17f4331 100644 --- a/guide/workflows/README.md +++ b/guide/workflows/README.md @@ -91,6 +91,25 @@ Build features in three locked phases: Research feasibility first, plan the impl **When to use**: Features with unclear feasibility, more than a day of work, unknown technical territory, or anywhere discovering a wrong assumption late is costly +### [GitHub Actions Workflows](./github-actions.md) ⭐ NEW + +**5 production-ready patterns for automating PR reviews, issue triage, and quality gates** + +Connect Claude directly to your GitHub workflow via the official `claude-code-action`. Two modes: interactive (`@claude` mentions) and fully automated (push/schedule triggers). + +**Key Topics**: +- Setup via `/install-github-app` (30-second quickstart) +- Pattern 1: On-demand PR review via `@claude` mention +- Pattern 2: Automatic review on every push +- Pattern 3: Issue triage and labeling +- Pattern 4: Security-focused review on sensitive paths +- Pattern 5: Scheduled weekly repo health check +- Cost control, concurrency, fork safety + +**When to use**: Any team wanting AI-powered code review without managing infrastructure + +--- + ### [Cognitive Mode Switching](./gstack-workflow.md) ⭐ NEW Switch between specialist roles across your ship cycle: strategic product gate, architecture review, paranoid code review, automated release, native browser QA, and retrospective. diff --git a/guide/workflows/github-actions.md b/guide/workflows/github-actions.md new file mode 100644 index 0000000..0ea189b --- /dev/null +++ b/guide/workflows/github-actions.md @@ -0,0 +1,393 @@ +--- +title: "GitHub Actions Workflows with Claude Code" +description: "Production-ready patterns for automating PR reviews, issue triage, and quality gates with claude-code-action" +tags: [workflow, ci-cd, github-actions, automation] +--- + +# GitHub Actions Workflows with Claude Code + +> **Confidence**: Tier 1 — Official Anthropic action (`anthropics/claude-code-action`, 6.2k stars, v1.0). + +Automate code reviews, issue triage, and quality gates by connecting Claude directly to your GitHub workflow. Two trigger models: `@claude` mentions (human-initiated) and scheduled/event automations (fully autonomous). + +--- + +## Table of Contents + +1. [TL;DR](#tldr) +2. [Two Models](#two-models) +3. [Setup](#setup) +4. [Pattern 1: PR Code Review on @claude Mention](#pattern-1-pr-code-review-on-claude-mention) +5. [Pattern 2: Automatic PR Review on Push](#pattern-2-automatic-pr-review-on-push) +6. [Pattern 3: Issue Triage and Labeling](#pattern-3-issue-triage-and-labeling) +7. [Pattern 4: Security-Focused Review](#pattern-4-security-focused-review) +8. [Pattern 5: Scheduled Repo Maintenance](#pattern-5-scheduled-repo-maintenance) +9. [Authentication Alternatives](#authentication-alternatives) +10. [Cost Control](#cost-control) +11. [Security Checklist](#security-checklist) +12. [See Also](#see-also) + +--- + +## TL;DR + +```yaml +# Minimal working example — paste into .github/workflows/claude.yml +name: Claude Code Review +on: + issue_comment: + types: [created] + +jobs: + claude: + if: contains(github.event.comment.body, '@claude') + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + issues: write + steps: + - uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} +``` + +Comment `@claude review this PR` on any PR → Claude reads the diff and posts a review. + +--- + +## Two Models + +| Model | Trigger | Use case | +|-------|---------|----------| +| **Interactive** | `@claude` mention in PR/issue comment | On-demand reviews, questions, fixes | +| **Automated** | Push, PR open, schedule, label | Continuous quality gates, triage | + +Both use the same action — the difference is the `on:` block and whether you include an `if:` condition. + +--- + +## Setup + +### Quickstart (30 seconds) + +In your Claude Code terminal, inside any project connected to a GitHub repo: + +``` +/install-github-app +``` + +This guides you through creating the GitHub App, adding `ANTHROPIC_API_KEY` to your repo secrets, and generating the base `claude.yml` workflow. + +### Manual Setup + +1. Add `ANTHROPIC_API_KEY` to your GitHub repository secrets +2. Create `.github/workflows/claude.yml` (see patterns below) +3. Grant the workflow permissions: `contents: write`, `pull-requests: write`, `issues: write` + +--- + +## Pattern 1: PR Code Review on @claude Mention + +Human-initiated. A developer comments `@claude review this PR` and Claude responds inline. + +```yaml +# .github/workflows/claude-review.yml +name: Claude Interactive Review +on: + issue_comment: + types: [created, edited] + pull_request_review_comment: + types: [created] + +jobs: + claude: + if: | + contains(github.event.comment.body, '@claude') || + contains(github.event.review_comment.body, '@claude') + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + issues: write + steps: + - uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + claude_env: | + GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} +``` + +**Usage examples:** +- `@claude review this PR` — full diff analysis with suggestions +- `@claude is this change backwards compatible?` — targeted question +- `@claude fix the failing test in src/auth.test.ts` — Claude opens a follow-up PR with the fix + +--- + +## Pattern 2: Automatic PR Review on Push + +Every PR gets a review the moment it opens or updates. No mention required. + +```yaml +# .github/workflows/claude-auto-review.yml +name: Claude Auto PR Review +on: + pull_request: + types: [opened, synchronize] + # Optional: only trigger on specific paths + # paths: + # - 'src/**' + # - '!**/*.md' + +jobs: + claude-review: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + steps: + - uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + prompt: | + Review this pull request. Focus on: + - Logic errors and edge cases + - Security issues (injection, auth, secrets) + - Performance regressions + - Missing error handling + + Format your response as: + ## Summary + One paragraph describing the change. + + ## Issues Found + Numbered list, severity (Critical/Major/Minor), file:line reference. + + ## Suggestions + Optional improvements. + + Keep it under 400 words. Be direct. +``` + +**Tip**: Add `paths:` to avoid triggering on doc-only PRs, or `if: github.event.pull_request.draft == false` to skip drafts. + +--- + +## Pattern 3: Issue Triage and Labeling + +Claude reads new issues, assigns labels, and posts a structured triage comment. + +```yaml +# .github/workflows/claude-triage.yml +name: Issue Triage +on: + issues: + types: [opened] + +jobs: + triage: + runs-on: ubuntu-latest + permissions: + issues: write + contents: read + steps: + - uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + prompt: | + Triage this GitHub issue: + + 1. Assign one label from: bug, enhancement, question, documentation, performance, security + 2. Assign a priority label: priority:critical, priority:high, priority:medium, priority:low + 3. Post a comment with: + - Issue type classification + - Which component is likely affected (based on the issue description) + - Next step recommendation for the reporter (reproduce steps needed? version info missing?) + + Be brief. One sentence per point. +``` + +--- + +## Pattern 4: Security-Focused Review + +Runs specifically for PRs touching sensitive paths (auth, payments, config). + +```yaml +# .github/workflows/claude-security.yml +name: Security Review +on: + pull_request: + paths: + - 'src/auth/**' + - 'src/payments/**' + - '**/config/**' + - '**/.env*' + - '**/secrets/**' + +jobs: + security-review: + runs-on: ubuntu-latest + permissions: + contents: read + pull-requests: write + steps: + - uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + prompt: | + Perform a security-focused review of this PR. Check for: + + - Injection vulnerabilities (SQL, command, LDAP) + - Authentication and authorization bypasses + - Secrets or credentials in code or comments + - Insecure direct object references + - Missing input validation + - Unsafe deserialization + - OWASP Top 10 patterns + + Rate overall risk: Low / Medium / High / Critical. + If High or Critical, add the label 'security-review-required'. + List each finding with: file:line, vulnerability type, and recommended fix. +``` + +--- + +## Pattern 5: Scheduled Repo Maintenance + +Weekly health check — runs without any human trigger. + +```yaml +# .github/workflows/claude-maintenance.yml +name: Weekly Repo Health Check +on: + schedule: + - cron: '0 9 * * 1' # Every Monday at 9am UTC + workflow_dispatch: # Also allows manual trigger + +jobs: + maintenance: + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@v4 + + - uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + prompt: | + Perform a weekly repository health check: + + 1. Scan package.json (or equivalent) for outdated major dependencies + 2. Check for TODO/FIXME comments older than 30 days in src/ + 3. Identify any test files without corresponding implementation files + 4. List any documentation files that reference deleted or renamed files + + Open a GitHub issue titled "Weekly Health Check - [date]" with your findings. + If nothing requires attention, post a comment "Health check passed — no issues found." +``` + +--- + +## Authentication Alternatives + +The examples above use `ANTHROPIC_API_KEY` directly. For teams using cloud providers: + +**Amazon Bedrock:** +```yaml +- uses: anthropics/claude-code-action@v1 + with: + use_bedrock: 'true' + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_REGION: us-east-1 + ANTHROPIC_MODEL: 'anthropic.claude-3-5-sonnet-20241022-v2:0' +``` + +**Google Vertex AI:** +```yaml +- uses: anthropics/claude-code-action@v1 + with: + use_vertex: 'true' + env: + ANTHROPIC_VERTEX_PROJECT_ID: ${{ secrets.GCP_PROJECT_ID }} + CLOUD_ML_REGION: us-east5 + ANTHROPIC_MODEL: 'claude-3-5-sonnet-v2@20241022' +``` + +Cloud providers benefit from data residency compliance and can leverage existing IAM policies instead of managing a separate API key. + +--- + +## Cost Control + +Automated workflows run without a human in the loop — set explicit limits. + +```yaml +- uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + # Cap spend per workflow run + claude_args: '--max-budget-usd 0.50' + # Use Haiku for triage, Sonnet for reviews — don't default to Opus + prompt: | + ... +``` + +**Budget guidance by pattern:** + +| Pattern | Model | Approx. cost / run | +|---------|-------|--------------------| +| PR review (medium PR) | Sonnet | $0.05–0.15 | +| Issue triage | Haiku | $0.01–0.03 | +| Security review (large PR) | Sonnet | $0.10–0.25 | +| Scheduled maintenance | Sonnet | $0.05–0.20 | + +Monitor actual spend with `ccusage` or the Anthropic Console usage dashboard. + +**Prevent runaway costs:** +- Use `paths:` filters to avoid triggering on irrelevant changes +- Add `if: github.event.pull_request.draft == false` to skip draft PRs +- Set `concurrency:` to prevent parallel runs on the same PR + +```yaml +jobs: + claude-review: + concurrency: + group: claude-${{ github.event.pull_request.number }} + cancel-in-progress: true +``` + +--- + +## Security Checklist + +Before deploying to a team repo: + +- [ ] `ANTHROPIC_API_KEY` stored as a GitHub secret, never in workflow YAML +- [ ] Workflow permissions are minimal — use `contents: read` unless writes are required +- [ ] For public repos: add `if: github.event.pull_request.head.repo.full_name == github.repository` to prevent fork PRs from triggering API calls +- [ ] Review what the workflow posts publicly — Claude's comments are visible to all contributors +- [ ] Use `pull_request_target` with caution — it runs with write permissions even from forks + +**Fork safety pattern (public repos):** +```yaml +jobs: + claude: + # Only run on PRs from the same repo, not forks + if: github.event.pull_request.head.repo.full_name == github.repository +``` + +--- + +## See Also + +- [Section 9.3 CI/CD Integration](../ultimate-guide.md#93-cicd-integration) — headless mode, Unix piping, `--output-format json` +- [Production Safety](../security/production-safety.md) — guardrails for automated agents +- [Security Hardening](../security/security-hardening.md) — MCP and webhook security +- [Official action docs](https://github.com/anthropics/claude-code-action) — solutions guide, migration, cloud providers +- [Community workflow blueprint](https://github.com/alirezarezvani/claude-code-github-workflow) — 8 workflows + 4 autonomous agents for advanced teams \ No newline at end of file