afrexai-openclaw-masteryExpert system for designing, deploying, optimizing, and scaling autonomous AI agents on OpenClaw with multi-agent support and robust memory management.
Install via ClawdBot CLI:
clawdbot install 1kalin/afrexai-openclaw-masteryBuilt by AfrexAI ā the team that runs 9+ production agents 24/7 on OpenClaw.
You are an expert OpenClaw platform engineer. Follow this complete system to design, deploy, optimize, and scale autonomous AI agents on OpenClaw.
Before building, assess what you need:
| Complexity | Examples | Channels | Crons | Memory | Skills |
|-----------|---------|----------|-------|--------|--------|
| Simple | Personal assistant, reminder bot | 1 | 0-2 | Basic MEMORY.md | 2-5 |
| Standard | Business ops, content creator | 1-2 | 3-5 | Daily + long-term | 5-10 |
| Advanced | Multi-agent swarm, trading system | 3+ | 5-10 | Full system + databases | 10-20 |
| Enterprise | Full business automation | 5+ | 10+ | Multi-DB + RAG | 20+ |
readiness_check:
hardware:
- [ ] Machine with 4GB+ RAM (8GB recommended)
- [ ] Stable internet connection
- [ ] Node.js v20+ installed
- [ ] Git installed
accounts:
- [ ] Anthropic API key (primary model)
- [ ] At least one channel configured (Telegram recommended for starting)
- [ ] Optional: OpenAI key (for embeddings/fallback)
planning:
- [ ] Agent purpose defined (1 sentence)
- [ ] Target audience identified
- [ ] Success metrics defined
- [ ] Budget estimated (model costs)
# Install OpenClaw
npm install -g openclaw
# Initialize workspace
openclaw init
# Configure (interactive)
openclaw setup
# Start the gateway
openclaw gateway start
# Verify
openclaw status
OpenClaw config lives at ~/.openclaw/config.yaml. Key sections:
# Essential config structure
version: 1
gateway:
port: 3578 # Default port
heartbeat:
intervalMs: 1800000 # 30 min default
prompt: "..." # Heartbeat instruction
models:
default: anthropic/claude-sonnet-4-20250514 # Cost-effective default
# Override per-session or per-agent
channels:
telegram:
botToken: "..." # From @BotFather
# discord, slack, signal, whatsapp, imessage, webchat
agents: {} # Multi-agent configs
bindings: [] # Channel-to-agent routing
| Model | Best For | Cost | Speed | Thinking |
|-------|---------|------|-------|----------|
| claude-sonnet-4-20250514 | Daily ops, chat, most tasks | $$ | Fast | Good |
| claude-opus-4-6 | Complex reasoning, strategy | $$$$ | Slower | Excellent |
| gpt-4o | Vision tasks, alternatives | $$$ | Fast | Good |
| claude-haiku | High-volume, simple tasks | $ | Fastest | Basic |
Cost optimization rule: Use Sonnet as default, Opus for strategy/complex tasks, Haiku for high-frequency simple operations.
# Required
ANTHROPIC_API_KEY=sk-ant-...
# Optional but recommended
OPENAI_API_KEY=sk-... # Fallback model
BRAVE_API_KEY=... # Web search
Your workspace (~/.openclaw/workspace/) IS the agent's persistent memory and personality. Design it carefully.
workspace/
āāā SOUL.md # WHO the agent is (personality, values, voice)
āāā AGENTS.md # HOW it operates (rules, workflows, protocols)
āāā IDENTITY.md # Quick identity card (name, role, emoji)
āāā USER.md # WHO it serves (user context, preferences)
āāā MEMORY.md # Long-term curated memory
āāā HEARTBEAT.md # Proactive check instructions
āāā TOOLS.md # Local tool notes, API keys location
āāā ACTIVE-CONTEXT.md # Current priorities, hot items
āāā memory/ # Daily logs
ā āāā 2026-02-19.md
ā āāā heartbeat-state.json
āāā skills/ # Installed ClawHub skills
āāā scripts/ # Custom automation scripts
āāā reference/ # Knowledge base documents
āāā projects/ # Project-specific work
āāā docs/ # OpenClaw documentation
This is the most important file. It defines WHO your agent is.
Template:
# SOUL.md ā [Agent Name]
## Prime Directive
[One sentence: what is this agent's primary purpose?]
## Core Truths
- [Personality trait 1 ā be specific, not generic]
- [Personality trait 2]
- [Communication style]
- [Decision-making philosophy]
## Anti-Patterns
Never do these:
- [Specific behavior to avoid]
- [Another anti-pattern]
## Relationship With Operator
- [How formal/casual]
- [When to ask vs act]
- [Escalation rules]
## Boundaries
- [What's off-limits]
- [Privacy rules]
- [External action rules]
## Vibe
[2-3 sentences describing the overall feel]
Quality Checklist (score 0-10 each):
Target: 40+ out of 50 before deploying.
# AGENTS.md
## Session Startup
1. Read SOUL.md
2. Read USER.md
3. Read memory/YYYY-MM-DD.md (today + yesterday)
4. If main session: Read MEMORY.md
## Decision Framework
[Your PIV, OODA, or custom loop]
## Daily Rhythm
- Morning: [tasks]
- Midday: [tasks]
- Evening: [tasks]
## Memory Protocol
- Daily notes: memory/YYYY-MM-DD.md
- Long-term: MEMORY.md (curated)
- Write it down ā no "mental notes"
## Safety Rules
- [Specific to your use case]
## External vs Internal Actions
- Safe to do freely: [list]
- Ask first: [list]
# USER.md
## Identity
- Name, timezone, language preferences
- Communication style preferences
## Professional Context
- Role, company, industry
- Current priorities
- Technical level
## Preferences
- How they like to receive information
- Pet peeves
- Activation phrases
Three-Layer System:
memory/YYYY-MM-DD.md) ā Raw event logs, decisions, outcomesMEMORY.md) ā Curated insights, lessons, persistent contextACTIVE-CONTEXT.md) ā Current priorities, hot items, WIPMemory Maintenance Protocol:
| Signal | Single Agent | Multi-Agent |
|--------|-------------|-------------|
| Tasks are related | ā | |
| Different personas needed | | ā |
| Different channels/audiences | | ā |
| Workload exceeds context window | | ā |
| Security isolation needed | | ā |
| Different model requirements | | ā |
channels:
telegram:
accounts:
main:
botToken: "TOKEN_1"
trader:
botToken: "TOKEN_2"
fitness:
botToken: "TOKEN_3"
agents:
trader:
model: anthropic/claude-sonnet-4-20250514
workspace: agents/trader
fitness:
model: anthropic/claude-sonnet-4-20250514
workspace: agents/fitness
bindings:
- pattern:
channel: telegram
account: trader
agent: trader
- pattern:
channel: telegram
account: fitness
agent: fitness
Each agent gets its own workspace directory:
workspace/
āāā agents/
ā āāā trader/
ā ā āāā SOUL.md # Trader personality
ā ā āāā AGENTS.md # Trading rules
ā ā āāā memory/
ā āāā fitness/
ā āāā SOUL.md # Coach personality
ā āāā AGENTS.md # Fitness protocols
ā āāā memory/
# From main agent, delegate to sub-agent:
sessions_spawn(task="Analyze BTC 4h chart", agentId="trader")
# Send message to another session:
sessions_send(sessionKey="...", message="Update: new client signed")
Rules:
sessions_spawn for fire-and-forget taskssessions_send for ongoing communication# 1. System Event (main session) ā inject text as system message
payload:
kind: systemEvent
text: "Check for new emails and report"
# 2. Agent Turn (isolated session) ā full agent run
payload:
kind: agentTurn
message: "Run morning briefing: check email, calendar, weather"
model: anthropic/claude-sonnet-4-20250514
timeoutSeconds: 300
# One-shot at specific time
schedule:
kind: at
at: "2026-02-20T09:00:00Z"
# Recurring interval
schedule:
kind: every
everyMs: 3600000 # Every hour
# Cron expression
schedule:
kind: cron
expr: "0 8 * * 1-5" # 8 AM weekdays
tz: "Europe/London"
Morning Briefing (Daily, 8:00 AM):
name: "Morning Ops"
schedule:
kind: cron
expr: "0 8 * * *"
tz: "America/New_York"
sessionTarget: isolated
payload:
kind: agentTurn
message: "Morning briefing: check email inbox for urgent items, review calendar for today and tomorrow, check weather, summarize to operator via Telegram"
timeoutSeconds: 300
delivery:
mode: announce
Evening Summary (Daily, 8:00 PM):
name: "Evening Ops"
schedule:
kind: cron
expr: "0 20 * * *"
tz: "America/New_York"
sessionTarget: isolated
payload:
kind: agentTurn
message: "Evening summary: what was accomplished today, any pending items, tomorrow's priorities"
timeoutSeconds: 300
delivery:
mode: announce
Weekly Strategy Review (Monday, 9:00 AM):
name: "Weekly Strategy"
schedule:
kind: cron
expr: "0 9 * * 1"
tz: "America/New_York"
sessionTarget: isolated
payload:
kind: agentTurn
message: "Weekly review: analyze past week performance, update strategy, set 3 priorities for this week"
timeoutSeconds: 600
delivery:
mode: announce
| Use Heartbeat When | Use Cron When |
|--------------------|---------------|
| Multiple checks can batch | Exact timing matters |
| Need recent conversation context | Task needs isolation |
| Timing can drift (±15 min OK) | Different model needed |
| Want to reduce API calls | One-shot reminders |
| Interactive follow-up likely | Output goes to specific channel |
# HEARTBEAT.md
## Priority 1: Critical Alerts
- [Time-sensitive checks ā positions, payments, security]
## Priority 2: Inbox Triage
- Check email for urgent items
- Check mentions/notifications
## Priority 3: Proactive Work
- Update documentation
- Review memory files
- Background research
## Quiet Hours
- 23:00-08:00: Only critical alerts
- If nothing to report: HEARTBEAT_OK
## Token Guard
- If usage seems high, note it
- Don't re-read large files unnecessarily
openclaw gateway startMulti-bot pattern: See Phase 4 config above.
Tips:
channels:
discord:
botToken: "..."
guildId: "..."
Tips:
<> to suppress embedschannels:
slack:
botToken: "xoxb-..."
appToken: "xapp-..."
| Platform | Tables | Headers | Links | Max Message |
|----------|--------|---------|-------|-------------|
| Telegram | ā | ā | ā | 4096 chars |
| Discord | ā | ā
| | 2000 chars |
| Slack | ā | ā | ā mrkdwn | 40000 chars |
| WhatsApp | ā | ā bold/CAPS | ā | 65536 chars |
# Search for skills
clawhub search "email marketing"
# Install a skill
clawhub install afrexai-email-marketing-engine
# Update all skills
clawhub update --all
# List installed
clawhub list
Build vs Install Decision:
Quality Signals:
my-skill/
āāā SKILL.md # Main instructions (required)
āāā README.md # Installation guide + description
āāā references/ # Supporting docs
āāā scripts/ # Automation scripts
SKILL.md Best Practices:
# ā NEVER hardcode secrets
ANTHROPIC_API_KEY=sk-ant-abc123 # In config files
export API_KEY=secret # In .bashrc committed to git
# ā NEVER log secrets
echo "Token is: $MY_TOKEN" # In scripts
console.log(apiKey) # In code
# Install
brew install 1password-cli # macOS
# or: https://1password.com/downloads/command-line
# Read a secret at runtime
op read "op://VaultName/ItemName/FieldName"
# In scripts
API_KEY=$(op read "op://MyVault/Brave Search/api_key")
# Store in ~/.openclaw/vault/ (gitignored)
echo "export MY_KEY=value" > ~/.openclaw/vault/my-service.env
# Source in scripts
source ~/.openclaw/vault/my-service.env
trash > rm ā recoverable beats gone forever| Strategy | Savings | Implementation |
|----------|---------|----------------|
| Use Haiku for simple tasks | 90%+ | Model override per cron |
| Limit heartbeat frequency | 50-70% | Increase intervalMs |
| Spawn sub-agents | Variable | Isolate heavy work |
| Trim MEMORY.md regularly | 20-30% | Weekly maintenance |
| Use file offsets | 10-20% | Read only what you need |
| HEARTBEAT_OK when nothing to do | 80%+ per beat | Check before acting |
sessions_spawn for independent heavy work# Check status
openclaw status
# View session usage
# In chat: /status
Track in memory/token-costs.md:
## 2026-02-19
- Morning briefing: ~$0.05
- Heartbeats (6x): ~$0.15
- Main session: ~$0.30
- Sub-agents: ~$0.10
- **Daily total: ~$0.60**
These patterns come from running 9+ agents in production 24/7.
Don't blast every event to the user. Route through tiers:
Default to Tier 3. Promote only with clear justification.
For truly autonomous agents:
## In AGENTS.md:
OPERATOR IS OUT OF THE LOOP ā run EVERYTHING autonomously.
Only message when: š° sale, š morning/evening briefing, šØ critical break.
## Weekly (during heartbeat):
1. Read recent memory/YYYY-MM-DD.md files
2. Distill significant events to MEMORY.md
3. Remove outdated info from MEMORY.md
4. Clean up temp files
## In HEARTBEAT.md:
- If a task failed, note what went wrong
- If you spot a repeated pattern, create a script
- Weekly: review AGENTS.md ā still accurate? Trim bloat.
- Build capabilities over time
One agent, multiple surfaces:
Use cron jobs to automate content distribution:
| Problem | Likely Cause | Fix |
|---------|-------------|-----|
| Agent not responding | Gateway not running | openclaw gateway start |
| "Rate limit" errors | Too many API calls | Increase heartbeat interval, use cheaper model |
| Agent forgets context | Session expired/new | Check MEMORY.md is being maintained |
| Wrong personality | SOUL.md not loaded | Ensure session startup reads SOUL.md first |
| Telegram not connecting | Invalid bot token | Re-check token from @BotFather |
| Cron not firing | Wrong timezone | Verify tz field in schedule |
| Agent too chatty in groups | No silence rules | Add "when to stay silent" to AGENTS.md |
| High token costs | Large files re-read | Use offsets, trim MEMORY.md, spawn sub-agents |
| Git push timeout | Network/auth issue | Use GitHub API instead of git CLI |
| 1Password hanging | Keychain issue on macOS | Use service account token, not desktop app |
Run periodically:
# 1. Gateway running?
openclaw status
# 2. Config valid?
openclaw gateway config --validate
# 3. Workspace files exist?
ls ~/.openclaw/workspace/{SOUL,AGENTS,IDENTITY,USER,MEMORY}.md
# 4. Memory not bloated?
wc -c ~/.openclaw/workspace/MEMORY.md # Should be <50KB
# 5. Skills up to date?
clawhub list
| Dimension | Weight | Score 0-10 |
|-----------|--------|-----------|
| Personality (SOUL.md depth) | 15% | |
| Memory System (3-layer) | 15% | |
| Automation (crons + heartbeat) | 15% | |
| Security (secrets management) | 10% | |
| Multi-Channel | 10% | |
| Skills Ecosystem | 10% | |
| Cost Optimization | 10% | |
| Self-Improvement | 10% | |
| Documentation | 5% | |
Scoring: 0-30 = Beginner, 31-50 = Intermediate, 51-70 = Advanced, 71-90 = Expert, 91-100 = Master
This skill gives you the complete OpenClaw operating system. Want industry-specific agent configurations with pre-built workflows?
AfrexAI Context Packs ($47 each):
Browse all: https://afrexai-cto.github.io/context-packs/
afrexai-agent-engineering ā Build & manage multi-agent systemsafrexai-prompt-engineering ā Master prompt designafrexai-vibe-coding ā AI-assisted development masteryafrexai-productivity-system ā Personal operating systemafrexai-technical-seo ā Complete SEO audit systemInstall any: clawhub install afrexai-[name]
Built with š by AfrexAI ā Autonomous intelligence for modern business.
https://afrexai-cto.github.io/context-packs/
Generated Feb 24, 2026
A simple agent for individuals to manage daily tasks, reminders, and personal organization via a single channel like Telegram. It uses basic memory and a few skills to automate scheduling and note-taking, ideal for beginners.
A standard agent for small businesses to handle customer inquiries, content scheduling, and internal notifications across 1-2 channels. It integrates skills for social media and CRM, with daily memory for tracking operations.
An advanced setup where multiple agents collaborate to manage customer support, sales, and technical queries across platforms like Discord and Slack. It uses full memory systems and databases to scale operations efficiently.
An enterprise-level multi-agent swarm for automating complex business processes such as inventory management, data analysis, and cross-department coordination. It leverages RAG, multiple databases, and 20+ skills for full automation.
A standard agent for creators and marketers to generate content, schedule posts, and analyze engagement across social media channels. It uses 5-10 skills and daily memory to optimize productivity and output.
Offer managed OpenClaw agents to businesses on a monthly subscription, providing setup, maintenance, and optimization. Revenue comes from tiered plans based on agent complexity and support levels.
Provide bespoke agent design, deployment, and training services for clients needing tailored automation solutions. Charge project-based or hourly rates for architecture assessment and workspace customization.
Sell pre-built skills, templates, and training courses for OpenClaw users to enhance their agents. Generate revenue through one-time sales, subscriptions for premium content, and workshops.
š¬ Integration Tip
Start with a simple agent on Telegram to test workflows, then scale by adding channels and skills based on the complexity matrix to avoid over-engineering.
Captures learnings, errors, and corrections to enable continuous improvement. Use when: (1) A command or operation fails unexpectedly, (2) User corrects Clau...
Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
Search and analyze your own session logs (older/parent conversations) using jq.
Typed knowledge graph for structured agent memory and composable skills. Use when creating/querying entities (Person, Project, Task, Event, Document), linking related objects, enforcing constraints, planning multi-step actions as graph transformations, or when skills need to share state. Trigger on "remember", "what do I know about", "link X to Y", "show dependencies", entity CRUD, or cross-skill data access.
Ultimate AI agent memory system for Cursor, Claude, ChatGPT & Copilot. WAL protocol + vector search + git-notes + cloud backup. Never lose context again. Vibe-coding ready.
Headless browser automation CLI optimized for AI agents with accessibility tree snapshots and ref-based element selection