This file provides Claude Code with context about the Prfect project to enhance development assistance.
Prfect is a CLI tool that generates professional pull request descriptions using local AI models via Ollama. It analyzes git commits, file changes, and code diffs to create structured PR descriptions automatically.
The codebase has been refactored into a modular architecture with utility classes for better testability and maintainability:
PRGenerator Class (index.ts)
- Main orchestration class that coordinates all utilities
- Handles CLI interaction, logging, and user prompts
- Delegates specific tasks to utility classes
- Methods:
run(),checkOllamaSetup(),generatePRMessage(),saveToFile()
GitAnalyzer (src/utils/GitAnalyzer.ts)
- Handles all git repository operations
- Methods:
isGitRepo(),getCurrentBranch(),detectDefaultBranch(),getCommitsInfo() - Manages git command execution with proper error handling
- Supports branch detection and commit analysis
- Utility methods:
getFileChanges(),getCodeSample(),getMergeBase()
OllamaClient (src/utils/OllamaClient.ts)
- Manages all Ollama API communication
- Methods:
getAvailableModels(),generate(),testConnection(),generatePRMessage() - Handles timeouts, retries, and response validation
- Includes specialized PR message generation with templates
- Host validation and model availability checking
OutputProcessor (src/utils/OutputProcessor.ts)
- Processes AI responses and handles output formatting
- Key method:
processResponse()- strips<think>.*?</think>tags using regex withgisflags - Utility methods:
generateFilename(),limitLines(),formatContent() - Thinking tag detection and extraction capabilities
- File validation and content formatting
TemplateLoader (src/utils/TemplateLoader.ts)
- Handles custom PR template loading and processing
- Methods:
loadTemplate(),generatePromptWithTemplate(),validateTemplate() - Smart detection priority system with multiple fallback paths
- GitHub standard template auto-detection
- Template validation and prompt generation integration
- Mono-repo support with directory tree traversal
- Central export file for easy importing of all utilities
- Provides TypeScript interfaces and type definitions
- Enables clean imports:
import { GitAnalyzer, OutputProcessor, OllamaClient, TemplateLoader } from './src/utils' - Exports TemplateConfig interface for template configuration
- Raw Response: Ollama returns JSON with
responsefield - Thinking Strip: OutputProcessor removes
<think>.*?</think>tags using regex withgisflags - Emoji Control: Conditionally includes emojis based on
noEmojisflag - File Output: Optional markdown file generation with timestamps via OutputProcessor
Adding new options requires updates in 3 places:
program.option()orprogram.argument()- CLI flag/argument definitionrun()method signature - TypeScript interfacegenerator.run()call - Passing options through
Prfect supports adding custom context to the AI prompt for enhanced PR descriptions:
# Add context about ticket numbers and background
prfect "This was a big refactor that addressed Linear ticket BE-123. Follow up for BE-124 coming soon but non blocking" --no-emoji
# Context with other options
prfect "Fixes critical bug from user reports" --source feature/bugfix --target main --model qwen3:latest
# Context in CI mode
prfect "Implements OAuth integration per security requirements" --ci --source feature/oauth --target main- Additional Information: Provide ticket numbers, background context, or motivation
- Template Integration: Context is automatically included in both custom templates and default prompts
- AI Enhancement: Helps the LLM understand business context not visible in code changes
- Flexible Usage: Works with all existing CLI options and modes
The --ci flag enables CI mode for automated workflows like GitHub Actions:
- Silent Operation: Suppresses all log messages and interactive prompts
- JSON Output: Outputs structured JSON with
title,body,source_branch, andtarget_branch - GitHub Actions Compatible: Designed for easy parsing in bash scripts and workflows
- Error Handling: Still throws errors for invalid git repos or Ollama connectivity issues
prfect --ci --source feature/branch --target main --model qwen3:latest{
"title": "Add user authentication system",
"body": "Implements JWT authentication with proper validation and error handling.",
"source_branch": "feature/auth",
"target_branch": "main"
}- name: Generate PR Description
run: |
PR_DATA=$(prfect --ci --source ${{ github.head_ref }} --target main)
TITLE=$(echo "$PR_DATA" | jq -r '.title')
BODY=$(echo "$PR_DATA" | jq -r '.body')
gh pr create --title "$TITLE" --body "$BODY"Prfect supports custom PR templates to match your team's workflow and requirements.
- Explicit path:
--template-path custom/template.md - GitHub standard:
.github/pull_request_template.md - Alternative naming:
.github/PULL_REQUEST_TEMPLATE.md - Docs location:
docs/pull_request_template.md - Default built-in: Fallback template
# Use custom template
prfect --template-path .github/custom_template.md
# Auto-detect GitHub template (default behavior)
prfect
# Specify source and target with template
prfect --source feature/auth --target main --template-path team_template.md- Mono-repo Support: Searches up directory tree for templates
- Validation: Checks template structure and content
- GitHub Integration: Works seamlessly with GitHub Actions
- Fallback Handling: Uses default if template not found
Templates should include common sections like:
## Summaryor## Overview## Type of Change(with checkboxes)## Key Changes## How has this been tested?## Breaking Changes(optional)
Example template structure:
## Summary
[Brief description of changes]
## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update
## Key Changes
-
-
## How has this been tested?
- [ ] Unit tests pass
- [ ] Manual testing completed- Git Errors: GitAnalyzer wraps commands in try/catch with descriptive messages
- Network Errors: OllamaClient detects timeouts via
error.name === "TimeoutError" - Model Errors: OllamaClient validates model existence before generation
- Repository Validation: GitAnalyzer checks for git repo and branch existence
--show-thinking: OutputProcessor preserves AI reasoning in output- Colored logging with chalk: info (green), warn (yellow), error (red)
- OllamaClient provides detailed connection diagnostics
- Bun Test: Uses Bun's built-in test runner for fast, native TypeScript testing
- No Additional Dependencies: Leverages Bun's testing utilities without external frameworks
- Test Commands: Run tests with
bun testorbun test --watchfor development
test/index.test.ts: Tests OutputProcessor and GitAnalyzer utilities directlytest/ollama.test.ts: Tests OllamaClient with mocked fetch responsestest/cli.test.ts: Tests CLI option parsing and validationtest/template.test.ts: Tests TemplateLoader functionality and template processing
- Feature Parity: Every new feature MUST have matching unit tests
- Method Coverage: Each public method in utility classes requires test coverage
- Edge Cases: Tests must cover error conditions, empty inputs, and boundary cases
- Mocking Strategy: Use Bun's mocking capabilities for external dependencies (git, fetch)
- Unit Testing: Each utility class can be imported and tested independently
- Mocking: OllamaClient allows proper API mocking for reliable tests with Bun's mock utilities
- Validation: OutputProcessor regex patterns tested with various inputs
- Coverage: Git command construction logic validated without actual git calls
- Fast Execution: Bun's native test runner provides rapid feedback during development
- Update default in PRGenerator
run()method - Update CLI option description and README examples
- Test model compatibility with thinking tags using OutputProcessor
- Update OllamaClient if new API patterns needed
- Modify prompt template in OllamaClient
generatePRMessage() - Extend OutputProcessor for new formatting requirements
- Add new processing methods to OutputProcessor utility
- Extend GitAnalyzer with new git command wrappers
- Add new methods to CommitInfo interface
- Handle edge cases (empty repos, single commits) in GitAnalyzer
- Implement retry logic in OllamaClient
- Add fallback models in OllamaClient configuration
- Improve git error diagnostics in GitAnalyzer
- Identify which utility class should handle the feature
- Add methods to appropriate utility class with proper TypeScript typing
- Write Tests First: Create unit tests for new methods using Bun's test utilities
- Update main PRGenerator to use new utility methods
- Verify Test Coverage: Ensure all new code paths are tested with
bun test - Update this CLAUDE.md documentation
- Test-Driven Development: Write tests before implementing features when possible
- Bun Test Syntax: Use
import { test, expect, mock } from 'bun:test'for testing utilities - Mock External Calls: Mock git commands, API calls, and file system operations
- Assert Behavior: Test both success and failure scenarios for robust coverage
- CI Mode Testing: Include tests for JSON output format and silent operation behavior
- Use
--show-thinkingflag to see AI reasoning process - Check OllamaClient connection with
testConnection()method - Validate git operations with GitAnalyzer methods
- Test output processing with OutputProcessor utilities
prfect/
├── index.ts # Main PRGenerator class
├── .github/
│ └── pull_request_template.md # Sample GitHub PR template
├── src/utils/
│ ├── index.ts # Utility exports
│ ├── GitAnalyzer.ts # Git operations
│ ├── OllamaClient.ts # AI communication
│ ├── OutputProcessor.ts # Response processing
│ └── TemplateLoader.ts # Custom template handling
├── test/
│ ├── index.test.ts # Core utility tests (Bun test runner)
│ ├── ollama.test.ts # API communication tests (Bun test runner)
│ ├── cli.test.ts # CLI option tests (Bun test runner)
│ └── template.test.ts # Template functionality tests (Bun test runner)
├── package.json # Includes bun test scripts
└── CLAUDE.md # This documentation
bun test: Run all tests oncebun test --watch: Run tests in watch mode during developmentbun test <file>: Run specific test filebun test --coverage: Generate test coverage report (if configured)
✅ Testable: Each utility class can be imported and tested independently
✅ Maintainable: Clear separation of concerns between git, AI, and output processing
✅ Extensible: Easy to add new features to specific utility classes
✅ Type-Safe: Full TypeScript support with proper interfaces
✅ Reusable: Utility classes can be used in other projects or contexts