Skip to content

Instantly share code, notes, and snippets.

@postazure
Created July 22, 2025 05:14
Show Gist options
  • Select an option

  • Save postazure/292099a794ebfaa1298ff6a838121b81 to your computer and use it in GitHub Desktop.

Select an option

Save postazure/292099a794ebfaa1298ff6a838121b81 to your computer and use it in GitHub Desktop.
Claude Config and Context

🧠 AI Coding Agent Guidelines

Core Principles

Please follow these principles when generating or modifying code:

  1. Apply SOLID Principles
    Write modular, maintainable code following:

    • Single Responsibility
    • Open/Closed
    • Liskov Substitution
    • Interface Segregation
    • Dependency Inversion
  2. Make Small, Incremental Changes

    • Limit scope to the task at hand.
    • Avoid broad refactors unless explicitly requested.
  3. Ensure Code is Reviewable

    • Structure changes as if submitting a focused pull request.
    • Include short summaries of the β€œwhat” and β€œwhy”.
  4. Reuse Existing Code and Patterns

    • Integrate with existing functions, components, and utilities.
    • Follow established architectural or stylistic patterns.
    • Don’t reinventβ€”extend what’s already there.
  5. Avoid Unnecessary Changes

    • Don’t rename, reformat, or reorder code without justification.
    • Preserve behavior unless changes are required.
  6. Write Testable Code

    • Ensure code is easy to unit test.
    • Use dependency injection and clear boundaries.
    • Include or suggest tests for new logic.

General Information

Tools

  • av is available on this machine to manage stacked PRs
  • git bisect is a good tool for identifying where specific issue cropped.
  • gh is available on this machine to gain information from github such as PR comments, and actions/workflows

Prohibitions

You are prohibited from the following behaviors:

  • Only make commits on my behalf when explicitly told to by me.
  • Commit messages should not include co-authored-by, they should not mention any AI authorship
  • Only push changes to remote branches when explicitly told to by me.

Additional Considerations

  • Prefer async/await over callbacks
  • Make sure to run tests after adding them
  • Typecheck changes using npx tsgo when available or npm scripts or tsc
  • Lint changes, resolve lint issues you create.

πŸ” Optional: Clarifying Questions

Ask before proceeding if needed:

  • What’s the intended user impact or feature goal?
  • Are there specific files or modules to avoid?
  • Should I follow a specific architecture (e.g., Clean Architecture)?

PR Review Guide for Claude Code

This document provides a comprehensive guide for conducting thorough PR reviews using Claude Code tools, following industry best practices for code review.

Overview

A good PR review should:

  • Identify critical issues that could cause bugs or security problems
  • Suggest improvements for code quality and maintainability
  • Recognize good practices and well-implemented features
  • Provide actionable feedback with specific suggestions
  • Follow a consistent priority system

Step-by-Step PR Review Process

1. Initial PR Analysis

Start by gathering basic PR information:

# Get PR overview, files changed, and metadata
gh pr view <PR_NUMBER> --json title,body,url,author,files

# Get the full diff for detailed analysis
gh pr diff <PR_NUMBER>

What to look for:

  • PR scope and purpose
  • Number and types of files changed
  • Size of changes (additions/deletions)
  • Author and any existing comments

2. Code Analysis Framework

Analyze the code changes using this priority framework:

πŸ”΄ Critical Issues (Must Fix)

  • Type Safety: TypeScript type errors, any usage, incorrect generics
  • Security: Exposed secrets, SQL injection risks, authentication bypasses
  • Runtime Errors: Null pointer exceptions, undefined references
  • Breaking Changes: API changes without migration, removed public methods

🟑 High Priority (Should Fix)

  • Code Quality: Poor error handling, missing validation
  • Readability: Complex logic, unclear naming, poor structure
  • Performance: Inefficient algorithms, memory leaks
  • Configuration: Hardcoded values, missing environment variables
  • Architecture: Violating established patterns, tight coupling

🟒 Medium Priority (Nice to Have)

  • Maintainability: Complex logic, missing documentation
  • Testing: Missing edge cases, testing implementation details
  • Style: Inconsistent formatting, unclear naming
  • Over-engineering: Unnecessary complexity, premature optimization

πŸ”΅ Low Priority/Style

  • Formatting: Missing newlines, consistent spacing
  • Documentation: Outdated comments, typos

3. Conducting the Review

Option A: Draft Review (Recommended)

Create a draft review that you can edit and submit later:

# Create a draft review with overall assessment and line comments
gh api repos/<OWNER>/<REPO>/pulls/<PR_NUMBER>/reviews -X POST \
  --field event=PENDING \
  --field body="## Overall Assessment

[Your assessment of the PR - positive aspects, main concerns, recommendation]

**Recommendation**: [Approve/Request Changes/Needs Discussion]" \
  --field 'comments=[
    {
      "path": "<FILE_PATH>",
      "line": <LINE_NUMBER>,
      "body": "**[Priority]**: [Issue description]\n\n[Detailed explanation and suggested fix]"
    },
    {
      "path": "<FILE_PATH_2>", 
      "line": <LINE_NUMBER_2>,
      "body": "**[Priority]**: [Another issue]\n\n[Explanation and fix]"
    }
  ]'

Advantages of Draft Reviews:

  • All comments are grouped together in one review
  • You can edit comments before submitting
  • Choose final action (Approve/Request Changes/Comment) in web UI
  • Review appears as "pending" until you submit it
  • More professional appearance than individual comments

Option B: Individual Line Comments

For immediate feedback or iterative review process:

gh api repos/<OWNER>/<REPO>/pulls/<PR_NUMBER>/comments -X POST \
  --field body="**[Priority]**: [Issue description]

[Detailed explanation and suggested fix]" \
  --field commit_id="$(gh api repos/<OWNER>/<REPO>/pulls/<PR_NUMBER> --jq '.head.sha')" \
  --field path="<FILE_PATH>" \
  --field line=<LINE_NUMBER>

Note: Individual comments are immediately visible and cannot be easily grouped or edited.

Comment Format Best Practices:

**Critical**: [Clear, specific issue description]

[Explanation of why it's a problem]
[Specific suggestion for fix with code examples if helpful]
**High Priority**: [Issue description]

[Why this matters for maintainability/performance/etc.]
[Recommended approach or alternative]
βœ… **Excellent**: [What was done well]

[Why this is good practice]
[How it benefits the codebase]

4. Code Readability - The Foundation of Quality

Readability is extremely important and should be a primary focus in every PR review. Code is read far more often than it's written, and readable code:

  • Reduces bugs by making logic clear and obvious
  • Speeds up development by helping developers understand code quickly
  • Enables easier maintenance and future modifications
  • Improves team collaboration and knowledge sharing
  • Reduces cognitive load and mental fatigue

Key Readability Issues to Flag:

πŸ”΄ Critical Readability Problems:

  • Misleading names: Variables/functions that don't match their purpose
  • Complex nested logic: Multiple levels of conditionals without clear structure
  • Magic numbers/strings: Hardcoded values without explanation
  • Overly long functions: Methods doing too many things

🟑 High Priority Readability Issues:

  • Unclear variable names: data, item, temp, result without context
  • Poor function organization: Mixing abstraction levels
  • Missing intermediate variables: Complex expressions that should be broken down
  • Inconsistent naming: Different patterns within the same file/module

🟒 Medium Priority Readability Improvements:

  • Missing comments: Complex algorithms without explanation
  • Long parameter lists: Functions with too many arguments
  • Unclear error messages: Generic or unhelpful error text
  • Inconsistent formatting: Mixed indentation, spacing patterns

Readability Comment Templates:

**High Priority**: Variable naming doesn't convey purpose.

`data` and `result` are too generic. Consider more descriptive names like `userPreferences` and `validationResult` to make the code self-documenting.
**Critical**: This function is doing too many things and is hard to follow.

Consider breaking this 50-line function into smaller, focused functions:
- `validateUserInput()`
- `processPayment()`  
- `updateUserAccount()`

Each function should have a single, clear responsibility.
**High Priority**: Complex conditional logic is hard to parse.

Consider extracting boolean expressions to well-named variables:
```javascript
// Instead of:
if (user.age >= 18 && user.hasValidId && !user.isBlocked && user.subscription.active)

// Use:
const isEligibleUser = user.age >= 18 && user.hasValidId && !user.isBlocked
const hasActiveSubscription = user.subscription.active
if (isEligibleUser && hasActiveSubscription)

5. Review Categories and Common Issues

Backend/API Reviews

  • Security: Authentication, authorization, input validation
  • Performance: Database queries, caching, async operations
  • Error Handling: Proper exception handling, meaningful error messages
  • API Design: RESTful patterns, consistent response formats
  • Configuration: Environment variables, secrets management

Frontend/Mobile Reviews

  • Type Safety: TypeScript usage, prop types, form validation
  • Performance: Component re-renders, bundle size, lazy loading
  • User Experience: Accessibility, error states, loading states
  • State Management: Proper state updates, side effects
  • Platform Considerations: iOS/Android differences, responsive design

Testing Reviews

  • Coverage: Critical paths tested, edge cases covered
  • Quality: Testing behavior vs implementation, clear test names
  • Maintainability: Test data setup, mocking strategies
  • Performance: Test execution speed, database cleanup

Documentation Reviews

  • Accuracy: Code matches documentation
  • Completeness: All public APIs documented
  • Clarity: Examples provided, common pitfalls mentioned
  • Maintenance: Docs will stay up-to-date

5. Comment Templates

Critical Issues

**Critical**: [Type safety/Security/Runtime error] issue description.

Problem: [What could go wrong]
Fix: [Specific solution]

High Priority Issues

**High Priority**: [Configuration/Performance/Architecture] concern.

Impact: [Why this matters]
Recommendation: [Better approach]

Positive Feedback

βœ… **Excellent**: [What was implemented well]

Great job with:
- [Specific good practice 1]
- [Specific good practice 2]  
- [How it benefits the codebase]

Questions/Suggestions

**Question**: [Clarification needed]

Could you explain the reasoning behind [decision]? 
Alternative approach: [suggestion]

6. Review Quality Checklist

Before submitting review:

  • Balanced feedback: Mix of critical issues, improvements, and positive recognition
  • Actionable suggestions: Each comment provides clear next steps
  • Priority levels: Issues categorized by importance
  • Code examples: Complex suggestions include code snippets
  • Context awareness: Considers existing codebase patterns
  • Respectful tone: Professional and constructive language

7. Common Tool Usage Patterns

Multiple Comments in Sequence

# Add multiple line comments for different issues
gh api repos/OWNER/REPO/pulls/PR_NUMBER/comments -X POST --field body="..." --field commit_id="..." --field path="..." --field line=N
gh api repos/OWNER/REPO/pulls/PR_NUMBER/comments -X POST --field body="..." --field commit_id="..." --field path="..." --field line=M
# etc.

Getting Commit SHA for Comments

# Get the latest commit SHA for the PR branch
gh api repos/OWNER/REPO/pulls/PR_NUMBER --jq '.head.sha'

Checking for Existing Comments

# See if there are already comments to avoid duplication
gh pr view PR_NUMBER --json comments

Example Review Workflows

Draft Review Workflow (Recommended)

# 1. Get PR info
gh pr view 56 --json title,body,files
gh pr diff 56

# 2. Analyze changes and identify issues
# [Manual code analysis using diff output]

# 3. Create draft review with all comments at once
gh api repos/postazure/CoTask/pulls/56/reviews -X POST \
  --field event=PENDING \
  --field body="## Overall Assessment

This is a well-implemented feature with excellent test coverage and documentation. Main concerns are around TypeScript type safety and configuration management.

**Recommendation**: Address the TypeScript issues before merging - otherwise looks great! πŸš€" \
  --field 'comments=[
    {
      "path": "apps/mobile/src/components/form/TextField.tsx",
      "line": 143,
      "body": "**Critical**: The forwardRef generic type signature loses type safety completely.\n\nCurrent code uses `any` which removes all type checking. Consider using a different pattern that preserves the generic type parameter."
    },
    {
      "path": "apps/api/src/well-known/well-known.controller.ts", 
      "line": 10,
      "body": "**High Priority**: Hardcoded Team ID should be moved to environment variable.\n\nConsider moving `ZBQMW5JHMN.com.postazure.cotask` to environment variables for better configuration management across environments."
    },
    {
      "path": "apps/api/test/integration/well-known/well-known.e2e-spec.ts",
      "line": 22, 
      "body": "βœ… **Excellent**: Comprehensive test coverage with both unit and integration tests.\n\nGreat job covering all important aspects:\n- JSON structure validation\n- Content-Type headers\n- App identifier format validation\n- Public accessibility (crucial for iOS verification)"
    }
  ]'

# 4. Review is now created as draft - you can:
# - View it in GitHub web UI
# - Edit comments and overall assessment
# - Add/remove comments
# - Choose final action (Approve/Request Changes/Comment)
# - Submit when ready

Individual Comments Workflow

# 1. Get PR info  
gh pr view 56 --json title,body,files
gh pr diff 56

# 2. Add overall comment
gh pr review 56 --comment --body "Overall assessment..."

# 3. Add specific line comments one by one
gh api repos/owner/repo/pulls/56/comments -X POST \
  --field body="**Critical**: TypeScript issue..." \
  --field commit_id="$(gh api repos/owner/repo/pulls/56 --jq '.head.sha')" \
  --field path="src/file.ts" \
  --field line=143

# 4. Continue with other issues...

Working with Draft Reviews

# List all reviews for a PR (including drafts)
gh api repos/OWNER/REPO/pulls/PR_NUMBER/reviews

# Get specific draft review details
gh api repos/OWNER/REPO/pulls/PR_NUMBER/reviews/REVIEW_ID

# Submit a draft review (via web UI is easier, but possible via API)
gh api repos/OWNER/REPO/pulls/PR_NUMBER/reviews/REVIEW_ID/events -X POST \
  --field event=COMMENT  # or APPROVE or REQUEST_CHANGES

Best Practices Summary

  1. Readability First: Always prioritize code readability - it's the foundation of maintainable software
  2. Start Positive: Acknowledge good work before diving into issues
  3. Prioritize Correctly: Focus reviewer attention on critical issues first
  4. Be Specific: Provide exact line numbers and concrete suggestions
  5. Include Examples: Show code snippets for complex fixes, especially for readability improvements
  6. Consider Context: Understand existing patterns and constraints
  7. Balance Feedback: Mix criticism with recognition
  8. Stay Professional: Constructive, respectful, and educational tone
  9. Think Like a Reader: Ask "Will someone understand this code in 6 months?" for every review

This approach ensures thorough, helpful PR reviews that improve code quality while maintaining positive team dynamics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment