diff --git a/docs/patterns/README.md b/docs/patterns/README.md new file mode 100644 index 0000000..3ce66b9 --- /dev/null +++ b/docs/patterns/README.md @@ -0,0 +1,23 @@ +# Patterns + +AI-assisted development patterns. Pick what you need - each works independently. + +## Agent Behavior Patterns + +How AI agents work during development. + +| Pattern | Description | +|---------|-------------| +| [Autonomous Quality Enforcement](autonomous-quality-enforcement.md) | Validate code before presenting to users | +| [Self-Review Reflection](self-review-reflection.md) | Agent reviews own work before delivery | + +## GitHub Actions Patterns + +CI/CD automations for AI-assisted workflows. + +| Pattern | Trigger | Description | +|---------|---------|-------------| +| [Issue-to-PR Automation](gha-automation-patterns.md#issue-to-pr-automation) | `issues.opened` | Auto-create draft PRs from issues | +| [PR Auto-Review](gha-automation-patterns.md#pr-auto-review) | `pull_request` | AI code review on PRs | +| [Dependabot Auto-Merge](gha-automation-patterns.md#dependabot-auto-merge) | `pull_request` | Safe auto-merge for dependencies | +| [Stale Issue Management](gha-automation-patterns.md#stale-issue-management) | `schedule` | Cleanup inactive issues | diff --git a/docs/patterns/autonomous-quality-enforcement.md b/docs/patterns/autonomous-quality-enforcement.md index 7ff0078..dad48e1 100644 --- a/docs/patterns/autonomous-quality-enforcement.md +++ b/docs/patterns/autonomous-quality-enforcement.md @@ -337,5 +337,5 @@ No divergence. If CI fails, local will fail too. ## Related Patterns +- [Self-Review Reflection](self-review-reflection.md) - Agent self-reviews before presenting work - [Multi-Agent Code Review](multi-agent-code-review.md) - Parallel agent review before presentation -- [Process Rules](#process-rules) - Agent behavior configuration diff --git a/docs/patterns/gha-automation-patterns.md b/docs/patterns/gha-automation-patterns.md new file mode 100644 index 0000000..7406a18 --- /dev/null +++ b/docs/patterns/gha-automation-patterns.md @@ -0,0 +1,283 @@ +# GitHub Actions Automation Patterns + +**Pattern**: Proactive CI/CD workflows that automate routine development tasks. + +**Problem**: Manual processes slow down development - reviewing PRs, creating PRs from issues, merging dependency updates, cleaning up stale issues. Teams spend time on toil instead of building. + +**Solution**: GitHub Actions workflows that trigger on repository events and handle routine work automatically. AI reviews code, issues become PRs, safe updates auto-merge, stale issues get cleaned up. + +--- + +## Issue-to-PR Automation + +Convert well-defined issues into draft pull requests automatically. + +### How It Works + +```mermaid +flowchart TD + A[Issue Opened] --> B{Well-defined?} + B -->|No| C[Request Clarification] + B -->|Yes| D[Analyze Issue] + D --> E[Self-Review Analysis] + E --> F[Create Branch] + F --> G[Create Draft PR] + G --> H[Link to Issue] +``` + +### Implementation + +```yaml +# .github/workflows/issue-to-pr.yml +name: Issue to Draft PR + +on: + issues: + types: [opened, labeled] + +permissions: + contents: write + pull-requests: write + issues: write + +jobs: + create-pr: + if: contains(github.event.label.name, 'ready-for-pr') || github.event.action == 'opened' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Analyze issue + id: analyze + uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + prompt: | + Analyze issue #${{ github.event.issue.number }}: ${{ github.event.issue.title }} + + Issue body: + ${{ github.event.issue.body }} + + Determine if this issue is actionable: + 1. Are requirements clear? + 2. Is scope well-defined? + 3. Any security concerns? + + Write decision to analysis-decision.txt: + - "create_pr" if ready for implementation + - "needs_clarification" if requirements unclear + + Write reasoning to analysis-reasoning.txt (2-3 lines). + + - name: Check decision + id: check + run: | + if [ -f analysis-decision.txt ]; then + echo "decision=$(cat analysis-decision.txt)" >> $GITHUB_OUTPUT + fi + + - name: Create draft PR + if: steps.check.outputs.decision == 'create_pr' + env: + GH_TOKEN: ${{ github.token }} + run: | + ISSUE_NUM="${{ github.event.issue.number }}" + BRANCH="feat/issue-${ISSUE_NUM}" + + git checkout -b "$BRANCH" + git push origin "$BRANCH" + + gh pr create \ + --draft \ + --title "[Draft] Issue #${ISSUE_NUM}: ${{ github.event.issue.title }}" \ + --body "Auto-generated from issue #${ISSUE_NUM}. See issue for requirements." +``` + +--- + +## PR Auto-Review + +AI-powered code review on every pull request. + +### Workflow + +```mermaid +flowchart TD + A[PR Opened/Updated] --> B[AI Reviews Code] + B --> C[Self-Review Findings] + C --> D[Post Review Comment] +``` + +### Workflow YAML + +```yaml +# .github/workflows/pr-review.yml +name: PR Auto-Review + +on: + pull_request: + types: [opened, synchronize] + +permissions: + contents: read + pull-requests: write + +jobs: + review: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Review code + uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + prompt: | + Review pull request #${{ github.event.pull_request.number }}. + + Focus on: + - Security issues (input validation, injection, secrets) + - Bug risks (edge cases, error handling) + - Code quality (clarity, maintainability) + + Post a review comment with findings. Use format: + 🔴 CRITICAL: [issue] - must fix + 🟡 WARNING: [issue] - should consider + ✅ GOOD: [positive observation] + + Be concise. Only flag issues you're confident about. +``` + +--- + +## Dependabot Auto-Merge + +Automatically merge low-risk dependency updates. + +### Flow + +```mermaid +flowchart TD + A[Dependabot PR] --> B{Patch Version?} + B -->|No| C[Require Human Review] + B -->|Yes| D{CI Passes?} + D -->|No| C + D -->|Yes| E[Auto-Merge] +``` + +### Auto-Merge YAML + +```yaml +# .github/workflows/dependabot-auto-merge.yml +name: Dependabot Auto-Merge + +on: + pull_request: + types: [opened, synchronize] + +permissions: + contents: write + pull-requests: write + +jobs: + auto-merge: + if: github.actor == 'dependabot[bot]' + runs-on: ubuntu-latest + steps: + - name: Get Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@v2 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + + - name: Auto-merge patch updates + if: steps.metadata.outputs.update-type == 'version-update:semver-patch' + env: + GH_TOKEN: ${{ github.token }} + run: | + gh pr merge "${{ github.event.pull_request.number }}" \ + --auto \ + --squash \ + --delete-branch +``` + +### Safety Conditions + +Only auto-merge when ALL conditions met: + +- ✅ PR author is `dependabot[bot]` +- ✅ Update is patch version (x.x.PATCH) +- ✅ All CI checks pass +- ✅ No merge conflicts + +For minor/major updates: require human review. + +--- + +## Stale Issue Management + +Clean up inactive issues automatically. + +### Process + +```mermaid +flowchart TD + A[Weekly Schedule] --> B[Find Inactive Issues] + B --> C[Add Stale Label] + C --> D[Wait 7 Days] + D --> E{Activity?} + E -->|Yes| F[Remove Stale Label] + E -->|No| G[Close Issue] +``` + +### Stale YAML + +```yaml +# .github/workflows/stale-issues.yml +name: Stale Issue Management + +on: + schedule: + - cron: '0 0 * * 0' # Weekly on Sunday midnight UTC + workflow_dispatch: # Manual trigger + +permissions: + issues: write + pull-requests: write + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v9 + with: + stale-issue-message: | + This issue has been inactive for 30 days. + It will be closed in 7 days if there's no activity. + Comment to keep it open. + stale-pr-message: | + This PR has been inactive for 14 days. + It will be closed in 7 days if there's no activity. + days-before-stale: 30 + days-before-close: 7 + stale-issue-label: 'stale' + stale-pr-label: 'stale' + exempt-issue-labels: 'pinned,security,bug' + exempt-pr-labels: 'pinned,security' +``` + +--- + +## Required Secrets + +| Secret | Used By | Purpose | +|--------|---------|---------| +| `ANTHROPIC_API_KEY` | Issue-to-PR, PR Review | AI analysis | +| `GITHUB_TOKEN` | All workflows | Repository access (auto-provided) | + +--- + +## Related Patterns + +- [Self-Review Reflection](self-review-reflection.md) - Agent self-review before presenting work +- [Autonomous Quality Enforcement](autonomous-quality-enforcement.md) - Validation loops diff --git a/docs/patterns/multi-agent-code-review.md b/docs/patterns/multi-agent-code-review.md index d641145..d115537 100644 --- a/docs/patterns/multi-agent-code-review.md +++ b/docs/patterns/multi-agent-code-review.md @@ -207,5 +207,5 @@ flowchart LR ## Related Patterns +- [Self-Review Reflection](self-review-reflection.md) - Agent self-reviews before presenting work - [Autonomous Quality Enforcement](autonomous-quality-enforcement.md) - Validation loops and git hooks -- [Process Rules](autonomous-quality-enforcement.md#process-rules) - Agent behavior configuration diff --git a/docs/patterns/self-review-reflection.md b/docs/patterns/self-review-reflection.md new file mode 100644 index 0000000..cfb0553 --- /dev/null +++ b/docs/patterns/self-review-reflection.md @@ -0,0 +1,192 @@ +# Self-Review Reflection + +**Pattern**: Agent reviews its own work before presenting to humans. + +**Problem**: AI agents present work with obvious issues - missing edge cases, security gaps, incomplete reasoning. Users waste time catching problems the agent should have caught itself. + +**Solution**: Build a reflection step into agent workflows. Before presenting any significant work, the agent re-examines its output from a reviewer's perspective, catches issues, and fixes them. Only polished work reaches humans. + +--- + +## Quick Start (2 Minutes) + +Add self-review to any agent prompt: + +```markdown +## Self-Review Protocol + +Before presenting your work: + +1. Re-read your output as if you're a code reviewer +2. Check for: + - Missing edge cases + - Security issues (injection, validation, secrets) + - Incomplete reasoning + - Assumptions that should be stated +3. Fix any issues found +4. Only then present to user + +If you found and fixed issues, briefly note: "Self-review: Fixed [issue]" +``` + +**Done.** Your agent now self-reviews before every response. + +--- + +## How It Works + +```mermaid +flowchart TD + A[Agent Does Work] --> B[Self-Review Check] + B --> C{Issues Found?} + C -->|Yes| D[Fix Issues] + D --> B + C -->|No| E[Present to User] +``` + +### The Reflection Loop + +| Step | Action | Purpose | +|------|--------|---------| +| 1. Complete work | Agent finishes initial task | Get something to review | +| 2. Switch perspective | Agent becomes reviewer | Fresh eyes on own work | +| 3. Identify issues | Check against criteria | Catch obvious problems | +| 4. Fix and re-check | Iterate until clean | Polish before delivery | +| 5. Present | Show work to human | Only quality output seen | + +### What to Check + +**Code-related work:** + +- Edge cases handled? +- Input validation present? +- Error handling complete? +- Security issues (OWASP Top 10)? +- Tests cover the changes? + +**Analysis/planning work:** + +- Reasoning complete? +- Assumptions stated? +- Alternatives considered? +- Risks identified? + +--- + +## Implementation Examples + +### In Agent System Prompts + +```markdown +## Self-Review (Mandatory) + +Before ANY response containing code, analysis, or recommendations: + +1. Pause and re-read your work +2. Ask yourself: + - "What would a senior engineer critique?" + - "What edge case am I missing?" + - "Is this actually correct?" +3. Fix issues before responding +4. Note significant fixes: "Self-review: [what you caught]" +``` + +### In GitHub Actions (Claude Code Action) + +```yaml +- name: Analyze and self-review + uses: anthropics/claude-code-action@v1 + with: + anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} + prompt: | + Analyze issue #${{ github.event.issue.number }}. + + After your analysis: + 1. Write analysis to analysis.txt + 2. Re-read analysis.txt as a reviewer + 3. Check: Did I miss security concerns? Implementation risks? + 4. Update analysis.txt if needed + 5. Write "REVIEW_PASSED=true" to review-status.txt when satisfied +``` + +### In Multi-Step Workflows + +```yaml +# Step 1: Do the work +- name: Generate implementation + id: implement + run: | + # Agent generates code/analysis + ./scripts/generate.sh + +# Step 2: Self-review the work +- name: Self-review + uses: anthropics/claude-code-action@v1 + with: + prompt: | + Review the implementation in ./output/. + + Check for: + - Security vulnerabilities + - Missing error handling + - Edge cases + - Code quality issues + + If issues found: fix them and re-validate. + Write summary to ./output/self-review.txt +``` + +--- + +## When to Use + +| Situation | Self-Review? | Why | +|-----------|--------------|-----| +| Code generation | ✅ Yes | Catches bugs before user sees them | +| Issue analysis | ✅ Yes | Ensures thorough reasoning | +| PR creation | ✅ Yes | Polishes before human review | +| Simple lookups | ❌ No | Overhead not worth it | +| Exploratory chat | ❌ No | Low stakes, fast iteration preferred | + +**Rule of thumb**: Self-review when the output will be acted upon or when mistakes are costly. + +--- + +## Measuring Success + +| Metric | Before | After | How to Measure | +|--------|--------|-------|----------------| +| User-caught issues | 3-5 per task | 0-1 | Count feedback requiring fixes | +| Iteration cycles | 2-3 rounds | 1 round | Track back-and-forth | +| Time to approval | Variable | First try | Measure approval speed | + +### Signs It's Working + +- Users rarely say "you missed X" +- First submission is usually accepted +- Agent notes what it caught: "Self-review: added input validation" + +### Signs It's Not Working + +- Same issues keep slipping through +- Self-review always says "no issues" (not actually checking) +- Review step adds time but not quality + +--- + +## Anti-Patterns + +❌ **Rubber-stamp review**: "Self-review complete, no issues" without actually checking + +❌ **Over-reviewing**: Spending 5 minutes reviewing a 2-line change + +❌ **Review without criteria**: Vague "looks good" instead of specific checks + +❌ **Skipping under pressure**: "No time for self-review" defeats the purpose + +--- + +## Related Patterns + +- [Autonomous Quality Enforcement](autonomous-quality-enforcement.md) - Validation loops for code quality +- [GHA Automation Patterns](gha-automation-patterns.md) - CI/CD workflows using reflection