Skill: tzx666888/beastxa-memory-pro (version 1.0.0)

--- name: beastxa-memory-pro description: > Production-grade memory system for OpenClaw agents. Auto-organizes notes into topic files, prevents context loss during compaction, and runs daily/weekly maintenance crons. Zero external dependencies — pure local Markdown files. Install and forget. Use when: agent keeps forgetting context, MEMORY.md is too large, notes are disorganized, or you want automatic memory maintenance without manual effort. license: MIT-0 --- # BeastXA Memory Pro Stop losing context. Start remembering everything. ## What It Does 1. **Structured Session Notes** — auto-maintained `session-notes.md` captures your current work state 2. **Smart Memory Split** — breaks large MEMORY.md into topic files with an index 3. **Auto Maintenance** — daily cleanup + weekly deep organization via cron 4. **Anti-Amnesia** — enhanced compaction saves critical context before compression ## Quick Start ```bash # Install clawhub install beastxa-memory-pro # Run setup (interactive, takes ~30 seconds) bash scripts/install.sh ``` That's it. Everything else is automatic. ## What Gets Created ``` your-workspace/ ├── memory/ │ ├── session-notes.md # Live session state (auto-updated) │ ├── MEMORY-INDEX.md # Topic file directory │ ├── YYYY-MM-DD.md # Daily logs (auto-appended) │ └── topics/ # Organized by theme │ ├── projects.md │ ├── decisions.md │ ├── lessons.md │ └── ... # Auto-generated from your content ``` ## How It Works ### Three-Layer Memory | Layer | File | Purpose | Update Frequency | |-------|------|---------|-----------------| | Session | `session-notes.md` | Current work state | Every compaction | | Daily | `YYYY-MM-DD.md` | Raw daily log | Every significant event | | Topics | `topics/*.md` | Long-term organized memory | Daily cron | ### Anti-Amnesia System Before each context compaction: 1. Saves current task, recent decisions, errors, and next steps 2. Writes to both `session-notes.md` and daily log 3. After compaction, agent reads session-notes and resumes seamlessly ### Auto Maintenance Crons - **Daily (23:30)** — extracts key decisions and lessons from today's log into topic files - **Weekly (Sunday 23:00)** — deduplicates, merges, trims topic files; verifies index ## Manual Commands **Split an existing MEMORY.md:** ```bash python3 scripts/split_memory.py --input MEMORY.md --output memory/topics/ ``` - Reads your MEMORY.md, detects topic boundaries (## headers) - Creates one file per topic in `memory/topics/` - Generates `memory/MEMORY-INDEX.md` with pointers - Original file untouched — zero risk **Verify installation:** ```bash bash scripts/verify.sh ``` ## Configuration The install script adds compaction enhancement to your OpenClaw config: ```json { "agents": { "defaults": { "compaction": { "memoryFlush": { "enabled": true, "prompt": "Pre-compaction memory flush. Store durable memories in memory/YYYY-MM-DD.md..." }, "instructions": "Preserve: user decisions, file paths, errors+fixes, current task, next step..." } } } } ``` You can customize the compaction instructions to match your workflow. ## FAQ **Will it overwrite my existing MEMORY.md?** Never. The split script only reads it. Your original stays intact. **Does it send data anywhere?** No. Everything is local Markdown files. No APIs, no cloud, no external services. **Can I use it with other memory skills?** Yes. It only creates files and cron jobs — no core modifications. **What if I don't like the topic categories?** Edit them freely. They're just Markdown files. The cron will respect your structure. ## Requirements - OpenClaw 2026.3.x or later - Python 3.8+ (for split script) - That's it

path: README.md
content: # 🧠 BeastXA Memory Pro

**Stop losing context. Start remembering everything.**

A production-grade memory system for [OpenClaw](https://github.com/openclaw/openclaw) agents. Zero external dependencies — pure local Markdown files.

## The Problem

AI agents forget. Every time the context window fills up and compacts, your agent loses track of what it was doing, what you decided, and what mistakes it already made. You end up repeating yourself. Again. And again.

## The Solution

BeastXA Memory Pro gives your agent a three-layer memory system that survives compaction:

| Layer | What | How |
|-------|------|-----|
| **Session Notes** | Current work state | Auto-updated before each compaction |
| **Daily Logs** | Raw daily records | Auto-appended, never overwritten |
| **Topic Files** | Organized long-term memory | Auto-maintained by daily/weekly crons |

## Quick Start

```bash
# Install from ClawHub
clawhub install beastxa-memory-pro

# Run setup (~30 seconds)
bash scripts/install.sh

# Done. Everything else is automatic.
```

## What It Does

- ✅ Creates structured memory directory (`memory/topics/`, `session-notes.md`)
- ✅ Splits large MEMORY.md into organized topic files
- ✅ Enhances compaction to preserve critical context
- ✅ Runs daily cleanup cron (23:30) — extracts key info into topics
- ✅ Runs weekly deep clean (Sunday 23:00) — dedup, merge, trim
- ✅ Never overwrites or deletes your existing files

## What It Doesn't Do

- ❌ No external APIs or cloud services
- ❌ No data leaves your machine
- ❌ No modifications to OpenClaw core
- ❌ No complex configuration needed

## Manual Split

Already have a large MEMORY.md? Split it:

```bash
python3 scripts/split_memory.py

# Preview first (no changes):
python3 scripts/split_memory.py --dry-run

# Custom paths:
python3 scripts/split_memory.py --input /path/to/MEMORY.md --output /path/to/topics/
```

## Verify Installation

```bash
bash scripts/verify.sh
```

## Requirements

- OpenClaw 2026.3.x+
- Python 3.8+

## License

MIT-0 — use it however you want, no attribution required.

## Credits

Built by [BeastXA](https://github.com/beastxa6-668) — battle-tested in production with 9 AI agents running 24/7.


path: docs/faq.md
content: # FAQ

## General

**Q: Will it overwrite my existing MEMORY.md?**
A: Never. The split script only reads it. Your original stays intact.

**Q: Does it send data anywhere?**
A: No. Everything is local Markdown files. No APIs, no cloud, no external services.

**Q: Can I use it with other memory skills?**
A: Yes. It only creates files and cron jobs — no core modifications.

**Q: What if I don't like the topic categories?**
A: Edit them freely. They're just Markdown files. The cron respects your structure.

## Installation

**Q: What if install.sh fails?**
A: Run `bash scripts/verify.sh` to see what's missing. Each step can be done manually — see the templates/ folder.

**Q: Can I run install.sh multiple times?**
A: Yes. It's idempotent — skips anything already set up.

**Q: What OpenClaw versions are supported?**
A: 2026.3.x and later.

## Memory Management

**Q: How big can my memory files get?**
A: The weekly cron trims topic files to ~100 lines each. Daily logs are never trimmed (they're your raw history).

**Q: What if the cron makes a mistake?**
A: Crons only append to topic files, never delete. Worst case: a duplicate entry that gets cleaned up next week.

**Q: Can I disable the crons?**
A: Yes. Run `openclaw cron list` to find the IDs, then `openclaw cron delete <id>`.

## Troubleshooting

**Q: My agent still forgets things after installing.**
A: Check that `memoryFlush.enabled` is `true` in your OpenClaw config. Run `bash scripts/verify.sh`.

**Q: The split script says "No ## headers found".**
A: Your MEMORY.md needs `## Section Name` headers for the splitter to detect topics. Add some headers and try again.

**Q: Crons aren't running.**
A: Check `openclaw cron list` — status should be "ok". If "error", check the cron logs.


path: docs/quickstart.md
content: # Quick Start — 5 Minutes to Never Forget Again

## Step 1: Install

```bash
clawhub install beastxa-memory-pro
```

Or clone from GitHub:
```bash
git clone https://github.com/beastxa6-668/beastxa-memory-pro.git
cp -r beastxa-memory-pro ~/.openclaw/skills/
```

## Step 2: Run Setup

```bash
cd ~/.openclaw/skills/beastxa-memory-pro
bash scripts/install.sh
```

The installer will:
1. Create `memory/` directory structure
2. Generate session-notes template
3. Configure compaction enhancement
4. Set up daily + weekly maintenance crons

## Step 3: (Optional) Split Existing Memory

If you already have a large MEMORY.md:

```bash
python3 scripts/split_memory.py
```

This reads your MEMORY.md, splits it by topic into `memory/topics/`, and creates an index. Your original file stays untouched.

## Step 4: Verify

```bash
bash scripts/verify.sh
```

You should see all green checkmarks.

## That's It

From now on:
- Your agent auto-saves context before each compaction
- Daily cron organizes today's notes into topic files (23:30)
- Weekly cron deduplicates and trims (Sunday 23:00)
- You never have to think about memory management again


path: scripts/install.sh
content: #!/usr/bin/env bash
#
# BeastXA Memory Pro — One-Click Installer
#
# Usage:
#   bash install.sh
#   bash install.sh --workspace /path/to/workspace
#
set -euo pipefail

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

echo ""
echo -e "${BLUE}🧠 BeastXA Memory Pro — Installer${NC}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

# Detect workspace
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SKILL_DIR="$(dirname "$SCRIPT_DIR")"

# Check if --workspace flag is provided
WORKSPACE=""
while [[ $# -gt 0 ]]; do
    case $1 in
        --workspace|-w)
            WORKSPACE="$2"
            shift 2
            ;;
        *)
            shift
            ;;
    esac
done

# Auto-detect workspace from OpenClaw config if not specified
if [ -z "$WORKSPACE" ]; then
    # Try to find workspace from openclaw config
    if command -v openclaw &> /dev/null; then
        WORKSPACE=$(openclaw config get agents.defaults.workspace 2>/dev/null || echo "")
    fi
    
    # Fallback: use current directory
    if [ -z "$WORKSPACE" ] || [ "$WORKSPACE" = "null" ]; then
        WORKSPACE="$(pwd)"
    fi
fi

echo -e "📂 Workspace: ${GREEN}${WORKSPACE}${NC}"
echo ""

# Step 1: Check prerequisites
echo -e "${YELLOW}Step 1/4: Checking prerequisites...${NC}"

if ! command -v python3 &> /dev/null; then
    echo -e "${RED}❌ Python 3 not found. Please install Python 3.8+${NC}"
    exit 1
fi
echo "   ✅ Python 3 found: $(python3 --version)"

if ! command -v openclaw &> /dev/null; then
    echo -e "${RED}❌ OpenClaw not found. Please install OpenClaw first.${NC}"
    echo "   See: https://docs.openclaw.ai"
    exit 1
fi
echo "   ✅ OpenClaw found"

OPENCLAW_CONFIG="$HOME/.openclaw/openclaw.json"
if [ ! -f "$OPENCLAW_CONFIG" ]; then
    echo -e "${RED}❌ OpenClaw config not found at $OPENCLAW_CONFIG${NC}"
    exit 1
fi
echo "   ✅ OpenClaw config found"
echo ""

# Step 2: Create memory structure
echo -e "${YELLOW}Step 2/4: Setting up memory structure...${NC}"
python3 "${SCRIPT_DIR}/setup_memory.py" --workspace "$WORKSPACE"
echo ""

# Step 3: Configure compaction enhancement
echo -e "${YELLOW}Step 3/4: Enhancing compaction config...${NC}"

python3 << PYEOF
import json
import os
import shutil
from datetime import datetime

config_path = os.path.expanduser("~/.openclaw/openclaw.json")

# Backup config first
backup_path = config_path + f".backup.{datetime.now().strftime('%Y%m%d%H%M%S')}"
shutil.copy2(config_path, backup_path)
print(f"   📋 Config backed up to {os.path.basename(backup_path)}")

with open(config_path, 'r') as f:
    cfg = json.load(f)

# Ensure agents.defaults.compaction exists
agents = cfg.setdefault('agents', {})
defaults = agents.setdefault('defaults', {})
compaction = defaults.setdefault('compaction', {})

# Add memoryFlush if not present
if 'memoryFlush' not in compaction:
    compaction['memoryFlush'] = {
        "enabled": True,
        "prompt": (
            "Pre-compaction memory flush. Store durable memories only in "
            "memory/{date}.md (use today's date in YYYY-MM-DD format). "
            "Create memory/ directory if needed. "
            "If the file already exists, APPEND new content only — do not overwrite. "
            "Do NOT modify MEMORY.md, SOUL.md, TOOLS.md, or AGENTS.md. "
            "If nothing to store, reply with NO_REPLY."
        )
    }
    print("   ✅ memoryFlush configured")
else:
    print("   ⏭️  memoryFlush already configured")

# Add compaction instructions if not present
if 'instructions' not in compaction:
    compaction['instructions'] = (
        "Preserve in summary: 1) User's explicit decisions and instructions (quote verbatim) "
        "2) File paths and code changes 3) Errors encountered and fixes applied "
        "4) Current task being worked on 5) Next step to take "
        "6) All non-tool user messages 7) Pending tasks not yet completed"
    )
    print("   ✅ Compaction instructions configured")
else:
    print("   ⏭️  Compaction instructions already configured")

with open(config_path, 'w') as f:
    json.dump(cfg, f, indent=2, ensure_ascii=False)

print("   ✅ Config saved")
PYEOF
echo ""

# Step 4: Set up cron jobs
echo -e "${YELLOW}Step 4/4: Setting up maintenance crons...${NC}"

# Check if crons already exist
EXISTING_CRONS=$(openclaw cron list 2>/dev/null | grep -c "Memory Pro" || true)
if [ "$EXISTING_CRONS" -gt 0 ]; then
    echo "   ⏭️  Memory Pro crons already exist ($EXISTING_CRONS found)"
else
    # Daily maintenance cron
    openclaw cron add \
        --name "Memory Pro — Daily Cleanup" \
        --cron "30 23 * * *" \
        --tz "$(python3 -c 'import time; print(time.tzname[0])' 2>/dev/null || echo 'UTC')" \
        --timeout-seconds 120 \
        --message 'You are a memory maintenance assistant. Tasks:
1. Read today'\''s memory/YYYY-MM-DD.md (use today'\''s date)
2. Extract key decisions, lessons, and rules
3. Append them to the appropriate memory/topics/*.md files
4. Do NOT delete any files or overwrite existing content
5. If nothing to organize, reply "No maintenance needed today."
Output: ✅ Daily cleanup: X topics updated' \
        > /dev/null 2>&1 && echo "   ✅ Daily cleanup cron created (23:30)" || echo "   ⚠️  Failed to create daily cron"

    # Weekly deep maintenance cron
    openclaw cron add \
        --name "Memory Pro — Weekly Deep Clean" \
        --cron "0 23 * * 0" \
        --tz "$(python3 -c 'import time; print(time.tzname[0])' 2>/dev/null || echo 'UTC')" \
        --timeout-seconds 180 \
        --message 'You are a memory maintenance assistant. Weekly deep clean:
1. Read all memory/topics/*.md files
2. Remove duplicate content across files
3. Merge related entries
4. Trim each file to under 100 lines (keep most recent/important)
5. Update memory/MEMORY-INDEX.md if topics changed
6. Do NOT delete any files or modify MEMORY.md
Output: ✅ Weekly cleanup: X files updated, Y duplicates removed' \
        > /dev/null 2>&1 && echo "   ✅ Weekly deep clean cron created (Sunday 23:00)" || echo "   ⚠️  Failed to create weekly cron"
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo -e "${GREEN}🎉 Installation complete!${NC}"
echo ""
echo "What happens now:"
echo "  • Your agent auto-saves context before each compaction"
echo "  • Daily cleanup runs at 23:30 (organizes today's notes)"
echo "  • Weekly deep clean runs Sunday 23:00 (dedup + trim)"
echo ""
echo "Optional next steps:"
echo "  • Split existing MEMORY.md: python3 ${SCRIPT_DIR}/split_memory.py"
echo "  • Verify installation: bash ${SCRIPT_DIR}/verify.sh"
echo ""


path: scripts/setup_memory.py
content: #!/usr/bin/env python3
"""
BeastXA Memory Pro — Memory Structure Setup

Creates the memory directory structure and templates.
Safe to run multiple times — won't overwrite existing files.

Usage:
    python3 setup_memory.py
    python3 setup_memory.py --workspace /path/to/workspace
"""

import argparse
import os
from pathlib import Path
from datetime import datetime

SESSION_NOTES_TEMPLATE = """# Session Notes
_Auto-maintained by BeastXA Memory Pro_

# Current State
_Describe what you're currently working on_

# Task Specification
_Core objectives and requirements_

# Files and Functions
_Key files you're working with_

# Errors and Corrections
_Mistakes made and how they were fixed_

# Learnings
_Lessons learned during this session_

# Key Results
_Important outputs and achievements_

# Worklog
_Chronological log of work done_
"""

MEMORY_TEMPLATE = """# MEMORY.md — Long-Term Memory

_Last updated: {date}_

## About You
- Name:
- Timezone:
- Key context:

## Active Projects
- Project 1: status
- Project 2: status

## Decisions & Lessons
- Decision 1: rationale
- Lesson 1: what happened and what to do differently

## Preferences & Rules
- Communication style:
- Work preferences:
- Red lines:

## Tools & Environment
- Platform:
- Key tools:
- Accounts:
"""


def create_file_if_missing(path: Path, content: str, label: str):
    """Create a file only if it doesn't exist."""
    if path.exists():
        print(f'   ⏭️  {label}: already exists, skipping')
        return False
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content, encoding='utf-8')
    print(f'   ✅ {label}: created')
    return True


def main():
    parser = argparse.ArgumentParser(description='Set up memory structure')
    parser.add_argument('--workspace', '-w', default='.',
                        help='Workspace root directory (default: current dir)')
    args = parser.parse_args()
    
    workspace = Path(args.workspace).resolve()
    print(f'🏗️  Setting up memory structure in: {workspace}')
    print()
    
    created = 0
    
    # Create directories
    dirs = ['memory', 'memory/topics']
    for d in dirs:
        dirpath = workspace / d
        if not dirpath.exists():
            dirpath.mkdir(parents=True, exist_ok=True)
            print(f'   📁 Created {d}/')
            created += 1
        else:
            print(f'   ⏭️  {d}/ already exists')
    
    print()
    
    # Create session-notes.md
    if create_file_if_missing(
        workspace / 'memory' / 'session-notes.md',
        SESSION_NOTES_TEMPLATE,
        'memory/session-notes.md'
    ):
        created += 1
    
    # Create MEMORY.md (only if it doesn't exist)
    if create_file_if_missing(
        workspace / 'MEMORY.md',
        MEMORY_TEMPLATE.format(date=datetime.now().strftime('%Y-%m-%d')),
        'MEMORY.md'
    ):
        created += 1
    
    # Create today's daily log
    today = datetime.now().strftime('%Y-%m-%d')
    daily_content = f'# {today}\n\n_Daily log created by BeastXA Memory Pro_\n'
    if create_file_if_missing(
        workspace / 'memory' / f'{today}.md',
        daily_content,
        f'memory/{today}.md'
    ):
        created += 1
    
    print()
    if created > 0:
        print(f'✅ Setup complete! {created} items created.')
    else:
        print('✅ Everything already set up. No changes needed.')
    
    print()
    print('Next steps:')
    print('  1. Edit MEMORY.md with your key information')
    print('  2. Run: bash scripts/install.sh  (to set up crons and compaction)')
    print('  3. Start chatting — your agent will auto-maintain memory from here')


if __name__ == '__main__':
    main()


path: scripts/split_memory.py
content: #!/usr/bin/env python3
"""
BeastXA Memory Pro — MEMORY.md Smart Splitter

Reads a large MEMORY.md file and splits it into topic files based on ## headers.
Generates an index file pointing to each topic.

Usage:
    python3 split_memory.py
    python3 split_memory.py --input /path/to/MEMORY.md --output /path/to/topics/
    python3 split_memory.py --dry-run   # Preview without writing
"""

import argparse
import os
import re
import sys
from pathlib import Path
from datetime import datetime


def slugify(text: str) -> str:
    """Convert a header to a safe filename."""
    # Remove markdown formatting and special chars
    text = re.sub(r'[#*`\[\](){}|]', '', text).strip()
    # Replace spaces and special chars with hyphens
    text = re.sub(r'[\s/\\:]+', '-', text)
    # Remove leading/trailing hyphens
    text = text.strip('-')
    # Lowercase for consistency
    return text.lower() if text else 'misc'


def detect_topics(content: str) -> list:
    """Split content by ## headers into topic chunks."""
    lines = content.split('\n')
    topics = []
    current_title = None
    current_lines = []
    
    for line in lines:
        # Match ## headers (but not ### or deeper)
        match = re.match(r'^##\s+(.+)$', line)
        if match:
            # Save previous topic
            if current_title is not None:
                body = '\n'.join(current_lines).strip()
                if body:  # Only save non-empty topics
                    topics.append({
                        'title': current_title,
                        'slug': slugify(current_title),
                        'body': body
                    })
            current_title = match.group(1).strip()
            current_lines = []
        else:
            current_lines.append(line)
    
    # Don't forget the last topic
    if current_title is not None:
        body = '\n'.join(current_lines).strip()
        if body:
            topics.append({
                'title': current_title,
                'slug': slugify(current_title),
                'body': body
            })
    
    # Handle content before first ## header
    if topics and lines:
        pre_header = []
        for line in lines:
            if re.match(r'^##\s+', line):
                break
            pre_header.append(line)
        pre_content = '\n'.join(pre_header).strip()
        if pre_content and not pre_content.startswith('# MEMORY'):
            topics.insert(0, {
                'title': 'General',
                'slug': 'general',
                'body': pre_content
            })
    
    return topics


def merge_duplicate_slugs(topics: list) -> list:
    """Merge topics with the same slug."""
    merged = {}
    order = []
    for t in topics:
        slug = t['slug']
        if slug in merged:
            merged[slug]['body'] += '\n\n' + t['body']
        else:
            merged[slug] = t.copy()
            order.append(slug)
    return [merged[s] for s in order]


def generate_index(topics: list, output_dir: str) -> str:
    """Generate MEMORY-INDEX.md content."""
    lines = [
        '# Memory Index',
        f'_Auto-generated by BeastXA Memory Pro on {datetime.now().strftime("%Y-%m-%d %H:%M")}_',
        f'_Source: MEMORY.md → {len(topics)} topic files_',
        '',
        '| Topic | File | Lines |',
        '|-------|------|-------|',
    ]
    for t in topics:
        filepath = f'topics/{t["slug"]}.md'
        line_count = t['body'].count('\n') + 1
        lines.append(f'| {t["title"]} | `{filepath}` | {line_count} |')
    
    return '\n'.join(lines) + '\n'


def main():
    parser = argparse.ArgumentParser(description='Split MEMORY.md into topic files')
    parser.add_argument('--input', '-i', default='MEMORY.md',
                        help='Path to MEMORY.md (default: ./MEMORY.md)')
    parser.add_argument('--output', '-o', default='memory/topics',
                        help='Output directory for topic files (default: memory/topics/)')
    parser.add_argument('--index', default='memory/MEMORY-INDEX.md',
                        help='Path for index file (default: memory/MEMORY-INDEX.md)')
    parser.add_argument('--dry-run', '-n', action='store_true',
                        help='Preview split without writing files')
    parser.add_argument('--force', '-f', action='store_true',
                        help='Overwrite existing topic files')
    args = parser.parse_args()
    
    # Read input
    input_path = Path(args.input)
    if not input_path.exists():
        print(f'❌ File not found: {input_path}')
        print(f'   Make sure MEMORY.md exists in your workspace')
        sys.exit(1)
    
    content = input_path.read_text(encoding='utf-8')
    original_lines = content.count('\n') + 1
    print(f'📖 Reading {input_path} ({original_lines} lines)')
    
    # Detect and merge topics
    topics = detect_topics(content)
    topics = merge_duplicate_slugs(topics)
    
    if not topics:
        print('⚠️  No ## headers found in MEMORY.md. Nothing to split.')
        sys.exit(0)
    
    total_lines = sum(t['body'].count('\n') + 1 for t in topics)
    print(f'🔍 Found {len(topics)} topics ({total_lines} lines of content)')
    
    # Preview
    print('\n📋 Topics:')
    for i, t in enumerate(topics, 1):
        lines = t['body'].count('\n') + 1
        print(f'   {i}. {t["title"]} → topics/{t["slug"]}.md ({lines} lines)')
    
    if args.dry_run:
        print('\n🏁 Dry run complete. No files written.')
        return
    
    # Create output directory
    output_dir = Path(args.output)
    output_dir.mkdir(parents=True, exist_ok=True)
    
    # Write topic files
    written = 0
    skipped = 0
    for t in topics:
        filepath = output_dir / f'{t["slug"]}.md'
        if filepath.exists() and not args.force:
            print(f'   ⏭️  Skipping {filepath} (exists, use --force to overwrite)')
            skipped += 1
            continue
        
        file_content = f'## {t["title"]}\n{t["body"]}\n'
        filepath.write_text(file_content, encoding='utf-8')
        written += 1
    
    # Write index
    index_path = Path(args.index)
    index_path.parent.mkdir(parents=True, exist_ok=True)
    index_content = generate_index(topics, str(output_dir))
    index_path.write_text(index_content, encoding='utf-8')
    
    print(f'\n✅ Split complete!')
    print(f'   📁 {written} topic files written to {output_dir}/')
    if skipped:
        print(f'   ⏭️  {skipped} files skipped (already exist)')
    print(f'   📑 Index written to {index_path}')
    print(f'   📖 Original MEMORY.md untouched')


if __name__ == '__main__':
    main()


path: scripts/verify.sh
content: #!/usr/bin/env bash
#
# BeastXA Memory Pro — Installation Verifier
#
set -euo pipefail

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

echo ""
echo "🔍 BeastXA Memory Pro — Verification"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

PASS=0
FAIL=0
WARN=0

check() {
    local label="$1"
    local condition="$2"
    if eval "$condition" > /dev/null 2>&1; then
        echo -e "   ${GREEN}✅${NC} $label"
        ((PASS++))
    else
        echo -e "   ${RED}❌${NC} $label"
        ((FAIL++))
    fi
}

warn() {
    local label="$1"
    local condition="$2"
    if eval "$condition" > /dev/null 2>&1; then
        echo -e "   ${GREEN}✅${NC} $label"
        ((PASS++))
    else
        echo -e "   ${YELLOW}⚠️${NC}  $label (optional)"
        ((WARN++))
    fi
}

echo "Prerequisites:"
check "Python 3 installed" "command -v python3"
check "OpenClaw installed" "command -v openclaw"
check "OpenClaw config exists" "test -f ~/.openclaw/openclaw.json"
echo ""

echo "Memory structure:"
check "memory/ directory exists" "test -d memory"
check "memory/topics/ directory exists" "test -d memory/topics"
check "memory/session-notes.md exists" "test -f memory/session-notes.md"
warn "MEMORY.md exists" "test -f MEMORY.md"
warn "memory/MEMORY-INDEX.md exists" "test -f memory/MEMORY-INDEX.md"
warn "Topic files exist" "ls memory/topics/*.md 2>/dev/null | head -1"
echo ""

echo "Configuration:"
check "memoryFlush enabled" "python3 -c \"
import json
with open('$HOME/.openclaw/openclaw.json') as f:
    c = json.load(f)
assert c.get('agents',{}).get('defaults',{}).get('compaction',{}).get('memoryFlush',{}).get('enabled') == True
\""
check "Compaction instructions set" "python3 -c \"
import json
with open('$HOME/.openclaw/openclaw.json') as f:
    c = json.load(f)
assert 'instructions' in c.get('agents',{}).get('defaults',{}).get('compaction',{})
\""
echo ""

echo "Cron jobs:"
warn "Daily cleanup cron" "openclaw cron list 2>/dev/null | grep -q 'Memory Pro.*Daily'"
warn "Weekly deep clean cron" "openclaw cron list 2>/dev/null | grep -q 'Memory Pro.*Weekly'"
echo ""

echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo -e "Results: ${GREEN}${PASS} passed${NC}, ${RED}${FAIL} failed${NC}, ${YELLOW}${WARN} warnings${NC}"

if [ "$FAIL" -eq 0 ]; then
    echo -e "${GREEN}🎉 All checks passed!${NC}"
else
    echo -e "${RED}⚠️  Some checks failed. Run install.sh to fix.${NC}"
fi
echo ""


path: templates/cron-prompts.md
content: # Cron Prompt Templates

Use these prompts when setting up maintenance crons manually.

## Daily Cleanup (recommended: 23:30)

```
You are a memory maintenance assistant. Tasks:
1. Read today's memory/YYYY-MM-DD.md (use today's date)
2. Extract key decisions, lessons, and rules
3. Append them to the appropriate memory/topics/*.md files
4. Do NOT delete any files or overwrite existing content
5. If nothing to organize, reply "No maintenance needed today."
Output: ✅ Daily cleanup: X topics updated
```

## Weekly Deep Clean (recommended: Sunday 23:00)

```
You are a memory maintenance assistant. Weekly deep clean:
1. Read all memory/topics/*.md files
2. Remove duplicate content across files
3. Merge related entries
4. Trim each file to under 100 lines (keep most recent/important)
5. Update memory/MEMORY-INDEX.md if topics changed
6. Do NOT delete any files or modify MEMORY.md
Output: ✅ Weekly cleanup: X files updated, Y duplicates removed
```

## Custom Cron Setup

```bash
# Daily cleanup
openclaw cron add \
  --name "Memory Pro — Daily Cleanup" \
  --cron "30 23 * * *" \
  --tz "Your/Timezone" \
  --timeout-seconds 120 \
  --message '<paste daily prompt above>'

# Weekly deep clean
openclaw cron add \
  --name "Memory Pro — Weekly Deep Clean" \
  --cron "0 23 * * 0" \
  --tz "Your/Timezone" \
  --timeout-seconds 180 \
  --message '<paste weekly prompt above>'
```


path: templates/memory-index.md
content: # Memory Index Template
_Auto-generated by split_memory.py_

| Topic | File | Lines |
|-------|------|-------|
| Example Topic | `topics/example.md` | 42 |

_Run `python3 scripts/split_memory.py` to generate this from your MEMORY.md_


path: templates/session-notes.md
content: # Session Notes Template
_Auto-maintained by BeastXA Memory Pro_
_Copy this to your workspace as memory/session-notes.md_

# Current State
_What are you currently working on? Update this before each compaction._

# Task Specification
_Core objectives — what does the user want to achieve?_

# Files and Functions
_Key files being worked with — paths, purposes, recent changes_

# Errors and Corrections
_Mistakes made and how they were fixed. Learn from these._

# Learnings
_Lessons learned — patterns, preferences, things to remember_

# Key Results
_Important outputs, achievements, milestones_

# Worklog
_Chronological log of work done in this session_


path: 产品方案.md
content: # 🧠 BeastXA Memory Pro — 产品方案

## 一句话定位
OpenClaw 记忆增强 Skill：让你的 AI 助手永远不断片，越用越聪明。

---

## 产品是什么

一个 OpenClaw Skill，安装后自动帮你的 AI 助手：
1. **结构化记忆** — 把杂乱的笔记自动整理成主题文件
2. **自动归档** — 每天自动整理、去重、归档，不用你管
3. **抗断片** — 对话压缩前自动保存关键信息，压缩后无缝恢复
4. **零依赖** — 纯本地运行，不需要任何外部 API 或服务

---

## 竞品分析

| 竞品 | 优点 | 缺点 | 我们的优势 |
|------|------|------|-----------|
| elite-longterm-memory | 功能全，评分高 | 复杂，需要配置多 | 一键安装，零配置 |
| memory-tiering | 分层概念好 | 只有分层没有搜索 | 搜索+分层+自动整理 |
| memory-setup | 教程清晰 | 只是配置指南，没有自动化 | 全自动，不用手动 |
| fluid-memory | 概念新 | 不成熟 | 经过实战验证 |

**我们的差异化：一键安装 + 全自动维护 + 纯本地零依赖 + 实战验证**

---

## 文件结构

```
beastxa-memory-pro/
├── SKILL.md                    # 技能说明（ClawHub 必须）
├── LICENSE                     # MIT-0 开源协议
├── README.md                   # GitHub 展示页
├── scripts/
│   ├── install.sh              # 一键安装脚本
│   ├── setup_memory.py         # 记忆结构初始化
│   ├── split_memory.py         # MEMORY.md 自动拆分
│   └── verify.sh               # 安装验证
├── templates/
│   ├── session-notes.md        # 会话笔记模板
│   ├── memory-index.md         # 索引模板
│   └── cron-prompts.md         # 自动整理 cron 提示词
└── docs/
    ├── quickstart.md           # 5分钟快速开始
    └── faq.md                  # 常见问题
```

---

## 安装流程（小白版）

### 方法一：一键安装（推荐）

```bash
# 第1步：安装 Skill
clawhub install beastxa-memory-pro

# 第2步：运行安装脚本
cd ~/.openclaw/skills/beastxa-memory-pro
bash scripts/install.sh
```

安装脚本会自动：
- ✅ 检测你的 OpenClaw 版本和配置
- ✅ 创建 memory/ 目录结构
- ✅ 生成 session-notes.md 模板
- ✅ 设置每日/每周自动整理 cron
- ✅ 验证一切正常

### 方法二：手动安装

如果你想自己控制每一步：

**第1步：创建记忆目录**
```bash
cd your-workspace/
mkdir -p memory/topics
```

**第2步：创建会话笔记模板**
在 `memory/session-notes.md` 里写入：
```markdown
# Session Notes
# Current State
_在这里写当前正在做什么_

# Task Specification
_在这里写核心任务_

# Errors and Corrections
_在这里记录踩过的坑_

# Worklog
_在这里记录工作流水_
```

**第3步：设置自动整理**
安装脚本会自动创建两个 cron 任务：
- 每天 23:30 — 日常整理（提取当天关键信息到主题文件）
- 每周日 23:00 — 深度整理（去重、合并、精简）

**第4步：验证**
```bash
ls memory/topics/
# 应该看到按主题分类的 .md 文件
ls memory/session-notes.md
# 应该看到会话笔记模板
```

---

## 使用方法

### 安装完就不用管了

Skill 安装后是全自动的：
- 每次对话快压缩时，自动保存关键信息到 `memory/YYYY-MM-DD.md`
- 每天 23:30 自动整理当天笔记到主题文件
- 每周日 23:00 深度整理（去重、合并、精简）

### 手动操作（可选）

**拆分已有的 MEMORY.md：**
```bash
python3 scripts/split_memory.py
# 自动把 MEMORY.md 按主题拆分到 memory/topics/
# 生成 memory/MEMORY-INDEX.md 索引
# 原文件不动，零风险
```

**搜索记忆：**
```bash
openclaw memory search "你想搜的关键词"
```

---

## 原理说明（给想了解的人）

### 为什么 AI 助手会"断片"？

AI 助手的对话窗口有大小限制（比如 200K tokens）。聊多了，早期的对话会被压缩或丢弃。这就是"断片"——你昨天跟它说的事，今天它不记得了。

### 我们怎么解决？

**三层记忆架构：**

```
┌─────────────────────────────────┐
│  Layer 1: 会话笔记              │  ← 当前对话的结构化摘要
│  (session-notes.md)             │     压缩前自动更新
├─────────────────────────────────┤
│  Layer 2: 每日日志              │  ← 每天的原始记录
│  (memory/YYYY-MM-DD.md)        │     自动追加，不覆盖
├─────────────────────────────────┤
│  Layer 3: 主题文件              │  ← 按主题分类的长期记忆
│  (memory/topics/*.md)           │     自动整理，去重合并
└─────────────────────────────────┘
```

全部存在本地文件里，纯 Markdown，不需要任何外部服务。

---

## 常见问题

**Q: 我的数据会发到外面吗？**
A: 不会。所有数据都存在本地 Markdown 文件里，不需要任何外部 API。

**Q: 安装后需要改代码吗？**
A: 不需要。运行安装脚本就行，全自动配置。

**Q: 支持哪些 OpenClaw 版本？**
A: 2026.3.x 及以上。

**Q: 我已经有 MEMORY.md 了，会被覆盖吗？**
A: 不会。拆分脚本只读取 MEMORY.md 生成主题文件，原文件完全不动。

**Q: 能和其他记忆 Skill 一起用吗？**
A: 可以。这个 Skill 不修改 OpenClaw 核心代码，只是文件层面的增强。

---

## 发布计划

### Phase 1：GitHub 开源（本周）
- 代码整理 + README + 安装脚本
- 发到 GitHub: `beastxa6-668/beastxa-memory-pro`
- 写博客教程发 wpclawai.com

### Phase 2：ClawHub 上架（本周）
- `clawhub publish` 发布
- 标签：memory, openclaw, vector-search, auto-organize

### Phase 3：引流（下周）
- X/Twitter 发帖
- OpenClaw Discord 社区分享
- 博客 SEO 优化

### Phase 4：迭代（持续）
- 收集用户反馈
- 加功能：多语言支持、自定义主题分类、团队共享记忆
- 考虑付费版（高级功能）

---

## 成本与收益预估

| 项目 | 数值 |
|------|------|
| 开发成本 | $0（代码已有） |
| 运营成本 | $0（GitHub + ClawHub 免费） |
| 时间投入 | 2-3 小时打包 + 1 小时写文档 |
| 预期下载 | 第一个月 100-500 |
| 变现方式 | 免费引流 → 付费高级版 / 咨询服务 |
| 品牌价值 | 在 OpenClaw 社区建立技术影响力 |


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