Skill: jose-compu/self-improving-meta (version 1.2.1)

--- name: self-improving-meta description: "Improves the agent infrastructure itself — core prompt files (AGENTS.md, SOUL.md, TOOLS.md, CLAUDE.md), skill definitions, hooks, rules, extensions, and memory management. Use when: (1) An agent misinterprets a prompt file instruction, (2) A hook fails or doesn't trigger, (3) A skill is not activating correctly, (4) Rules conflict across files, (5) Context window is bloated by verbose prompt files, (6) Memory entries are stale or degrading quality, (7) A skill template is missing sections or unclear." --- # Self-Improving Meta Skill Log infrastructure learnings, meta issues, and feature requests to markdown files for continuous improvement of the agent system itself. Captures prompt drift, rule conflicts, skill gaps, hook failures, context bloat, and instruction ambiguity. Important learnings may be promoted into the files they govern — prompt files, hook code, rule files, skill templates, and memory policies — after explicit human review. This is the skill that improves skills. Its learnings influence infrastructure that all other skills depend on, so changes should be reviewed conservatively. ## First-Use Initialisation 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 "# Meta Learnings\n\nPrompt drift, rule conflicts, skill gaps, hook failures, context bloat, and instruction ambiguity.\n\n**Categories**: prompt_drift | rule_conflict | skill_gap | hook_failure | context_bloat | instruction_ambiguity\n**Areas**: agent_config | skill_authoring | hook_scripts | prompt_files | rule_files | memory_management | extension_api\n\n---\n" > .learnings/LEARNINGS.md [ -f .learnings/META_ISSUES.md ] || printf "# Meta Issues Log\n\nInfrastructure failures: hook crashes, skill activation problems, prompt file errors, memory corruption, extension breakage.\n\n---\n" > .learnings/META_ISSUES.md [ -f .learnings/FEATURE_REQUESTS.md ] || printf "# Feature Requests\n\nCapabilities needed for agent infrastructure, skill authoring, hook development, and prompt management.\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 file contents. Use a manual-first workflow by default. If you want reminders, use the opt-in hook workflow described in [Hook Integration](#hook-integration). ## Safety Boundaries - Do not auto-modify core prompt files (`AGENTS.md`, `SOUL.md`, `TOOLS.md`, `MEMORY.md`) without explicit user approval. - Prefer proposing a minimal patch and rationale before applying infrastructure changes. - Treat hook output as sensitive; avoid logging raw command output or full transcripts. - Keep fixes scoped to the identified issue; avoid broad refactors during incident response. ## Quick Reference | Situation | Action | |-----------|--------| | Agent misreads AGENTS.md instruction | Log to `.learnings/LEARNINGS.md` with `instruction_ambiguity` | | Hook script fails silently | Log to `.learnings/META_ISSUES.md` | | Skill doesn't activate when expected | Log to `.learnings/META_ISSUES.md` | | Two rules contradict each other | Log to `.learnings/LEARNINGS.md` with `rule_conflict` | | Prompt file too verbose, wasting context | Log to `.learnings/LEARNINGS.md` with `context_bloat` | | Stale memory entry causes wrong behavior | Log to `.learnings/LEARNINGS.md` with `prompt_drift` | | Skill template missing required section | Log to `.learnings/META_ISSUES.md` | | New extension capability needed | Log to `.learnings/FEATURE_REQUESTS.md` | | Recurring misinterpretation across sessions | Link entries, bump priority, consider promotion | | Broadly applicable infrastructure fix | Promote directly to the affected file | ## OpenClaw Setup (Recommended) OpenClaw is the primary platform for this skill. It uses workspace-based prompt injection with automatic skill loading. ### Installation **Via ClawdHub (recommended):** ```bash clawdhub install self-improving-meta ``` **Manual:** ```bash git clone https://github.com/jose-compu/self-improving-meta.git ~/.openclaw/skills/self-improving-meta ``` ### Workspace Structure OpenClaw injects these files into every session: ``` ~/.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 ├── META_ISSUES.md └── FEATURE_REQUESTS.md ``` ### Create Learning Files ```bash mkdir -p ~/.openclaw/workspace/.learnings ``` Then create the log files (or copy from `assets/`): - `LEARNINGS.md` — prompt drift, rule conflicts, skill gaps, context bloat, instruction ambiguity - `META_ISSUES.md` — hook crashes, skill activation failures, prompt file errors, memory corruption - `FEATURE_REQUESTS.md` — infrastructure capabilities, tooling, automation ### Promotion Targets When meta-learnings prove broadly applicable, promote them to the files they govern with explicit user approval: | Learning Type | Promote To | Example | |---------------|------------|---------| | Agent behavior corrections | `SOUL.md` | "Be concise" repeated 6 ways → single directive | | Workflow/delegation improvements | `AGENTS.md` | Vague "long tasks" → explicit threshold | | Tool integration fixes | `TOOLS.md` | Missing timeout guidance → add retry config | | Memory management patterns | `MEMORY.md` | Stale entries → 30-day rotation policy | ### Optional: Enable Hook For automatic reminders at session start: ```bash cp -r hooks/openclaw ~/.openclaw/hooks/self-improving-meta openclaw hooks enable self-improving-meta ``` See `references/openclaw-integration.md` for complete details. --- ## Generic Setup (Other Agents) 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 reference to agent files Add to `AGENTS.md`, `CLAUDE.md`, or `.github/copilot-instructions.md`: #### Self-Improving Meta Workflow When agent infrastructure issues are discovered: 1. Log to `.learnings/META_ISSUES.md`, `LEARNINGS.md`, or `FEATURE_REQUESTS.md` 2. Review and promote broadly applicable learnings directly to: - `SOUL.md` — behavioral corrections - `AGENTS.md` — workflow and delegation improvements - `TOOLS.md` — tool integration fixes - `MEMORY.md` — memory management policies - Rule files — `.cursor/rules/`, `AGENTS.md` rules - Hook code — fix the handler directly ## Logging Format ### Learning Entry [LRN-YYYYMMDD-XXX] Append to `.learnings/LEARNINGS.md`: ```markdown ## [LRN-YYYYMMDD-XXX] category **Logged**: ISO-8601 timestamp **Priority**: low | medium | high | critical **Status**: pending **Area**: agent_config | skill_authoring | hook_scripts | prompt_files | rule_files | memory_management | extension_api ### Summary One-line description of the infrastructure insight ### Details Full context: what prompt file instruction was ambiguous, which rules conflict, why context is bloated, how memory drifted. Include the relevant file paths and line numbers. Quote the problematic instruction verbatim. ### Suggested Action Specific fix: rewrite the instruction, compress the file, consolidate the rules, update the hook code, prune the memory entries. ### Metadata - Source: agent_behavior_observation | hook_output_inspection | context_window_analysis | learnings_review | prompt_audit - Affected Files: AGENTS.md, SOUL.md, etc. - Tags: tag1, tag2 - See Also: LRN-20250110-001 (if related to existing entry) - Pattern-Key: rule_conflict.package_manager (optional) - Recurrence-Count: 1 (optional) - First-Seen: 2025-01-15 (optional) - Last-Seen: 2025-01-15 (optional) --- ``` **Categories for learnings:** | Category | Use When | |----------|----------| | `prompt_drift` | Prompt file content no longer matches actual practices or references deleted files | | `rule_conflict` | Two or more files give contradictory instructions on the same topic | | `skill_gap` | No skill exists for a recurring pattern with enough learnings to extract | | `hook_failure` | Hook script fails, produces wrong output, or doesn't trigger when expected | | `context_bloat` | Prompt file is too verbose, duplicative, or includes stale content wasting tokens | | `instruction_ambiguity` | Prompt file instruction is vague, causing inconsistent agent behavior | ### Meta Issue Entry [META-YYYYMMDD-XXX] Append to `.learnings/META_ISSUES.md`: ```markdown ## [META-YYYYMMDD-XXX] issue_type **Logged**: ISO-8601 timestamp **Priority**: high **Status**: pending **Area**: agent_config | skill_authoring | hook_scripts | prompt_files | rule_files | memory_management | extension_api ### Summary Brief description of the infrastructure failure ### Error Output \`\`\` Actual error message, hook output, or observed misbehavior \`\`\` ### Root Cause What in the infrastructure caused this failure. Include the affected file and section. ### Suggested Fix How to resolve: update hook code, fix skill frontmatter, correct prompt file, prune memory. ### Metadata - Source: hook_output_inspection | skill_activation_failure | prompt_injection_error | memory_corruption | extension_api_breakage - Affected Files: path/to/file - Reproducible: yes | no | unknown - See Also: META-20250110-001 (if recurring) --- ``` ### Feature Request Entry [FEAT-YYYYMMDD-XXX] Append to `.learnings/FEATURE_REQUESTS.md`: ```markdown ## [FEAT-YYYYMMDD-XXX] capability_name **Logged**: ISO-8601 timestamp **Priority**: medium **Status**: pending **Area**: agent_config | skill_authoring | hook_scripts | prompt_files | rule_files | memory_management | extension_api ### Requested Capability What infrastructure tool, automation, or capability is needed ### User Context Why it's needed, what workflow it improves, what infrastructure problem it solves ### Complexity Estimate simple | medium | complex ### Suggested Implementation How this could be built: hook script, skill template, audit script, linting tool ### Metadata - Frequency: first_time | recurring - Related Features: existing_tool_or_feature --- ``` ## ID Generation Format: `TYPE-YYYYMMDD-XXX` - TYPE: `LRN` (learning), `META` (meta/infrastructure issue), `FEAT` (feature request) - YYYYMMDD: Current date - XXX: Sequential number or random 3 chars (e.g., `001`, `A7B`) Examples: `LRN-20250415-001`, `META-20250415-A3F`, `FEAT-20250415-002` ## Resolving Entries When an issue is fixed, update the entry: 1. Change `**Status**: pending` → `**Status**: resolved` 2. Add resolution block after Metadata: ```markdown ### Resolution - **Resolved**: 2025-01-16T09:00:00Z - **Fix Applied To**: AGENTS.md / SOUL.md / hook code / skill template - **Notes**: Rewrote delegation instruction / compressed SOUL.md / fixed hook path ``` Other status values: - `in_progress` — Actively investigating or fixing - `wont_fix` — Decided not to address (add reason in Resolution notes) - `promoted` — Elevated directly to a prompt file, rule, hook, or configuration - `promoted_to_skill` — Extracted as a reusable meta-skill ## Promoting to Project Memory Meta-learnings are special: they can affect shared infrastructure. When you improve a prompt file, that improvement affects future sessions. When you fix a hook, that fix can propagate to all bootstraps. Use review gates. ### When to Promote - Same misinterpretation occurs across 2+ sessions - Rule conflict is confirmed (not a one-off edge case) - Context savings exceed 500 tokens after compression - Hook failure affects multiple sessions or agents - Skill gap has 3+ related learnings ready for extraction ### Promotion Targets | Pattern | Action | Target | |---------|--------|--------| | Ambiguous instruction | Rewrite with explicit criteria | AGENTS.md / SOUL.md / TOOLS.md | | Verbose prompt file | Compress and distill | The file itself | | Conflicting rules | Consolidate into single authoritative source | Primary file; remove from secondary | | Hook failure pattern | Update hook code or documentation | handler.ts/js, HOOK.md | | Skill gap | Create new skill or update existing | New SKILL.md or existing one | | Memory management insight | Update rotation/pruning policy | MEMORY.md | ### How to Promote 1. **Distill** the learning into a concrete fix 2. **Prepare** a minimal patch for the affected file 3. **Test** in a fresh session to verify the fix works 4. **Apply after approval**, then update original entry: - Change `**Status**: pending` → `**Status**: promoted` - Add `**Promoted**: AGENTS.md (delegation section rewrite)` (or equivalent) ## Recurring Pattern Detection If logging something similar to an existing entry: 1. **Search first**: `grep -r "keyword" .learnings/` 2. **Link entries**: Add `**See Also**: LRN-20250110-001` in Metadata 3. **Bump priority** if issue keeps recurring 4. **Consider systemic fix**: Recurring meta issues often indicate: - Instruction needs rewriting (→ edit the prompt file) - Rule belongs in a different file (→ relocate) - Hook needs hardening (→ add validation/output checks) - Skill template is incomplete (→ update template) ## Simplify & Harden Feed Ingest recurring infrastructure patterns from `simplify-and-harden` into prompt file fixes and hook improvements. 1. For each candidate, use `pattern_key` as the dedupe key. 2. Search `.learnings/LEARNINGS.md` for existing entry: `grep -n "Pattern-Key: <key>" .learnings/LEARNINGS.md` 3. If found: increment `Recurrence-Count`, update `Last-Seen`, add `See Also` links. 4. If not found: create new `LRN-...` entry with `Source: simplify-and-harden`. **Promotion threshold**: `Recurrence-Count >= 3`, seen in 2+ sessions, within 30-day window. **Meta-specific actions**: - Verbose prompt file → compress (target: 50% token reduction) - Conflicting rules → consolidate to single source of truth - Ambiguous instruction → rewrite with concrete examples or thresholds - Hook producing wrong output → fix handler code and add test case ## Periodic Review Review `.learnings/` at natural breakpoints: ### When to Review - Before publishing a new skill - After modifying any core prompt file (AGENTS.md, SOUL.md, TOOLS.md, MEMORY.md) - When adding or removing hooks - When agent behavior degrades unexpectedly - Monthly audit of all prompt files for staleness and conflicts ### Quick Status Check ```bash # Count pending meta issues grep -h "Status\*\*: pending" .learnings/*.md | wc -l # List pending high-priority infrastructure issues grep -B5 "Priority\*\*: high" .learnings/META_ISSUES.md | grep "^## \[" # Find learnings for a specific area grep -l "Area\*\*: hook_scripts" .learnings/*.md # Find all rule conflicts grep -B2 "rule_conflict" .learnings/LEARNINGS.md | grep "^## \[" ``` ### Review Actions - Resolve fixed infrastructure issues - Promote recurring patterns to prompt files - Link related entries across files - Extract skill candidates (3+ related learnings) - Prune stale memory entries referenced in learnings ## Detection Triggers Automatically log when you encounter: **Instruction Problems** (→ learning with `instruction_ambiguity`): - Agent says "I'm not sure what this instruction means" or paraphrases incorrectly - Agent ignores a rule that should apply to the current task - Agent asks for clarification on the same topic across multiple sessions - Skill frontmatter description doesn't match actual behavior - Rule file has no clear trigger condition **Configuration Conflicts** (→ learning with `rule_conflict`): - Two prompt files give contradictory guidance on the same topic - CLAUDE.md convention conflicts with AGENTS.md workflow step - .cursor/rules/ entry contradicts AGENTS.md instruction - Skill description conflicts with global behavioral rules **Context Issues** (→ learning with `context_bloat`): - Agent loads too much context and truncates important information - Prompt file exceeds 200 lines without structured formatting - Same information duplicated across 2+ prompt files - Historical context that belongs in README or changelog **Memory Problems** (→ learning with `prompt_drift`): - Memory entry references deleted files or outdated conventions - Daily memory file contains information superseded by newer entries - MEMORY.md rotation policy hasn't been applied in 30+ days - Agent behavior changed because stale memory overrides current instructions **Hook Failures** (→ meta issue): - Hook output is empty when it shouldn't be - Hook script exits with non-zero code - Hook fires on wrong event or doesn't fire at expected event - Hook configuration path points to non-existent script **Skill Problems** (→ meta issue): - Skill doesn't activate despite matching trigger conditions - Skill frontmatter is malformed (missing name, description, or YAML errors) - Skill template is missing required sections - Skill extraction script produces invalid scaffold ## Priority Guidelines | Priority | When to Use | Meta Examples | |----------|-------------|---------------| | `critical` | Agent actively doing wrong thing due to bad prompt file | Rule conflict causing harmful output, corrupted memory overriding safety rules | | `high` | Hook failure affecting multiple sessions | Skill not activating, context bloat degrading performance, silent hook failure for 2+ weeks | | `medium` | Instruction could be clearer | Memory needs pruning, template improvement, prompt compression opportunity | | `low` | Documentation or style consistency | Minor template tweak, naming convention, comment formatting | ## Area Tags Use to filter learnings by infrastructure domain: | Area | Scope | |------|-------| | `agent_config` | AGENTS.md, SOUL.md, TOOLS.md, MEMORY.md, CLAUDE.md, copilot-instructions.md | | `skill_authoring` | SKILL.md files, skill templates, skill extraction, naming conventions | | `hook_scripts` | activator.sh, error-detector.sh, handler.ts/js, hook configuration | | `prompt_files` | Any file injected into agent context (workspace files, rules, instructions) | | `rule_files` | .cursor/rules/, AGENTS.md rules, coding standards files | | `memory_management` | MEMORY.md, daily memory files, memory rotation, staleness detection | | `extension_api` | OpenClaw extensions, tool integrations, MCP servers, ClawdHub | ## Best Practices 1. **Keep prompt files concise** — every token counts against context window 2. **One authoritative source per rule** — no duplication across files 3. **Test skills in fresh sessions** before publishing 4. **Version prompt files** — track what changed and when 5. **Audit hooks monthly** — silent failures are the worst failures 6. **Prune memory aggressively** — stale entries cause drift 7. **Write skill descriptions as trigger conditions**, not feature lists 8. **Use structured formats** (tables, lists) over prose in prompt files 9. **Quote the problematic instruction** verbatim when logging ambiguity 10. **Apply fixes directly** — meta-learnings should change the files they describe ## Hook Integration Enable reminders through agent hooks only when needed. This is **opt-in**. ### Conservative Mode (Recommended) - Default to **no hooks** and log manually. - If reminders are useful, enable `UserPromptSubmit` with `scripts/activator.sh` only. - Enable `PostToolUse` (`scripts/error-detector.sh`) only in trusted environments when you explicitly want command-output pattern checks. ### Quick Setup (Claude Code / Codex) Create `.claude/settings.json` in your project: ```json { "hooks": { "UserPromptSubmit": [{ "matcher": "", "hooks": [{ "type": "command", "command": "./skills/self-improving-meta/scripts/activator.sh" }] }] } } ``` This injects an infrastructure-focused learning evaluation reminder after each prompt (~50-100 tokens overhead). ### Advanced Setup (With Error Detection) ```json { "hooks": { "UserPromptSubmit": [{ "matcher": "", "hooks": [{ "type": "command", "command": "./skills/self-improving-meta/scripts/activator.sh" }] }], "PostToolUse": [{ "matcher": "Bash", "hooks": [{ "type": "command", "command": "./skills/self-improving-meta/scripts/error-detector.sh" }] }] } } ``` Enable `PostToolUse` only if you want the hook to inspect command output for infrastructure-related error terms (hook, skill, AGENTS.md, frontmatter, truncated, etc.). ### Available Hook Scripts | Script | Hook Type | Purpose | |--------|-----------|---------| | `scripts/activator.sh` | UserPromptSubmit | Reminds to evaluate infrastructure learnings after tasks | | `scripts/error-detector.sh` | PostToolUse (Bash) | Triggers on infrastructure error terms in command output | See `references/hooks-setup.md` for detailed configuration and troubleshooting. ## Automatic Skill Extraction When a meta-learning is valuable enough to become a reusable skill, extract it. Meta-skills extracting from meta-learnings is recursive improvement — the system improving itself. ### Skill Extraction Criteria | Criterion | Description | |-----------|-------------| | **Recurring** | Same infrastructure pattern in 2+ sessions or projects | | **Verified** | Status is `resolved` with working fix tested in fresh session | | **Non-obvious** | Required actual investigation or multiple attempts | | **Broadly applicable** | Not specific to one prompt file; useful across agent setups | | **User-flagged** | User says "save this as a skill" or similar | ### Extraction Workflow 1. **Identify candidate**: Learning meets extraction criteria 2. **Run helper** (or create manually): ```bash ./skills/self-improving-meta/scripts/extract-skill.sh skill-name --dry-run ./skills/self-improving-meta/scripts/extract-skill.sh skill-name ``` 3. **Customize SKILL.md**: Fill in template with infrastructure-specific content 4. **Update learning**: Set status to `promoted_to_skill`, add `Skill-Path` 5. **Test in fresh session**: Meta-skills require fresh session verification because they modify shared infrastructure 6. **Verify no regressions**: Ensure other skills and hooks still work ### Extraction Detection Triggers **In conversation**: "This keeps happening", "Save this infrastructure fix as a skill", "Every project has this prompt file issue", "This hook pattern should be standard". **In entries**: Multiple `See Also` links, high priority + resolved, `rule_conflict` or `context_bloat` with broad applicability, same `Pattern-Key` across projects. ## Meta-Improvement Loop This skill is unique: its learnings directly modify the infrastructure that all other skills depend on. This creates a feedback loop: 1. **Observe**: Agent misinterprets instruction / hook fails / context is bloated 2. **Log**: Record the infrastructure issue in `.learnings/` 3. **Analyze**: Identify root cause (ambiguity, conflict, bloat, drift, gap, failure) 4. **Fix**: Apply correction directly to the affected file 5. **Propagate**: The fix takes effect in all future sessions for all agents 6. **Verify**: Confirm the fix works in a fresh session 7. **Learn from the fix**: If the fix itself causes issues, log that too (recursive) When you improve a prompt file, that improvement affects all future sessions. When you fix a hook, that fix propagates to all bootstraps. When you update a skill template, all future skill extractions benefit. The meta skill is the only skill whose learnings directly modify the infrastructure that all other skills depend on. Handle with care — test before applying. ## Multi-Agent Support | Agent | Activation | Detection | |-------|-----------|-----------| | Claude Code | Hooks (UserPromptSubmit, PostToolUse) | Automatic via error-detector.sh | | Codex CLI | Hooks (same pattern) | Automatic via hook scripts | | GitHub Copilot | Manual (`.github/copilot-instructions.md`) | Manual review | | OpenClaw | Workspace injection + inter-agent messaging | Via session tools | ## Gitignore Options **Keep learnings local** (per-developer): ```gitignore .learnings/ ``` **Track learnings in repo** (team-wide): Don't add to .gitignore — learnings become shared knowledge. **Hybrid** (track templates, ignore entries): ```gitignore .learnings/*.md !.learnings/.gitkeep ``` ## Stackability Contract (Standalone + Multi-Skill) This skill is standalone-compatible and stackable with other self-improving skills. ### Namespaced Logging (recommended for 2+ skills) - Namespace for this skill: `.learnings/meta/` - Keep current standalone behavior if you prefer flat files. - Optional shared index for all skills: `.learnings/INDEX.md` ### Required Metadata Every new entry must include: ```markdown **Skill**: meta ``` ### Hook Arbitration (when 2+ skills are enabled) - Use one dispatcher hook as the single entrypoint. - Dispatcher responsibilities: route by matcher, dedupe repeated events, and rate-limit reminders. - Suggested defaults: dedupe key = `event + matcher + file + 5m_window`; max 1 reminder per skill every 5 minutes. ### Narrow Matcher Scope (meta) Only trigger this skill automatically for meta orchestration signals such as: - `cross-skill conflict|routing ambiguity|policy overlap|dedupe` - `learning loop quality|stackability issue|prompt governance` - explicit meta intent in user prompt ### Cross-Skill Precedence When guidance conflicts, apply: 1. `security` 2. `engineering` 3. `coding` 4. `ai` 5. user-explicit domain skill 6. `meta` as tie-breaker ### Ownership Rules - This skill writes only to `.learnings/meta/` in stackable mode. - It may read other skill folders for cross-linking, but should not rewrite their entries.

path: assets/FEATURE_REQUESTS.md
content: # Feature Requests

Capabilities needed for agent infrastructure, skill authoring, hook development, and prompt management.

---


path: assets/ERRORS.md
content: # Meta Issues Log

Infrastructure failures: hook crashes, skill activation problems, prompt file errors, memory corruption, extension breakage.

---


path: assets/SKILL-TEMPLATE.md
content: # Meta Skill Template

Template for creating skills extracted from meta-learnings. Meta-skills are special: they modify the infrastructure that all other skills depend on. Extra care in testing is required.

---

## SKILL.md Template

```markdown
---
name: skill-name-here
description: "Concise description of the agent infrastructure pattern, prompt fix, or hook improvement this skill addresses. Include trigger conditions."
---

# Skill Name

Brief introduction: what infrastructure problem this skill solves, which prompt files or hooks it affects, and its origin.

## Quick Reference

| Situation | Action |
|-----------|--------|
| [Infrastructure trigger] | [Fix or improvement to apply] |
| [Related trigger] | [Alternative approach] |

## Background

Why this meta-knowledge matters. What agent misbehavior it prevents. What context efficiency or reliability improvement it provides.

## The Problem

### Current State

Description of the problematic prompt file content, hook behavior, rule conflict, or skill gap.

```
// Example of the broken instruction, verbose prompt, or conflicting rule
```

### Impact

How this infrastructure problem manifests in agent behavior: misinterpretation, ignored rules, context waste, silent failures.

## Solution

### Fix

```
// Corrected instruction, compressed prompt, resolved conflict, or fixed hook
```

### Step-by-Step

1. Identify the infrastructure problem
2. Locate all affected files (prompt files, hooks, rules, skills)
3. Apply the fix with minimal disruption
4. Test in a fresh session to verify agent behavior
5. Document the change in the affected file's version history

## Testing

### Fresh Session Test

Meta-skills MUST be tested in a fresh session because:
- Prompt file changes affect all subsequent agent behavior
- Hook changes alter the bootstrap sequence
- Rule changes can cascade through multiple skills

### Verification Checklist

- [ ] Agent correctly interprets the modified instruction
- [ ] No other rules or skills are broken by the change
- [ ] Context token usage is reduced (if compression was applied)
- [ ] Hook fires correctly and produces expected output
- [ ] No regressions in related skills

## Propagation

Meta-skills propagate differently from domain skills:

| Change Type | Propagation Scope |
|-------------|-------------------|
| AGENTS.md edit | All future sessions, all agents |
| SOUL.md edit | All future sessions, behavioral changes |
| TOOLS.md edit | All future tool usage patterns |
| MEMORY.md edit | Memory management for all sessions |
| Hook code fix | All future bootstraps |
| Skill template update | All future skill extractions |
| Rule file update | All agents reading that rule file |

## Rollback

If the meta-skill causes regressions:

1. Revert the prompt file / hook / rule to previous version
2. Log the regression as a new META issue
3. Re-evaluate the original learning with additional context

## Source

Extracted from meta learning entry.
- **Learning ID**: LRN-YYYYMMDD-XXX or META-YYYYMMDD-XXX
- **Original Category**: prompt_drift | rule_conflict | skill_gap | hook_failure | context_bloat | instruction_ambiguity
- **Area**: agent_config | skill_authoring | hook_scripts | prompt_files | rule_files | memory_management | extension_api
- **Extraction Date**: YYYY-MM-DD
```

---

## Minimal Template

For simple meta-skills that don't need all sections:

```markdown
---
name: skill-name-here
description: "What infrastructure pattern this addresses and when to apply it."
---

# Skill Name

[Problem statement in one sentence]

## Problem

Description of the infrastructure issue and its impact on agent behavior.

## Solution

Corrected instruction, compressed prompt, or fixed hook code.

## Testing

Verify in a fresh session that agent behavior is correct.

## Source

- Learning ID: LRN-YYYYMMDD-XXX
```

---

## Naming Conventions

- **Skill name**: lowercase, hyphens for spaces
  - Good: `prompt-file-compression`, `hook-error-handling`, `rule-deduplication`
  - Bad: `PromptCompression`, `fix_hooks`, `meta1`

- **Description**: Start with action verb, mention the infrastructure component
  - Good: "Compresses verbose SOUL.md personality directives to save context tokens. Use when SOUL.md exceeds 200 lines."
  - Bad: "Prompt stuff"

- **Files**:
  - `SKILL.md` — Required, main documentation
  - `scripts/` — Optional, automation (compression, validation, auditing)
  - `references/` — Optional, detailed docs
  - `assets/` — Optional, templates

---

## Extraction Checklist

Before creating a skill from a meta-learning:

- [ ] Infrastructure fix is verified (tested in fresh session)
- [ ] Fix is broadly applicable (not a one-off typo correction)
- [ ] Affected files are identified and listed
- [ ] Propagation scope is understood (which agents/sessions are affected)
- [ ] Rollback plan exists
- [ ] Name follows conventions
- [ ] Description includes trigger conditions

After creating:

- [ ] Update original learning with `promoted_to_skill` status
- [ ] Add `Skill-Path: skills/skill-name` to learning metadata
- [ ] Test skill by reading it in a fresh session
- [ ] Verify no regressions in affected prompt files, hooks, or rules
- [ ] Notify team if the change affects shared infrastructure


path: assets/LEARNINGS.md
content: # Meta Learnings

Prompt drift, rule conflicts, skill gaps, hook failures, context bloat, and instruction ambiguity captured during agent infrastructure work.

**Categories**: prompt_drift | rule_conflict | skill_gap | hook_failure | context_bloat | instruction_ambiguity
**Areas**: agent_config | skill_authoring | hook_scripts | prompt_files | rule_files | memory_management | extension_api
**Statuses**: pending | in_progress | resolved | wont_fix | promoted | promoted_to_skill

## Status Definitions

| Status | Meaning |
|--------|---------|
| `pending` | Not yet addressed |
| `in_progress` | Actively being worked on |
| `resolved` | Issue fixed or knowledge integrated |
| `wont_fix` | Decided not to address (reason in Resolution) |
| `promoted` | Elevated to prompt file, rule, hook code, or configuration |
| `promoted_to_skill` | Extracted as a reusable meta-skill |

## Skill Extraction Fields

When a learning is promoted to a skill, add these fields:

```markdown
**Status**: promoted_to_skill
**Skill-Path**: skills/skill-name
```

Example:
```markdown
## [LRN-20250415-001] instruction_ambiguity

**Logged**: 2025-04-15T10:00:00Z
**Priority**: high
**Status**: promoted_to_skill
**Skill-Path**: skills/prompt-file-compression
**Area**: agent_config

### Summary
AGENTS.md delegation section uses vague thresholds causing inconsistent sub-agent usage
...
```

---


path: scripts/activator.sh
content: #!/bin/bash
# Meta Self-Improvement Activator Hook
# Triggers on UserPromptSubmit to remind about infrastructure learning capture
# Keep output minimal (~50-100 tokens) to minimize overhead

set -e

cat << 'EOF'
<meta-improvement-reminder>
After completing this task, evaluate if agent infrastructure learnings emerged:
- Did any prompt file instruction cause confusion or get ignored?
- Did a hook fail to trigger or produce unexpected output?
- Was a skill missing or inadequate for the task?
- Are any rules contradicting each other across files?
- Is context being wasted on verbose or stale prompt content?
- Could memory entries be pruned or updated?

If yes: Log to .learnings/ using the self-improving-meta format.
If infrastructure fix needed: Apply directly to the affected file.
</meta-improvement-reminder>
EOF


path: scripts/extract-skill.sh
content: #!/bin/bash
# Meta Skill Extraction Helper
# Creates a new skill from a meta learning entry
# Usage: ./extract-skill.sh <skill-name> [--dry-run]

set -e

SKILLS_DIR="./skills"

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

usage() {
    cat << EOF
Usage: $(basename "$0") <skill-name> [options]

Create a new meta skill from an infrastructure learning entry.

Meta-skills are special: they modify the infrastructure that all other skills
depend on. Extra care in testing is required — always verify in a fresh session.

Arguments:
  skill-name     Name of the skill (lowercase, hyphens for spaces)

Options:
  --dry-run      Show what would be created without creating files
  --output-dir   Relative output directory under current path (default: ./skills)
  -h, --help     Show this help message

Examples:
  $(basename "$0") prompt-file-compression
  $(basename "$0") hook-error-handling --dry-run
  $(basename "$0") rule-deduplication --output-dir ./skills/meta

The skill will be created in: \$SKILLS_DIR/<skill-name>/
EOF
}

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

SKILL_NAME=""
DRY_RUN=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --dry-run)
            DRY_RUN=true
            shift
            ;;
        --output-dir)
            if [ -z "${2:-}" ] || [[ "${2:-}" == -* ]]; then
                log_error "--output-dir requires a relative path argument"
                usage
                exit 1
            fi
            SKILLS_DIR="$2"
            shift 2
            ;;
        -h|--help)
            usage
            exit 0
            ;;
        -*)
            log_error "Unknown option: $1"
            usage
            exit 1
            ;;
        *)
            if [ -z "$SKILL_NAME" ]; then
                SKILL_NAME="$1"
            else
                log_error "Unexpected argument: $1"
                usage
                exit 1
            fi
            shift
            ;;
    esac
done

if [ -z "$SKILL_NAME" ]; then
    log_error "Skill name is required"
    usage
    exit 1
fi

if ! [[ "$SKILL_NAME" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ ]]; then
    log_error "Invalid skill name format. Use lowercase letters, numbers, and hyphens only."
    log_error "Examples: 'prompt-file-compression', 'hook-error-handling', 'rule-deduplication'"
    exit 1
fi

if [[ "$SKILLS_DIR" = /* ]]; then
    log_error "Output directory must be a relative path under the current directory."
    exit 1
fi

if [[ "$SKILLS_DIR" =~ (^|/)\.\.(/|$) ]]; then
    log_error "Output directory cannot include '..' path segments."
    exit 1
fi

SKILLS_DIR="${SKILLS_DIR#./}"
SKILLS_DIR="./$SKILLS_DIR"

SKILL_PATH="$SKILLS_DIR/$SKILL_NAME"

if [ -d "$SKILL_PATH" ] && [ "$DRY_RUN" = false ]; then
    log_error "Skill already exists: $SKILL_PATH"
    log_error "Use a different name or remove the existing skill first."
    exit 1
fi

if [ "$DRY_RUN" = true ]; then
    log_info "Dry run - would create:"
    echo "  $SKILL_PATH/"
    echo "  $SKILL_PATH/SKILL.md"
    echo ""
    echo "Template content would be:"
    echo "---"
    cat << TEMPLATE
name: $SKILL_NAME
description: "[TODO: Describe the agent infrastructure pattern, prompt file fix, or hook improvement this skill addresses]"
---

# $(echo "$SKILL_NAME" | sed 's/-/ /g' | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2))}1')

[TODO: Brief introduction — what infrastructure problem this solves]

**WARNING**: This is a meta-skill. It modifies infrastructure that other skills depend on.
Test thoroughly in a fresh session before publishing.

## Quick Reference

| Situation | Action |
|-----------|--------|
| [Infrastructure trigger] | [Fix or improvement] |

## The Problem

### Current State

[TODO: Description of the problematic prompt file content, hook behavior, or rule conflict]

### Impact

[TODO: How this manifests in agent behavior — misinterpretation, ignored rules, context waste]

## Solution

### Fix

[TODO: Corrected instruction, compressed prompt, resolved conflict, or fixed hook]

### Step-by-Step

1. [TODO: Identify the infrastructure problem]
2. [TODO: Locate all affected files]
3. [TODO: Apply the fix]
4. [TODO: Test in a fresh session]
5. [TODO: Document the change]

## Testing

- [ ] Agent correctly interprets the modified instruction
- [ ] No other rules or skills are broken
- [ ] Context token usage is reduced (if applicable)
- [ ] Hook fires correctly (if applicable)

## Propagation

| Change Type | Scope |
|-------------|-------|
| [File changed] | [Who/what is affected] |

## Source

- Learning ID: [TODO: Add original learning ID]
- Category: [TODO: prompt_drift | rule_conflict | skill_gap | hook_failure | context_bloat | instruction_ambiguity]
- Area: [TODO: agent_config | skill_authoring | hook_scripts | prompt_files | rule_files | memory_management | extension_api]
- Original File: .learnings/LEARNINGS.md or .learnings/META_ISSUES.md
TEMPLATE
    echo "---"
    exit 0
fi

log_info "Creating meta skill: $SKILL_NAME"

mkdir -p "$SKILL_PATH"

cat > "$SKILL_PATH/SKILL.md" << TEMPLATE
---
name: $SKILL_NAME
description: "[TODO: Describe the agent infrastructure pattern, prompt file fix, or hook improvement this skill addresses]"
---

# $(echo "$SKILL_NAME" | sed 's/-/ /g' | awk '{for(i=1;i<=NF;i++) $i=toupper(substr($i,1,1)) tolower(substr($i,2))}1')

[TODO: Brief introduction — what infrastructure problem this solves]

**WARNING**: This is a meta-skill. It modifies infrastructure that other skills depend on.
Test thoroughly in a fresh session before publishing.

## Quick Reference

| Situation | Action |
|-----------|--------|
| [Infrastructure trigger] | [Fix or improvement] |

## The Problem

### Current State

[TODO: Description of the problematic prompt file content, hook behavior, or rule conflict]

### Impact

[TODO: How this manifests in agent behavior — misinterpretation, ignored rules, context waste]

## Solution

### Fix

[TODO: Corrected instruction, compressed prompt, resolved conflict, or fixed hook]

### Step-by-Step

1. [TODO: Identify the infrastructure problem]
2. [TODO: Locate all affected files]
3. [TODO: Apply the fix]
4. [TODO: Test in a fresh session]
5. [TODO: Document the change]

## Testing

- [ ] Agent correctly interprets the modified instruction
- [ ] No other rules or skills are broken
- [ ] Context token usage is reduced (if applicable)
- [ ] Hook fires correctly (if applicable)

## Propagation

| Change Type | Scope |
|-------------|-------|
| [File changed] | [Who/what is affected] |

## Source

- Learning ID: [TODO: Add original learning ID]
- Category: [TODO: prompt_drift | rule_conflict | skill_gap | hook_failure | context_bloat | instruction_ambiguity]
- Area: [TODO: agent_config | skill_authoring | hook_scripts | prompt_files | rule_files | memory_management | extension_api]
- Original File: .learnings/LEARNINGS.md or .learnings/META_ISSUES.md
TEMPLATE

log_info "Created: $SKILL_PATH/SKILL.md"

log_warn "Meta-skills modify shared infrastructure. Test in a fresh session before publishing."

echo ""
log_info "Skill scaffold created."
echo ""
echo "Next steps:"
echo "  1. Edit $SKILL_PATH/SKILL.md"
echo "  2. Fill in the TODO sections with the infrastructure fix from your learning"
echo "  3. Add testing checklist (fresh session verification is mandatory for meta-skills)"
echo "  4. Add propagation table showing which files/agents are affected"
echo "  5. Update the original learning entry with:"
echo "     **Status**: promoted_to_skill"
echo "     **Skill-Path**: skills/$SKILL_NAME"


path: scripts/error-detector.sh
content: #!/bin/bash
# Meta Self-Improvement Error Detector Hook (Optional)
# Conservative detector for explicit infrastructure failures only.
# Reads CLAUDE_TOOL_OUTPUT (when provided by PostToolUse).

set -e

OUTPUT="${CLAUDE_TOOL_OUTPUT:-}"

# If hook context didn't provide output, do nothing.
[ -n "$OUTPUT" ] || exit 0

ERROR_PATTERNS=(
    "failed to load skill"
    "frontmatter"
    "yaml parse"
    "metadata"
    "context length exceeded"
    "token limit exceeded"
    "prompt is too long"
    "malformed"
    "No such file or directory"
)

contains_error=false
for pattern in "${ERROR_PATTERNS[@]}"; do
    if [[ "$OUTPUT" == *"$pattern"* ]]; then
        contains_error=true
        break
    fi
done

if [ "$contains_error" = true ]; then
    cat << 'EOF'
<meta-error-detected>
A high-signal infrastructure failure pattern was detected.
Log only if the issue required investigation or is likely to recur.
Prefer minimal, reviewed fixes for shared prompt files and hooks.
</meta-error-detected>
EOF
fi


path: hooks/openclaw/handler.js
content: /**
 * Self-Improving Meta Hook for OpenClaw
 *
 * Injects a meta-specific reminder to evaluate infrastructure learnings during agent bootstrap.
 * Fires on agent:bootstrap event before workspace files are injected.
 */

const REMINDER_CONTENT = `
## Meta Self-Improvement Reminder

After completing tasks, evaluate if any agent infrastructure learnings should be captured:

**Log learnings when:**
- Agent misinterprets a prompt file instruction → \`.learnings/LEARNINGS.md\` (instruction_ambiguity)
- Two rules contradict each other across files → \`.learnings/LEARNINGS.md\` (rule_conflict)
- Context window feels cramped or truncated → \`.learnings/LEARNINGS.md\` (context_bloat)
- Memory entry is stale or causing wrong behavior → \`.learnings/LEARNINGS.md\` (prompt_drift)
- Skill template is missing a section → \`.learnings/LEARNINGS.md\` (skill_gap)

**Log meta issues when:**
- Hook fails or produces no output → \`.learnings/META_ISSUES.md\`
- Skill doesn't activate when expected → \`.learnings/META_ISSUES.md\`
- Prompt file has malformed frontmatter → \`.learnings/META_ISSUES.md\`
- Extension API breaks or behaves unexpectedly → \`.learnings/META_ISSUES.md\`

**Log feature requests when:**
- New infrastructure capability needed → \`.learnings/FEATURE_REQUESTS.md\`
- Skill authoring workflow improvement → \`.learnings/FEATURE_REQUESTS.md\`
- Hook development tooling gap → \`.learnings/FEATURE_REQUESTS.md\`

**Promote when pattern is proven:**
- Instruction fixes → rewrite directly in AGENTS.md / SOUL.md / TOOLS.md
- Behavior patterns → SOUL.md
- Workflow improvements → AGENTS.md
- Tool integration fixes → TOOLS.md
- Memory management patterns → MEMORY.md
- Skill improvements → update the affected SKILL.md

Meta-learnings modify the infrastructure all other skills depend on. Apply fixes directly.
`.trim();

const handler = async (event) => {
  if (!event || typeof event !== 'object') {
    return;
  }

  if (event.type !== 'agent' || event.action !== 'bootstrap') {
    return;
  }

  if (!event.context || typeof event.context !== 'object') {
    return;
  }

  if (Array.isArray(event.context.bootstrapFiles)) {
    event.context.bootstrapFiles.push({
      path: 'META_SELF_IMPROVEMENT_REMINDER.md',
      content: REMINDER_CONTENT,
      virtual: true,
    });
  }
};

module.exports = handler;
module.exports.default = handler;


path: hooks/openclaw/HOOK.md
content: ---
name: self-improving-meta
description: "Injects meta self-improvement reminder during agent bootstrap"
metadata: {"openclaw":{"emoji":"🔧","events":["agent:bootstrap"]}}
---

# Meta Self-Improvement Hook

Injects a reminder to evaluate agent infrastructure learnings during agent bootstrap.

## What It Does

- Fires on `agent:bootstrap` (before workspace files are injected)
- Adds a meta-specific reminder block to check `.learnings/` for infrastructure entries
- Prompts the agent to log prompt file issues, hook failures, skill activation problems, rule conflicts, context bloat, and memory staleness
- Skips subagent sessions to avoid noise
- Reminder-only behavior: does not modify files or call network resources

## Reminder Content

The hook injects reminders to log to the appropriate file based on what occurred:

| Trigger | Target File | Category |
|---------|-------------|----------|
| Agent misinterprets prompt file instruction | `LEARNINGS.md` | `instruction_ambiguity` |
| Hook fails or produces no output | `META_ISSUES.md` | hook_failure |
| Skill doesn't activate when expected | `META_ISSUES.md` | skill_gap |
| Two rules contradict each other | `LEARNINGS.md` | `rule_conflict` |
| Context window feels cramped/truncated | `LEARNINGS.md` | `context_bloat` |
| Memory entry is stale or wrong | `LEARNINGS.md` | `prompt_drift` |
| Missing skill capability | `FEATURE_REQUESTS.md` | feature request |

## Configuration

No configuration needed. Enable with:

```bash
openclaw hooks enable self-improving-meta
```


path: hooks/openclaw/handler.ts
content: /**
 * Self-Improving Meta Hook for OpenClaw
 *
 * Injects a meta-specific reminder to evaluate infrastructure learnings during agent bootstrap.
 * Fires on agent:bootstrap event before workspace files are injected.
 * Skips subagent sessions to reduce noise.
 */

import type { HookHandler } from 'openclaw/hooks';

const REMINDER_CONTENT = `## Meta Self-Improvement Reminder

After completing tasks, evaluate if any agent infrastructure learnings should be captured:

**Log learnings when:**
- Agent misinterprets a prompt file instruction → \`.learnings/LEARNINGS.md\` (instruction_ambiguity)
- Two rules contradict each other across files → \`.learnings/LEARNINGS.md\` (rule_conflict)
- Context window feels cramped or truncated → \`.learnings/LEARNINGS.md\` (context_bloat)
- Memory entry is stale or causing wrong behavior → \`.learnings/LEARNINGS.md\` (prompt_drift)
- Skill template is missing a section → \`.learnings/LEARNINGS.md\` (skill_gap)

**Log meta issues when:**
- Hook fails or produces no output → \`.learnings/META_ISSUES.md\`
- Skill doesn't activate when expected → \`.learnings/META_ISSUES.md\`
- Prompt file has malformed frontmatter → \`.learnings/META_ISSUES.md\`
- Extension API breaks or behaves unexpectedly → \`.learnings/META_ISSUES.md\`

**Log feature requests when:**
- New infrastructure capability needed → \`.learnings/FEATURE_REQUESTS.md\`
- Skill authoring workflow improvement → \`.learnings/FEATURE_REQUESTS.md\`
- Hook development tooling gap → \`.learnings/FEATURE_REQUESTS.md\`

**Promote when pattern is proven:**
- Instruction fixes → rewrite directly in AGENTS.md / SOUL.md / TOOLS.md
- Behavior patterns → SOUL.md
- Workflow improvements → AGENTS.md
- Tool integration fixes → TOOLS.md
- Memory management patterns → MEMORY.md
- Skill improvements → update the affected SKILL.md

Meta-learnings modify the infrastructure all other skills depend on. Apply fixes directly.`;

const handler: HookHandler = async (event) => {
  if (!event || typeof event !== 'object') {
    return;
  }

  if (event.type !== 'agent' || event.action !== 'bootstrap') {
    return;
  }

  if (!event.context || typeof event.context !== 'object') {
    return;
  }

  const sessionKey = event.sessionKey || '';
  if (sessionKey.includes(':subagent:')) {
    return;
  }

  if (Array.isArray(event.context.bootstrapFiles)) {
    event.context.bootstrapFiles.push({
      path: 'META_SELF_IMPROVEMENT_REMINDER.md',
      content: REMINDER_CONTENT,
      virtual: true,
    });
  }
};

export default handler;


path: references/examples.md
content: # Entry Examples

Concrete examples of well-formatted meta entries with all fields.

## Learning: Instruction Ambiguity (Vague Delegation Threshold)

```markdown
## [LRN-20250415-001] instruction_ambiguity

**Logged**: 2025-04-15T10:30:00Z
**Priority**: high
**Status**: pending
**Area**: agent_config

### Summary
AGENTS.md says "use sub-agents for long tasks" but doesn't define "long" — causing inconsistent delegation

### Details
The delegation section in AGENTS.md states: "For long-running tasks, delegate to a sub-agent."
Different sessions interpret "long" differently — some delegate after 5 minutes of work,
others only after 10+ steps, and some never delegate at all. The instruction lacks a
concrete threshold (time-based, step-count-based, or complexity-based), resulting in
wildly inconsistent behavior across sessions.

### Suggested Action
Rewrite the delegation rule with explicit thresholds:
- "Delegate to a sub-agent when a task requires more than 8 tool calls OR
  involves modifying files in 3+ directories OR touches both frontend and backend."

Remove the vague "long-running" phrasing entirely.

### Metadata
- Source: agent_behavior_observation
- Affected Files: AGENTS.md (delegation section)
- Tags: delegation, threshold, ambiguity, agents-md
- Pattern-Key: instruction_ambiguity.vague_threshold

---
```

## Learning: Rule Conflict (Package Manager Contradiction)

```markdown
## [LRN-20250416-001] rule_conflict

**Logged**: 2025-04-16T09:00:00Z
**Priority**: high
**Status**: pending
**Area**: rule_files

### Summary
CLAUDE.md says "always use pnpm" but AGENTS.md workflow step says "npm install" — agent confused

### Details
CLAUDE.md line 42: "Package management: always use pnpm for all install and run commands."
AGENTS.md line 118 (setup workflow): "Step 3: Run `npm install` to install dependencies."

When the agent encounters the setup workflow, it faces contradictory instructions.
In 3 out of 5 sessions observed, the agent used npm (following AGENTS.md workflow order),
in 2 it used pnpm (following CLAUDE.md rule). Neither outcome was consistent.

### Suggested Action
1. Identify the authoritative source for package manager choice (CLAUDE.md for conventions)
2. Update AGENTS.md workflow step to use `pnpm install`
3. Grep all prompt files for "npm " and replace with "pnpm " where appropriate
4. Add a "Single Source of Truth" comment in AGENTS.md pointing to CLAUDE.md for tool conventions

### Metadata
- Source: agent_behavior_observation
- Affected Files: CLAUDE.md, AGENTS.md
- Tags: rule-conflict, package-manager, pnpm, npm, contradiction
- Pattern-Key: rule_conflict.package_manager

---
```

## Learning: Context Bloat (Verbose SOUL.md)

```markdown
## [LRN-20250417-001] context_bloat

**Logged**: 2025-04-17T14:00:00Z
**Priority**: medium
**Status**: pending
**Area**: prompt_files

### Summary
SOUL.md grew to 400 lines with redundant personality directives, wasting ~2K tokens per session

### Details
SOUL.md accumulated personality directives over several months without pruning:
- Lines 12-45: "Be concise and clear" expressed 6 different ways
- Lines 80-120: Communication style rules that duplicate the conciseness directives
- Lines 200-280: Historical context about the project that is now in README.md
- Lines 300-380: Deprecated workflow patterns superseded by AGENTS.md

At 400 lines, SOUL.md consumes approximately 2,000 tokens every session. After
deduplication and compression, the same behavioral guidance fits in 120 lines (~600 tokens),
saving 1,400 tokens per session for actual work context.

### Suggested Action
1. Deduplicate personality directives — one statement per behavioral rule
2. Remove content that belongs in other files (README, AGENTS.md)
3. Use structured lists instead of prose paragraphs
4. Target: SOUL.md under 150 lines, under 800 tokens

### Metadata
- Source: context_window_analysis
- Affected Files: SOUL.md
- Tags: context-bloat, soul-md, compression, token-waste
- Pattern-Key: context_bloat.verbose_soul

---
```

## Meta Issue: Hook Failure (Activator Path Changed)

```markdown
## [META-20250418-001] hook_failure

**Logged**: 2025-04-18T11:00:00Z
**Priority**: high
**Status**: pending
**Area**: hook_scripts

### Summary
activator.sh exits with code 0 but produces no output — SKILL path changed and script references old location

### Details
After reorganizing the skills directory from `./skills/` to `~/.openclaw/skills/`,
the activator.sh hook at `./skills/self-improving-meta/scripts/activator.sh` was
moved but the hook configuration in `.claude/settings.json` still points to the
old path. The shell finds no script at the old path and exits silently (code 0
because set -e doesn't trigger on a missing path in the command field).

The hook appeared to work (no errors in logs) but produced zero output for 2 weeks.
No self-improvement reminders were injected during that period.

### Root Cause
Hook configuration path was not updated after skill directory reorganization.
No validation exists to check that hook scripts actually produce output.

### Suggested Fix
1. Update hook path in `.claude/settings.json`
2. Add a health check: hook scripts should output at least a version marker
3. Consider adding a `--verify` flag to hook scripts that validates configuration
4. Log a warning if a hook produces empty output

### Metadata
- Source: hook_output_inspection
- Affected Files: .claude/settings.json, scripts/activator.sh
- Tags: hook, silent-failure, path, configuration
- Reproducible: yes

---
```

## Meta Issue: Skill Gap (Database Migration Patterns)

```markdown
## [META-20250419-001] skill_gap

**Logged**: 2025-04-19T16:00:00Z
**Priority**: medium
**Status**: pending
**Area**: skill_authoring

### Summary
No skill for database migration patterns despite 5 related learnings in .learnings/

### Details
Searching .learnings/ reveals 5 entries related to database migrations:
- LRN-20250320-003: Migration rollback failed due to missing down() method
- LRN-20250328-001: Schema change broke running queries during deployment
- LRN-20250405-002: Migration order dependency not documented
- BUG-20250410-004: Data migration corrupted timestamps due to timezone handling
- LRN-20250415-007: Idempotent migration pattern prevented duplicate column errors

These learnings share a common theme and meet extraction criteria (5 related entries,
cross-project applicability, non-obvious patterns). No skill exists to capture this
knowledge as a reusable resource.

### Suggested Fix
1. Extract a `database-migration-patterns` skill from the 5 related learnings
2. Include rollback strategy, zero-downtime patterns, idempotency
3. Update all 5 original entries with `promoted_to_skill` status

### Metadata
- Source: learnings_review
- Affected Files: .learnings/LEARNINGS.md, .learnings/BUG_PATTERNS.md
- Tags: skill-gap, database, migration, extraction-candidate
- Related Entries: LRN-20250320-003, LRN-20250328-001, LRN-20250405-002, BUG-20250410-004, LRN-20250415-007

---
```

## Feature Request: Automated Prompt File Conflict Detection

```markdown
## [FEAT-20250420-001] prompt_conflict_detector

**Logged**: 2025-04-20T10:00:00Z
**Priority**: high
**Status**: pending
**Area**: agent_config

### Requested Capability
Automated detection of contradictory instructions across AGENTS.md, SOUL.md, TOOLS.md, CLAUDE.md, and copilot-instructions.md.

### User Context
Rule conflicts (like the pnpm vs npm example) go unnoticed for weeks because no tool
cross-references instructions across prompt files. Manual audits catch conflicts eventually,
but a script that flags potential contradictions at commit time or session start would
prevent agent confusion proactively.

### Complexity Estimate
medium

### Suggested Implementation
1. Parse all prompt files into structured sections (tool rules, conventions, workflows)
2. Build a keyword-to-file index (e.g., "pnpm" → CLAUDE.md:42, "npm" → AGENTS.md:118)
3. Flag entries where the same topic appears in multiple files with different instructions
4. Run as a pre-commit hook or OpenClaw bootstrap check
5. Output a conflict report with file paths and line numbers

### Metadata
- Frequency: recurring (3 conflicts found in last month)
- Related Features: prompt file linting, rule deduplication

---
```

## Learning: Promoted to AGENTS.md (Consolidated Delegation Rules)

```markdown
## [LRN-20250410-002] instruction_ambiguity

**Logged**: 2025-04-10T11:00:00Z
**Priority**: high
**Status**: promoted
**Promoted**: AGENTS.md (delegation section rewrite)
**Area**: agent_config

### Summary
Delegation rules scattered across 3 files consolidated into single authoritative section in AGENTS.md

### Details
Delegation guidance was spread across:
- AGENTS.md line 45: "Use sub-agents for complex tasks"
- SOUL.md line 88: "Prefer to handle tasks yourself unless overwhelmed"
- TOOLS.md line 23: "Sub-agent spawning is expensive, use sparingly"

These three statements gave contradictory signals. Consolidated into a single
decision table in AGENTS.md with concrete criteria, and removed delegation
mentions from SOUL.md and TOOLS.md (replaced with "See AGENTS.md for delegation policy").

### Metadata
- Source: agent_behavior_observation
- Affected Files: AGENTS.md, SOUL.md, TOOLS.md
- Tags: delegation, consolidation, single-source-of-truth
- Pattern-Key: instruction_ambiguity.scattered_delegation
- Recurrence-Count: 4
- First-Seen: 2025-03-15
- Last-Seen: 2025-04-10

---
```

## Learning: Promoted to Skill (Prompt File Compression)

```markdown
## [LRN-20250412-003] context_bloat

**Logged**: 2025-04-12T15:00:00Z
**Priority**: high
**Status**: promoted_to_skill
**Skill-Path**: skills/prompt-file-compression
**Area**: prompt_files

### Summary
Systematic approach to compressing verbose prompt files while preserving behavioral fidelity

### Details
Developed a repeatable compression workflow after encountering context bloat in 4 separate
prompt files over 2 months. The pattern is consistent: prompt files grow through
accretion (new rules added, old rules never removed), leading to duplication, contradiction,
and context waste.

### Compression Checklist
1. Count lines and estimate token usage
2. Identify duplicated concepts (same rule expressed differently)
3. Remove content that belongs in other files
4. Convert prose paragraphs to structured lists/tables
5. Remove historical context (move to changelog or README)
6. Verify behavioral fidelity in fresh session
7. Measure token savings

### Metadata
- Source: context_window_analysis
- Affected Files: SOUL.md, AGENTS.md, TOOLS.md, CLAUDE.md
- Tags: compression, context-bloat, prompt-engineering, token-efficiency
- See Also: LRN-20250417-001, LRN-20250325-002, LRN-20250402-004

---
```


path: references/openclaw-integration.md
content: # OpenClaw Integration

Complete setup and usage guide for integrating the self-improving-meta skill with OpenClaw.

## Overview

OpenClaw uses workspace-based prompt injection combined with event-driven hooks. Context is injected from workspace files at session start, and hooks can trigger on lifecycle events. The meta skill is unique: it monitors and improves the very infrastructure that OpenClaw and other skills depend on.

## Workspace Structure

```
~/.openclaw/
├── workspace/                   # Working directory
│   ├── AGENTS.md               # Multi-agent coordination patterns
│   ├── SOUL.md                 # Behavioral guidelines and personality
│   ├── TOOLS.md                # Tool capabilities and gotchas
│   ├── MEMORY.md               # Long-term memory (main session only)
│   └── memory/                 # Daily memory files
│       └── YYYY-MM-DD.md
├── skills/                      # Installed skills
│   └── self-improving-meta/
│       └── SKILL.md
└── hooks/                       # Custom hooks
    └── self-improving-meta/
        ├── HOOK.md
        └── handler.ts
```

## Quick Setup

### 1. Install the Skill

```bash
clawdhub install self-improving-meta
```

Or copy manually:

```bash
cp -r self-improving-meta ~/.openclaw/skills/
```

### 2. Install the Hook (Optional)

```bash
cp -r hooks/openclaw ~/.openclaw/hooks/self-improving-meta
openclaw hooks enable self-improving-meta
```

### 3. Create Learning Files

```bash
mkdir -p ~/.openclaw/workspace/.learnings
```

## Promotion Targets (Meta-Specific)

Meta-learnings promote directly into the files they govern:

| Learning Type | Promote To | Example |
|---------------|------------|---------|
| Agent behavior corrections | `SOUL.md` | "Be concise" repeated 6 ways → single directive |
| Workflow/delegation improvements | `AGENTS.md` | Vague "long tasks" → explicit step-count threshold |
| Tool integration fixes | `TOOLS.md` | Missing MCP timeout guidance → add retry config |
| Memory management patterns | `MEMORY.md` | Stale entries accumulating → add 30-day rotation policy |
| Skill authoring improvements | Affected `SKILL.md` | Missing frontmatter field → update template |
| Hook code fixes | Hook source code | Silent failure → add output validation |
| Rule clarifications | Rule file directly | Ambiguous trigger → explicit condition |

### Promotion Decision Tree

```
Is it about agent behavior or personality?
├── Yes → Promote to SOUL.md
└── No → Is it about workflows or delegation?
    ├── Yes → Promote to AGENTS.md
    └── No → Is it about tool usage or integration?
        ├── Yes → Promote to TOOLS.md
        └── No → Is it about memory management?
            ├── Yes → Promote to MEMORY.md
            └── No → Is it about a specific skill?
                ├── Yes → Update that skill's SKILL.md
                └── No → Is it about hooks?
                    ├── Yes → Update hook code + HOOK.md
                    └── No → Is it about rules?
                        ├── Yes → Update the rule file directly
                        └── No → Log as feature request
```

## Meta-Specific Detection Triggers

| Trigger | Action | Target |
|---------|--------|--------|
| Agent ignores a prompt file rule | Log learning | LEARNINGS.md (instruction_ambiguity) |
| Two files give contradictory guidance | Log learning | LEARNINGS.md (rule_conflict) |
| Context window truncated or cramped | Log learning | LEARNINGS.md (context_bloat) |
| Memory entry references deleted file | Log learning | LEARNINGS.md (prompt_drift) |
| Hook produces no output | Log meta issue | META_ISSUES.md (hook_failure) |
| Skill doesn't activate on matching trigger | Log meta issue | META_ISSUES.md (skill_gap) |
| Frontmatter malformed or missing fields | Log meta issue | META_ISSUES.md |
| New infrastructure capability needed | Log feature request | FEATURE_REQUESTS.md |

## Inter-Agent Communication

OpenClaw provides tools for cross-session communication. Use only when cross-session sharing is explicitly needed.

### sessions_send

Share an infrastructure finding with another session:
```
sessions_send(sessionKey="session-id", message="Rule conflict: CLAUDE.md says pnpm, AGENTS.md says npm. Authoritative source: CLAUDE.md.")
```

### sessions_spawn

Spawn a background agent to audit prompt files:
```
sessions_spawn(task="Audit all prompt files for contradictions and context bloat", label="meta-audit")
```

## Available Hook Events

| Event | When It Fires |
|-------|---------------|
| `agent:bootstrap` | Before workspace files inject |
| `command:new` | When `/new` command issued |
| `command:reset` | When `/reset` command issued |
| `command:stop` | When `/stop` command issued |
| `gateway:startup` | When gateway starts |

## Verification

```bash
openclaw hooks list        # Check hook is registered
openclaw status            # Check skill is loaded
```

## Troubleshooting

### Hook not firing
1. Ensure hooks enabled in config
2. Restart gateway after config changes
3. Check gateway logs for errors

### Learnings not persisting
1. Verify `.learnings/` directory exists
2. Check file permissions
3. Ensure workspace path is configured correctly

### Skill not loading
1. Check skill is in skills directory
2. Verify SKILL.md has correct frontmatter
3. Run `openclaw status` to see loaded skills


path: references/hooks-setup.md
content: # Hook Setup Guide

Configure automatic meta self-improvement triggers for AI coding agents.

## Overview

Hooks can help capture infrastructure learnings with minimal overhead:
- **UserPromptSubmit** (recommended): Reminder after each prompt to evaluate meta learnings
- **PostToolUse (Bash)** (optional): Conservative error-pattern reminder based on command output in trusted environments

## Claude Code Setup

### Option 1: Project-Level Configuration

Create `.claude/settings.json` in your project root (activator-only recommended):

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-meta/scripts/activator.sh"
          }
        ]
      }
    ]
  }
}
```

### Optional: Add PostToolUse Error Detector

Enable this only when you explicitly want command-output pattern checks:

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-meta/scripts/error-detector.sh"
          }
        ]
      }
    ]
  }
}
```

### Option 2: User-Level Configuration

Add to `~/.claude/settings.json` for global activation:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/skills/self-improving-meta/scripts/activator.sh"
          }
        ]
      }
    ]
  }
}
```

### Minimal Setup (Activator Only)

For lower overhead, use only the UserPromptSubmit hook:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-meta/scripts/activator.sh"
          }
        ]
      }
    ]
  }
}
```

## Codex CLI Setup

Codex uses the same hook system. Create `.codex/settings.json`:

```json
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "./skills/self-improving-meta/scripts/activator.sh"
          }
        ]
      }
    ]
  }
}
```

## GitHub Copilot Setup

Copilot doesn't support hooks. Add guidance to `.github/copilot-instructions.md`:

```markdown
## Meta Self-Improvement

After modifying agent configuration or prompt files, consider logging to `.learnings/`:
- Instruction ambiguity, rule conflicts, context bloat → LEARNINGS.md
- Hook failures, skill activation issues, prompt errors → META_ISSUES.md
- Infrastructure capability requests → FEATURE_REQUESTS.md

Promote recurring patterns directly into the affected prompt files.
```

## Verification

### Test Activator Hook

1. Enable the hook configuration
2. Start a new Claude Code session
3. Send any prompt
4. Verify you see `<meta-improvement-reminder>` in the context

### Test Error Detector Hook

1. Enable PostToolUse hook for Bash
2. Run a command that references a missing SKILL.md or AGENTS.md
3. Verify you see `<meta-error-detected>` reminder

### Dry Run Extract Script

```bash
./skills/self-improving-meta/scripts/extract-skill.sh test-skill --dry-run
```

## Troubleshooting

### Hook Not Triggering

1. **Check script permissions**: `chmod +x scripts/*.sh`
2. **Verify path**: Use absolute paths or paths relative to project root
3. **Check settings location**: Project vs user-level settings
4. **Restart session**: Hooks are loaded at session start

### Permission Denied

```bash
chmod +x ./skills/self-improving-meta/scripts/activator.sh
chmod +x ./skills/self-improving-meta/scripts/error-detector.sh
chmod +x ./skills/self-improving-meta/scripts/extract-skill.sh
```

### Script Not Found

If using relative paths, ensure you're in the correct directory or use absolute paths:

```json
{
  "command": "/absolute/path/to/skills/self-improving-meta/scripts/activator.sh"
}
```

### Too Much Overhead

If the activator feels intrusive:

1. **Use minimal setup**: Only UserPromptSubmit, skip PostToolUse
2. **Add matcher filter**: Only trigger for infrastructure-related prompts:

```json
{
  "matcher": "hook|skill|AGENTS|SOUL|TOOLS|MEMORY|CLAUDE|rule|prompt",
  "hooks": [...]
}
```

## Hook Output Budget

The activator is designed to be lightweight:
- **Target**: ~50-100 tokens per activation
- **Content**: Structured meta-specific reminder, not verbose instructions
- **Format**: XML tags for easy parsing

## Security Considerations

- Hook scripts run with the same permissions as the agent
- Scripts only output text; they don't modify files or run commands
- Error detector reads `CLAUDE_TOOL_OUTPUT` only when PostToolUse is enabled
- Treat `CLAUDE_TOOL_OUTPUT` as potentially sensitive; do not log verbatim
- All scripts are opt-in
- Recommended default: enable `UserPromptSubmit` only; add `PostToolUse` when you want infrastructure error detection

## Disabling Hooks

To temporarily disable without removing configuration:

1. Comment out in settings
2. Or delete the settings file — hooks won't run without configuration


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