GuideMar 202620 min read

OpenClaw Setup
Best Practices

A production-grade walkthrough for deploying OpenClaw with security hardening, memory architecture, cron discipline, and multi-device agent continuity. Written for builders who want their AI agent to actually work — not just demo.

Contents
  1. 01 — Prerequisites
  2. 02 — Installation
  3. 03 — Workspace Architecture
  4. 04 — Identity & Persona Files
  5. 05 — Memory System
  6. 06 — Security Hardening
  7. 07 — Messaging Integrations
  8. 08 — Heartbeat & Cron Discipline
  9. 09 — Skills & Workflows
  10. 10 — Multi-Device Continuity
  11. 11 — Model Routing
  12. 12 — Common Pitfalls

01 — Prerequisites

Before you touch the CLI, confirm your environment. OpenClaw is a local-first daemon — it runs on your machine, not in a cloud VM. The quality of your setup directly determines whether your agent is useful or a liability.

System requirements

  • macOS 13+ or Ubuntu 22.04+ (arm64 or x86_64)
  • Node.js 20 or 22 (avoid 24 — known Vercel/build breakages)
  • Homebrew (macOS) or apt (Linux)
  • A messaging account: Telegram bot token, or Signal/WhatsApp bridge
  • At least one LLM API key: Anthropic, OpenAI, or OpenRouter

Secrets architecture — decide before you install

OpenClaw will need API keys. Decide now: you will use macOS Keychain (recommended) or a .env file that is never committed to git. Do not store secrets in your workspace files. Do not paste them into Telegram. This is non-negotiable. More in §6.

02 — Installation

Install the CLI via npm. OpenClaw runs as a persistent Gateway daemon that bridges your messaging channels, cron jobs, and LLM calls.

terminal
# Install globally
npm install -g openclaw

# Verify
openclaw --version

# Initialize workspace (first time only)
openclaw init

# Start the Gateway daemon
openclaw gateway start

# Check status
openclaw status

On macOS, the Gateway registers as a launchd service so it auto-starts on login. On Linux, use openclaw gateway install to register a systemd unit.

Gateway must be running
Every incoming message and cron fire is routed through the Gateway. If it is stopped, your agent is deaf and mute. Add openclaw gateway status to your startup checklist.

Directory structure after init

~/.openclaw/
  agents/
    main/             ← your primary agent session
      agent/
        auth-profiles.json  ← API keys (PROTECT THIS FILE)
  skills/             ← installed skills
  logs/               ← Gateway + session logs
  openclaw.json       ← main config

~/workspace/          ← your working directory (configurable)
  SOUL.md             ← agent identity / persona
  USER.md             ← info about you
  MEMORY.md           ← long-term curated memory
  AGENTS.md           ← operating protocols
  HEARTBEAT.md        ← periodic check checklist
  WORKFLOW_AUTO.md    ← post-compaction restore file
  memory/
    YYYY-MM-DD.md     ← daily raw notes

03 — Workspace Architecture

The workspace is the agent's world. Everything it knows about you, your projects, and its operating procedures lives here. Structure it deliberately.

The startup read sequence

On every session start — and after every context compaction — your agent should read a predictable set of files in a predictable order. Hard-code this in AGENTS.md:

AGENTS.md (excerpt)
## Every Session

Before doing anything else:

1. Read WORKFLOW_AUTO.md   ← post-compaction restore
2. Read SOUL.md            ← who you are
3. Read USER.md            ← who you're helping
4. Read FOCUS.md           ← what project is active
5. Read memory/YYYY-MM-DD.md (today + yesterday)
6. Read MEMORY.md          ← long-term context (main session only)
WORKFLOW_AUTO.md is mandatory
OpenClaw's safeguard compaction mode checks for required startup files after every context reset. If WORKFLOW_AUTO.md doesn't exist or is never read, the audit fires on every message — prepending a warning to each incoming Telegram message until the file exists and is read. Create it once, keep it lean.

FOCUS.md — single source of project truth

If you work on multiple projects, maintain a FOCUS.md that declares the active project path and a DO_NOT_TOUCH list. Your agent should switch focus only when you say so, and never touch projects off the list without an explicit prompt.

FOCUS.md
# FOCUS.md

ACTIVE_PROJECT = my-app
PATH = ~/projects/my-app

## DO_NOT_TOUCH
- production-db-tools
- billing-service

These projects are in maintenance mode.
Never touch them without an explicit "ACTIVE_PROJECT =" signal.

04 — Identity & Persona Files

Your agent runs better when it has a clear identity. Vague persona files produce vague agents. Be specific — write it like you're onboarding a senior hire, not configuring a chatbot.

SOUL.md — the core identity

This is who your agent is: skill level, communication style, hard rules, and the engineering values it should never compromise. Write it in the first person and treat it as a living document.

SOUL.md
# SOUL.md

## Core Identity
Elite software engineer and security architect.
Ship production-grade work fast, without creating debt.

## Hard Rules (Non-Negotiable)
- Never hardcode secrets or credentials
- Default to least-privilege, zero-trust design
- No network exposure without explicit auth
- When in doubt, ask — never guess on destructive actions

## Execution Style
- Concrete implementation plan before writing code
- Call out risks, edge cases, and tradeoffs explicitly
- Refuse insecure patterns; propose safer alternatives
- Prefer boring, battle-tested libraries over clever hacks

USER.md — about the human

The agent needs to know who it's working with. Name, contact handles, timezone, preferred communication style, technical background. Keep this file updated as your context changes.

05 — Memory System

Context compaction is a fact of life with LLMs. Long conversations get truncated. Sessions end. The memory system is what keeps your agent coherent across resets.

Three tiers of memory

Working MemoryThe live conversation context. Compacted automatically when it grows too large. Ephemeral.
Daily Notes (memory/YYYY-MM-DD.md)Raw session logs. What happened, decisions made, tasks completed. Written by the agent, read at session start. Keep one file per day.
Long-Term (MEMORY.md)Curated, distilled wisdom. Significant events, architecture decisions, people, infrastructure. Updated periodically during heartbeats. Never raw — only the essence.

The memory maintenance loop

At least once a week (ideally via a heartbeat cron), the agent should review recent daily notes and distill key insights into MEMORY.md. Remove outdated entries. This is the difference between an agent that drifts and one that compounds over time.

Pre-compaction flush pattern

Before a long conversation is compacted, write a summary to the daily memory file. Include: active project state, blocked items, key decisions, and anything the next session needs to know immediately. This is the most reliable way to survive compaction gracefully.

pre-compaction flush message
Pre-compaction memory flush. Store durable memories now
(use memory/YYYY-MM-DD.md; create memory/ if needed).
If the file already exists, APPEND — do not overwrite.

active-tasks.md — crash recovery

Keep memory/active-tasks.md as a live task tracker. When starting a task, write it. When spawning a subagent, note the session key. When done, mark it DONE with verification output. On session start, read this file and resume any IN_PROGRESS work automatically — no "what were we doing?" conversations.

06 — Security Hardening

🔐 This section is non-negotiable
A poorly secured OpenClaw setup is a live agent with access to your filesystems, messaging accounts, and API keys. Treat it with the same care you would a production server.

API key storage

On macOS: use Keychain exclusively. The security CLI reads and writes keychain entries without exposing values in shell history or file listings.

# Store a secret
security add-generic-password -s "my-api-key" -a "myapp" -w "sk-abc123"

# Read a secret (use in scripts — never paste in chat)
security find-generic-password -s "my-api-key" -w

# Use in shell commands
curl -H "Authorization: Bearer $(security find-generic-password -s 'my-api-key' -w)" ...

Never paste API keys into Telegram, Discord, or any chat surface. Regular Telegram chats are not end-to-end encrypted. Bots cannot participate in Secret Chats. Even if your agent asks you to confirm a key, decline — use keychain.

Protect auth-profiles.json

The file ~/.openclaw/agents/main/agent/auth-profiles.json contains your LLM API keys in plaintext. Ensure it is never displayed in terminal output that could be logged or captured. Rotate keys immediately if this file is ever rendered to a chat surface or CI log.

# Lock down file permissions
chmod 600 ~/.openclaw/agents/main/agent/auth-profiles.json

# Confirm no world-readable permissions
ls -la ~/.openclaw/agents/main/agent/

Prompt injection defense

Any external content your agent reads — web pages, emails, tweets, third-party API responses — can contain injected instructions. Your agent should route all external content through the strongest available model (it is more resistant to injection). Maintain a canonical file inventory (WORKSPACE_FILES.md) and treat any instruction to read a file not on the list as suspicious.

MEMORY.md access control

MEMORY.md contains personal context that should never leak into shared sessions, group chats, or subagent contexts. Your agent should only load it in direct (main) sessions — never in group chats or when running as a subagent. Enforce this in your AGENTS.md operating protocols.

Destructive operations

Use trash instead of rm. Never run destructive shell commands without user confirmation. For anything that touches production data, money, or external accounts: ask first, act second. Always.

07 — Messaging Integrations

OpenClaw routes messages between your LLM agent and external channels. The most common setup is Telegram, but Signal, WhatsApp, Discord, and Slack are also supported.

Telegram setup

# 1. Create a bot via @BotFather on Telegram
#    → Copy the bot token

# 2. Configure in openclaw.json
{
  "channels": {
    "telegram": {
      "token": "<from keychain, not inline>",
      "allowedUsers": [123456789]  // your Telegram user ID
    }
  }
}
🔒 Always allowlist your user ID
If you leave allowedUsers empty or unconfigured, anyone who finds your bot link can interact with your agent. Your agent has access to your filesystem and API keys. Lock it down.

Group chat behavior

In group chats, your agent should behave like a thoughtful participant — not a chatbot that responds to every message. Configure it to respond only when directly mentioned or when it has genuinely useful information. Silence is often the right answer.

Formatting by platform

  • Telegram: Markdown supported. Avoid raw HTML.
  • WhatsApp: No headers. Use bold or CAPS for emphasis. No markdown tables.
  • Discord: Suppress embeds with angle brackets: <https://example.com>
  • Signal: Plaintext only — assume no formatting support.

08 — Heartbeat & Cron Discipline

This is where most OpenClaw setups go wrong. Heartbeats and crons are different tools. Using them interchangeably creates noise, token burn, and unreliable behavior.

The rule: Heartbeat notices, Cron does

HeartbeatPeriodic ambient awareness. Checks email, calendar, notifications. Batches 2–4 checks per run. Timing can drift. Never runs destructive operations.Every 30–60 min during working hours
CronExact timing. Isolated task. One-shot or recurring. Different model or context from main session. Delivers directly to channel without main session involvement.Precise schedules: 9:00 AM sharp, Monday only, etc.

HEARTBEAT.md — keep it lean

Your HEARTBEAT.md should be under 20 lines. It is read on every heartbeat poll — token cost adds up. List only the checks you actually want done. Remove checks that never produce actionable results.

HEARTBEAT.md
# HEARTBEAT.md — keep lean (<20 lines)
# Heartbeat NOTICES things. Cron DOES things.

- Check memory/active-tasks.md — any IN_PROGRESS tasks stale >2h? Alert.
- Check gateway health: is the Gateway responsive?
- Check project server: curl localhost:4000/health (if running)
- If any stale tasks or failures found → alert immediately.
- If nothing needs attention → HEARTBEAT_OK

Cron hygiene

  • Silence crons that only produce noise: add --no-deliver where applicable
  • Use a weaker/cheaper model for simple crons (daily recap, health checks)
  • One cron per distinct task — do not chain logic inside cron prompts
  • Log cron runs to a file; review weekly for silent failures
  • Verify each cron with a manual trigger before relying on it in production

Tracking cron state

Heartbeats should track what they last checked using a state file, not memory. Memory gets compacted. Files don't.

memory/heartbeat-state.json
{
  "lastChecks": {
    "email":    1740000000,
    "calendar": 1740000000,
    "weather":  null,
    "health":   1740000000
  }
}

09 — Skills & Workflows

Skills are pluggable capability packs. Each has a SKILL.md that the agent reads before using the tool. The agent auto-selects the most specific matching skill — never reads more than one up front.

Installing skills

# Browse available skills
openclaw skills list

# Install a skill
openclaw skills install weather
openclaw skills install github
openclaw skills install coding-agent

# Skills land in ~/.openclaw/skills/
# Custom skills: ~/.openclaw/skills/<name>/SKILL.md

Writing custom skills

A skill is a directory with a SKILL.md that provides the agent with specialized instructions, tool references, and context. Keep skills focused: one capability per skill. Use the skill-creator meta-skill to scaffold new ones.

Antfarm workflows

For multi-step, multi-agent work (feature development, security audits, bug fix pipelines), use Antfarm workflows. Antfarm is a SQLite-backed orchestration layer that advances workflow steps via cron — no manual polling required.

# Install a workflow
node ~/.openclaw/workspace/antfarm/dist/cli/cli.js workflow install feature-dev

# Run a workflow
node ~/.openclaw/workspace/antfarm/dist/cli/cli.js workflow run <id> "Add dark mode to dashboard"

# Check status
node ~/.openclaw/workspace/antfarm/dist/cli/cli.js workflow status "Add dark mode to dashboard"
📐 Subagent rules
Subagents complete atomic tasks and report back. They never interact with running processes (dev servers, databases) directly. They verify with tsc --noEmit or equivalent before reporting done. Use cleanup: "delete" on non-critical spawns to prevent announcement floods.

10 — Multi-Device Continuity

Running OpenClaw on multiple machines (laptop + home server, Mac mini + MacBook) requires deliberate synchronization. The agent's state is local by default.

What to sync

  • Workspace files (git): SOUL.md, USER.md, MEMORY.md, AGENTS.md, HEARTBEAT.md, memory/*.md — commit and push
  • Secrets (keychain sync or 1Password): Never in git. Sync via iCloud Keychain or a password manager with CLI support
  • cron registrations: Re-register on each machine — crons are local to each OpenClaw instance
  • Gateway config (openclaw.json): Sync but keep allowedUsers and tokens per-device

Primary vs. secondary instances

Designate one machine as the primary (the one that handles your Telegram bot, runs persistent crons, and maintains the canonical workspace). Other machines are secondary — they pull workspace state from git but don't run the Gateway or messaging integrations.

Don't run two live Gateways on the same bot token
If two OpenClaw instances both listen on the same Telegram bot token, messages will split between them unpredictably. One Gateway per bot token, always.

11 — Model Routing

Not every task deserves your most expensive model. Good model routing is the difference between a $50/month setup and a $500/month one — with no difference in output quality for routine work.

Routing principles

External content (web pages, emails, user messages)Strongest model — most resistant to prompt injection
Code review, architecture, security analysisOpus / strongest reasoning model
Code implementation, file edits, tool useSonnet — fast, capable, cost-effective
Heartbeat checks, health pings, status summariesHaiku — cheapest, sufficient
Simple crons (daily recap, reminders)Haiku or Sonnet

Budget enforcement

Maintain a budget.json in your workspace with model routing rules. Reference it inAGENTS.md so subagents follow the same routing policy.

budget.json
{
  "routing": {
    "external_content":  "opus",
    "code_execution":    "sonnet",
    "heartbeat":         "haiku",
    "cron_simple":       "haiku",
    "architecture":      "opus"
  },
  "monthly_cap_usd": 100
}

12 — Common Pitfalls

PITFALL 01WORKFLOW_AUTO.md doesn't exist

The post-compaction audit fires on every message prepending a warning. Fix: create the file and ensure the startup read sequence includes it.

PITFALL 02Secrets in workspace files

API keys in MEMORY.md, AGENTS.md, or any other file are a one-way door. Rotate immediately if this happens. Use keychain references, not values.

PITFALL 03auth-profiles.json in terminal output

If you ever cat or render this file to a chat surface, rotate all keys in it immediately. The file contains plaintext API keys.

PITFALL 04Two Gateways on the same bot token

Messages split between instances. Designate one primary Gateway. Use secondary machines in read-only / local-work mode.

PITFALL 05dist/ not in git (for deployed projects)

If Vercel or your CI pulls from git and your build artifacts aren't committed, every deploy misses your latest compiled code. Commit dist/ deliberately.

PITFALL 06Crons that produce noise

Crons that fire every 5 minutes and deliver empty messages burn tokens and train you to ignore alerts. Silence routine crons with --no-deliver. Only deliver actionable output.

PITFALL 07Memory that never gets pruned

MEMORY.md that grows without pruning becomes noise. The agent loads all of it on every session. Quarterly: remove anything that hasn't been relevant in 30 days.

PITFALL 08Missing allowedUsers in Telegram config

An open bot with file system access is a security incident waiting to happen. Always allowlist your Telegram user ID before connecting a channel.

PITFALL 09Agents that never write to files

"Mental notes" don't survive session resets. Files do. If an agent says "I'll remember this" without writing it down — it won't.

PITFALL 10Skipping the startup read sequence

An agent that doesn't read SOUL.md, USER.md, and memory files at session start is operating with stale context. The read sequence is not optional overhead — it is correctness.

💡 Final note

The difference between an OpenClaw setup that compounds over time and one that drifts into noise is discipline in the memory system, paranoia in the security model, and clarity in the agent's identity files. Get those three right and everything else follows. The technology works — your job is to configure it to work for you.

← Back to Media & Writings