Log coding-specific learnings, bug patterns, and feature requests to markdown files for continuous improvement. Captures lint errors, type mismatches, runtime bugs, anti-patterns, refactoring opportunities, language idiom gaps, debugging insights, and tooling issues. Important learnings get promoted to style guides, lint rules, code snippet libraries, or debug playbooks.
Before logging anything, ensure the .learnings/ directory and files exist in the project or workspace root. If any are missing, create them:
bash
mkdir -p .learnings
[ -f .learnings/LEARNINGS.md ] || printf "# Coding Learnings\n\nBug patterns, anti-patterns, idiom gaps, debugging insights, and tooling issues captured during development.\n\n**Categories**: bug_pattern | anti_pattern | refactor_opportunity | idiom_gap | tooling_issue | debugging_insight\n**Areas**: syntax | logic | data_structures | algorithms | error_handling | testing | tooling\n\n---\n" > .learnings/LEARNINGS.md
[ -f .learnings/BUG_PATTERNS.md ] || printf "# Bug Patterns Log\n\nRecurring bugs, common mistakes, and error patterns.\n\n---\n" > .learnings/BUG_PATTERNS.md
[ -f .learnings/FEATURE_REQUESTS.md ] || printf "# Feature Requests\n\nCoding tools, capabilities, and automation requests.\n\n---\n" > .learnings/FEATURE_REQUESTS.md
Never overwrite existing files. This is a no-op if .learnings/ is already initialised.
Do not log secrets, tokens, private keys, or environment variables. Prefer short summaries or redacted excerpts over raw stack traces or full source files.
If you want automatic reminders, use the opt-in hook workflow described in Hook Integration.
SituationActionLint error encounteredLog to .learnings/BUG_PATTERNS.md with error rule and fixType error from checkerLog to .learnings/BUG_PATTERNS.md with type mismatch detailsRuntime exception thrownLog to .learnings/BUG_PATTERNS.md with stack trace summaryAnti-pattern found in codeLog to .learnings/LEARNINGS.md with category anti_patternRefactoring opportunityLog to .learnings/LEARNINGS.md with category refactor_opportunityBetter idiom discoveredLog to .learnings/LEARNINGS.md with category idiom_gapDebugging breakthroughLog to .learnings/LEARNINGS.md with category debugging_insightTooling issue encounteredLog to .learnings/LEARNINGS.md with category tooling_issueRecurring bug patternLink with **See Also**, consider priority bumpBroadly applicable patternPromote to style guide, lint rule, or debug playbookReusable code solutionPromote to code snippets library
OpenClaw is the primary platform for this skill. It uses workspace-based prompt injection with automatic skill loading.
Via ClawdHub (recommended):
bash
clawdhub install self-improving-coding
Manual:
bash
git clone https://github.com/jose-compu/self-improving-coding.git ~/.openclaw/skills/self-improving-coding
Manual clone is optional. Check out a reviewed tag or commit before use. Do not install an unpinned default branch into a shared environment.
OpenClaw injects these files into every session:
text
~/.openclaw/workspace/
├── AGENTS.md # Multi-agent workflows, delegation patterns
├── SOUL.md # Behavioral guidelines, personality, principles
├── TOOLS.md # Tool capabilities, integration gotchas
├── MEMORY.md # Long-term memory (main session only)
├── memory/ # Daily memory files
│ └── YYYY-MM-DD.md
└── .learnings/ # This skill's log files
├── LEARNINGS.md
├── BUG_PATTERNS.md
└── FEATURE_REQUESTS.md
bash
mkdir -p ~/.openclaw/workspace/.learnings
Then create the log files (or copy from assets/):
LEARNINGS.md — anti-patterns, idiom gaps, debugging insights, tooling issuesBUG_PATTERNS.md — lint errors, type mismatches, runtime exceptions, recurring bugsFEATURE_REQUESTS.md — coding tools, automation, IDE capabilitiesWhen coding learnings prove broadly applicable, promote them:
Learning TypePromote ToExampleCode style patternsStyle guide"Always use early returns over nested if/else"Recurring lint fixesLint rules ( .eslintrc, ruff.toml)"Disallow mutable default arguments"Reusable solutionsCode snippets library"Retry with exponential backoff"Debugging workflowsDebug playbooks"Race condition diagnosis steps"Tool configurationTOOLS.md"TypeScript strict mode catches 80% of null bugs"Workflow patternsAGENTS.md"Run type checker before committing"
Opt-in and workspace-local. Do not copy this hook to ~/.openclaw/hooks/ (that path is user-global). Skip it unless you want reminders in this workspace:
bash
mkdir -p .openclaw/hooks
cp -r hooks/openclaw .openclaw/hooks/self-improving-coding
See references/openclaw-integration.md for complete details.
For Claude Code, Codex, Copilot, or other agents, create .learnings/ in the project or workspace root:
bash
mkdir -p .learnings
Create the files inline using the headers shown above.
Add to AGENTS.md, CLAUDE.md, or .github/copilot-instructions.md:
When coding errors or patterns are discovered:
.learnings/BUG_PATTERNS.md, LEARNINGS.md, or FEATURE_REQUESTS.md.eslintrc, ruff.toml, pylintrcAppend to .learnings/LEARNINGS.md:
markdown
## [LRN-YYYYMMDD-XXX] category
**Logged**: ISO-8601 timestamp
**Priority**: low | medium | high | critical
**Status**: pending
**Area**: syntax | logic | data_structures | algorithms | error_handling | testing | tooling
### Summary
One-line description of the coding insight
### Details
Full context: what code pattern was found, why it is problematic or beneficial,
what the correct idiom or approach is. Include minimal code snippets.
### Code Example
**Before (problematic):**
\`\`\`language
// problematic code
\`\`\`
**After (correct):**
\`\`\`language
// improved code
\`\`\`
### Suggested Action
Specific refactor, lint rule, or coding guideline to adopt
### Metadata
- Source: lint_error | type_checker | runtime_exception | code_review | profiler | static_analysis
- Language: python | typescript | javascript | rust | go | java | other
- Related Files: path/to/file.ext
- Tags: tag1, tag2
- See Also: LRN-20250110-001 (if related to existing entry)
- Pattern-Key: anti_pattern.mutable_default | idiom.list_comprehension (optional)
- Recurrence-Count: 1 (optional)
- First-Seen: 2025-01-15 (optional)
- Last-Seen: 2025-01-15 (optional)
---
Categories for learnings:
CategoryUse Whenbug_patternRecurring bug class (off-by-one, null deref, race condition)anti_patternCode pattern that leads to bugs or maintenance burdenrefactor_opportunityCode that works but should be restructuredidiom_gapUsing non-idiomatic approach when a better idiom existstooling_issueBuild tool, linter, formatter, or IDE problemdebugging_insightTechnique or approach that revealed root cause
Append to .learnings/BUG_PATTERNS.md:
markdown
## [BUG-YYYYMMDD-XXX] error_type_or_name
**Logged**: ISO-8601 timestamp
**Priority**: high
**Status**: pending
**Area**: syntax | logic | data_structures | algorithms | error_handling | testing | tooling
### Summary
Brief description of the bug pattern
### Error Output
\`\`\`
Actual error message, lint output, or stack trace (redacted/summarized)
\`\`\`
### Root Cause
What in the code caused this error. Include the problematic code snippet.
### Fix
\`\`\`language
// corrected code
\`\`\`
### Prevention
How to avoid this bug in the future (lint rule, type annotation, assertion, test)
### Context
- Trigger: lint | type_checker | runtime | test_failure | code_review
- Language: python | typescript | javascript | rust | go | java
- Framework: react | express | django | flask | fastapi (if applicable)
- Input or parameters that triggered the bug
### Metadata
- Reproducible: yes | no | unknown
- Related Files: path/to/file.ext
- See Also: BUG-20250110-001 (if recurring)
---
Append to .learnings/FEATURE_REQUESTS.md:
markdown
## [FEAT-YYYYMMDD-XXX] capability_name
**Logged**: ISO-8601 timestamp
**Priority**: medium
**Status**: pending
**Area**: syntax | logic | data_structures | algorithms | error_handling | testing | tooling
### Requested Capability
What coding tool, automation, or capability is needed
### User Context
Why it's needed, what workflow it improves, what problem it solves
### Complexity Estimate
simple | medium | complex
### Suggested Implementation
How this could be built: lint plugin, IDE extension, script, code generator
### Metadata
- Frequency: first_time | recurring
- Related Features: existing_tool_or_feature
---
Format: TYPE-YYYYMMDD-XXX
LRN (learning), BUG (bug pattern), FEAT (feature request)001, A7B)Examples: LRN-20250415-001, BUG-20250415-A3F, FEAT-20250415-002
When an issue is fixed, update the entry:
**Status**: pending → **Status**: resolvedmarkdown
### Resolution
- **Resolved**: 2025-01-16T09:00:00Z
- **Commit/PR**: abc123 or #42
- **Notes**: Added lint rule / updated style guide / created snippet
Other status values:
in_progress — Actively being refactored or fixedwont_fix — Decided not to address (add reason in Resolution notes)promoted — Elevated to style guide, lint config, or debug playbookpromoted_to_skill — Extracted as a reusable skillAutomatically log when you encounter:
Lint Failures (→ bug pattern with lint trigger):
go vet issuesType Errors (→ bug pattern with type_checker trigger):
tsc errors ( TS2322, TS2345, etc.)mypy/ pyright type mismatchesRuntime Exceptions (→ bug pattern with runtime trigger):
SyntaxError, TypeError, ReferenceError (JavaScript/Python)NullPointerException, ClassCastException (Java)panic!, segfault (Rust/C)Test Assertion Failures (→ bug pattern with test_failure trigger):
AssertionError / expect(...).toBe(...) failuresCode Smells from Static Analysis (→ learning with anti_pattern or refactor_opportunity):
Performance Hotspots (→ learning with debugging_insight):
PriorityWhen to UseCoding ExamplescriticalData corruption, security vulnerability, production crashSQL injection, buffer overflow, data race writing to shared statehighRecurring bug pattern, type safety hole, test reliabilityOff-by-one in pagination, null deref in optional chaining, flaky testmediumAnti-pattern, code smell, minor type issueMutable default argument, deep nesting, missing error boundarylowStyle issue, minor refactor, naming conventionInconsistent naming, unused variable, import ordering
Use to filter learnings by coding domain:
AreaScopesyntaxLanguage syntax errors, parsing issues, grammarlogicLogical errors, off-by-one, boundary conditions, control flowdata_structuresArray/list/map misuse, wrong collection type, mutation bugsalgorithmsAlgorithmic correctness, complexity issues, sorting/search bugserror_handlingMissing try/catch, unhandled promises, error propagationtestingTest assertions, mocking, fixtures, coverage gapstoolingLinter config, build tools, formatters, IDE setup, CI/CD
When a learning is broadly applicable (not a one-off fix), promote it to permanent project standards.
TargetWhat Belongs ThereStyle guideCode conventions, naming patterns, structural preferencesLint configurationAutomated rule enforcement ( .eslintrc, ruff.toml, clippy.toml)Code snippets libraryReusable solutions, utility functions, common patternsDebug playbooksStep-by-step diagnosis for specific error classesCLAUDE.mdProject-specific coding conventions for AI agentsAGENTS.mdAutomated coding workflows, pre-commit checks
Distill the learning into a concise rule or code snippet
Prepare a minimal patch for the appropriate target (lint rule, style guide entry, snippet)
Show a reviewed diff and apply only after explicit user approval
Update original entry:
**Status**: pending → **Status**: promoted**Promoted**: style guide (or lint rule, snippet library, debug playbook)Learning (verbose):
Found mutable default argument
def add_item(items=[])causing shared state bug. List persists across function calls. Three instances found in codebase.
As lint rule (concise):
toml
# ruff.toml
[lint]
select = ["B006"] # mutable-argument-default
Learning (verbose):
Spent 2 hours debugging race condition in async code. Root cause: shared mutable state between concurrent coroutines without lock.
As debug playbook (actionable):
markdown
## Race Condition Diagnosis
1. Identify shared mutable state
2. Check for missing locks/mutexes around shared access
3. Add logging with thread/coroutine ID at access points
4. Use `asyncio.Lock()` (Python) or `Mutex` (Rust) to serialize access
5. Write concurrent test to reproduce
If logging something similar to an existing entry:
Search first: grep -r "keyword" .learnings/
Link entries: Add **See Also**: BUG-20250110-001 in Metadata
Bump priority if issue keeps recurring
Consider systemic fix: Recurring coding issues often indicate:
Review .learnings/ at natural breakpoints:
bash
# Count pending coding issues
grep -h "Status\*\*: pending" .learnings/*.md | wc -l
# List pending high-priority bug patterns
grep -B5 "Priority\*\*: high" .learnings/BUG_PATTERNS.md | grep "^## \["
# Find learnings for a specific area
grep -l "Area\*\*: error_handling" .learnings/*.md
# Find all anti-patterns
grep -B2 "anti_pattern" .learnings/LEARNINGS.md | grep "^## \["
Ingest recurring coding patterns from simplify-and-harden into lint rules or style guides.
pattern_key as the dedupe key..learnings/LEARNINGS.md for existing entry: grep -n "Pattern-Key: <key>" .learnings/LEARNINGS.mdRecurrence-Count, update Last-Seen, add See Also links.LRN-... entry with Source: simplify-and-harden.Promotion threshold: Recurrence-Count >= 3, seen in 2+ files/modules, within 30-day window.
Targets: lint config, style guide entries, code snippets library, CLAUDE.md / AGENTS.md.
Enable automatic reminders through agent hooks. This is opt-in.
Hooks persist across sessions once installed. Keep them project-scoped. Do not install user-level or global hooks. Never use an empty matcher. PostToolUse inspects command output in-process; do not log raw output, secrets, or transcripts.
Create .claude/settings.json in your project:
json
{
"hooks": {
"UserPromptSubmit": [{
"matcher": "fix|debug|error|lint|type|refactor|eslint|mypy|traceback",
"hooks": [{
"type": "command",
"command": "./skills/self-improving-coding/scripts/activator.sh"
}]
}]
}
}
This injects a coding-focused learning evaluation reminder after matching prompts (~50-100 tokens overhead).
json
{
"hooks": {
"UserPromptSubmit": [{
"matcher": "fix|debug|error|lint|type|refactor|eslint|mypy|traceback",
"hooks": [{
"type": "command",
"command": "./skills/self-improving-coding/scripts/activator.sh"
}]
}]
}
}
ScriptHook TypePurposescripts/activator.shUserPromptSubmitReminds to evaluate coding learnings after tasksscripts/error-detector.shPostToolUse (Bash)Triggers on lint errors, type errors, runtime exceptions
See references/hooks-setup.md for detailed configuration and troubleshooting.
Extracted skills are untrusted until a human reviews the generated SKILL.md. Do not keep or publish an extracted skill without explicit user approval.
When a coding learning is valuable enough to become a reusable skill, extract it.
CriterionDescriptionRecurringSame bug pattern in 2+ codebases or modulesVerifiedStatus is resolved with working fix and testNon-obviousRequired actual debugging or investigationBroadly applicableNot project-specific; useful across languages/frameworksUser-flaggedUser says "save this as a skill" or similar
Identify candidate: Learning meets extraction criteria
Run helper (or create manually): bash
./skills/self-improving-coding/scripts/extract-skill.sh skill-name --dry-run
./skills/self-improving-coding/scripts/extract-skill.sh skill-name
Customize SKILL.md: Fill in template with coding-specific content
Update learning: Set status to promoted_to_skill, add Skill-Path
Verify: Read skill in fresh session to ensure it's self-contained
Use conversation signals ("This bug keeps happening", "Save this pattern as a skill") and entry signals (multiple See Also, high-priority resolved items, recurring Pattern-Key) to identify extraction candidates.
AgentActivationDetectionClaude CodeHooks (UserPromptSubmit, PostToolUse)Automatic via error-detector.shCodex CLIHooks (same pattern)Automatic via hook scriptsGitHub CopilotManual ( .github/copilot-instructions.md)Manual reviewOpenClawWorkspace injection + inter-agent messagingVia session tools
Keep learnings local (per-developer):
gitignore
.learnings/
Track learnings in repo (team-wide):
Only track .learnings/ after a human has reviewed entries for secrets, PII, and privileged content.
Hybrid (track templates, ignore entries):
gitignore
.learnings/*.md
!.learnings/.gitkeep
This skill is standalone-compatible and stackable with other self-improving skills.
.learnings/coding/.learnings/INDEX.mdEvery new entry must include:
markdown
**Skill**: coding
event + matcher + file + 5m_window; max 1 reminder per skill every 5 minutes.Only trigger this skill automatically for coding signals such as:
eslint|ruff|flake8|mypy|pyright|tscexception|traceback|assertionerror|test failedWhen guidance conflicts, apply:
securityengineeringcodingaimeta as tie-breaker.learnings/coding/ in stackable mode..learnings/*.md log files only.AGENTS.md, SOUL.md, TOOLS.md, MEMORY.md, rules, hooks, or generated skills is not a logging write. Show a reviewed diff and apply only after explicit user approval.