エージェント定義

hachimoku のレビューエージェントは TOML ファイルで定義されます。 コード変更なしにエージェントの追加・カスタマイズが可能なデータ駆動型アーキテクチャを採用しています。 ビルトインエージェントを標準提供し、プロジェクト固有のカスタムエージェントも追加できます。

ビルトインエージェント

以下のエージェントがパッケージに同梱されています。

エージェント名

説明

出力スキーマ

フェーズ

適用条件

breaking-change-detector

公開 API・データモデル・CLI・設定ファイルの破壊的変更検出

severity_classified

main

content_patterns

code-reviewer

コード品質・バグ検出

scored_issues

main

常時適用

dependency-auditor

依存関係のセキュリティ・健全性監査

severity_classified

main

content_patterns

silent-failure-hunter

サイレント障害の検出

severity_classified

main

content_patterns

pr-test-analyzer

テストカバレッジの評価

test_gap_assessment

main

file_patterns

type-design-analyzer

型アノテーション・型安全性の実用分析

multi_dimensional_analysis

main

file_patterns + content_patterns

comment-analyzer

コメントの正確性分析

category_classification

final

content_patterns

code-simplifier

コード簡潔化の提案

improvement_suggestions

final

常時適用

出力スキーマの詳細は 出力スキーマ を参照してください。

セレクターエージェント

セレクターエージェントは、レビュー対象を分析して実行すべきレビューエージェントを選択する専用エージェントです。 レビューエージェントと同様に TOML 定義ファイルで構成情報を管理します。

SelectorDefinition

フィールド

必須

説明

name

str

Yes

セレクター名("selector" 固定)

description

str

Yes

セレクターの説明

model

str | None

No

使用する LLM モデル名。デフォルト: Noneモデル解決の優先順位 で解決)

system_prompt

str

Yes

セレクターのシステムプロンプト

allowed_tools

list[str]

No

許可するツールカテゴリ。デフォルト: 空。ビルトイン selector.toml では git_read, gh_read, file_read の3カテゴリを設定(web_fetch は含まない)

レビューエージェントの AgentDefinition とは異なり、output_schemaphaseapplicability フィールドはありません。 セレクターの出力は常に SelectorOutput(選択されたエージェント名リストと理由)に固定されます。

モデル解決の優先順位

セレクターエージェントのモデルは以下の優先順位で解決されます:

  1. [selector] 設定の model設定 参照)

  2. セレクター定義の model

  3. グローバル設定の model(デフォルト: "claudecode:claude-opus-4-6"

ビルトインセレクター定義

パッケージにはビルトインの selector.toml が同梱されています。 カスタムの selector.toml.hachimoku/agents/selector.toml に配置すると、ビルトインを上書きできます。

selector.toml(ビルトイン)
name = "selector"
description = "Analyzes review targets and selects optimal review agents"
model = "claudecode:claude-opus-4-6"
allowed_tools = ["git_read", "gh_read", "file_read"]
system_prompt = """
You are an agent selector for code review. Your role is twofold:
1. Select the most applicable review agents from the available list.
2. Provide analysis metadata that will be forwarded to the selected review agents.

## Input Format

For diff and PR modes, the user message contains a diff summary (not the full diff) with:
- A table of changed files with their status (modified/new/deleted/renamed/binary) and addition/deletion counts
- A brief preview of the first few changed lines per file

This summary provides enough context for agent selection decisions. If you need to examine specific changes in detail for your metadata analysis, use the run_git tool to access the full diff.

## File Navigation

The user message includes a "Directory Tree" section under "Pre-fetched Context" that lists all source files in the project. **Always refer to this directory tree before using the read_file tool** to verify that the file path exists. If you need to explore a directory not covered by the tree, use the list_directory tool first to discover available files before calling read_file. Never guess file paths.

## Agent Selection
Analyze the review target provided in the user message. Consider each agent's description, applicability rules (file_patterns, content_patterns), and phase when making your selection. Return the selected agent names and your reasoning.

## Metadata for Review Agents
Populate the following fields to provide context that review agents cannot easily derive on their own:

### change_intent
Summarize the purpose and intent of the changes. What problem is being solved? What design decisions were made? This helps review agents focus on whether the implementation achieves its stated goal.

### affected_files
List file paths OUTSIDE the diff that may be affected by these changes. Investigate with your tools:
- Trace imports and call sites of modified functions/classes
- Check configuration files that reference changed values
- Look for tests that reference changed APIs
Only include files you have verified exist and are actually affected. Do not speculate.

### relevant_conventions
List project conventions relevant to this review. Check CLAUDE.md, .hachimoku/config.toml, and project documentation for applicable rules. This helps agents avoid suggesting changes that contradict project policies.

### issue_context
If an issue number is provided and issue context is NOT already available in the pre-fetched data (check the user message for '## Pre-fetched Context > ### Issue Context'), use the run_gh tool to fetch the issue details. If issue context has been pre-fetched, summarize it directly from the provided data. Include relevant requirements, acceptance criteria, and discussion points that help review agents understand the broader context.

### referenced_content
When the diff or associated context mentions external references (Issue numbers like "#152", file paths like "src/foo.py", or quoted passages attributed to a source), fetch the referenced content and include it in this field. For each reference:
- Set reference_type to the kind of reference: "issue", "file", "spec", or "other".
- Set reference_id to the identifier (e.g., "#152", "src/hachimoku/models/_base.py").
- Set content to the relevant text from the referenced source.

Before fetching, check if the referenced content is already available in the pre-fetched data. Use the run_gh tool to fetch issue bodies, the read_file tool to read files. **When a reference mentions a path you are not certain exists, use the list_directory tool to verify the actual directory structure before calling read_file.** Only include references you successfully fetched. If a reference cannot be resolved, omit it.

This data enables review agents to verify consistency between the diff text and its referenced sources (e.g., correct quoting, accurate paraphrasing, matching terminology).
"""

load_selector()

セレクター定義を読み込みます。custom_dir を指定し、そのディレクトリに selector.toml が存在する場合はビルトインを上書きします。

from hachimoku.agents import load_selector

definition = load_selector()
print(definition.name)  # "selector"

TOML 定義ファイル形式

エージェント定義は以下の形式の TOML ファイルで記述します。

code-reviewer.toml(ビルトイン)
name = "code-reviewer"
description = "Comprehensive review of code quality, bugs, and best practices"
model = "claudecode:claude-opus-4-6"
output_schema = "scored_issues"
phase = "main"
allowed_tools = ["git_read", "gh_read", "file_read"]
system_prompt = """
You are code-reviewer, an expert code quality analyst. Analyze code changes for bugs, security issues, and best practice violations.

## Review Methodology
1. Use run_git(["diff", "--name-only"]) to list changed files.
2. Use run_git(["diff"]) to examine the full diff for each changed file.
3. Use read_file(path) to read surrounding context when the diff alone is insufficient.
4. Check for bugs, logical errors, race conditions, and off-by-one errors.
5. Identify security vulnerabilities: injection, authentication bypass, data exposure.
6. Evaluate error handling: missing exception handling, swallowed errors.
7. Assess performance: unnecessary allocations, N+1 queries, blocking I/O.
8. Review naming, structure, and adherence to coding standards.

## Investigation Protocol
When a diff changes a function signature, class interface, or public API, always trace callers outside the diff. Use run_git(["ls-files"]) to list project files, then read_file(path) to check call sites in files not included in the diff. Report broken callers as bugs.
When a diff modifies error handling or changes the exceptions a function can raise, focus on whether the change breaks callers. Use read_file(path) to read direct callers and verify they handle the new exception type. Leave error-silencing analysis to silent-failure-hunter.
When a diff adds or modifies a return type, use run_git(["log", "-p", "-S", "the_function_name", "--", "path/to/file"]) (substituting the actual function name and file path from the diff) to check if the function's contract changed. Verify callers handle the new return shape.
Do not report caller impact speculatively. Only flag issues where you have read the caller code and confirmed the incompatibility.
If you cannot complete the investigation due to tool call limits, list the files or callers you were unable to verify in your output.

## Turn Budget Strategy
You have a limited number of tool calls available. Exceeding this limit terminates your execution and discards all findings. Producing a complete result with partial investigation is always better than exhaustive investigation with no result.
Follow these rules to manage your budget:
1. Quick scan phase: Start with run_git(["diff", "--name-only"]) and run_git(["diff"]) for changed files only. Do not use run_git(["ls-files"]) or read unrelated files until you have assessed the diff.
2. Scope your investigation: Limit cross-file verification (caller tracing, exception handling checks) to at most 5 read_file calls beyond the changed files. If more files need checking, list the unverified files in your output instead of reading them.
3. Documentation-only changes: When the diff contains only documentation files (.md, .rst, .txt, .adoc), skip call-site verification entirely. Focus on content accuracy and structural issues.
4. Output priority: After your investigation, you must produce your structured output. Never spend your remaining budget on additional verification at the expense of producing a result.

## Severity Criteria
- Critical: Security vulnerabilities, data corruption, crashes in production paths.
- Important: Bugs causing incorrect behavior, missing error handling for likely failures.
- Suggestion: Readability improvements, minor optimizations, non-idiomatic patterns.
- Nitpick: Formatting, naming conventions, trivial style preferences.

## Scoring Guidelines
Set overall_score on a 0.0-10.0 scale:
- 9-10: No issues or only nitpicks. Production-ready.
- 7-8: Minor issues that do not block merge.
- 4-6: Significant issues requiring changes before merge.
- 0-3: Critical problems. Do not merge.

## Tool Usage
- run_git(args): Read git history and diffs. Allowed: diff, log, show, status, merge-base, rev-parse, branch, ls-files.
- run_gh(args): Read PR metadata. Allowed: pr view, pr diff, issue view, api (GET only).
- read_file(path): Read file contents for full context.
- list_directory(path, pattern=None): Discover project structure and related files.

## Output Format
- Set agent_name to "code-reviewer" in every ReviewIssue.
- Provide location (file_path + line_number) whenever possible.
- Write a concrete suggestion for each issue explaining how to fix it.
- Use category to classify: "bug", "security", "performance", "error-handling", "style".

## Confidence Filtering
Before reporting each finding, assign it an internal confidence score (0-100) representing how certain you are that it is a genuine, actionable issue.

### Confidence Scale
- 91-100: Confirmed bugs, verified security vulnerabilities, or clear rule violations found by reading the actual code.
- 76-90: Likely bugs or important best-practice violations supported by code evidence, but with some ambiguity in context.
- 51-75: Valid concerns that are context-dependent or low-impact; the code works but could be improved.
- 26-50: Stylistic preferences or patterns that are acceptable in context; likely not worth changing.
- 0-25: Speculative issues with no evidence from the code; probably false positives.

### Reporting Threshold
Only report findings with confidence >= 80. Silently discard anything below this threshold.
The confidence score is for your internal reasoning only — do not include it in the output.

## Self-Filtering Rules
- Do NOT report an issue if your own analysis concludes that no change is needed, the current code is acceptable as-is, or no action is required.
- Every reported issue must be actionable — it must clearly require a code change, documentation fix, or other concrete developer action.
- If you investigate a potential concern but determine it is acceptable in context, omit it entirely from your output.
- Before reporting any finding, confirm you have used read_file to read the relevant code and verified the issue exists. Do not report issues based on assumptions about code you have not read.
- Do not use uncertain language in suggestions: "should", "probably", "seems to", "might", "could potentially". State only confirmed facts. If you are not certain, do not report the finding.
- Do not report issues that only "might become a problem in the future" or "could cause issues at scale". Only report issues where the problem is present now and demonstrably affects the current code.

## Quality Principles
- Only report issues you are confident about. Omit uncertain findings.
- Be language-agnostic. Do not assume a specific programming language.
- Focus on substance over style. Prefer fewer high-quality findings over many trivial ones.
"""

[applicability]
always = true

フィールド一覧

フィールド

必須

説明

name

str

Yes

エージェント名。アルファベット小文字・数字・ハイフンのみ(^[a-z0-9-]+$

description

str

Yes

エージェントの説明

model

str

Yes

使用する LLM モデル名

output_schema

str

Yes

SCHEMA_REGISTRY に登録されたスキーマ名

system_prompt

str

Yes

エージェントのシステムプロンプト

allowed_tools

list[str]

No

許可するツールカテゴリのリスト。デフォルト: 空

phase

str

No

実行フェーズ。デフォルト: "main"

max_turns

int | None

No

エージェント固有の最大ターン数。デフォルト: None(グローバル設定を使用)。正の値

timeout

int | None

No

エージェント固有のタイムアウト秒数。デフォルト: None(グローバル設定を使用)。正の値

[applicability] テーブル:

フィールド

デフォルト

説明

always

bool

false

常時適用フラグ

file_patterns

list[str]

[]

fnmatch パターンのリスト

content_patterns

list[str]

[]

正規表現パターンのリスト

[applicability] テーブルを省略した場合、always = true がデフォルトとして適用されます。

Phase(実行フェーズ)

エージェントの実行順序を制御するフェーズです。 エージェントはフェーズ順に実行され、同フェーズ内では名前の辞書順で実行されます。

実行順序

説明

early

0

前処理フェーズ

main

1

メインレビューフェーズ

final

2

後処理フェーズ

from hachimoku.agents import Phase, PHASE_ORDER

assert PHASE_ORDER[Phase.EARLY] < PHASE_ORDER[Phase.MAIN] < PHASE_ORDER[Phase.FINAL]

ApplicabilityRule(適用条件)

エージェントがレビュー対象に適用されるかどうかを判定する条件です。

条件評価ロジック:

  1. always = true の場合、常に適用

  2. file_patterns のいずれかにファイル名(basename)がマッチすれば適用

  3. content_patterns のいずれかにコンテンツがマッチすれば適用

  4. 上記いずれも該当しなければ不適用

file_patternscontent_patterns は OR 関係です。

ビルトインエージェントの適用条件

エージェント

条件

パターン

breaking-change-detector

content_patterns

def\s+\w+\s*\(, class\s+\w+, async\s+def\s+\w+, __all__\s*=, app\.command, typer\.Option, typer\.Argument, BaseModel, \[tool\., \[project\]

code-reviewer

always = true

-

dependency-auditor

content_patterns

\[dependencies\], \[project\.dependencies\], \[project\.optional-dependencies\], \[tool\.uv, uv\.lock, requirements, \[build-system\], "dependencies"\s*:, "devDependencies"\s*:, \[dependencies\.\w+\], \[dev-dependencies\]

silent-failure-hunter

content_patterns

try\s*:, except\s, catch\s*\(, \.catch\s*\(

pr-test-analyzer

file_patterns

test_*.py, *_test.py, *.test.ts, *.test.js, *.spec.ts, *.spec.js

type-design-analyzer

file_patterns + content_patterns

ファイル: *.py, *.ts, *.tsx / コンテンツ: class\s+\w+, interface\s+\w+, type\s+\w+\s*=

comment-analyzer

content_patterns

""", ''', /\*\*, //\s*TODO, #\s*TODO

code-simplifier

always = true

-

LoadError(読み込みエラー)

エージェント定義ファイルの読み込み時に発生したエラー情報を保持します。 読み込みに失敗した個別のエージェント定義はスキップされ、他のエージェントの読み込みは継続します。

フィールド

制約

source

str

空文字列不可。エラー発生元(ファイルパス等)

message

str

空文字列不可。エラーメッセージ

LoadResult(読み込み結果)

エージェント定義の読み込み結果です。 正常に読み込まれた定義とスキップされたエラー情報を分離して保持します。

フィールド

制約

agents

tuple[AgentDefinition, ...]

読み込み成功したエージェント定義

errors

tuple[LoadError, ...]

デフォルト空タプル。読み込みエラー情報

エージェントの読み込み

load_builtin_agents()

パッケージに同梱されたビルトインエージェント定義を読み込みます。

from hachimoku.agents import load_builtin_agents

result = load_builtin_agents()

load_custom_agents(custom_dir)

指定ディレクトリ内の *.toml ファイルをカスタムエージェント定義として読み込みます。 ディレクトリが存在しない場合は空の LoadResult を返します。

from pathlib import Path
from hachimoku.agents import load_custom_agents

result = load_custom_agents(Path(".hachimoku/agents"))

load_agents(custom_dir=None)

ビルトインとカスタムのエージェント定義を統合して読み込みます。 カスタム定義がビルトインと同名の場合、カスタムがビルトインを上書きします。

from pathlib import Path
from hachimoku.agents import load_agents

# ビルトインのみ
result = load_agents()

# カスタムと統合
result = load_agents(custom_dir=Path(".hachimoku/agents"))

for agent in result.agents:
    print(f"{agent.name}: {agent.description}")

# 読み込みエラーの確認
for error in result.errors:
    print(f"Skipped {error.source}: {error.message}")

カスタムエージェントの作成

プロジェクト固有のカスタムエージェントを追加する手順:

  1. .hachimoku/agents/ ディレクトリを作成

  2. TOML 形式でエージェント定義ファイルを配置

.hachimoku/agents/security-checker.toml
name = "security-checker"
description = "Detect security vulnerabilities"
model = "anthropic:claude-opus-4-6"
output_schema = "scored_issues"
allowed_tools = ["git_read", "gh_read", "file_read"]
system_prompt = """
You are security-checker, a security vulnerability specialist.
Analyze the code for injection, authentication, and data exposure issues.
"""

[applicability]
always = true

output_schema には SCHEMA_REGISTRY に登録されたスキーマ名を指定します。 ビルトインと同名のファイルを配置すると、ビルトインの定義を上書きできます。