Agent Skills 是一种模块化扩展机制,通过文件系统级别的指令、脚本和资源打包,让 AI 代理按场景自动加载专业知识,避免重复提供提示词。文章深入讨论了 Skills 的工作原理(渐进式信息披露、三层加载模型)、目录结构与文件规范、编写技巧(精简、自由度控制、跨模型测试)、评估驱动开发以及脚本错误处理等关键实践,并以 C++ 代码审查为例给出可落地的项目结构。
---
name: your-skill-name
description: Brief description of what this Skill does and when to use it
---# Your Skill Name## Instructions
[Clear, step-by-step guidance for Claude to follow]
## Examples
[Concrete examples of using this Skill]
YAML 里 name 和 description 是必填的。name 作为唯一标识,限制小写字母、数字和连字符,最长 64 字符,不能用保留词 anthropic 或 claude。这种命名约定(kebab-case)和 npm 包名类似,避免文件系统引用的歧义。description 用于语义匹配,最长 1024 字符,也不能有 XML 标签。
字段
约束条件
说明
name
最长 64 字符 仅允许小写字母、数字和连字符 不得包含 XML 标签 不得使用保留词 anthropic、claude
## Deployment Workflow- [ ] Step 1: Run test suite and confirm all tests pass
- [ ] Step 2: Generate changelog from commit history
- [ ] Step 3: Update version number in package.json
- [ ] Step 4: Build production artifacts
- [ ] Step 5: Run validation script `./scripts/validate.py`- [ ] Step 6: Deploy to staging and verify
最有效的开发模式是让两个 Claude 实例配合:一个(Claude A)和你一起设计优化 Skill 指令,另一个独立实例(Claude B)用真实任务测试这些指令。Claude A 扮演指令作者,Claude B 是执行者。Claude 对 Agent 指令的编写和解读具有双向理解,能预判怎样的表述最容易被执行实例准确理解,也能根据执行偏差快速定位指令中的歧义。这比独自反复修改测试高效得多。
Skills 中的脚本执行
Skills 里的脚本承担确定性计算,结果回传模型推理。所以脚本健壮性直接影响整个 Skill 的可靠性。一个核心原则:脚本应自己处理错误,别把异常抛给模型。未处理的异常会导致 Claude 收到一堆错误堆栈,它得消耗 token 去分析原因,这既浪费又增加不确定性。
以文件处理为例,良好的错误处理会在内部闭环,遇到可预见的异常提供降级方案,并通过标准输出告知 Claude 发生了什么:
defprocess_file(path):
"""Process a file, creating it if it doesn't exist."""try:
withopen(path) as f:
return f.read()
except FileNotFoundError:
# 文件不存在时主动创建,而非让调用方处理异常print(f"File {path} not found, creating default")
withopen(path, "w") as f:
f.write("")
return""except PermissionError:
# 权限不足时返回默认值,避免流程中断print(f"Cannot access {path}, using default")
return""
---
name: cpp-code-review
description: >
Performs structured C/C++ code review focusing on memory safety,
coding standards, and performance.
Trigger when asked to review C or C++ source files, pull requests,
or code changes.
---# C/C++ Code Review## Instructions
When asked to review C/C++ code, follow these steps in order.
Copy the checklist from `checklist.md` into your response and check off items as you complete them.
### Step 1: Static Analysis
Run the include dependency check and complexity analysis:
```bash
python3 scripts/check_includes.py <target_directory>
python3 scripts/count_complexity.py <target_files>
Report any findings before proceeding.
Step 2: Memory Safety Review
Examine the code for memory-related issues:
Unmatched malloc/free or new/delete pairs
Buffer overflows from unchecked array indexing or strcpy
Use-after-free and dangling pointer risks
Missing null checks after allocation
Refer to common-issues.md Section 1 for detailed patterns.
Step 3: Coding Standards
Check adherence to project conventions:
Naming consistency (variables, functions, types)
Header guard correctness (#pragma once or #ifndef pattern)
Const correctness for function parameters and member functions
Step 4: Performance Considerations
Identify potential performance issues:
Unnecessary copies in loops (prefer references or std::move)
Repeated allocations that could be hoisted
Algorithm complexity mismatches for data scale
Step 5: Summary
Provide a severity-ranked list of all findings. Each finding must include:
file path, line number, severity (critical/warning/info), and a concrete fix suggestion.
References
checklist.md — Copy into response and track progress
common-issues.md — Detailed patterns for common C/C++ defects
all_findings = []
for arg in sys.argv[1:]:
path = Path(arg)
if path.is_file():
all_findings.extend(analyze_file(path))
elif path.is_dir():
for ext in ('*.c', '*.cpp', '*.cc', '*.h', '*.hpp'):
for f in path.rglob(ext):
all_findings.extend(analyze_file(f))
else:
print(f"SKIP: {arg} is not a valid file or directory")
ifnot all_findings:
print("OK: All functions are within complexity threshold "f"({COMPLEXITY_THRESHOLD})")
else:
print(f"FOUND: {len(all_findings)} function(s) exceed "f"complexity threshold ({COMPLEXITY_THRESHOLD}):\n")
for f insorted(all_findings, key=lambda x: -x['complexity']):
print(f" {f['file']}:{f['line']} — "f"{f['function']}() complexity={f['complexity']}")
if __name__ == '__main__':
main()
几个关键实践:COMPLEXITY_THRESHOLD 和 BRANCH_KEYWORDS 常量都附注释说明取值依据;FileNotFoundError 和 UnicodeDecodeError 在函数内捕获并输出 SKIP,不会让脚本崩溃;输出以 OK 或 FOUND 开头,结果按严重程度降序排列,便于模型优先处理复杂函数。
使用效果
当用户发出类似 'review the src/ directory for C++ issues' 的指令时,Claude 匹配到该 Skill,加载 SKILL.md,按工作流依次执行:先跑脚本做静态分析,再结合代码内容逐项检查清单,最后输出按严重等级排序的审查报告。脚本负责确定性度量,Claude 负责语义分析,各司其职。