This skill provides systematic methodology for identifying reusable patterns from completed work and automatically updating the knowledge core to preserve institutional knowledge across sessions.
Include: Date, decision, rationale, alternatives considered
Example: "2025-10-17: Chose Redis over Memcached for caching (reason: better data structure support)"
Learnings from mistakes or discoveries
Classification criteria:
Principle: Applies across many features/files
Pattern: Reusable template for specific problem
Decision: One-time choice with lasting impact
Learning: New insight or gotcha discovered
Step 3: Pattern Documentation (< 30 seconds)
For each pattern identified, document:
### Pattern: [Descriptive Name]**Context**: [When to use this pattern]
- Use when: [Specific scenarios]
- Don't use when: [Scenarios where it doesn't fit]
**Problem**: [What problem does this solve?]
**Solution**:
[Brief description of the pattern]
**Implementation Example**:
```[language]
// Minimal code example showing pattern
// File: path/to/example.ts
Files Demonstrating Pattern:
path/to/file1.ts - [What aspect it demonstrates]
path/to/file2.ts - [What aspect it demonstrates]
Related Patterns:
[Other patterns that work well with this]
Trade-offs:
✅ Benefits: [List]
⚠️ Costs: [List]
Alternatives Considered:
[Alternative 1] - Rejected because [reason]
[Alternative 2] - Rejected because [reason]
**Quality criteria**:
- **Actionable**: Another developer can apply this pattern from the description
- **Specific**: Not vague generalities ("use good code" → ❌)
- **Verified**: Pattern is actually implemented in referenced files
- **Complete**: Includes when to use AND when not to use
### Step 4: Knowledge Core Update (< 20 seconds)
**Update `knowledge-core.md` following its structure**:
```markdown
# Knowledge Core
Last Updated: [ISO date]
Version: [increment version number]
## 1. Architectural Principles
### [New principle if identified]
[Description]
**Rationale**: [Why this principle]
**Established**: [Date]
**Applies to**: [Which parts of codebase]
---
## 2. Established Patterns
### [New pattern from Step 3]
[Full pattern documentation]
---
## 3. Key Decisions & Learnings
### [YYYY-MM-DD] [Decision Title]
**Decision**: [What was decided]
**Context**: [What prompted this decision]
**Alternatives**: [What else was considered]
**Rationale**: [Why this was chosen]
**Implementation**: See `[files]`
**Status**: [Active / Superseded by [link]]
---
Update protocol:
Read current knowledge-core.md
Check for duplicates (don't add pattern if it already exists)
Append new patterns to appropriate sections
Increment version number
Update "Last Updated" timestamp
Write updated file
Merge strategy (if pattern partially exists):
Enhance existing pattern with new examples/files
Note that pattern was "reinforced" in latest implementation
Purpose: Track implementation outcomes for pattern learning and confidence scoring
Metrics to Capture:
Success/Failure Classification:
success = (
all_tests_passing AND
quality_gates_passed AND
no_rollback_required
)
Implementation Duration:
duration_minutes = (end_time - start_time).total_seconds() / 60# Start time: When @code-implementer begins# End time: When tests pass and implementation complete
Quality Scores (if available from /workflow):
quality_score = (research_pack_score + implementation_plan_score) / 2# Only available if full workflow used (research + plan phases)
Self-Correction Count:
retry_count = number_of_self_correction_attempts
# Reported by @code-implementer (0-3 range, lower is better)
# If pattern failed 3+ times consecutively with no successes, mark as anti-patternif pattern['failures'] >= 3and pattern['successes'] == 0:
pattern['anti_pattern'] = True
pattern['deprecation_warning'] = "This pattern has failed repeatedly. Consider alternatives."# If pattern rejected 3+ times, reduce confidenceif pattern.get('total_suggestions', 0) >= 3and pattern['user_acceptance_rate'] < 0.30:
pattern['confidence'] *= 0.8# Reduce by 20%
pattern['deprecation_warning'] = "This pattern has been rejected frequently."
6. Write Updated JSON:
# Update metadata
pattern_index['metadata']['total_implementations'] += 1
pattern_index['metadata']['last_updated'] = today_iso()
# Recalculate overall success rate
total_successes = sum(p['successes'] for p in pattern_index['patterns'].values())
total_uses = sum(p['total_uses'] for p in pattern_index['patterns'].values())
pattern_index['metadata']['overall_success_rate'] = round(
total_successes / total_uses if total_uses > 0else0.0,
2
)
# Write updated JSON
write_json('~/.codex/data/pattern-index.json', pattern_index)
# Validate JSON is still valid
verify_json_valid('~/.codex/data/pattern-index.json')
Performance Target: < 15 seconds for complete metrics update
Step 7: Verification (< 10 seconds)
Before finalizing update:
✓ Completeness check:
Pattern has name, context, problem, solution
At least 1 file reference provided
Trade-offs documented
✓ Accuracy check:
Referenced files actually exist
Code snippets are actual code (not hallucinated)
Pattern is demonstrated in listed files
✓ Uniqueness check:
Pattern not duplicate of existing pattern
Or if similar, explains difference/enhancement
✓ Usefulness check:
Pattern is reusable (not one-off specific to this feature)
Pattern solves a problem that will recur
Pattern is clear enough for future use
If any check fails: Fix before updating knowledge-core.md
Automation Notes
Codex does not support Claude Code hook lifecycle automation. Treat the legacy
hook example below as historical context only; do not configure .claude/hooks
or claim automatic Stop-hook capture in Codex. For Codex, run this skill
manually at the end of a meaningful implementation session, then update
knowledge-core.md or the relevant repository memory file directly.
Legacy Claude Code Stop Hook Example (Do Not Use In Codex):
{"hooks":{"Stop":[{"matcher":"*","command":"update-knowledge-core.sh","description":"Automatically capture patterns from session"}]}}
#!/bin/bash# Triggered at end of session to update knowledge core# Check if any implementations occurred this sessionif [ -f ".claude/session-summary.json" ]; then# Extract patterns from session# Call Claude Code with pattern-recognition skill# Update knowledge-core.mdecho"🧠 Updating knowledge core with session learnings..."fi
Pattern Categories
Common Patterns to Recognize
1. Service Layer Pattern:
// Business logic separated into servicesclassProductService {
constructor(privaterepo: ProductRepository) {}
asyncgetProduct(id: string) {
// Business logic herereturnthis.repo.findById(id);
}
}
### Anti-Pattern: Direct Database Access in Controllers**Problem**: Controller directly queries database
**Why It's Bad**:
- Violates separation of concerns
- Hard to test
- Business logic mixed with HTTP handling
**Instead Use**: Repository pattern (see Section 2)
**Files that demonstrate BAD approach** (for reference):
- ❌ `old-code/legacy-controller.ts` (before refactor)
**Files that demonstrate GOOD approach**:
- ✅ `src/controllers/ProductController.ts` (uses ProductService)
Knowledge Core Maintenance
Regular review (monthly recommended):
Check if documented patterns still apply
Mark deprecated patterns as "Superseded by [new pattern]"
Consolidate similar patterns if identified
Update examples if file paths changed
Version control:
knowledge-core.md should be in git
Track changes over time
Tag versions with major architectural changes
Performance Targets
Pattern identification: < 30 seconds
Documentation: < 30 seconds per pattern
Knowledge core update: < 20 seconds
Total time: < 90 seconds per completed implementation
Example Usage
Scenario: @code-implementer just completed Redis caching implementation
Claude (using this skill):
[Internal: Implementation complete, capture patterns]
🧠 Activating pattern-recognition skill
🔍 Analyzing implementation for patterns...
Identified patterns:
1. Service Layer Pattern (CacheService wraps Redis client)
2. Factory Pattern (createRedisClient() encapsulates connection)
3. Configuration Pattern (TTL and host via env vars)
4. Error Handling Pattern (try-catch with logging + fallback)
📝 Documenting patterns...
[Creates detailed pattern documentation for each]
📚 Updating knowledge-core.md...
Added to Section 2 (Established Patterns):
- Pattern: Redis Client Factory
- Pattern: Cache Service Layer
- Pattern: Environment-Based TTL Configuration
Added to Section 3 (Key Decisions):
- 2025-10-17: Chose Redis client v4.6.0 (promise-based over callback)
- 2025-10-17: TTL configured per-environment (dev: 60s, prod: 300s)
✅ Knowledge core updated (version 1.3 → 1.4)
New patterns available for future implementations!
Confidence Calculation Algorithm (NEW v3.1)
Bayesian Confidence with Time Decay
Purpose: Calculate pattern reliability based on success rate, recency, and evidence quality
80%: High confidence ensures 80%+ suggestion accuracy
50%: Medium patterns may work but need review
<50%: Low confidence patterns need more evidence or deprecation
Example Calculations
Case 1: Proven Recent Pattern (IDEAL)
Success rate: 8/10 = 0.80
Last used: 20 days ago → decay = 1.0
Total uses: 10 → evidence = 1.0
Confidence: 0.80 × 1.0 × 1.0 = 0.80 (HIGH)
Case 2: Unproven Pattern (LOW EVIDENCE)
Success rate: 2/2 = 1.00
Last used: 5 days ago → decay = 1.0
Total uses: 2 → evidence = 0.5
Confidence: 1.00 × 1.0 × 0.5 = 0.50 (MEDIUM)
Case 3: Stale Pattern (OLD, NOT USED)
Success rate: 5/5 = 1.00
Last used: 200 days ago → decay = 0.5
Total uses: 5 → evidence = 1.0
Confidence: 1.00 × 0.5 × 1.0 = 0.50 (MEDIUM)
Case 4: Failed Pattern (POOR SUCCESS RATE)
Success rate: 1/5 = 0.20
Last used: 10 days ago → decay = 1.0
Total uses: 5 → evidence = 1.0
Confidence: 0.20 × 1.0 × 1.0 = 0.20 (LOW)
Implementation Reference
Script: ~/.codex/scripts/calculate-confidence.sh
This algorithm is implemented in bash for standalone calculation and testing. The pattern-recognition skill uses these same calculations when updating pattern-index.json.
This skill ensures institutional knowledge is captured automatically AND learns from outcomes to suggest proven patterns proactively, making future implementations 30-40% faster.