comment-code
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesecomment-code
comment-code
コードにコメント・ドキュメンテーションコメントを追加・補強する。コードの実装は変更せず、役割の境界・呼び出し元の前提・返値の契約・他所との依存を「その場で読める」形で記述することが目的。
Adds and enhances comments and documentation comments in code. The goal is to document role boundaries, caller prerequisites, return value contracts, and dependencies with other components in a 'readable on the spot' format without modifying code implementation.
使い方
Usage
comment-code <対象ファイルまたはディレクトリ> [--lang <言語>]引数を省略した場合は の差分ファイルを対象とする。
を指定するとドキュメンテーションコメントの形式(JSDoc / docstring / rustdoc 等)を優先言語として扱う。指定がない場合は拡張子から自動判定する。
git diff HEAD--langcomment-code <target file or directory> [--lang <language>]If no arguments are provided, the diff files from will be targeted.
When is specified, the documentation comment format (JSDoc / docstring / rustdoc, etc.) will be treated as the priority language. If not specified, it will be automatically determined from the file extension.
git diff HEAD--lang前提条件
Prerequisites
- 対象ファイルが読み取り可能な状態であること
- Git リポジトリ内であること(引数省略時に を使用するため)
git diff HEAD
- The target files must be readable
- Must be within a Git repository (since is used when arguments are omitted)
git diff HEAD
フロー
Flow
Step 1: 対象ファイルを特定する
Step 1: Identify target files
引数が指定された場合はそのファイル・ディレクトリを対象にする。
bash
undefinedIf arguments are specified, those files/directories will be targeted.
bash
undefined引数なしの場合: 直近の差分ファイルを列挙(staged / unstaged 両方を HEAD と比較)
Without arguments: List recent diff files (compare both staged/unstaged with HEAD)
git diff HEAD --name-only
git diff HEAD --name-only
untracked(新規未追跡)ファイルも対象にしたい場合
To include untracked (new uncommitted) files
git ls-files --others --exclude-standard
対象が空(変更なし・引数なし)の場合はユーザーに対象を確認する。git ls-files --others --exclude-standard
If the target is empty (no changes / no arguments), confirm the target with the user.Step 2: 対象の役割をコードベースから調査する
Step 2: Investigate the role of the target in the codebase
このステップが最も重要。 ファイル単体だけを見るのではなく、システム全体の中での位置づけを把握する。
This step is the most important. Don't just look at individual files; understand their position in the overall system.
2-1: 呼び出し元を調査する
2-1: Investigate callers
対象ファイルが公開するシンボル(関数・クラス・型・定数)をコードベース全体で検索し、どのレイヤー・どのサービスから呼ばれているかを把握する。
bash
undefinedSearch the entire codebase for symbols (functions, classes, types, constants) exposed by the target file to understand which layers/services call them.
bash
undefinedシンボル名で呼び出し元を検索(例: exportされる関数名)
Search for callers by symbol name (e.g., exported function name)
grep -rn "対象シンボル名" --include=".ts" --include=".js" .
undefinedgrep -rn "target symbol name" --include=".ts" --include=".js" .
undefined2-2: import・依存関係を確認する
2-2: Check imports and dependencies
対象ファイルが依存している外部モジュール・サービス・設定を把握する。
bash
undefinedUnderstand external modules, services, and configurations that the target file depends on.
bash
undefinedimport 文の一覧
List import statements
grep -n "^import|^from|require(" 対象ファイル
undefinedgrep -n "^import|^from|require(" target-file
undefined2-3: パッケージ・サービス境界を確認する
2-3: Check package/service boundaries
- ・
package.json・go.mod等でパッケージ名・公開 API を確認するCargo.toml - サービス間通信(HTTP クライアント・イベント発行・メッセージキュー)が含まれる場合は接続先を特定する
- 認証・認可のミドルウェアやセッション管理と対象の関係を確認する
- Confirm package names and public APIs using ,
package.json,go.mod, etc.Cargo.toml - If inter-service communication (HTTP clients, event publishing, message queues) is involved, identify the connection destination.
- Check the relationship between the target and authentication/authorization middleware or session management.
2-4: 既存コメントスタイルを確認する
2-4: Check existing comment styles
同じファイル・同じパッケージ内の既存コメントを読み、スタイル(JSDoc / docstring / rustdoc 等)・言語(日本語/英語)を把握する。
Read existing comments in the same file/package to understand the style (JSDoc / docstring / rustdoc, etc.) and language (Japanese/English).
Step 3: コメントを追加・補強する
Step 3: Add and enhance comments
Step 2 で把握した「他ファイル・他サービスからの観点」をコメントとして書き込む。
Write comments incorporating the "perspective from other files/services" identified in Step 2.
コメントスタイルの規約(中心思想)
Comment Style Guidelines (Core Principles)
対象リポジトリに が存在する場合はそちらを優先して従う。存在しない場合は以下の要点に従う。
.claude/rules/code-comment-style.md書くべき内容:
| 観点 | 書く内容 |
|---|---|
| 役割・責務の境界 | 「このモジュールは〜サービスの〜境界を担う」「〜パッケージの公開インターフェースとして機能する」 |
| 呼び出し元の文脈 | どのレイヤー・どのサービスから呼ばれるか。呼び出し元が前提とする状態・権限 |
| 呼び出し先との契約 | 何を保証して返すか。エラー・例外の条件とその意味(null を返すのか例外を投げるのか等) |
| 他ファイル・他サービスとの依存 | 読み手がファイルを跨がないと見つけられない外部依存・設定・共有状態 |
| 非自明な制約・背景・why | なぜその実装になっているか。背景・経緯・仕様上の制限 |
書かないもの:
- シグネチャ・型から自明な逐語的説明(what の言い換え)
- 実装と乖離して陳腐化しやすい重複情報
- 解決済みの経緯だけを残したコメント
If exists in the target repository, follow it first. If not, follow the key points below.
.claude/rules/code-comment-style.mdContent to include:
| Aspect | Content to write |
|---|---|
| Role/responsibility boundaries | "This module handles the boundary of ~ service", "Functions as the public interface of ~ package" |
| Caller context | Which layers/services call it. The state/permissions assumed by the caller |
| Contract with callee | What is guaranteed to be returned. Conditions and meanings of errors/exceptions (whether to return null or throw an exception, etc.) |
| Dependencies with other files/services | External dependencies, configurations, shared states that cannot be found without cross-referencing files |
| Non-obvious constraints/background/why | Why the implementation is structured this way. Background, context, and specification limitations |
Content to avoid:
- Verbose explanations that are obvious from the signature/type (paraphrasing "what")
- Duplicate information that easily becomes outdated and diverges from the implementation
- Comments that only document resolved context
ドキュメンテーションコメント(言語別慣習)
Documentation Comments (Language-Specific Conventions)
言語の慣習に従った形式を使用する:
- TypeScript / JavaScript: JSDoc ()
/** ... */ - Python: docstring ()
"""...""" - Rust: (アイテム) /
///(モジュール)//! - Go: 形式
// FuncName ... - Java / Kotlin: Javadoc ()
/** ... */ - その他: 言語公式ドキュメントの慣習に従う
先頭の要約行に「役割・境界」を書き、本文に呼び出し元・呼び出し先の文脈・非自明な制約を追記する。
Use formats that follow language conventions:
- TypeScript / JavaScript: JSDoc ()
/** ... */ - Python: docstring ()
"""...""" - Rust: (items) /
///(modules)//! - Go: format
// FuncName ... - Java / Kotlin: Javadoc ()
/** ... */ - Others: Follow the conventions in the official language documentation
Write the "role/boundary" in the opening summary line, and add caller/callee context and non-obvious constraints in the body.
インラインコメント
Inline Comments
why(なぜその実装か)を書く。what はコードが示している。制約・背景・仕様上の都合は該当行またはブロックの直前に書く。参照すべき外部情報(Issue 番号・仕様書 URL)は積極的に記載する。
Write the "why" (why the implementation is this way). The "what" is indicated by the code. Constraints, background, and specification considerations should be written immediately before the relevant line or block. Actively include references to external information (Issue numbers, specification document URLs).
良い例・悪い例
Good/Bad Examples
悪い例(what の逐語的な言い換え):
typescript
/**
* ユーザーIDを受け取り、ユーザー情報を返す。
* @param userId ユーザーID
* @returns ユーザー情報
*/
function getUser(userId: string): User | null { ... }良い例(役割と他所からの観点を含む):
typescript
/**
* 認証レイヤーの公開インターフェース。API ハンドラーから呼ばれ、
* セッション検証済みの呼び出しのみを前提とする(未認証は上流ミドルウェアで遮断)。
*
* UserRepository に委譲し、DB から取得した値を返す。
* 存在しない場合は null を返す(例外は投げない)——
* 呼び出し元は null チェックを必ず行うこと。
*
* 注: soft delete されたユーザーも null として扱う(仕様: issue #142)。
*/
function getUser(userId: string): User | null { ... }Bad example (verbose paraphrasing of "what"):
typescript
/**
* Receives a user ID and returns user information.
* @param userId User ID
* @returns User information
*/
function getUser(userId: string): User | null { ... }Good example (includes role and perspective from other components):
typescript
/**
* Public interface of the authentication layer. Called from API handlers,
* assuming only calls with validated sessions (unauthenticated requests are blocked by upstream middleware).
*
* Delegates to UserRepository and returns values retrieved from the DB.
* Returns null if the user does not exist (does not throw exceptions)——
* Callers must perform null checks.
*
* Note: Soft-deleted users are also treated as null (specification: issue #142).
*/
function getUser(userId: string): User | null { ... }Step 4: 自己チェックを行う
Step 4: Perform self-check
追加・補強したコメントを以下の観点でレビューする。
Review the added/enhanced comments from the following perspectives.
内容の正確性
Content Accuracy
- 自明な逐語的説明・what の言い換えになっていないか
- 実装と乖離した内容を書いていないか(シグネチャと矛盾しないか)
- Step 2 の調査結果(呼び出し元・依存関係)が正しくコメントに反映されているか
- Is it not a verbose paraphrase of obvious content from the signature/type?
- Is there no content that diverges from the implementation (does it not contradict the signature)?
- Are the investigation results from Step 2 (callers, dependencies) correctly reflected in the comments?
セキュリティ(必須チェック)
Security (Mandatory Check)
- コメントにAPIキー・トークン・パスワード等の秘密情報を書いていないか
- コメントに個人情報(PII)を直接記載していないか(ユーザーIDの例示等)
- 認証・認可の前提条件を誤解を招く形で記述していないか(「認証不要」等の誤記)
- セキュリティ上の制約・権限の前提は明確かつ正確に記述されているか
上記チェックで問題が見つかった場合は、コメント内容を修正してから次に進む。
- Are secrets such as API keys, tokens, or passwords not written in comments?
- Is personal identifiable information (PII) not directly included in comments (e.g., user ID examples)?
- Are authentication/authorization prerequisites not described in a misleading way (e.g., incorrect "no authentication required" statements)?
- Are security constraints and permission prerequisites clearly and accurately described?
If issues are found in the above checks, modify the comment content before proceeding.
日本語スタイル
Japanese Style
- 常体(だ・である調)で記述されているか
- コマンド・識別子・ファイル名は英語のまま(翻訳しない)
- 絵文字の多用がないか
- Is it written in plain form (da/dearu style)?
- Are commands, identifiers, and filenames kept in English (not translated)?
- Is there no excessive use of emojis?
Step 5: 差分を提示して報告する
Step 5: Present diff and report
変更内容を差分形式で提示し、以下の形式でレポートする。
undefinedPresent changes in diff format and report in the following format.
undefinedcomment-code 完了報告
comment-code Completion Report
対象ファイル
Target Files
- (追加: N 件、補強: M 件)
path/to/file.ts
- (Added: N, Enhanced: M)
path/to/file.ts
追加したコメントの観点
Perspectives of Added Comments
- 呼び出し元: [どこから呼ばれるかを明記した箇所]
- 呼び出し先との契約: [返値・エラー条件を明記した箇所]
- 非自明な制約・背景: [why を記述した箇所]
- Caller: [Location where caller information is specified]
- Contract with callee: [Location where return value/error conditions are specified]
- Non-obvious constraints/background: [Location where "why" is described]
セキュリティチェック
Security Check
- 結果: ✅ 問題なし / ⚠️ 警告あり(詳細)
- Result: ✅ No issues / ⚠️ Warnings (details)
次のアクション
Next Actions
- コミットする場合: create-commit スキルを使用
- CLAUDE.md を更新する場合: update-docs スキルを使用
コミットは `create-commit` スキルへ委譲する(このスキル自身はコミットを行わない)。- To commit: Use the create-commit skill
- To update CLAUDE.md: Use the update-docs skill
Commit is delegated to the `create-commit` skill (this skill itself does not perform commits).検証
Verification
コメント追加後、以下で確認する。
bash
git diff HEAD- コードのロジック(関数本体・制御フロー)が変更されていないこと
- 追加したコメントが実装と矛盾していないこと
- Step 4 の自己チェックリストがすべて通過していること
After adding comments, verify with the following.
bash
git diff HEAD- Ensure code logic (function bodies, control flow) has not been modified
- Ensure added comments do not contradict the implementation
- Ensure all items in the Step 4 self-check list have been passed
よくある失敗
Common Failures
| 問題 | 回避策 |
|---|---|
| シグネチャ・型から自明な内容を逐語的に書く(what の言い換え) | 「なぜその実装か」「呼び出し元の前提」など自明でない情報のみ書く |
| 呼び出し元を調査せず推測でコメントを書く | Step 2 で必ず grep で呼び出し元を確認してから記述する |
| コメントにシークレット・個人情報を混入する | Step 4 のセキュリティチェックで秘密情報・PII がないことを確認する |
| コードのロジックを「整理しながら」変更してしまう | 実装変更が必要な箇所はコメントで TODO を残し、 |
| Issue | Mitigation |
|---|---|
| Writing verbose content that is obvious from the signature/type (paraphrasing "what") | Only write non-obvious information such as "why the implementation is this way" or "caller prerequisites" |
| Writing comments based on speculation without investigating callers | Always confirm callers using grep in Step 2 before writing |
| Including secrets/PII in comments | Confirm no secrets/PII exist during the Step 4 security check |
| Modifying code logic while "organizing" | Leave a TODO comment where implementation changes are needed and redirect to |
注意事項
Notes
- コードのロジックは変更しない — コメントの追加・補強のみ行う。実装に問題があると判断した場合は スキルへ誘導する
implement-issue - コメントは実装と同期させる — 既存コメントが実装と乖離している場合は修正する(乖離したコメントは正確なコメントより有害)
- 詳細規約は対象リポジトリに従う — が存在する場合はそちらを優先する。本スキルの Step 3 の要点はそのファイルが未配備の場合のフォールバックとして機能する
.claude/rules/code-comment-style.md - AI エージェントも読み手と想定する — 「他のファイルを参照すれば分かる」は通用しないと想定して書く。Claude 等のエージェントはコメントを主要な文脈源として使用する
- など pre-commit フック回避は禁止。コミット時にフックが失敗した場合は原因を調査・修正してから再実行する
--no-verify
- Do not modify code logic — Only add or enhance comments. If implementation issues are identified, redirect to the skill
implement-issue - Keep comments synchronized with implementation — If existing comments diverge from the implementation, correct them (outdated comments are more harmful than accurate ones)
- Follow detailed rules of the target repository — If exists, prioritize it. The key points in Step 3 of this skill serve as a fallback when that file is not available
.claude/rules/code-comment-style.md - Assume AI agents are also readers — Assume "you can find it by referencing other files" does not apply. Agents like Claude use comments as their primary context source
- Avoid bypassing pre-commit hooks with . If hooks fail during commit, investigate and fix the cause before re-running
--no-verify