Open6

Claude Codeメモ

Fujiya228Fujiya228

Claude Codeの権限管理

claudeのsettingsで管理

~/.claude/settings.json

{
  "permissions": {
    "deny": [
      // Secrets: 物理的に隔離するのが第一。念のため全面拒否
      "Read(.env*)", "Edit(.env*)", "Write(.env*)",
      "Read(**/.env*)", "Edit(**/.env*)", "Write(**/.env*)",

      "Read(secrets/**)", "Edit(secrets/**)", "Write(secrets/**)",
      "Read(**/secrets/**)", "Edit(**/secrets/**)", "Write(**/secrets/**)",

      // よくある資格情報の場所と拡張子
      "Read(**/.ssh/**)", "Edit(**/.ssh/**)", "Write(**/.ssh/**)",
      "Read(**/*id_rsa*)", "Read(**/*.pem)", "Read(**/*.key)", "Read(**/*.p12)",
      "Read(**/*service-account*.json)", "Read(**/credentials/*.json)",

      // 外部送信経路を縮める(必要に応じて調整)
      "WebFetch",
      "Bash(curl:*)", "Bash(wget:*)", "Bash(scp:*)", "Bash(ssh:*)",
      "Bash(git push:*)"

       // その他危険なコマンド
      "Bash(git config *)",
      "Bash(brew install *)",
      "Bash(chmod 777 *)",
      "Bash(rm -rf /*)",
      "Bash(gh repo delete:*)"
    ],
    "allow": []
  }
hooksのPreToolUseでダブルチェック
{
  "permissions": {
    ・
    ・
    ・
  },
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash|Read|Write|Edit|WebFetch",
        "hooks": [
          {
            "type": "command",
            "command": "python ~/.claude/scripts/deny-check.py"
          }
        ]
      }
    ]
  }
}
#!/usr/bin/env python3

import json
import sys
import fnmatch
from pathlib import Path

def read_json_input():
    """標準入力からJSONを読み取り、コマンドとツール名を抽出"""
    try:
        input_data = sys.stdin.read()
        data = json.loads(input_data)
        command = data.get('tool_input', {}).get('command', '')
        tool_name = data.get('tool_name', '')
        print(f"command: {command}, tool_name: {tool_name}") # claude --debugで確認用
        return command, tool_name
    except (json.JSONDecodeError, KeyError):
        return '', ''

def get_deny_patterns():
    """settings.jsonから拒否パターンを読み取り"""
    settings_file = Path.home() / '.claude' / 'settings.json'
    
    if not settings_file.exists():
        return []
    
    try:
        with open(settings_file, 'r', encoding='utf-8') as f:
            settings = json.load(f)
        
        deny_patterns = []
        for pattern in settings.get('permissions', {}).get('deny', []):
            deny_patterns.append(pattern)
        
        return deny_patterns
    except (json.JSONDecodeError, KeyError):
        return []

def extract_pattern_info(pattern):
    """パターンからツールタイプとパターンを抽出"""
    # 例: "Bash(rm -rf *)" -> ("Bash", "rm -rf *")
    # 例: "Read(.env*)" -> ("Read", ".env*")
    # 例: "WebFetch" -> ("WebFetch", "")
    
    if '(' in pattern and pattern.endswith(')'):
        # 括弧がある場合
        tool_type = pattern[:pattern.find('(')]
        inner_pattern = pattern[pattern.find('(')+1:-1]
        return tool_type, inner_pattern
    else:
        # 括弧がない場合(例: WebFetch)
        return pattern, ""

def matches_deny_pattern(cmd, pattern):
    """コマンドが拒否パターンにマッチするかチェック"""
    # 先頭・末尾の空白を削除
    cmd = cmd.strip()
    
    # glob パターンマッチング(ワイルドカード対応)
    return fnmatch.fnmatch(cmd, pattern)

def check_command(command, tool_name, deny_patterns):
    """コマンド全体と各部分をチェック"""
    # 各拒否パターンをチェック
    for pattern in deny_patterns:
        if not pattern:
            continue
            
        tool_type, inner_pattern = extract_pattern_info(pattern)
        
        # ツールタイプが一致するかチェック
        if tool_type != tool_name:
            continue
            
        # パターンが空の場合は完全一致(例: WebFetch, WebSearch)
        if not inner_pattern:
            if tool_name == tool_type:
                print(f"Error: ツールが拒否されました: '{tool_name}' (パターン: '{pattern}')", file=sys.stderr) # claude --debugで確認用
                return False
            continue
        
        # Bashコマンドの場合は特別な処理
        if tool_type == "Bash":
            # まずコマンド全体をチェック
            if matches_deny_pattern(command, inner_pattern):
                print(f"Error: コマンドが拒否されました: '{command}' (パターン: '{pattern}')", file=sys.stderr) # claude --debugで確認用
                return False
            
            # コマンドを論理演算子で分割し、各部分もチェック
            # セミコロン、&& と || で分割(パイプ | と単一 & は分割しない)
            temp_command = command.replace(';', '\n').replace('&&', '\n').replace('||', '\n')
            
            for cmd_part in temp_command.split('\n'):
                # 空の部分をスキップ
                if not cmd_part.strip():
                    continue
                
                # このコマンド部分がパターンにマッチするかチェック
                if matches_deny_pattern(cmd_part.strip(), inner_pattern):
                    print(f"Error: コマンドが拒否されました: '{cmd_part.strip()}' (パターン: '{pattern}')", file=sys.stderr) # claude --debugで確認用
                    return False
        
        # Read, Write, Edit, MultiEditの場合はファイルパスをチェック
        elif tool_type in ["Read", "Write", "Edit", "MultiEdit"]:
            # commandはファイルパスとして扱う
            if matches_deny_pattern(command, inner_pattern):
                print(f"Error: ファイルアクセスが拒否されました: '{command}' (パターン: '{pattern}')", file=sys.stderr)
                return False
        
        # Globの場合はファイルパターンマッチング
        elif tool_type == "Glob":
            # commandはファイルパターンとして扱う
            if matches_deny_pattern(command, inner_pattern):
                print(f"Error: ファイルパターンが拒否されました: '{command}' (パターン: '{pattern}')", file=sys.stderr)
                return False
        
        # Grepの場合は検索パターン
        elif tool_type == "Grep":
            # commandは検索パターンとして扱う
            if matches_deny_pattern(command, inner_pattern):
                print(f"Error: 検索パターンが拒否されました: '{command}' (パターン: '{pattern}')", file=sys.stderr)
                return False
        
        # Taskの場合はタスク内容
        elif tool_type == "Task":
            # commandはタスク内容として扱う
            if matches_deny_pattern(command, inner_pattern):
                print(f"Error: タスクが拒否されました: '{command}' (パターン: '{pattern}')", file=sys.stderr)
                return False
    
    return True

def main():
    # JSON 入力を読み取り、コマンドとツール名を抽出
    command, tool_name = read_json_input()
    
    # 拒否パターンをチェックするツールタイプのみをチェック
    supported_tools = ["Task", "Bash", "Glob", "Grep", "Read", "Edit", "MultiEdit", "Write", "WebFetch", "WebSearch"]
    if tool_name not in supported_tools:
        sys.exit(0)
    
    # settings.json から拒否パターンを読み取り
    deny_patterns = get_deny_patterns()
    
    # コマンドをチェック
    if check_command(command, tool_name, deny_patterns):
        # コマンドを許可
        sys.exit(0)
    else:
        # コマンドを拒否
        sys.exit(2)

if __name__ == "__main__":
    main()

hooksでのチェックはこちらを参考にしました
https://wasabeef.jp/blog/claude-code-secure-bash

確認

スラッシュコマンドで設定自体があるかを確認

/permissions

検証用のファイルを作って確認

> .env.testというファイルを読み込んでください

⏺ Read(.env.test)
  ⎿  Error: Permission to read /Users/hoge/dev/.env.test has been denied.

⏺ .env.testファイルの読み込み権限がありません。

hooksを使った場合

⏺ Bash(git config --list | grep user)
  ⎿  Error: Bash operation blocked by hook:
     - [python ~/.claude/scripts/deny-check.py]: Error: コマンドが拒否されました: 'git
      config --list | grep user' (パターン: 'Bash(git config *)')

既知の注意点

  • deny が Read/Write に効かない、あるいは回避されるとの報告(2025年5–7月)。.env を deny しても可視・露出、system reminder 経由で内容が現れる等。必ず 機密はワーキングディレクトリに置かない/追加ディレクトリに含めない運用を。GitHubGitHubGitHubAnthropic
  • ネットワーク系は既定で curl / wget をブロックする設計だが、他経路(許可済み MCP / Git / API ライブラリ 等)で外部送信は理論上可能。devcontainer の ホワイトリスト型ファイアウォールで実線防御を。AnthropicAnthropiccodefactor.io
  • GitHub Actions 版は ネットワーク制限がデフォルトで無いため、プロキシや StepSecurity Harden-Runner 等で明示的に締めることが推奨。stepsecurity.io

「デフォルト無効化テンプレ」の公開状況

  • 公式: 明確な「デフォルト deny テンプレ」は未提供。代わりに、
    • 権限システム(allow/deny、gitignore準拠パターン、優先順位)と、Anthropic
    • devcontainer 参照実装(アウトバウンドを npm / GitHub / Anthropic 等に限定する iptables + ipset + init-firewall.sh)が公開。Anthropiccodefactor.io
  • コミュニティ:
    • centminmod の スターター設定リポジトリ(設定方針をまとめた README。個別 deny の網羅テンプレは限定的)。GitHub
    • まとめ系ブログ/チートシートや Reddit スレで allow/deny 例は多いが、機密全面ブロックの標準テンプレはまだ確立していません。ainativedev.iodevoriales.comReddit
    • 逆に「.env/secrets を保護したい」という Issue 例と推奨パターンは複数共有あり(Read(.env*)Read(**/secrets/**) を両方書く等)。GitHub

追加の実務ガード(強く推奨)

  1. 物理分離:機密はプロジェクト外 or 別ボリュームに置き、Claude からは additionalDirectories に含めないAnthropic
  2. devcontainer 実行 + 送信先ホワイトリストinit-firewall.sh 相当で GitHub メタレンジ + npm + Anthropic API + 必要最小限のみ許可Anthropiccodefactor.io
  3. disableBypassPermissionsMode: "disable" を常時設定(組織は managed settings で強制)。AnthropicAnthropic
  4. Git セーフティネット:専用ブランチ + 小刻みコミット。git push は原則 deny、必要時のみ一時許可。Anthropic
  5. 監査/permissions を定期点検、OpenTelemetry 監視を有効化。AnthropicAnthropic

参考

https://wasabeef.jp/blog/claude-code-secure-bash

Fujiya228Fujiya228

通知

公式のが動かなかったので、こちらで対応

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "afplay -v 1 /System/Library/Sounds/Submarine.aiff" }
        ]
      }
    ]
  }
}
Fujiya228Fujiya228

Claude Codeが利用できるコマンド?

  • Read / Write / Edit / MultiEdit: ファイルの読み込み・書き込み・編集操作を実行。
    • Updateも?
  • LS / Glob / Grep: ファイル検索・探索
  • WebSearch: インターネット検索による情報取得
  • Bash: シェルコマンドの実行(セキュリティと許可制御あり)
  • TodoWrite / TodoRead, Task: タスク管理系
  • MCP系
Fujiya228Fujiya228

スラッシュコマンド概要

  • 対話中に**/コマンド**でClaudeのふるまいを即変更・実行する仕組み。
  • 種別はBuilt-in(標準搭載)、Custom(自作コマンド)、MCP(接続サーバ由来)。

Built-in(主なもの)

  • セッション/履歴/clear(履歴クリア)、/compact(会話圧縮)、/status
  • 設定/権限/config/permissions
  • アカウント/login/logout
  • モデル/コスト/model/cost
  • ヘルスチェック/支援/doctor/help/bug
  • コード支援/init(CLAUDE.md作成)、/review(コードレビュー)、/pr_comments
  • 環境/モード/terminal-setup/vim
  • 拡張/agents(サブエージェント管理)、/memory(Claudeのメモ編集)、/mcp(MCP接続管理)

Custom slash commands(自作コマンド)

  • 呼び方/command-name [arguments]

  • 配置場所

    • プロジェクト共通:.claude/commands/(/helpに“(project)”表示)
    • 個人共通:~/.claude/commands/(/helpに“(user)”表示)
  • 名前空間:サブディレクトリ→/frontend:componentのように階層名がコマンド名に反映
    ※ユーザ/プロジェクト間の同名衝突は非対応

  • 引数:Markdownファイル内で$ARGUMENTSプレースホルダを使用

  • Bash事前実行:Markdownに ! 付きコマンドを埋め込むと実行結果を文脈へ取り込み可能
    → その際 frontmatterの allowed-tools に Bash(実行許可コマンド) を明記する必要あり

  • ファイル参照@path/to/file で対象ファイルの内容をコマンド文脈へ取り込み

  • 思考モード:拡張思考キーワードを含めて“深く考える”モードを起動可能

  • Frontmatter(メタ情報)

    • allowed-tools:使用許可ツール(例:Bash(git status:*), Bash(git commit:*)
    • argument-hint:補完時に出す引数ヒント
    • description:/helpに出る説明文
    • modelopus/sonnet/haiku等、使用モデル指定
  • 簡単な例

    • プロジェクトコマンド作成:
      .claude/commands/optimize.md に「パフォーマンス改善提案して」等を書く → /optimize
    • 引数付き:本文に Fix issue #$ARGUMENTS と書けば /fix-issue 123 で「#123を修正」指示に

MCP slash commands

  • 形式/mcp__<server-name>__<prompt-name> [arguments]

  • 特徴

    • 接続中のMCPサーバが公開するプロンプトが自動でコマンド化(動的発見)
    • サーバ/プロンプト名は小文字・アンダースコアで正規化
    • 引数はサーバ側定義に従う(例:/mcp__github__pr_review 456
  • 管理/mcpで接続状況、OAuth認証、ツール/プロンプト一覧、トークンのクリアなどを操作

使いどころの勘所

  • よく使うレビュー/修正指示をCustomコマンド化して省力化(例:/security-review
  • 実行前にgit statusdiffBash取り込み→コンテキスト付きの自動化を実現
  • プロジェクト標準の共通プロンプト.claude/commandsで共有、個人用は~/.claude/commands
  • 外部システム連携や社内ツールはMCP経由のスラコマで一元操作

最重要ポイント(3行)

  1. /コマンドで即操作、Custom/MCPで拡張。
  2. .claude/commands と ~/.claude/commandsで共有と個人を使い分け。
  3. Frontmatter(allowed-tools等)+ !/@ 構文でBash実行とファイル参照を安全・再現性高く組み込む。
Fujiya228Fujiya228

カスタムスラッシュコマンド

0) 最速セットアップ

# プロジェクト配下に作る(チーム共有に向く)
mkdir -p .claude/commands

# 個人常用コマンドはホーム配下
mkdir -p ~/.claude/commands

1) 基本形(最小構成)

.claude/commands/optimize.md/optimize で呼び出し

---
description: Analyze this code for performance issues and suggest optimizations
---

Analyze this code for performance issues and suggest practical optimizations.

構造だけ。まずはこれでコマンドが生えます。


2) 引数を使う($ARGUMENTS)

使い方/fix-issue 123$ARGUMENTS123 に展開。

.claude/commands/fix-issue.md/fix-issue [issueNumber]

---
description: Fix an issue with the provided number following our coding standards
argument-hint: [issueNumber]
---

Fix issue #$ARGUMENTS following our coding standards.
- Write tests first (TDD).
- Keep changes minimal and focused.
- Produce a short commit message and a longer body with rationale.

ヒント:引数はそのまま1つの文字列として入ります。/cmd foo bar と投げると $ARGUMENTSfoo bar。複数引数っぽく使いたいときは「最初のトークン=ID、残り=メッセージ」のように本文側でパース指示を書きます。


3) 名前空間(サブディレクトリ)

ファイル位置がコマンド名に反映されます。

.claude/commands/frontend/component.md   # => /frontend:component (project)
~/.claude/commands/component.md          # => /component (user)

プロジェクト側の /frontend:component とユーザ側の /component別物として共存可。同名衝突(同じ階層・同じベース名)は非対応


4) Bash の事前実行(! 前置 + allowed-tools)

Bash の実行結果を文脈として取り込む。安全のため実行許可を限定します。

.claude/commands/commit/create.md/commit:create "feat: add filter"

---
allowed-tools: Bash(git status:*), Bash(git diff:*), Bash(git branch:*), Bash(git log:*)
description: Create a conventional commit from current changes
argument-hint: [commitTitle]
---

## Context (auto-collected)
- Current branch: !`git branch --show-current`
- Git status: !`git status --porcelain`
- Diff (staged & unstaged): !`git diff HEAD`
- Recent commits: !`git log --oneline -10`

## Task
Using the context, craft a Conventional Commit:
- Title: "$ARGUMENTS"
- Body: why, what changed, risk, rollback plan
- Include a bullet list of changed files with short rationale.

ポイント

  • allowed-tools は必須Bash(*) みたいな広すぎる指定は避ける。
  • ! の中は バッククォートでコマンド。出力がそのまま本文に埋まる。

5) ファイル参照(@ プレフィックス)

コードや設定ファイルの中身をプロンプトに取り込む。

.claude/commands/review/security.md/review:security

---
description: Security review for the provided files and configs
---

Review the implementation for security vulnerabilities.

Focus:
- Auth flow, secrets handling, SSRF, RCE, SQL/NoSQLi, XSS, CSRF, authZ.

Reference files:
- @src/server/auth.ts
- @src/pages/api/*
- @next.config.js
- @package.json

Produce:
- Findings (severity with rationale)
- Concrete fixes (code/block diffs)
- Quick checks that can be automated in CI

@ファイルもディレクトリもOK。ディレクトリを指すと中身が(実装側の仕様に従い)展開されます。巨大リポジトリでは的を絞るのがコツ。


6) 実務テンプレ(Next.js / TypeScript向け)

6.1 Lint & Fix

.claude/commands/frontend/lint-fix.md/frontend:lint-fix

---
allowed-tools: Bash(npm run:*), Bash(pnpm:*), Bash(yarn:*)
description: Run lint, summarize, and propose auto-fixes
---

## Context
- Package scripts: @package.json
- ESLint config: @.eslintrc.*, @eslint.config.js

## Run
!`npm run -s lint || true`

## Task
1) Summarize errors/warnings by rule and file (top offenders).
2) Suggest config-level fixes (but avoid masking real issues).
3) Offer safe code changes (diff blocks) for the top 5 issues.

6.2 Unit Test triage

.claude/commands/test/triage.md/test:triage

---
allowed-tools: Bash(npm run:*), Bash(pnpm:*), Bash(yarn:*), Bash(git diff:*), Bash(git log:*)
description: Run tests, summarize failures, and propose fixes
---

## Context
- Changed files: !`git diff --name-only HEAD~1`
- Recent commits: !`git log --oneline -5`
- Vitest config: @vitest.config.*

## Run
!`npm run -s test -- --reporter=verbose || true`

## Task
- Group failures by suite/test.
- Hypothesize root causes with code pointers.
- Provide minimal patch diffs to make tests pass.

6.3 PR 用テンプレ生成

.claude/commands/pr/create-template.md/pr:create-template [title]

---
allowed-tools: Bash(git branch:*), Bash(git diff:*), Bash(git rev-parse:*), Bash(git log:*)
description: Generate a PR description using conventional sections
argument-hint: [title]
---

## Context
- Branch: !`git branch --show-current`
- Range: !`git rev-parse --short HEAD~10` .. !`git rev-parse --short HEAD`
- Diff summary: !`git diff --stat HEAD~1`

## Task
Create a PR body:

### Title
$ARGUMENTS

### Summary
- what/why/background

### Changes
- bullet list with scope per file

### Risks & Rollback
- risk matrix + revert steps

### Tests
- coverage and key cases

7) 引数を“賢く”使う(軽量パース)

一つの引数に複合値を渡すパターン。例:/release:notes 2.1.0 | feature,performance | major refactor api routes

---
description: Generate release notes from tags and keywords
argument-hint: [version | tagsCSV | summary]
---

Parse $ARGUMENTS into:
- version (before first '|')
- tagsCSV (between first and second '|')
- summary (after second '|')

If a part is missing, infer from recent commits: !`git log --oneline -50`
Output a well-structured CHANGELOG section for version.

こうしておくと拡張に強く、コマンド側で「分割して使って」と明示できます。


8) モデル切替(重い/軽いを使い分け)

---
model: sonnet
description: Deep architectural review
---

重い推論が必要なレビューだけ sonnet(例)に。ライトな整形系は既定モデルのまま。


9) 安全運用のコツ(重要)

  • allowed-tools を絞るBash(git status:*) のようにコマンド単位で許可。野良コマンドは入れない。
  • 破壊的操作に注意git add/commit/push を許可する場合、専用コマンドに分離し、実行前に「確認プロンプト」を入れる。
  • 巨大参照の制御@ でディレクトリを参照しすぎるとトークン肥大化@src/**/service/*.ts のように絞る。
  • ユーザとプロジェクトの役割分担:個人はユーティリティ系、プロジェクトは規約・標準手順系に置くと衝突しない。
  • 説明(description/argument-hint)を丁寧に/help リストが自分用UIになります。

10) あなた向けスターター(そのまま使える例)

10.1 Clean Architecture チェック

.claude/commands/arch/check.md/arch:check

---
description: Check code against our Clean Architecture/DDD rules
---

Review the repository for rule violations.

Rules:
- Domain entities must not import from application or infrastructure.
- Adapters may depend inward, never outward.
- UI components must not access repositories directly.
- Value Objects are immutable; no public setters.

Reference:
- @src/domains/**
- @src/app/**
- @src/infrastructure/**
- @src/components/**

Output:
- Violations list (file,line,rule)
- Suggested refactors and file moves

10.2 GA4 設計レビュー

.claude/commands/analytics/ga4-event-plan.md/analytics:ga4-event-plan [featureName]

---
description: Draft GA4 event plan with parameters, GTM mapping, and validation steps
argument-hint: [featureName]
---

Create a GA4 event plan for "$ARGUMENTS".

Deliver:
- Event names, parameters, and types
- GTM dataLayer schema and triggers
- DebugView / Tag Assistant validation checklist
- BigQuery export table expectations

10.3 dbt Runbook

.claude/commands/dbt/runbook.md/dbt:runbook [modelOrTag]

---
allowed-tools: Bash(dbt:*), Bash(gcloud:*), Bash(bq:*), Bash(gsutil:*)
description: Prepare a safe run plan for dbt models
argument-hint: [modelOrTag]
---

## Context
- dbt project: @dbt_project.yml
- Target profiles: @profiles.yml
- Recent runs (if available): !`dbt ls --resource-type model --select $ARGUMENTS || true`

## Task
Propose a safe run plan:
- Impacted models (graph)
- Test strategy (generic + singular)
- Backfill range (if incremental)
- Rollback plan

11) トラブルシューティング

  • /help に出ない → パス/拡張子/権限再確認(.md必須、階層名に注意)。
  • Bash が動かない → allowed-tools対象コマンドが許可されているか引数パターンにマッチしているか。
  • 引数が想定通り入らない → $ARGUMENTSまるごと一つの文字列。パース手順を本文に明記
  • 衝突する → 同名ファイル(同階層)は非サポート名前空間(サブディレクトリ)で回避。
Fujiya228Fujiya228

commandsでよく使う“本文セクション”一覧

セクション名 目的/役割 典型フレーズ・例 使う場面の目安
Context 現状や前提を共有 “Current branch: !`git branch --show-current`” / “問題の背景は…” レビュー/要約/意思決定の前に前提を揃えたい
Problem / Background 解くべき課題の定義 “We need to reduce INP under 200ms.” 課題の輪郭が曖昧なとき
Inputs / Arguments 受け取る引数の確認 “$ARGUMENTS = ‘123 fix copy’” 引数を使い分けるコマンド
Parse / Argument Rules 引数の分解規則を明示 “version tagsCSV summary の順で” 1引数に複数値を詰めるとき
References / Files 参照ファイルを取り込む “@src/server/auth.ts, @package.json” コード/設定を文脈に含めたい
Run / Collected Context 事前Bashで情報収集 “!`git status --porcelain`” Git差分やテスト結果を自動添付
Environment 実行環境の明示 “Node 20 / pnpm / OS …” 再現性や相違点の切り分け用
Assumptions 仮定を固定 “SSRは不要と仮定” 迷いを減らして出力を安定化
Constraints / Rules ガードレール “Entity→Infraの依存は禁止” 設計規約や禁止事項がある
Scope 対象範囲 “UI層のみ、DB変更なし” 作業の広がり防止
Out of Scope 非対象範囲 “API仕様変更は含まない” 期待値コントロール
Goal / Objective 成果目標 “INP改善の方針を3案” 出力の方向性を一本化
Task やることの一文定義 “上記を踏まえPR本文を生成” 仕上げるアウトプットを明確化
Steps / Plan 手順・進め方 “1) 計測 2) 特定 3) 修正案” 手続き的な作業に強い
Guidelines / Style スタイル・規約 “Conventional Commitsで” 文章/コードの体裁統一
Acceptance Criteria / DoD 完了条件 “警告ゼロ・差分5行以内” 出力の品質ゲート
Deliverables / Output Format 納品物と形式 “Markdownの見出し構成で” 結果の形式を固定
Patch / Diff 変更差分の提示 diff … コード修正や提案の即適用
Risk & Rollback リスクと戻し方 “リスク: CSS回り込み / ロールバック手順” 変更が大きい・本番影響時
Validation / Test Plan 検証方法 “Tag AssistantでXを確認” 手戻りを防ぎたい
Review Checklist レビュー観点 “a11y, i18n, perf, sec” PRレビュー効率化
Metrics / KPIs 成果指標 “TTI, INP, error率” 効果測定が必要
Notes / Caveats 補足・注意点 “Monorepoではコマンド変更” 例外や特殊条件の共有
Next Actions / Follow-ups 次アクション “CIにlint追加、期限8/15” 継続作業の引き継ぎ
Owners / Reviewers 担当・レビュア “Owner: FE@A / Reviewer: QA@B” 責任の所在を明確化
Timebox 時間上限 “30分で案3つまで” ラフ案やスプリント中の作業
Examples / Templates 例示 “良い/悪いPR本文サンプル” 期待値の具体化
Changelog / History 変更履歴 “v1→v2で方針更新” コマンドを運用改善する時

Frontmatter(メタ情報)でよく使う項目

フィールド 役割 注意点
description /helpに出る説明文 description: Create a git commit 1行で“何が起きるか”を端的に
argument-hint 引数の補完ヒント argument-hint: [message] 実際の引数パターンに合わせる
allowed-tools 事前Bashの実行許可 Bash(git status:*), Bash(npm run:*) 必須(!コマンド使う時)。最小権限で
model 利用モデル指定 model: sonnet 重たい思考が要る時だけ切替推奨

使い分けのコツ

  • Context/References/Runで“材料”を揃え、Task/Deliverablesで“出口”を固定。
  • 失敗を防ぐのはConstraints/Acceptance/Validation
  • 運用を回すのはReview Checklist/Next Actions/Risk & Rollback