AGENT SKILL

经验教训捕获与知识沉淀

learn

从失败、纠正、重复错误、成功恢复模式或直接的 /learn 请求中捕获持久化经验教训。当用户调用 /learn、要求保存/记住/记录一条经验,或某次工作流失败应转化为可复用的流程知识时使用。始终持久化到 Claude memory、可选的 mem0、roadmap 日志(ROADMAP_DIR)、beads 以及 wiki-ingest(WIKI_ROOT)。

License 许可
MIT
最近更新
2026-11-14
Stars
★ 6
Forks
0

01 前言 Front Matter

name
learn
description
Capture durable learnings from failures, corrections, repeated mistakes, successful recovery patterns, or direct /learn requests. Use whenever the user invokes /learn, asks to save/remember/capture a lesson, or when a workflow failure should become reusable process knowledge. Always persist to Claude memory, optional mem0, the roadmap log (ROADMAP_DIR), beads, and wiki-ingest (WIKI_ROOT).

03 SKILL.md 正文

Learn

Use this skill to turn a concrete lesson into durable, discoverable artifacts. Do not stop at a chat summary. A complete learning capture writes the file-backed records that future agents and reviewers will actually find.

Required outputs

Every confirmed learning must produce or update all of these:

  1. Claude auto-memory under ~/.claude/projects/<project-key>/memory/.
  2. Optional mem0 save when the configured helper and mem0 package are available (see step 3 gates).
  3. Monthly roadmap log at ${ROADMAP_DIR:-$HOME/roadmap}/learnings-YYYY-MM.md (skip and report when that directory is absent).
  4. A closed or referenced bead in .beads/issues.jsonl when the current repo has beads.
  5. LLM wiki ingest under the configured wiki (resolved following wiki-ingest's exact 4-step order: --wiki <path> override if passed, .wiki-default in repo root, ~/.wiki-default in home, or $WIKI_ROOT/wiki; report "WIKI_ROOT not configured" and skip when no wiki is configured): raw source copy, source page, index entry, log entry, and relevant concept/entity updates.

If a persistence target is unavailable, report the exact blocker and continue with the remaining targets. Do not silently skip wiki ingest.

Workflow

1. Extract the learning

  • If the user supplied a lesson, use it as the source.
  • If the user invoked /learn without specifics, inspect the recent conversation and extract the most actionable failure, correction, or pattern.
  • Classify it as Critical, Mandatory, Best Practice, or Anti-Pattern.
  • Prefer precise references: PR URLs, commit SHAs, file paths, commands, error strings, artifacts, and verification results.
  • Search existing local records before writing:
    • ~/.claude/projects/**/memory
    • ${ROADMAP_DIR:-$HOME/roadmap}/learnings-*.md
    • .beads/issues.jsonl
    • $WIKI_ROOT/wiki/index.md and relevant concepts/ pages (when configured)

1a. Fix vs. Document decision (apply BEFORE writing the memory entry)

Workarounds-as-memory are NOT a complete resolution when a small fix is possible. Apply the fix-on-discovery rule from ~/.claude/CLAUDE.md:

Bug class Action
User-managed config (yaml/plist/dotfile) + fix < 10 lines + currently blocking FIX IT NOW, then write memory entry that references the fix (commit SHA, diff, or <config-file>:line). Memory body must say "FIX: <what> at <where> on <date>" — not just "workaround: ..."
User's published code in a separate PR scope (separate repo, separate concern) Document workaround; open a dedicated fix PR; memory links the fix PR
Third-party code (provider outage, npm package, OS-level) Workaround only — no fix possible from here. Memory describes the trigger conditions and the recovery path
Agent-orchestrator core code in same repo Fix in same PR per project CLAUDE.md; memory captures the pattern (e.g. "configKey/name/path mismatch must be validated at write-time") so the fix is durable
Documentation, test, tooling, scripts Document; no fix required

If you find yourself writing "workaround: ..." without a corresponding fix, re-read the table. The most common mistake is treating a 1-line config fix as "out of scope" — that is exactly the class this rule targets.

2. Write Claude auto-memory

Determine memory type from classification: Critical/Mandatory rules → feedback; architecture or design decisions → project; best practices → feedback; durable external facts or documentation-style lookups → reference.

Use the current git root to derive the project memory path:

project_key = git_root.replace("/", "-")
memory_dir = ~/.claude/projects/<project_key>/memory/

Create or update:

  • <type>_YYYY-MM-DD_<slug>.md
  • MEMORY.md

Never let a write failure (permissions, disk) block learning capture. If the write fails, log a warning and continue to the remaining persistence targets.

The memory file must include frontmatter:

---
name: <learning title>
description: <one-line summary>
type: feedback|project|reference
bead: <bead id or none>
---

The body must include context, technical detail, solution or rule, verification, references, and a reusable pattern.

3. Save to mem0 when available

Save a concise text record only when a configured helper and the mem0 Python package are present. Do NOT probe OPENAI_API_KEY / MEM0_API_KEY — those were the pre-Ollama-era gates; mem0 now uses local Ollama embedder + Groq LLM (configured in $MEM0_HOOKS_DIR/mem0_config.py), neither of which require OPENAI_API_KEY. The real availability gates are:

  1. python3 -c "from mem0 import Memory" resolves (requires mem0ai PyPI pkg).
  2. The helper script exists:
    • $MEM0_HOOKS_DIR/mem0_save.py (machine-local hooks dir; unset means skip mem0), OR
    • $(git rev-parse --show-toplevel)/.claude/hooks/mem0_save.py (repo-local fallback)
  3. mem0_config.py exists next to that helper and its mem0_hooks_enabled() returns True (this is the helper's own gate — it inspects OPENAI_API_KEY, GROQ_API_KEY, OLLAMA_HOST, etc., not what we hard-code here).

Verification step (mandatory before reporting "mem0 unavailable"): Run the existing read-only health check. Do not manufacture a learning message or require a Qdrant/markdown write merely to test availability:

"${MEM0_PYTHON:-python3}" - <<'EOF'
import os, subprocess, sys
from pathlib import Path
try:
    from mem0 import Memory  # noqa: F401
except ImportError as e:
    raise AssertionError(f"mem0 package missing: {e}")
hooks_env = os.environ.get("MEM0_HOOKS_DIR", "")
hooks = Path(hooks_env) if hooks_env else None
helpers = [hooks / "mem0_save.py"] if hooks else []
if not any(h.is_file() for h in helpers):
    result = subprocess.run(
        ["git", "rev-parse", "--show-toplevel"],
        capture_output=True, text=True, timeout=10,
    )
    if result.returncode == 0:
        helpers.append(Path(result.stdout.strip()) / ".claude/hooks/mem0_save.py")
found = [h for h in helpers if h.is_file()]
assert found, f"mem0_save.py missing (MEM0_HOOKS_DIR not configured?): {helpers}"
hooks = found[0].parent
assert (hooks / "mem0_config.py").is_file(), f"mem0_config.py missing: {hooks}"
sys.path.insert(0, str(hooks))
import mem0_config
assert mem0_config.mem0_hooks_enabled(), "mem0_hooks_enabled() is False"
print("mem0 available")
EOF

This checks all three gates above (the real Memory import, either helper path, and the helper's own mem0_hooks_enabled() — asserting mem0_config.py exists first so a missing hooks dir yields an assertion, not a traceback), never writes anything, and prints the failing assertion. If it fails report mem0 unavailable: <exact assertion message>; otherwise report mem0 available and save only the actual learning. Never block learning capture on a mem0 error — it is an optional target; continue to the remaining persistence steps regardless of outcome.

Reference incident: 2026-06-24 — old SKILL.md probed OPENAI_API_KEY and falsely reported "mem0 unavailable" for ~2 months after the Ollama/Groq switch in PR #7178 / bead rev-1cmaj (2026-05-24).

4. Append the roadmap learning log

Append to ${ROADMAP_DIR:-$HOME/roadmap}/learnings-YYYY-MM.md (if the directory is absent, report it and skip):

## YYYY-MM-DD - <learning title>

- **Type**: feedback|project|reference
- **Classification**: Critical|Mandatory|Best Practice|Anti-Pattern
- **Summary**: <one-line summary>
- **Bead**: <bead id or none>
- **Files**: <paths created or updated>
- **References**: <PRs, commits, artifact links, commands>

5. Create or reference a bead

If .beads/issues.jsonl exists:

  • Reuse a matching learning bead when one already exists.
  • Otherwise create a closed task bead with labels including learning and documentation.
  • Use the repository's normal bead id prefix when possible: follow the prefix existing beads use (for example rev-) via br create ... --type task --priority 3 rather than inventing a bd- id.
  • Record the bead id in the Claude memory frontmatter and roadmap entry.

If beads are unavailable, write none and report why.

6. Always wiki-ingest using the calling CLI

Wiki ingest is mandatory for /learn. Use the Claude memory file (preferred) or the roadmap entry as the source document. Read the canonical wiki-ingest skill and execute its full procedure with the calling CLI's own inference and tools. If the runtime provides a native skill invocation, it may use that; a Claude-specific Skill tool or a second CLI is never a prerequisite. Writes performed as part of the complete wiki-ingest procedure are authorized; do not substitute a partial copy that skips entity/concept extraction or validation.

Resolve the wiki destination once for both ingestion and verification, following the exact wiki-ingest order (--wiki <path> / $WIKI_OVERRIDE first, then .wiki-default in repo root, then ~/.wiki-default, then $WIKI_ROOT/wiki):

# Resolve destination once for both ingestion and verification:
if [ -n "${WIKI_OVERRIDE:-}" ]; then
  WIKI="$WIKI_OVERRIDE"
elif [ -f ".wiki-default" ]; then
  WIKI=$(cat .wiki-default)
elif [ -f "$HOME/.wiki-default" ]; then
  WIKI=$(cat "$HOME/.wiki-default")
elif [ -n "${WIKI_ROOT:-}" ]; then
  WIKI="$WIKI_ROOT/wiki"
else
  echo "WIKI_ROOT not configured — skipping wiki ingest and verification"
  return 0 2>/dev/null || exit 0
fi

# Gate verification assertions directly against the resolved $WIKI:
if [ -n "${WIKI:-}" ] && [ -d "$WIKI" ]; then
  WIKI_ROOT=$(dirname "$WIKI")
  RAW_DIR="$WIKI_ROOT/raw"

  # Verify raw source copy, canonical source page, index, log, and clean git commit recording the ingested source page:
  ( { test -f "$RAW_DIR/<basename>" 2>/dev/null || test -f "$WIKI/raw/<basename>"; } && \
    test -f "$WIKI/sources/<slug>.md" && \
    grep -q -F "<slug>" "$WIKI/index.md" && \
    tail -20 "$WIKI/log.md" | grep -q "<title>" && \
    test -z "$(git -C "$WIKI" status --porcelain)" && \
    git -C "$WIKI" log -n 1 --oneline -- "sources/<slug>.md" | grep -q . ) || \
    { echo "ERROR: wiki ingest verification failed" >&2; exit 1; }
fi

After execution, verify the required side effects using the exact resolved destination $WIKI (and sibling $RAW_DIR):

  • "$RAW_DIR/<basename>" (or "$WIKI/raw/<basename>") exists
  • "$WIKI/sources/<slug>.md" exists with the canonical frontmatter (title, type, tags, sources, last_updated) and [[wikilinks]]
  • "$WIKI/index.md" was updated under ## Sources (verify with grep -F "<slug>" "$WIKI/index.md")
  • "$WIKI/log.md" was appended with ## [YYYY-MM-DD] ingest | <title> (verify with tail -20 "$WIKI/log.md")
  • Git commit created on publish branch (verify with test -z "$(git -C "$WIKI" status --porcelain)" && git -C "$WIKI" log -n 1 --oneline -- "sources/<slug>.md" | grep -q .)
  • Relevant entity/concept updates exist and the wiki's link lint passes.

If the full procedure cannot be completed, report the exact missing step and continue independent persistence; never present a partial ingest as complete.

No exceptions for "the learning seems not wiki-bearing." The learning itself is the source. The skill's classifier decides what is wiki-bearing.

Working-directory caveat: if the current session cwd is not the resolved $WIKI_ROOT (e.g. an /integrate flow running in a feature worktree), resolve the source by its absolute path and pass an explicit --wiki "$WIKI" path (setting WIKI_OVERRIDE="$WIKI") so the destination does not depend on a current-directory override.

7. Validate and report

Before reporting complete:

  • Verify files exist for each persistence target that was available.
  • Validate .beads/issues.jsonl parses when modified.
  • Check duplicate bead ids when a bead was created manually.
  • Run a whitespace check for repo changes when applicable.

Final report must name the created/updated paths and any skipped persistence target with its reason.

04 同仓库更多 Skills

jleechanorg
jleechanorg/jleechan-skills

disk-reclaim-playbook

Use Disk Magician to diagnose disk growth or qualify cleanup on macOS or Linux.

★ 6
jleechanorg
jleechanorg/jleechan-skills

claudea-bench

Compare `claudea` and normal `claude` on a fair split of comparable work by default; use `--strict` for duplicate runs of the exact same task.

★ 6
jleechanorg
jleechanorg/jleechan-skills

pr

Alias for the canonical pr-lifecycle PR workflow skill (/pr-workflow, /prw).

★ 6
jleechanorg
jleechanorg/jleechan-skills

whisper

OpenAI's general-purpose speech recognition model. Supports 99 languages, transcription, translation to English, and language identification. Six model sizes from tiny (39M params) to large (1550M params). Use for speech-to-text, podcast transcription, or multilingual audio processing. Best for robust, multilingual ASR.

★ 6
jleechanorg
jleechanorg/jleechan-skills

webapp-testing

Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.

★ 6
jleechanorg
jleechanorg/jleechan-skills

pr-report

This skill should be used when the user asks for a PR report, PR audit, PR delta analysis, /pr-report, or wants per-PR summary with delta files/lines. Generates a structured report for one or more open PRs covering purpose, files changed, +/− line counts, /code-standards + /thermo review findings, /ponytail simplification opportunities, file-overlap combination candidates, and /green status per pr-green-definition. Output: machine-readable JSONL + human-readable markdown. Read-only by default; can apply simplifications if user opts in.

★ 6