Faceted Prompting テンプレート整備: ペルソナからドメイン知識を分離、Policy配置を最適化

- ペルソナテンプレート (expert/character) から「ドメイン知識」セクションを削除
- templates/reports/ → templates/output-contracts/ にリネーム
- knowledge テンプレートを追加
- Policy を Instructions の後ろに移動(recency効果で制約遵守を強化)
- Policy Reminder(上下二重配置)を廃止し、末尾の1箇所に統一
- ドキュメント (prompt-composition.ja/en) にファセット典型例と合成プロンプト例を追加
This commit is contained in:
nrslib 2026-02-07 21:09:42 +09:00
parent 5f1d85277a
commit d92f5aa4fe
14 changed files with 583 additions and 71 deletions

View File

@ -0,0 +1,39 @@
# {ドメイン名}知識
## {トピック1}
{トピックの概要。1-2文}
| 基準 | 判定 |
|------|------|
| {基準1} | {判定} |
| {基準2} | {判定} |
| {基準3} | {判定} |
{補足説明や確認手法}
### {サブトピック}
{詳細な説明}
```typescript
// NG
{悪い例}
// OK
{良い例}
```
## {トピック2}
{テーブル、コード例、箇条書きを自由に組み合わせる}
| パターン | 例 | 問題 |
|---------|-----|------|
| {パターンA} | `{コード例}` | {なぜ問題か} |
| {パターンB} | `{コード例}` | {なぜ問題か} |
検証アプローチ:
1. {確認手順1}
2. {確認手順2}
3. {確認手順3}

View File

@ -26,8 +26,6 @@
- {キャラクターA}へ: {評価と批判}
- {キャラクターB}へ: {評価と批判}
## ドメイン知識
### 思考の特徴
**{特徴1のラベル}:** {特徴の説明。どう考え、どう判断するか}

View File

@ -19,50 +19,3 @@
- {このエージェント固有の行動指針1}
- {このエージェント固有の行動指針2}
- {このエージェント固有の行動指針3}
## ドメイン知識
### {観点1}
{概要説明。1-2文}
| 基準 | 判定 |
|------|------|
| {条件A} | REJECT |
| {条件B} | 警告 |
| {条件C} | OK |
### {観点2}
{概要説明。1-2文}
```typescript
// REJECT - {問題の説明}
{悪い例のコード}
// OK - {正しい理由}
{良い例のコード}
```
### {観点3: 検出手法}
{何をどうやって検出するかの説明}
| パターン | 問題 | 検出方法 |
|---------|------|---------|
| {パターンA} | {問題} | {grepで〜を確認} |
| {パターンB} | {問題} | {呼び出し元を追跡} |
検証アプローチ:
1. {検証ステップ1}
2. {検証ステップ2}
3. {検証ステップ3}
### アンチパターン検出
以下を見つけたら REJECT:
| アンチパターン | 問題 |
|---------------|------|
| {パターンA} | {なぜ問題か} |
| {パターンB} | {なぜ問題か} |

View File

@ -37,6 +37,271 @@ knowledge/ # CONTEXT — 前提知識・参照資料
output-contracts/ # OUTPUT — 出力契約テンプレート
```
### 配置と各ファセットの典型例
LLMに渡せるスロットは **system prompt****user message** の2つだけである。5つの関心はこの2つに配置される。
```
System Prompt:
┌─────────────────────────────────────────────┐
│ Persona — エージェントの役割・専門性・行動姿勢 │
└─────────────────────────────────────────────┘
User Message:
┌─────────────────────────────────────────────┐
│ Policy — 守るべきルール・禁止事項・品質基準 │
│ Knowledge — 判断の前提となる参照資料 │
│ Instruction — このステップでやるべき手順 │
│ Output Contract — 出力の構造定義 │
└─────────────────────────────────────────────┘
```
Personaはエージェントの**identity**であり、タスクによって変わらない。system promptに置くことでLLMの応答全体を方向付ける。残りの4つはステップごとに変わるため、user messageに合成する。
以下に各ファセットの典型的なファイル例を示す。
#### Persona — `personas/architecture-reviewer.md`
system promptに配置される。役割の定義、境界、行動姿勢のみを含む。
```markdown
# Architecture Reviewer
あなたはソフトウェアアーキテクチャの専門家です。
コードの構造・設計・保守性を評価します。
## 役割の境界
**やること:**
- 構造・設計の妥当性検証
- コード品質の評価
- 変更スコープの適切性確認
**やらないこと:**
- セキュリティ脆弱性のレビューSecurity Reviewerの仕事
- 自分でコードを書く
## 行動姿勢
- 完璧な設計を求めない。現状の制約下で最善かを判断する
- 既存コードベースの規約を尊重する
```
以下の4つはすべてuser messageに配置される。
#### Policy — `policies/coding.md`
タスクをまたがって適用される共有ルール。規範的(「こうすべき」)。
```markdown
# コーディングポリシー
## 原則
| 原則 | 基準 |
|------|------|
| DRY | 3回以上の重複はREJECT |
| Fail Fast | 不正状態は早期にエラー |
| 最小権限 | 必要最小限のスコープ |
## 禁止事項
- **未使用コード** - 「念のため」のメソッド、将来用フィールド
- **オブジェクトの直接変更** - スプレッド演算子で新規作成
- **フォールバックの濫用** - `?? 'default'` で不確実性を隠さない
```
#### Knowledge — `knowledge/architecture.md`
判断の前提となる参照情報。記述的(「こうなっている」)。
```markdown
# アーキテクチャ知識
## レイヤー構造
依存の方向: 上位層 → 下位層(逆方向禁止)
| レイヤー | 責務 | 依存先 |
|---------|------|--------|
| Controller | HTTPリクエスト処理 | Service |
| Service | ビジネスロジック | Repository |
| Repository | データアクセス | なし |
## ファイル構成
| 基準 | 判定 |
|------|------|
| 1ファイル300行超 | 分割を検討 |
| 1ファイルに複数の責務 | REJECT |
| 循環依存 | REJECT |
```
#### Instruction — `instructions/implement.md`
このステップ固有の手順。命令形で記述する。
```markdown
計画に基づいてタスクを実装してください。
**やること:**
1. 変更スコープを宣言する
2. コードを実装する
3. テストを書いて実行する
4. 判断ログを記録する
**注意:** Previous Response がある場合は差し戻しです。
指摘事項を踏まえて修正してください。
```
#### Output Contract — `output-contracts/review.md`
出力の構造を定義する。エージェントはこの形式に従って出力する。
````markdown
```markdown
# アーキテクチャレビュー
## 結果: APPROVE / REJECT
## サマリー
{1-2文で結果を要約}
## 確認した観点
| 観点 | 結果 | 備考 |
|------|------|------|
| 構造・設計 | ✅ | - |
| コード品質 | ✅ | - |
| テストカバレッジ | ✅ | - |
## 問題点REJECTの場合
| # | 場所 | 問題 | 修正案 |
|---|------|------|--------|
| 1 | `src/file.ts:42` | 問題の説明 | 修正方法 |
```
````
#### 合成後の完全なプロンプト
上記5つのファイルがエンジンによって合成され、最終的にLLMに渡される形を示す。
**System Prompt:**
```markdown
# Architecture Reviewer
あなたはソフトウェアアーキテクチャの専門家です。
コードの構造・設計・保守性を評価します。
## 役割の境界
**やること:**
- 構造・設計の妥当性検証
- コード品質の評価
- 変更スコープの適切性確認
**やらないこと:**
- セキュリティ脆弱性のレビューSecurity Reviewerの仕事
- 自分でコードを書く
## 行動姿勢
- 完璧な設計を求めない。現状の制約下で最善かを判断する
- 既存コードベースの規約を尊重する
```
**User Message:**
```markdown
## Policy
### 原則
| 原則 | 基準 |
|------|------|
| DRY | 3回以上の重複はREJECT |
| Fail Fast | 不正状態は早期にエラー |
| 最小権限 | 必要最小限のスコープ |
### 禁止事項
- **未使用コード** - 「念のため」のメソッド、将来用フィールド
- **オブジェクトの直接変更** - スプレッド演算子で新規作成
- **フォールバックの濫用** - `?? 'default'` で不確実性を隠さない
---
## Knowledge
### レイヤー構造
依存の方向: 上位層 → 下位層(逆方向禁止)
| レイヤー | 責務 | 依存先 |
|---------|------|--------|
| Controller | HTTPリクエスト処理 | Service |
| Service | ビジネスロジック | Repository |
| Repository | データアクセス | なし |
### ファイル構成
| 基準 | 判定 |
|------|------|
| 1ファイル300行超 | 分割を検討 |
| 1ファイルに複数の責務 | REJECT |
| 循環依存 | REJECT |
---
## User Request
ユーザー認証モジュールにJWTトークンの検証機能を追加してください。
---
## Instructions
計画に基づいてタスクを実装してください。
**やること:**
1. 変更スコープを宣言する
2. コードを実装する
3. テストを書いて実行する
4. 判断ログを記録する
**注意:** Previous Response がある場合は差し戻しです。
指摘事項を踏まえて修正してください。
---
## Output Contract
以下のフォーマットでレポートを出力してください。
\```markdown
# アーキテクチャレビュー
## 結果: APPROVE / REJECT
## サマリー
{1-2文で結果を要約}
## 確認した観点
| 観点 | 結果 | 備考 |
|------|------|------|
| 構造・設計 | ✅ | - |
| コード品質 | ✅ | - |
| テストカバレッジ | ✅ | - |
## 問題点REJECTの場合
| # | 場所 | 問題 | 修正案 |
|---|------|------|--------|
| 1 | `src/file.ts:42` | 問題の説明 | 修正方法 |
\```
```
このように、独立したファイルがランタイムで1つのプロンプトに組み立てられる。ファイルの内容を変えればプロンプトが変わり、別のファイルを指せば別の組み合わせになる。
### なぜこの5つか
**Persona** と **Instruction** は最低限必要なもの — エージェントが誰で、何をすべきかを定義する必要がある。しかし実際には、さらに3つの関心が独立した軸として現れる。

View File

@ -37,6 +37,275 @@ knowledge/ # CONTEXT — reference materials
output-contracts/ # OUTPUT — output contract templates
```
### Placement and Typical Examples
An LLM has only two slots: **system prompt** and **user message**. The five concerns map to these two slots.
```
System Prompt:
┌──────────────────────────────────────────────────┐
│ Persona — agent's role, expertise, principles │
└──────────────────────────────────────────────────┘
User Message:
┌──────────────────────────────────────────────────┐
│ Policy — rules, prohibitions, quality standards │
│ Knowledge — reference materials for judgment │
│ Instruction — step-specific procedures │
│ Output Contract — output structure definition │
└──────────────────────────────────────────────────┘
```
Persona is the agent's **identity** — it doesn't change across tasks. Placing it in the system prompt shapes all LLM responses. The remaining four change per step and are composed into the user message.
Below are typical file examples for each facet.
#### Persona — `personas/architecture-reviewer.md`
Placed in the system prompt. Contains only role definition, boundaries, and behavioral principles.
```markdown
# Architecture Reviewer
You are a software architecture specialist.
You evaluate code structure, design, and maintainability.
## Role Boundaries
**Do:**
- Validate structural and design soundness
- Evaluate code quality
- Verify change scope appropriateness
**Don't:**
- Review security vulnerabilities (Security Reviewer's job)
- Write code yourself
## Behavioral Principles
- Don't demand perfect design. Judge whether it's the best under current constraints
- Respect existing codebase conventions
```
The following four are all placed in the user message.
#### Policy — `policies/coding.md`
Shared rules that apply across tasks. Prescriptive ("you must").
```markdown
# Coding Policy
## Principles
| Principle | Standard |
|-----------|----------|
| DRY | 3+ duplications → REJECT |
| Fail Fast | Reject invalid state early |
| Least Privilege | Minimal scope necessary |
## Prohibitions
- **Unused code** — no "just in case" methods, no future-use fields
- **Direct object mutation** — create new objects with spread operators
- **Fallback abuse** — don't hide uncertainty with `?? 'default'`
```
#### Knowledge — `knowledge/architecture.md`
Reference information for judgment. Descriptive ("this is how it works").
```markdown
# Architecture Knowledge
## Layer Structure
Dependency direction: upper layers → lower layers (reverse prohibited)
| Layer | Responsibility | Depends On |
|-------|---------------|------------|
| Controller | HTTP request handling | Service |
| Service | Business logic | Repository |
| Repository | Data access | None |
## File Organization
| Criteria | Judgment |
|----------|----------|
| File exceeds 300 lines | Consider splitting |
| Multiple responsibilities in one file | REJECT |
| Circular dependencies | REJECT |
```
#### Instruction — `instructions/implement.md`
Step-specific procedures. Imperative voice.
```markdown
Implement the task based on the plan.
**Steps:**
1. Declare the change scope
2. Implement the code
3. Write and run tests
4. Record decision log
**Note:** If Previous Response exists, this is a rework.
Address the feedback and fix accordingly.
```
#### Output Contract — `output-contracts/review.md`
Defines output structure. The agent follows this format when producing output.
````markdown
```markdown
# Architecture Review
## Result: APPROVE / REJECT
## Summary
{1-2 sentence summary of the result}
## Reviewed Aspects
| Aspect | Result | Notes |
|--------|--------|-------|
| Structure & Design | ✅ | - |
| Code Quality | ✅ | - |
| Test Coverage | ✅ | - |
## Issues (if REJECT)
| # | Location | Issue | Fix |
|---|----------|-------|-----|
| 1 | `src/file.ts:42` | Issue description | How to fix |
```
````
#### Assembled Prompt — Complete Example
The engine composes the five files above into the final prompt sent to the LLM.
**System Prompt:**
```markdown
# Architecture Reviewer
You are a software architecture specialist.
You evaluate code structure, design, and maintainability.
## Role Boundaries
**Do:**
- Validate structural and design soundness
- Evaluate code quality
- Verify change scope appropriateness
**Don't:**
- Review security vulnerabilities (Security Reviewer's job)
- Write code yourself
## Behavioral Principles
- Don't demand perfect design. Judge whether it's the best under current constraints
- Respect existing codebase conventions
```
**User Message:**
```markdown
## Policy
# Coding Policy
## Principles
| Principle | Standard |
|-----------|----------|
| DRY | 3+ duplications → REJECT |
| Fail Fast | Reject invalid state early |
| Least Privilege | Minimal scope necessary |
## Prohibitions
- **Unused code** — no "just in case" methods, no future-use fields
- **Direct object mutation** — create new objects with spread operators
- **Fallback abuse** — don't hide uncertainty with `?? 'default'`
---
## Knowledge
# Architecture Knowledge
## Layer Structure
Dependency direction: upper layers → lower layers (reverse prohibited)
| Layer | Responsibility | Depends On |
|-------|---------------|------------|
| Controller | HTTP request handling | Service |
| Service | Business logic | Repository |
| Repository | Data access | None |
## File Organization
| Criteria | Judgment |
|----------|----------|
| File exceeds 300 lines | Consider splitting |
| Multiple responsibilities in one file | REJECT |
| Circular dependencies | REJECT |
---
## User Request
Add JWT token verification to the user authentication module.
---
## Instructions
Implement the task based on the plan.
**Steps:**
1. Declare the change scope
2. Implement the code
3. Write and run tests
4. Record decision log
**Note:** If Previous Response exists, this is a rework.
Address the feedback and fix accordingly.
---
## Output Contract
Output your report in the following format.
\```markdown
# Architecture Review
## Result: APPROVE / REJECT
## Summary
{1-2 sentence summary of the result}
## Reviewed Aspects
| Aspect | Result | Notes |
|--------|--------|-------|
| Structure & Design | ✅ | - |
| Code Quality | ✅ | - |
| Test Coverage | ✅ | - |
## Issues (if REJECT)
| # | Location | Issue | Fix |
|---|----------|-------|-----|
| 1 | `src/file.ts:42` | Issue description | How to fix |
\```
```
Independent files are assembled into a single prompt at runtime. Change a file's content and the prompt changes; point to different files and the combination changes.
### Why These Five?
**Persona** and **Instruction** are the minimum — you need to define who the agent is and what it should do. But in practice, three more concerns emerge as independent axes:

View File

@ -102,7 +102,6 @@ export class InstructionBuilder {
const policyContents = this.context.policyContents ?? this.step.policyContents;
const hasPolicy = !!(policyContents && policyContents.length > 0);
const policyContent = hasPolicy ? policyContents!.join('\n\n---\n\n') : '';
const policyReminder = ''; // Reminder text is in the template itself
// Knowledge injection (domain-specific knowledge, no reminder needed)
const knowledgeContents = this.context.knowledgeContents ?? this.step.knowledgeContents;
@ -132,7 +131,6 @@ export class InstructionBuilder {
retryNote,
hasPolicy,
policyContent,
policyReminder,
hasKnowledge,
knowledgeContent,
instructions,

View File

@ -5,7 +5,7 @@
pieceStructure, iteration, movementIteration, movement, hasReport, reportInfo,
phaseNote, hasTaskSection, userRequest, hasPreviousResponse, previousResponse,
hasUserInputs, userInputs, hasRetryNote, retryNote, hasPolicy, policyContent,
policyReminder, hasKnowledge, knowledgeContent, instructions
hasKnowledge, knowledgeContent, instructions
builder: InstructionBuilder
-->
## Execution Context
@ -18,13 +18,6 @@
{{#if editRule}}- {{editRule}}
{{/if}}
Note: This section is metadata. Follow the language used in the rest of the prompt.
{{#if hasPolicy}}
## Policy
The following policies are behavioral standards applied to this movement. You MUST comply with them.
{{policyContent}}
{{/if}}
{{#if hasKnowledge}}
## Knowledge
@ -70,6 +63,8 @@ The following knowledge is domain-specific information for this movement. Use it
{{instructions}}
{{#if hasPolicy}}
---
**Policy Reminder:** Comply with the policy standards defined in the Policy section above.{{policyReminder}}
## Policy
The following policies are behavioral standards applied to this movement. You MUST comply with them.
{{policyContent}}
{{/if}}

View File

@ -5,7 +5,7 @@
pieceStructure, iteration, movementIteration, movement, hasReport, reportInfo,
phaseNote, hasTaskSection, userRequest, hasPreviousResponse, previousResponse,
hasUserInputs, userInputs, hasRetryNote, retryNote, hasPolicy, policyContent,
policyReminder, hasKnowledge, knowledgeContent, instructions
hasKnowledge, knowledgeContent, instructions
builder: InstructionBuilder
-->
## 実行コンテキスト
@ -17,13 +17,6 @@
- **Bashコマンドで `cd` を使用しないでください。** 作業ディレクトリは既に正しく設定されています。ディレクトリを変更せずにコマンドを実行してください。
{{#if editRule}}- {{editRule}}
{{/if}}
{{#if hasPolicy}}
## Policy
以下のポリシーはこのムーブメントに適用される行動規範です。必ず遵守してください。
{{policyContent}}
{{/if}}
{{#if hasKnowledge}}
## Knowledge
@ -69,6 +62,8 @@
{{instructions}}
{{#if hasPolicy}}
---
**Policy Reminder:** 上記の Policy セクションで定義されたポリシー規範を遵守してください。{{policyReminder}}
## Policy
以下のポリシーはこのムーブメントに適用される行動規範です。必ず遵守してください。
{{policyContent}}
{{/if}}