
Skill Architecture
- 122 installs
- 62 repo stars
- Updated August 3, 2026
- terrylica/cc-skills
Use skill-architecture for development tasks
About
skill-architecture: A skill for development. This provides functionality for development workflows.
- skill-architecture
Skill Architecture by the numbers
- 122 all-time installs (skills.sh)
- +1 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #2,825 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/terrylica/cc-skills --skill skill-architectureAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 122 |
|---|---|
| repo stars | ★ 62 |
| Last updated | August 3, 2026 |
| Repository | terrylica/cc-skills ↗ |
What it does
Use skill-architecture for development tasks
Files
Skill Architecture
Comprehensive guide for creating effective Claude Code skills following Anthropic's official standards with emphasis on security and progressive disclosure architecture.
Self-Evolving Skill: This skill improves through use. If instructions are wrong, parameters drifted, or a workaround was needed — fix this file immediately, don't defer. Only update for real, reproducible issues.
Scope: Claude Code Agent Skills (~/.claude/skills/), not Claude.ai API skillsSelf-Evolution Protocol
This skill — and every skill it creates — must actively evolve through use. This section is placed first because it governs all other sections.
During execution, watch for these signals: friction in instructions, missing edge cases, better patterns discovered, repeated manual steps, drift between documentation and reality.
Before writing any change, pass all three admission gates:
| Gate | Question | Fail → |
|---|---|---|
| VALUE | Does this fix a real problem observed empirically, not speculated? | Skip |
| REDUNDANCY | Is this already documented or obvious from the code? | Skip |
| FRESHNESS | Will this still be true next month, or is it ephemeral? | Skip |
Most executions should produce no evolution. Convergence to stability is success, not stagnation.
When all gates pass: Pause current work → fix SKILL.md or references → log in evolution-log.md with trigger + evidence → resume. Do NOT defer — the next invocation inherits whatever you leave behind.
What never passes the gate: Major structural changes (discuss with user first), speculative improvements without empirical evidence, cosmetic preferences.
---
When to Use This Skill
Use this skill when:
- Creating new Claude Code skills from scratch
- Learning skill YAML frontmatter and structure requirements
- Validating skill file format and portability
- Understanding progressive disclosure patterns for skills
---
Task Templates
Select the appropriate template before starting skill work -- templates encode common workflows and prevent missing steps that cause silent failures.
See Task Templates for all templates (A-F) and the quality checklist.
| Template | Purpose |
|---|---|
| A | Create New Skill |
| B | Update Existing Skill |
| C | Add Resources to Skill |
| D | Convert to Self-Evolving Skill |
| E | Troubleshoot Skill Not Triggering |
| F | Create Lifecycle Suite |
---
Post-Change Checklist (Self-Maintenance)
After modifying THIS skill (skill-architecture):
1. [ ] Templates and 6 Steps tutorial remain aligned 2. [ ] Skill Quality Checklist reflects current best practices 3. [ ] All referenced files in references/ exist 4. [ ] Append changes to evolution-log.md 5. [ ] Update user's CLAUDE.md if triggers changed
---
---
About Skills
Skills are modular, self-contained packages that extend Claude's capabilities with specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific domains -- transforming Claude from general-purpose to specialized agent with procedural knowledge no model fully possesses.
What Skills Provide
1. Specialized workflows - Multi-step procedures for specific domains 2. Tool integrations - Instructions for working with specific file formats or APIs 3. Domain expertise - Company-specific knowledge, schemas, business logic 4. Bundled resources - Scripts, references, assets for complex/repetitive tasks
Skill Discovery and Precedence
Skills are discovered from multiple locations. When names collide, higher-precedence wins:
1. Enterprise (managed settings) -- highest 2. Personal (~/.claude/skills/) 3. Project (.claude/skills/ in repo) 4. Plugin (namespaced: plugin:skill-name) 5. Nested (monorepo .claude/skills/ in subdirectories -- auto-discovered) 6. `--add-dir` (CLI flag, live change detection) -- lowest
Management commands:
claude plugin enable <name>/claude plugin disable <name>-- toggle pluginsclaude skill list-- show all discovered skills with source location
Monorepo support: Claude Code automatically discovers .claude/skills/ directories in nested project roots within a monorepo. No configuration needed.
---
cc-skills Plugin Architecture
This section applies specifically to the cc-skills marketplace plugin structure. Generic standalone skills are unaffected.
Canonical Structure
plugins/<plugin>/
└── skills/
└── <skill-name>/
└── SKILL.md <- single canonical file (context AND user-invocable)skills/<name>/SKILL.md is the single source of truth. The separate commands/ layer was eliminated -- it required maintaining two identical files per skill and caused Skill() invocations to return "Unknown skill". See migration issue for full context.
How Skills Become Slash Commands
Two install paths, both supported:
| Path | Mechanism | Notes |
|---|---|---|
| Automated (primary) | mise run release:full -> sync-commands-to-settings.sh reads skills/*/SKILL.md -> writes ~/.claude/commands/<plugin>:<name>.md | Fully automated post-release. Bypasses Anthropic cache bugs #17361, #14061 |
| Official CLI | claude plugin install itp@cc-skills -> reads from skills/ in plugin cache | Cache may not refresh on update -- use claude plugin update after new releases |
Hooks
sync-hooks-to-settings.sh reads hooks/hooks.json directly -> merges into ~/.claude/settings.json. Bypasses path re-expansion bug #18517.
Creating a New Skill in cc-skills
Place the SKILL.md under plugins/<plugin>/skills/<name>/SKILL.md. No commands/ copy needed. The validator (bun scripts/validate-plugins.mjs) checks frontmatter completeness.
---
Skill Creation Process
See Creation Tutorial for the detailed 6-step walkthrough, or Creation Workflow for the comprehensive guide with examples.
Quick summary: Gather requirements -> Plan resources -> Initialize -> Edit SKILL.md -> Validate -> Register and iterate.
---
Testing and Iteration
Good skills emerge through testing and feedback, not from getting the first draft perfect. After writing or updating a skill, verify it works by running it against realistic prompts.
Write Test Prompts
Come up with 2-3 realistic test prompts -- the kind of thing a real user would actually say. Not abstract requests, but concrete tasks with enough detail to exercise the skill. Share them with the user for confirmation before running.
Run and Evaluate
For each test prompt, run the skill and examine the output:
- Did the skill trigger? If not, the description may need stronger trigger language.
- Did it follow the workflow? Check whether instructions were followed or ignored.
- Was the output useful? Compare against what you'd expect from a skilled human.
When subagents are available, run with-skill and without-skill versions in parallel to measure the skill's actual value-add. When not available, run test cases yourself as a sanity check.
Iterate Based on Feedback
After evaluating results, improve the skill and retest. Keep iterating until the user is satisfied or feedback is consistently positive. Key principles for each iteration:
1. Generalize from specific feedback. Skills will be used across many different prompts. Avoid overfitting to test cases with fiddly, narrow fixes. If a pattern keeps failing, try a different approach or metaphor rather than adding more constraints.
2. Keep the skill lean. Every section must earn its tokens. Read the execution transcripts -- if the skill causes the model to waste time on unproductive steps, cut those instructions and see what happens.
3. Explain the why, not just the what. LLMs respond better to understanding _why_ a rule exists than to being commanded with rigid directives. Instead of "ALWAYS do X", explain: "Do X because skipping it causes Y, which leads to Z." This produces more robust behavior that generalizes to novel situations.
4. Look for repeated work across test cases. If every test run independently creates the same helper script or takes the same multi-step approach, bundle that script in scripts/ so future invocations don't reinvent the wheel.
5. Bundle common patterns as scripts. When test runs reveal that the model writes similar boilerplate code every time, extract it into a bundled script. This saves tokens and improves reliability.
---
Skill Writing Principles
These principles (aligned with Anthropic's official guidance) apply to all skill content:
- Imperative form: "Run the script", "Check the output" -- not passive or indirect phrasing.
- Explain reasoning over rigid rules: If you find yourself writing MUST/NEVER/ALWAYS in all caps, that's a signal to reframe. Explain the reasoning so the model internalizes the principle rather than treating it as an arbitrary constraint. The model is smart -- help it understand, don't just command it.
- Pushy descriptions for triggering: Claude tends to undertrigger skills. Descriptions should actively claim territory: "Use this skill whenever the user mentions X, Y, or Z, even if they don't explicitly ask for it." Include negative triggers too: "Do NOT use for A or B."
- Natural language descriptions: Write descriptions as sentences a human could read, not keyword lists. "Use this skill whenever..." is better than "TRIGGERS - keyword1, keyword2".
- Keep execution out of descriptions: Descriptions tell Claude _when_ to trigger. The skill body tells Claude _how_ to execute. Don't mix them.
See Writing Guide for extended guidance with examples.
---
Skill Anatomy
skill-name/
├── SKILL.md # Required: YAML frontmatter + instructions
├── scripts/ # Optional: Executable code (Python/Bash)
├── references/ # Optional: Documentation loaded as needed
│ └── evolution-log.md # Required for self-evolving: Change history
└── assets/ # Optional: Files used in outputYAML Frontmatter (Required)
See YAML Frontmatter Reference for the complete field reference, invocation control table, permission rules, description guidelines, and YAML pitfalls.
Minimal example:
---
name: my-skill
description: Does X when user mentions Y. Use for Z workflows.
---Key rules: name is lowercase-hyphen, description is single-line max 1024 chars with trigger keywords, no colons in description text.
Progressive Disclosure (3 Levels)
Skills use progressive loading to manage context efficiently:
1. Metadata (name + description) - Always in context (~100 words) 2. SKILL.md body - When skill triggers (<5k words) 3. Bundled resources - As needed by Claude (unlimited\*)
\*Scripts can execute without reading into context.
Skill Description Budget
Skills are loaded into the context window based on description relevance. Large skills may be excluded if the budget is exceeded:
- Budget: ~2% of context window (16K character fallback)
- Check: Run
/contextto see which skills are loaded vs excluded - Override: Set
SLASH_COMMAND_TOOL_CHAR_BUDGETenv var to increase budget - Mitigation: Keep SKILL.md body lean, move detail to
references/
---
Bundled Resources
Skills can include scripts/, references/, and assets/ directories. See Progressive Disclosure for detailed guidance on when to use each.
---
CLI-Specific Features
CLI skills support allowed-tools for granting tool access without per-use approval. See Security Practices for details.
String Substitutions
Skill bodies support these substitutions (resolved at load time):
| Variable | Resolves To | Example |
|---|---|---|
$ARGUMENTS | Full argument string from /name arg1 arg2 | Process: $ARGUMENTS |
$ARGUMENTS[N] | Nth argument (0-indexed) | File: $ARGUMENTS[0] |
$N | Shorthand for $ARGUMENTS[N] | $0 = first arg |
${CLAUDE_SESSION_ID} | Current session UUID | Log correlation |
Dynamic Context Injection
Use the pattern ! + ` command ` (exclamation mark followed by a backtick-wrapped command) in skill body to inject command output at load time:
Current branch: <exclamation>`git branch --show-current`
Last commit: <exclamation>`git log -1 --oneline`(Replace <exclamation> with ! in actual usage.)
The command runs when the skill loads -- output replaces the pattern inline.
Extended Thinking
Include the keyword ultrathink in a skill body to enable extended thinking mode for that skill's execution.
---
Structural Patterns
See Structural Patterns for detailed guidance on:
1. Workflow Pattern - Sequential multi-step procedures 2. Task Pattern - Specific, bounded tasks 3. Reference Pattern - Knowledge repository 4. Capabilities Pattern - Tool integrations 5. Suite Pattern - Multi-skill lifecycle management (bootstrap, operate, diagnose, configure, upgrade, teardown)
---
User Conventions Integration
This skill follows common user conventions:
- Absolute paths: Always use full paths (terminal Cmd+click compatible)
- Unix-only: macOS, Linux (no Windows support)
- Python:
uv run script.pywith PEP 723 inline dependencies - Planning: OpenAPI 3.1.1 specs when appropriate
---
Marketplace Scripts
See Scripts Reference for marketplace script usage.
---
Reference Documentation
For detailed information, see:
- Task Templates - Templates A-F and quality checklist
- Creation Tutorial - 6-step creation process walkthrough
- YAML Frontmatter - Field reference, invocation control, description guidelines
- Structural Patterns - 5 skill architecture patterns (including Suite Pattern)
- Workflow Patterns - Workflow skill implementation patterns
- Progressive Disclosure - Context management patterns
- Creation Workflow - Step-by-step process with examples
- Scripts Reference - Marketplace script usage
- Security Practices - Threats and defenses (CVE references)
- Phased Execution - Preflight/Execute/Verify/Reflect/Rectify patterns and variants
- Post-Execution Reflection - Compulsory self-rectification pattern for stepwise skills
- Theory: Self-Evolving Skills - Research synthesis from Gemini DR #70 (6 threads)
- Invocation Control - Skill invocation modes, permission rules, legacy commands migration
- Interactive Patterns - AskUserQuestion integration patterns
- Token Efficiency - Context optimization
- Advanced Topics - CLI vs API, composition, bugs
- Path Patterns - Safe/unsafe path references (known bugs documented)
- Bash Compatibility - Shell portability patterns
- Validation Reference - Quality checklist
- Writing Guide - Tone, reasoning-based instructions, description optimization
- Script Design - Designing scripts for agentic consumption
- Troubleshooting - Common issues and solutions
- SYNC-TRACKING - Marketplace version tracking
- Evolution Log - This skill's change history
---
Post-Execution Reflection (Compulsory)
This section is placed last so it is the final thing processed before the skill exits — maximizing recency effect.
Every skill MUST include a Post-Execution Reflection section — workflow skills, task skills, and capability skills alike. This is a structural requirement, not advisory. Without it, errors and drift repeat silently across sessions. Task-pattern skills are just as susceptible: scripts change interfaces, parameters get added, error messages drift from documentation.
After this skill completes, reflect before closing
0. Locate yourself. — Find this SKILL.md's canonical path (Glob for this skill's name) before editing. All corrections target THIS file and its sibling references/ — never other documentation. 1. What failed? — Fix the instruction that caused it. If it could recur, add it as an anti-pattern. 2. What worked better than expected? — Promote it to recommended practice. Document why. 3. What drifted? — Any script, reference, or external dependency that no longer matches reality gets fixed now. 4. Pass the admission gates. — Apply the Self-Evolution Protocol (top of this file). VALUE + REDUNDANCY + FRESHNESS must all pass before writing any change. 5. Log it. — Every change gets an evolution-log entry with trigger, fix, and evidence.
Do NOT defer. The next invocation inherits whatever you leave behind.
Template: Workflow / Stepwise Skills
For skills with multiple phases, evolution-log, and references/:
## Post-Execution Reflection
After this skill completes, reflect before closing the task:
0. **Locate yourself.** — Find this SKILL.md's canonical path before editing.
1. **What failed?** — Fix the instruction that caused it.
2. **What worked better than expected?** — Promote to recommended practice.
3. **What drifted?** — Fix any script, reference, or dependency that no longer matches reality.
4. **Log it.** — Evolution-log entry with trigger, fix, and evidence.
Do NOT defer. The next invocation inherits whatever you leave behind.Template: Task-Pattern Skills
For single-action skills wrapping a CLI command or script:
## Post-Execution Reflection
After this skill completes, check before closing:
1. **Did the command succeed?** — If not, fix the instruction or error table that caused the failure.
2. **Did parameters or output change?** — If the script's interface drifted, update Usage examples and Parameters table to match.
3. **Was a workaround needed?** — If you had to improvise (different flags, extra steps), update this SKILL.md so the next invocation doesn't need the same workaround.
Only update if the issue is real and reproducible — not speculative.See Post-Execution Reflection Reference for the full pattern, validation requirements, and examples.
Skill: Skill Architecture
Part 2.5: Critical Formatting Bugs (MUST READ)
🚨 BUG #9817: Multiline Description Footgun
CRITICAL: Skills with multiline descriptions are silently ignored - no error message!
What breaks (silently ignored):
---
name: my-skill
description: This description wraps to multiple lines
and will be silently ignored by Claude
---What works (single line):
---
name: my-skill
description: This description stays on one line and works correctly.
---How to prevent:
- ✅ Keep description under 180 characters (safe from Prettier wrapping)
- ✅ Use third person ("Reads files...") not imperative ("Read files...")
- ✅ Test with
/clearand trigger keywords after creating skill - ✅ If skill doesn't activate, check description length/format first
Why it happens: Prettier with proseWrap: true reformats long descriptions to wrap across lines. Claude Code's YAML parser silently fails on multiline descriptions. This is a known footgun tracked in Issue #9817.
Validation checklist:
- [ ] Description is single line (check with
head -5 SKILL.md) - [ ] Description uses third person ("Does X", not "Do X")
- [ ] Description under 200 chars (CLI max is 1024 but Prettier wraps ~80)
- [ ] Test activation with
/clearand trigger keywords
Part 4: Content Sections (Recommended)
After YAML frontmatter, organize content:
````markdown
Agent Skill Name
Brief introduction (1-2 sentences).
Instructions
Step-by-step guidance in imperative mood:
1. Read the file using Read tool 2. Process content with scripts/helper.py 3. Verify output
Examples
Concrete usage:
Input: process_data.csv
Action: Run scripts/validate.py && scripts/process.py
Output: cleaned_data.csv with 1000 rowsReferences
For detailed API specs, see reference.md. For advanced examples, see examples.md. ````
Writing style:
- ✅ Imperative: "Read the file", "Run the script"
- ❌ Suggestive: "You should read", "Maybe try"
---
Part 5: Agent Skill Composition & Limitations
What Agent Skills CAN'T Do
❌ Explicitly reference other Agent Skills:
# ❌ WRONG - Agent Skills can't call each other directly
"First use the api-auth skill, then use api-client skill"What Agent Skills CAN Do
✅ Claude uses multiple Agent Skills automatically:
- If both
api-authandapi-clientare relevant, Claude loads both - No explicit coordination needed
- Agent Skills work together organically based on descriptions
---
Part 6: Claude Code vs API Differences
| Feature | Claude Code | Claude.ai API |
|---|---|---|
| File name | SKILL.md (uppercase) | SKILL.md (uppercase) |
| Location | ~/.claude/skills/ | ZIP upload |
| Description limit | 1024 characters | Max 1024 chars |
allowed-tools | ✅ Supported | ❌ Not supported |
| Privacy | Personal or project | Individual account only |
| Package install | claude plugin install / marketplace | Pre-installed only |
Plugin-Level Features
Plugins (which contain skills) support additional configuration beyond individual skill frontmatter:
| Feature | Purpose | Defined In |
|---|---|---|
outputStyles | Custom formatting rules for skill output | plugin.json |
lspServers | Language server integrations | plugin.json |
mcpServers | Model Context Protocol server connections | plugin.json |
settings | Default settings applied when plugin enabled | plugin.json |
This Agent Skill teaches CLI format only.
---
Known Issue Table Pattern
For skills that handle troubleshooting, use a structured table mapping symptoms to fixes. Place the table in the SKILL.md body for immediate access during diagnostics.
Table Structure
| Column | Content | Example |
|---|---|---|
| Issue | User-visible symptom | "No output produced" |
| Likely Cause | Technical root cause | "Stale lock file prevents execution" |
| Diagnostic | Command to confirm | stat /path/to/lock && cat /path/to/lock |
| Fix | Command to resolve | rm -f /path/to/lock |
Example
| Issue | Likely Cause | Diagnostic | Fix |
| ---------------------- | ------------------- | ---------------------- | -------------------------- |
| No output | Stale lock file | `stat /tmp/app.lock` | `rm -f /tmp/app.lock` |
| Service not responding | Process crashed | `pgrep -la service` | Restart service |
| Slow performance | CPU fallback active | Check GPU availability | Reinstall with GPU support |
| Double execution | Race condition | Check lock age + PID | Kill duplicate, clean lock |Design Guidelines
1. Keep in SKILL.md body: The table should load immediately when the diagnostic skill triggers (Level 2 content) 2. Detail in references: Create references/common-issues.md with expanded diagnostic procedures per issue 3. Resolution trees: For complex issues with multiple possible causes, use branching logic in references 4. Cross-reference skills: When the fix requires another skill (e.g., "run the health check skill"), name it explicitly 5. Maintain actively: Update the table when new issues are discovered during real usage
Integration with Symptom Collection
Combine with Interactive Patterns Pattern 4 (Symptom Collection):
1. Collect symptoms via AskUserQuestion 2. Match symptoms against Known Issue Table 3. Run the Diagnostic command to confirm 4. Apply the Fix 5. Verify resolution
---
Hook Integration Pattern
Plugins can include hooks for event-driven automation that runs outside of conversation context. Hooks execute on Claude Code lifecycle events (session start, tool use, session stop).
Structure
my-plugin/
├── hooks/
│ ├── hooks.json # Hook registration (declarative)
│ └── my-event-handler.ts # Hook implementationhooks.json Format
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "bun $HOME/.claude/plugins/marketplaces/cc-skills/plugins/my-plugin/hooks/my-handler.ts",
"timeout": 10000
}
]
}
]
}
}Available events: PreToolUse, PostToolUse, Stop (see Hooks Development Guide in repo docs)
Anti-Pattern: `$CLAUDE_PLUGIN_ROOT` in hooks.json
>
$CLAUDE_PLUGIN_ROOTis available inside Claude Code's plugin execution context (skill loading) but is NOT a shell environment variable. Hook commands fromhooks.jsonare synced verbatim to~/.claude/settings.jsonand executed as shell commands, where$CLAUDE_PLUGIN_ROOTresolves to empty string → "Module not found" errors.
>
| Variable | Available In | Works in hooks.json? |
| --------------------- | ------------------------- | -------------------- |
| $CLAUDE_PLUGIN_ROOT | Plugin skill loading only | NO || $HOME | All shell contexts | YES || $CLAUDE_PROJECT_DIR | Hook stdin JSON only | NO (not env var) |>
Always use `$HOME`-based absolute paths in hooks.json commands.
When to Use Hooks
- Cross-session automation: Notifications when a session ends
- Event-driven actions: Validate tool output, enforce policies
- Integration with external systems: Send alerts to messaging platforms
- Telemetry: Log session activity for audit or analysis
Design Guidelines
1. Hooks run outside conversation - No user interaction (no AskUserQuestion) 2. Respect timeout - Keep execution fast (typically 10s max) 3. Fail silently - Hooks should not block Claude Code operation on failure 4. File-based communication - Write to notification directories rather than calling APIs directly from hooks 5. Provide a management command - Include a /plugin:hooks command for install/uninstall/status (see Command-Skill Duality) 6. Use `$HOME`-based absolute paths - Never use $CLAUDE_PLUGIN_ROOT in hook commands (see anti-pattern above)
Bash Compatibility for Skills
This reference documents the mandatory bash compatibility patterns for skill files.
ADR: Skill Bash Compatibility Enforcement
Problem
Claude Code's Bash tool on macOS runs through zsh by default. Bash-specific syntax fails:
| Pattern | Error in Zsh |
|---|---|
declare -A | bad substitution |
VAR=$(cmd) other-cmd | parse error near '(' |
[[ $x =~ regex ]] + BASH_REMATCH | undefined variable |
\!= (escaped) | condition expected |
grep -oP | invalid option (no PCRE) |
Mandatory Pattern
All bash code blocks in skill files MUST use heredoc wrapper:
/usr/bin/env bash << 'SCRIPT_NAME_EOF'
# Your bash script here
# All bash-specific syntax works inside heredoc:
declare -A MAP
MAP["key"]="value"
if [[ "$var" =~ pattern ]]; then
echo "${BASH_REMATCH[1]}"
fi
RESULT=$(some_command)
echo "$RESULT"
SCRIPT_NAME_EOFWhy This Works
1. /usr/bin/env bash - Invokes bash explicitly (portable across macOS, Linux, BSD) 2. << 'NAME_EOF' - Heredoc with quoted delimiter prevents variable expansion in the outer shell 3. All bash syntax inside the heredoc is interpreted by bash, not zsh
Prohibited Patterns
| Pattern | Why | Fix |
|---|---|---|
declare -A NAME | Bash 4+ only, fails in zsh | Use parallel indexed arrays |
grep -oP | Perl regex not portable | Use grep -oE + awk |
$'\n' | ANSI-C quoting | Use literal newlines |
\!= in [[ ]] | Unnecessary escape | Use != directly |
Unwrapped $(...) | Fails in inline assignment | Wrap entire block in heredoc |
Parallel Indexed Arrays (Replacing declare -A)
/usr/bin/env bash << 'BASH_COMPATIBILITY_SCRIPT_EOF'
# ❌ WRONG: Associative array (bash 4+ only)
declare -A ACCOUNTS
ACCOUNTS["alice"]="ssh-key"
ACCOUNTS["bob"]="gh-cli"
# ✅ CORRECT: Parallel indexed arrays
ACCOUNT_NAMES=()
ACCOUNT_SOURCES=()
add_account() {
local name="$1" source="$2"
for idx in "${!ACCOUNT_NAMES[@]}"; do
if [[ "${ACCOUNT_NAMES[$idx]}" == "$name" ]]; then
ACCOUNT_SOURCES[$idx]+="$source "
return
fi
done
ACCOUNT_NAMES+=("$name")
ACCOUNT_SOURCES+=("$source ")
}
add_account "alice" "ssh-key"
add_account "bob" "gh-cli"
BASH_COMPATIBILITY_SCRIPT_EOFPortable Regex (Replacing grep -P)
/usr/bin/env bash << 'MISE_EOF'
# ❌ WRONG: Perl regex (not available on all systems)
account=$(grep -oP '(?<=GH_ACCOUNT=")[^"]+' .mise.toml)
# ✅ CORRECT: Extended regex + awk
account=$(grep -E 'GH_ACCOUNT\s*=' .mise.toml | sed 's/.*=\s*"\([^"]*\)".*/\1/')
MISE_EOFHeredoc Naming Convention
Use descriptive EOF markers matching the script purpose:
| Script Purpose | EOF Marker |
|---|---|
| Preflight checks | PREFLIGHT_EOF |
| Account detection | DETECT_ACCOUNTS_EOF |
| Setup scripts | SETUP_ORPHAN_EOF |
| Validation | VALIDATE_EOF |
| Configuration | CONFIG_EOF |
Examples
Skill SKILL.md
## Preflight Check
\`\`\`bash
/usr/bin/env bash << 'PREFLIGHT_EOF'
MISSING=()
for tool in git gh jq; do
command -v "$tool" &>/dev/null || MISSING+=("$tool")
done
if [[${#MISSING[@]} -gt 0]]; then
echo "Missing: ${MISSING[*]}"
exit 1
fi
echo "All tools installed"
PREFLIGHT_EOF
\`\`\`Command File (commands/\*.md)
## Execute
\`\`\`bash
/usr/bin/env bash << 'COMMAND_EOF'
PROJECT_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}"
if [[-f "$PROJECT_DIR/.claude/config.json"]]; then
cat "$PROJECT_DIR/.claude/config.json" | python3 -m json.tool
else
echo "Config not found"
fi
COMMAND_EOF
\`\`\`Validation
Run the validation script to check for bash compatibility issues:
# Marketplace plugins (strict)
bun run plugins/plugin-dev/scripts/validate-skill.ts plugins/your-plugin/skills/your-skill/
# Project-local skills with documentation-only bash blocks
bun run plugins/plugin-dev/scripts/validate-skill.ts .claude/skills/your-skill/ --skip-bashThe validator checks for:
- Bash blocks without heredoc wrapper (ERROR if contains
$(),[[, etc.) declare -Ausage (ERROR)grep -Pusage (WARNING)
Note: Use --skip-bash for project-local skills where bash blocks are user-facing documentation examples (not executed by Claude). This is common for workflow/tutorial skills.
To auto-fix bash blocks by adding heredoc wrappers:
bun run plugins/plugin-dev/scripts/fix-bash-blocks.ts plugins/your-plugin/ --dry # Preview
bun run plugins/plugin-dev/scripts/fix-bash-blocks.ts plugins/your-plugin/ # ApplyReference
Skill: Skill Architecture
Skill Creation Process (Detailed Tutorial)
Note: Use Task Templates for execution. This section provides detailed context for each phase.
Step 1: Understanding the Skill with Concrete Examples
Clearly understand concrete examples of how the skill will be used. Ask users:
- "What functionality should this skill support?"
- "Can you give examples of how it would be used?"
- "What would trigger this skill?"
Skip only when usage patterns are already clearly understood.
Step 2: Planning Reusable Contents
Analyze each example to identify what resources would be helpful:
Example 1 - PDF Editor:
- Rotating PDFs requires rewriting code each time
- -> Create
scripts/rotate_pdf.py
Example 2 - Frontend Builder:
- Webapps need same HTML/React boilerplate
- -> Create
assets/hello-world/template
Example 3 - BigQuery:
- Queries require rediscovering table schemas
- -> Create
references/schema.md
Step 3: Initialize the Skill
Run the init script from plugin-dev:
uv run plugins/plugin-dev/scripts/skill-creator/init_skill.py <skill-name> --path <target-path>Creates: skill directory + SKILL.md template + example resource directories
Step 4: Edit the Skill
Writing Style: Imperative/infinitive form (verb-first), not second person
- "To accomplish X, do Y"
- "You should do X"
SKILL.md must include:
1. What is the purpose? (few sentences) 2. When should it be used? (trigger keywords in description) 3. How should Claude use bundled resources? 4. Task Templates - Pre-defined tasks for common scenarios 5. Post-Change Checklist - Self-maintenance verification
Start with resources (scripts/, references/, assets/), then update SKILL.md
Step 5: Validate the Skill
For local development (validation only, no zip creation):
uv run plugins/plugin-dev/scripts/skill-creator/quick_validate.py <path/to/skill-folder>For distribution (validates AND creates zip):
uv run plugins/plugin-dev/scripts/skill-creator/package_skill.py <path/to/skill-folder>Validates: YAML frontmatter, naming, description, file organization
Note: Use quick_validate.py for most workflows. Only use package_skill.py when actually distributing the skill to others.
Step 6: Register and Iterate
1. Register skill in project CLAUDE.md (Workspace Skills section) 2. Use skill on real tasks 3. Notice struggles/inefficiencies 4. Update SKILL.md or resources 5. Test again 6. Verify against Skill Quality Checklist
Skill: Skill Architecture
Creation Workflow
Step-by-step process for creating effective skills, merging marketplace best practices with security-focused approach.
Overview
Two complementary workflows:
1. Marketplace 6-Step Process (comprehensive, uses scripts) 2. Manual Creation (lightweight, no scripts)
Choose based on complexity and tooling preferences.
---
Marketplace 6-Step Process (Recommended)
Step 1: Understanding with Concrete Examples
Gather real examples of how the skill will be used.
Questions to ask:
- "What functionality should this skill support?"
- "Can you give examples of how it would be used?"
- "What would trigger this skill?"
- "What file types or domains are involved?"
- "Is this part of a larger lifecycle? (bootstrap, operate, diagnose, upgrade, teardown)"
- "Does the user need to make choices? (intent branching, configuration selection)"
Example conversation:
User: "I need help rotating PDFs"
You: "What else besides rotation? Merging? Splitting?"
User: "Yes, and extracting text"
You: "What would you say to trigger this? 'Rotate this PDF'?"Output: Clear list of use cases and trigger phrases
Step 2: Planning Reusable Contents
Analyze each use case to identify resources needed.
Decision matrix:
| Task Type | Resource Type | Example |
|---|---|---|
| Repeated code | scripts/ | PDF rotation algorithm |
| Domain knowledge | references/ | Database schemas, API docs |
| Templates/assets | assets/ | HTML boilerplate, config files |
| Simple workflows | SKILL.md only | Basic instructions |
| Multi-component integration | Suite Pattern | Full lifecycle: bootstrap through teardown |
| Branching/destructive workflow | Interactive | AskUserQuestion for confirmation/selection |
| Multiple scripts sharing logic | Shared Library | scripts/lib/common.sh |
Example analysis:
- "Rotating PDFs" → Code repeated each time →
scripts/rotate_pdf.py - "Database queries" → Schema not memorized →
references/schema.md - "Frontend apps" → Same boilerplate →
assets/template/
Step 3: Initialize with Script
Use init script for proper structure:
uv run plugins/plugin-dev/scripts/skill-creator/init_skill.py pdf-editor --path ~/.claude/skills/Creates:
~/.claude/skills/pdf-editor/
├── SKILL.md (template with TODOs)
├── scripts/
│ └── example_script.py (delete if not needed)
├── references/
│ └── example_reference.md (delete if not needed)
└── assets/
└── example_asset.txt (delete if not needed)Delete unused directories - Most skills don't need all three.
Step 4: Edit the Skill
A. Start with Resources
Implement planned resources from Step 2:
Step 4.1: Bash Compatibility Check (MANDATORY)
If your skill contains bash code blocks:
1. Wrap all code blocks with heredoc:
/usr/bin/env bash << 'YOUR_SCRIPT_EOF'
# ... your bash code ...
YOUR_SCRIPT_EOF2. Avoid non-portable patterns:
- ❌
declare -A→ ✅ parallel indexed arrays - ❌
grep -P→ ✅grep -E+ awk - ❌
BASH_REMATCHoutside heredoc → ✅ inside heredoc - ❌
\!=in conditionals → ✅!=directly
3. Run validation:
bun run plugins/plugin-dev/scripts/validate-links.ts plugins/your-plugin/skills/your-skill/See Bash Compatibility Reference for detailed patterns and examples.
- Write scripts in
scripts/ - Document schemas/APIs in
references/ - Add templates to
assets/
May require user input (brand assets, credentials, etc.)
B. Update SKILL.md
Answer three questions:
1. What is the purpose? (2-3 sentences) 2. When should it be used? (Trigger keywords!) 3. How to use bundled resources? (Commands, examples)
Writing style: Imperative form (verb-first)
- ✅ "To rotate a PDF, run
scripts/rotate_pdf.py <file> <degrees>" - ❌ "You can rotate PDFs by running..."
C. Update Description
Critical for skill discovery:
---
description: Extract text and tables from PDFs, rotate pages, merge documents. Use when working with PDF files or when user mentions forms, contracts, document processing.
---Include:
- WHAT it does (specific capabilities)
- WHEN to use (triggers: file types, keywords, domains)
Step 5: Package and Validate
Run packaging script (validates automatically):
uv run plugins/plugin-dev/scripts/skill-creator/package_skill.py ~/.claude/skills/pdf-editor/Validates:
- [ ] YAML frontmatter format
- [ ] Required fields present
- [ ] Naming conventions
- [ ] Description quality
- [ ] File organization
Output: pdf-editor.zip (if valid)
Step 6: Iterate
1. Test: Use skill on real tasks 2. Observe: Notice struggles or inefficiencies 3. Identify: What needs updating? 4. Implement: Fix SKILL.md or resources 5. Repeat: Test again
Common iterations:
- Add missing trigger keywords to description
- Extract large SKILL.md sections to references/
- Add scripts for repeatedly rewritten code
- Improve examples with real use cases
---
Manual Creation (Lightweight)
For simple skills without scripts/assets:
Step 1: Define Purpose and Triggers
Answer:
- What specific problem does this solve?
- What keywords would users naturally mention?
- What file types or domains?
Step 2: Create Structure
mkdir -p ~/.claude/skills/your-skill-name
touch ~/.claude/skills/your-skill-name/SKILL.mdStep 3: Write YAML Frontmatter
---
name: your-skill-name
description: What this does and when to use it. Include trigger keywords!
allowed-tools: Read, Grep, Bash # Optional, for security
---Step 4: Write Instructions
- Use imperative form
- Be specific and actionable
- Include examples
Example:
## Instructions
1. Check file exists: `ls <file>`
2. Process with: `grep -i "pattern" <file>`
3. Output resultsStep 5: Test Activation
1. Start new conversation (or /clear) 2. Ask question using trigger keywords 3. Verify Claude loads skill (output mentions skill name) 4. Refine description if not activating
Step 6: Security Audit
- [ ] No hardcoded secrets
- [ ] Input validation present
- [ ]
allowed-toolsrestricts dangerous operations - [ ] Tested for prompt injection
- [ ] No unsafe file operations
See Security Practices
---
Common Creation Patterns
See Workflow Patterns for practical examples and workflow comparison.
---
User Conventions (Terry's Standards)
<!-- Link to repo CLAUDE.md removed - not available in installed context -->
When creating skills, follow conventions from ~/.claude/CLAUDE.md:
Relative Paths for Skill Links
Use relative paths for links within the skill:
# From SKILL.md to references/
See [Schema](./references/schema.md)
# From one reference to another
See [Schema](./schema.md)
# From reference back to SKILL.md
See [Main Skill](../SKILL.md)Python Scripts
Use PEP 723 inline dependencies:
# /// script
# dependencies = ["pyyaml>=6.0"]
# ///
import yamlRun with: uv run scripts/process.py
Unix-Only
Specify platform scope:
> ⚠️ **Platform**: macOS, Linux only (no Windows support)Machine-Readable Planning
For complex workflows, reference OpenAPI specs:
See specification: [`specifications/workflow.yaml`](/specifications/workflow.yaml)---
Troubleshooting Creation
"Skill not activating"
Cause: Description doesn't match user query
Fix: Add more trigger keywords
# Before
description: PDF manipulation tool
# After
description: Extract text and tables from PDFs, rotate pages, merge documents. Use when working with PDF files or when user mentions forms, contracts, document processing."SKILL.md too long"
Cause: Too much detail in main file
Fix: Use progressive disclosure
- Move details to
references/ - Keep only essential info in SKILL.md
- Add navigation links
"Skill loaded but fails"
Cause: Instructions unclear or incomplete
Fix:
- Add specific examples
- Include error handling
- Test instructions manually first
"Validation fails"
Cause: Structural or format issues
Fix: Run validation script for details
uv run plugins/plugin-dev/scripts/skill-creator/package_skill.py <skill-path>See error messages for specific issues.
Error Message Style Guide
Standardized conventions for error, warning, and success messages in skill scripts.
Message Prefixes
Shell Scripts
# Errors (stderr, exit non-zero)
echo "ERROR: Description of what failed" >&2
# Warnings (stderr, continue execution)
echo "WARNING: Description of potential issue" >&2
# Success (stdout)
echo "OK: Description of success"
# Progress (stdout, with checkmark)
echo "✓ Task completed successfully"Python Scripts
import sys
# Errors (stderr, exit non-zero)
print("Error: Description of what failed", file=sys.stderr)
sys.exit(1)
# Warnings (stderr, continue execution)
print("Warning: Description of potential issue", file=sys.stderr)
# Success (stdout)
print("OK: Description of success")
# Structured status (for validators)
print("[OK] Check passed")
print("[FAIL] Check failed")
print("[PASS] All checks passed")Capitalization Rules
| Language | Error | Warning | Success |
|---|---|---|---|
| Shell | ERROR: (all caps) | WARNING: (all caps) | OK: or ✓ |
| Python | Error: (title case) | Warning: (title case) | OK: or [OK] |
Output Destination
| Message Type | Destination | Rationale |
|---|---|---|
| Errors | stderr | Separates from normal output, visible even if stdout redirected |
| Warnings | stderr | Non-fatal issues should not pollute stdout |
| Success/Progress | stdout | Normal output flow |
| Debug | stderr | Optional, for troubleshooting |
Anti-Patterns
Avoid these inconsistent patterns found in legacy code:
# BAD: Emoji mixing
echo "❌ ERROR: ..." # Inconsistent with plain ERROR:
# BAD: Leading space
echo " ERROR: ..." # Inconsistent spacing
# BAD: Lowercase in shell
echo "error: ..." # Should be ERROR: in shell
# BAD: Missing colon
echo "ERROR something" # Should be "ERROR: something"Color Codes (Optional)
If using color, define constants at script top:
/usr/bin/env bash << 'ERROR_MESSAGE_STYLE_SCRIPT_EOF'
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
echo -e "${RED}ERROR:${NC} Description"
echo -e "${GREEN}✓${NC} Success"
echo -e "${YELLOW}WARNING:${NC} Caution"
ERROR_MESSAGE_STYLE_SCRIPT_EOFValidator Scripts
For scripts that check multiple conditions, use bracketed notation:
# Individual checks
print("[OK] ADR file exists")
print("[FAIL] Missing YAML frontmatter")
# Final summary
print("\n[PASS] All checks passed")
# or
print("\n[FAIL] 2 checks failed")Migration Checklist
When updating existing scripts:
- [ ] Replace
❌ ERROR:with plainERROR: - [ ] Remove leading spaces from error messages
- [ ] Ensure shell uses
ERROR:(caps) and Python usesError:(title) - [ ] Add
>&2orfile=sys.stderrfor error/warning output - [ ] Use consistent exit codes (0=success, 1=error)
Evolution Log
Convention: Reverse chronological order (newest on top, oldest at bottom). Prepend new entries.
---
2026-03-31: Relocate Self-Evolution for Attention Primacy/Recency
Trigger: Empirical observation over months that the self-evolving mechanism was not firing — skills never evolved despite instructions to do so. Research across 6 GitHub repos, 4 blog posts, and Anthropic's own context window documentation confirmed the root cause.
Root Cause
The self-evolving instructions were buried at lines 52-93 of a 362-line SKILL.md — the attention "dead zone." Research shows:
- Context window quality degrades at 20-40% capacity due to attention dilution (not token exhaustion)
- Instructions at document boundaries (top/bottom) receive disproportionately higher attention weight
- Fully autonomous self-improvement without admission gating produces noise faster than signal
Changes Made
1. New section: "Self-Evolution Protocol" — placed immediately after frontmatter (line 12), before all other content. Contains a 3-gate admission protocol (VALUE, REDUNDANCY, FRESHNESS) that makes "do nothing" the default outcome. 2. Moved "Post-Execution Reflection" — from line 52 (mid-document) to absolute last section (after Reference Documentation) for maximum recency effect. Added step 4 requiring admission gate passage before writing changes. 3. Removed "Continuous Improvement" — consolidated into the Self-Evolution Protocol. The old 5-line section was too weak to trigger behavior. 4. Added cross-reference — Post-Execution Reflection step 4 now explicitly references the admission gates at the top, creating a top↔bottom sandwich.
Key Insight
Placement determines whether instructions get followed. "Attention primacy" (top of document) and "recency effect" (bottom of document) are the two highest-weight positions. Self-evolution instructions must occupy both — the protocol at the top sets the rules, the reflection at the bottom triggers the action. The mid-document position is where instructions go to die.
Sources
- 191341025/Self-Evolving-Skill — Five-Gate Protocol, confidence decay
- KERNEL — deletion as evolution, file-based persistence
- Context Window Degradation (BSWEN) — 20-40% capacity threshold
- nathanonn.com — index-based loading, SKILL.md under 100 lines
---
2026-03-27: Add Compulsory Post-Execution Reflection
Trigger: User identified that agent skills executing stepwise are prone to errors that repeat silently across sessions because skills never learn from their own execution failures. The existing "Continuous Improvement" section was advisory, not structural — skills could (and did) skip reflection entirely.
Changes Made
1. New section in SKILL.md: "Post-Execution Reflection (Compulsory)" — Mandatory architectural requirement (not advisory) with template, rationale, and link to reference 2. New reference: `post-execution-reflection.md` — Canonical pattern document with minimal and extended templates, phased execution integration, validation requirements, empirical examples, and anti-patterns for reflection itself 3. Updated `phased-execution.md`: Added Phase 3 (Reflect & Rectify) to core pattern, new [Reflect] and [Rectify] phase labels, updated all template examples 4. Updated `task-templates.md`: Template A step 8 now requires Post-Execution Reflection section; Template D step 4 adds it; Skill Quality Checklist gains two new items (reflection section present, phase labels include Reflect/Rectify) 5. SKILL.md Reference Documentation: Added post-execution-reflection.md link, updated phased-execution description
Key Insight
The difference between "advisory" and "structural" is whether the pattern survives a busy session. Advisory improvements get skipped under time pressure. Structural requirements — like YAML frontmatter or Post-Change Checklists — persist because the skill itself enforces them. Post-execution reflection must be structural to close the feedback loop.
Related
- Memory:
project_skill_architecture_self_rectification.md(planned upgrade, partially fulfilled) - Gemini Deep Research issues: #67-#70
---
2026-03-06: Align with Anthropic skill-creator (9-Agent Deep Dive)
Trigger: 9-agent investigation comparing our skill-architecture against Anthropic's official skill-creator (forked to ~/fork-tools/skills). Found 3 CRITICAL, 3 HIGH, 3 MEDIUM gaps.
Changes Made
1. Description: Converted from keyword-list format ("TRIGGERS - keyword1, keyword2") to natural language sentences per Anthropic's guidance 2. Task Templates: Replaced "MANDATORY" with reasoning-based explanation 3. New section: Testing and Iteration (~50 lines): Test prompts, evaluation methodology, iteration philosophy (generalize, keep lean, explain why, bundle repeated work) 4. New section: Skill Writing Principles (~15 lines): Inline key principles from Anthropic (reasoning over rigidity, pushy descriptions, natural language, keep execution out of descriptions) 5. New reference: writing-guide.md: Extended guidance on tone, description optimization, leanness, generalization, examples 6. New reference: script-design.md: Agentic script best practices (no interactive prompts, structured output, idempotency, PEP 723) 7. TOCs added: To reference files over 500 lines (per Anthropic's guideline) 8. Updated Reference Documentation list: Added links to new reference files
Key Insight
"We teach 'design and build correctly'; Anthropic teaches 'measure and iterate.' These are complementary halves."
Our unique value (Task Templates, 6-level precedence, CLI features, 5 structural patterns, phased execution, security practices) is preserved. The gaps filled are eval methodology, writing philosophy, and description optimization.
Reports
9 detailed agent reports at /tmp/skill-alignment-agents/agent{1-9}-*.md.
---
2026-02-25: Add 10 Checklist Items from Official Sources
Trigger: Gap analysis of Skill Quality Checklist (SKILL.md) and Validation Checklist (validation-reference.md) against Claude Code docs + agentskills.io spec revealed 10 missing items.
Items Added (both checklists)
1. name must match parent directory, no consecutive hyphens 2. Description not too broad (false-trigger guard) 3. SKILL.md body under 500 lines 4. Classify as reference vs task → set invocation control accordingly 5. context: fork requires actionable instructions (not guidelines-only) 6. compatibility field for external tool requirements 7. Fixed allowed-tools wording: "grants" not "restricts" (validation-reference.md) 8. Test activation both ways: manual /name AND organic triggers 9. Run /context to verify not excluded by budget 10. Reference-vs-task classification drives disable-model-invocation / user-invocable defaults
---
2026-02-25: Align with Official Claude Code Skills Docs (28 Findings)
Trigger: 9-agent forensic audit compared skill-architecture docs against code.claude.com/docs/en/skills and agentskills.io/specification. Found 2 CRITICAL, 8 HIGH, 11 MEDIUM, 7 LOW misalignments + 2 internal contradictions.
Changes Made (8 Work Units)
1. SKILL.md frontmatter: Expanded 3-field table → 10-field table with all official fields (context, agent, disable-model-invocation, user-invocable, argument-hint, allowed-permission-prompt, name-aliases). Fixed allowed-tools semantics: grants tools, doesn't restrict. Added invocation control truth table and Skill Permission Rules. 2. SKILL.md budget: Added Skill Description Budget subsection (2% context window, /context command, SLASH_COMMAND_TOOL_CHAR_BUDGET override). 3. TodoWrite → TaskCreate: Migrated all 8 SKILL.md occurrences. Terminology now matches Claude Code's TaskCreate tool. 4. SKILL.md CLI features: Added String Substitutions table ($ARGUMENTS, $N, ${CLAUDE_SESSION_ID}), Dynamic Context Injection (` !cmd syntax), Extended Thinking (ultrathink keyword). 5. **Skill Discovery**: Added precedence chain (Enterprise > Personal > Project > Plugin > Nested > --add-dir), monorepo auto-discovery, claude plugin enable/disable commands. 6. **command-skill-duality.md → invocation-control.md**: Complete rewrite. Old dual-entity model replaced with merged command/skill reality. Added truth table, permission rules, migration guide, historical note. 7. **advanced-topics.md**: Fixed CLI vs API table (SKILL.md everywhere, claude plugin install, removed unverifiable 200-char limit). Added Plugin-Level Features table (outputStyles, lspServers, mcpServers, settings). 8. **validation-reference.md**: Added 6 optional plugin.json` fields to template. SYNC-TRACKING.md: Updated sync date, added official docs + agentskills.io sources, added Known Spec Discrepancies table. 9. progressive-disclosure.md: Replaced 7 absolute paths with relative paths. 10. Continuous Improvement: Condensed from 42 lines to 7 lines (offset new content growth).
Key Insight
Documentation alignment requires auditing against multiple official sources simultaneously. The Claude Code docs and Agent Skills spec have subtle discrepancies (comma vs space delimiters, name requirement) that must be explicitly documented rather than silently choosing one.
---
2026-02-13: Fix Hook Integration Anti-Pattern (CLAUDE_PLUGIN_ROOT)
Trigger: The $CLAUDE_PLUGIN_ROOT variable was recommended in the Hook Integration Pattern (advanced-topics.md) but does NOT work in hooks.json commands. When hooks.json is synced to settings.json, the variable is copied verbatim and resolves to empty string at shell execution time, causing "Module not found" errors.
Anti-Patterns Documented
1. `$CLAUDE_PLUGIN_ROOT` in hooks.json: This env var only exists inside Claude Code's internal plugin skill loading context, not as a shell environment variable. Hook commands must use $HOME-based absolute paths. 2. Empty TOML table sections: mise rejects [hooks.enter] containing only comments (no key-value pairs). Either add a key or remove the section.
Changes Made
1. advanced-topics.md: Replaced $CLAUDE_PLUGIN_ROOT example with $HOME-based path, added anti-pattern callout with comparison table, fixed guideline #6 2. lifecycle-reference.md (itp-hooks): Clarified CLAUDE_PLUGIN_ROOT documentation, added both anti-patterns to Common Pitfalls table
Key Insight
Plugin context variables (CLAUDE_PLUGIN_ROOT) are available when Claude Code loads skills but NOT when hook commands execute as shell processes from settings.json. The sync script copies hooks.json commands verbatim without variable resolution. Only standard shell env vars ($HOME) are safe in hook commands.
---
2026-02-13: Extract Advanced Patterns from tts-tg-sync
Trigger: The tts-tg-sync plugin (8 skills, 3 commands, hooks, shared library) demonstrated 10 advanced patterns not captured in skill-architecture. These were extracted as agnostic, universally applicable patterns.
Changes Made
1. structural-patterns.md: Added Pattern 5 (Suite Pattern) for multi-skill lifecycle management 2. New: phased-execution.md: Preflight/Execute/Verify pattern with 3 variants (Sandwich Verification, Dependency-Aware Teardown, Config Read-Edit-Validate-Apply) and TodoWrite phase labels 3. New: command-skill-duality.md: When to use commands vs skills, complementary design, plugin layout with both 4. New: interactive-patterns.md: 5 AskUserQuestion patterns (intent branching, destructive confirmation, config group selection, symptom collection, feedback collection) 5. advanced-topics.md: Added Known Issue Table pattern and Hook Integration pattern 6. scripts-reference.md: Added Shared Library pattern (scripts/lib/ convention) 7. creation-workflow.md: Added lifecycle and interactive questions to Steps 1-2, expanded decision matrix 8. SKILL.md: Added Suite Pattern to structural patterns list, Template F for lifecycle suites, 2 checklist items, 3 new reference links, expanded trigger keywords in description
Key Insight
A single mature plugin demonstrated patterns that individual simple skills never encounter. The Suite Pattern is a fundamentally new structural category alongside Workflow, Task, Reference, and Capabilities. All patterns were generalized to use generic domain language (service, component, integration) with no TTS/Telegram-specific references.
---
2025-12-04: Expand Path Patterns for Script Portability
Trigger: Multi-agent audit found hardcoded paths across all skills/scripts.
Problem
Path-patterns.md only covered markdown-specific patterns. Scripts had transgressions:
/Users/<username>/.claude/skills(user-specific path)/tmp/jscpd-report(hardcoded temp directory)~/.local/bin/graph-easy(hardcoded binary location)
Solution
1. Added 3 new unsafe patterns to path-patterns.md:
- Pattern 4: Hardcoded user-specific paths (
/Users/<user>,/home/<user>) - Pattern 5: Hardcoded temp directories (
/tmp) - Pattern 6: Hardcoded binary locations (
~/.local/bin/tool)
2. Expanded Validation Checklist with script-specific checks
3. Updated Skill Quality Checklist with inline examples:
- Use
$HOMEnot/Users/<user> - Use
tempfile.TemporaryDirectorynot/tmp - Use
command -vnot hardcoded paths
Key Insight
Portability requires discipline in BOTH markdown AND scripts. Multi-agent parallel audit is effective for finding distributed issues across a codebase.
---
2025-12-04: Add Path Patterns Reference
Trigger: /itp:setup command failed due to unsupported $(dirname "$0") pattern in markdown.
Problem
Command markdown files used $(dirname "$0") to resolve script paths, but $0 is not set in the context where Claude reads markdown files. This is a known Claude Code bug (#9354).
Solution
1. Created references/path-patterns.md documenting:
- Safe patterns: Explicit fallback paths, relative links,
${BASH_SOURCE[0]}in scripts - Unsafe patterns:
$(dirname "$0")in markdown, bare${CLAUDE_PLUGIN_ROOT}without fallback - Related GitHub issues: #9354, #11278
- Migration guide: How to find and fix unsafe patterns
2. Added to Skill Quality Checklist:
- "No unsafe path patterns in markdown"
3. Added to Reference Documentation list
Key Insight
Environment variables and bash context ($0, $SCRIPT_DIR) behave differently in actual scripts vs. markdown documentation that Claude reads. Always use explicit fallback paths for marketplace plugins.
---
2025-12-04: Add Continuous Improvement Section
Trigger: User identified gap—skill had mechanics for self-evolution but no proactive trigger.
Problem
Skill-architecture taught HOW to make skills self-evolving (Template D, Post-Change Checklist, evolution-log) but didn't instruct Claude to ACTIVELY WATCH for improvement opportunities during normal usage.
Solution
Added "Continuous Improvement (Proactive Self-Evolution)" section with:
- 6 improvement signals to watch for (friction, edge cases, better patterns, confusion, tool evolution, repeated steps)
- Immediate Update Protocol (pause → fix → log → resume)
- What NOT to update (guard rails)
- Self-Reflection Trigger (post-task question)
Key Insight
The distinction between reactive (what to do after changes) and proactive (actively seeking improvements) is critical. Skills should be vigilant observers, not passive recipients.
---
2024-12-04: Adversarial Audit Round 3 (Multi-Agent)
Trigger: User spawned 5 parallel sub-agents for comprehensive audit.
Agents Deployed
| Agent | Perspective | Severity Found |
|---|---|---|
| Structural | Skill Anatomy compliance | NONE |
| Template-Tutorial | Alignment check | MEDIUM |
| References | Link integrity | LOW |
| Description | YAML triggers | MEDIUM |
| Checklist | Self-compliance | CRITICAL |
Critical Fix
Issue: skill-architecture not registered in ~/.claude/CLAUDE.md Impact: Violates its own teaching (Template A step 10, Tutorial Step 6) Fix: Added "Global Skills" section to ~/.claude/CLAUDE.md
Medium Fixes
1. YAML description - Added specific trigger keywords: "YAML frontmatter", "validate skill", "TodoWrite templates", "bundled resources", "progressive disclosure", "allowed-tools"
2. Orphaned file - Added workflow-patterns.md to Reference Documentation
3. Template ordering - Swapped steps 4↔5 in Template A to match tutorial advice ("resources first, then SKILL.md")
Low Fix
Orphaned file: workflow-patterns.md existed but wasn't referenced. Added to Reference Documentation section.
Key Insight
Multi-agent parallel audit with different perspectives finds issues single-pass review misses. Critical issue (not registered in CLAUDE.md) was ironic - the skill teaches the very thing it violated.
---
2024-12-04: Adversarial Audit Round 2
Trigger: User requested second adversarial review to find remaining flaws.
Flaws Found
| # | Flaw | Location |
|---|---|---|
| 1 | Skill Anatomy incomplete - missing evolution-log.md | Lines 213-219 |
| 2 | Template D assumes config-reference.md always needed | Line 66 |
| 3 | Templates don't reference detailed tutorial | Lines 18-83 |
| 4 | "6 Steps" title misleading vs 11-step Template A | Line 124 |
Changes Made
1. Skill Anatomy updated - Added references/evolution-log.md as recommended structure 2. Template D step 5 - Changed to "(if skill manages external config)" 3. Added cross-reference - Templates section now links to tutorial 4. Renamed section - "6 Steps" → "Detailed Tutorial" with note to use templates
Key Insight
Adversarial self-review catches inconsistencies that initial implementation misses. Two passes are better than one.
---
2024-12-04: TodoWrite-First Pattern + Self-Alignment
Trigger: User identified skill-architecture didn't follow its own standards.
Changes Made
1. Added TodoWrite Task Templates section (FIRST section after frontmatter)
- Template A: Create New Skill (11 steps)
- Template B: Update Existing Skill
- Template C: Add Resources to Skill
- Template D: Convert to Self-Evolving Skill
- Template E: Troubleshoot Skill Not Triggering
- Skill Quality Checklist
2. Added Post-Change Checklist (Self-Maintenance)
- skill-architecture now maintains itself like other skills
3. Updated Step 4: Edit the Skill
- Added requirements for TodoWrite Task Templates
- Added requirements for Post-Change Checklist
4. Updated Step 6: Register and Iterate
- Added "Register skill in project CLAUDE.md"
- Added "Verify against Skill Quality Checklist"
5. Created this evolution-log.md
- skill-architecture is now self-documenting
Flaws Fixed
| Flaw | Resolution |
|---|---|
| 6 Steps vs Template A misaligned | Updated 6 Steps to include registration and checklist verification |
| No Post-Change Checklist for self | Added Self-Maintenance section |
| Not self-evolving | Created evolution-log.md |
| Step 4 incomplete | Added TodoWrite templates + Checklist requirements |
Key Insight
The meta-skill that teaches skill creation must itself be an exemplar. Any pattern it teaches (TodoWrite templates, Post-Change Checklist, evolution tracking) must be present in itself.
Skill: Skill Architecture
Interactive Patterns (AskUserQuestion)
Skills that manage multi-option workflows, destructive operations, or diagnostic processes should integrate AskUserQuestion for structured user interaction. This reference documents five canonical patterns.
---
Prerequisites
Include AskUserQuestion in the skill's allowed-tools field:
---
name: my-skill
description: ...
allowed-tools: Read, Bash, Glob, AskUserQuestion
------
Pattern 1: Intent Branching
Present action options when a single skill handles multiple related operations.
Use when: The skill supports start/stop/restart, create/update/delete, or other mutually exclusive actions.
Structure:
## Phase 1: Determine Intent
Use AskUserQuestion to present available actions:
"What would you like to do?"
- Start service
- Stop service
- Restart service
- View logsTodoWrite integration:
1. [Preflight] Check current service state
2. [Ask] Present action options via AskUserQuestion
3. [Execute] Perform selected action
4. [Verify] Confirm state changeGuidelines:
- List the most common action first
- Include a status/diagnostic option when available
- Limit to 4 options per question (use follow-up questions for sub-choices)
---
Pattern 2: Destructive Action Confirmation
Require explicit confirmation before irreversible operations.
Use when: The operation deletes data, stops services, removes configurations, or modifies shared state.
Structure:
## Phase 1: Confirm Scope
Present what will be affected:
"This will remove the following:"
- Runtime environment (~500MB)
- Shell integrations (symlinks)
- Temporary files
- Secrets (optional, requires separate confirmation)
"Proceed with removal?"
- Full removal (all components)
- Partial removal (keep secrets and config)
- CancelTodoWrite integration:
1. [Preflight] Inventory components to remove
2. [Ask] Confirm removal scope via AskUserQuestion
3. [Execute] Remove in dependency order
4. [Verify] Confirm removal complete
5. [Ask] Remove secrets? (separate confirmation)Guidelines:
- List exactly what will be affected (sizes, counts)
- Always include a "Cancel" or "Dry run" option
- Separate secrets removal into its own confirmation step
- Document what is preserved and why
---
Pattern 3: Configuration Group Selection
Present categorized settings for the user to choose which to adjust.
Use when: The skill manages configuration with multiple independent groups (voice, performance, queue, security, etc.).
Structure:
## Phase 1: Read Current Configuration
Read and display current values from the configuration SSoT.
## Phase 2: Select Group
Use AskUserQuestion to present config categories:
"Which settings would you like to adjust?"
- Voice settings (language, model, speed)
- Performance settings (timeout, concurrency, queue depth)
- Notification settings (channels, rate limits)
- Security settings (tokens, permissions)TodoWrite integration:
1. [Preflight] Read current configuration from SSoT
2. [Ask] Select configuration group via AskUserQuestion
3. [Ask] Choose specific values to change
4. [Execute] Edit configuration SSoT
5. [Verify] Validate new values against constraints
6. [Execute] Restart service if neededGuidelines:
- Show current values before asking what to change
- Group by concern (not alphabetically)
- Validate ranges and types after editing
- Indicate which changes require a service restart
---
Pattern 4: Symptom Collection
Gather problem context from the user to guide diagnostic workflows.
Use when: The skill performs troubleshooting and the root cause depends on symptoms the user has observed.
Structure:
## Phase 1: Collect Symptoms
Use AskUserQuestion to understand the problem:
"What are you experiencing?"
- No output at all
- Output is wrong or garbled
- Intermittent failures
- Error messages in logs
"When did this start?"
- After a recent change
- Randomly / no clear trigger
- After system restartTodoWrite integration:
1. [Ask] Collect symptoms via AskUserQuestion
2. [Execute] Run targeted diagnostics based on symptoms
3. [Execute] Check Known Issue Table for matches
4. [Ask] Confirm suspected root cause with user
5. [Execute] Apply fix
6. [Verify] Confirm issue resolvedGuidelines:
- Start broad ("what happened?"), then narrow ("when?", "what changed?")
- Map symptoms to diagnostic commands (avoid running all checks for every issue)
- Present findings before applying fixes
- Cross-reference a Known Issue Table when available (see Advanced Topics)
---
Pattern 5: Feedback Collection
Gather user preferences after presenting options or completing an action.
Use when: The skill compares alternatives (A/B testing voices, themes, configurations) or needs subjective judgment.
Structure:
## Phase 5: Collect Feedback
After presenting options A, B, and C:
"Which option did you prefer?"
- Option A
- Option B
- Option C
- None of these / try different options
"Apply this as the new default?"
- Yes, update configuration
- No, keep current defaultTodoWrite integration:
1. [Preflight] Verify comparison environment ready
2. [Execute] Present option A
3. [Execute] Present option B
4. [Ask] Which option preferred?
5. [Ask] Apply as new default?
6. [Execute] Update configuration if confirmedGuidelines:
- Present options with objective metadata (grade, rating, characteristics) alongside subjective experience
- Always offer a "none / try more" option
- Separate preference from application (ask "which?" then "apply?")
- Log preferences for future reference
---
Anti-Patterns
| Anti-Pattern | Problem | Fix |
|---|---|---|
| Asking without showing state | User can't make informed decision | Always display current state first |
| Single "Are you sure?" | Too vague for destructive operations | List exactly what will be affected |
| Too many questions | Decision fatigue, user abandons workflow | Maximum 2-3 questions per phase |
| No cancel option | User feels trapped | Always include cancel/skip |
| Asking after the fact | "Did that work?" without verification | Run automated checks instead of asking |
---
Combining with Phased Execution
Interactive patterns integrate naturally with Phased Execution:
Preflight → [Ask] Intent → Execute → Verify → [Ask] FeedbackThe [Ask] phase label signals that user interaction is needed at that step. This helps both Claude (knows to use AskUserQuestion) and the user (sees where input is needed in the TodoWrite checklist).
Skill: Skill Architecture
Invocation Control
Commands and skills have been merged in Claude Code. Both create /name slash commands. Skills are recommended for all new work — they support the full feature set (description-based auto-triggering, frontmatter fields, bundled resources).
---
Invocation Control Fields
Two frontmatter fields control how a skill is invoked:
| Field | Effect when true | Default |
|---|---|---|
disable-model-invocation | Only manual /name — Claude never auto-triggers | false |
user-invocable | When false, no /name — Claude-only trigger | true |
Truth Table
disable-model-invocation | user-invocable | /name? | Auto-trigger? | Use case |
|---|---|---|---|---|
false (default) | true (default) | Yes | Yes | Most skills |
true | true | Yes | No | Hook-installation skills only |
false | false | No | Yes | Domain knowledge, context |
true | false | No | No | Effectively disabled |
---
When to Use Each Mode
Default (both omitted) — Most Skills
The skill is available via /name AND Claude auto-triggers it when description keywords match the conversation. This is the right choice for ~90% of skills.
Manual-Only (disable-model-invocation: true)
Reserved exclusively for hook-installation skills (skills/hooks/) that modify ~/.claude/settings.json. All other skills — including deploy, release, setup, and destructive ops — should keep the default false so Claude can auto-trigger them when the user's intent matches. Claude already asks for confirmation before executing side effects via allowed-tools restrictions.
Background-Only (user-invocable: false)
Use for skills that provide context but shouldn't be manually invoked:
- Domain knowledge: coding standards, API schemas, business rules
- Convention enforcement: style guides loaded when relevant code is discussed
- Contextual helpers: auto-loaded when Claude detects relevant conversation topics
---
Skill Permission Rules
When configuring allowed-tools in settings.json to permit skill invocations:
Skill(skill-name)— exact match, allows one specific skillSkill(skill-name *)— prefix match, allows skill and all sub-invocations
Example in settings.json:
{
"permissions": {
"allow": ["Skill(itp:go)", "Skill(devops-tools *)"]
}
}---
Historical Note: cc-skills commands/ Elimination
The cc-skills marketplace originally used a separate commands/ directory alongside skills/. This was eliminated because:
1. Duplication: Each skill needed an identical copy in commands/ to be slash-invocable 2. Sync bugs: Skill() invocations returned "Unknown skill" when only the command copy existed 3. Maintenance burden: Two files to update for every change
Now, skills/<name>/SKILL.md is the single source of truth. The sync-commands-to-settings.sh script reads from skills/ directly.
See migration issue for full context.
---
Migration Guide (Legacy commands/)
If a plugin still has a commands/ directory:
1. Move command content into the corresponding skills/<name>/SKILL.md 2. Add argument-hint to frontmatter if the command accepted arguments 3. Set disable-model-invocation: true if the command was intentionally manual-only 4. Delete the commands/ directory 5. Run bun scripts/validate-plugins.mjs to verify
Path Patterns Reference
Safe and unsafe patterns for referencing bundled scripts and files in Claude Code skills and plugins.
---
Known Limitations
Bug: ${CLAUDE_PLUGIN_ROOT} environment variable does NOT expand in command markdown files.>
Issue: #9354 - Fix ${CLAUDE_PLUGIN_ROOT} in command markdown
>
Status: Open (as of 2024-12)
---
Safe Patterns (Use These)
Pattern 1: Explicit Fallback Path (Recommended)
For marketplace plugins, use explicit fallback to the marketplace installation path:
/usr/bin/env bash << 'PATH_PATTERNS_SCRIPT_EOF'
# Environment-agnostic with explicit marketplace fallback
PLUGIN_DIR="${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/plugins/marketplaces/<publisher>/<plugin-name>}"
bash "$PLUGIN_DIR/scripts/my-script.sh"
PATH_PATTERNS_SCRIPT_EOFExample (itp plugin):
/usr/bin/env bash << 'PREFLIGHT_EOF'
PLUGIN_DIR="${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/plugins/marketplaces/cc-skills/plugins/itp}"
bash "$PLUGIN_DIR/scripts/install-dependencies.sh" --check
PREFLIGHT_EOFWhy it works: When ${CLAUDE_PLUGIN_ROOT} isn't set (which is the case in markdown files due to bug #9354), the explicit fallback path is used.
Pattern 2: Relative Links in Markdown
For documentation links within the same skill/plugin:
See [Security Practices](./references/security-practices.md) for details.Why it works: Relative paths resolve correctly regardless of installation location.
Pattern 3: Direct Script Execution (in .sh files)
Inside bash scripts (not markdown), self-relative paths work:
/usr/bin/env bash << 'PATH_PATTERNS_SCRIPT_EOF_2'
#!/bin/bash
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PLUGIN_DIR="$(dirname "$SCRIPT_DIR")"
# Now use $PLUGIN_DIR for other resources
PATH_PATTERNS_SCRIPT_EOF_2Why it works: ${BASH_SOURCE[0]} is set correctly when the script runs.
---
Unsafe Patterns (Do NOT Use in Markdown)
Pattern 1: $(dirname "$0") in Markdown
/usr/bin/env bash << 'PATH_PATTERNS_SCRIPT_EOF_3'
# ❌ DOES NOT WORK in command/skill markdown files
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PLUGIN_DIR="${CLAUDE_PLUGIN_ROOT:-$(dirname "$SCRIPT_DIR")}"
PATH_PATTERNS_SCRIPT_EOF_3Why it fails: $0 is not set to the markdown file path when Claude reads the file. The expansion produces garbage or empty string.
Pattern 2: Bare ${CLAUDE_PLUGIN_ROOT} Without Fallback
/usr/bin/env bash << 'PATH_PATTERNS_SCRIPT_EOF_4'
# ❌ DOES NOT WORK - no fallback when variable unset
bash "${CLAUDE_PLUGIN_ROOT}/scripts/my-script.sh"
PATH_PATTERNS_SCRIPT_EOF_4Why it fails: Due to bug #9354, ${CLAUDE_PLUGIN_ROOT} is not expanded in markdown files, resulting in /scripts/my-script.sh (missing the plugin path).
Pattern 3: Assuming Fixed Installation Path
# ❌ FRAGILE - assumes specific installation location
bash ~/.claude/plugins/itp/scripts/my-script.shWhy it fails: Marketplace plugins install to ~/.claude/plugins/marketplaces/<publisher>/<plugin>/, not ~/.claude/plugins/<plugin>/.
Pattern 4: Hardcoded User-Specific Paths
# ❌ BREAKS on other machines
find /Users/terryli/.claude/skills -name "SKILL.md"
cd /home/alice/projectsWhy it fails: User-specific paths only work on the developer's machine. Always use $HOME:
# ✅ WORKS for all users
find "$HOME/.claude/skills" -name "SKILL.md"Pattern 5: Hardcoded Temp Directories
# ❌ Not portable (Windows, permissions, cleanup)
output_dir = "/tmp/jscpd-report"Why it fails: /tmp doesn't exist on Windows, may have permissions issues, and doesn't clean up.
# ✅ WORKS - proper temp directory handling
import tempfile
with tempfile.TemporaryDirectory() as tmpdir:
output_dir = Path(tmpdir)
# Auto-cleans when context exitsPattern 6: Hardcoded Binary Locations
# ❌ Assumes specific installation location
/opt/homebrew/bin/graph-easy --as=boxart
~/.local/bin/uv publishWhy it fails: Tools can be installed via different methods (mise, homebrew, apt, cargo, etc.).
# ✅ WORKS - uses PATH resolution
graph-easy --as=boxart
# ✅ WORKS - command exists check first
command -v uv &>/dev/null || { echo "uv not found"; exit 1; }
uv publish---
Context-Specific Guidance
| Context | Safe Pattern | Notes |
|---|---|---|
| SKILL.md | Explicit fallback or relative links | Use Pattern 1 for bash, Pattern 2 for docs |
| *commands/\.md** | Explicit fallback only | $0 doesn't work here |
| *scripts/\.sh** | ${BASH_SOURCE[0]} | Self-relative paths work in actual scripts |
| *references/\.md** | Relative links only | No bash execution expected |
---
Validation Checklist
When reviewing skills/plugins for path issues:
Markdown Files (.md):
- [ ] No
$(dirname "$0")in any.mdfile - [ ] No
$(dirname "$SCRIPT_DIR")in any.mdfile - [ ] All
${CLAUDE_PLUGIN_ROOT}usages have explicit fallback - [ ] Fallback paths match actual marketplace structure
- [ ] Relative links used for internal documentation
Scripts (.sh, .py):
- [ ] No hardcoded
/Users/<username>or/home/<username>paths - [ ] Use
$HOMEor environment variables instead of user-specific paths - [ ] Use
tempfilemodule (Python) ormktemp(Bash) for temp directories - [ ] Use
command -vor PATH resolution for tool execution - [ ] No hardcoded binary locations like
~/.local/bin/toolor/opt/homebrew/bin/tool
---
Environment Variable Expansion by Context
Critical: Environment variables like $HOME and ${VAR} are NOT universally expanded. Expansion depends on the execution context.
| Context | $HOME Expanded? | ${VAR} Expanded? | Notes |
|---|---|---|---|
| JSON config files | NO | NO | JSON is literal text - never expands |
| Bash scripts | YES | YES | Shell expands variables |
| Heredoc in markdown | YES | YES | Executed by shell via /usr/bin/env bash |
| Python with `shell=True` | YES | YES | Via shell subprocess |
| Python with `shell=False` | NO | NO | Use os.path.expanduser() or os.path.expandvars() |
| YAML files | DEPENDS | DEPENDS | Tool-specific (some expand, some don't) |
| TOML files (mise) | YES | YES | Use {{env.HOME}} or {{env.VAR}} |
JSON Config Files (CRITICAL)
Never use `$HOME`, `~`, or `${VAR}` in JSON files. JSON is a data format that does NOT expand environment variables.
Wrong (creates literal $HOME folder):
{
"installLocation": "$HOME/.claude/plugins/marketplaces/cc-skills"
}Correct (absolute path):
{
"installLocation": "/Users/username/.claude/plugins/marketplaces/cc-skills"
}Affected files:
~/.claude/plugins/known_marketplaces.json~/.claude/plugins/installed_plugins.json~/.claude/settings.json(hook paths)
See Troubleshooting: Literal $HOME Folders for recovery if you encounter this issue.
---
Related Issues
| Issue | Description | Status |
|---|---|---|
| #9354 | ${CLAUDE_PLUGIN_ROOT} not expanded in command markdown | Open |
| #11278 | Plugin path resolution uses marketplace.json file path | Open |
| #4276 | Environment variable expansion not supported in JSON | Open |
| #13138 | Race condition creates literal $HOME folders | Open |
---
Migration Guide
If you find unsafe patterns in existing skills:
1. Search for the pattern:
grep -rn 'dirname.*\$0\|dirname.*\$SCRIPT_DIR' --include="*.md"2. Replace with explicit fallback:
/usr/bin/env bash << 'PATH_PATTERNS_SCRIPT_EOF_5'
Before (broken)
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" PLUGIN_DIR="${CLAUDE_PLUGIN_ROOT:-$(dirname "$SCRIPT_DIR")}"
After (works)
PLUGIN_DIR="${CLAUDE_PLUGIN_ROOT:-$HOME/.claude/plugins/marketplaces/<publisher>/<plugin>}"
PATH_PATTERNS_SCRIPT_EOF_5
3. **Test** by running the command/skill and verifying scripts execute correctly.Skill: Skill Architecture
Phased Execution Patterns
Robust skills follow a phased execution model that prevents failures, guides users through complex operations, and verifies outcomes. This reference documents the core pattern and its variants.
---
Core Pattern: Preflight → Execute → Verify
Every non-trivial skill workflow should follow three phases:
Phase 0: Preflight
Verify prerequisites exist and the system is in a valid state before starting work.
What to check:
- Required tools installed (
command -v tool) - Required services running (
pgrep -la service) - Configuration files present and valid
- No conflicting processes or stale lock files
- Sufficient permissions for the operation
Fail fast: If any preflight check fails, stop immediately with an actionable error message. Never proceed with missing prerequisites.
[Preflight] Verify bun installed: command -v bun
[Preflight] Verify mise installed: command -v mise
[Preflight] Verify config exists: test -f config.toml
[Preflight] Check no conflicting processes: ! pgrep -f "service-name"Phase 1: Execute
Perform the core operation with clear progress indicators.
[Execute] Install dependencies
[Execute] Configure environment
[Execute] Start servicePhase 2: Verify
Confirm the operation succeeded by checking expected outcomes.
[Verify] Service responds to health check
[Verify] Config values match expectations
[Verify] No errors in log outputPhase 3: Reflect & Rectify
After execution completes, retrospectively examine the skill's own performance and rectify its artifacts. This phase is compulsory for all skills that perform stepwise execution — errors discovered empirically must feed back into the skill itself.
Why this phase exists: Skills execute in unpredictable environments. Instructions that work in testing fail in production. Scripts break on edge cases. References become stale. Without a structural reflection phase, these failures repeat silently across sessions. The skill never learns.
What to reflect on:
- Steps that failed or required manual workarounds → fix the instructions
- Steps that were skipped as unnecessary → consider removing or making conditional
- Unexpected successes (a better approach emerged) → promote to recommended pattern
- Recurring friction points → document as anti-patterns with the specific error observed
- Script output that was wrong or misleading → fix the script, not just the instructions
- References that were outdated or incorrect → update or remove
[Reflect] Review execution: any steps failed or needed manual intervention?
[Reflect] Identify empirical patterns: what worked better than prescribed?
[Reflect] Identify empirical anti-patterns: what caused repeated friction?
[Rectify] Update SKILL.md instructions with findings
[Rectify] Fix scripts/references that produced incorrect results
[Rectify] Log changes in evolution-log.md with evidenceKey principle: Rectification is immediate. Do not defer known fixes. If a step failed because the instruction was wrong, fix the instruction now — not in a future maintenance pass.
See Post-Execution Reflection Reference for the full pattern.
---
TodoWrite Phase Labels
Use bracketed phase labels in TodoWrite templates for clarity and traceability:
| Label | Purpose | Example |
|---|---|---|
[Preflight] | Prerequisite verification | [Preflight] Verify Python 3.14 installed |
[Execute] | Core operation steps | [Execute] Install package dependencies |
[Verify] | Outcome confirmation | [Verify] Service responds on port 8080 |
[Reflect] | Post-execution skill review | [Reflect] Review execution for errors/friction |
[Rectify] | Skill self-correction | [Rectify] Update SKILL.md with empirical findings |
[Cleanup] | Post-operation tidying | [Cleanup] Remove temporary build artifacts |
[Ask] | User input required | [Ask] Select configuration profile |
Template example:
1. [Preflight] Verify all prerequisites installed
2. [Preflight] Check no conflicting processes running
3. [Preflight] Validate configuration file
4. [Execute] Stop existing service
5. [Execute] Install new version
6. [Execute] Apply configuration
7. [Verify] Service starts successfully
8. [Verify] Health check passes
9. [Reflect] Review execution: any steps failed or needed workarounds?
10. [Rectify] Update skill instructions/scripts with empirical findings
11. [Cleanup] Remove old version artifacts---
Variant: Sandwich Verification
Capture baseline state before an operation, execute, then re-run the same checks to compare.
Use when: Upgrading components, applying configuration changes, or any operation where regressions are possible.
Pattern:
1. [Preflight] Run health check (record baseline)
2. [Preflight] Record current versions
3. [Execute] Perform upgrade/change
4. [Verify] Re-run same health check
5. [Verify] Compare versions (old → new)
6. [Verify] Confirm no regressions (all checks still pass)Key principle: The pre-check and post-check must be identical. Use the same diagnostic commands before and after so results are directly comparable.
Example health check table:
| Subsystem | Before | After | Status |
| --------------- | ------------------ | ------------------ | ------- |
| Service process | Running (PID 1234) | Running (PID 5678) | OK |
| API endpoint | 200 OK | 200 OK | OK |
| Version | 1.2.0 | 1.3.0 | Updated |
| Dependencies | All present | All present | OK |---
Variant: Dependency-Aware Teardown
Remove components in the correct order, respecting dependencies between them.
Use when: Uninstalling, cleaning up, or decommissioning multi-component systems.
Pattern:
1. [Ask] Confirm teardown scope (full vs partial)
2. [Execute] Stop running processes (must come first)
3. [Execute] Remove runtime artifacts (venvs, caches)
4. [Execute] Remove integrations (symlinks, hooks, cron jobs)
5. [Execute] Clean temporary files
6. [Ask] Confirm secrets removal (optional, explicit consent)Ordering rules:
1. Processes must stop before their files can be removed 2. Dependents must be removed before their dependencies 3. Secrets removal is always optional and requires explicit confirmation 4. Configuration and source code are preserved by default (for easy reinstall)
Document what is NOT removed and why:
| Preserved | Reason | Location |
| ------------- | ------------------------------------------ | ------------------------ |
| Model cache | Large download, reusable across reinstalls | ~/.cache/models/ |
| Source code | Git-tracked, not a runtime artifact | ~/project/src/ |
| Configuration | SSoT for environment, needed for reinstall | ~/project/mise.toml |
| Audit logs | Compliance/debugging history | ~/.local/share/app/logs/ |Reversibility: Each removal step should note whether it is reversible. Stopping a process is reversible (restart it). Deleting a venv is partially reversible (recreate it). Deleting secrets requires re-provisioning.
---
Variant: Config Read-Edit-Validate-Apply
Manage configuration through a structured read-edit-validate cycle using a single source of truth.
Use when: Skills that manage settings, environment variables, or configuration files.
Pattern:
1. [Preflight] Read current config from SSoT
2. [Ask] Present config groups to user (categorized by concern)
3. [Execute] Edit selected values in SSoT
4. [Verify] Validate new values against constraints (ranges, types, enums)
5. [Execute] Apply changes (restart service if needed)
6. [Verify] Confirm new values are activeConfiguration grouping: Present settings categorized by concern, not alphabetically:
Which settings to adjust?
- Voice settings (language, voice model, speed)
- Performance settings (timeout, queue depth, concurrency)
- Notification settings (channels, rate limits, formatting)
- Security settings (tokens, permissions, audit level)Validation rules: Each setting should have documented constraints:
| Setting | Type | Range | Default |
| ---------- | ----- | --------------------------- | ------- |
| speed | float | 0.5-2.0 | 1.25 |
| timeout_ms | int | 1000-60000 | 15000 |
| max_queue | int | 1-100 | 5 |
| voice | enum | [voice_a, voice_b, voice_c] | voice_a |SSoT principle: All configuration lives in one file. Skills read from and write to this single location. No duplicated config values across multiple files.
---
Combining Phases with Interactive Patterns
Phased execution often combines with Interactive Patterns:
1. [Preflight] Verify prerequisites
2. [Ask] What would you like to do? (intent branching)
3. [Execute] Perform selected action
4. [Verify] Confirm result
5. [Reflect] Review: any errors, new patterns, or anti-patterns discovered?
6. [Rectify] Update skill artifacts if findings warrant changes
7. [Ask] Satisfied with the outcome? (feedback)See Interactive Patterns for detailed AskUserQuestion patterns.
---
Anti-Patterns
| Anti-Pattern | Problem | Fix |
|---|---|---|
| Skip preflight | Operation fails mid-way, harder to diagnose | Always check prerequisites first |
| No verification | Silent failures go unnoticed | Always confirm expected outcomes |
| Verify different things | Pre and post checks not comparable | Use identical diagnostic commands |
| Remove before stop | Files locked by running process | Always stop processes first |
| Edit config without validation | Invalid values cause runtime errors | Validate constraints before applying |
| Hardcode removal order | Dependencies change over time | Document ordering rationale |
Skill: Skill Architecture
Post-Execution Reflection
Compulsory self-rectification pattern for agent skills. After every stepwise execution, the skill reminds Claude to retrospectively examine what happened and fix the skill's own artifacts based on empirical evidence.
---
Why This Is Compulsory
Agent skills executing stepwise are inherently fragile. Instructions written in isolation break when they meet real environments — different OS versions, missing tools, unexpected file layouts, API changes, race conditions. Without a structural feedback loop, these failures repeat identically across sessions because the skill never learns from its own execution.
The Post-Execution Reflection pattern closes this loop. It is not a nice-to-have or a best practice — it is a structural requirement for any skill that performs multi-step work, because:
1. Skills accumulate drift — Instructions written for one environment silently fail in another. Only execution reveals the drift. 2. Anti-patterns are empirical — You cannot predict which instructions will cause friction until the skill runs against real conditions. The skill must capture these discoveries. 3. Scripts and references go stale — A bundled script that worked last month may fail today due to upstream changes. Only execution reveals staleness. 4. Patterns emerge from repetition — When a workaround appears across multiple executions, it should be promoted to a recommended pattern in the skill itself.
---
The Reflection Section
Every skill with stepwise execution must include this section in its SKILL.md. The section triggers at the end of every invocation — after Verify, before Cleanup.
Canonical Template
All skills use this exact template. No bespoke variants — the principles are universal.
## Post-Execution Reflection
After this skill completes, reflect before closing the task:
0. **Locate yourself.** — Find this SKILL.md's canonical path (Glob for this skill's name) before editing. All corrections target THIS file and its sibling references/ — never other documentation.
1. **What failed?** — Fix the instruction that caused it. If it could recur, add it as an anti-pattern.
2. **What worked better than expected?** — Promote it to recommended practice. Document why.
3. **What drifted?** — Any script, reference, or external dependency that no longer matches reality gets fixed now.
4. **Log it.** — Every change gets an evolution-log entry with trigger, fix, and evidence.
Do NOT defer. The next invocation inherits whatever you leave behind.Why one template, not bespoke versions: Domain-specific reflection sections become stale the moment the domain shifts. Principle-based reflection adapts to whatever the execution actually encounters — the principles guide the agent to the right action without prescribing domain details that drift.
Extended Template (DEPRECATED — use canonical template above)
Previously, complex skills used an extended form. This is no longer recommended — the canonical template's principles cover all cases. Retained for reference only:
## Post-Execution Reflection
After this skill completes, reflect before closing the task:
### Error Review
- Did any step fail? Update the step's instructions with the failure mode and recovery.
- Did any step require a manual workaround? Encode the workaround into the instructions.
- Were any steps skipped as unnecessary? Consider removing or making conditional.
### Pattern Discovery
- Did a better approach emerge during execution? Promote it to the recommended approach.
- Did any instruction produce consistently good results despite seeming risky? Document WHY it works — this is a validated pattern.
- Document new patterns in a `## Recommended Patterns` section or in `references/`.
### Anti-Pattern Discovery
- Did any instruction cause recurring friction? Document the specific error and the fix.
- Did any assumption prove wrong? (e.g., "tool X is always installed" — it wasn't)
- Document new anti-patterns in a `## Anti-Patterns` section or in `references/`.
### Artifact Rectification
- **SKILL.md**: Update instructions that were wrong, unclear, or incomplete.
- **scripts/**: Fix any script that produced incorrect output or failed on edge cases.
- **references/**: Update any reference that was outdated, misleading, or incomplete.
- **evolution-log.md**: Log every change with trigger, fix, and evidence.
Do NOT skip this section. Do NOT defer fixes to "next time."---
Phased Execution Integration
The reflection phase sits between Verify and Cleanup in the standard execution model:
Phase 0: Preflight — verify prerequisites
Phase 1: Execute — perform core operation
Phase 2: Verify — confirm outcomes
Phase 3: Reflect — review execution, identify patterns/anti-patterns
Phase 3b: Rectify — fix skill artifacts based on findings
Phase 4: Cleanup — remove temporary artifactsUse [Reflect] and [Rectify] labels in task templates:
7. [Verify] Health check passes
8. [Reflect] Review execution: any steps failed or needed workarounds?
9. [Reflect] Identify empirical patterns and anti-patterns
10. [Rectify] Update SKILL.md instructions with findings
11. [Rectify] Fix scripts/references that produced incorrect results
12. [Rectify] Log changes in evolution-log.md
13. [Cleanup] Remove temporary build artifacts---
What Gets Rectified
| Artifact | What to check | How to fix |
|---|---|---|
| SKILL.md | Instructions that were wrong, unclear, or incomplete | Rewrite the specific step |
| scripts/ | Scripts that failed, produced wrong output, or had errors | Fix the script code |
| references/ | References that were outdated, misleading, or missing info | Update or remove the reference |
| evolution-log.md | Missing entries for changes made | Add entry with trigger, change, evidence |
| Anti-patterns | Friction points not yet documented | Add to Anti-Patterns section or reference file |
| Patterns | Successful approaches not yet documented | Add to Recommended Patterns section or reference |
---
Validation Requirements
The skill validator should check that skills with stepwise execution include a Post-Execution Reflection section. Detection heuristics:
1. Section header present: SKILL.md contains ## Post-Execution Reflection (or close variant like ## Post-Execution Review) 2. Reflection triggers present: The section contains references to error review, pattern/anti-pattern discovery, or artifact rectification 3. Evolution log reference: The section references evolution-log.md
Validator Check (for validate-skill.ts)
CHECK: post-execution-reflection
SEVERITY: warning (skills without stepwise execution are exempt)
CONDITION: SKILL.md contains task templates with [Execute] labels
AND does NOT contain "Post-Execution Reflection" section header
MESSAGE: "Skill performs stepwise execution but lacks Post-Execution Reflection section.
Add one following the template in post-execution-reflection.md."Skills that are purely reference (no side effects, no stepwise execution) are exempt. The validator should only flag skills that have task templates with [Execute] labels.
---
Examples of Empirical Findings
These are the kinds of discoveries that the reflection phase captures:
Pattern Example
Trigger: During kokoro-tts:install, discovered that checkingsherpa-onnxversion viapython -c "import sherpa_onnx"is unreliable because the import succeeds even with a broken installation.
>
Pattern: Use sherpa-onnx --help 2>&1 | head -1 to check the CLI binary directly. This catches broken installations that the Python import misses.>
Rectification: Updated step 5 in the install template from Python import check to CLI binary check.
Anti-Pattern Example
Trigger: During itp:go, the preflight step checked formiseavailability but not for the specific mise task the skill needed. Execution failed at step 4 becausemise run check-fullwasn't defined in the project.
>
Anti-Pattern: Checking tool installation without checking task/command availability. Tools being installed doesn't mean the required commands exist.
>
Rectification: Added [Preflight] Verify mise task exists: mise task ls | grep check-full to the template.Script Fix Example
Trigger:validate-links.tsreported false positives for anchor links containing colons (e.g.,#phase-3-reflect--rectify). The regex treated colons as invalid characters.
>
Fix: Updated the anchor validation regex in validate-links.ts to allow colons and ampersands in anchor fragments.>
Evidence: Error: Invalid anchor "#phase-3-reflect--rectify" in line 42---
Anti-Patterns for Reflection Itself
| Anti-Pattern | Problem | Fix |
|---|---|---|
| Reflection without rectification | Noticing problems but not fixing them ("will fix later") | The section MUST instruct immediate fixes |
| Speculative rectification | Changing instructions based on what MIGHT go wrong | Only rectify based on observed empirical evidence |
| Over-rectification | Rewriting large portions of the skill after one failure | Fix the specific failure; don't refactor the whole skill |
| Missing evidence in evolution log | Logging "fixed X" without the error that prompted it | Always include the actual error/output as evidence |
| Skipping reflection on success | Only reflecting when things fail | Successful executions also reveal patterns worth capturing |
Skill: Skill Architecture
Progressive Disclosure
Context management pattern for efficient skill loading.
Three-Level Loading System
Level 1: Metadata (Always Loaded)
What: YAML frontmatter only Size: ~100 words When: Every Claude session Cost: Negligible
---
name: pdf-editor
description: Extract text, rotate, merge, split PDFs. Use when working with PDF files.
---Purpose: Skill discovery - Claude knows the skill exists and when to use it.
Level 2: SKILL.md Body (Loaded on Trigger)
What: Main skill instructions Size: <5k words (aim for <2k) When: Skill activates Cost: Moderate (part of context window)
Guidelines:
- Essential procedures only
- Quick reference format
- Link to references/ for details
- Keep under 200 lines when possible
Example:
## Quick Start
1. Rotate PDF: Run `scripts/rotate_pdf.py <file> <degrees>`
2. Merge PDFs: Run `scripts/merge_pdfs.py <file1> <file2>`
See [Advanced Operations](./references/advanced.md) for complex scenarios.Level 3: Bundled Resources (Loaded on Demand)
What: references/, scripts/, assets/ Size: Unlimited When: Claude explicitly reads them Cost: High (full file content) or Zero (scripts execute without loading)
References - Loaded when Claude needs deep context:
See [Schema Documentation](./references/schema.md)Scripts - May execute without loading:
scripts/rotate_pdf.py input.pdf 90
# Claude runs without reading script contentAssets - Never loaded (copied/modified only):
Copy template: `cp assets/template.html output.html`Designing for Progressive Disclosure
Anti-Pattern: Monolithic SKILL.md
❌ Bad: 500-line SKILL.md with everything inline
# PDF Editor
## Rotation
[50 lines of rotation details]
## Merging
[100 lines of merge details]
## Splitting
[80 lines of split details]
## Format Conversion
[150 lines of conversion details]
## Troubleshooting
[120 lines of error handling]Problem: Every skill activation loads 500 lines, even for simple "rotate 90 degrees" task.
Pattern: Lean Entry + Rich References
✅ Good: Lean SKILL.md + detailed references
# PDF Editor
## Capabilities
- **Rotate**: `scripts/rotate_pdf.py <file> <degrees>`
- **Merge**: `scripts/merge_pdfs.py <files...> <output>`
- **Split**: `scripts/split_pdf.py <file> <page-ranges>`
- **Convert**: See [Conversion Guide](./references/conversion.md)
## Troubleshooting
Common issues: See [Troubleshooting](./references/troubleshooting.md)Benefit: SKILL.md loads quickly, references loaded only when needed.
When to Use Each Level
Put in SKILL.md (Level 2)
- ✅ Common use cases (80% of tasks)
- ✅ Quick reference commands
- ✅ Navigation guide to references
- ✅ Security warnings
- ✅ Tool restrictions (
allowed-tools)
Put in references/ (Level 3)
- ✅ Detailed explanations (>100 words)
- ✅ Edge cases and advanced scenarios
- ✅ Comprehensive documentation
- ✅ Large schemas/API docs
- ✅ Troubleshooting guides
Put in scripts/ (Level 3)
- ✅ Deterministic operations
- ✅ Repeatedly rewritten code
- ✅ External tool wrappers
- ✅ Complex algorithms
Put in assets/ (Level 3)
- ✅ Templates (HTML, config files)
- ✅ Images, icons, fonts
- ✅ Boilerplate code
- ✅ Sample documents
Real-World Example: BigQuery Skill
Before Progressive Disclosure (400 lines):
# BigQuery
## Table Schemas
[200 lines of schema documentation]
## Query Patterns
[100 lines of query examples]
## Troubleshooting
[100 lines of error handling]After Progressive Disclosure (80 lines + references):
````markdown
BigQuery
Quick Queries
Find today's user logins:
SELECT COUNT(*) FROM users WHERE login_date = CURRENT_DATE()````
Complex queries: See Query Patterns (./references/query-patterns.md)
Schema
Main tables: users, sessions, events Full schema: See Schema Documentation (./references/schema.md)
Grep for tables: grep -i "table_name" ./references/schema.md
Troubleshooting
See Common Issues (./references/troubleshooting.md)
**Result**:
- Level 2: 80 lines (fast load, covers 80% of tasks)
- Level 3: 300+ lines in references (loaded only when needed)
- Token efficiency: 73% improvement for common tasks
## Measuring Effectiveness
**Good progressive disclosure**:
- SKILL.md handles 80% of tasks standalone
- References loaded <20% of the time
- No duplicate content between levels
- Clear navigation from SKILL.md to references
**Poor progressive disclosure**:
- SKILL.md too minimal (constant reference lookups)
- SKILL.md too detailed (loads unnecessary content)
- Duplicate content across SKILL.md and references
- Unclear when to consult referencesScript Design for Agentic Consumption
Scripts bundled with skills are executed by Claude Code agents, not humans at a terminal. This reference documents the design principles that make scripts reliable in agentic contexts.
Core Principles
1. No Interactive Prompts
Agent stdin is not connected. Any script that blocks waiting for input will hang the agent indefinitely.
| Pattern | Status | Alternative |
|---|---|---|
input("Continue? ") | Prohibited | Accept --yes / --force flag |
read -p "Enter value" | Prohibited | Require as CLI argument |
select menu | Prohibited | Accept choice as argument |
confirm() dialog | Prohibited | Default to safe action or --dry-run |
2. --help as Primary Agent Interface
The agent reads --help output to understand how to invoke a script. Write help text as if it were API documentation.
usage: check-deps.py [--format json|text] [--strict] [paths...]
Check project dependencies for version conflicts.
Options:
--format json|text Output format (default: json)
--strict Fail on warnings too
--dry-run Show what would change without modifying files
Exit codes:
0 All checks passed
1 Dependency conflicts found
2 Invalid argumentsInclude: usage line, description, all flags with defaults, exit codes. Omit: version numbers, author info, decorative formatting.
3. Structured Output
Prefer JSON on stdout over free-form text. The agent can parse JSON reliably; it cannot reliably parse prose.
# stdout: structured data (agent consumes this)
echo '{"status": "ok", "files_changed": 3, "warnings": []}'
# stderr: diagnostics (agent reads for troubleshooting)
echo "Scanning 142 files..." >&2Rules:
- stdout = data (JSON, CSV, or single values)
- stderr = progress, warnings, diagnostics
- Never mix data and diagnostics on the same stream
4. Idempotency
Running a script twice with the same arguments must produce the same result. The agent may retry on failure or re-run during iteration.
# Good: check before acting
if not path.exists():
path.mkdir(parents=True)
# Bad: fails on second run
path.mkdir() # FileExistsError5. Meaningful Exit Codes
0 Success
1 General failure (with message on stderr)
2 Invalid arguments / usage errorNever exit 0 on failure. The agent uses exit codes as the primary success/failure signal.
6. Predictable Output Size
Unbounded output floods the agent's context window and degrades performance.
| Pattern | Problem | Fix |
|---|---|---|
find / -name "*.py" | Thousands of lines | Limit scope or paginate |
| Dumping entire DB table | Unbounded | LIMIT 100 + --limit flag |
| Full stack traces | Verbose | Summarize, full trace on --verbose |
Rule of thumb: Default output should fit in 50 lines. Offer --verbose for more.
7. Self-Contained Dependencies
Scripts should declare their own dependencies so the agent can run them without manual setup.
Python: PEP 723 Inline Metadata
# /// script
# requires-python = ">=3.14"
# dependencies = [
# "httpx>=0.27",
# "rich>=13.0",
# ]
# ///
"""Check API endpoint health."""
import json
import sys
import httpx
def main():
url = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080/health"
try:
r = httpx.get(url, timeout=10)
result = {"url": url, "status": r.status_code, "ok": r.is_success}
except httpx.RequestError as e:
result = {"url": url, "status": None, "ok": False, "error": str(e)}
print(json.dumps(result))
sys.exit(1)
print(json.dumps(result))
sys.exit(0 if result["ok"] else 1)
if __name__ == "__main__":
main()Run with: uv run --python 3.14 scripts/check-health.py https://example.com/health
TypeScript/Bun: Auto-Install
#!/usr/bin/env bun
/**
* Validate JSON schema conformance.
* Usage: bun run scripts/validate-schema.ts <schema.json> <data.json>
*
* Exit codes: 0 = valid, 1 = invalid, 2 = bad arguments
*/
import Ajv from "ajv"; // bun auto-installs on first run
const [schemaPath, dataPath] = Bun.argv.slice(2);
if (!schemaPath || !dataPath) {
console.error("Usage: validate-schema.ts <schema.json> <data.json>");
process.exit(2);
}
const schema = await Bun.file(schemaPath).json();
const data = await Bun.file(dataPath).json();
const ajv = new Ajv();
const valid = ajv.validate(schema, data);
const result = {
valid,
errors: valid ? [] : ajv.errors,
};
console.log(JSON.stringify(result, null, 2));
process.exit(valid ? 0 : 1);Run with: bun run scripts/validate-schema.ts schema.json data.json
8. Dry-Run Support
Destructive operations must support --dry-run to let the agent preview effects before committing.
def delete_stale_branches(branches: list[str], dry_run: bool = False):
for branch in branches:
if dry_run:
print(json.dumps({"action": "would_delete", "branch": branch}))
else:
subprocess.run(["git", "branch", "-D", branch], check=True)
print(json.dumps({"action": "deleted", "branch": branch}))The agent calls with --dry-run first, reviews output, then runs without it.
9. Actionable Error Messages
Errors go to stderr and include what went wrong, why, and how to fix it.
# Bad
sys.exit("Error")
# Good
print(
"Error: config.toml not found at /project/config.toml. "
"Run 'init-project --dir /project' to create it.",
file=sys.stderr,
)
sys.exit(1)Quick Checklist
Use this when reviewing scripts bundled with skills:
- [ ] No interactive prompts (no stdin reads)
- [ ]
--helpdocuments usage, flags, and exit codes - [ ] Data on stdout, diagnostics on stderr
- [ ] JSON output by default (or
--format jsonoption) - [ ] Idempotent (safe to re-run)
- [ ] Exit 0 only on success
- [ ] Output bounded by default (< 50 lines)
- [ ] Dependencies declared inline (PEP 723 or Bun auto-install)
- [ ]
--dry-runfor destructive operations - [ ] Error messages include fix guidance
Reference
- Progressive Disclosure - When to use scripts vs references
- Bash Compatibility - Shell portability for bash scripts
- Security Practices - Script permission and threat model
Skill: Skill Architecture
Part 3: Security (Critical)
🚨 Security Threats
1. Prompt Injection Attacks
- Malicious input tricks Agent Skill into executing unintended actions
- Recent CVEs: CVE-2025-54794 (path bypass), CVE-2025-54795 (command injection)
- Defense: Validate inputs, use
allowed-toolsto restrict capabilities
2. Tool Abuse
- Adversary manipulates Agent Skill to run unsafe commands or exfiltrate data
- Defense: Minimize tool power, require confirmations for high-impact actions
3. Data Exfiltration
- Agent Skill could be tricked into leaking sensitive files
- Defense: Never hardcode secrets, use
allowed-toolsto block network commands
Security Best Practices
DO:
- ✅ Run Claude Code in sandboxed environment (VM/container)
- ✅ Use
allowed-toolsto restrict dangerous tools (block WebFetch, Bash curl/wget) - ✅ Validate all user inputs before file operations
- ✅ Use deny-by-default permission configs
- ✅ Audit downloaded Agent Skills before enabling
- ✅ Red-team test for prompt injection
DON'T:
- ❌ Hardcode API keys, passwords, or secrets in SKILL.md
- ❌ Run as root
- ❌ Trust Agent Skills from unknown sources
- ❌ Use unchecked
sudoorrm -rfoperations - ❌ Enable all tools by default
Security Example
Insecure Agent Skill:
---
name: unsafe-api
description: Calls API with hardcoded key
---
API_KEY = "sk-1234..." # ❌ NEVER DO THISSecure Agent Skill:
---
name: safe-api
description: Calls API using environment variables
allowed-tools: Read, Bash # Blocks WebFetch to prevent data exfiltration
---
# Safe API Client
Use environment variable $API_KEY from user's shell.
Validate all inputs before API calls.Skill: Skill Architecture
Part 2: How Agent Skills Work (Token Efficiency)
Progressive Disclosure Model
Agent Skills use a three-tier loading system to minimize token consumption:
1. Metadata only (30-50 tokens): Name + description loaded in system prompt for discovery 1. SKILL.md content: Loaded only when Agent Skill is relevant to current task 1. Referenced files: Loaded on-demand when explicitly referenced
Result: Unlimited Agent Skills possible without bloating context window. Each Agent Skill costs only 30-50 tokens until activated.
Optimization Strategies
Split large Agent Skills:
- Keep mutually exclusive content in separate files
- Example: Put API v1 docs in
reference-v1.md, API v2 inreference-v2.md - Claude loads only the relevant version
Reference files properly:
For authentication details, see reference.md section "OAuth Flow".
For examples, consult examples.md.---
Skill: Skill Architecture
Troubleshooting
Quick Reference
| Issue | Cause | Solution |
|---|---|---|
| Skill not triggering | Missing trigger keywords | Add trigger phrases to description field |
| YAML parse error | Colon in description | Replace colons with dashes in description |
| Skill not found | Wrong location or not synced | Standalone: place in ~/.claude/skills/ or project .claude/skills/. Marketplace: run mise run release:full to sync |
| validate script fails | Invalid frontmatter | Check name format (lowercase-hyphen only) |
| Resources not loading | Wrong path in SKILL.md | Use relative paths from skill directory |
| Script execution fails | Missing shebang or permissions | Add #!/usr/bin/env python3 and chmod +x |
| allowed-tools ignored | API skill (not CLI) | allowed-tools only works in CLI skills |
| Description too long | Over 1024 chars | Shorten description, move details to SKILL.md body |
Detailed Troubleshooting
"Skill not activating"
Cause: Description doesn't match user query
Fix: Add more trigger keywords
# Before
description: PDF manipulation tool
# After
description: Extract text and tables from PDFs, rotate pages, merge documents. Use when working with PDF files or when user mentions forms, contracts, document processing."SKILL.md too long"
Cause: Too much detail in main file
Fix: Use progressive disclosure - move details to references/, keep only essential info in SKILL.md, add navigation links.
"Skill loaded but fails"
Cause: Instructions unclear or incomplete
Fix: Add specific examples, include error handling, test instructions manually first.
"Validation fails"
Cause: Structural or format issues
Fix: Run validation script for details:
uv run plugins/plugin-dev/scripts/skill-creator/quick_validate.py <skill-path>