Instalar com Codex ou Claude Copie este prompt, cole no Codex, Claude ou outro assistente e deixe que ele revise a página da skill e instale para você.
Um comando direto ignora o prompt de revisão. Verifique a origem antes de executá-lo.
Meta-skill for continuous self-improvement through the Reflect, Abstract, Generalize, Store loop.
Quick Start
# Auto-triggers on detection of:# - User corrections# - Preference statements# - Repeated patterns# - Positive reinforcement# Manual trigger for reflection
/claude-reflection
# Review captured learningscat ~/.claude/memory/learnings.yaml
# Sync learnings across sessions
/claude-reflection --sync
Overview
The claude-reflection skill enables Claude to learn continuously from user interactions, capturing corrections, preferences, workflow patterns, and positive feedback. Unlike session-scoped context, learnings persist across conversations through structured memory files.
Why This Matters
Without reflection:
Same mistakes repeated across sessions
User preferences forgotten
Valuable patterns lost
No accumulation of domain knowledge
With reflection:
Corrections learned once, applied forever
User preferences remembered and applied
Workflow patterns automated over time
Domain expertise accumulates across sessions
Core Philosophy
REFLECT - Notice what happened (correction, preference, pattern)
ABSTRACT - Extract the generalizable principle
GENERALIZE - Determine scope (global, domain, project, session)
STORE - Persist to appropriate memory file
When to Use
Auto-Detection Triggers
This skill auto-executes when it detects these patterns in conversation:
1. Direct Correction
User: "No, don't use snake_case for that. Use camelCase for JavaScript."
Trigger: Explicit correction of Claude's behavior
Action: Capture coding style preference
2. Preference Statement
User: "I prefer shorter commit messages, just one line."
Trigger: Statement of preference (I prefer, I like, I want, always, never)
Action: Capture workflow preference
3. Explicit Memory Request
User: "Remember that this project uses tabs, not spaces."
Trigger: Direct request to remember (remember, don't forget, always do)
Action: Store as project-level preference
4. Positive Reinforcement
User: "Perfect! That's exactly how I want error messages formatted."
Trigger: Positive feedback on specific behavior
Action: Reinforce and capture the pattern
5. Repeated Patterns
User asks for the same type of change 3+ times in a session
Trigger: Repetition detection
Action: Extract pattern for automation
6. Error-Then-Success
Claude makes mistake -> User corrects -> Claude succeeds
Trigger: Correction followed by success
Action: Capture the correction as a learning
Manual Trigger
# Force reflection analysis on recent conversation
/claude-reflection
# Reflect on specific topic
/claude-reflection --topic "code formatting"# Export learnings for review
/claude-reflection --export# Clear session learnings (keeps persistent)
/claude-reflection --clear-session
Core Process
The Reflect-Abstract-Generalize-Store Loop
+------------------+
| DETECTION |
| (correction, |
| preference, |
| pattern) |
+--------+---------+
|
v
+------------------+ +---------+ +------------------+
| REFLECT |<---| Event |--->| ABSTRACT |
| What happened? | +---------+ | What's the |
| What was wrong? | | underlying |
| What was right? | | principle? |
+--------+---------+ +--------+---------+
| |
v v
+------------------+ +------------------+
| GENERALIZE | | STORE |
| What scope? | | Where to save? |
| Global/Domain/ | | What format? |
| Project/Session | | How to retrieve? |
+--------+---------+ +------------------+
| ^
+--------------------------------------+
Step 1: Reflect
Analyze what happened in the interaction:
# Example reflection analysisdefreflect(interaction: dict) -> dict:
"""Analyze what happened and why."""
reflection = {
"event_type": classify_event(interaction),
"what_happened": interaction["claude_action"],
"user_response": interaction["user_feedback"],
"outcome": "correction" | "success" | "preference",
"confidence": calculate_confidence(interaction)
}
return reflection
# Example: User corrected formatting# {# "event_type": "correction",# "what_happened": "Used 4-space indentation",# "user_response": "Use 2-space indentation for this project",# "outcome": "correction",# "confidence": 0.95# }
# Example generalizationdefdetermine_scope(principle: dict) -> str:
"""Determine if learning is global, domain, project, or session specific."""
context_clues = principle.get("context_clues", [])
# Session-only: temporary, experimentalifany(word in context_clues for word in ["just this time", "for now", "temporarily"]):
return"session"# Project-specific: mentions project name or "this project"if"this project"in context_clues or detect_project_name(context_clues):
return"project"# Domain-specific: mentions technology or domainif detect_domain(context_clues): # javascript, python, marine, etc.return"domain"# Global: general preference, no specific contextreturn"global"# Example: "this project" -> scope: project
# Correction indicatorscorrection_signals:explicit:-"No, "-"Actually, "-"That's wrong"-"Don't do that"-"Instead, "-"Use X instead of Y"implicit:-user_edits_claude_output-user_asks_to_redo-user_provides_alternativecontextual:-negation_after_claude_action-contrast_statement
Example 1: Coding Style Correction
# Detected interactioninteraction:claude_action:"Created function with snake_case name: get_user_data()"user_response:"Use camelCase for JavaScript functions"# Reflection outputreflection:event_type:correctioncategory:coding_stylerule:"Use camelCase for JavaScript function names"anti_pattern:"snake_case function names"correct_pattern:"camelCase function names"scope:domaindomain:javascriptconfidence:0.95# Stored learninglearning:id:"js-function-naming-001"timestamp:"2026-01-17T10:30:00Z"category:coding_stylescope:domaindomain:javascriptrule:"Use camelCase for function names in JavaScript"example:wrong:"get_user_data()"right:"getUserData()"source:user_correctionconfidence:0.95
Example 2: Error Handling Correction
# Claude's original approach (incorrect)defprocess_data(data):
return data.transform() # No error handling# User correction:# "Always wrap data operations in try-except with logging"# Learned pattern
learning = {
"category": "error_handling",
"scope": "global",
"rule": "Wrap data operations in try-except with logging",
"anti_pattern": """
def process_data(data):
return data.transform()
""",
"correct_pattern": """
def process_data(data):
try:
return data.transform()
except Exception as e:
logger.error(f"Data processing failed: {e}")
raise
""",
"confidence": 0.9
}
2. Preference Capture
Preference Indicators:
# Phrases indicating preferencespreference_signals:strong:-"I prefer"-"I always want"-"Never do"-"Always use"-"My preference is"moderate:-"I like"-"I'd rather"-"Can you use"-"Let's go with"implicit:-consistent_user_choices-repeated_requests_for_same_format
Example 3: Communication Preference
# Detected preferenceinteraction:context:"Claude provided detailed explanation"user_response:"I prefer concise responses. Just give me the code."# Captured preferencepreference:id:"comm-style-001"timestamp:"2026-01-17T11:00:00Z"category:communicationscope:globalpreference:"Provide concise responses with minimal explanation"context:"When providing code solutions"strength:strongsource:explicit_statement# Application ruleapplication:when:"user_asks_for_code"action:"Provide code with brief comment, skip lengthy explanations"unless:"user_asks_for_explanation"
Example 4: Formatting Preference
# Detected pattern (multiple interactions)interactions:-user_edits_claude_output:"Removed extra blank lines"-user_edits_claude_output:"Removed extra blank lines"-user_statement:"Too much whitespace"# Captured preferencepreference:id:"format-whitespace-001"category:formattingscope:globalpreference:"Minimize blank lines in code output"evidence:-"2 edits removing blank lines"-"explicit complaint about whitespace"confidence:0.85
3. Pattern Extraction from Repeated Workflows
Pattern Detection:
defdetect_workflow_pattern(session_history: list) -> Optional[dict]:
"""Detect repeated workflow patterns worth automating."""# Look for repeated sequences
sequences = extract_sequences(session_history)
for sequence in sequences:
if sequence.occurrences >= 3:
pattern = {
"steps": sequence.steps,
"occurrences": sequence.occurrences,
"trigger": identify_trigger(sequence),
"automation_potential": calculate_automation_score(sequence)
}
if pattern["automation_potential"] > 0.7:
return pattern
returnNone
# ~/.claude/memory/global_learnings.yamlversion:"1.0"last_updated:"2026-01-17T12:00:00Z"total_learnings:15learnings:-id:"learn-001"timestamp:"2026-01-15T09:00:00Z"category:coding_stylerule:"Use descriptive variable names over abbreviations"example:wrong:"x = get_val()"right:"user_count = get_user_count()"confidence:0.95times_applied:12last_applied:"2026-01-17T10:30:00Z"validated:true-id:"learn-002"timestamp:"2026-01-16T14:00:00Z"category:communicationrule:"Provide code first, explanation after"context:"When user asks for code solution"confidence:0.9times_applied:8last_applied:"2026-01-17T11:00:00Z"validated:true-id:"learn-003"timestamp:"2026-01-17T10:00:00Z"category:error_handlingrule:"Always include error context in log messages"example:wrong:'logger.error("Failed")'right:'logger.error(f"Failed to process {item}: {e}")'confidence:0.85times_applied:3last_applied:"2026-01-17T11:30:00Z"validated:false# Needs more applications
defload_applicable_learnings(project_path: Optional[Path] = None) -> dict:
"""Load all learnings applicable to current context."""
learnings = {
"global": [],
"domain": [],
"project": []
}
# 1. Load global learnings
global_path = Path.home() / ".claude/memory/global_learnings.yaml"if global_path.exists():
withopen(global_path) as f:
data = yaml.safe_load(f)
learnings["global"] = data.get("learnings", [])
# 2. Load domain learnings (detect from project)
domains = detect_project_domains(project_path)
for domain in domains:
domain_path = Path.home() / f".claude/memory/domains/{domain}/learnings.yaml"if domain_path.exists():
withopen(domain_path) as f:
data = yaml.safe_load(f)
learnings["domain"].extend(data.get("learnings", []))
# 3. Load project learningsif project_path:
project_mem = project_path / ".claude/memory/project_learnings.yaml"if project_mem.exists():
withopen(project_mem) as f:
data = yaml.safe_load(f)
learnings["project"] = data.get("learnings", [])
return learnings
defapply_learnings_to_context(learnings: dict) -> str:
"""Generate context prompt from loaded learnings."""
context_parts = []
# High-priority learnings (high confidence, frequently applied)
priority_learnings = []
for scope in ["global", "domain", "project"]:
for learning in learnings[scope]:
if learning.get("confidence", 0) > 0.8and learning.get("times_applied", 0) > 3:
priority_learnings.append(learning)
if priority_learnings:
context_parts.append("## Learned Preferences\n")
for learning in priority_learnings[:10]: # Top 10
context_parts.append(f"- {learning['rule']}")
return"\n".join(context_parts)
Validation and Reinforcement:
# Validation rulesvalidation:# Learning becomes validated after:conditions:-times_applied>=5-no_contradictions:true-user_confirmed:true# Optional but accelerates# Confidence decay for unused learningsdecay:days_without_use:30decay_rate:0.05# -5% per month of non-useminimum_confidence:0.3# Reinforcement on successful applicationreinforcement:successful_application:+0.02user_confirmation:+0.1maximum_confidence:0.99
Integration with Progress Tracking
Hook Integration
#!/bin/bash# .claude/hooks/post-interaction.sh# Called after each significant interaction
INTERACTION_LOG="$1"
REFLECTION_SKILL="$HOME/.claude/skills/workspace-hub/claude-reflection"# Check for reflection triggersif grep -qE "(No,|Actually,|I prefer|Remember that)""$INTERACTION_LOG"; thenecho"Reflection trigger detected, analyzing...""$REFLECTION_SKILL/analyze.sh""$INTERACTION_LOG"fi
Session Summary
At session end, generate reflection summary:
# Session reflection summarysession_summary:session_id:"2026-01-17-session-001"duration:"2h 30m"learnings_captured:total:5corrections:2preferences:2patterns:1details:-type:correctionrule:"Use 2-space indentation for YAML"scope:domainconfidence:0.95-type:preferencerule:"Prefer functional approach over OOP"scope:projectconfidence:0.85-type:patternname:"Test-then-implement workflow"occurrences:3automation_potential:0.7validation_status:pending:3validated:2recommendations:-"Consider creating /yaml-format command for repeated YAML formatting"-"Review python domain learnings - 2 may conflict"
File Formats
learnings.yaml Schema
# Schema for learnings files$schema:"https://workspace-hub.dev/schemas/learnings-v1.yaml"version:"1.0"last_updated:"2026-01-17T12:00:00Z"total_learnings:0metadata:scope:global|domain|projectdomain:null|string# For domain-scopedproject:null|string# For project-scopedlearnings:-id:string# Unique identifiertimestamp:datetime# When capturedcategory:string# coding_style, communication, workflow, error_handling, etc.rule:string# The learned rule/preferencecontext:string# When this applies (optional)example:# Optional examplewrong:stringright:stringanti_pattern:string# What NOT to do (optional)correct_pattern:string# What TO do (optional)confidence:float# 0.0 to 1.0times_applied:int# Usage countlast_applied:datetimesource:string# user_correction, preference_statement, pattern_extractionvalidated:boolean# Meets validation criteriatags:list[string]# Optional categorization
preferences.yaml Schema
# Schema for preferences files$schema:"https://workspace-hub.dev/schemas/preferences-v1.yaml"version:"1.0"last_updated:"2026-01-17T12:00:00Z"preferences:communication:verbosity:concise|detailed|adaptiveexplanation_style:code_first|explanation_first|balancedquestion_format:direct|exploratorycoding:indentation:spaces|tabsindent_size:2|4naming_convention:snake_case|camelCase|PascalCasecomments:minimal|moderate|comprehensiveworkflow:tdd:true|falsecommit_style:conventional|descriptive|minimalbranch_naming:feature/|feat/|customformatting:line_length:80|100|120blank_lines:minimal|standardtrailing_newline:true|false
patterns.yaml Schema
# Schema for workflow patterns$schema:"https://workspace-hub.dev/schemas/patterns-v1.yaml"version:"1.0"last_updated:"2026-01-17T12:00:00Z"patterns:-id:stringname:stringdescription:stringtrigger:phrases:list[string]conditions:list[string]steps:-action:stringparameters:dictoptional:booleanoccurrences:intlast_used:datetimeautomation:potential:float# 0.0 to 1.0skill_candidate:booleansuggested_command:string
Best Practices
1. Learning Quality
Do:
Capture specific, actionable learnings
Include examples when available
Set appropriate scope (don't over-generalize)
Validate learnings over time
Don't:
Capture one-off adjustments as permanent learnings
Over-generalize from single instances
Ignore conflicting learnings
Let unvalidated learnings persist indefinitely
2. Scope Selection
# Decision tree for scope selectiondefselect_scope(learning: dict) -> str:
"""Select appropriate scope for a learning."""# Check for explicit scope indicatorsif"this project"in learning.get("context", "").lower():
return"project"if"always"in learning.get("context", "").lower():
return"global"# Check for domain indicators
domain_keywords = {
"javascript": "javascript",
"python": "python",
"marine": "marine-engineering",
"offshore": "marine-engineering",
"react": "javascript"
}
for keyword, domain in domain_keywords.items():
if keyword in learning.get("rule", "").lower():
learning["domain"] = domain
return"domain"# Default to project if uncertainreturn"project"
3. Conflict Resolution
# When learnings conflictconflict_resolution:strategy:"newer_wins"|"higher_confidence"|"ask_user"example:learning_1:rule:"Use 4-space indentation"timestamp:"2026-01-10"confidence:0.8learning_2:rule:"Use 2-space indentation"timestamp:"2026-01-17"confidence:0.95resolution:action:"supersede"winner:learning_2reason:"Newer with higher confidence"notification:message:"Superseded learning: 'Use 4-space indentation' replaced by 'Use 2-space indentation'"
4. Privacy Considerations
# Privacy rulesprivacy:never_capture:-passwords-api_keys-personal_identifiable_information-financial_data-credentialssanitize:-file_paths:"Replace with placeholders"-user_names:"Anonymize"-project_names:"Use generic references unless essential"retention:validated_learnings:"indefinite"unvalidated_learnings:"90 days"session_data:"end of session"
# 1. Backup corrupted filecp ~/.claude/memory/global_learnings.yaml ~/.claude/memory/global_learnings.yaml.bak
# 2. Restore from last good backup or reset
/claude-reflection --reset-memory --scope global
Too Many Low-Quality Learnings
Symptom: Memory files bloated with unvalidated learnings
Solution:
# Prune learnings that:# - Have never been applied# - Are older than 90 days# - Have confidence < 0.5
/claude-reflection --prune --criteria "times_applied=0,age>90d,confidence<0.5"
Execution Checklist
On Trigger Detection:
Identify trigger type (correction/preference/pattern)