@gonzui/claude-pattern-lang
v1.3.0
Published
CLI tool for automatically extracting and cataloging patterns from Claude Code session logs
Maintainers
Readme
claude-pattern-lang
日本語 | English
A CLI tool to automatically extract and catalog patterns from Claude Code session logs. It captures effective approaches as a pattern language that Claude can reference, enabling faster task completion and more consistent code quality in future sessions.
Overview
claude-pattern-lang analyzes your Claude Code session logs to identify reusable patterns—effective prompt structures, problem-solving approaches, and project-specific idioms. These patterns are automatically cataloged and synced to your CLAUDE.md, making them available to Claude in subsequent sessions.
Why Pattern Language?
- Faster Task Completion: Patterns guide Claude to solutions directly, reducing conversation turns by ~35%
- Consistent Code Quality: Templates ensure uniform coding style and reduce code volume by ~44%
- Reusable Solutions: Capture effective approaches for future use
- Automatic Discovery: No manual documentation required
Validation Results: In testing, projects with patterns completed API implementation tasks in 9 turns vs 14 turns without patterns, producing 39 lines of consistent code vs 69 lines of ad-hoc implementation. See validation report for details.
Features
- Automatic Pattern Extraction: LLM-powered analysis of session logs
- Pattern Catalog Management: Store and organize patterns in YAML format
- CLAUDE.md Sync: Automatically integrate patterns into Claude's context
- Claude Code Skills Export: Export patterns as on-demand Skills to save context
- Usage Scoring & Pruning: Measure which patterns are actually used and clean up unused ones
- Claude Code Hooks: Seamless integration with session lifecycle
- Duplicate Detection: Automatic deduplication and merging
- Privacy Protection: Automatic masking of sensitive information
- Incremental Analysis: Only analyze new sessions since last run
- Multi-LLM Support: Claude Code (default, no API key required), Anthropic, OpenAI, Gemini, Ollama, DeepSeek
Installation
Global Install
npm install -g @gonzui/claude-pattern-langLocal Install
npm install
npm run buildRequirements
- Node.js >= 18.0.0
- macOS, Linux, or Windows (WSL supported)
Usage
Initialize
Set up the tool for the first time:
cpl initThis creates the configuration directory and installs Claude Code hooks.
Analyze Sessions
Extract patterns from your session logs:
# Analyze all recent sessions
cpl analyze
# Analyze a specific session
cpl analyze --session <session-id>
# Analyze sessions since a date
cpl analyze --since 2024-01-01
# Analyze sessions for a specific project
cpl analyze --project /path/to/projectNote: The
analyzecommand calls the LLM API for each session to extract patterns. Token consumption increases with the number of sessions analyzed. You can monitor usage withcpl metrics.
List Patterns
Browse your pattern catalog:
# List all patterns
cpl list
# Filter by type
cpl list --type prompt
# Search by keyword
cpl list --search "error handling"
# Output as JSON
cpl list --jsonShow Pattern Details
View a specific pattern:
cpl show <pattern-name>Sync to CLAUDE.md
Update your project's CLAUDE.md with cataloged patterns:
# Sync to current project
cpl sync
# Sync to specific project
cpl sync --project /path/to/project
# Preview changes without writing
cpl sync --dry-run
# Sync to global CLAUDE.md
cpl sync --globalHow Sync Works
The sync command creates two files:
patterns.md - Contains the actual pattern content
- Project local:
{project}/.claude/patterns.md - Global (
--global):~/.claude-patterns/patterns.md
- Project local:
CLAUDE.md - Contains an
@reference to patterns.md<!-- CPL:PATTERNS:START --> @.claude/patterns.md <!-- CPL:PATTERNS:END -->
This approach keeps CLAUDE.md clean and allows patterns to be managed independently. Claude Code's @ import feature automatically loads the pattern content.
Export as Claude Code Skills
Export patterns as Claude Code Skills instead of loading them all into context via patterns.md. Skills are loaded on demand — Claude reads each skill's description and loads the full content only when relevant, keeping your context window lean even with a large pattern catalog.
# Export all patterns as Skills to the current project
cpl export --skills
# Export specific patterns only (ID can be shortened)
cpl export <pattern-id> --skills
# Export to a specific project
cpl export --skills --project /path/to/project
# Export to personal skills (~/.claude/skills)
cpl export --skills --global
# Preview generated files without writing
cpl export --skills --dry-run
# Write without confirmation
cpl export --skills --forceHow Export Works
Each pattern becomes a skill directory containing a SKILL.md:
{project}/.claude/skills/
└── <pattern-name>/
└── SKILL.md # frontmatter (name, description) + pattern contentThe skill's description is generated from the pattern's context, problem, and tags, so Claude can decide when to load it.
sync vs export:
| Aspect | cpl sync | cpl export --skills |
|--------|-----------|----------------------|
| Loading | Always in context (via @patterns.md) | On demand (Skills) |
| Context cost | Grows with catalog size | Near-constant (descriptions only) |
| Best for | Small catalogs, always-relevant rules | Large catalogs, situational patterns |
Measure Pattern Usage
Scan your Claude Code session logs to see which patterns are actually mentioned in conversations:
# Score patterns against current project's sessions
cpl score
# Scan all projects / since a date
cpl score --all
cpl score --since 2026-01-01
# Output as JSON / persist usage counts to the catalog
cpl score --json
cpl score --saveThe scan counts pattern-name mentions in user and assistant messages only. Tool outputs and <system-reminder> blocks are excluded, so reading patterns.md itself doesn't inflate the counts.
Prune Unused Patterns
Remove patterns that never appear in your sessions:
# Preview prune candidates
cpl prune --dry-run
# Remove patterns used fewer than 3 times
cpl prune --min-uses 3
# Remove without confirmation
cpl prune --forceAfter pruning, run cpl sync / cpl export to update the synced files.
Deduplicate Similar Patterns
Detect semantically similar patterns and merge them with LLM assistance:
# Preview merge proposals
cpl dedupe --dry-run
# Merge interactively (confirm each pair)
cpl dedupe
# Merge all judged duplicates without confirmation
cpl dedupe --force
# Tune candidate detection
cpl dedupe --threshold 0.5 --limit 5Candidate pairs are first filtered by lexical similarity, then the configured LLM judges whether each pair is a true semantic duplicate and proposes a merged pattern.
Share Patterns with Your Team
Export patterns to a portable YAML file and import them on another machine:
# Export all patterns (or specific IDs) to a shareable file
cpl export --output team-patterns.yaml
cpl export a1b2c3d4 --output team-patterns.yaml
# Import from a file or URL
cpl import team-patterns.yaml
cpl import https://example.com/team-patterns.yaml
# Preview / update existing same-name patterns
cpl import team-patterns.yaml --dry-run
cpl import team-patterns.yaml --overwriteShared files contain only the pattern content (no local IDs, timestamps or usage stats). On import, patterns with an existing name are skipped unless --overwrite is given.
Automatic Analysis (Hooks)
With Claude Code hooks installed, cpl can run the whole loop automatically. Enable it in ~/.claude-patterns/config.yaml:
analysis:
auto_analyze: true
sync:
auto_sync: true # optional: auto-sync extracted patterns to CLAUDE.mdThe SessionEnd hook queues finished sessions, and the Stop hook analyzes queued sessions in the background (up to 3 per run) and syncs the results.
Manage Patterns
Manually add or remove patterns:
# Add a pattern interactively
cpl add
# Create a pattern interactively (alias for add -i)
cpl create
# Add from YAML file
cpl add --file pattern.yaml
# Remove a pattern
cpl remove <pattern-name>Analytics
There are two analytics commands with different purposes:
cpl session - Claude Code Session Analysis
Analyzes token usage from Claude Code's conversation logs. Use this to understand how efficiently Claude Code is using context in your sessions.
# Analyze latest session for current project
cpl session
# Analyze all sessions for current project
cpl session --all
# Analyze sessions for a specific project
cpl session --project /path/to/project
# Analyze a specific session file
cpl session ~/.claude/projects/.../session-id.jsonlOutput includes:
- Message count (conversation turns)
- Input/Output tokens
- Cache creation/read tokens
- Cache efficiency percentage
cpl metrics - CPL Tool Usage Metrics
Tracks usage statistics for the cpl tool itself (e.g., when running cpl analyze). Use this to monitor your pattern extraction activity.
# Show metrics history and statistics
cpl metrics
# Show statistics only
cpl metrics --stats
# Show statistics for last 30 days
cpl metrics --days 30
# Clear all metrics
cpl metrics --clearKey differences:
| Aspect | cpl session | cpl metrics |
|--------|---------------|---------------|
| Target | Claude Code conversations | cpl tool usage |
| Data source | ~/.claude/projects/**/*.jsonl | ~/.claude-patterns/metrics.yaml |
| Purpose | Analyze session efficiency | Track pattern extraction activity |
| Tokens tracked | Claude Code's LLM calls | cpl's LLM calls (during analyze) |
Pattern Types
Prompt Patterns (prompt)
Effective prompt structures and techniques that produce good results:
- Specific phrasing that elicits better responses
- Framework structures for complex requests
- Context-setting patterns
Solution Patterns (solution)
Repeatable problem-solving approaches:
- Debugging and investigation procedures
- Common problem resolutions
- Architectural decision patterns
Code Patterns (code)
Project-specific coding idioms:
- Recurring code structures
- Template conventions
- Framework-specific patterns
Configuration
The configuration file is located at ~/.claude-patterns/config.yaml:
version: 1
llm:
# LLM provider: claude-code | anthropic | openai | gemini | ollama | deepseek
provider: claude-code
# Model to use
model: claude-opus-4-20250514
# API key environment variable (not needed for claude-code / ollama)
api_key_env: ""
# Custom endpoint (for ollama etc.)
# base_url: http://localhost:11434
analysis:
# Auto-analyze on session end
auto_analyze: false
# Minimum message count for analysis
min_session_length: 5
# Patterns to exclude (glob)
exclude_patterns: []
sync:
# Auto-sync to CLAUDE.md after analysis
auto_sync: false
# Target projects for sync (glob)
target_projects: []Supported LLM Providers
Switch providers interactively with cpl config --provider, or edit config.yaml directly:
| Provider | Default model | API key env var | Notes |
|----------|---------------|-----------------|-------|
| claude-code | claude-code | (not required) | Default. Uses your local Claude Code CLI |
| anthropic | claude-sonnet-4-20250514 | ANTHROPIC_API_KEY | |
| openai | gpt-4o | OPENAI_API_KEY | base_url for OpenAI-compatible endpoints |
| gemini | gemini-2.0-flash | GEMINI_API_KEY | |
| ollama | llama3.1 | (not required) | Local models. base_url defaults to http://localhost:11434 |
| deepseek | deepseek-chat | DEEPSEEK_API_KEY | |
If the configured provider's API key is missing, cpl automatically falls back to Claude Code (disable with CPL_DISABLE_FALLBACK=1).
Directory Structure
After installation, the following structure is created:
~/.claude-patterns/
├── config.yaml # Global configuration
├── patterns.yaml # Pattern catalog
├── patterns.md # Synced patterns (global, for --global sync)
├── prompts/ # Custom prompt templates
│ └── extract.txt
└── cache/
├── sessions.yaml # Analyzed session cache
└── queue.yaml # Analysis queueProject-specific structure (after running cpl sync):
{project}/
├── .claude/
│ ├── patterns.yaml # Project-specific patterns (optional)
│ └── patterns.md # Synced patterns (referenced by CLAUDE.md)
└── CLAUDE.md # Contains @.claude/patterns.md referenceDevelopment
Setup
# Clone the repository
git clone https://github.com/yourusername/claude-pattern-lang.git
cd claude-pattern-lang
# Install dependencies
npm install
# Build
npm run build
# Run tests
npm testScripts
| Command | Description |
|---------|-------------|
| npm run build | Build the project |
| npm run dev | Build in watch mode |
| npm run lint | Lint source code |
| npm run lint:fix | Fix linting issues |
| npm run format | Format code with Prettier |
| npm run format:check | Check code formatting |
| npm test | Run unit tests |
| npm run test:run | Run tests once |
| npm run test:e2e | Run E2E tests |
| npm run test:all | Run all tests |
| npm run typecheck | Run TypeScript type checking |
Tech Stack
- Runtime: Node.js 18+ with TypeScript
- CLI: commander.js
- LLM SDKs: @anthropic-ai/sdk, openai, ollama
- YAML: js-yaml
- Testing: Vitest
- Build: tsup
Testing
Running Tests
# Run unit tests
npm test
# Run tests once (without watch mode)
npm run test:run
# Run E2E tests
npm run test:e2e
# Run all tests (unit + E2E)
npm run test:all
# Run tests with coverage
npm run test:run -- --coverageTest Structure
tests/
├── unit/ # Unit tests
│ ├── *.test.ts # Individual test files
│ └── commands/ # Command-specific tests
├── e2e/ # End-to-end tests
│ ├── commands/ # E2E command tests
│ ├── integration/ # Integration flow tests
│ └── errors/ # Error handling tests
├── test_data/ # Test data fixtures
│ ├── sessions/ # Sample session logs (JSONL)
│ └── patterns/ # Expected patterns (YAML)
└── fixtures/ # Additional test fixtures
└── sessions/ # Legacy fixturesTest Data
Test sessions and expected patterns are stored in tests/test_data/:
tests/test_data/
├── sessions/ # Session logs for testing
│ ├── test-session-with-patterns.jsonl
│ ├── code-pattern-session.jsonl
│ ├── empty-session.jsonl
│ └── prompt-pattern-session.jsonl
└── patterns/ # Expected extracted patterns
├── expected-patterns.yaml
├── react-form-pattern.yaml
├── debugging-pattern.yaml
└── empty-patterns.yamlWriting Tests
- Unit Tests: Test individual functions and classes
// Example unit test
import { describe, it, expect } from 'vitest';
import { extractPatterns } from '@/core/analyzer';
describe('Pattern Extractor', () => {
it('should extract patterns from session', async () => {
const session = loadTestSession('test-session.jsonl');
const patterns = await extractPatterns(session);
expect(patterns).toHaveLength(3);
});
});- E2E Tests: Test complete command flows
// Example E2E test
import { describe, it, expect } from 'vitest';
import { execSync } from 'child_process';
describe('CLI: list command', () => {
it('should list all patterns', () => {
const output = execSync('cpl list', { encoding: 'utf-8' });
expect(output).toContain('Patterns:');
});
});- Using Test Data
import { readFileSync } from 'fs';
import { join } from 'path';
function loadTestSession(filename: string) {
const path = join(__dirname, '../test_data/sessions', filename);
return readFileSync(path, 'utf-8');
}Adding Sample Patterns
Sample Pattern Library
The sample/ directory contains reusable patterns that serve as both examples and a library for common scenarios:
sample/
├── README.md # Sample patterns guide
└── patterns/
├── coding-patterns.yaml # Coding best practices
├── tool-usage-patterns.yaml # Claude Code tool usage
├── debugging-patterns.yaml # Debugging approaches
├── effective-prompts.yaml # Effective prompting techniques
└── architecture-patterns.yaml # Software architecture patternsCreating New Sample Patterns
Choose the appropriate file based on pattern type:
coding-patterns.yaml- Code conventions and idiomstool-usage-patterns.yaml- Claude Code workflow patternsdebugging-patterns.yaml- Problem-solving approacheseffective-prompts.yaml- Prompt engineering techniquesarchitecture-patterns.yaml- Design patterns
Follow the pattern structure:
patterns:
- name: pattern-name # Unique identifier (kebab-case)
type: prompt | solution | code # Pattern type
context: When to use this pattern
solution: How to solve the problem
example: | # Code example OR
your code here
example_prompt: "Your prompt here" # Prompt example
tags: [tag1, tag2, tag3] # For searchability
notes: Additional context (optional)Pattern types:
prompt: Effective prompt structures for requesting work from Claudesolution: Repeatable problem-solving approaches and debugging methodscode: Reusable code templates and idioms
Example: Adding a new pattern
# In coding-patterns.yaml
- name: error-boundary-react
type: code
context: Reactでエラー境界を実装する場合
solution: Error Boundaryコンポーネントで子コンポーネントのエラーをキャッチ
example: |
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error('Error caught:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
tags: [react, error-handling, typescript]Pattern Guidelines
- Name: Use kebab-case, descriptive and concise
- Context: Clearly describe when the pattern applies
- Solution: Explain the approach, not just the code
- Example: Provide complete, runnable examples
- Tags: Include relevant tags for discoverability
- Language: Write patterns in your project's language
Using Sample Patterns
Sample patterns can be:
- Referenced when creating project-specific patterns
- Imported directly into your pattern catalog
- Used as templates for custom patterns
- Shared with your team as coding standards
License
MIT © [Your Name]
For more details, see spec.md for the complete specification.
