--- name: skill-creator description: Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. --- # Skill Creator A skill for creating new skills and iteratively improving them. At a high level, the process of creating a skill goes like this: --- ## Key Resource: Prompt Optimization Framework This skill is integrated with a comprehensive **Prompt Optimization Framework** that synthesizes advanced prompt engineering techniques from cutting-edge research. Reference `prompt-optimization-framework.md` for: - **Prompt Technique Decision Tree**: Choose the right approach (zero-shot, few-shot, CoT, meta prompting, etc.) - **Pattern-Specific Guidelines**: Tailored instructions for tool-wrapper, generator, reviewer, inversion, and pipeline patterns - **Context Engineering Principles**: Progressive disclosure, theory of mind, structured outputs, anti-patterns to avoid - **Real-World Examples**: Complete prompt templates demonstrating best practices **When to reference the framework**: - Before writing SKILL.md (to choose the right prompt technique) - When improving a skill (to identify better prompting approaches) - When debugging a skill (to check for common anti-patterns) - For pattern-specific templates and examples The framework ensures skills use optimal prompt engineering from the start, making them more effective, generalizable, and maintainable. --- - Decide what you want the skill to do and roughly how it should do it - Write a draft of the skill - Create a few test prompts and run the agent with the skill loaded - Help the user evaluate the results both qualitatively and quantitatively - While the runs happen in the background, draft some quantitative evals if there aren't any (if there are some, you can either use as is or modify if you feel something needs to change about them). Then explain them to the user (or if they already existed, explain the ones that already exist) - Use the `eval-viewer/generate_review.py` script to show the user the results for them to look at, and also let them look at the quantitative metrics - Rewrite the skill based on feedback from the user's evaluation of the results (and also if there are any glaring flaws that become apparent from the quantitative benchmarks) - Repeat until you're satisfied - Expand the test set and try again at larger scale Your job when using this skill is to figure out where the user is in this process and then jump in and help them progress through these stages. So for instance, maybe they're like "I want to make a skill for X". You can help narrow down what they mean, write a draft, write the test cases, figure out how they want to evaluate, run all the prompts, and repeat. On the other hand, maybe they already have a draft of the skill. In this case you can go straight to the eval/iterate part of the loop. Of course, you should always be flexible and if the user is like "I don't need to run a bunch of evaluations, just vibe with me", you can do that instead. Then after the skill is done (but again, the order is flexible), you can also run the skill description improver, which we have a whole separate script for, to optimize the triggering of the skill. Cool? Cool. ## Communicating with the user The skill creator is liable to be used by people across a wide range of familiarity with coding jargon. If you haven't heard (and how could you, it's only very recently that it started), there's a trend now where the power of AI agents is inspiring plumbers to open up their terminals, parents and grandparents to google "how to install npm". On the other hand, the bulk of users are probably fairly computer-literate. So please pay attention to context cues to understand how to phrase your communication! In the default case, just to give you some idea: - "evaluation" and "benchmark" are borderline, but OK - for "JSON" and "assertion" you want to see serious cues from the user that they know what those things are before using them without explaining them It's OK to briefly explain terms if you're in doubt, and feel free to clarify terms with a short definition if you're unsure if the user will get it. --- ## Creating a skill ### Capture Intent Start by understanding the user's intent. The current conversation might already contain a workflow the user wants to capture (e.g., they say "turn this into a skill"). If so, extract answers from the conversation history first — the tools used, the sequence of steps, corrections the user made, input/output formats observed. The user may need to fill the gaps, and should confirm before proceeding to the next step. 1. What should this skill enable the agent to do? 2. When should this skill trigger? (what user phrases/contexts) 3. What's the expected output format? 4. Should we set up test cases to verify the skill works? Skills with objectively verifiable outputs (file transforms, data extraction, code generation, fixed workflow steps) benefit from test cases. Skills with subjective outputs (writing style, art) often don't need them. Suggest the appropriate default based on the skill type, but let the user decide. ### Choose Your Design Pattern After capturing intent, help the user select the appropriate design pattern for their skill. The five core patterns are: | Pattern | When to Use | Key Characteristics | |---------|-------------|---------------------| | **Tool Wrapper** | Domain-specific expertise (libraries, frameworks, conventions) | Loads docs on-demand, applies rules as truth | | **Generator** | Consistent structured output (documents, code, configs) | Templates + style guides, fill-in-the-blank | | **Reviewer** | Evaluation against criteria (code review, audits, checks) | Separate checklist from evaluation, severity-based | | **Inversion** | Tasks requiring user input to proceed (planning, requirements) | Agent interviews user first, gated phases | | **Pipeline** | Multi-step workflows with checkpoints (build, deploy, analyze) | Strict sequence, hard gates, no skipping | **Pattern Selection Decision Tree:** ``` Does the task require user input before proceeding? ├─ Yes → Use INVERSION pattern │ Examples: project planning, requirements gathering, design sessions └─ No → Does the task evaluate work against criteria? ├─ Yes → Use REVIEWER pattern │ Examples: code review, security audit, style checking └─ No → Does the task require multiple steps in sequence? ├─ Yes → Use PIPELINE pattern │ Examples: documentation generation, build processes, data pipelines └─ No → Does the task need consistent structured output? ├─ Yes → Use GENERATOR pattern │ Examples: report writing, API docs, config generation └─ No → Use TOOL WRAPPER pattern Examples: library expertise, framework conventions, best practices ``` **Note:** Patterns are not mutually exclusive — they compose. A Pipeline can include a Reviewer step at the end. A Generator can use Inversion to gather variables first. Document the chosen pattern in the skill's metadata: ```yaml --- name: your-skill description: ... metadata: pattern: generator # tool-wrapper, generator, reviewer, inversion, pipeline domain: your-domain --- ``` ### Interview and Research Proactively ask questions about edge cases, input/output formats, example files, success criteria, and dependencies. Wait to write test prompts until you've got this part ironed out. Check available MCPs - if useful for research (searching docs, finding similar skills, looking up best practices), research in parallel via subagents if available, otherwise inline. Come prepared with context to reduce burden on the user. ### Write the SKILL.md Based on the user interview and chosen design pattern, fill in these components: **Important**: Before writing, review the **Prompt Optimization Framework** at `prompt-optimization-framework.md`. This guide provides: - A decision tree for choosing the right prompt technique - Pattern-specific guidelines for each design pattern - Best practices for context engineering and prompt structure - Real-world examples demonstrating effective prompts This ensures your skill uses optimal prompt engineering techniques from the start, avoiding common pitfalls and ensuring the skill is generalizable and effective. - **name**: Skill identifier - **description**: When to trigger, what it does. This is the primary triggering mechanism - include both what the skill does AND specific contexts for when to use it. All "when to use" info goes here, not in the body. Note: currently agents have a tendency to "undertrigger" skills -- to not use them when they'd be useful. To combat this, please make the skill descriptions a little bit "pushy". So for instance, instead of "How to build a simple fast dashboard to display internal Anthropic data.", you might write "How to build a simple fast dashboard to display internal Anthropic data. Make sure to use this skill whenever the user mentions dashboards, data visualization, internal metrics, or wants to display any kind of company data, even if they don't explicitly ask for a 'dashboard.'" - **metadata**: Include the pattern type (`pattern: tool-wrapper|generator|reviewer|inversion|pipeline`) and domain (`domain: your-domain`) - **compatibility**: Required tools, dependencies (optional, rarely needed) - **the rest of the skill :)** ### Pattern Examples Here are complete examples for each of the five patterns. Use these as templates and adapt to your use case. **Tool Wrapper Pattern** — Expert knowledge on demand: ```markdown # skills/fastapi-expert/SKILL.md --- name: fastapi-expert description: FastAPI development best practices and conventions. Use when building, reviewing, or debugging FastAPI applications, REST APIs, or Pydantic models. Apply these conventions whenever working with FastAPI code. metadata: pattern: tool-wrapper domain: fastapi --- You are an expert in FastAPI development. Apply these conventions to the user's code or question. ## Core Conventions Load 'references/conventions.md' for the complete list of FastAPI best practices. ## When Reviewing Code 1. Load the conventions reference 2. Check the user's code against each convention 3. For each violation, cite the specific rule and suggest the fix ## When Writing Code 1. Load the conventions reference 2. Follow every convention exactly 3. Add type annotations to all function signatures 4. Use Annotated style for dependency injection ``` **Generator Pattern** — Structured output from templates: ```markdown # skills/report-generator/SKILL.md --- name: report-generator description: Generates structured technical reports in Markdown. Use when the user asks to write, create, or draft a report, summary, or analysis document that requires consistent structure. metadata: pattern: generator output-format: markdown --- You are a technical report generator. Follow these steps exactly: Step 1: Load 'references/style-guide.md' for tone and formatting rules. Step 2: Load 'assets/report-template.md' for the required output structure. Step 3: Ask the user for any missing information needed to fill the template: - Topic or subject - Key findings or data points - Target audience (technical, executive, general) Step 4: Fill the template following the style guide rules. Every section in the template must be present in the output. Step 5: Return the completed report as a single Markdown document. ``` **Reviewer Pattern** — Evaluation with severity: ```markdown # skills/code-reviewer/SKILL.md --- name: code-reviewer description: Reviews Python code for quality, style, and common bugs. Use when the user submits code for review, asks for feedback on their code, or wants a code audit. metadata: pattern: reviewer severity-levels: error,warning,info --- You are a Python code reviewer. Follow this review protocol exactly: Step 1: Load 'references/review-checklist.md' for the complete review criteria. Step 2: Read the user's code carefully. Understand its purpose before critiquing. Step 3: Apply each rule from the checklist to the code. For every violation found: - Note the line number (or approximate location) - Classify severity: error (must fix), warning (should fix), info (consider) - Explain WHY it's a problem, not just WHAT is wrong - Suggest a specific fix with corrected code Step 4: Produce a structured review with these sections: - **Summary**: What the code does, overall quality assessment - **Findings**: Grouped by severity (errors first, then warnings, then info) - **Score**: Rate 1-10 with brief justification - **Top 3 Recommendations**: The most impactful improvements ``` **Inversion Pattern** — Interview first, act later: ```markdown # skills/project-planner/SKILL.md --- name: project-planner description: Plans a new software project by gathering requirements through structured questions before producing a plan. Use when the user says "I want to build", "help me plan", "design a system", or "start a new project". metadata: pattern: inversion interaction: multi-turn --- You are conducting a structured requirements interview. DO NOT start building or designing until all phases are complete. ## Phase 1 — Problem Discovery (ask one question at a time, wait for each answer) Ask these questions in order. Do not skip any. - Q1: "What problem does this project solve for its users?" - Q2: "Who are the primary users? What is their technical level?" - Q3: "What is the expected scale? (users per day, data volume, request rate)" ## Phase 2 — Technical Constraints (only after Phase 1 is fully answered) - Q4: "What deployment environment will you use?" - Q5: "Do you have any technology stack requirements or preferences?" - Q6: "What are the non-negotiable requirements? (latency, uptime, compliance, budget)" ## Phase 3 — Synthesis (only after all questions are answered) 1. Load 'assets/plan-template.md' for the output format 2. Fill in every section of the template using the gathered requirements 3. Present the completed plan to the user 4. Ask: "Does this plan accurately capture your requirements? What would you change?" 5. Iterate on feedback until the user confirms ``` **Pipeline Pattern** — Multi-step workflow with gates: ```markdown # skills/doc-pipeline/SKILL.md --- name: doc-pipeline description: Generates API documentation from Python source code through a multi-step pipeline. Use when the user asks to document a module, generate API docs, or create documentation from code. metadata: pattern: pipeline steps: "4" --- You are running a documentation generation pipeline. Execute each step in order. Do NOT skip steps or proceed if a step fails. ## Step 1 — Parse & Inventory Load 'references/step1-inventory-rules.md' for extraction guidelines. Analyze the user's Python code to extract all public classes, functions, and constants. Present the inventory as a checklist. Ask: "Is this the complete public API you want documented?" ### Save Handoff Document After completing this step, save a handoff document as: `workspace/step-1-handoff.md` Include in the handoff: - Complete inventory (all classes, functions, constants found) - Extraction decisions (what was included, excluded, or modified) - Location of each symbol in the source code - Any issues encountered during extraction **Do NOT proceed to Step 2 until the handoff document is saved.** ## Step 2 — Generate Docstrings Load 'workspace/step-1-handoff.md' to get the inventory from Step 1. Load 'references/step2-docstring-style.md' for the required format. For each function lacking a docstring: - Generate a docstring following the style guide exactly - Present each generated docstring for user approval Do NOT proceed to Step 3 until the user confirms. ### Save Handoff Document After completing this step, save a handoff document as: `workspace/step-2-handoff.md` Include in the handoff: - ALL generated docstrings (not just those shown to user) - Generation decisions (why this format was chosen) - Pending user approval items - Any docstrings that failed to generate or need revision **Do NOT proceed to Step 3 until the handoff document is saved.** ## Step 3 — Assemble Documentation Load 'workspace/step-2-handoff.md' to get the generated docstrings. Load 'workspace/step-1-handoff.md' to get the original inventory. Load 'references/step3-assembly-rules.md' for compilation guidelines. Load 'assets/api-doc-template.md' for the output structure. Compile all classes, functions, and docstrings into a single API reference document. ### Save Handoff Document After completing this step, save a handoff document as: `workspace/step-3-handoff.md` Include in the handoff: - Complete assembled document (or reference to it) - Assembly transformation history (how inputs became outputs) - Quality metrics (word counts, coverage stats) - Assembly errors (items that couldn't be assembled and why) **Do NOT proceed to Step 4 until the handoff document is saved.** ## Step 4 — Quality Check Load 'workspace/step-3-handoff.md' to get the assembled document. Load 'references/step4-quality-checklist.md' for validation criteria. Review against the checklist: - Every public symbol documented - Every parameter has a type and description - At least one usage example per function Report results. Fix issues before presenting the final document. ``` **Directory Structure for Split References:** ``` doc-pipeline/ ├── SKILL.md ├── assets/ │ └── api-doc-template.md └── references/ ├── step1-inventory-rules.md # Only loaded in Step 1 ├── step2-docstring-style.md # Only loaded in Step 2 ├── step3-assembly-rules.md # Only loaded in Step 3 └── step4-quality-checklist.md # Only loaded in Step 4 ``` ### Pattern Composition Patterns can work together. Examples: - **Pipeline + Reviewer**: A documentation pipeline that ends with a Reviewer step to quality-check the generated docs - **Generator + Inversion**: A report generator that uses Inversion at the start to interview the user for variables, then fills the template - **Tool Wrapper + Pipeline**: A FastAPI expert skill that uses Pipeline for code generation with review steps When composing patterns, clearly mark each pattern's section and explain how they interact. ### Skill Writing Guide #### Anatomy of a Skill ``` skill-name/ ├── SKILL.md (required) │ ├── YAML frontmatter (name, description required) │ └── Markdown instructions └── Bundled Resources (optional) ├── scripts/ - Executable code for deterministic/repetitive tasks ├── references/ - Docs loaded into context as needed └── assets/ - Files used in output (templates, icons, fonts) ``` #### Progressive Disclosure Skills use a three-level loading system: 1. **Metadata** (name + description) - Always in context (~100 words) 2. **SKILL.md body** - In context whenever skill triggers (<500 lines ideal) 3. **Bundled resources** - As needed (unlimited, scripts can execute without loading) These word counts are approximate and you can feel free to go longer if needed. **Key patterns:** - Keep SKILL.md under 500 lines; if you're approaching this limit, add an additional layer of hierarchy along with clear pointers about where the model using the skill should go next to follow up. - Reference files clearly from SKILL.md with guidance on when to read them - For large reference files (>300 lines), include a table of contents **Domain organization**: When a skill supports multiple domains/frameworks, organize by variant: ``` cloud-deploy/ ├── SKILL.md (workflow + selection) └── references/ ├── aws.md ├── gcp.md └── azure.md ``` The agent reads only the relevant reference file. #### Principle of Lack of Surprise This goes without saying, but skills must not contain malware, exploit code, or any content that could compromise system security. A skill's contents should not surprise the user in their intent if described. Don't go along with requests to create misleading skills or skills designed to facilitate unauthorized access, data exfiltration, or other malicious activities. Things like a "roleplay as an XYZ" are OK though. #### Writing Patterns Prefer using the imperative form in instructions. **Defining output formats** - You can do it like this: ```markdown ## Report structure ALWAYS use this exact template: # [Title] ## Executive summary ## Key findings ## Recommendations ``` **Examples pattern** - It's useful to include examples. You can format them like this (but if "Input" and "Output" are in the examples you might want to deviate a little): ```markdown ## Commit message format **Example 1:** Input: Added user authentication with JWT tokens Output: feat(auth): implement JWT-based authentication ``` ### Writing Style **Core Principle**: Explain the WHY, not just the WHAT. Use theory of mind to explain the reasoning behind instructions. Today's LLMs are smart - when given a good harness, they can go beyond rote instructions and really make things happen. **Key Guidelines**: - Try to explain to the model why things are important in lieu of heavy-handed musty MUSTs - Use theory of mind and try to make the skill general and not super-narrow to specific examples - Start by writing a draft and then look at it with fresh eyes and improve it - **SAY WHAT TO DO, not what NOT to do** (e.g., "Include error handling" not "Don't forget error handling") - Be specific and direct (e.g., "Add try-catch around I/O operations" not "Make sure to handle errors properly") **Reference the Prompt Optimization Framework**: The complete prompt optimization framework is available in `prompt-optimization-framework.md`. Use it to: - Choose the right prompt technique (zero-shot, few-shot, CoT, etc.) for your skill - Apply pattern-specific guidelines for tool-wrapper, generator, reviewer, inversion, and pipeline patterns - Follow context engineering principles (progressive disclosure, theory of mind, structured outputs) - Review the quick reference checklist before finalizing prompts The framework includes: - Decision tree for selecting prompt techniques - Reference examples for each technique (zero-shot, few-shot, CoT, meta prompting, ReAct, etc.) - Pattern-specific prompt templates and guidelines - Anti-patterns to avoid - Real-world examples showing integrated prompt design --- ## Environment-Specific Knowledge ### Subagent System The environment uses a sophisticated subagent system for parallel task execution. **Creating Subagents:** Use the `sessions_spawn` tool to create subagents: ```bash sessions_spawn --task "your task description" --label "task-label" ``` Key parameters: - `task` (required): The task description - `label` (optional): A label for the subagent - `agentId` (optional): Spawn under a different agent (if allowed) - `model` (optional): Override the model for this subagent - `thinking` (optional): Override thinking level - `runTimeoutSeconds` (optional): Timeout for this run - `thread` (default `false`): Request thread binding for this session - `mode` (`run|session`): One-shot mode or persistent session mode - `cleanup` (`delete|keep`, default `keep`): Cleanup behavior **Managing Subagents:** Use the `/subagents` slash commands: - `/subagents list` — List all subagents for current session - `/subagents kill ` — Stop subagent(s) - `/subagents log [limit] [tools]` — Show subagent logs - `/subagents info ` — Show subagent metadata - `/subagents send ` — Send message to subagent - `/subagents steer ` — Steer subagent direction - `/subagents spawn ` — Manually spawn subagent **Subagent Nesting:** By default, subagents cannot spawn their own subagents (`maxSpawnDepth: 1`). Enable nesting: ```json { "agents": { "defaults": { "subagents": { "maxSpawnDepth": 2, "maxChildrenPerAgent": 5, "maxConcurrent": 8 } } } } ``` **Subagent Lifecycle:** 1. Spawn → `queued` 2. Agent starts → `running` 3. Completion → `succeeded`, `failed`, `timed_out`, or `cancelled` 4. Announce to parent (optional based on settings) 5. Auto-archive after `archiveAfterMinutes` (default: 60) ### Background Task System The environment has a comprehensive background task tracking system. **What Creates Tasks:** - ACP background runs — Spawning a child ACP session - Subagent orchestration — Spawning a subagent via `sessions_spawn` - Cron jobs (all types) — Every cron execution - CLI operations — `openclaw agent` commands through gateway **What Does NOT Create Tasks:** - Heartbeat turns (main-session) - Normal interactive chat turns - Direct `/command` responses **Task Lifecycle:** ``` queued → running → terminal (succeeded | failed | timed_out | cancelled | lost) ``` **Task Notification Policies:** - `done_only` (default) — Only terminal state - `state_changes` — Every state transition - `silent` — Nothing at all **Task Management CLI:** ```bash # List all tasks openclaw tasks list # Filter by runtime or status openclaw tasks list --runtime subagent openclaw tasks list --status running # Show details openclaw tasks show # Cancel running task openclaw tasks cancel # Change notification policy openclaw tasks notify state_changes # Run health audit openclaw tasks audit ``` Key parameters: - `task` (required): The task description - `label` (optional): A label for the subagent - `agentId` (optional): Spawn under a different agent (if allowed) - `model` (optional): Override the model for this subagent - `thinking` (optional): Override thinking level - `runTimeoutSeconds` (optional): Timeout for this run - `thread` (default `false`): Request thread binding for this session - `mode` (`run|session`): One-shot mode or persistent session mode - `cleanup` (`delete|keep`, default `keep`): Cleanup behavior **Managing Subagents:** Use `/subagents` slash commands: - `/subagents list` — List all subagents for current session - `/subagents kill ` — Stop subagent(s) - `/subagents log [limit] [tools]` — Show subagent logs - `/subagents info ` — Show subagent metadata - `/subagents send ` — Send message to subagent - `/subagents steer ` — Steer subagent direction - `/subagents spawn ` — Manually spawn subagent **Subagent Nesting:** By default, subagents cannot spawn their own subagents (`maxSpawnDepth: 1`). Enable nesting: ```json { "agents": { "defaults": { "subagents": { "maxSpawnDepth": 2, // Allow subagents to spawn children "maxChildrenPerAgent": 5, // Max active children per agent "maxConcurrent": 8 // Global concurrency cap } } } } ``` **Subagent Lifecycle:** 1. Spawn → `queued` 2. Agent starts → `running` 3. Completion → `succeeded`, `failed`, `timed_out`, or `cancelled` 4. Announce to parent (optional based on settings) 5. Auto-archive after `archiveAfterMinutes` (default: 60) ### Background Task System The environment has a comprehensive background task tracking system: **What Creates Tasks:** | Source | When a task record is created | |--------|------------------------------| | ACP background runs | Spawning a child ACP session | | Subagent orchestration | Spawning a subagent via `sessions_spawn` | | Cron jobs (all types) | Every cron execution (main-session and isolated) | | CLI operations | `openclaw agent` commands through gateway | **What Does NOT Create Tasks:** - Heartbeat turns (main-session) - Normal interactive chat turns - Direct `/command` responses **Task Lifecycle:** ``` queued → running → terminal (succeeded | failed | timed_out | cancelled | lost) ``` **Task Notification Policies:** | Policy | What is delivered | |--------|------------------| | `done_only` (default) | Only terminal state | | `state_changes` | Every state transition | | `silent` | Nothing at all | **Task Management CLI:** ```bash # List all tasks openclaw tasks list # Filter by runtime or status openclaw tasks list --runtime subagent openclaw tasks list --status running # Show details openclaw tasks show # Cancel running task openclaw tasks cancel # Change notification policy openclaw tasks notify state_changes # Run health audit openclaw tasks audit # Preview or apply maintenance openclaw tasks maintenance openclaw tasks maintenance --apply ``` **Task Storage:** Tasks persist in SQLite at: `$OPENCLAW_STATE_DIR/tasks/runs.sqlite` Retention: Terminal task records are kept for 7 days, then automatically pruned. ### Hook System The environment has two hook systems: **Internal Hooks (Gateway Hooks):** Event-driven scripts for commands and lifecycle events: - `agent:bootstrap` — Runs while building bootstrap files before system prompt - Command hooks: `/new`, `/reset`, `/stop`, etc. **Plugin Hooks:** Extension points inside the agent/tool lifecycle and gateway pipeline: | Hook | When it runs | |------|-------------| | `before_model_resolve` | Pre-session, before model resolution | | `before_prompt_build` | After session load, before prompt submission | | `before_agent_start` | Legacy compatibility hook | | `before_agent_reply` | After inline actions, before LLM call | | `agent_end` | After completion | | `before_compaction` / `after_compaction` | Observe/annotate compaction cycles | | `before_tool_call` / `after_tool_call` | Intercept tool params/results | | `before_install` | Inspect scan findings, block installs | | `tool_result_persist` | Transform tool results before persistence | | `message_received` / `message_sending` / `message_sent` | Message hooks | | `session_start` / `session_end` | Session lifecycle | | `gateway_start` / `gateway_stop` | Gateway lifecycle | Use these hooks when your skill needs to intercept or modify agent behavior at specific points. ### Agent Loop The agent loop is a serialized run per session: **Flow:** 1. Intake → context assembly → model inference → tool execution → streaming replies → persistence 2. Runs are serialized per session key (session lane) and optionally through a global lane 3. Enforces timeout → aborts run if exceeded (default 48 hours, configurable via `agents.defaults.timeoutSeconds`) 4. Emits lifecycle and stream events **Entry Points:** - Gateway RPC: `agent` and `agent.wait` - CLI: `agent` command **Understanding the agent loop helps you:** - Know when hooks fire - Understand how tools are executed - Know how results flow back - Understand timeout behavior - Know when persistence happens ### Test Cases After writing the skill draft, come up with 2-3 realistic test prompts — the kind of thing a real user would actually say. Share them with the user: [you don't have to use this exact language] "Here are a few test cases I'd like to try. Do these look right, or do you want to add more?" Then run them. Save test cases to `evals/evals.json`. Don't write assertions yet — just the prompts. You'll draft assertions in the next step while the runs are in progress. ```json { "skill_name": "example-skill", "evals": [ { "id": 1, "prompt": "User's task prompt", "expected_output": "Description of expected result", "files": [] } ] } ``` See `references/schemas.md` for the full schema (including the `assertions` field, which you'll add later). ### Testing Scripts For testing skills, specialized bash scripts are provided that detect skill invocation by parsing session transcripts: **Available scripts:** - `scripts/test_skill.sh` - Test a single query against a skill - `scripts/batch_test_skill.sh` - Batch test multiple queries from a JSON file **Detection method:** These scripts detect skill invocation by searching session transcript JSONL files (`~/.openclaw/agents//sessions/*.jsonl`) for `read` tool calls to `.md` files matching the skill name. This works because the environment's `formatSkillsForPrompt` function formats skills as XML and instructs agents to use the `read` tool when a task matches a skill's description. **Usage:** ```bash # Test single query ./scripts/test_skill.sh [--session ] # Batch test from JSON file ./scripts/batch_test_skill.sh [--session ] ``` **See also:** - `docs/TESTING.md` - Complete testing guide with JQ expressions, debugging tips, and best practices - `evals/evals_example.json` - Sample test cases for reference ## Running and evaluating test cases This section is one continuous sequence — don't stop partway through. Do NOT use `/skill-test` or any other testing skill. Put results in `-workspace/` as a sibling to the skill directory. Within the workspace, organize results by iteration (`iteration-1/`, `iteration-2/`, etc.) and within that, each test case gets a directory (`eval-0/`, `eval-1/`, etc.). Don't create all of this upfront — just create directories as you go. ### Step 1: Spawn all runs (with-skill AND baseline) in the same turn For each test case, spawn two subagents in the same turn — one with the skill, one without. This is important: don't spawn the with-skill runs first and then come back for baselines later. Launch everything at once so it all finishes around the same time. **In this environment**, use `sessions_spawn` to create subagents: **With-skill run:** ```bash # Use sessions_spawn tool with the skill loaded sessions_spawn --task "" --label "eval--with-skill" # The skill should already be loaded via workspace or ~/.openclaw/skills/ ``` **Baseline run** (same prompt, but the baseline depends on context): - **Creating a new skill**: no skill at all. Use `sessions_spawn --task "" --label "eval--without-skill"` and save to `without_skill/outputs/`. - **Improving an existing skill**: the old version. Before editing, snapshot the skill (`cp -r /skill-snapshot/`), then reload the skill, use `sessions_spawn --task "" --label "eval--old-skill" and save to `old_skill/outputs/`. **Note**: In this environment, you track subagent runs using `/subagents` commands or `openclaw agents` CLI. Each subagent gets a unique sessionKey in the format `agent::subagent:`. Write an `eval_metadata.json` for each test case (assertions can be empty for now). Give each eval a descriptive name based on what it's testing — not just "eval-0". Use this name for the directory too. If this iteration uses new or modified eval prompts, create these files for each new eval directory — don't assume they carry over from previous iterations. ```json { "eval_id": 0, "eval_name": "descriptive-name-here", "prompt": "The user's task prompt", "assertions": [] } ``` ### Step 2: While runs are in progress, draft assertions Don't just wait for the runs to finish — you can use this time productively. Draft quantitative assertions for each test case and explain them to the user. If assertions already exist in `evals/evals.json`, review them and explain what they check. Good assertions are objectively verifiable and have descriptive names — they should read clearly in the benchmark viewer so someone glancing at the results immediately understands what each one checks. Subjective skills (writing style, design quality) are better evaluated qualitatively — don't force assertions onto things that need human judgment. Update the `eval_metadata.json` files and `evals/evals.json` with the assertions once drafted. Also explain to the user what they'll see in the viewer — both the qualitative outputs and the quantitative benchmark. ### Step 3: As runs complete, capture timing data When each subagent run completes, you can retrieve timing data using the environment's task tracking system: ```bash # Get task details openclaw tasks show # Or use subagents command to get session info /subagents info ``` Save the timing data to `timing.json` in the run directory: ```json { "total_tokens": 84852, "duration_ms": 23332, "total_duration_seconds": 23.3, "sessionKey": "agent::subagent:", "runId": "" } ``` **In this environment**, timing and token data is persisted in the background task system (`$OPENCLAW_STATE_DIR/tasks/runs.sqlite`). You can query this using: - `openclaw tasks list` — list all tasks with timing info - `openclaw tasks show ` — detailed info for a specific task - `/subagents info ` — subagent-specific info Process each notification as it arrives rather than trying to batch them. ### Step 4: Grade, aggregate, and launch the viewer Once all runs are done: 1. **Grade each run** — spawn a grader subagent (or grade inline) that reads `agents/grader.md` and evaluates each assertion against the outputs. Save results to `grading.json` in each run directory. The grading.json expectations array must use the fields `text`, `passed`, and `evidence` (not `name`/`met`/`details` or other variants) — the viewer depends on these exact field names. For assertions that can be checked programmatically, write and run a script rather than eyeballing it — scripts are faster, more reliable, and can be reused across iterations. 2. **Aggregate into benchmark** — run the aggregation script from the skill-creator directory: ```bash python -m scripts.aggregate_benchmark /iteration-N --skill-name ``` This produces `benchmark.json` and `benchmark.md` with pass_rate, time, and tokens for each configuration, with mean ± stddev and the delta. If generating benchmark.json manually, see `references/schemas.md` for the exact schema the viewer expects. Put each with_skill version before its baseline counterpart. 3. **Do an analyst pass** — read the benchmark data and surface patterns the aggregate stats might hide. See `agents/analyzer.md` (the "Analyzing Benchmark Results" section) for what to look for — things like assertions that always pass regardless of skill (non-discriminating), high-variance evals (possibly flaky), and time/token tradeoffs. 4. **Launch the viewer** with both qualitative outputs and quantitative data: **Headless environments**: Use `--static ` to write a standalone HTML file: ```bash python /eval-viewer/generate_review.py \ /iteration-N \ --skill-name "my-skill" \ --benchmark /iteration-N/benchmark.json \ --static /tmp/eval-review-iteration-N.html ``` Then provide the file path to the user so they can open it in their browser. **For iteration 2+**, also pass `--previous-workspace /iteration-` to show comparisons. **Environments with browser/display**: If you have access to a browser, you can run the viewer as a server: ```bash nohup python /eval-viewer/generate_review.py \ /iteration-N \ --skill-name "my-skill" \ --benchmark /iteration-N/benchmark.json \ > /dev/null 2>&1 & VIEWER_PID=$! ``` **Note**: In most environments are headless (CLI, chat channels), so the `--static` approach is typically preferred. Note: please use generate_review.py to create the viewer; there's no need to write custom HTML. 5. **Tell the user** something like: "I've opened the results in your browser. There are two tabs — 'Outputs' lets you click through each test case and leave feedback, 'Benchmark' shows the quantitative comparison. When you're done, come back here and let me know." ### What the user sees in the viewer The "Outputs" tab shows one test case at a time: - **Prompt**: the task that was given - **Output**: the files the skill produced, rendered inline where possible - **Previous Output** (iteration 2+): collapsed section showing last iteration's output - **Formal Grades** (if grading was run): collapsed section showing assertion pass/fail - **Feedback**: a textbox that auto-saves as they type - **Previous Feedback** (iteration 2+): their comments from last time, shown below the textbox The "Benchmark" tab shows the stats summary: pass rates, timing, and token usage for each configuration, with per-eval breakdowns and analyst observations. Navigation is via prev/next buttons or arrow keys. When done, they click "Submit All Reviews" which saves all feedback to `feedback.json`. ### Step 5: Read the feedback When the user tells you they're done, read `feedback.json`: ```json { "reviews": [ {"run_id": "eval-0-with_skill", "feedback": "the chart is missing axis labels", "timestamp": "..."}, {"run_id": "eval-1-with_skill", "feedback": "", "timestamp": "..."}, {"run_id": "eval-2-with_skill", "feedback": "perfect, love this", "timestamp": "..."} ], "status": "complete" } ``` **In this environment**: When using `--static` mode, the feedback.json file is downloaded to the user's browser's default download location (typically `~/Downloads/`). You'll need to: 1. Ask the user where they saved the feedback.json file 2. Copy it to the workspace directory for the next iteration to pick up Empty feedback means the user thought it was fine. Focus your improvements on the test cases where the user had specific complaints. Kill the viewer server when you're done with it (if you ran it as a server): ```bash kill $VIEWER_PID 2>/dev/null ``` --- ## Improving the skill This is the heart of the loop. You've run the test cases, the user has reviewed the results, and now you need to make the skill better based on their feedback. ### How to think about improvements 1. **Generalize from the feedback.** The big picture thing that's happening here is that we're trying to create skills that can be used a million times (maybe literally, maybe even more who knows) across many different prompts. Here you and the user are iterating on only a few examples over and over again because it helps move faster. The user knows these examples in and out and it's quick for them to assess new outputs. But if the skill you and the user are codeveloping works only for those examples, it's useless. Rather than put in fiddly overfitty changes, or oppressively constrictive MUSTs, if there's some stubborn issue, you might try branching out and using different metaphors, or recommending different patterns of working. It's relatively cheap to try and maybe you'll land on something great. **Use the Prompt Optimization Framework** to guide improvements: - Review the "Iterative Improvement Guidelines" section for principles on generalizing feedback - Check if changing prompt techniques would help (e.g., from few-shot to meta prompting) - Apply theory of mind principles when explaining WHY changes are needed - Keep prompts lean - remove instructions that aren't pulling their weight 2. **Keep the prompt lean.** Remove things that aren't pulling their weight. Make sure to read the transcripts, not just the final outputs — if it looks like the skill is making the model waste a bunch of time doing things that are unproductive, you can try getting rid of the parts of the skill that are making it do that and seeing what happens. 3. **Explain the why.** Try hard to explain the **why** behind everything you're asking the model to do. Today's LLMs are *smart*. They have good theory of mind and when given a good harness can go beyond rote instructions and really make things happen. Even if the feedback from the user is terse or frustrated, try to actually understand the task and why the user is writing what they wrote, and what they actually wrote, and then transmit this understanding into the instructions. If you find yourself writing ALWAYS or NEVER in all caps, or using super rigid structures, that's a yellow flag — if possible, reframe and explain the reasoning so that the model understands why the thing you're asking for is important. That's a more humane, powerful, and effective approach. 4. **Look for repeated work across test cases.** Read the transcripts from the test runs and notice if the subagents all independently wrote similar helper scripts or took the same multi-step approach to something. If all 3 test cases resulted in the subagent writing a `create_docx.py` or a `build_chart.py`, that's a strong signal the skill should bundle that script. Write it once, put it in `scripts/`, and tell the skill to use it. This saves every future invocation from reinventing the wheel. This task is pretty important (we are trying to create billions a year in economic value here!) and your thinking time is not the blocker; take your time and really mull things over. I'd suggest writing a draft revision and then looking at it anew and making improvements. Really do your best to get into the head of the user and understand what they want and need. ### The iteration loop After improving the skill: 1. Apply your improvements to the skill 2. Rerun all test cases into a new `iteration-/` directory, including baseline runs. If you're creating a new skill, the baseline is always `without_skill` (no skill) — that stays the same across iterations. If you're improving an existing skill, use your judgment on what makes sense as the baseline: the original version the user came in with, or the previous iteration. 3. Launch the reviewer with `--previous-workspace` pointing at the previous iteration 4. Wait for the user to review and tell you they're done 5. Read the new feedback, improve again, repeat Keep going until: - The user says they're happy - The feedback is all empty (everything looks good) - You're not making meaningful progress --- ## Advanced: Blind comparison For situations where you want a more rigorous comparison between two versions of a skill (e.g., the user asks "is the new version actually better?"), there's a blind comparison system. Read `agents/comparator.md` and `agents/analyzer.md` for the details. The basic idea is: give two outputs to an independent agent without telling it which is which, and let it judge quality. Then analyze why the winner won. This is optional, requires subagents, and most users won't need it. The human review loop is usually sufficient. --- ## Description Optimization The description field in SKILL.md frontmatter is the primary mechanism that determines when a skill is invoked. After creating or improving a skill, offer to optimize the description for better triggering accuracy. **Manual Iteration Approach:** Since the environment does not have built-in programmatic description optimization, use manual iteration: 1. Test the skill with realistic prompts 2. Collect feedback on which queries triggered vs. didn't 3. Iteratively refine the description based on patterns 4. Use the "pushy" principle: be explicit about when to use the skill ### Step 1: Generate trigger eval queries Create 20 eval queries — a mix of should-trigger and should-not-trigger. Save as JSON: ```json [ {"query": "the user prompt", "should_trigger": true}, {"query": "another prompt", "should_trigger": false} ] ``` The queries must be realistic and something a user would actually type. Not abstract requests, but requests that are concrete and specific and have a good amount of detail. For instance, file paths, personal context about the user's job or situation, column names and values, company names, URLs. A little bit of backstory. Some might be in lowercase or contain abbreviations or typos or casual speech. Use a mix of different lengths, and focus on edge cases rather than making them clear-cut (the user will get a chance to sign off on them). Bad: `"Format this data"`, `"Extract text from PDF"`, `"Create a chart"` Good: `"ok so my boss just sent me this xlsx file (its in my downloads, called something like 'Q4 sales final FINAL v2.xlsx') and she wants me to add a column that shows the profit margin as a percentage. The revenue is in column C and costs are in column D i think"` **Environment-specific considerations:** - Include queries that reference skills, agents, plugins, workspaces - Include chat channel contexts (Discord commands, Slack workflows, etc.) - Include terminal/CLI workflows - Include subagent orchestration scenarios - Include model provider references (if relevant to the skill) For the **should-trigger** queries (8-10), think about coverage. You want different phrasings of the same intent — some formal, some casual. Include cases where the user doesn't explicitly name the skill or file type but clearly needs it. Throw in some uncommon use cases and cases where this skill competes with another but should win. For the **should-not-trigger** queries (8-10), the most valuable ones are the near-misses — queries that share keywords or concepts with the skill but actually need something different. Think adjacent domains, ambiguous phrasing where a naive keyword match would trigger but shouldn't, and cases where the query touches on something the skill does but in a context where another tool is more appropriate. The key thing to avoid: don't make should-not-trigger queries obviously irrelevant. "Write a fibonacci function" as a negative test for a PDF skill is too easy — it doesn't test anything. The negative cases should be genuinely tricky. ### Step 2: Review with user Present the eval set to the user for review using the HTML template: 1. Read the template from `assets/eval_review.html` 2. Replace the placeholders: - `__EVAL_DATA_PLACEHOLDER__` → the JSON array of eval items (no quotes around it — it's a JS variable assignment) - `__SKILL_NAME_PLACEHOLDER__` → the skill's name - `__SKILL_DESCRIPTION_PLACEHOLDER__` → the skill's current description 3. Write to a temp file (e.g., `/tmp/eval_review_.html`) and open it: `open /tmp/eval_review_.html` 4. The user can edit queries, toggle should-trigger, add/remove entries, then click "Export Eval Set" 5. The file downloads to `~/Downloads/eval_set.json` — check the Downloads folder for the most recent version in case there are multiple (e.g., `eval_set (1).json`) This step matters — bad eval queries lead to bad descriptions. ### How skill triggering works Understanding the triggering mechanism helps design better eval queries. Skills are loaded from multiple directories with precedence and appear in the agent's skill list. The agent decides whether to consult a skill based on the skill's `description` field in its SKILL.md frontmatter. The important thing to know is that the agent only consults skills for tasks it can't easily handle on its own — simple, one-step queries like "read this PDF" may not trigger a skill even if the description matches perfectly, because the agent can handle them directly with basic tools. Complex, multi-step, or specialized queries reliably trigger skills when the description matches. This means your eval queries should be substantive enough that the agent would actually benefit from consulting a skill. Simple queries like "read file X" are poor test cases — they won't trigger skills regardless of description quality. **Skill Loading Precedence:** Skills are loaded in this order (highest to lowest precedence): 1. `/skills/` — Per-agent 2. `/.agents/skills/` — Per-workspace agent 3. `~/.agents/skills/` — Shared agent profile 4. `~/.openclaw/skills/` — Shared (all agents) 5. Bundled skills — Global This means workspace-specific skills override shared skills, and shared skills override bundled ones. --- ### Package and Present Package the skill for distribution: ```bash python -m scripts.package_skill ``` **Distribution methods**: 1. **Directory structure**: Copy the entire skill directory to the appropriate location (`workspace/skills/`, `~/.agents/skills/`, or `~/.openclaw/skills/`) 2. **Packaged skill**: The `package_skill.py` script creates a packaged version that can be shared After packaging: - If a `.skill` file is created, tell the user where to find it - If the skill is packaged as a directory, tell the user to copy it to the appropriate skill location **To install a skill**: ```bash # Copy to workspace cp -r ~/.openclaw/workspace/skills/ # Or copy to shared skills cp -r ~/.openclaw/skills/ # Then restart gateway or start a new session /new # or openclaw gateway restart # Verify skill loaded openclaw skills list ``` --- --- ## CLI-Specific Instructions (Without Subagent Support) In CLI environments without subagent support, the core workflow is the same (draft → test → review → improve → repeat), but some mechanics change. **Running test cases**: Without subagents, no parallel execution. For each test case, read the skill's SKILL.md, then follow its instructions to accomplish the test prompt yourself. Do them one at a time. This is less rigorous than independent subagents (you wrote the skill and you're also running it, so you have full context), but it's a useful sanity check — and the human review step compensates. Skip the baseline runs — just use the skill to complete the task as requested. **Reviewing results**: If you can't open a browser, skip the browser reviewer entirely. Instead, present results directly in the conversation. For each test case, show the prompt and the output. If the output is a file the user needs to see (like a .docx or .xlsx), save it to the filesystem and tell them where it is so they can download and inspect it. Ask for feedback inline: "How does this look? Anything you'd change?" **Benchmarking**: Skip the quantitative benchmarking — it relies on baseline comparisons which aren't meaningful without subagents. Focus on qualitative feedback from the user. **The iteration loop**: Same as before — improve the skill, rerun the test cases, ask for feedback — just without the browser reviewer in the middle. You can still organize results into iteration directories on the filesystem if you have one. **Blind comparison**: Requires subagents. Skip it. **Packaging**: The `package_skill.py` script works anywhere with Python and a filesystem. You can run it and the user can use the resulting `.skill` file or directory. **Updating an existing skill**: The user might be asking you to update an existing skill, not create a new one. In this case: - **Preserve the original name.** Note the skill's directory name and `name` frontmatter field — use them unchanged. - **Copy to a writeable location before editing.** The installed skill path may be read-only. Copy to a workspace location or `/tmp/skill-name/`, edit there, and package from the copy. - **Check skill location**: Skills can be in `workspace/skills/`, `workspace/.agents/skills/`, `~/.agents/skills/`, or `~/.openclaw/skills/`. Verify the right location before editing. --- ## Reference files The agents/ directory contains instructions for specialized subagents. Read them when you need to spawn the relevant subagent. - `agents/grader.md` — How to evaluate assertions against outputs - `agents/comparator.md` — How to do blind A/B comparison between two outputs - `agents/analyzer.md` — How to analyze why one version beat another The references/ directory has additional documentation: - `references/schemas.md` — JSON structures for evals.json, grading.json, etc. --- Repeating one more time the core loop here for emphasis: - Figure out what the skill is about - **Reference the Prompt Optimization Framework** to choose the right prompt technique - Draft or edit the skill (using pattern-specific guidelines from the framework) - Run the agent with the skill loaded on test prompts - With the user, evaluate the outputs: - Create benchmark.json and run `eval-viewer/generate_review.py` to help the user review them - Run quantitative evals - Repeat until you and the user are satisfied (use framework principles to generalize improvements) - Package the final skill and return it to the user. **Remember**: The `prompt-optimization-framework.md` is your companion throughout this process. It ensures your skills use best practices from the latest prompt engineering research, making them more effective and maintainable. Please add steps to your TodoList, if you have such a thing, to make sure you don't forget. Good luck!