0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

AIエージェント向け AGENTS.md 設計パターン:Cline / .clinerules との比較・実践ガイド

0
Posted at

はじめに

AI コーディングエージェントを活用する開発者が増える中、「どうエージェントに一貫した指示を与えるか」という設計課題が注目されています。その解として普及しつつあるのが AGENTS.md というコンベンション(慣習ファイル)です。

ただし、AGENTS.md は特定のツールの公式機能ではなく、エージェント間で自然発生的に広まった慣習です。代表的な採用例は OpenAI Codex ですが、Cline(VS Code 拡張)では独自の .clinerules が主要な設定ファイルであり、両者の関係を正確に理解しておく必要があります。

本記事では、AGENTS.md の設計思想・実践パターンを解説しながら、Cline における .clinerules との違い・使い分けを上級者向けに整理します。

⚠️ 注意: 本記事のエージェントの挙動に関する記述は 2026 年 3 月時点の情報に基づきます。Cline・各エージェントの実装はバージョンによって異なるため、公式ドキュメントを必ずご確認ください。


目次

  1. AGENTS.md とは何か?その成り立ちと位置づけ
  2. Cline における設定ファイル:.clinerules vs AGENTS.md
  3. 設定ファイルの構造設計:上級者向けテンプレート
  4. セクション別詳解:何を書くべきか
  5. 高度なパターン:条件分岐・優先度・禁止事項
  6. 多段階エージェントワークフローでの設計
  7. コンテキスト効率の最適化(上級)
  8. よくある失敗パターンとアンチパターン
  9. 実践例:フルスタック Next.js プロジェクトの .clinerules + AGENTS.md
  10. まとめ

1. AGENTS.md とは何か?その成り立ちと位置づけ

AGENTS.md は、AI エージェントがリポジトリ内で自律的に作業する際に参照する慣習的な設定ファイルです。2025 年に OpenAI が Codex の仕様として公式採用したことで広く知られるようになりましたが、それ以前から複数のエージェント実装で使われてきたコンベンションでもあります。

AGENTS.md が解決する課題

毎回プロンプトで指示 → 一時的・再現性なし・コンテキスト肥大化リスク
AGENTS.md / .clinerules → 永続的・バージョン管理可能・チーム共有可能
観点 プロンプト指示のみ 設定ファイル活用
再現性 ❌ 毎回指示が必要 ✅ 自動読み込み
チーム共有 ❌ 属人化 ✅ Git 管理
バージョン管理 ❌ 履歴なし ✅ 変更履歴追跡可能
コンテキスト効率 ❌ 毎回トークン消費 ✅ 構造化・最適化可能
エージェント間ポータビリティ ❌ ツール固有 △ ツール依存(後述)

主要エージェントの設定ファイル対応状況

エージェント 専用設定ファイル AGENTS.md の扱い
OpenAI Codex AGENTS.md ✅ 公式仕様(メイン)
Cline (VS Code) .clinerules △ 非公式・バージョン依存
Claude Code CLAUDE.md △ 非公式・参考程度
GitHub Copilot .github/copilot-instructions.md △ 非公式
Cursor .cursor/rules/*.mdc(旧:.cursorrules △ 非公式

補足: Cursor は 0.40+ 以降、.cursorrules を非推奨とし .cursor/rules/ ディレクトリ配下の .mdc ファイルへ移行しています。古い記事の情報には注意してください。

重要: Cline で「AGENTS.md を使いこなす」という文脈では、実質的には .clinerules の設計の話になります。本記事では両者を明確に区別して解説します。


2. Cline における設定ファイル:.clinerules vs AGENTS.md

Cline の主要な設定ファイルは .clinerules です。AGENTS.md を読み込むかどうかはバージョンと設定に依存するため、Cline での開発では .clinerules を中心に設計するのが確実です。

機能比較

特性 .clinerules(Cline 主力) AGENTS.md(汎用慣習)
Cline での優先度 ✅ 高(公式サポート) △ バージョン依存
他エージェントでの利用 ❌ Cline 固有 ✅ Codex 等で有効
スコープ プロジェクトルート(最新版ではサブディレクトリにも対応) ツール実装依存
記述形式 Markdown(自由形式) Markdown(自由形式)
Git 管理 ✅ 推奨 ✅ 推奨

推奨使い分け戦略

.clinerules  → Cline での日常開発のメイン設定
AGENTS.md    → 複数エージェントを併用する場合の共通定義
              (両ファイルで共通化できる内容を AGENTS.md に切り出す)

マルチエージェント構成例:

project/
├── .clinerules        # Cline 専用の詳細設定
├── AGENTS.md          # 複数エージェント共通の最小ルール
├── CLAUDE.md          # Claude Code 用
└── .github/
    └── copilot-instructions.md  # Copilot 用

3. 設定ファイルの構造設計:上級者向けテンプレート

以下は、実務で使える .clinerules / AGENTS.md 共通のテンプレートです。

# .clinerules (or AGENTS.md) — [Project Name] v[version]
# Last Updated: YYYY-MM-DD
# Scope: [root / src / api / tests]
# Target agents: [Cline / Codex / Claude Code / etc.]

## 🎯 Mission Statement
[このプロジェクトが解決する問題と、エージェントに期待する役割の1〜2行要約]

## 🏗️ Architecture Overview
[アーキテクチャの簡潔な説明。テキストとディレクトリ構造で表現]

## 📋 Core Constraints
### MUST(必須)
- [絶対に守るべきルール]

### MUST NOT(禁止)
- [絶対にやってはいけないこと]

### SHOULD(推奨)
- [できる限り従うべきベストプラクティス]

## 🔧 Technical Specifications
### Language & Runtime
### Dependencies & Package Management
### Code Style & Formatting
### Testing Requirements

## 🔄 Workflow Instructions
### Before Modifying Code
### After Modifying Code
### PR/Commit Guidelines

## 📁 File Structure Reference
[重要なファイル・ディレクトリとその役割]

## 🚨 Critical Warnings
[特別な注意が必要な箇所・過去のバグ・地雷]

4. セクション別詳解:何を書くべきか

4.1 Architecture Overview

アーキテクチャはエージェントが理解できる形式で記述します。図(Mermaid 等)はエージェントによっては解釈されないため、テキストとディレクトリ構造が最も確実です。

## Architecture Overview

This is a hexagonal architecture (Ports & Adapters) application.

src/
├── domain/          # Pure business logic, NO external dependencies
│   ├── entities/    # Immutable value objects
│   └── usecases/    # Application use cases (interfaces only)
├── adapters/        # Implementation of domain interfaces
│   ├── repositories/
│   └── services/
└── infrastructure/  # Framework-specific code (Express, Prisma, etc.)

**Rule**: Domain layer MUST NOT import from adapters or infrastructure.
**Rule**: Dependencies flow inward (infrastructure → adapters → domain).

4.2 Critical Constraints の書き方

曖昧な指示はエージェントの判断を狂わせます。機械が解釈できる具体性が重要です。

## Critical Constraints

### MUST NOT
- NEVER use `any` type in TypeScript. Use `unknown` + type narrowing instead.
- NEVER commit secrets or API keys. Use environment variables via `process.env.XXX`.
- NEVER modify files under `src/generated/` — they are auto-generated by `npm run codegen`.
- NEVER use `console.log` in production code. Use the `logger` utility at `src/utils/logger.ts`.

### MUST
- ALL new functions must have JSDoc comments with `@param`, `@returns`, and `@throws`.
- ALL database operations must go through the repository pattern in `src/adapters/repositories/`.
- ALL errors must be instances of `AppError` class defined in `src/domain/errors/AppError.ts`.

4.3 Testing Requirements

## Testing Requirements

- Unit tests: Vitest, located in `__tests__/unit/` mirroring `src/` structure
- Integration tests: `__tests__/integration/`, requires running Docker services
- Coverage threshold: Statements ≥ 80%, Branches ≥ 75%
- Run before commit: `npm run test:unit`
- NEVER mock the domain layer in unit tests — it should be tested as pure functions
- Use `createMockRepository()` factory from `__tests__/helpers/` for repository mocks

5. 高度なパターン:条件分岐・優先度・禁止事項

5.1 タスクタイプ別の条件分岐

## Task-Specific Instructions

### When adding a new API endpoint:
1. Define the request/response types in `src/domain/types/api/`
2. Add OpenAPI annotation in `src/infrastructure/openapi/schema.yaml`
3. Implement handler in `src/adapters/controllers/`
4. Add integration test in `__tests__/integration/api/`
5. Update `docs/api-changelog.md`

### When fixing a bug:
1. Write a failing test FIRST that reproduces the bug
2. Fix the minimal amount of code to make the test pass
3. Add the bug to `docs/known-issues-resolved.md` with root cause analysis

### When refactoring:
1. Ensure existing tests pass BEFORE starting
2. Make changes incrementally — one abstraction at a time
3. Run `npm run type-check` after each change

5.2 コンテキスト認識型の指示

## Environment-Aware Behavior

- If `NODE_ENV=production`: NEVER add debug logging, NEVER expose stack traces in responses
- If working in `src/domain/`: enforce pure functions (no I/O, no side effects)
- If modifying `prisma/schema.prisma`: ALWAYS run `npx prisma generate` after changes
- If the task involves authentication: review `docs/security/auth-model.md` FIRST

5.3 優先度マトリクスの明示

## Decision Priority (highest to lowest)

1. Security (never compromise)
2. Data integrity (ACID guarantees)
3. Test coverage (don't reduce)
4. Performance (optimize if > 100ms p95)
5. Code elegance (nice to have)

When two concerns conflict, higher priority always wins.

6. 多段階エージェントワークフローでの設計

Cline を orchestrator として複数のサブタスクに委譲するようなワークフローでは、役割ごとに設定ファイルをスコープ分割することが効果的です。最新バージョンの Cline では .clinerules をサブディレクトリに配置することも可能ですが、読み込み優先度の挙動は実際の動作で検証することを推奨します。

/project/
├── .clinerules              # Cline グローバルルール
├── src/
│   ├── .clinerules          # src 配下の追加ルール
│   ├── api/
│   │   └── .clinerules      # API 層の詳細ルール
│   └── frontend/
│       └── .clinerules      # UI 層のルール
├── tests/
│   └── .clinerules          # テスト戦略・カバレッジ要件
└── docs/
    └── .clinerules          # ドキュメント生成ルール

グローバル設定の例(/.clinerules)

# Global Rules — Applied to ALL Cline tasks

## Project Identity
- Name: MyApp
- Stack: Next.js 15 (App Router) + Prisma + PostgreSQL
- Language: TypeScript (strict mode)

## Non-Negotiable Rules
- TypeScript strict mode: ALWAYS enabled
- No secrets in code: use `.env.local` (not committed)
- Conventional Commits: `feat:`, `fix:`, `refactor:`, `test:`, `docs:`

## Cross-Cutting Concerns
- Logging: use `src/lib/logger.ts` (structured JSON logs)
- Error handling: all errors → `AppError` hierarchy
- i18n: all user-facing strings via `next-intl`, no hardcoded strings

API 層の設定例(/src/api/.clinerules)

# API Layer Rules (extends root .clinerules)

## This directory scope
Handles: REST API routes under `app/api/`

## Additional constraints for this scope
- Rate limiting: ALL endpoints must use `withRateLimit()` HOF
- Auth: ALL non-public endpoints must use `withAuth()` middleware
- Validation: use `zod` schemas, defined in `src/lib/validators/`
- Response format: ALWAYS use `ApiResponse<T>` wrapper type

## Forbidden in this scope
- Direct Prisma calls — use repository classes only
- Returning raw error messages to client — sanitize with `toClientError()`

7. コンテキスト効率の最適化(上級)

設定ファイル自体が長大になるとエージェントのコンテキストウィンドウを圧迫し、本来のタスクに使えるトークンが減少します。設定ファイルは 200 行以内を目安に保つことを推奨します。

7.1 参照分離パターン

# BAD: 詳細をすべて .clinerules に書く(500行超)
## Database Schema
[Prismaスキーマの全フィールド定義がここに...]

# GOOD: 要点のみ書き、詳細は別ファイルへの参照にする
## Database Schema
See `prisma/schema.prisma`. Key rules:
- All models need `createdAt`, `updatedAt` (see `docs/db-conventions.md`)
- NEVER add raw SQL — use Prisma migrations only

7.2 「エージェントが迷う場面」に絞る

設定ファイルに書くべきは「エージェントが自分で判断できないこと」だけです。

# BAD: 明らかなことを書く(トークン無駄)
- Use meaningful variable names.
- Don't write duplicate code.

# GOOD: プロジェクト固有の判断が必要なことだけ書く
- `UserService``AuthService` の責務分離: 認証ロジックは AuthService のみ。
  UserService は認証済みユーザーデータの CRUD に集中する。
- `src/hooks/` の Custom Hooks は UI ロジックのみ。副作用(fetch)は禁止。

7.3 動的コンテキスト vs 静的定義

# 静的定義向き(設定ファイルに書く)
- アーキテクチャルール(変更頻度が低い)
- 禁止パターン / 命名規約

# 動的参照向き(タスク実行時にエージェントが直接ファイルを読む)
- 詳細な API 仕様 → OpenAPI スキーマを直接参照させる
- DB スキーマ → Prisma ファイルを直接参照させる
- テスト例 → 既存テストファイルを参照させる

8. よくある失敗パターンとアンチパターン

❌ アンチパターン 1:曖昧な指示

# BAD
- Write clean code.
- Follow best practices.
- Handle errors properly.

# GOOD
- Functions must be ≤ 30 lines. Extract helpers if needed.
- Use Result<T, E> pattern (see src/types/Result.ts) instead of throwing in domain layer.
- ALL caught errors must be logged with `logger.error({ err, context })` before re-throwing.

❌ アンチパターン 2:情報過多

設定ファイルは 200 行以内を目安に。重要情報が後半に埋もれると、エージェントが実質的に読み飛ばすリスクがあります。

# BAD: 500行超の詳細仕様。重要ルールが後半に埋もれている
# GOOD
- 重要ルールは上部に集約(MUST/MUST NOT)
- 詳細仕様は別ファイルに分離し、参照: `docs/architecture.md`

❌ アンチパターン 3:矛盾する指示

# BAD(ルートとサブディレクトリで矛盾)
# /.clinerules: Use 2-space indentation.
# /src/api/.clinerules: Use 4-space indentation.  ← 矛盾!

# GOOD(明示的な上書きを宣言する)
# /src/api/.clinerules:
- OVERRIDE root rule: Use 4-space indentation in this directory only (legacy codebase).

❌ アンチパターン 4:更新されない設定ファイル

設定ファイルはリビングドキュメントです。PR チェックリストに組み込みましょう。

## PR Checklist (.github/pull_request_template.md に追加)
- [ ] Does this change require updates to .clinerules / AGENTS.md?
- [ ] Are new architectural decisions documented?
- [ ] Are new forbidden patterns added to MUST NOT section?

❌ アンチパターン 5:プロンプトインジェクションへの無防備

外部データを扱うプロジェクトでは、設定ファイルでインジェクション対策を明示します。

## Security: Prompt Injection Defense

- NEVER pass raw user input directly to AI API calls — always sanitize/truncate first.
- When processing external data (webhooks, APIs), treat all string values as UNTRUSTED.
- Log all AI-processed inputs for audit: use `src/lib/audit-logger.ts`.

9. 実践例:フルスタック Next.js プロジェクトの .clinerules + AGENTS.md

⚠️ 注意: 以下は架空のサンプルプロジェクト「NextShop」を用いた説明用の例です。実際のプロジェクトに合わせてカスタマイズしてください。

/.clinerules(Cline 向けメイン設定)

# .clinerules — NextShop (Fictional Sample Project)
# Version: 1.0.0 | Updated: 2026-03-20

## 🎯 Mission
NextShop is a fictional B2C e-commerce platform: Next.js 15 + TypeScript + Prisma + Stripe.

## 🏗️ Architecture

src/
├── app/                    # Next.js 15 App Router
│   ├── api/                # API routes
│   └── (routes)/           # Page components
├── components/             # shadcn/ui based components
├── lib/
│   ├── db/                 # Prisma client singleton
│   ├── auth/               # Auth.js v5 (GA) config
│   ├── stripe/             # Stripe SDK wrappers
│   └── validators/         # Zod schemas
├── server/
│   ├── actions/            # Next.js Server Actions
│   └── repositories/       # Data access layer
└── types/                  # Shared TypeScript types

## 📋 MUST NOT

- NEVER call Prisma directly from components — use `server/repositories/`
- NEVER store payment card data — delegate entirely to Stripe
- NEVER use `dangerouslySetInnerHTML` without DOMPurify sanitization
- NEVER expose internal error messages to API responses

## 📋 MUST

- ALL Server Actions must use `withAuth()` wrapper if authentication is required
- ALL database writes wrapped in transactions when modifying >1 table
- Run `npm run type-check && npm run test:unit` before any task is complete

## 🔧 Tech Stack

| Layer | Technology | Version |
|-------|-----------|---------|
| Framework | Next.js (App Router) | 15.x |
| Language | TypeScript (strict) | 5.x |
| ORM | Prisma | 6.x |
| Database | PostgreSQL | 17.x |
| Auth | Auth.js (NextAuth GA) | 5.x |
| Payment | Stripe | Latest |
| UI | shadcn/ui + Tailwind | Latest |
| Testing | Vitest + Testing Library | Latest |

## 🚨 Critical Warnings

1. **Stripe Webhooks**: `app/api/webhooks/stripe/route.ts` uses raw body.
   NEVER add body-parser middleware to this route.
2. **Auth.js v5**: Breaking changes from v4. Check `types/next-auth.d.ts` before accessing `session.user`.
3. **Rate Limiting**: All `/api/` routes limited via Upstash Redis (`lib/rate-limit.ts`).

/AGENTS.md(他エージェント向け共通定義)

# AGENTS.md — NextShop Common Rules
# Minimal shared rules for non-Cline agents (Codex, etc.)
# For Cline: see .clinerules (more detailed)

## Language & Stack
- TypeScript strict mode. No `any`.
- Next.js 15 App Router. No Pages Router patterns.

## Non-Negotiable
- No direct DB access outside `server/repositories/`
- No secrets in code
- Conventional Commits only

10. まとめ

設定ファイルは「エージェントとの契約書」です。しかし、ツールごとの仕様差を理解した上で設計することが前提となります。

ツール 信頼すべき設定ファイル AGENTS.md の扱い
Cline .clinerules(公式) 補助的・バージョン確認必須
OpenAI Codex AGENTS.md(公式) メイン設定
Claude Code CLAUDE.md(公式) 補助的
Cursor .cursor/rules/*.mdc(公式) 補助的

設計の黄金律

原則 実践
ツール仕様を確認する 「AGENTS.md が読まれる」と断言せず、バージョン確認を習慣に
具体性 曖昧な指示より、機械的に判断できる指示を
優先度明示 MUST / MUST NOT / SHOULD を明確に区別
簡潔性 設定ファイルは 200 行以内を目安。詳細は別ファイルへ参照分離
Living Document PR ごとに更新する習慣を。陳腐化は有害
インジェクション対策 外部データを扱う場合は Security セクションを必ず設ける

AI エージェントとの協働が標準となる時代、「どのエージェントに・何を・どのファイルで伝えるか」の設計力はエンジニアの新たな必須スキルとなるでしょう。


参考リンク


この記事が役に立ったら LGTM をよろしくお願いします!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?