じゃあ、おうちで学べる

本能を呼び覚ますこのコードに、君は抗えるか

Claude Code の .claude/commands/**.md は設定した方がいい

はじめに

Claude Code でよく同じコメントを打ってませんか?

「毎回『テスト実行して、lint チェックして、問題なければコミットして』って言うの面倒だな」とか「プロジェクトごとに決まった手順があるんだけど、毎回説明するのダルい」とか思ったことないですか?

そんなあなたに朗報です。

Claude Code にはカスタムスラッシュコマンドという機能があって、よく使うプロンプトをコマンド化できるんです。しかも設定は超簡単。Markdownファイルを置くだけ。手順書やMakefile自然言語で書ける時代ですね⋯。

docs.anthropic.com

正直なところ、この機能を知ったときは「え、こんな便利な機能あったの?」って感じでした。公式ドキュメントをちゃんと読んでない自分を殴りたくなりました。というか書くって言って書いてはいてかなり前なのにいろいろやることがあって公開は遅れました。人生とは難しいものです。

というわけで今回は、.claude/commands/**.md の設定方法と、実際に私が使っている設定を紹介します。あなたの開発効率が爆上がりすること間違いなしです。

このブログが良ければ読者になったりnwiizoXGithubをフォロワーしてくれると嬉しいです。では、早速はじめていきます。

📣 アップデート情報(v1.0.25)
直近のアップデートで、カスタムコマンドの呼び出しがさらに簡単になりました!以前は/project:/user:というプレフィックスが必要でしたが、v1.0.25からはプレフィックス不要で直接コマンド名を入力できるようになりました。また、コマンド検出の安定性も向上しています。

謝辞:検証のタイミングと公開のタイミングがズレた為ぬこぬこさんがアップデート情報を教えてくれました。ありがとうございます。

カスタムスラッシュコマンドとは何か

まず基本から。Claude Code には元々いくつかのビルトインコマンドがあります。

/help     # ヘルプを表示
/clear    # 会話履歴をクリア
/memory   # CLAUDE.mdを編集
/cost     # トークン使用量を確認
/mcp      # MCP関連(v1.0.24で改善)

これらに加えて、自分でコマンドを定義できるのがカスタムスラッシュコマンドです。

仕組みは簡単で、.claude/commands/ ディレクトリにMarkdownファイルを置くとファイル名がコマンド名になり、ファイルの中身がプロンプトとして使われます。例えば、.claude/commands/test-and-commit.md というファイルを作れば、/test-and-commit というコマンドが使えるようになります。

v1.0.25での表示形式:

コマンドを入力すると、以下のような形式で候補が表示されます:

/test-and-commit     Test and Commit (project)

コマンド名の後に、Markdownファイルの最初の見出し(# Test and Commit)が説明として表示され、最後の (project) はプロジェクトスコープのコマンドであることを示します。

2種類のコマンドスコープとプレフィックスフリーな呼び出し

カスタムコマンドには2つのスコープがあります。

プロジェクトコマンド(推奨).claude/commands/ に配置し、プロジェクト固有の作業に使います。チームで共有でき、表示形式は /command-name Command Description (project) となります。

個人コマンド~/.claude/commands/ に配置し、全プロジェクトで使う個人的なコマンドに適しています。表示形式は /command-name Command Description (user) となります。

v1.0.25以降の呼び出し方法:

# 新しい方法(v1.0.25以降)
/test-and-commit

# 従来の方法(後方互換性のため引き続き使用可能)
/project:test-and-commit  # プロジェクトコマンド
/user:test-and-commit     # 個人コマンド

v1.0.25のアップデートにより、どちらのスコープのコマンドもプレフィックスなしで呼び出せるようになりました。同名のコマンドが複数のスコープに存在する場合は、プロジェクトコマンドが優先されます。明示的にスコープを指定したい場合は、従来通りプレフィックスを使用することも可能です。

私は基本的にプロジェクトコマンドを使ってます。Gitで管理できるし、チームメンバーと共有できるから。

なぜカスタムコマンドが必要なのか

「プロンプトをコピペすればいいじゃん」と思うかもしれません。そう思ってた時期が僕にもありました。

でも実際に使ってみると、カスタムコマンドには大きなメリットがあります。

1. 一貫性の担保と再現性

毎回微妙に違うプロンプトを打つと、AIの挙動も微妙に変わります。カスタムコマンドなら、常に同じプロンプトが実行されるので、結果が安定します。

実例:

# 悪い例(毎回微妙に違う)
"テスト実行して問題なければコミットして"
"テストを走らせてからコミットお願い"
"test実行→コミット"

# 良い例(カスタムコマンド)
/test-and-commit
# → 常に同じ手順で、同じ品質チェックが実行される

特に、AIモデルがアップデートされても、コマンドの指示が明確なので動作が安定します。

2. チーム開発での標準化とオンボーディング

「PRを作るときはこの手順で」「デプロイ前にはこのチェックを」みたいなチームのルールを、コマンドとして標準化できます。新しいメンバーが入ってきても、コマンドを実行するだけでOK。

具体的な効果:

  • 新人の立ち上がり時間: 2週間 → 2日
  • レビュー指摘の減少: 「lint忘れてます」「テスト回してください」がゼロに
  • ドキュメント不要: コマンド自体が生きたドキュメント
# 新人でも初日から正しい手順でPRが作れる
/create-pr feature/user-authentication

3. 複雑な作業の自動化と時間節約

長いプロンプトや、複数ステップの作業をワンコマンドで実行できます。私の場合、「テスト→lint→型チェック→コミット」という一連の流れを1つのコマンドにまとめてます。

時間節約の実例:

手動の場合(毎回入力):
- プロンプト入力: 30秒
- 指示の修正や追加: 20秒
- 合計: 50秒 × 1日20回 = 約17分/日

カスタムコマンドの場合:
- コマンド入力: 3秒
- 節約時間: 47秒 × 20回 = 約16分/日
- 年間節約時間: 約64時間!

4. 引数による柔軟性と再利用性

$ARGUMENTS プレースホルダーを使えば、動的な値を渡せます。同じコマンドを様々な状況で使い回せます。

# コンポーネント作成
/create-component Button
/create-component Modal
/create-component Card

# API エンドポイント作成
/create-api users GET
/create-api products POST
/create-api orders DELETE

5. プロンプトのバージョン管理

カスタムコマンドはGitで管理できるので、プロンプトの改善履歴が追跡できます。

# プロンプトの改善が見える化される
git log .claude/commands/test-and-commit.md

# チームでプロンプトを改善
git checkout -b improve-test-command
# コマンドを編集
git commit -m "feat: add performance test to test-and-commit command"

6. コンテキストとベストプラクティスの埋め込み

プロジェクト固有の知識や制約をコマンドに埋め込めます。

# プロジェクト固有の知識を含むコマンド例
This is a Next.js 14 project using:
- App Router (not Pages Router)
- Server Components by default
- Tailwind CSS for styling
- Prisma for database
- Our custom design system components from @/components/ui/

Always consider these when implementing features.

7. エラー処理とロールバックの自動化

手動だと忘れがちなエラー処理も、コマンドに組み込んでおけば安心です。

If any test fails:
1. Run the failed test in isolation with verbose output
2. Check if it's a flaky test (run 3 times)
3. If consistently failing, rollback any changes made
4. Generate an error report with:
   - Failed test name and file
   - Error message and stack trace
   - Git diff of changes made

これらのメリットを一度体験すると、もうカスタムコマンドなしの開発には戻れません。最初の設定に10分かけるだけで、その後の開発効率が劇的に向上します。

基本的な使い方

では、実際にカスタムコマンドを作ってみましょう。

ステップ1:ディレクトリ作成

mkdir -p .claude/commands

ステップ2:コマンドファイル作成

例として、テストを実行してからコミットするコマンドを作ります。

.claude/commands/test-and-commit.md:

# Test and Commit

Please follow these steps:

1. Run all tests using `npm test`
2. If tests pass, check for linting issues with `npm run lint`
3. If both pass, create a commit with a descriptive message
4. Show me the test results and commit hash

Make sure to stop if any step fails and show me the error.

ポイント: - ファイルの最初の見出し(# Test and Commit)がコマンドの説明として表示されます - この説明は、コマンド選択時に /test-and-commit Test and Commit (project) のような形で表示されます - 分かりやすい見出しを付けることで、コマンドの用途が一目で分かるようになります

ステップ3:実行

# v1.0.25以降(推奨)
/test-and-commit

# 従来の方法(引き続き使用可能)
/project:test-and-commit

たったこれだけ!簡単でしょ?

サンプル集:プロに学ぶコマンド設計

まず、素晴らしいサンプルリポジトリを紹介します。

プロフェッショナルなコマンドテンプレート集

Claude-Command-Suiteは、ソフトウェア開発のベストプラクティスに基づいた、包括的なカスタムコマンドのコレクションです。

主要なコマンド:

  • コードレビュー系

  • 開発ワークフロー系

    • /create-feature - 機能開発の全工程を自動化
    • /fix-issue - GitHub issue解決ワークフロー
    • /refactor-code - 安全なリファクタリング
    • /debug-error - 体系的なデバッグアプローチ

これらのコマンドは、Anthropic公式のベストプラクティスに準拠しており、そのまま使えるクオリティです。インストールもinstall.sh が配備されております。

Sphinxドキュメント自動化の実例

drillerさんの記事では、Sphinxを使ったドキュメント生成を自動化する実践的な例が紹介されています。

3つのコマンドでドキュメント管理を完全自動化:

  1. /sphinx-create - プロジェクト初期化
  2. /sphinx-update - 設定更新
  3. /sphinx-build - ドキュメントビルド

特に素晴らしいのは、複雑なSphinxの設定を.claude/docs/config/に外部化している点。これにより、Sphinxを知らない人でも簡単にドキュメントを生成できます。

私の例

私が実際に使っているコマンドもいくつか紹介します。ccswarmというプロジェクトで使ってるものです。

1. 複雑なビルドプロセスの自動化

.claude/commands/build-all.md:

# Build All Targets

Build all components of the ccswarm project in the correct order:

1. Clean previous builds: `rm -rf dist/`
2. Build shared libraries first
3. Build main application
4. Build plugins
5. Run integration tests
6. Generate build report

Show progress for each step and summarize any warnings or errors at the end.

このコマンドで、複雑な依存関係があるプロジェクトでも、正しい順序でビルドできます。

2. セキュリティチェック

.claude/commands/security-check.md:

# Security Audit

Perform a comprehensive security check:

1. Run `npm audit` and analyze vulnerabilities
2. Check for exposed secrets using git-secrets
3. Scan for common security anti-patterns in the code
4. Review authentication and authorization logic
5. Generate a security report with recommendations

Focus on critical and high severity issues first.

定期的なセキュリティチェックも、コマンド一発で実行できます。

3. リリース準備

.claude/commands/prepare-release.md:

# Prepare Release

Prepare for a new release with version: $ARGUMENTS

Steps:
1. Update version in package.json
2. Generate CHANGELOG.md from git commits
3. Run full test suite
4. Build production bundle
5. Create git tag
6. Generate release notes

If any step fails, rollback changes and notify me.

使用例:

# v1.0.25以降
/prepare-release v1.2.0

# 従来の方法
/project:prepare-release v1.2.0

高度な活用法

ネームスペースの活用

サブディレクトリを使えば、コマンドを整理できます:

.claude/commands/
├── frontend/
│   ├── component.md      # /component (project:frontend)
│   └── style-check.md    # /style-check (project:frontend)
├── backend/
│   ├── migration.md      # /migration (project:backend)
│   └── api-test.md       # /api-test (project:backend)
└── deploy/
    ├── staging.md        # /staging (project:deploy)
    └── production.md     # /production (project:deploy)

v1.0.25での変更点: - サブディレクトリ内のコマンドもファイル名だけで呼び出せるようになりました - コマンド候補の表示形式: /component Create Component (project:frontend) /style-check Style Check (project:frontend) /migration Database Migration (project:backend) - Markdownファイルの最初の見出しが説明として表示されます - 括弧内にディレクトリ構造が表示され、どこに配置されているか一目で分かります

同名のコマンドが複数のディレクトリにある場合の動作: - すべての候補が表示され、選択できます - 例:frontend/test.mdbackend/test.md がある場合、/test と入力すると両方が候補として表示されます

大規模プロジェクトでは、この構造化が本当に役立ちます。ディレクトリで論理的に整理しつつ、シンプルなコマンド名で呼び出せるベストな仕組みです。

Orchestratorパターン

mizchiさんの記事で紹介されている、複雑なタスクを分解実行するパターンも超便利です。

.claude/commands/orchestrator.md:

# Orchestrator

Split complex tasks into sequential steps, where each step can contain multiple parallel subtasks.

[詳細な実装は長いので省略]

これを使うと、「分析→並列実行→結果統合」みたいな複雑なワークフローも自動化できます。

コマンド作成のベストプラクティス

使ってみてこんなふうにするとみたいなやつです。

1. 明確で具体的に

# 悪い例
Do the usual checks and commit

# 良い例(Rustプロジェクトの場合)
1. Run `cargo test` and ensure all tests pass
2. Run `cargo clippy -- -D warnings` and fix any lints
3. Run `cargo fmt --check` for formatting validation
4. Run `cargo check` for compilation errors
5. If all pass, commit with conventional commit format

2. エラーハンドリングを明記

If any step fails:
- Stop execution immediately
- Show the full error message with cargo's verbose output
- For test failures, show the specific test name and assertion
- For clippy warnings, provide the lint name and suggested fix
- Do NOT proceed to the next step

3. 出力フォーマットを指定

After completion, provide a summary in this format:
- Tests: ✅ Passed (42/42)
- Clippy: ✅ No warnings
- Format: ✅ Properly formatted
- Build: ✅ Clean compilation
- Commit: abc123 - feat: add new parser module

4. コンテキストを含める

This is a Rust project using:
- Rust 2021 edition
- Clippy with pedantic lints enabled
- cargo-nextest for parallel test execution
- Conventional commits
- workspace with multiple crates

Keep these constraints in mind when executing commands.

この辺はプロンプトエンジニアリングの原則に近いです。

実際のRustプロジェクト用コマンド例

Rustのベストプラクティスに基づいた、より実践的なコマンドを紹介します:

.claude/commands/rust-check-all.md:

# Comprehensive Rust Check

Perform a complete quality check for this Rust project using modern best practices.

## Environment check
First, check for optimal tooling:
- Verify cargo-nextest is installed (suggest installation if missing)
- Check for cargo-audit availability
- Confirm clippy and rustfmt are available

## Pre-flight checks
1. **Working directory status**
   - Run `git status --porcelain` to check for uncommitted changes
   - If changes exist, list them clearly
   - Ensure we're on the correct branch

2. **Dependency status**
   - Run `cargo tree --duplicate` to find duplicate dependencies
   - Check for outdated dependencies with `cargo outdated` if available
   - Note any security advisories

## Quality checks sequence

1. **Fast syntax check**
   - Run `cargo check --all-targets --all-features`
   - This is the fastest way to catch compilation errors
   - Stop immediately if this fails

2. **Format check**
   - Run `cargo fmt --all -- --check`
   - If formatting issues found:
     - Show diff of required changes
     - Offer to fix automatically with `cargo fmt --all`

3. **Clippy analysis (progressive)**
   First, standard lints:
   - Run `cargo clippy --all-targets --all-features -- -D warnings`
   
   If user requests pedantic mode:
   - Run `cargo clippy --all-targets --all-features -- -W clippy::pedantic`
   - Group warnings by category (style, complexity, performance, etc.)
   - For each warning, show:
     - File and line number
     - The specific lint rule
     - A brief explanation of why it matters

4. **Test execution (optimized)**
   Check for cargo-nextest first:
   - If available: `cargo nextest run --all-features`
     - Benefits: Faster execution, better output, automatic retry support
   - If not available: `cargo test --all-features`
   
   For test failures:
   - Show test name and module path
   - Display assertion failure details
   - Include relevant source code snippet
   - If using nextest, note any flaky tests (passed on retry)

5. **Documentation check**
   - Run `cargo doc --no-deps --all-features --document-private-items`
   - Check for broken intra-doc links
   - Verify all public APIs have documentation
   - Run doctests: `cargo test --doc`

6. **Benchmarks** (if present)
   - Check for benches with `cargo bench --no-run`
   - If benchmarks exist, offer to run them

7. **Security audit**
   If cargo-audit is installed:
   - Run `cargo audit --deny warnings`
   - Group vulnerabilities by severity
   - Provide upgrade recommendations

## Advanced checks (optional)

8. **Build optimization check**
   - Analyze Cargo.toml for optimization opportunities
   - Check if release profile is properly configured
   - Look for unnecessary features being compiled

9. **Code coverage** (if requested)
   - Check for cargo-tarpaulin or cargo-llvm-cov
   - Offer to generate coverage report

## Summary format
After all checks complete, provide a comprehensive summary:

---
🦀 Rust Project Quality Report
================================
📊 Project: {name} v{version}

Checks Summary:
📋 Syntax:       ✅ Clean
📐 Format:       ✅ Properly formatted
🔍 Clippy:       ⚠️  3 warnings (2 style, 1 complexity)
🧪 Tests:        ✅ 156/156 passed (4.2s)
📚 Docs:         ✅ 100% documented
🔒 Security:     ✅ No known vulnerabilities
⚡ Performance:  ℹ️  Consider enabling lto in release

Clippy Warnings Summary:
- redundant_closure_for_method_calls (2 occurrences)
- unnecessary_wraps (1 occurrence)

Test Performance:
- Fastest: test_parse_simple (12ms)
- Slowest: integration::test_full_workflow (823ms)
- Total duration: 4.2s (with nextest parallelization)

Recommendations:
1. Address clippy warnings for cleaner code
2. Consider splitting slow integration tests
3. Enable link-time optimization for release builds

Ready to commit! Suggested message:
"test: improve parser coverage and fix edge cases"
---

## Error handling
- If any critical check fails (syntax, tests, security):
  - Stop execution and focus on that issue
  - Provide specific fix suggestions
  - Offer relevant documentation links
- For non-critical issues (style, some clippy warnings):
  - Continue checking but note them in summary
  - Prioritize fixes by impact

## Performance tips
- Use `cargo check` before `cargo build`
- Leverage cargo-nextest for 30-60% faster test runs
- Consider `sccache` for faster rebuilds
- Use `--jobs` flag for parallel compilation

このコマンドは、cargo-nextestという高速なテストランナーや、Clippyのpedanticモードなどのより厳格なリントを活用しています。また、セキュリティ監査や依存関係のチェックなど、実際のプロジェクトで必要な包括的なチェックを含んでいます。

知っておくと便利なTips

Git管理について

コマンドファイルは必ずGitに含めるべきです。.claude/commands/ はプロジェクトの一部として管理することで、チーム全体で同じワークフローを共有できます。これがカスタムコマンドの大きなメリットの一つです。

個人的な設定が必要な場合は、~/.claude/commands/ に個人用コマンドを配置するか、.gitignore に特定のコマンドを追加する方法があります。例えば、個人的なデバッグ用コマンドなどは共有する必要がないかもしれません。

コマンドの長さと複雑さ

Markdownファイルなので、必要なだけ詳細に書くことができます。1000行のコマンドでも問題なく動作します。ただし、あまりに複雑になってきた場合は、複数のコマンドに分割することを検討してください。保守性を考えると、1つのコマンドは1つの明確な目的を持つべきです。

命名の競合について

v1.0.25以降、プレフィックスが不要になったことで、ビルトインコマンドとの名前の競合に注意が必要です。ただし、カスタムコマンドがビルトインコマンドと同名の場合でも、ビルトインコマンドが優先されるため、システムが壊れることはありません。

プロジェクトコマンドと個人コマンドで同名のものがある場合、プロジェクトコマンドが優先されます。明示的にスコープを指定したい場合は、従来通りプレフィックスを使用できます:

/user:build    # 個人コマンドを明示的に指定
/project:build # プロジェクトコマンドを明示的に指定

コマンドの説明を追加する

@budougumi0617さんに教えていただいた便利な機能があります。Markdownファイルの先頭にfrontmatterを記述することで、コマンド一覧により詳細な説明を表示できます。

使い方:

---
description: "プロジェクトの全コンポーネントを正しい順序でビルドし、テストを実行します"
---

# Build All Targets

Build all components of the ccswarm project in the correct order:
[以下、コマンドの内容]

表示例:

/build-all     Build All Targets - プロジェクトの全コンポーネントを正しい順序でビルドし、テストを実行します (project)

このように、frontmatterのdescriptionフィールドに記載した内容が、コマンド候補の一覧に表示されます。これにより、標準のスラッシュコマンドのように、コマンドを選択する前にその用途を詳しく確認できます。

特に複数の似たようなコマンドがある場合、この説明があることで適切なコマンドを素早く選択できるようになります。チーム開発では、新しいメンバーがコマンドの用途を理解しやすくなるという利点もあります。

トラブルシューティング

コマンドが認識されない時

まず確認すべきは、ファイルの拡張子が.mdになっているかどうかです。.markdown.txtでは認識されません。また、ファイル名に特殊文字(スペースや日本語など)が含まれていると問題が起きることがあります。

v1.0.25ではコマンド検出の安定性が改善されているため、以前よりも認識の問題は少なくなっています。それでも認識されない場合は、Claude Codeを再起動してみてください。

引数が正しく渡されない時

$ARGUMENTSプレースホルダーは完全一致である必要があります。

  • $arguments(小文字)
  • ${ARGUMENTS}(ブレース付き)
  • $ARGS(省略形)

これらはすべて動作しません。必ず$ARGUMENTSと記述してください。

ファイルの権限問題

ファイルの読み取り権限が必要です。コンテナなどの別権限で実行する時に頭の片隅にあると良いかもですがこれすらもClaude Codeが解決してくれそうな気もしますので忘れてもよいです。

chmod 644 .claude/commands/*.md

まとめ

Claude Codeのカスタムコマンドは、設定が簡単なのに効果は絶大です。そしてv1.0.25のアップデートでさらに使いやすくなりました

特に重要なポイントとして、Markdownファイルを置くだけで使えるという手軽さがあります。v1.0.25からプレフィックス不要で呼び出せるようになり、プロジェクト固有の作業を標準化できるため、チーム開発での一貫性を保てます。さらに、複雑な作業も1コマンドで実行可能になり、コマンド検出の安定性が向上しました。

まだ設定してない人は、今すぐ.claude/commands/ディレクトリを作って、よく使うプロンプトをコマンド化してみてください。きっと「なんで今まで使ってなかったんだろう」って思うはずです。

私も最初は「まあ、そのうち設定すればいいか」と思ってました。でも一度使い始めたら、もう元には戻れません。開発効率が文字通り爆上がりします。

そして、良いコマンドができたらぜひ共有してください。Claude-Command-Suiteのようなリポジトリが増えれば、みんなの開発がもっと楽になるはずです。

最新のClaude Codeを使って、より快適な開発体験を手に入れましょう!

参考リンク