Skill: shibing624/learn-from-experience (version 1.0.0)

--- name: learn-from-experience slug: learn-from-experience version: 1.3.0 description: "Learn from experience: self-reflection + self-criticism + self-learning + self-organizing memory + cross-session sync. Agent evaluates its own work, catches mistakes, and improves permanently. Compiles confirmed learnings to global config for automatic cross-session persistence. Use when (1) a command, tool, API, or operation fails; (2) the user corrects you or rejects your work; (3) you realize your knowledge is outdated or incorrect; (4) you discover a better approach; (5) the user explicitly installs or references the skill for the current task." changelog: "v1.3.0: Rebrand to learn-from-experience. Add cross-session memory sync protocol — compile confirmed preferences to agent global config for automatic loading in new sessions. Multi-agent compatibility: Claude Code, OpenClaw, Codex, CodeBuddy, opencode." metadata: {"clawdbot":{"emoji":"🧠","requires":{"bins":[]},"os":["linux","darwin","win32"],"configPaths":["~/learn-from-experience/"],"configPaths.optional":["./AGENTS.md","./SOUL.md","./HEARTBEAT.md"]}} --- ## When to Use User corrects you or points out mistakes. You complete significant work and want to evaluate the outcome. You notice something in your own output that could be better. Knowledge should compound over time without manual maintenance. ## Supported Agent Products This skill is agent-agnostic. It works with any product that loads a global config file on session start. | Product | Skill Install Path | Global Config File | Global Config Path | |---------|-------------------|--------------------|-------------------| | Claude Code | `~/.claude/skills/learn-from-experience/` | `CLAUDE.md` | `~/.claude/CLAUDE.md` | | OpenClaw | `~/.openclaw/skills/learn-from-experience/` | `AGENTS.md` | `~/.openclaw/AGENTS.md` | | Codex | `~/.codex/skills/learn-from-experience/` | `AGENTS.md` | `~/.codex/AGENTS.md` | | CodeBuddy | `~/.codebuddy/skills/learn-from-experience/` | `CODEBUDDY.md` | `~/.codebuddy/CODEBUDDY.md` | | opencode | `~/.config/opencode/skills/learn-from-experience/` | `AGENTS.md` | `~/.config/opencode/AGENTS.md` | The skill auto-detects which product is running by checking which config path exists. Memory data always lives in `~/learn-from-experience/` (shared across all products). ## Architecture Memory lives in `~/learn-from-experience/` with tiered structure. If `~/learn-from-experience/` does not exist, run `setup.md`. Workspace setup should add the standard steering to the workspace AGENTS, SOUL, and `HEARTBEAT.md` files, with recurring maintenance routed through `heartbeat-rules.md`. Confirmed preferences are compiled to the agent's global config `### Patterns` section for cross-session persistence (see Sync Protocol below). ``` ~/learn-from-experience/ ├── memory.md # HOT: <=100 lines, always loaded ├── index.md # Topic index with line counts + sync status ├── heartbeat-state.md # Heartbeat state: last run, reviewed change, action notes ├── projects/ # Per-project learnings ├── domains/ # Domain-specific (code, writing, comms) ├── archive/ # COLD: decayed patterns └── corrections.md # Last 50 corrections log ``` ## Quick Reference | Topic | File | |-------|------| | Setup guide | `setup.md` | | Heartbeat state template | `heartbeat-state.md` | | Memory template | `memory-template.md` | | Workspace heartbeat snippet | `HEARTBEAT.md` | | Heartbeat rules | `heartbeat-rules.md` | | Learning mechanics | `learning.md` | | Security boundaries | `boundaries.md` | | Scaling rules | `scaling.md` | | Memory operations | `operations.md` | | Self-reflection log | `reflections.md` | ## Requirements - No credentials required - No extra binaries required - Agent must have a global config file that auto-loads on session start ## Learning Signals Log automatically when you notice these patterns: **Corrections** -> add to `corrections.md`, evaluate for `memory.md`: - "No, that's not right..." - "Actually, it should be..." - "You're wrong about..." - "I prefer X, not Y" - "Remember that I always..." - "I told you before..." - "Stop doing X" - "Why do you keep..." - "bu dui, bu shi zhe yang de......" - "shi ji shang, ying gai shi......" - "ni gao cuo le......" - "wo geng xi huan X, bu shi Y" - "ji zhu wo yong yuan dou yao......" - "wo zhi qian gen ni shuo guo......" - "bie zai zuo X le" - "ni wei shen me yi zhi......" **Preference signals** -> add to `memory.md` if explicit: - "I like when you..." - "Always do X for me" - "Never do Y" - "My style is..." - "For [project], use..." - "ni zhe yang...de shi hou wo jue de hen hao" - "yi ding yao bang wo zuo X" - "yong yuan bu yao zuo Y" - "wo de feng ge shi......" - "zai [xiang mu] zhong yao yong......" **Pattern candidates** -> track, promote after 3x: - Same instruction repeated 3+ times - Workflow that works well repeatedly - User praises specific approach **Ignore** (don't log): - One-time instructions ("do X now") - Context-specific ("in this file...") - Hypotheticals ("what if...") ## Self-Reflection After completing significant work, pause and evaluate: 1. **Did it meet expectations?** -- Compare outcome vs intent 2. **What could be better?** -- Identify improvements for next time 3. **Is this a pattern?** -- If yes, log to `corrections.md` **When to self-reflect:** - After completing a multi-step task - After receiving feedback (positive or negative) - After fixing a bug or mistake - When you notice your output could be better **Log format:** ``` CONTEXT: [type of task] REFLECTION: [what I noticed] LESSON: [what to do differently] ``` **Example:** ``` CONTEXT: Flutter UI build REFLECTION: Spacing was wrong, had to redo LESSON: Check visual spacing before showing to user ``` Self-reflection entries follow the same promotion rules: 3x applied successfully -> promote to HOT. ## Quick Queries | User says | Action | |-----------|--------| | "What do you know about X?" | Search all tiers for X | | "What have you learned?" | Show last 10 from `corrections.md` | | "Show my patterns" | List `memory.md` (HOT) | | "Show [project] patterns" | Load `projects/{name}.md` | | "What's in warm storage?" | List files in `projects/` + `domains/` | | "Memory stats" | Show counts per tier | | "Forget X" | Remove from all tiers (confirm first) | | "Export memory" | ZIP all files | | "Sync memory" / "sync" | Run cross-session sync now | ## Memory Stats On "memory stats" request, report: ``` Learn-from-Experience Memory HOT (always loaded): memory.md: X entries WARM (load on demand): projects/: X files domains/: X files COLD (archived): archive/: X files Cross-session sync: Last sync: YYYY-MM-DD Status: in_sync | stale Recent activity (7 days): Corrections logged: X Promotions to HOT: X Demotions to WARM: X ``` ## Common Traps | Trap | Why It Fails | Better Move | |------|--------------|-------------| | Learning from silence | Creates false rules | Wait for explicit correction or repeated evidence | | Promoting too fast | Pollutes HOT memory | Keep new lessons tentative until repeated | | Reading every namespace | Wastes context | Load only HOT plus the smallest matching files | | Compaction by deletion | Loses trust and history | Merge, summarize, or demote instead | ## Core Rules ### 1. Learn from Corrections and Self-Reflection - Log when user explicitly corrects you - Log when you identify improvements in your own work - Never infer from silence alone - After 3 identical lessons -> ask to confirm as rule ### 2. Tiered Storage | Tier | Location | Size Limit | Behavior | |------|----------|------------|----------| | HOT | memory.md | <=100 lines | Always loaded | | WARM | projects/, domains/ | <=200 lines each | Load on context match | | COLD | archive/ | Unlimited | Load on explicit query | ### 3. Automatic Promotion/Demotion - Pattern used 3x in 7 days -> promote to HOT - Pattern unused 30 days -> demote to WARM - Pattern unused 90 days -> archive to COLD - Never delete without asking ### 4. Namespace Isolation - Project patterns stay in `projects/{name}.md` - Global preferences in HOT tier (memory.md) - Domain patterns (code, writing) in `domains/` - Cross-namespace inheritance: global -> domain -> project ### 5. Conflict Resolution When patterns contradict: 1. Most specific wins (project > domain > global) 2. Most recent wins (same level) 3. If ambiguous -> ask user ### 6. Compaction When file exceeds limit: 1. Merge similar corrections into single rule 2. Archive unused patterns 3. Summarize verbose entries 4. Never lose confirmed preferences ### 7. Transparency - Every action from memory -> cite source: "Using X (from projects/foo.md:12)" - Weekly digest available: patterns learned, demoted, archived - Full export on demand: all files as ZIP ### 8. Security Boundaries See `boundaries.md` -- never store credentials, health data, third-party info. ### 9. Graceful Degradation If context limit hit: 1. Load only memory.md (HOT) 2. Load relevant namespace on demand 3. Never fail silently -- tell user what's not loaded ## Cross-Session Sync Protocol ### Problem Memory in `~/learn-from-experience/memory.md` is only loaded when the skill is activated. The agent's global config file is automatically loaded every session. Without sync, learnings from one session are invisible to the next. ### Solution Compile confirmed preferences from `memory.md` into the global config's `### Patterns` section under `## Learnings`. This is a one-way compile: memory.md is the source of truth, global config is the read-only cache. ### When to Sync - After recording a user correction to Confirmed Preferences - After promote/demote/compact operations on memory.md - User explicitly says "sync memory" - Session end self-reflection if new confirmed rules were added this session ### Sync Rules 1. **Source**: Only `## Confirmed Preferences` entries from memory.md 2. **Format**: Each entry compiles to `- [tag] one-line description` 3. **Target**: `### Patterns` block under `## Learnings` in agent's global config 4. **Limit**: Max 30 lines; if exceeded, keep only HIGH priority + highest confidence entries 5. **Safety**: Only replace content between `### Patterns` header and the next `###` or `##` header. Never touch other global config content 6. **Timestamp**: Include sync timestamp in HTML comment after `### Patterns` header 7. **Stale detection**: On session start, check `~/learn-from-experience/index.md` sync status. If `stale`, auto-sync ### Sync Flow ``` 1. Read ~/learn-from-experience/memory.md -> extract ## Confirmed Preferences 2. Compile each entry: "### title | confidence" -> "- [tag] description" 3. Detect agent product -> locate global config file 4. Read global config file 5. Find ### Patterns block (create if missing, under ## Learnings) 6. Replace block content (preserve everything else) 7. Update ~/learn-from-experience/index.md sync timestamp + status ``` ### Agent Detection To find the correct global config file: ``` Check in order (first existing path wins): 1. ~/.claude/CLAUDE.md (Claude Code) 2. ~/.openclaw/AGENTS.md (OpenClaw) 3. ~/.codex/AGENTS.md (Codex) 4. ~/.codebuddy/CODEBUDDY.md (CodeBuddy) 5. ~/.config/opencode/AGENTS.md (opencode) ``` If multiple exist, sync to all of them (user may use multiple products). ## Session Lifecycle ``` Session Start: 1. Global config auto-loads (built-in to agent product) 2. Skill activates: read ~/learn-from-experience/memory.md (full HOT) 3. Check index.md sync status -> if stale, auto-sync 4. Detect project context -> load projects/{name}.md if needed Session Work: 5. Correction received -> write corrections.md + memory.md + sync global config 6. New pattern discovered -> write memory.md (tentative) [no sync until confirmed] Session End: 7. If new confirmed rules this session -> sync global config ``` ## Scope This skill ONLY: - Learns from user corrections and self-reflection - Stores preferences in local files (`~/learn-from-experience/`) - Syncs confirmed preferences to agent's global config `### Patterns` section - Maintains heartbeat state in `~/learn-from-experience/heartbeat-state.md` when the workspace integrates heartbeat - Reads its own memory files on activation This skill NEVER: - Accesses calendar, email, or contacts - Makes network requests - Reads files outside `~/learn-from-experience/` and the agent's global config file - Infers preferences from silence or observation - Deletes or blindly rewrites memory during heartbeat cleanup - Modifies its own SKILL.md - Touches global config content outside the `### Patterns` block ## Data Storage Local state lives in `~/learn-from-experience/`: - `memory.md` for HOT rules and confirmed preferences - `corrections.md` for explicit corrections and reusable lessons - `projects/` and `domains/` for scoped patterns - `archive/` for decayed or inactive patterns - `heartbeat-state.md` for recurring maintenance markers - `index.md` for tier index + cross-session sync status ## Related Skills Install with `clawhub install <slug>` if user confirms: - `memory` -- Long-term memory patterns for agents - `learning` -- Adaptive teaching and explanation - `decide` -- Auto-learn decision patterns - `escalate` -- Know when to ask vs act autonomously

path: corrections.md
content: # 更正日志 — 模板

> 该文件会在你首次使用本技能时创建于`~/learn-from-experience/corrections.md`。
> 仅保留最近50条更正，旧条目会评估是否升级留存或归档。


## 示例条目

```markdown
## 2026-02-19

### 14:32 — 代码风格
- **Correction:** "使用2空格缩进，不要用4空格"
- **Context:** 编辑TypeScript文件
- **Count:** 1（首次出现）

### 16:15 — 沟通规范
- **Correction:** "不要用'好问题！'开头回复"
- **Context:** 聊天回复
- **Count:** 3 → **已添加至memory.md**

## 2026-02-18

### 09:00 — Project: website
- **Correction:** "本项目统一使用Tailwind"
- **Context:** CSS样式讨论
- **Action:** 已添加至projects/website.md
```

## Log Format

Each entry includes:
- **Timestamp** — 更正发生的时间
- **Correction** — 用户提出的更正要求
- **Context** — 触发更正的场景
- **Count** — 累计出现次数（用于优化追踪）
- **Action** — 优化后存储的位置（若已优化）


path: memory-template.md
content: # Memory Template

> This file is created in `~/learn-from-experience/memory.md` on first use.
> Keep it <=100 lines. Most-used patterns live here.

## Example Entries

```markdown
# Learn-from-Experience Memory

## Confirmed Preferences
<!-- Patterns confirmed by user, never decay -->

### simplicity_first | 0.98
Simple > complex; experiment proves before adopting complex solutions.

### verify_before_answer | 0.99 | HIGH
Never speculate technical details; read source/config first. Say "let me check" when uncertain.

## Active Patterns
<!-- Patterns observed 3+ times, subject to decay -->

### dataset_stats_first | 0.95
Calculate baseline stats before designing experiments. top-k/total > 10% means too easy.

## Recent (last 7 days)
<!-- New corrections pending confirmation -->
- prefer SQLite for MVPs (corrected 02-14)
```

## Usage

The agent will:
1. Load this file on every session
2. Add entries when patterns are used 3x in 7 days
3. Demote unused entries to WARM after 30 days
4. Never exceed 100 lines (compacts automatically)
5. Confirmed Preferences are auto-synced to the agent's global config for cross-session persistence

## Initial Directory Structure

Create on first activation:

```bash
mkdir -p ~/learn-from-experience/{projects,domains,archive}
touch ~/learn-from-experience/{memory.md,index.md,corrections.md,heartbeat-state.md}
```

## Index Template

For `~/learn-from-experience/index.md`:

```markdown
# Memory Index

## HOT
- memory.md: 0 lines

## WARM
- (no namespaces yet)

## COLD
- (no archives yet)

Last update: never

## Sync Status
Last global config sync: never
memory.md last modified: never
Sync status: pending_first_sync
```

## Corrections Log Template

For `~/learn-from-experience/corrections.md`:

```markdown
# Corrections Log

<!-- Format:
## YYYY-MM-DD
- [HH:MM] Changed X -> Y
  Type: format|technical|communication|project
  Context: What was corrected
  Confirmed: pending (N/3) | yes | no
-->
```

## Heartbeat State Template

For `~/learn-from-experience/heartbeat-state.md`:

```markdown
# Learn-from-Experience Heartbeat State

last_heartbeat_started_at: never
last_reviewed_change_at: never
last_heartbeat_result: never

## Last actions
- none yet
```


path: operations.md
content: # Memory Operations

## User Commands

| Command | Action |
|---------|--------|
| "What do you know about X?" | Search all tiers, return matches with sources |
| "Show my memory" | Display memory.md contents |
| "Show [project] patterns" | Load and display specific namespace |
| "Forget X" | Remove from all tiers, confirm deletion |
| "Forget everything" | Full wipe with export option |
| "Recent changes?" | Show last 20 corrections |
| "Export memory" | Generate downloadable archive |
| "Memory stats" | Show tier sizes, last compaction, sync status |
| "Sync memory" | Trigger cross-session sync now |


## Automatic Operations

### On Session Start
1. Load memory.md (HOT tier)
2. Check index.md for context hints and sync status
3. If sync status is `stale` -> detect agent product -> run global config sync
4. If project detected -> preload relevant namespace

### On Correction Received
```
1. Parse correction type (preference, pattern, override)
2. Check if duplicate (exists in any tier)
3. If new:
   - Add to corrections.md with timestamp
   - Increment correction counter
4. If duplicate:
   - Bump counter, update timestamp
   - If counter >= 3: ask to confirm as rule
5. Determine namespace (global, domain, project)
6. Write to appropriate file
7. Update index.md line counts
8. If written to Confirmed Preferences -> trigger global config sync
```

### On Pattern Match
When applying learned pattern:
```
1. Find pattern source (file:line)
2. Apply pattern
3. Cite source: "Using X (from memory.md:15)"
4. Log usage for decay tracking
```

### Weekly Maintenance (Cron)
```
1. Scan all files for decay candidates
2. Move unused >30 days to WARM
3. Archive unused >90 days to COLD
4. Run compaction if any file >limit
5. Update index.md
6. Generate weekly digest (optional)
7. Check sync status -> if stale, run global config sync
```

## Global Config Sync Operation

### Trigger Conditions
- Correction promoted to Confirmed Preferences
- memory.md promote/demote/compact completed
- User says "sync memory"
- Session end with new confirmed rules

### Agent Detection
```
Check in order (first existing path wins):
1. ~/.claude/CLAUDE.md              (Claude Code)
2. ~/.openclaw/AGENTS.md            (OpenClaw)
3. ~/.codex/AGENTS.md               (Codex)
4. ~/.codebuddy/CODEBUDDY.md        (CodeBuddy)
5. ~/.config/opencode/AGENTS.md     (opencode)
If multiple exist, sync to all of them.
```

### Sync Procedure
```
1. Read ~/learn-from-experience/memory.md
2. Extract ## Confirmed Preferences section
3. For each entry "### title | confidence [| priority]":
   - Derive tag from title (snake_case, abbreviated)
   - Compile to: "- [tag] one-line core description"
   - If priority is HIGH, mark for retention during truncation
4. Detect agent product(s) -> locate global config file(s)
5. For each global config file:
   a. Read the file
   b. Locate ### Patterns block under ## Learnings
      - If ## Learnings not found: create it at the end of the file
      - If ### Patterns not found: create it after the last ### under ## Learnings
   c. Replace content between ### Patterns header and next ###/## header
      - Preserve the comment line with updated timestamp
      - Write compiled entries (max 30 lines)
      - If > 30 entries: keep HIGH priority first, then by confidence desc
6. Update ~/learn-from-experience/index.md:
   - Set "Last global config sync:" to today
   - Set "Sync status: in_sync"
7. Confirm to user: "Synced N entries to global config"
```

### Stale Detection
```
On skill activation:
1. Read ~/learn-from-experience/index.md
2. Compare "Last global config sync" vs "memory.md last modified"
3. If memory.md is newer -> set "Sync status: stale"
4. If stale -> auto-sync and notify user
```

### Safety Guards
- ONLY modify ### Patterns block; never touch other global config content
- Before write: verify old content was correctly located (check surrounding headers)
- After write: count lines in ### Patterns block; if > 30, truncate and warn
- If global config read fails: skip sync, log warning, do not block session

## File Formats

### memory.md (HOT)
```markdown
# Learn-from-Experience Memory

## Confirmed Preferences
- format: bullet points over prose (confirmed 2026-01)
- tone: direct, no hedging (confirmed 2026-01)

## Active Patterns
- "looks good" = approval to proceed (used 15x)
- single emoji = acknowledged (used 8x)

## Recent (last 7 days)
- prefer SQLite for MVPs (corrected 02-14)
```

### corrections.md
```markdown
# Corrections Log

## 2026-02-15
- [14:32] Verbose explanation -> bullet summary
  Type: communication
  Context: Chat response
  Confirmed: pending (1/3)

## 2026-02-14
- [09:15] Use SQLite not Postgres for MVP
  Type: technical
  Context: database discussion
  Confirmed: yes (said "always")
```

### projects/{name}.md
```markdown
# Project: my-app

Inherits: global, domains/code

## Patterns
- Use Tailwind (project standard)
- No Prettier (eslint only)
- Deploy via GitLab CI

## Overrides
- semicolons: yes (overrides global no-semi)

## History
- Created: 2026-01-15
- Last active: 2026-02-15
- Corrections: 12
```

## Edge Case Handling

### Contradiction Detected
```
Pattern A: "Use tabs" (global, confirmed)
Pattern B: "Use spaces" (project, corrected today)

Resolution:
1. Project overrides global -> use spaces for this project
2. Log conflict in corrections.md
3. Ask: "Should spaces apply only to this project or everywhere?"
```

### User Changes Mind
```
Old: "Always use formal tone"
New: "Actually, casual is fine"

Action:
1. Archive old pattern with timestamp
2. Add new pattern as tentative
3. Keep archived for reference ("You previously preferred formal")
```

### Context Ambiguity
```
User says: "Remember I like X"

But which namespace?
1. Check current context (project? domain?)
2. If unclear, ask: "Should this apply globally or just here?"
3. Default to most specific active context
```

### Multiple Agent Products
```
User has both Claude Code and CodeBuddy installed.

Action:
1. Sync writes to ALL detected global config files
2. memory.md remains the single source of truth
3. Each product reads its own global config independently
```


path: setup.md
content: # Setup -- Learn from Experience

## Supported Agent Products

| Product | Global Config File | Global Config Path |
|---------|-------------------|-------------------|
| Claude Code | `CLAUDE.md` | `~/.claude/CLAUDE.md` |
| OpenClaw | `AGENTS.md` | `~/.openclaw/AGENTS.md` |
| Codex | `AGENTS.md` | `~/.codex/AGENTS.md` |
| CodeBuddy | `CODEBUDDY.md` | `~/.codebuddy/CODEBUDDY.md` |
| opencode | `AGENTS.md` | `~/.config/opencode/AGENTS.md` |

## First-Time Setup

### 1. Create Memory Structure

```bash
mkdir -p ~/learn-from-experience/{projects,domains,archive}
```

### 2. Initialize Core Files

Create `~/learn-from-experience/memory.md` using `memory-template.md`:

```markdown
Copy the structure from `memory-template.md` into `~/learn-from-experience/memory.md`.
```

Memory file baseline:
```markdown
# Learn-from-Experience Memory

## Confirmed Preferences
<!-- Patterns confirmed by user, never decay -->

## Active Patterns
<!-- Patterns observed 3+ times, subject to decay -->

## Recent (last 7 days)
<!-- New corrections pending confirmation -->
```

Create `~/learn-from-experience/corrections.md`:
```markdown
# Corrections Log

| Date | What I Got Wrong | Correct Answer | Status |
|------|-----------------|----------------|--------|
```

Create `~/learn-from-experience/index.md`:
```markdown
# Memory Index

## HOT
- memory.md: 0 lines

## WARM
- (no namespaces yet)

## COLD
- (no archives yet)

Last update: never

## Sync Status
Last global config sync: never
memory.md last modified: never
Sync status: pending_first_sync
```

Create `~/learn-from-experience/heartbeat-state.md`:
```markdown
# Learn-from-Experience Heartbeat State

last_heartbeat_started_at: never
last_reviewed_change_at: never
last_heartbeat_result: never

## Last actions
- none yet
```

### 3. Initialize Cross-Session Sync

Detect the agent product and ensure the global config has a `## Learnings` section with `### Patterns` block:

```
For each detected global config file:
  1. Read the file
  2. If ## Learnings section exists:
     - Check for ### Patterns subsection
     - If missing, add it after existing ### subsections
  3. If ## Learnings section missing:
     - Append at end of file:
       ## Learnings
       ### Patterns
       <!-- Auto-synced from ~/learn-from-experience/memory.md | Last sync: never -->
  4. Do NOT modify any existing content
```

### 4. Choose Operating Mode

Add to your AGENTS.md or workspace config:

```markdown
## Learn-from-Experience Mode

Current mode: Passive

Available modes:
- Passive: Only learn from explicit corrections
- Active: Suggest patterns after 3x repetition
- Strict: Require confirmation for every entry
```

### 5. Add SOUL.md Steering

Add this section to your `SOUL.md`:

```markdown
**Learn from Experience**
Compounding execution quality is part of the job.
Before non-trivial work, load `~/learn-from-experience/memory.md` and only the smallest relevant domain or project files.
After corrections, failed attempts, or reusable lessons, write one concise entry to the correct file in `~/learn-from-experience/` immediately.
Prefer learned rules when relevant, but keep self-inferred rules revisable.
Do not skip retrieval just because the task feels familiar.
```

### 6. Add the Proactivity Companion as Part of Setup

At the end of setup, briefly tell the user that you are going to add characteristics so the agent is more proactive:

- noticing missing next steps
- verifying outcomes instead of assuming they landed
- recovering context better after long or interrupted threads
- keeping the right level of initiative

Then say that, for this, you are going to install the `Proactivity` skill.
Only install it after the user explicitly agrees.

If the user agrees:

1. Run `clawhub install proactivity`
2. Read the installed `proactivity` skill
3. Continue into its setup flow immediately so the skill is active for this workspace

If the user says no, skip it cleanly and continue with learn-from-experience only.

### 7. Refine AGENTS.md Memory Section (Non-Destructive)

Update `AGENTS.md` by complementing the existing `## Memory` section. Do not replace the whole section and do not remove existing lines.

If your `## Memory` block differs from the default template, insert the same additions in equivalent places so existing information is preserved.

Add this line in the continuity list (next to Daily notes and Long-term):

```markdown
- **Learn from experience:** `~/learn-from-experience/` (via `learn-from-experience` skill) -- execution-improvement memory (preferences, workflows, style patterns, what improved/worsened outcomes)
```

Right after the sentence "Capture what matters...", add:

```markdown
Use `memory/YYYY-MM-DD.md` and `MEMORY.md` for factual continuity (events, context, decisions).
Use `~/learn-from-experience/` for compounding execution quality across tasks.
For compounding quality, read `~/learn-from-experience/memory.md` before non-trivial work, then load only the smallest relevant domain or project files.
If in doubt, store factual history in `memory/YYYY-MM-DD.md` / `MEMORY.md`, and store reusable performance lessons in `~/learn-from-experience/` (tentative until human validation).
```

Before the "Write It Down" subsection, add:

```markdown
Before any non-trivial task:
- Read `~/learn-from-experience/memory.md`
- List available files first:
  ```bash
  for d in ~/learn-from-experience/domains ~/learn-from-experience/projects; do
    [ -d "$d" ] && find "$d" -maxdepth 1 -type f -name "*.md"
  done | sort
  ```
- Read up to 3 matching files from `~/learn-from-experience/domains/`
- If a project is clearly active, also read `~/learn-from-experience/projects/<project>.md`
- Do not read unrelated domains "just in case"

If inferring a new rule, keep it tentative until human validation.
```

Inside the "Write It Down" bullets, refine the behavior (non-destructive):
- Keep existing intent, but route execution-improvement content to `~/learn-from-experience/`.
- If the exact bullets exist, replace only these lines; if wording differs, apply equivalent edits without removing unrelated guidance.

Use this target wording:

```markdown
- When someone says "remember this" -> if it's factual context/event, update `memory/YYYY-MM-DD.md`; if it's a correction, preference, workflow/style choice, or performance lesson, log it in `~/learn-from-experience/`
- Explicit user correction -> append to `~/learn-from-experience/corrections.md` immediately
- Reusable global rule or preference -> append to `~/learn-from-experience/memory.md`
- Domain-specific lesson -> append to `~/learn-from-experience/domains/<domain>.md`
- Project-only override -> append to `~/learn-from-experience/projects/<project>.md`
- Keep entries short, concrete, and one lesson per bullet; if scope is ambiguous, default to domain rather than global
- After a correction or strong reusable lesson, write it before the final response
```

### 8. Add HEARTBEAT.md Steering

Add this section to your `HEARTBEAT.md`:

```markdown
## Learn-from-Experience Check

- Read `./skills/learn-from-experience/heartbeat-rules.md`
- Use `~/learn-from-experience/heartbeat-state.md` for last-run markers and action notes
- If no file inside `~/learn-from-experience/` changed since the last reviewed change, return `HEARTBEAT_OK`
```

Keep this in the same default setup flow as the AGENTS and SOUL additions so recurring maintenance is installed consistently.
If your installed skills path differs, keep the same three lines but point the first line at the installed copy of `heartbeat-rules.md`.

## Verification

Run "memory stats" to confirm setup:

```
Learn-from-Experience Memory

HOT (always loaded):
   memory.md: 0 entries

WARM (load on demand):
   projects/: 0 files
   domains/: 0 files

COLD (archived):
   archive/: 0 files

Cross-session sync:
   Last sync: never
   Status: pending_first_sync

Mode: Passive
```


path: heartbeat-rules.md
content: # Heartbeat Rules

Use heartbeat to keep `~/learn-from-experience/` organized without creating churn or losing data.

## Source of Truth

Keep the workspace `HEARTBEAT.md` snippet minimal.
Treat this file as the stable contract for learn-from-experience heartbeat behavior.
Store mutable run state only in `~/learn-from-experience/heartbeat-state.md`.

## Start of Every Heartbeat

1. Ensure `~/learn-from-experience/heartbeat-state.md` exists.
2. Write `last_heartbeat_started_at` immediately in ISO 8601.
3. Read the previous `last_reviewed_change_at`.
4. Scan `~/learn-from-experience/` for files changed after that moment, excluding `heartbeat-state.md` itself.

## If Nothing Changed

- Set `last_heartbeat_result: HEARTBEAT_OK`
- Append a short "no material change" note if you keep an action log
- Return `HEARTBEAT_OK`

## If Something Changed

Only do conservative organization:

- refresh `index.md` if counts or file references drift
- compact oversized files by merging duplicates or summarizing repetitive entries
- move clearly misplaced notes to the right namespace only when the target is unambiguous
- preserve confirmed rules and explicit corrections exactly
- update `last_reviewed_change_at` only after the review finishes cleanly
- check cross-session sync status; if `stale`, run global config sync

## Safety Rules

- Most heartbeat runs should do nothing
- Prefer append, summarize, or index fixes over large rewrites
- Never delete data, empty files, or overwrite uncertain text
- Never reorganize files outside `~/learn-from-experience/`
- If scope is ambiguous, leave files untouched and record a suggested follow-up instead

## State Fields

Keep `~/learn-from-experience/heartbeat-state.md` simple:

- `last_heartbeat_started_at`
- `last_reviewed_change_at`
- `last_heartbeat_result`
- `last_actions`

## Behavior Standard

Heartbeat exists to keep the memory system tidy and trustworthy.
If no rule is clearly violated, do nothing.


path: learning.md
content: # Learning Mechanics 学习机制

## What Triggers Learning 触发学习的场景

| Trigger | Confidence | Action |
|---------|------------|--------|
| "不，换做X操作" | High | Log correction immediately |
| "我之前告诉过你..." | High | Flag as repeated, bump priority |
| "永远/永远不要做X" | Confirmed | Promote to preference |
| 用户编辑你的输出 | Medium | Log as tentative pattern |
| 同一更正出现3次 | Confirmed | Ask to make permanent |
| "针对本项目..." | Scoped | Write to project namespace |

## What Does NOT Trigger Learning 不会触发学习的场景

- 沉默（不代表确认）
- 任何内容仅出现一次
- 假设性讨论
- 第三方偏好（比如"约翰喜欢..."）
- 群聊模式（除非用户确认）
- 隐含偏好（绝不自行推断）

## Correction Classification 更正分类

### By Type 按类型分
| Type | Example | Namespace |
|------|---------|-----------|
| Format | "用项目符号不要用散文" | global |
| Technical | "用SQLite不用Postgres" | domain/code |
| Communication | "消息更短一点" | global |
| Project-specific | "本仓库用Tailwind" | projects/{name} |
| Person-specific | "马库斯要求结论优先" | domains/comms |

### By Scope 按作用域分
```
Global: applies everywhere 即所有场景生效
  └── Domain: applies to category (code, writing, comms) 即对应分类生效（代码、写作、沟通）
       └── Project: applies to specific context 即特定上下文生效
            └── Temporary: applies to this session only 即仅本次会话生效
```

## Confirmation Flow 确认流程

After 3 similar corrections（三次相似更正后触发）:
```
Agent: "我注意到你相比 Y 更偏好 X（已更正 3 次）.
        需要我后面一直这么做吗？?
        - Yes, always  
        - Only in [context]
        - No, case by case"

User: "Yes, always" or  User: "是的" or User: "好"

Agent: → Moves to Confirmed Preferences
       → Removes from correction counter
       → Cites source on future use
```

## Pattern Evolution 模式演化

### Stages 阶段
1. **Tentative** — Single correction, watch for repetition
2. **Emerging** — 2 corrections, likely pattern
3. **Pending** — 3 corrections, ask for confirmation
4. **Confirmed** — User approved, permanent unless reversed
5. **Archived** — Unused 90+ days, preserved but inactive

### Reversal 撤销规则
User can always reverse:
```
User: "我改变了对 X 的想法"

Agent: 
1. Archive old pattern (keep history)
2. Log reversal with timestamp
3. Add new preference as tentative
4. "明白了，我接下来会用 Y. (Previous: X, archived)"
```

## Anti-Patterns 反模式

### Never Learn 绝对禁止学习
- What makes user comply faster (manipulation)
- Emotional triggers or vulnerabilities
- Patterns from other users (even if shared device)
- Anything that feels "creepy" to surface

### Avoid 需要避免
- Over-generalizing from single instance
- Learning style over substance
- Assuming preference stability
- Ignoring context shifts

## Quality Signals 质量信号

### Good Learning 好的学习
- User explicitly states preference（用户明确说明偏好）
- Pattern consistent across contexts（模式在不同上下文保持一致）
- Correction improves outcomes（更正后输出结果变好）
- User confirms when asked（询问后得到用户确认）

### Bad Learning 坏的学习
- Inferred from silence（从沉默推断得出）
- Contradicts recent behavior（和近期行为矛盾）
- Only works in narrow context（仅在极窄上下文生效）
- User never confirmed（用户从未确认）


path: HEARTBEAT.md
content: ## Learn-from-Experience Check

- Read `./skills/learn-from-experience/heartbeat-rules.md`
- Use `~/learn-from-experience/heartbeat-state.md` for last-run markers and action notes
- If no file inside `~/learn-from-experience/` changed since the last reviewed change, return `HEARTBEAT_OK`
- Check cross-session sync status in `~/learn-from-experience/index.md`; if `stale`, trigger global config sync


path: boundaries.md
content: # Security Boundaries 安全边界

## Never Store 绝不存储

| Category | Examples | Why |
|----------|----------|-----|
|身份凭证|密码、API 密钥、令牌、SSH 密钥|安全泄露风险|
|金融信息|银行卡号、银行账户、加密货币助记词|欺诈风险|
|医疗信息|诊断结果、用药方案、健康状况|隐私保护、HIPAA合规|
|生物识别信息|语音声纹、行为特征指纹|身份盗用风险|
|第三方信息|关于其他人员的信息|未获得第三方知情同意|
|位置轨迹|家庭/工作地址、日常作息规律|人身安全|
|权限特征|用户可访问的系统范围|权限提升风险|

## Store with Caution 谨慎存储

| Category | Rules |
|----------|-------|
|工作上下文|项目结束后自动清除，禁止跨项目共享|
|情绪状态|仅存储用户明确分享的内容，禁止自行推断|
|人际关系|仅存储角色身份（如「经理」「客户」），不保留个人细节|
|日程安排|可存储大致规律（如「上午忙碌」），不存储具体时间点|

## Transparency Requirements 透明度要求

1. **Audit on demand** — 用户询问 "你存储了哪些关于我的信息？?" → 必须完整输出
2. **Source tracking** — 每一条存储信息都必须标记获取的时间与方式
3. **Explain actions** — "格式为「我执行X操作，是因为你在[date]提出了Y要求」"
4. **No hidden state** — 任何会影响行为决策的信息，都必须对外可见
5. **Deletion verification** — 确认目标信息已移除，展示更新后的数据

## Red Flags to Catch 需要警惕的危险信号

如果你发现自己出现以下任何行为，立刻停止：

- 仅出于「日后可能有用」的目的存储信息
- 从非敏感数据中推断敏感信息
- 用户要求删除后仍保留数据
- 将个人上下文套用至工作场景，或将工作上下文套用至个人场景
- 总结能让用户更快依从的规律
- 构建用户心理画像
- 留存第三方信息

## Kill Switch  

当用户要求「忘记一切」时：
1. 将当前所有记忆导出为文件（方便用户复查）
2. 彻底清除所有习得数据
3. 确认提示：「已清空记忆，重新启动。」
4. 不得在行为中保留任何「隐形残留模式」


## Consent Model 授权规则

|数据类型|授权要求|
|-----------|---------------|
|明确更正内容|更正行为本身即代表隐含授权|
|推断得出的偏好|观察3次后需主动询问用户确认|
|上下文/项目数据|首次检测到需要存储时主动询问|
|跨会话行为规律|需要用户明确选择同意后才可存储|


path: reflections.md
content: # Self-Reflections Log 

Track self-reflections from completed work. Each entry captures what the agent learned from evaluating its own output.

## Format

```
## [Date] — [Task Type]

**What I did:** 简要描述
**Outcome:** 实际结果 (成功, 部分完成, 失败)
**Reflection:** 我对本次工作的观察
**Lesson:** 下次该做出什么调整
**Status:** ⏳ candidate | ✅ promoted | 📦 archived
```

## Example Entry

```
## 2026-02-25 — Flutter UI Build

**What I did:** 开发了带切换开关的设置页
**Outcome:** 用户反馈："间距不对"
**Reflection:** 我只关注了功能，没有做视觉检查
**Lesson:** 交付给用户前，一定要截图检查视觉平衡
**Status:** ✅ promoted to domains/flutter.md
```

## Entries

(New entries appear here)


path: memory.md
content: # HOT Memory — Template

> This file is created in `~/learn-from-experience/memory.md` when you first use the skill.
> Keep it ≤100 lines. Most-used patterns live here.

## Example Entries

```markdown
## Preferences
- Code style: Prefer explicit over implicit
- Communication: Direct, no fluff
- Time zone: Asia/Shanghai

## Patterns (promoted from corrections)
- Always use TypeScript strict mode
- Prefer pnpm over npm
- Format: ISO 8601 for dates

## Project defaults
- Tests: Jest with coverage >80%
- Commits: Conventional commits format
```

## Usage

The agent will:
1. Load this file on every session
2. Add entries when patterns are used 3x in 7 days
3. Demote unused entries to WARM after 30 days
4. Never exceed 100 lines (compacts automatically)


path: scaling.md
content: # Scaling Patterns

## Volume Thresholds

| Scale | Entries | Strategy |
|-------|---------|----------|
| Small | <100 | Single memory.md, no namespacing |
| Medium | 100-500 | Split into domains/, basic indexing |
| Large | 500-2000 | Full namespace hierarchy, aggressive compaction |
| Massive | >2000 | Archive yearly, summary-only HOT tier |

## When to Split

Create new namespace file when:
- Single file exceeds 200 lines
- Topic has 10+ distinct corrections
- User explicitly separates contexts ("for work...", "in this project...")

## Compaction Rules

### Merge Similar Corrections
```
BEFORE (3 entries):
- [02-01] Use tabs not spaces
- [02-03] Indent with tabs
- [02-05] Tab indentation please

AFTER (1 entry):
- Indentation: tabs (confirmed 3x, 02-01 to 02-05)
```

### Summarize Verbose Patterns
```
BEFORE:
- When writing emails to Marcus, use bullet points, keep under 5 items,
  no jargon, bottom-line first, he prefers morning sends

AFTER:
- Marcus emails: bullets <=5, no jargon, BLUF, AM preferred
```

### Archive with Context
When moving to COLD:
```
## Archived 2026-02

### Project: old-app (inactive since 2025-08)
- Used Vue 2 patterns
- Preferred Vuex over Pinia
- CI on Jenkins (deprecated)

Reason: Project completed, patterns unlikely to apply
```

## Index Maintenance

`index.md` tracks all namespaces plus sync status:
```markdown
# Memory Index

## HOT (always loaded)
- memory.md: 87 lines, updated 2026-02-15

## WARM (load on match)
- projects/current-app.md: 45 lines
- projects/side-project.md: 23 lines
- domains/code.md: 112 lines
- domains/writing.md: 34 lines

## COLD (archive)
- archive/2025.md: 234 lines
- archive/2024.md: 189 lines

Last compaction: 2026-02-01
Next scheduled: 2026-03-01

## Sync Status
Last global config sync: 2026-02-15
memory.md last modified: 2026-02-15
Sync status: in_sync
```

## Multi-Project Patterns

### Inheritance Chain
```
global (memory.md)
  |-- domain (domains/code.md)
       |-- project (projects/app.md)
```

### Override Syntax
In project file:
```markdown
## Overrides
- indentation: spaces (overrides global tabs)
- Reason: Project eslint config requires spaces
```

### Conflict Detection
When loading, check for conflicts:
1. Build inheritance chain
2. Detect contradictions
3. Most specific wins
4. Log conflict for later review

## User Type Adaptations

| User Type | Memory Strategy |
|-----------|-----------------|
| Power user | Aggressive learning, minimal confirmation |
| Casual | Conservative learning, frequent confirmation |
| Team shared | Per-user namespaces, shared project space |
| Privacy-focused | Local-only, explicit consent per category |

## Recovery Patterns

### Context Lost
If agent loses context mid-session:
1. Re-read memory.md
2. Check index.md for relevant namespaces
3. Load active project namespace
4. Continue with restored patterns

### Corruption Recovery
If memory file corrupted:
1. Check archive/ for recent backup
2. Rebuild from corrections.md
3. Ask user to re-confirm critical preferences
4. Log incident for debugging

### Sync Recovery
If global config sync fails or global config is corrupted:
1. memory.md is always the source of truth
2. Re-run sync from memory.md to rebuild ### Patterns block
3. If global config file is missing, skip sync (agent product may not be installed)
4. Never attempt to recover memory.md from global config (one-way sync only)


path: openclaw-heartbeat.md
content: ## Learn-from-Experience Check (OpenClaw)

- Read `./skills/learn-from-experience/heartbeat-rules.md`
- Use `~/learn-from-experience/heartbeat-state.md` for last-run markers and action notes
- If no file inside `~/learn-from-experience/` changed since the last reviewed change, return `HEARTBEAT_OK`
- Check cross-session sync status in `~/learn-from-experience/index.md`; if `stale`, trigger global config sync

Note: OpenClaw uses the same memory directory (`~/learn-from-experience/`) and the same sync protocol as all other agent products.


path: heartbeat-state.md
content: # Heartbeat State Template

Use this file as the baseline for `~/learn-from-experience/heartbeat-state.md`.
It stores only lightweight run markers and maintenance notes.

```markdown
# Learn-from-Experience Heartbeat State

last_heartbeat_started_at: never
last_reviewed_change_at: never
last_heartbeat_result: never

## Last actions
- none yet
```

## Rules

- update `last_heartbeat_started_at` at the beginning of every heartbeat
- update `last_reviewed_change_at` only after a clean review of changed files
- keep `last_actions` short and factual
- never turn this file into another memory log


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (CRITICAL)