claude-reflection

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Claude Reflection Skill

Claude Reflection 技能

Meta-skill for continuous self-improvement through the Reflect, Abstract, Generalize, Store loop.
一款通过Reflect(反思)、Abstract(提炼)、Generalize(泛化)、Store(存储)循环实现持续自我提升的元技能。

Quick Start

快速开始

bash
undefined
bash
undefined

Auto-triggers on detection of:

Auto-triggers on detection of:

- User corrections

- User corrections

- Preference statements

- Preference statements

- Repeated patterns

- Repeated patterns

- Positive reinforcement

- Positive reinforcement

Manual trigger for reflection

Manual trigger for reflection

/claude-reflection
/claude-reflection

Review captured learnings

Review captured learnings

cat ~/.claude/memory/learnings.yaml
cat ~/.claude/memory/learnings.yaml

Sync learnings across sessions

Sync learnings across sessions

/claude-reflection --sync
undefined
/claude-reflection --sync
undefined

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.
claude-reflection技能让Claude能够从用户交互中持续学习,捕获纠正反馈、偏好、工作流模式和积极反馈。与会话范围的上下文不同,学习内容通过结构化的内存文件在对话间持久保存。

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
REFLECT    - 记录发生的情况(纠正、偏好、模式)
ABSTRACT   - 提取可泛化的原则
GENERALIZE - 确定适用范围(全局、领域、项目、会话)
STORE      - 持久化到对应的内存文件

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
当对话中出现以下模式时,该技能会自动执行:
1. 直接纠正
用户: "不对,那个不要用snake_case。JavaScript要用camelCase。"
触发条件: 明确纠正Claude的行为
动作: 捕获编码风格偏好
2. 偏好声明
用户: "我更喜欢简短的提交信息,就一行。"
触发条件: 偏好声明(我偏好、我喜欢、我想要、总是、绝不)
动作: 捕获工作流偏好
3. 明确记忆请求
用户: "记住这个项目用制表符,不是空格。"
触发条件: 直接要求记住(记住、别忘了、总是要)
动作: 存储为项目级偏好
4. 积极强化
用户: "完美!这正是我想要的错误消息格式。"
触发条件: 对特定行为的积极反馈
动作: 强化并捕获该模式
5. 重复模式
用户在一个会话中多次(3次以上)要求相同类型的修改
触发条件: 检测到重复行为
动作: 提取模式用于自动化
6. 错误-修正-成功流程
Claude犯错 -> 用户纠正 -> Claude成功完成
触发条件: 纠正后成功完成任务
动作: 将纠正内容作为学习项捕获

Manual Trigger

手动触发

bash
undefined
bash
undefined

Force reflection analysis on recent conversation

强制分析最近对话进行反思

/claude-reflection
/claude-reflection

Reflect on specific topic

针对特定主题进行反思

/claude-reflection --topic "code formatting"
/claude-reflection --topic "code formatting"

Export learnings for review

导出学习内容供查看

/claude-reflection --export
/claude-reflection --export

Clear session learnings (keeps persistent)

清除会话级学习内容(保留持久化内容)

/claude-reflection --clear-session
undefined
/claude-reflection --clear-session
undefined

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? |
+--------+---------+                   +------------------+
         |                                      ^
         +--------------------------------------+
                    +------------------+
                    |    检测模块     |
                    | (纠正、偏好、  |
                    |   模式)        |
                    +--------+---------+
                             |
                             v
+------------------+    +---------+    +------------------+
|     反思模块      |<---|  事件  |--->|     提炼模块      |
| 发生了什么?      |    +---------+    | 核心原则是什么?  |
| 哪里出错了?      |                   |                   |
| 哪里做对了?      |                   |                   |
+--------+---------+                   +--------+---------+
         |                                      |
         v                                      v
+------------------+                   +------------------+
|   泛化模块       |                   |      存储模块       |
| 适用范围是什么? |                   | 保存到何处?        |
| 全局/领域/项目/会话 |                   | 采用什么格式?      |
|                  |                   | 如何检索?          |
+--------+---------+                   +------------------+
         |                                      ^
         +--------------------------------------+

Step 1: Reflect

步骤1:反思

Analyze what happened in the interaction:
python
undefined
分析交互过程中发生的情况:
python
undefined

Example reflection analysis

Example reflection analysis

def reflect(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
def reflect(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

Example: User corrected formatting

{

{

"event_type": "correction",

"event_type": "correction",

"what_happened": "Used 4-space indentation",

"what_happened": "Used 4-space indentation",

"user_response": "Use 2-space indentation for this project",

"user_response": "Use 2-space indentation for this project",

"outcome": "correction",

"outcome": "correction",

"confidence": 0.95

"confidence": 0.95

}

}

undefined
undefined

Step 2: Abstract

步骤2:提炼

Extract the generalizable principle:
python
undefined
提取可泛化的核心原则:
python
undefined

Example abstraction

Example abstraction

def abstract_principle(reflection: dict) -> dict: """Extract the underlying principle from the reflection.""" principle = { "category": categorize(reflection), # coding_style, workflow, communication "rule": extract_rule(reflection), "anti_pattern": reflection.get("what_happened"), "correct_pattern": extract_correct_pattern(reflection), "context_clues": extract_context(reflection) } return principle
def abstract_principle(reflection: dict) -> dict: """Extract the underlying principle from the reflection.""" principle = { "category": categorize(reflection), # coding_style, workflow, communication "rule": extract_rule(reflection), "anti_pattern": reflection.get("what_happened"), "correct_pattern": extract_correct_pattern(reflection), "context_clues": extract_context(reflection) } return principle

Example output:

Example output:

{

{

"category": "coding_style",

"category": "coding_style",

"rule": "Use 2-space indentation",

"rule": "Use 2-space indentation",

"anti_pattern": "4-space indentation",

"anti_pattern": "4-space indentation",

"correct_pattern": "2-space indentation",

"correct_pattern": "2-space indentation",

"context_clues": ["javascript", "this project"]

"context_clues": ["javascript", "this project"]

}

}

undefined
undefined

Step 3: Generalize

步骤3:泛化

Determine the appropriate scope:
python
undefined
确定合适的适用范围:
python
undefined

Example generalization

Example generalization

def determine_scope(principle: dict) -> str: """Determine if learning is global, domain, project, or session specific."""
context_clues = principle.get("context_clues", [])

# Session-only: temporary, experimental
if any(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 domain
if detect_domain(context_clues):  # javascript, python, marine, etc.
    return "domain"

# Global: general preference, no specific context
return "global"
def determine_scope(principle: dict) -> str: """Determine if learning is global, domain, project, or session specific."""
context_clues = principle.get("context_clues", [])

# Session-only: temporary, experimental
if any(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 domain
if detect_domain(context_clues):  # javascript, python, marine, etc.
    return "domain"

# Global: general preference, no specific context
return "global"

Example: "this project" -> scope: project

Example: "this project" -> scope: project

undefined
undefined

Step 4: Store

步骤4:存储

Persist the learning appropriately:
python
undefined
将学习内容持久化到合适位置:
python
undefined

Example storage

Example storage

def store_learning(principle: dict, scope: str) -> None: """Store learning in appropriate memory location."""
learning_entry = {
    "timestamp": datetime.now().isoformat(),
    "category": principle["category"],
    "rule": principle["rule"],
    "anti_pattern": principle.get("anti_pattern"),
    "correct_pattern": principle["correct_pattern"],
    "confidence": principle.get("confidence", 0.8),
    "source": "user_correction",
    "times_applied": 0
}

# Route to appropriate storage
storage_paths = {
    "global": "~/.claude/memory/global_learnings.yaml",
    "domain": f"~/.claude/memory/domains/{domain}/learnings.yaml",
    "project": ".claude/memory/project_learnings.yaml",
    "session": "session_context"  # Not persisted
}

append_to_yaml(storage_paths[scope], learning_entry)
undefined
def store_learning(principle: dict, scope: str) -> None: """Store learning in appropriate memory location."""
learning_entry = {
    "timestamp": datetime.now().isoformat(),
    "category": principle["category"],
    "rule": principle["rule"],
    "anti_pattern": principle.get("anti_pattern"),
    "correct_pattern": principle["correct_pattern"],
    "confidence": principle.get("confidence", 0.8),
    "source": "user_correction",
    "times_applied": 0
}

# Route to appropriate storage
storage_paths = {
    "global": "~/.claude/memory/global_learnings.yaml",
    "domain": f"~/.claude/memory/domains/{domain}/learnings.yaml",
    "project": ".claude/memory/project_learnings.yaml",
    "session": "session_context"  # Not persisted
}

append_to_yaml(storage_paths[scope], learning_entry)
undefined

Storage Scopes

存储范围

Scope Hierarchy

范围层级

+----------------------------------------------------------+
|  GLOBAL (~/.claude/memory/global_learnings.yaml)         |
|  - User-wide preferences                                  |
|  - Universal coding style                                 |
|  - Communication preferences                              |
|  +-----------------------------------------------------+ |
|  |  DOMAIN (~/.claude/memory/domains/<domain>/)        | |
|  |  - Technology-specific preferences                   | |
|  |  - Domain knowledge (marine, finance, etc.)         | |
|  |  +------------------------------------------------+ | |
|  |  |  PROJECT (.claude/memory/project_learnings.yaml)| | |
|  |  |  - Project conventions                          | | |
|  |  |  - Team standards                               | | |
|  |  |  +-------------------------------------------+ | | |
|  |  |  |  SESSION (in-memory only)                 | | | |
|  |  |  |  - Temporary adjustments                  | | | |
|  |  |  |  - Experimental preferences               | | | |
|  |  |  +-------------------------------------------+ | | |
|  |  +------------------------------------------------+ | |
|  +-----------------------------------------------------+ |
+----------------------------------------------------------+
+----------------------------------------------------------+
|  全局(~/.claude/memory/global_learnings.yaml)         |
|  - 用户级偏好                                  |
|  - 通用编码风格                                 |
|  - 沟通偏好                              |
|  +-----------------------------------------------------+ |
|  |  领域(~/.claude/memory/domains/<domain>/)        | |
|  |  - 技术特定偏好                   | |
|  |  - 领域知识(海事、金融等)         | |
|  |  +------------------------------------------------+ | |
|  |  |  项目(.claude/memory/project_learnings.yaml)| | |
|  |  |  - 项目规范                          | | |
|  |  |  - 团队标准                               | | |
|  |  |  +-------------------------------------------+ | | |
|  |  |  |  会话(仅内存)                 | | | |
|  |  |  |  - 临时调整                  | | | |
|  |  |  |  - 实验性偏好               | | | |
|  |  |  +-------------------------------------------+ | | |
|  |  +------------------------------------------------+ | |
|  +-----------------------------------------------------+ |
+----------------------------------------------------------+

Storage Locations

存储位置

ScopeLocationPersistenceExample
Global
~/.claude/memory/
Permanent"Always use descriptive variable names"
Domain
~/.claude/memory/domains/<name>/
Permanent"JavaScript: use camelCase"
Project
.claude/memory/
With project"This repo uses tabs"
SessionIn-memorySession only"Skip tests for this PR"
范围路径持久化性示例
全局
~/.claude/memory/
永久"始终使用描述性变量名"
领域
~/.claude/memory/domains/<name>/
永久"JavaScript: 使用camelCase"
项目
.claude/memory/
随项目保存"此仓库使用制表符"
会话仅内存仅当前会话"此PR跳过测试"

Directory Structure

目录结构

~/.claude/
├── memory/
│   ├── global_learnings.yaml       # User-wide learnings
│   ├── preferences.yaml            # User preferences
│   ├── patterns.yaml               # Workflow patterns
│   ├── corrections.yaml            # Correction history
│   └── domains/
│       ├── python/
│       │   ├── learnings.yaml
│       │   └── patterns.yaml
│       ├── javascript/
│       │   ├── learnings.yaml
│       │   └── patterns.yaml
│       └── marine-engineering/
│           ├── learnings.yaml
│           └── domain_knowledge.yaml
└── reflection/
    ├── session_log.yaml            # Current session learnings
    └── pending_confirmations.yaml  # Learnings awaiting validation

<project>/.claude/
├── memory/
│   ├── project_learnings.yaml      # Project-specific learnings
│   ├── team_preferences.yaml       # Team conventions
│   └── automation_candidates.yaml  # Patterns to automate
└── reflection/
    └── history.yaml                # Reflection history
~/.claude/
├── memory/
│   ├── global_learnings.yaml       # 用户级学习内容
│   ├── preferences.yaml            # 用户偏好
│   ├── patterns.yaml               # 工作流模式
│   ├── corrections.yaml            # 纠正历史
│   └── domains/
│       ├── python/
│       │   ├── learnings.yaml
│       │   └── patterns.yaml
│       ├── javascript/
│       │   ├── learnings.yaml
│       │   └── patterns.yaml
│       └── marine-engineering/
│           ├── learnings.yaml
│           └── domain_knowledge.yaml
└── reflection/
    ├── session_log.yaml            # 当前会话学习内容
    └── pending_confirmations.yaml  # 待验证的学习内容

<project>/.claude/
├── memory/
│   ├── project_learnings.yaml      # 项目特定学习内容
│   ├── team_preferences.yaml       # 团队规范
│   └── automation_candidates.yaml  # 待自动化的模式
└── reflection/
    └── history.yaml                # 反思历史

Core Capabilities

核心能力

1. Correction Detection and Learning

1. 纠正检测与学习

Detection Patterns:
yaml
undefined
检测模式:
yaml
undefined

Correction indicators

Correction indicators

correction_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_alternative
contextual: - negation_after_claude_action - contrast_statement

**Example 1: Coding Style Correction**

```yaml
correction_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_alternative
contextual: - negation_after_claude_action - contrast_statement

**示例1:编码风格纠正**

```yaml

Detected interaction

Detected interaction

interaction: claude_action: "Created function with snake_case name: get_user_data()" user_response: "Use camelCase for JavaScript functions"
interaction: claude_action: "Created function with snake_case name: get_user_data()" user_response: "Use camelCase for JavaScript functions"

Reflection output

Reflection output

reflection: event_type: correction category: coding_style rule: "Use camelCase for JavaScript function names" anti_pattern: "snake_case function names" correct_pattern: "camelCase function names" scope: domain domain: javascript confidence: 0.95
reflection: event_type: correction category: coding_style rule: "Use camelCase for JavaScript function names" anti_pattern: "snake_case function names" correct_pattern: "camelCase function names" scope: domain domain: javascript confidence: 0.95

Stored learning

Stored learning

learning: id: "js-function-naming-001" timestamp: "2026-01-17T10:30:00Z" category: coding_style scope: domain domain: javascript rule: "Use camelCase for function names in JavaScript" example: wrong: "get_user_data()" right: "getUserData()" source: user_correction confidence: 0.95

**Example 2: Error Handling Correction**

```python
learning: id: "js-function-naming-001" timestamp: "2026-01-17T10:30:00Z" category: coding_style scope: domain domain: javascript rule: "Use camelCase for function names in JavaScript" example: wrong: "get_user_data()" right: "getUserData()" source: user_correction confidence: 0.95

**示例2:错误处理纠正**

```python

Claude's original approach (incorrect)

Claude's original approach (incorrect)

def process_data(data): return data.transform() # No error handling
def process_data(data): return data.transform() # No error handling

User correction:

User correction:

"Always wrap data operations in try-except with logging"

"Always wrap data operations in try-except with logging"

Learned pattern

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 }
undefined
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 }
undefined

2. Preference Capture

2. 偏好捕获

Preference Indicators:
yaml
undefined
偏好指示器:
yaml
undefined

Phrases indicating preferences

Phrases indicating preferences

preference_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**

```yaml
preference_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

**示例3:沟通偏好**

```yaml

Detected preference

Detected preference

interaction: context: "Claude provided detailed explanation" user_response: "I prefer concise responses. Just give me the code."
interaction: context: "Claude provided detailed explanation" user_response: "I prefer concise responses. Just give me the code."

Captured preference

Captured preference

preference: id: "comm-style-001" timestamp: "2026-01-17T11:00:00Z" category: communication scope: global preference: "Provide concise responses with minimal explanation" context: "When providing code solutions" strength: strong source: explicit_statement
preference: id: "comm-style-001" timestamp: "2026-01-17T11:00:00Z" category: communication scope: global preference: "Provide concise responses with minimal explanation" context: "When providing code solutions" strength: strong source: explicit_statement

Application rule

Application rule

application: when: "user_asks_for_code" action: "Provide code with brief comment, skip lengthy explanations" unless: "user_asks_for_explanation"

**Example 4: Formatting Preference**

```yaml
application: when: "user_asks_for_code" action: "Provide code with brief comment, skip lengthy explanations" unless: "user_asks_for_explanation"

**示例4:格式偏好**

```yaml

Detected pattern (multiple interactions)

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"
interactions:
  • user_edits_claude_output: "Removed extra blank lines"
  • user_edits_claude_output: "Removed extra blank lines"
  • user_statement: "Too much whitespace"

Captured preference

Captured preference

preference: id: "format-whitespace-001" category: formatting scope: global preference: "Minimize blank lines in code output" evidence: - "2 edits removing blank lines" - "explicit complaint about whitespace" confidence: 0.85
undefined
preference: id: "format-whitespace-001" category: formatting scope: global preference: "Minimize blank lines in code output" evidence: - "2 edits removing blank lines" - "explicit complaint about whitespace" confidence: 0.85
undefined

3. Pattern Extraction from Repeated Workflows

3. 从重复工作流中提取模式

Pattern Detection:
python
def detect_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

    return None
Example 5: Git Workflow Pattern
yaml
undefined
模式检测:
python
def detect_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

    return None
示例5:Git工作流模式
yaml
undefined

Detected repeated workflow

Detected repeated workflow

pattern: id: "git-workflow-001" name: "Feature Branch Workflow" occurrences: 5
steps: - action: "git checkout -b feature/..." variation: "branch name varies" - action: "make changes" - action: "git add ." - action: "git commit -m '...'" variation: "message varies" - action: "git push -u origin feature/..." - action: "gh pr create"
trigger: "user says 'new feature' or 'start feature'"
automation: potential: 0.85 suggestion: "Create /start-feature command" template: | git checkout -b feature/{name} # ... make changes ... git add . git commit -m "{type}: {description}" git push -u origin feature/{name} gh pr create --title "{description}"
pattern: id: "git-workflow-001" name: "Feature Branch Workflow" occurrences: 5
steps: - action: "git checkout -b feature/..." variation: "branch name varies" - action: "make changes" - action: "git add ." - action: "git commit -m '...'" variation: "message varies" - action: "git push -u origin feature/..." - action: "gh pr create"
trigger: "user says 'new feature' or 'start feature'"
automation: potential: 0.85 suggestion: "Create /start-feature command" template: | git checkout -b feature/{name} # ... make changes ... git add . git commit -m "{type}: {description}" git push -u origin feature/{name} gh pr create --title "{description}"

Stored for potential skill creation

Stored for potential skill creation

automation_candidate: pattern_id: "git-workflow-001" skill_name: "feature-branch-creator" priority: high confirmed: false

**Example 6: Data Analysis Pattern**

```yaml
automation_candidate: pattern_id: "git-workflow-001" skill_name: "feature-branch-creator" priority: high confirmed: false

**示例6:数据分析模式**

```yaml

Detected repeated workflow

Detected repeated workflow

pattern: id: "data-analysis-001" name: "CSV Analysis Workflow" occurrences: 4
steps: - action: "Load CSV with pandas" - action: "Check for missing values" - action: "Generate summary statistics" - action: "Create visualization" - action: "Export HTML report"
parameters: - input_file: varies - output_path: "reports/" - viz_type: usually "plotly"
automation: potential: 0.9 suggestion: "Create /analyze-csv command" template: | df = pd.read_csv("{input_file}") missing = df.isnull().sum() stats = df.describe() fig = create_plotly_viz(df) save_html_report(fig, stats, "{output_path}")
undefined
pattern: id: "data-analysis-001" name: "CSV Analysis Workflow" occurrences: 4
steps: - action: "Load CSV with pandas" - action: "Check for missing values" - action: "Generate summary statistics" - action: "Create visualization" - action: "Export HTML report"
parameters: - input_file: varies - output_path: "reports/" - viz_type: usually "plotly"
automation: potential: 0.9 suggestion: "Create /analyze-csv command" template: | df = pd.read_csv("{input_file}") missing = df.isnull().sum() stats = df.describe() fig = create_plotly_viz(df) save_html_report(fig, stats, "{output_path}")
undefined

4. Knowledge Persistence

4. 知识持久化

File Format: YAML
yaml
undefined
文件格式:YAML
yaml
undefined

~/.claude/memory/global_learnings.yaml

~/.claude/memory/global_learnings.yaml

version: "1.0" last_updated: "2026-01-17T12:00:00Z" total_learnings: 15
learnings:
  • id: "learn-001" timestamp: "2026-01-15T09:00:00Z" category: coding_style rule: "Use descriptive variable names over abbreviations" example: wrong: "x = get_val()" right: "user_count = get_user_count()" confidence: 0.95 times_applied: 12 last_applied: "2026-01-17T10:30:00Z" validated: true
  • id: "learn-002" timestamp: "2026-01-16T14:00:00Z" category: communication rule: "Provide code first, explanation after" context: "When user asks for code solution" confidence: 0.9 times_applied: 8 last_applied: "2026-01-17T11:00:00Z" validated: true
  • id: "learn-003" timestamp: "2026-01-17T10:00:00Z" category: error_handling rule: "Always include error context in log messages" example: wrong: 'logger.error("Failed")' right: 'logger.error(f"Failed to process {item}: {e}")' confidence: 0.85 times_applied: 3 last_applied: "2026-01-17T11:30:00Z" validated: false # Needs more applications

**Persistence Operations:**

```python
def persist_learning(learning: dict, scope: str) -> str:
    """Persist a learning to the appropriate memory file."""

    # Determine storage path
    if scope == "global":
        path = Path.home() / ".claude/memory/global_learnings.yaml"
    elif scope == "domain":
        domain = learning.get("domain", "general")
        path = Path.home() / f".claude/memory/domains/{domain}/learnings.yaml"
    elif scope == "project":
        path = Path.cwd() / ".claude/memory/project_learnings.yaml"
    else:
        return "session_only"  # Don't persist

    # Ensure directory exists
    path.parent.mkdir(parents=True, exist_ok=True)

    # Load existing learnings
    if path.exists():
        with open(path) as f:
            data = yaml.safe_load(f) or {"learnings": []}
    else:
        data = {
            "version": "1.0",
            "last_updated": None,
            "total_learnings": 0,
            "learnings": []
        }

    # Add new learning
    learning["id"] = f"learn-{len(data['learnings']) + 1:04d}"
    data["learnings"].append(learning)
    data["last_updated"] = datetime.now().isoformat()
    data["total_learnings"] = len(data["learnings"])

    # Write back
    with open(path, "w") as f:
        yaml.dump(data, f, default_flow_style=False)

    return learning["id"]
version: "1.0" last_updated: "2026-01-17T12:00:00Z" total_learnings: 15
learnings:
  • id: "learn-001" timestamp: "2026-01-15T09:00:00Z" category: coding_style rule: "Use descriptive variable names over abbreviations" example: wrong: "x = get_val()" right: "user_count = get_user_count()" confidence: 0.95 times_applied: 12 last_applied: "2026-01-17T10:30:00Z" validated: true
  • id: "learn-002" timestamp: "2026-01-16T14:00:00Z" category: communication rule: "Provide code first, explanation after" context: "When user asks for code solution" confidence: 0.9 times_applied: 8 last_applied: "2026-01-17T11:00:00Z" validated: true
  • id: "learn-003" timestamp: "2026-01-17T10:00:00Z" category: error_handling rule: "Always include error context in log messages" example: wrong: 'logger.error("Failed")' right: 'logger.error(f"Failed to process {item}: {e}")' confidence: 0.85 times_applied: 3 last_applied: "2026-01-17T11:30:00Z" validated: false # Needs more applications

**持久化操作:**

```python
def persist_learning(learning: dict, scope: str) -> str:
    """Persist a learning to the appropriate memory file."""

    # Determine storage path
    if scope == "global":
        path = Path.home() / ".claude/memory/global_learnings.yaml"
    elif scope == "domain":
        domain = learning.get("domain", "general")
        path = Path.home() / f".claude/memory/domains/{domain}/learnings.yaml"
    elif scope == "project":
        path = Path.cwd() / ".claude/memory/project_learnings.yaml"
    else:
        return "session_only"  # Don't persist

    # Ensure directory exists
    path.parent.mkdir(parents=True, exist_ok=True)

    # Load existing learnings
    if path.exists():
        with open(path) as f:
            data = yaml.safe_load(f) or {"learnings": []}
    else:
        data = {
            "version": "1.0",
            "last_updated": None,
            "total_learnings": 0,
            "learnings": []
        }

    # Add new learning
    learning["id"] = f"learn-{len(data['learnings']) + 1:04d}"
    data["learnings"].append(learning)
    data["last_updated"] = datetime.now().isoformat()
    data["total_learnings"] = len(data["learnings"])

    # Write back
    with open(path, "w") as f:
        yaml.dump(data, f, default_flow_style=False)

    return learning["id"]

5. Cross-Session Learning

5. 跨会话学习

Loading Learnings at Session Start:
python
def load_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():
        with open(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():
            with open(domain_path) as f:
                data = yaml.safe_load(f)
                learnings["domain"].extend(data.get("learnings", []))

    # 3. Load project learnings
    if project_path:
        project_mem = project_path / ".claude/memory/project_learnings.yaml"
        if project_mem.exists():
            with open(project_mem) as f:
                data = yaml.safe_load(f)
                learnings["project"] = data.get("learnings", [])

    return learnings

def apply_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.8 and 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:
yaml
undefined
会话启动时加载学习内容:
python
def load_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():
        with open(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():
            with open(domain_path) as f:
                data = yaml.safe_load(f)
                learnings["domain"].extend(data.get("learnings", []))

    # 3. Load project learnings
    if project_path:
        project_mem = project_path / ".claude/memory/project_learnings.yaml"
        if project_mem.exists():
            with open(project_mem) as f:
                data = yaml.safe_load(f)
                learnings["project"] = data.get("learnings", [])

    return learnings

def apply_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.8 and 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)
验证与强化:
yaml
undefined

Validation rules

Validation rules

validation:

Learning becomes validated after:

conditions: - times_applied >= 5 - no_contradictions: true - user_confirmed: true # Optional but accelerates

Confidence decay for unused learnings

decay: days_without_use: 30 decay_rate: 0.05 # -5% per month of non-use minimum_confidence: 0.3

Reinforcement on successful application

reinforcement: successful_application: +0.02 user_confirmation: +0.1 maximum_confidence: 0.99
undefined
validation:

Learning becomes validated after:

conditions: - times_applied >= 5 - no_contradictions: true - user_confirmed: true # Optional but accelerates

Confidence decay for unused learnings

decay: days_without_use: 30 decay_rate: 0.05 # -5% per month of non-use minimum_confidence: 0.3

Reinforcement on successful application

reinforcement: successful_application: +0.02 user_confirmation: +0.1 maximum_confidence: 0.99
undefined

Integration with Progress Tracking

与进度跟踪系统的集成

Hook Integration

钩子集成

bash
#!/bin/bash
bash
#!/bin/bash

.claude/hooks/post-interaction.sh

.claude/hooks/post-interaction.sh

Called after each significant interaction

Called after each significant interaction

INTERACTION_LOG="$1" REFLECTION_SKILL="$HOME/.claude/skills/workspace-hub/claude-reflection"
INTERACTION_LOG="$1" REFLECTION_SKILL="$HOME/.claude/skills/workspace-hub/claude-reflection"

Check for reflection triggers

Check for reflection triggers

if grep -qE "(No,|Actually,|I prefer|Remember that)" "$INTERACTION_LOG"; then echo "Reflection trigger detected, analyzing..." "$REFLECTION_SKILL/analyze.sh" "$INTERACTION_LOG" fi
undefined
if grep -qE "(No,|Actually,|I prefer|Remember that)" "$INTERACTION_LOG"; then echo "Reflection trigger detected, analyzing..." "$REFLECTION_SKILL/analyze.sh" "$INTERACTION_LOG" fi
undefined

Session Summary

会话总结

At session end, generate reflection summary:
yaml
undefined
会话结束时生成反思总结:
yaml
undefined

Session reflection summary

Session reflection summary

session_summary: session_id: "2026-01-17-session-001" duration: "2h 30m"
learnings_captured: total: 5 corrections: 2 preferences: 2 patterns: 1
details: - type: correction rule: "Use 2-space indentation for YAML" scope: domain confidence: 0.95
- type: preference
  rule: "Prefer functional approach over OOP"
  scope: project
  confidence: 0.85

- type: pattern
  name: "Test-then-implement workflow"
  occurrences: 3
  automation_potential: 0.7
validation_status: pending: 3 validated: 2
recommendations: - "Consider creating /yaml-format command for repeated YAML formatting" - "Review python domain learnings - 2 may conflict"
undefined
session_summary: session_id: "2026-01-17-session-001" duration: "2h 30m"
learnings_captured: total: 5 corrections: 2 preferences: 2 patterns: 1
details: - type: correction rule: "Use 2-space indentation for YAML" scope: domain confidence: 0.95
- type: preference
  rule: "Prefer functional approach over OOP"
  scope: project
  confidence: 0.85

- type: pattern
  name: "Test-then-implement workflow"
  occurrences: 3
  automation_potential: 0.7
validation_status: pending: 3 validated: 2
recommendations: - "Consider creating /yaml-format command for repeated YAML formatting" - "Review python domain learnings - 2 may conflict"
undefined

File Formats

文件格式

learnings.yaml Schema

learnings.yaml Schema

yaml
undefined
yaml
undefined

Schema for learnings files

Schema for learnings files

version: "1.0" last_updated: "2026-01-17T12:00:00Z" total_learnings: 0
metadata: scope: global | domain | project domain: null | string # For domain-scoped project: null | string # For project-scoped
learnings:
  • id: string # Unique identifier timestamp: datetime # When captured category: string # coding_style, communication, workflow, error_handling, etc. rule: string # The learned rule/preference context: string # When this applies (optional)
    example: # Optional example wrong: string right: string
    anti_pattern: string # What NOT to do (optional) correct_pattern: string # What TO do (optional)
    confidence: float # 0.0 to 1.0 times_applied: int # Usage count last_applied: datetime
    source: string # user_correction, preference_statement, pattern_extraction validated: boolean # Meets validation criteria
    tags: list[string] # Optional categorization
undefined
version: "1.0" last_updated: "2026-01-17T12:00:00Z" total_learnings: 0
metadata: scope: global | domain | project domain: null | string # For domain-scoped project: null | string # For project-scoped
learnings:
  • id: string # Unique identifier timestamp: datetime # When captured category: string # coding_style, communication, workflow, error_handling, etc. rule: string # The learned rule/preference context: string # When this applies (optional)
    example: # Optional example wrong: string right: string
    anti_pattern: string # What NOT to do (optional) correct_pattern: string # What TO do (optional)
    confidence: float # 0.0 to 1.0 times_applied: int # Usage count last_applied: datetime
    source: string # user_correction, preference_statement, pattern_extraction validated: boolean # Meets validation criteria
    tags: list[string] # Optional categorization
undefined

preferences.yaml Schema

preferences.yaml Schema

yaml
undefined
yaml
undefined

Schema for preferences files

Schema for preferences files

version: "1.0" last_updated: "2026-01-17T12:00:00Z"
preferences: communication: verbosity: concise | detailed | adaptive explanation_style: code_first | explanation_first | balanced question_format: direct | exploratory
coding: indentation: spaces | tabs indent_size: 2 | 4 naming_convention: snake_case | camelCase | PascalCase comments: minimal | moderate | comprehensive
workflow: tdd: true | false commit_style: conventional | descriptive | minimal branch_naming: feature/ | feat/ | custom
formatting: line_length: 80 | 100 | 120 blank_lines: minimal | standard trailing_newline: true | false
undefined
version: "1.0" last_updated: "2026-01-17T12:00:00Z"
preferences: communication: verbosity: concise | detailed | adaptive explanation_style: code_first | explanation_first | balanced question_format: direct | exploratory
coding: indentation: spaces | tabs indent_size: 2 | 4 naming_convention: snake_case | camelCase | PascalCase comments: minimal | moderate | comprehensive
workflow: tdd: true | false commit_style: conventional | descriptive | minimal branch_naming: feature/ | feat/ | custom
formatting: line_length: 80 | 100 | 120 blank_lines: minimal | standard trailing_newline: true | false
undefined

patterns.yaml Schema

patterns.yaml Schema

yaml
undefined
yaml
undefined

Schema for workflow patterns

Schema for workflow patterns

version: "1.0" last_updated: "2026-01-17T12:00:00Z"
patterns:
  • id: string name: string description: string
    trigger: phrases: list[string] conditions: list[string]
    steps:
    • action: string parameters: dict optional: boolean
    occurrences: int last_used: datetime
    automation: potential: float # 0.0 to 1.0 skill_candidate: boolean suggested_command: string
undefined
version: "1.0" last_updated: "2026-01-17T12:00:00Z"
patterns:
  • id: string name: string description: string
    trigger: phrases: list[string] conditions: list[string]
    steps:
    • action: string parameters: dict optional: boolean
    occurrences: int last_used: datetime
    automation: potential: float # 0.0 to 1.0 skill_candidate: boolean suggested_command: string
undefined

Best Practices

最佳实践

1. Learning Quality

1. 学习内容质量

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

2. 范围选择

python
undefined
python
undefined

Decision tree for scope selection

Decision tree for scope selection

def select_scope(learning: dict) -> str: """Select appropriate scope for a learning."""
# Check for explicit scope indicators
if "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 uncertain
return "project"
undefined
def select_scope(learning: dict) -> str: """Select appropriate scope for a learning."""
# Check for explicit scope indicators
if "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 uncertain
return "project"
undefined

3. Conflict Resolution

3. 冲突解决

yaml
undefined
yaml
undefined

When learnings conflict

When learnings conflict

conflict_resolution: strategy: "newer_wins" | "higher_confidence" | "ask_user"
example: learning_1: rule: "Use 4-space indentation" timestamp: "2026-01-10" confidence: 0.8
learning_2:
  rule: "Use 2-space indentation"
  timestamp: "2026-01-17"
  confidence: 0.95

resolution:
  action: "supersede"
  winner: learning_2
  reason: "Newer with higher confidence"
notification: message: "Superseded learning: 'Use 4-space indentation' replaced by 'Use 2-space indentation'"
undefined
conflict_resolution: strategy: "newer_wins" | "higher_confidence" | "ask_user"
example: learning_1: rule: "Use 4-space indentation" timestamp: "2026-01-10" confidence: 0.8
learning_2:
  rule: "Use 2-space indentation"
  timestamp: "2026-01-17"
  confidence: 0.95

resolution:
  action: "supersede"
  winner: learning_2
  reason: "Newer with higher confidence"
notification: message: "Superseded learning: 'Use 4-space indentation' replaced by 'Use 2-space indentation'"
undefined

4. Privacy Considerations

4. 隐私考虑

yaml
undefined
yaml
undefined

Privacy rules

Privacy rules

privacy: never_capture: - passwords - api_keys - personal_identifiable_information - financial_data - credentials
sanitize: - 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"
undefined
privacy: never_capture: - passwords - api_keys - personal_identifiable_information - financial_data - credentials
sanitize: - 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"
undefined

5. Maintenance

5. 维护

bash
undefined
bash
undefined

Regular maintenance tasks

Regular maintenance tasks

1. Review unvalidated learnings

1. Review unvalidated learnings

cat ~/.claude/memory/global_learnings.yaml | grep "validated: false"
cat ~/.claude/memory/global_learnings.yaml | grep "validated: false"

2. Check for conflicting learnings

2. Check for conflicting learnings

/claude-reflection --check-conflicts
/claude-reflection --check-conflicts

3. Prune unused learnings (>6 months, <3 applications)

3. Prune unused learnings (>6 months, <3 applications)

/claude-reflection --prune --dry-run
/claude-reflection --prune --dry-run

4. Export learnings for backup

4. Export learnings for backup

/claude-reflection --export > ~/claude-learnings-backup-$(date +%Y%m%d).yaml
/claude-reflection --export > ~/claude-learnings-backup-$(date +%Y%m%d).yaml

5. Sync domain learnings across projects

5. Sync domain learnings across projects

/claude-reflection --sync-domains
undefined
/claude-reflection --sync-domains
undefined

Troubleshooting

故障排除

Learnings Not Being Applied

学习内容未被应用

Symptom: Claude doesn't seem to remember previous corrections
Check:
bash
undefined
症状: Claude似乎不记得之前的纠正反馈
检查:
bash
undefined

1. Verify learnings exist

1. 验证学习内容是否存在

cat ~/.claude/memory/global_learnings.yaml
cat ~/.claude/memory/global_learnings.yaml

2. Check if learning is validated

2. 检查学习内容是否已验证

grep -A5 "rule: 'your expected rule'" ~/.claude/memory/global_learnings.yaml
grep -A5 "rule: 'your expected rule'" ~/.claude/memory/global_learnings.yaml

3. Verify confidence threshold

3. 验证置信度阈值

Learnings with confidence < 0.5 may not be applied

置信度<0.5的学习内容可能不会被应用


**Solution:**
- Manually validate the learning
- Increase confidence by repeating the preference
- Check for conflicting learnings

**解决方案:**
- 手动验证学习内容
- 通过重复偏好提高置信度
- 检查是否存在冲突的学习内容

Conflicting Learnings

相互冲突的学习内容

Symptom: Claude applies inconsistent rules
Check:
bash
undefined
症状: Claude应用不一致的规则
检查:
bash
undefined

Find potential conflicts

查找潜在冲突

/claude-reflection --check-conflicts
/claude-reflection --check-conflicts

Example output:

Example output:

CONFLICT DETECTED:

CONFLICT DETECTED:

Learning 1: "Use 4-space indentation" (global, conf: 0.8)

Learning 1: "Use 4-space indentation" (global, conf: 0.8)

Learning 2: "Use 2-space indentation" (project, conf: 0.9)

Learning 2: "Use 2-space indentation" (project, conf: 0.9)

Resolution: Project scope takes precedence

Resolution: Project scope takes precedence


**Solution:**
- Review and remove outdated learnings
- Set appropriate scopes
- Explicitly confirm the correct preference

**解决方案:**
- 查看并移除过时的学习内容
- 设置合适的范围
- 明确确认正确的偏好

Memory Files Corrupted

内存文件损坏

Symptom: YAML parsing errors
Check:
bash
undefined
症状: YAML解析错误
检查:
bash
undefined

Validate YAML syntax

验证YAML语法

python -c "import yaml; yaml.safe_load(open('~/.claude/memory/global_learnings.yaml'))"

**Solution:**
```bash
python -c "import yaml; yaml.safe_load(open('~/.claude/memory/global_learnings.yaml'))"

**解决方案:**
```bash

1. Backup corrupted file

1. 备份损坏的文件

cp ~/.claude/memory/global_learnings.yaml ~/.claude/memory/global_learnings.yaml.bak
cp ~/.claude/memory/global_learnings.yaml ~/.claude/memory/global_learnings.yaml.bak

2. Restore from last good backup or reset

2. 从最近的良好备份恢复或重置

/claude-reflection --reset-memory --scope global
undefined
/claude-reflection --reset-memory --scope global
undefined

Too Many Low-Quality Learnings

低质量学习内容过多

Symptom: Memory files bloated with unvalidated learnings
Solution:
bash
undefined
症状: 内存文件中充满未验证的学习内容
解决方案:
bash
undefined

Prune learnings that:

清理以下学习内容:

- Have never been applied

- 从未被应用过

- Are older than 90 days

- 超过90天

- Have confidence < 0.5

- 置信度<0.5

/claude-reflection --prune --criteria "times_applied=0,age>90d,confidence<0.5"
undefined
/claude-reflection --prune --criteria "times_applied=0,age>90d,confidence<0.5"
undefined

Execution Checklist

执行检查清单

On Trigger Detection:
  • Identify trigger type (correction/preference/pattern)
  • Extract relevant information
  • Classify category
  • Determine appropriate scope
  • Check for existing similar learnings
  • Handle conflicts if any
  • Store with appropriate confidence
  • Log for session summary
At Session End:
  • Generate session summary
  • Review captured learnings
  • Flag any for user confirmation
  • Update confidence scores
  • Sync to storage
Periodic Maintenance:
  • Validate pending learnings
  • Prune stale learnings
  • Check for conflicts
  • Backup memory files
  • Review automation candidates
检测到触发条件时:
  • 识别触发类型(纠正/偏好/模式)
  • 提取相关信息
  • 分类类别
  • 确定合适的范围
  • 检查是否存在类似的现有学习内容
  • 处理潜在冲突
  • 按合适的置信度存储
  • 记录到会话总结
会话结束时:
  • 生成会话总结
  • 查看捕获的学习内容
  • 标记需要用户确认的内容
  • 更新置信度分数
  • 同步到存储
定期维护:
  • 验证待确认的学习内容
  • 清理过时的学习内容
  • 检查冲突
  • 备份内存文件
  • 查看自动化候选内容

Related Skills

相关技能

  • skill-learner - Creates skills from patterns
  • repo-readiness - Loads project context
  • session-start-routine - Session initialization
  • skill-learner - 从模式中创建技能
  • repo-readiness - 加载项目上下文
  • session-start-routine - 会话初始化

References

参考资料

  • Memory Management Best Practices
  • Learning Framework
  • YAML Configuration Standards

  • Memory Management Best Practices
  • Learning Framework
  • YAML Configuration Standards

Version History

版本历史

  • 1.0.0 (2026-01-17): Initial release - comprehensive meta-skill for self-improvement with Reflect-Abstract-Generalize-Store loop, multi-scope storage (global/domain/project/session), correction detection, preference capture, pattern extraction, cross-session learning, YAML persistence, validation framework, conflict resolution, and integration with progress tracking system
  • 1.0.0 (2026-01-17): 初始版本 - 包含Reflect-Abstract-Generalize-Store循环的全面自我提升元技能,多范围存储(全局/领域/项目/会话),纠正检测,偏好捕获,模式提取,跨会话学习,YAML持久化,验证框架,冲突解决,以及与进度跟踪系统的集成