pattern-recognition
Systematic methodology for identifying, capturing, and documenting reusable patterns from implementations. Enables automatic learning and knowledge-core.md updates. Claude invokes this after successful implementations to preserve institutional knowledge.
git clone --depth 1 https://github.com/VAMFI/claude-user-memory /tmp/pattern-recognition && cp -r /tmp/pattern-recognition/.claude/skills/pattern-recognition ~/.claude/skills/pattern-recognitionskill.md
# Pattern Recognition Skill
This skill provides systematic methodology for identifying reusable patterns from completed work and automatically updating the knowledge core to preserve institutional knowledge across sessions.
## When Claude Should Use This Skill
Claude will automatically invoke this skill when:
- Implementation successfully completed (tests passing)
- @code-implementer finishes major feature work
- Chief-architect synthesizes results from multiple agents
- User explicitly requests pattern documentation
- Stop hook triggers (end of session)
## Core Principles (BRAHMA Constitution)
1. **Knowledge preservation** - Capture patterns for future use
2. **Reproducibility** - Document enough detail to replicate pattern
3. **Simplicity** - Extract essential pattern, not every detail
4. **Verification** - Patterns should be validated by actual code
5. **Adaptive learning** - Learn from outcomes to suggest proven patterns (NEW v3.1)
## Before Implementation (Pattern Suggestion - NEW v3.1)
**Trigger**: User requests feature implementation via /workflow, /implement, or direct agent invocation
**Purpose**: Leverage past implementation success to accelerate current work by suggesting proven patterns proactively
### Pattern Suggestion Workflow
**Step 1: Context Extraction** (< 5 seconds)
Extract context tags from user request to find similar past implementations:
- **Technology keywords**: "nodejs", "python", "redis", "postgresql", "express", "fastapi"
- **Problem domain**: "authentication", "caching", "logging", "error-handling", "validation"
- **Solution type**: "service-layer", "repository", "factory", "middleware", "api"
**Example**:
```
User request: "Add JWT authentication to Express API"
Extracted tags: ["nodejs", "express", "authentication", "jwt", "security"]
```
**Step 2: Pattern Lookup** (< 2 seconds)
```markdown
Read ~/.claude/data/pattern-index.json
Find patterns with ≥60% context tag overlap (similarity matching)
Filter to HIGH confidence patterns only (confidence ≥ 0.80)
Rank by: confidence DESC, quality DESC, recency DESC
Return top 3 patterns
```
**Graceful Degradation**:
```python
try:
pattern_index = read_json('~/.claude/data/pattern-index.json')
suggestions = suggest_patterns(context_tags, pattern_index)
except (FileNotFoundError, JSONDecodeError):
logger.warning("pattern-index.json unavailable, skipping suggestions")
suggestions = [] # Proceed without suggestions
# User impact: ZERO (workflow continues normally)
```
**Step 3: Present Suggestions** (user interaction)
If HIGH confidence patterns found, show top 3:
```markdown
💡 Suggested patterns based on past implementations:
1. [HIGH CONFIDENCE: 92%] JWT Authentication Middleware Pattern
- Used 8 times, 7 successes (88% success rate)
- Average time: 12 minutes, Average quality: 89/100
- Context match: 85% similar to your request
- See: knowledge-core.md#jwt-authentication-middleware-pattern
2. [HIGH CONFIDENCE: 85%] Token Refresh Pattern
- Used 5 times, 4 successes (80% success rate)
- Average time: 15 minutes, Average quality: 85/100
- See: knowledge-core.md#token-refresh-pattern
Use suggested pattern? (y/n/view)
```
**Step 4: User Response Handling**
- **User accepts (y)**: Track acceptance, use pattern in implementation
- **User rejects (n)**: Track rejection, proceed without pattern
- **User views (view)**: Show full pattern from knowledge-core.md, ask again
- **No response**: Proceed without pattern (don't block workflow)
**Step 5: Record User Feedback**
Update pattern acceptance tracking in pattern-index.json:
```json
{
"user_acceptance_rate": (accepted_count + 1) / (total_suggestions + 1),
"total_suggestions": total_suggestions + 1
}
```
**Performance Target**: < 7 seconds total for suggestion workflow
---
## Pattern Recognition Methodology
### Step 1: Implementation Analysis (< 30 seconds)
**Objective**: Review what was just implemented to identify patterns
**Analysis questions**:
1. **Architectural patterns**:
- What high-level structure was used? (Service layer, Repository, Factory, etc.)
- How are concerns separated? (Business logic, data access, presentation)
- What design patterns were applied? (Singleton, Strategy, Observer, etc.)
2. **Integration patterns**:
- How does new code connect to existing code?
- What interfaces/contracts were established?
- How is dependency injection handled?
3. **Error handling patterns**:
- How are errors caught and handled?
- What logging/monitoring was added?
- How are errors propagated to callers?
4. **Testing patterns**:
- What test structure was used? (AAA: Arrange-Act-Assert, etc.)
- How are mocks/stubs created?
- What edge cases were covered?
5. **Configuration patterns**:
- How are environment-specific values managed?
- Where do defaults live?
- How is configuration validated?
**Data to extract**:
- File paths demonstrating pattern
- Code snippets showing key concepts
- When this pattern should/shouldn't be used
- Alternatives considered and why rejected
### Step 2: Pattern Classification (< 15 seconds)
**Classify into knowledge-core.md sections**:
#### Section 1: Architectural Principles (high-level rules)
- Broad guidelines affecting entire codebase
- Example: "Use dependency injection for all external services"
- Example: "All API routes must have auth middleware"
- Example: "Database queries must go through repository layer"
#### Section 2: Established Patterns (concrete implementations)
- Specific, reusable implementation patterns
- Include: Pattern name, context, implementation example, files
- Example: "Service Layer Pattern for business logic"
- Example: "Factory pattern for creating Redis clients"
#### Section 3: Key Decisions & Learnings (chronological log)
- Decisions made during specific implementations
- Include: Date, decision, rationale, alternatives considered
- Example: "2025-10-17: Chose Redis over Memcached for cachCross-artifact consistency and coverage analysis specialist with Anthropic think protocol. Validates alignment between specifications, plans, tasks, and implementation. Use before implementation to catch conflicts early.
Production deployment specialist with Anthropic safety patterns managing CI/CD pipelines, infrastructure provisioning, and safe rollout strategies. Defaults to canary deployments with auto-rollback. Use for production deployments and release management.
Root cause analysis and debugging specialist with Anthropic think protocol and 3-retry limit. Focuses on systematic problem diagnosis, error tracing, and fix validation. Use for complex bugs and system failures.
Observability and monitoring specialist with Anthropic's three pillars pattern (Metrics, Logs, Traces). Sets up comprehensive monitoring, SLI/SLO tracking, and incident detection. Use for system observability and proactive alerting.
Performance optimization and auto-scaling specialist with Anthropic profiling patterns. Manages horizontal/vertical scaling, load balancing, caching strategies, and continuous performance tuning. Use for scaling challenges and performance work.
Master orchestrator for complex, multi-faceted software projects. Coordinates specialist agents (researchers, planners, implementers) to deliver cohesive solutions. Use for projects requiring 3+ capabilities or cross-domain work (frontend + backend + devops).
Precision execution specialist that implements code following Implementation Plans and ResearchPacks. Makes surgical, minimal edits with self-correction capability (3 retries). Always runs tests and validates against plan. Requires both ResearchPack and Implementation Plan as input.
High-speed documentation specialist. Fetches version-accurate docs from official sources to prevent coding from stale memory. Use before implementing any feature with external libraries or APIs. Delivers ResearchPack in < 2 minutes.