Back to The Times of Claw

Advanced OpenClaw Skill Writing: Patterns and Best Practices

Advanced OpenClaw skill writing guide: context injection, conditional logic, API rate limits, references/, scripts/ structure, and patterns for production-grade skills.

Mark Rachapoom
Mark Rachapoom
·8 min read
Advanced OpenClaw Skill Writing: Patterns and Best Practices

Writing a basic OpenClaw skill is easy — create a SKILL.md, describe what the agent should do, done. Writing a good skill that works reliably across different contexts, handles edge cases, and stays maintainable over time is harder. This guide covers the advanced patterns.

If you're new to skills entirely, read what DenchClaw is and how it works first, then come back.

Skill Anatomy Recap#

Every skill is a directory with a SKILL.md at the root. Optionally, it has:

my-skill/
├── SKILL.md           # The agent reads this
├── references/        # Supporting docs the agent can read
│   └── api-docs.md
├── scripts/           # Shell scripts the agent can run
│   └── run-query.sh
└── README.md          # For human developers

The agent reads SKILL.md first. Everything else is referenced from within SKILL.md. Think of SKILL.md as the index.

Pattern 1: Progressive Context Loading#

The problem: SKILL.md has a token cost. If you dump everything — all API docs, all SQL schemas, all reference material — into a single file, you're loading thousands of tokens into the context for every task, even simple ones.

The pattern: Keep SKILL.md lean. Reference detailed documentation only when the agent actually needs it.

# GitHub Skill
 
Use this skill for GitHub operations via the `gh` CLI.
 
## Quick Reference
 
For most tasks, the `gh` CLI covers everything:
- `gh issue list --repo owner/repo`
- `gh pr view 123`
- `gh run list --workflow ci.yml`
 
## Detailed API Reference
 
For complex operations, read `references/gh-api-reference.md`.
 
## Auth Status
 
Before any operation, verify: `gh auth status`

This way, the agent loads the quick reference immediately but defers the API docs unless it hits something complex. The agent will read the reference file when it needs it — you don't have to pre-load it.

Pattern 2: Explicit Decision Trees#

Vague instructions produce inconsistent behavior. Replace ambiguous guidance with explicit decision trees.

Bad:

When the user asks about leads, help them manage their pipeline.

Good:

## Lead Handling Decision Tree
 
When asked about leads:
 
1. **If asked to "show my leads":**
   - Query: `SELECT * FROM v_contacts WHERE status = 'Lead' ORDER BY created_at DESC LIMIT 20`
   - Present as a table: Name, Company, Status, Last Activity
 
2. **If asked to "score" a lead:**
   - Require lead name or ID before proceeding
   - Apply scoring rubric in `references/lead-scoring.md`
   - UPDATE the lead_score field in DuckDB
   - Confirm: "Lead scored: [name] → [score]/100"
 
3. **If asked to "move" a lead:**
   - Ask: "Move to which stage?" if not specified
   - Valid stages: Prospect, Qualified, Proposal, Negotiation, Closed Won, Closed Lost
   - UPDATE status field, log event to entry_fields

Explicit paths produce deterministic behavior. The agent doesn't have to interpret.

Pattern 3: Guard Clauses and Safety Checks#

Production skills need guard clauses — explicit checks before destructive or irreversible actions.

## Deleting Records
 
Before deleting ANY record:
 
1. Show the user what will be deleted (name, ID, type)
2. Ask for explicit confirmation: "Are you sure you want to delete [X]? This cannot be undone."
3. Wait for confirmation. "yes", "y", "confirm" are valid.
4. Only then execute the DELETE query.
 
NEVER delete without confirmation. NEVER batch delete more than 10 records in a single operation without listing them first.

This pattern is especially important for skills that touch email, external APIs, or database writes. Add guard clauses for anything you'd be unhappy to discover the agent did autonomously.

Pattern 4: Rate Limit Handling#

Skills that call external APIs need explicit rate limit instructions. Don't assume the agent will figure this out.

## API Rate Limits
 
This skill calls the Clearbit API for contact enrichment.
 
Rate limits:
- 600 requests/minute on the Business plan
- 50 requests/minute on the Starter plan
 
When enriching multiple contacts:
- Process in batches of 10
- Add a 6-second delay between batches: `sleep 6`
- If you receive a 429 response, wait 60 seconds and retry ONCE
- If the retry also fails, skip that contact and note it for manual review
 
NEVER loop through 100+ contacts without batching.

Without this, the agent will happily hammer an API at full speed and generate 429 errors or burn your quota. Explicit rate limit instructions prevent this.

Pattern 5: Schema Documentation in Skills#

If your skill does DuckDB operations, document the schema inside the skill. Don't make the agent query DESCRIBE every time.

## DuckDB Schema Reference
 
The workspace uses an EAV (Entity-Attribute-Value) schema.
 
### Core Tables
 
**objects** — types of records
```sql
CREATE TABLE objects (
  id TEXT PRIMARY KEY,
  name TEXT,
  slug TEXT UNIQUE,
  created_at TIMESTAMP
);

entries — individual records

CREATE TABLE entries (
  id TEXT PRIMARY KEY,
  object_id TEXT REFERENCES objects(id),
  label TEXT,
  created_at TIMESTAMP
);

entry_fields — field values for records

CREATE TABLE entry_fields (
  id TEXT PRIMARY KEY,
  entry_id TEXT REFERENCES entries(id),
  field_key TEXT,
  field_value TEXT,
  updated_at TIMESTAMP
);

PIVOT Views#

Use v_contacts instead of raw joins. Example:

SELECT name, email, company, status FROM v_contacts WHERE status = 'Lead';

This is worth the SKILL.md tokens. The agent writes better SQL when it knows the schema upfront.

---

## Pattern 6: Output Format Specifications

Inconsistent output format is one of the biggest usability problems with AI tools. Skills should specify exactly how output should be formatted.

```markdown
## Output Formats

### Contact Summaries
Always present contact summaries in this format:

[Name] | [Company] | [Status] Email: [email] | Phone: [phone] Last activity: [date] — [activity description]


### SQL Query Results
For queries returning >5 rows: use a markdown table.
For queries returning ≤5 rows: use bullet lists.
For COUNT queries: state the number plainly ("47 leads in your pipeline").

### Error Messages
Format: "⚠️ [Error type]: [What happened]. [What to do next]."
Example: "⚠️ Record not found: No contact with email 'john@example.com'. Did you mean a different email?"

Pattern 7: Skill Composition#

Complex workflows often require multiple skills working together. Document the composition explicitly.

## Dependencies
 
This skill requires:
- `crm` skill — for reading and writing contact data
- `browser` skill — for looking up company information
- `himalaya` skill — for sending follow-up emails
 
When running the "enrich and outreach" workflow:
1. Use CRM skill to identify leads missing company data
2. Use Browser skill to find each company's website and LinkedIn
3. Update DuckDB with enrichment data (CRM skill)
4. Use Himalaya skill to send personalized follow-up (requires user confirmation)

Pattern 8: Versioning and Changelogs#

Skills evolve. Without a version history, debugging regressions is painful.

# My CRM Skill
 
**Version:** 2.3.1
**Last updated:** 2026-03-20
**Maintainer:** @mark
 
## Changelog
 
### 2.3.1 (2026-03-20)
- Fixed lead scoring to correctly handle null company fields
 
### 2.3.0 (2026-03-15)
- Added bulk email enrichment via Clearbit (Pattern 4 rate limits apply)
 
### 2.2.0 (2026-03-01)
- Added support for custom pipeline stages

When a skill breaks unexpectedly, the changelog tells you what changed recently.

Testing Your Skill#

Before shipping a skill, test it against these scenarios:

  1. Happy path — Does it work for the obvious case?
  2. Empty results — How does it behave when a query returns nothing?
  3. Bad input — What happens if the user gives ambiguous or wrong input?
  4. External failure — If an API is down, does it fail gracefully?
  5. Edge cases — What about records with missing fields? Duplicate names?

Write these as a checklist in your skill's README, not in SKILL.md:

## Testing Checklist
 
- [ ] `show leads` with 0 leads in database
- [ ] `score lead Jane` when two contacts named Jane exist
- [ ] `enrich contacts` when Clearbit API key is missing
- [ ] `delete lead 123` — confirm guard clause fires

Publishing to ClawHub#

Once your skill is production-ready, consider publishing to ClawHub, the skills marketplace for OpenClaw.

Requirements for publication:

  • Valid SKILL.md at root
  • README.md with description, use cases, and setup instructions
  • Version number in SKILL.md frontmatter or header
  • No hardcoded API keys (use environment variable references)

The full setup guide includes steps for installing skills from ClawHub.

FAQ#

How long should a SKILL.md be? As long as it needs to be and no longer. A skill with 5 clear commands can be 100 lines. A skill with complex workflow logic might be 500 lines. Optimize for clarity, not brevity or comprehensiveness. If you're past 800 lines, move supporting docs to references/.

Can a skill call another skill? Not directly — the agent reads skills sequentially, not recursively. But you can reference other skills in your SKILL.md: "For email operations, see the himalaya skill." The agent will switch context when appropriate.

How do I handle environment-specific values (dev vs prod)? Use .env files in the workspace root and reference them explicitly in the skill: "Read the API endpoint from the CLEARBIT_API_URL environment variable."

What's the difference between references/ and scripts/? references/ is for documents the agent reads. scripts/ is for shell scripts the agent executes. Both are organized under the skill directory and referenced from SKILL.md.

How often should I update skills? When behavior needs to change. Don't update for the sake of it — every update requires team members to re-install. Batch small changes and release on a cadence (bi-weekly or monthly).

Ready to try DenchClaw? Install in one command: npx denchclaw. Full setup guide →

Mark Rachapoom

Written by

Mark Rachapoom

Building the future of AI CRM software.

Continue reading

DENCH

© 2026 DenchHQ · San Francisco, CA