Skip to content

Instantly share code, notes, and snippets.

@potomak
Last active March 27, 2026 13:49
Show Gist options
  • Select an option

  • Save potomak/ce2dfa068750fff04dd55b0609f77764 to your computer and use it in GitHub Desktop.

Select an option

Save potomak/ce2dfa068750fff04dd55b0609f77764 to your computer and use it in GitHub Desktop.
Claude Code Agent Playbook — how to bootstrap autonomous agents with Claude Code

Claude Code Agent Playbook

A distilled guide for bootstrapping autonomous agents on top of Claude Code.

TL;DR: An agent is a directory with a CLAUDE.md that gives Claude a role, a startup/shutdown ritual, and a map of files and skills. The rest is just files.


Table of Contents

  1. Philosophy
  2. Standard File Structure
  3. CLAUDE.md — The Agent's Brain
  4. Memory System
  5. Skills
  6. Data Files
  7. Permissions
  8. Session Ritual Pattern
  9. Agent Type Patterns
  10. Discord Bridge
  11. Bootstrap Checklist
  12. References

Philosophy

A Claude Code agent is not an app — it's a working directory with context. Claude reads CLAUDE.md when you open a session, picks up its role, loads relevant files, and starts acting within that role.

The key insight: Claude already knows how to do most things. The agent's job is to give it:

  • A clear role and personality
  • A ritual for loading and saving state
  • A map of where information lives
  • Constraints on what it can and cannot do

Keep it simple. Markdown files beat databases. Rituals beat code. Files you can read and edit yourself beat black boxes.

When to build an agent:

  • You have a persistent domain (home, business, project) with ongoing state
  • You interact with it repeatedly over time, not just once
  • There's information worth remembering across sessions
  • You want Claude to act within a role, not just answer questions

Standard File Structure

project-root/
├── CLAUDE.md                     # Required. The agent's role, rituals, and map.
├── README.md                     # Optional. Human-facing intro.
├── .claude/
│   └── settings.local.json       # Project-level permissions whitelist
├── memory/
│   ├── MEMORY.md                 # Required. Auto-loaded index of memory files.
│   └── *.md                      # Individual memory files (profiles, facts, etc.)
├── data/
│   └── *.md                      # Domain data: inventory, tasks, lists, etc.
├── skills/
│   └── <skill-name>/
│       └── SKILL.md              # One file per skill, invoked via slash command
└── config/
    └── *.json                    # Structured config (optional, for machine-readable data)

For business/autonomous agents, add:

├── agents/
│   └── <role>/
│       └── SKILL.md              # Subagent role definitions
├── scripts/                      # Automation scripts (Python, shell)
├── docs/                         # Supporting documentation
└── JOURNAL.md                    # Session-by-session operational log

CLAUDE.md — The Agent's Brain

CLAUDE.md is the only file Claude Code automatically reads at session start. Everything else must be explicitly referenced from here. This is your most important file.

Required Sections

1. Role & Persona

Who is this agent? Give it a name, a clear role, and a tone. Be specific — vague instructions produce vague behavior.

# Maya — Personal Assistant

You are Maya, a personal assistant helping manage day-to-day tasks, notes, and projects.
Organized, practical, and proactive. Keep responses concise and action-oriented.
# Ops Agent — E-Commerce Store

You are the operations manager for an independent e-commerce store.
The human owner reviews and approves major decisions; you handle everything else.

2. Context / The World

Who are the key people or entities? What is the domain? What does the agent need to understand about its environment?

## The Team
- **Alex** — Owner. Makes final calls on budget and strategy.
- **Jordan** — Operations. Day-to-day store management.
- **The Store** — Sells handmade goods via Shopify + Etsy.

3. Startup Ritual

The ordered list of things Claude must do at the start of every session. This is how you achieve state continuity across sessions.

## On Every Session Start
1. Read `memory/MEMORY.md` — load persistent context
2. Read `data/tasks.md` — know what's pending
3. Check `data/status.md` — note current project state
4. Greet the user, surfacing anything urgent or time-sensitive

Keep it short (3–6 steps). Everything in the startup ritual should be fast to read.

4. Shutdown Ritual

The ordered list of things Claude must do before ending a session. This is how state is preserved.

## Before Ending Every Session (Mandatory)
1. Update any data files that changed during the session
2. Update memory files if new facts were learned
3. Git commit: `git add -A && git commit -m "session: <summary>"`

For business agents, add a JOURNAL.md entry as a step — it creates an audit trail of decisions.

5. Skill Map

A table or list of available skills and how to invoke them.

## Skills
- `/review` — Weekly review of status, tasks, and priorities → `skills/review/SKILL.md`
- `/plan` — Plan a project or sprint → `skills/planning/SKILL.md`
- `/report` — Generate a status report → `skills/reporting/SKILL.md`

6. Data File Index

A reference table of all important files and what they contain.

## Data Files
| File | Purpose |
|---|---|
| `data/tasks.md` | Active task list |
| `data/status.md` | Current project / business status |
| `data/notes.md` | Scratch pad and reference notes |

7. Hard Rules

Non-negotiable constraints. Keep this list short — if everything is a rule, nothing is.

## Hard Rules
- Never commit credentials or API keys to the repo.
- Flag to the owner before any commitment over $500.
- Never delete data files — archive instead.

Memory System

The memory system provides cross-session persistence. It's a folder of markdown files indexed by a single MEMORY.md that Claude loads at startup.

Structure

memory/
├── MEMORY.md           # Index only — loaded automatically, points to other files
├── people.md           # Who the key people are and their roles
├── preferences.md      # Preferences, working styles, constraints
└── context.md          # Background on the domain or project

MEMORY.md (Index)

Keep this file short — it's a table of contents, not content. Claude reads it at startup to know what memory files exist and what's in them.

# Memory Index

- `memory/people.md` — Key people, roles, and contact info
- `memory/preferences.md` — Working preferences and constraints
- `memory/context.md` — Domain background and history

## Quick Facts (Always Relevant)
- Weekly sync every Monday at 10am
- Budget decisions require owner approval above $500
- Primary communication channel is Slack

Memory File Design

Each memory file covers one topic:

# People
_Key contacts and their roles._

## Alex (Owner)
- Final decision authority on budget and strategy
- Prefers async updates over meetings
- Available Mon–Thu

## Jordan (Operations)
- Day-to-day point of contact
- Handles supplier relationships

What Goes in Memory vs. Data Files

Memory Data
Who people are, their roles and preferences Current state: task list, inventory, pipeline
Stable knowledge that changes rarely Operational data that changes every session
Domain background, key decisions Active projects, current metrics
Platform IDs, credentials location, strategy Reports, logs, current queue

Skills

Skills are specialized modes for complex tasks. They live in skills/<name>/SKILL.md (or agents/<role>/SKILL.md for business agents) and are invoked via slash commands.

When to Create a Skill

Create a skill when a task:

  • Has a multi-step process worth documenting
  • Has domain-specific rules or conventions
  • Will be invoked repeatedly
  • Would clutter CLAUDE.md if included inline

Skill File Structure (SKILL.md)

# Skill: [Name]

Invoked with `/skill-name`

Brief description of when to use this skill.

---

## What This Skill Does
1. Step one
2. Step two
3. Step three

## Domain Rules
- Rule 1
- Rule 2

## Process Detail
(step-by-step guide for the most common operations)

## End of Session
What to update/save after using this skill.

Example Skills

Personal assistant / productivity agent:

  • /review — weekly review: what's done, what's pending, what to prioritize
  • /plan — break down a goal into tasks and schedule them
  • /capture — quickly log notes, tasks, or ideas into the right file

Business / e-commerce agent:

  • agents/content/ — copywriting, product descriptions, brand voice
  • agents/marketing/ — campaign setup, performance review, budgets
  • agents/ops/ — store operations, order management, fulfillment
  • agents/design/ — asset creation specs, naming conventions

Data Files

Data files hold the agent's operational state — things that change every session.

Design Principles

Human-readable first. You should be able to open any file and understand it without Claude. Use markdown tables, checklists, and headers.

No databases. Markdown files are easier to read, diff in git, and edit manually when needed. A table in a .md file is almost always sufficient.

One concept per file. Don't mix task lists with status updates; keep them separate.

Date-stamped. Always include a "Last updated" line at the top so you know when the data is from.

Common Data File Patterns

Task list:

# Tasks
_Last updated: 2026-03-19_
Priority: 🔴 Urgent | 🟡 This week | 🟢 When possible | ✅ Done

| Priority | Task | Owner | Notes |
|---|---|---|---|
| 🔴 | Fix checkout bug | Jordan | Reported by 3 customers |
| 🟡 | Write Q2 campaign brief | Alex | Due before April |
| 🟢 | Update supplier list | Jordan | Not urgent |

## Done ✅
| Date | Task |
|---|---|
| 2026-03-18 | Publish new product listings |

Status / dashboard:

# Status
_Last updated: 2026-03-19_

## Current Sprint
Goal: Launch spring collection by March 28

## Key Metrics
- Orders this week: 42
- Revenue MTD: $3,840
- Open support tickets: 3

## Blockers
- Supplier hasn't confirmed stock for SKU-004

Inventory / stock:

# Inventory
_Last updated: 2026-03-19_

| SKU | Product | Stock | Reorder At | Notes |
|---|---|---|---|---|
| SKU-001 | Blue Widget | 48 | 10 | |
| SKU-002 | Red Widget | 7 | 10 | Reorder now |
| SKU-003 | Green Widget | 0 | 10 | Out of stock |

## Needs Reordering
- SKU-002 (7 left, threshold 10)
- SKU-003 (out of stock)

Log / notes:

# Notes
_Scratch pad — running log of decisions, ideas, and context._

## 2026-03-19
- Agreed to delay SKU-003 restock until April (supplier issue)
- New photography style approved for spring campaign

## 2026-03-15
- Switched email provider to Mailchimp (lower cost, better analytics)

Permissions

The .claude/settings.local.json file controls what tools Claude can use in this project. Keep permissions minimal — only what the agent actually needs.

{
  "permissions": {
    "allow": [
      "Read(*)",
      "Write(*)",
      "Edit(*)",
      "Bash(ls *)",
      "Bash(mkdir *)",
      "Bash(git add *)",
      "Bash(git commit *)",
      "Bash(python3 scripts/*)",
      "WebSearch(*)",
      "WebFetch(*)"
    ],
    "deny": []
  }
}

For a read-heavy agent (research, content): add WebSearch, WebFetch. For an automation-heavy agent (scripts, APIs): add specific Bash(python3 scripts/*) patterns. For a pure file-management agent (tasks, notes): Read, Write, Edit are enough.


Session Ritual Pattern

This is the core pattern that makes agents work across sessions. Without rituals, each session starts from zero.

Startup Ritual (load state)

1. Read memory index → understand the domain and key people
2. Read operational state → what's pending, what's in progress
3. Greet with context → surface anything urgent or timely

Work Phase

Normal conversation + file editing as needed.

Shutdown Ritual (save state)

1. Update any changed data files (tasks, status, inventory, notes)
2. Update memory if new facts were learned
3. Git commit → changes survive machine restarts and are versioned

Journal Pattern (for business agents)

Add a JOURNAL.md with newest-first entries — an audit trail of what happened and why:

## 2026-03-19 — Session: Spring campaign launch

### What was done
- Created email campaign targeting past customers
- Updated product descriptions for 4 new listings
- Resolved 2 open support tickets

### Decisions made
| Decision | Rationale |
|---|---|
| 10% launch discount | Drive first-week volume; revert after 7 days |
| Delay SKU-003 restock | Supplier unavailable until April |

### Blockers
- Analytics not yet connected — can't measure conversion rate

### Next session priorities
1. Connect analytics platform
2. Check campaign open rates after 48h
3. Follow up with supplier on SKU-003

Agent Type Patterns

Personal Assistant Agent

Character: Warm, named, relatable. Has a personality and a tone. Memory: People-centric — who they are, preferences, working styles. Data: Tasks, notes, calendar reminders, project status. Skills: Capture, review, plan, research. Tone: Conversational, proactive, mentions names naturally. Shutdown: Update files. Commit. No journal needed unless tracking decisions matters.

Best for: personal productivity, home management, research, journaling, any domain where one person is the primary user.

Business / Autonomous Agent

Character: Has a title (CEO, Ops Manager, Editor), clear authority levels. Memory: Decision-centric — strategy choices, platform IDs, pricing rules, vendor info. Data: Products, campaigns, financials, pipeline. Skills: Specialized by function (content, marketing, ops, design). Tone: Professional. Tracks decisions and their rationale. Shutdown: JOURNAL.md entry + TODO.md update + git commit. Hard rules: Financial guardrails, approval thresholds, legal/brand constraints. Subagents: Multiple role-specific SKILL.md files under agents/.

Best for: e-commerce, content operations, project management — anything where decisions and rationale need to be tracked over time.

Key Differences

Aspect Personal Assistant Business Agent
Personality Named character, warm Role/title, professional
Memory People & preferences Decisions & platform facts
Shutdown Update files + commit Journal + update + commit
Escalation User preference Hard rules + approval tiers
Skills directory skills/ agents/
Operational log Optional JOURNAL.md (required)

Discord Bridge

Bridge a Discord channel directly to your agent's tmux session so users can interact with it via chat messages — no terminal access required.

Project: potomak/claude-discord-bridge

How it works

Discord user sends message
    │
    ▼
Bot injects message into tmux session (+ reply-file instruction)
    │
    ▼
Claude does its work — tool calls relayed to Discord as progress updates
    │
    ▼
Claude writes final reply → /tmp/<bot>-reply-<uuid>.txt
    │
    ▼
Bot detects file → posts contents to Discord → deletes file

The key design: instead of scraping tmux output (noisy, unreliable), the bot uses a file handoff. Every incoming message is injected with an appended instruction telling Claude to write its final response to a unique temp file. The bot polls for that file; when it appears the contents are posted to Discord and the file is deleted. This gives a clean, unambiguous signal for when the response is ready.

While Claude works, the bot also:

  • Posts each tool call to Discord as a one-liner (🔧 Bash — list files in scripts/) so the user can follow along
  • Forwards permission prompts from Claude Code to Discord, letting the user reply with 1 / 2 / 3
  • Captures the extended-thinking spinner from the tmux pane and posts it as a 💭 message

Setup

Full instructions in the project's SKILL.md. Short version:

  1. Create a Discord bot at discord.com/developers/applications — enable Message Content Intent
  2. Add required vars to config/.env:
    DISCORD_BOT_TOKEN=<token>
    DISCORD_CHANNEL_ID=<channel_id>
    TMUX_SESSION=<session_name>
    CLAUDE_PROJECTS_DIR=/home/pi/.claude/projects/<project-slug>
    BOT_NAME=<name>-bot
    BOT_STARTUP_MSG=🤖 <Agent name> online — Claude is listening.
    BOT_ENABLE_IMAGES=false
    
  3. Run install.sh to generate and install the systemd service:
    ./install.sh /path/to/project <service-name>
  4. Add the Discord bridge section to your CLAUDE.md (see below)

CLAUDE.md addition

Add this section to your project's CLAUDE.md so the agent is primed from session start:

## Discord bridge

This session is bridged to Discord via a bot running as a systemd service (`<service-name>`).
Messages from Discord are injected into this tmux session verbatim.

**Reply file convention:** every incoming message ends with an instruction like:
```
When you have finished, write your complete reply for the user to this file using the Write tool: /tmp/<bot>-reply-<id>.txt
```
You **must** follow this instruction as your final action — use the Write tool to write exactly
what you want the user to read to that path. The bot detects the file, posts its contents to
Discord, and deletes it. If you skip this step the user receives no response.

Global permission (one-time)

Add this to ~/.claude/settings.json so Claude is never prompted for permission when writing reply files to /tmp/:

{
  "permissions": {
    "allow": [
      "Write(/tmp/**)"
    ]
  }
}

Bootstrap Checklist

When starting a new agent from scratch:

1. Define the agent

  • What is the agent's domain? (home, business, project, research...)
  • What persona or role does it have?
  • Who are the key people or entities it needs to know about?
  • What are the hard rules — things it must never do?

2. Create the structure

mkdir -p my-agent/{memory,data,skills,.claude}

3. Write CLAUDE.md

  • Role + persona (2–3 sentences)
  • Context (who, what, key entities)
  • Startup ritual (3–6 steps)
  • Shutdown ritual (2–4 steps)
  • Skill map (table of skills + paths)
  • Data file index (table of files + purpose)
  • Hard rules (3–7 max)

4. Create memory files

  • memory/MEMORY.md (index)
  • At least one memory file with core context (people, preferences, or domain background)

5. Create data files

  • One file per operational domain (tasks, status, inventory, notes...)
  • Include "Last updated" at top of each
  • Pre-populate with realistic starter data

6. Create skills

  • One SKILL.md per major recurring workflow
  • Include: trigger command, purpose, step-by-step process, what to update after

7. Set permissions

  • Create .claude/settings.local.json
  • Whitelist only the tools the agent actually needs

8. Initialize git

git init
git add -A
git commit -m "Initial agent setup"
git remote add origin git@github.com:your-org/your-agent.git
git push -u origin main

9. Write README.md

  • What is this agent?
  • How to start a session (cd ~/my-agent && claude)
  • Available skills (table)
  • File structure overview
  • First-session checklist for new users

10. Add a Discord bridge (optional)

  • Follow setup steps in potomak/claude-discord-bridge
  • Add bot env vars to config/.env
  • Run install.sh to install the systemd service
  • Add the Discord bridge section to CLAUDE.md
  • Add Write(/tmp/**) to ~/.claude/settings.json global permissions

References

Similar Projects & Frameworks

  • OpenClaw — Full-featured multi-agent framework. WebSocket gateway, registry-based skill system, npm plugins. Heavier but more capable for complex multi-agent setups.
  • NanoClaw — Container-isolated agents with per-group CLAUDE.md. Good for multi-tenant or multi-channel setups (WhatsApp, Telegram, etc.).
  • PicoClaw — Ultra-lightweight Go binary (~10MB RAM). Runs on minimal hardware, MCP integration, JSONL memory. Great for resource-constrained or always-on deployments.

Claude Code Docs

  • CLAUDE.md is loaded automatically when you run claude in a directory — it's the entry point for every agent
  • .claude/settings.local.json controls per-project tool permissions
  • Skills are invoked via slash commands defined in CLAUDE.md

Key Design Decisions

Why markdown files over a database? Markdown is readable by humans and Claude alike. You can edit it directly, diff it in git, and open it in any text editor. A SQLite database requires tooling; a .md file requires nothing.

Why a startup ritual instead of persistent context? Claude's context window resets each session. The ritual is the mechanism that reloads state — it's explicit, auditable, and reliable. Don't rely on caching; rely on files.

Why git? Versioning the agent's knowledge base means you can roll back bad edits, see what changed and when, and sync across machines. The agent's memory is just code — treat it that way.

Why separate memory/ from data/? Memory = slow-changing facts about people and the world. Data = fast-changing operational state. Keeping them separate clarifies which files to read at startup (memory) vs. which to update during a session (data).

Why keep CLAUDE.md short? Long CLAUDE.md files dilute focus. The file should orient Claude quickly, not document everything. Put deep domain knowledge in SKILL.md files and data files where it's actually needed.

Why a shutdown ritual? Without it, every session ends with unsaved state. The ritual is a forcing function: it ensures that changes are written to files and committed before the session closes, so the next session starts with accurate context.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment