2026年3月16日11 分鐘閱讀agent-skills

寫你的第一個 SKILL.md:逐步教學

從零開始建立一個可運作的 Agent Skill。涵蓋 SKILL.md frontmatter、body 結構、scripts、reference 檔案、測試與分享,附完整可複製貼上的範例。

DH
Danny Huang

什麼是 SKILL.md?

Skill 就是一個資料夾,裡面放一個 SKILL.md 檔案。那個檔案教 AI coding agent 一項專門能力。Agent 讀取它、判斷何時套用、然後執行 -- 跨 Claude Code、Codex CLI、GitHub Copilot、Gemini CLI 以及 35 個以上支援開放標準的平台都能通用。

Skill 出現之前,你每次都把長串指令貼進 system prompt 或聊天訊息。每一次。Skill 取代了這個做法。寫一次、結構化存放,之後任何 agent 進入你的專案都會自動讀取。

完整的生態系概觀 -- marketplace、安全審計、跨 agent 相容性、Superpowers framework -- 請參考 Agent Skills 完全指南

Skill 的檔案結構

每個 skill 住在一個目錄裡,結構如下:

my-skill/
├── SKILL.md          # 必要。進入點,包含 frontmatter 和指令。
├── scripts/           # 選用。Agent 可執行的 script。
├── references/        # 選用。需要時才載入的長篇文件。
└── assets/            # 選用。靜態檔案 -- 模板、logo、範例。

SKILL.md 是唯一必要的檔案。包含 YAML frontmatter(agent 啟動時讀取的 metadata)和 markdown body(實際指令)。Body 控制在 500 行以內。Agent 的 context window 有限,肥大的 skill 會拖累推理品質。

scripts/ 放確定性操作。SKILL.md 叫 agent 跑某個 script 時,agent 透過 bash 執行並只接收輸出。Script 原始碼不會進入 context window -- 只有執行結果會。驗證、格式化、資料轉換這類需要精確可重複行為的任務,就該用 script。

references/ 放詳細文件,agent 按需載入。這就是漸進式揭露(progressive disclosure)。Agent 先讀 SKILL.md -- 短、聚焦。只在任務需要更深 context 時才拉入 reference 檔案。API 文件、style guide、協議規範放這裡。

assets/ 放靜態檔案 -- 模板、範例輸出、icon、設定片段。這些不是指令,是 skill 操作或參考的素材。

第一步:Frontmatter

建目錄和 SKILL.md 檔案:

mkdir -p .claude/skills/commit-msg
touch .claude/skills/commit-msg/SKILL.md

開檔案,用 --- 標記寫 YAML frontmatter:

---
name: commit-msg
description: >
  Enforces Conventional Commits format for all git commit messages.
  Use this skill whenever the user asks to commit changes, create a
  commit message, or when you detect a git commit operation. Ensures
  every commit follows the pattern: type(scope): description.
  Supported types: feat, fix, docs, style, refactor, test, chore, perf, ci.
  Rejects commits that don't match the format.
---

兩個欄位最重要:

name -- 變成 /commit-msg slash command。只能用小寫字母、數字和連字號,最長 64 字元。使用者手動觸發 skill 時打這個。

description -- 主要觸發機制。使用者請求進來時,agent 讀所有 skill 的 description 來決定載入哪些。模糊的 description 代表 skill 幾乎不會被觸發。具體的 description 加上明確觸發條件,才會可靠地啟動。

怎麼寫好 Description

Description 有兩個用途:告訴 agent 這個 skill「做什麼」和「什麼時候啟動」。觸發條件要強勢、要明確。邊界情況也要涵蓋。

不好的 description:

Helps with commit messages.

Agent 不知道什麼時候該觸發。「Helps with」毫無意義。沒有觸發條件,沒有具體性。

好的 description:

Enforces Conventional Commits format for all git commit messages.
Use this skill whenever the user asks to commit changes, create a
commit message, or when you detect a git commit operation.

這清楚告訴 agent 做什麼(強制 Conventional Commits 格式)和什麼時候啟動(commit 操作、commit message 請求、偵測到 git commit)。Agent 可以做出明確的 yes/no 判斷。

選用的 Frontmatter 欄位

allowed-tools -- 用 glob pattern 限制 skill 可用的工具。對安全敏感的 skill 很有用。例如:allowed-tools: ["Bash", "Read"] 限制 skill 只能讀檔和跑命令,阻止它發 network request 或編輯專案外的檔案。

disable-model-invocation -- 設為 true 阻止自動觸發。Skill 只透過 /name slash command 啟動。適合有副作用且時機重要的 skill -- deploy skill、資料庫 migration skill、任何具破壞性的操作。

第二步:寫 Body

Body 放在 frontmatter 下方。三段式結構:什麼時候觸發做什麼怎麼做

以下是 Conventional Commits skill 的完整 SKILL.md

---
name: commit-msg
description: >
  Enforces Conventional Commits format for all git commit messages.
  Use this skill whenever the user asks to commit changes, create a
  commit message, or when you detect a git commit operation. Ensures
  every commit follows the pattern: type(scope): description.
  Supported types: feat, fix, docs, style, refactor, test, chore, perf, ci.
  Rejects commits that don't match the format.
---

# Conventional Commit Messages

## When to Activate

Activate this skill when:
- The user asks you to commit changes
- The user asks you to write a commit message
- You are about to run `git commit` as part of a larger task
- The user asks to amend a commit message

## Commit Format

Every commit message MUST follow this pattern:

type(scope): short description

[optional body]

[optional footer]


### Allowed Types

| Type | When to Use |
|------|------------|
| feat | A new feature visible to users |
| fix | A bug fix |
| docs | Documentation-only changes |
| style | Formatting, semicolons, whitespace — no logic change |
| refactor | Code restructuring that doesn't fix a bug or add a feature |
| test | Adding or correcting tests |
| chore | Build, tooling, dependency updates |
| perf | Performance improvement |
| ci | CI/CD configuration changes |

### Rules

1. Type is required. Scope is optional but encouraged.
2. Description starts with lowercase, no period at the end.
3. Description is imperative mood: "add feature" not "added feature".
4. Body wraps at 72 characters.
5. Breaking changes MUST include `BREAKING CHANGE:` in the footer.
6. If multiple logical changes exist, suggest splitting into separate commits.

### Examples

Good:
- `feat(auth): add OAuth2 login with Google provider`
- `fix(api): handle null response from payment gateway`
- `refactor(db): extract connection pooling into shared module`

Bad:
- `updated stuff` — no type, vague description
- `Fix: Bug` — wrong format, not descriptive
- `feat: Added new feature for users.` — past tense, period, vague

## Process

1. Analyze the staged changes with `git diff --cached`
2. Determine the appropriate type based on the nature of changes
3. Identify the scope from the primary directory or module affected
4. Write a concise description in imperative mood
5. If changes are complex, add a body explaining the "why"
6. Present the commit message to the user for approval before committing

結構是刻意的。Agent 讀「When to Activate」確認 skill 適用。讀格式區塊理解規則。讀流程區塊知道執行步驟。每個區塊自足 -- 搜尋引擎或 AI 概覽摘出任何單獨區塊,都能獨立理解。

第三步:加入 Script

有些任務該寫成 script,不是指令。判斷原則:任務是確定性的,用自然語言描述會脆弱,就寫 script。

Commit message 驗證是好例子。與其期望 agent 從文字描述正確實作 regex 驗證,不如給它 script:

mkdir -p .claude/skills/commit-msg/scripts

.claude/skills/commit-msg/scripts/validate.sh

#!/bin/bash
# Validates a commit message against Conventional Commits format.
# Usage: ./validate.sh "feat(auth): add login"
# Exit 0 = valid, Exit 1 = invalid with error message.

MSG="$1"

if [ -z "$MSG" ]; then
  echo "Error: No commit message provided."
  exit 1
fi

PATTERN='^(feat|fix|docs|style|refactor|test|chore|perf|ci)(\([a-z0-9-]+\))?: .+$'

FIRST_LINE=$(echo "$MSG" | head -n1)

if ! echo "$FIRST_LINE" | grep -qE "$PATTERN"; then
  echo "Invalid commit message: '$FIRST_LINE'"
  echo ""
  echo "Expected format: type(scope): description"
  echo "Allowed types: feat, fix, docs, style, refactor, test, chore, perf, ci"
  exit 1
fi

if echo "$FIRST_LINE" | grep -qE '\.$'; then
  echo "Invalid: description should not end with a period."
  exit 1
fi

echo "Valid commit message."
exit 0

在 SKILL.md body 裡引用:

## Validation

Before committing, validate the message by running:

```bash
bash .claude/skills/commit-msg/scripts/validate.sh "your commit message here"

If validation fails, fix the message and re-validate.

Agent 跑 script 時透過 bash 執行,只接收 stdout/stderr 輸出。Script 原始碼不進 context。Context window 乾淨,驗證行為完全確定性。

第四步:Reference 檔案

Reference 檔案解決 SKILL.md 太長的問題。如果 skill 需要知道大型 API、詳細 style guide 或複雜協議,放到 reference 檔案,告訴 agent 什麼時候讀。

.claude/skills/commit-msg/references/team-conventions.md

# Team Commit Conventions

## Scope Naming

Our project uses these scope names consistently:

| Scope | Meaning |
|-------|---------|
| api | Backend API routes |
| ui | Frontend React components |
| db | Database schemas and migrations |
| auth | Authentication and authorization |
| config | Configuration and environment |
| ci | CI/CD pipelines |
| deps | Dependency updates |

## Breaking Change Policy

Breaking changes require:
1. `BREAKING CHANGE:` footer in the commit
2. A linked issue or RFC number
3. Migration notes in the commit body

## Multi-Package Repos

For monorepo commits affecting multiple packages:
- Use the most-affected package as scope
- List other affected packages in the commit body
- If truly cross-cutting, omit scope entirely

## Release Automation

Our CI reads commit types to auto-generate changelogs:
- `feat` → "Features" section, triggers minor version bump
- `fix` → "Bug Fixes" section, triggers patch version bump
- `BREAKING CHANGE` → triggers major version bump
- All other types → excluded from changelog

在 SKILL.md 裡引用:

## Team-Specific Conventions

For scope naming, breaking change policy, and release automation rules,
read the reference file at `references/team-conventions.md`.
Only load this file when the user asks about scopes, breaking changes,
or when you encounter an ambiguous situation.

這就是漸進式揭露的實際運作。Agent 先載 SKILL.md -- 短、聚焦。只在任務涉及 scope 命名或 breaking change 時才載 reference 檔案 -- 詳細、具體。Context 保持精簡。關於漸進式揭露及其對 agent 效能影響的完整說明,請見 Agent Skills 完全指南

第五步:測試你的 Skill

沒有測過的 skill 就是不能用的 skill。以下是驗證方法。

安裝 Skill

放在 .claude/skills/ 裡的話,Claude Code 已經自動安裝了。Claude Code 在專案啟動 session 時會自動註冊 skill。

其他 agent 的安裝路徑不同 -- Codex CLI 用 .codex/skills/、Copilot 用 .github/skills/。SKILL.md 格式在所有平台都一樣。各 AI CLI 工具的 skill 目錄完整比較,請見連結中的指南。

手動觸發

直接打 slash command:

/commit-msg

Claude Code 載入完整 SKILL.md body 並進入 skill 的 context。用 prompt 測試:

I've staged changes to the auth module. Write me a commit message.

驗證 agent 是否遵循格式規則、選對 type、建議適當 scope。

自動觸發測試

測試 skill 不用 slash command 也能啟動。開新 session,直接問:

Commit the current staged changes.

Description 寫得好的話,agent 應該自動載入 commit-msg skill 並產出 Conventional Commits 格式。沒觸發的話,description 需要修改 -- 把觸發條件寫得更明確。

用特定 Prompt 除錯

測邊界情況:

  • "Commit these changes"(應該觸發)
  • "Write a commit message for this refactor"(應該觸發)
  • "What did the last commit change?"(不該觸發 -- 讀取操作,不是 commit)
  • "Amend the last commit message"(應該觸發)

Skill 在不該觸發的 prompt 上觸發了,收窄 description。在該觸發的 prompt 上沒觸發,拓寬 description 或加入更多觸發條件。

Termdock 工作流

最快的測試迴圈:一邊在一個終端面板編輯 SKILL.md,一邊在另一個面板測試。改一條規則、切到 agent 面板、觸發 skill、觀察、切回去、迭代。沒有視窗管理開銷,沒有 tab 切換。就是 authoring 和 testing 之間的緊密 feedback loop。

Try Termdock Drag Resize Terminals works out of the box. Free download →

第六步:分享你的 Skill

Skill 存在三個層級:

個人 -- 放在 ~/.claude/skills/(或 agent 對應的路徑)。每個專案都會載入。適合個人偏好:commit 風格、code review checklist、偏好的錯誤處理模式。

專案 -- 放在專案 repository 的 .claude/skills/。專案上的所有人都會載入。適合團隊慣例:commit 格式、API 設計規則、測試要求。把 skill 目錄 commit 到 git,全隊都能用。

Marketplace -- 發佈到 skill marketplace(SkillsMP、Skills.sh、ClawHub)讓任何人安裝。具廣泛通用性的 skill:Conventional Commits skill、code review skill、dependency audit skill。發佈需要打包 skill 目錄並提交到 marketplace 的 registry。

從 GitHub 安裝

Skill 可以直接從 GitHub URL 安裝:

claude skill install github.com/username/my-commit-skill

把 skill 目錄 clone 到本地 skill 資料夾。立即可用,不需重啟。

Codex CLI 的做法:

codex skill add github.com/username/my-commit-skill

格式完全一樣。Agent 讀同一份 SKILL.md、同批 script、同批 reference。寫一次,在任何支援標準的 agent 上都能跑。

常見錯誤

Description 太模糊。 像「helps with code」這種 description 永遠不會自動觸發,因為它什麼都匹配也什麼都不匹配。Agent 無法判斷什麼時候該用。修法:加明確觸發條件 -- 「Use when the user asks to...」、「Activate when you detect...」。

SKILL.md 太長。 超過 500 行的 skill 消耗太多 context。Context 充滿指令而非實際要處理的程式碼時,agent 推理品質會下降。修法:詳細內容搬到 reference 檔案。SKILL.md 應該是概覽和導航中心,不是百科全書。

過度指定 HOW 而不是 WHY。 指令像「run git add . then run git commit -m」很脆弱。Agent 知道怎麼跑 git 命令。它不知道的是你們團隊的慣例 -- 也就是 WHY。修法:解釋原則和規則,讓 agent 自己想出實作方式。「All commits must use Conventional Commits format with these allowed types...」比一步步的 shell script 好得多。

沒有觸發條件。 SKILL.md 解釋了做什麼但從不說什麼時候啟動,就是只能靠 slash command 才能用的 skill。要自動觸發,body 裡需要清楚的「When to Activate」區塊,讓 agent 能拿來比對當前任務。

寫死路徑。 引用絕對路徑(/Users/john/project/src/...)的 skill 對其他人全部不能用。用專案根目錄的相對路徑,或讓 agent 動態發現路徑。

完整範例:「Code Review」Skill

以下是完整、可運作的 skill,可以直接複製到專案裡用。包含 SKILL.md 和 reference 檔案。

目錄結構

.claude/skills/code-review/
├── SKILL.md
└── references/
    └── review-checklist.md

SKILL.md

---
name: code-review
description: >
  Performs structured code reviews following the team's quality standards.
  Use this skill when the user asks to review code, review a PR, review
  changes, check code quality, or when you detect a code review request.
  Covers correctness, security, performance, readability, and test coverage.
  Outputs a structured review with severity ratings for each finding.
---

# Code Review Skill

## When to Activate

Activate when:
- The user asks you to review code or a pull request
- The user asks to "check" or "audit" specific files
- The user asks about code quality of recent changes
- You are asked to compare code before and after a change

Do NOT activate when:
- The user asks you to write or implement code (that is a coding task, not a review)
- The user asks about git history without requesting quality feedback

## Review Process

1. **Identify the scope.** Determine which files or changes to review.
   - If reviewing staged changes: `git diff --cached`
   - If reviewing a branch: `git diff main...HEAD`
   - If reviewing specific files: read them directly

2. **Analyze each file.** For every file in scope, evaluate against
   the checklist in `references/review-checklist.md`.

3. **Classify findings.** Every finding gets a severity:
   - **Critical** — Will cause bugs, security issues, or data loss. Must fix.
   - **Warning** — Code smell, performance risk, or maintainability issue. Should fix.
   - **Suggestion** — Style preference, minor improvement. Nice to fix.

4. **Output the review** in this format:

Code Review: [scope description]

Summary

[1-3 sentence overall assessment]

Findings

Critical

  • [file:line] — [description of issue and why it matters]

Warnings

  • [file:line] — [description and recommendation]

Suggestions

  • [file:line] — [description and recommendation]

Verdict

[APPROVE / REQUEST CHANGES / NEEDS DISCUSSION]


5. **If no issues found**, say so explicitly. Do not invent problems.

## Principles

- Review the code, not the author.
- Every finding must explain WHY it is a problem, not just WHAT is wrong.
- Prefer fewer high-quality findings over many nitpicks.
- If you are uncertain about a finding, flag it as "Suggestion" with a note.
- Acknowledge good patterns when you see them.

references/review-checklist.md

# Code Review Checklist

## Correctness
- [ ] Does the code do what it claims to do?
- [ ] Are edge cases handled (null, empty, negative, overflow)?
- [ ] Are error paths tested, not just happy paths?
- [ ] Do async operations handle failures and timeouts?

## Security
- [ ] No secrets hardcoded (API keys, passwords, tokens)
- [ ] User input is validated and sanitized
- [ ] SQL queries use parameterized statements
- [ ] Authentication checks are present where needed
- [ ] No overly permissive CORS or CSP headers

## Performance
- [ ] No N+1 query patterns
- [ ] Large collections are paginated, not loaded entirely
- [ ] Expensive operations are cached where appropriate
- [ ] No unnecessary re-renders in React components
- [ ] Database indexes exist for queried columns

## Readability
- [ ] Functions are under 40 lines
- [ ] Nesting depth is 3 levels or fewer
- [ ] Variable names describe what they hold
- [ ] Comments explain WHY, not WHAT
- [ ] No dead code or commented-out blocks

## Testing
- [ ] New code has corresponding tests
- [ ] Tests cover both success and failure cases
- [ ] Tests are deterministic (no flaky assertions)
- [ ] Test names describe the behavior being verified
- [ ] Mocks are minimal — prefer real implementations

## Architecture
- [ ] Changes follow existing project patterns
- [ ] No circular dependencies introduced
- [ ] Public API surface is minimal
- [ ] Breaking changes are documented
- [ ] Backward compatibility is maintained

code-review 目錄複製到任何專案的 .claude/skills/。啟動 Claude Code(或任何相容 agent),打 /code-review 或問「review the changes on this branch」。Agent 載入 skill、遵循 review 流程、按需引用 checklist,輸出結構化 review。

這是你每天都會用的 skill。把 checklist 改成符合團隊標準的版本。加 domain-specific 的 reference 檔案 -- fintech 的安全 checklist、即時系統的效能 checklist、前端的無障礙 checklist。

DH
Free Download

Ready to streamline your terminal workflow?

Multi-terminal drag-and-drop layout, workspace Git sync, built-in AI integration, AST code analysis — all in one app.

Download Termdock →
#skill-md#agent-skills#claude-code#tutorial

相關文章