上下文工程中的檔案類型整合
本文件說明 .agent.md、.instructions.md、.prompt.md 以及 RAG(檢索增強生成)在 AI 系統上下文工程中的作用與協作機制。
一、核心概念架構
1.1 上下文工程定義
上下文工程(Context Engineering) 是設計和管理 AI 系統輸入上下文的學科,目標是: - 提供相關且精確的信息給 LLM - 控制 AI 行為邊界和輸出格式 - 優化 token 使用效率 - 確保響應的一致性和可預測性
1.2 四大組成元素
┌─────────────────────────────────────────────────────┐
│ User Input + Workspace │
│ (動態上下文來源) │
└────────────────┬────────────────────────────────────┘
↓
┌────────────┴────────────┐
│ Context Pipeline │
└────────────┬────────────┘
↓
┌────────────────────────┐
│ 1. .agent.md │ ← 定義 Agent 身份與能力
│ 2. .instructions.md │ ← 自動注入規則和指南
│ 3. .prompt.md │ ← 可重用提示詞模板
│ 4. RAG System │ ← 智能檢索相關代碼/文檔
└────────────┬───────────┘
↓
┌──────────────┐
│ LLM │
└──────┬───────┘
↓
┌──────────────┐
│ Response │
└──────────────┘
二、.agent.md - Agent 定義檔
2.1 作用與目的
.agent.md 文件定義專業化的 AI Agent,為 LLM 提供:
- 角色身份:明確 Agent 是什麼(規劃者、實作者、審查者)
- 工具權限:可使用的工具集(read_file、runSubagent、replace_string_in_file)
- 行為邊界:停止規則防止越權
- 工作流程:結構化的執行步驟
- 交接機制:handoffs 連接到其他 Agent
2.2 在上下文工程中的位置
User Request → Agent Router → 選擇適當的 .agent.md
↓
載入 Agent System Prompt
↓
注入 Tools + Workflow + Rules
↓
執行並根據 handoffs 轉移控制權
2.3 實際運作機制
範例:Plan.agent.md
---
name: Plan
tools: ['search', 'runSubagent', 'fetch']
handoffs:
- label: Start Implementation
agent: agent # 轉給通用實作 agent
---
You are a PLANNING AGENT, NOT an implementation agent.
運作流程:
1. 用戶輸入:「幫我規劃一個新功能」
2. VS Code Copilot 識別為規劃任務 → 載入 Plan.agent.md
3. System Prompt 注入:「You are a PLANNING AGENT...」
4. Tools 限制:只能使用 search、runSubagent(不能編輯檔案)
5. Workflow 執行:
- 使用 runSubagent 收集上下文
- 生成計劃並暫停等待反饋
- 用戶確認後透過 handoff 轉給實作 agent
2.4 與其他上下文的關係
| 互動對象 | 關係 | 說明 |
|---|---|---|
.instructions.md |
補充 | Agent 系統提示 + Instructions 規則 = 完整上下文 |
.prompt.md |
引用 | Agent 可在 workflow 中引用 prompt 模板 |
| RAG | 工具 | Agent 透過 semantic_search 工具使用 RAG |
| User Input | 觸發 | 用戶請求決定載入哪個 Agent |
三、.instructions.md - 自動上下文注入
3.1 作用與目的
.instructions.md 是自動附加到上下文的規則檔案,提供:
- 作用域規則:針對特定檔案路徑或模式的指令
- 編碼標準:格式、命名、最佳實踐
- 禁止事項:不應該做的操作
- 自動生效:無需用戶手動引用
3.2 檔案結構
---
description: 簡短描述這些指令的用途
applyTo: '**/*.java' # Glob 模式定義作用範圍
---
- Rule 1: Always use @Transactional for database operations
- Rule 2: Never expose sensitive data in logs
- Rule 3: Follow naming convention: [verb][Noun][Type]
作用域配置:
- **/*.java - 所有 Java 檔案
- src/main/** - src/main 目錄下所有檔案
- ** - 全域生效
3.3 在上下文管線中的位置
User opens file: src/service/UserService.java
↓
VS Code 掃描 instructions 檔案
↓
找到匹配的 .instructions.md (applyTo: '**/*.java')
↓
自動注入規則到上下文
↓
LLM 在生成代碼時遵循這些規則
3.4 實際應用範例
專案結構:
d:\wpg\credit\
├── prompt\
│ ├── checkBadSmell.instructions.md # 代碼壞味道檢查
│ ├── dto-mapper.instructions.md # DTO 映射規則
│ ├── jpa-mapper.instructions.md # JPA 實體映射規則
│ └── refactor-service.instructions.md # 服務重構指南
├── src\
│ └── main\
│ └── java\
│ └── com\bpaas\creditcontrol\
│ ├── mapper\ # ← 這裡會套用 dto-mapper, jpa-mapper
│ └── v1\service\ # ← 這裡會套用 refactor-service
checkBadSmell.instructions.md
---
description: Code smell detection rules
applyTo: '**/*'
---
When reviewing or generating code, check for:
- **Long Methods**: Methods exceeding 50 lines should be refactored
- **God Classes**: Classes with > 10 methods need decomposition
- **Magic Numbers**: Use named constants instead of literals
- **Duplicated Code**: Extract common logic into helper methods
運作情境:
1. 用戶請求:「重構 UserService.java」
2. VS Code 開啟 src/v1/service/UserService.java
3. 自動載入:
- checkBadSmell.instructions.md(applyTo: **/*)
- refactor-service.instructions.md(applyTo: **/*Service.java)
4. LLM 生成重構建議時會:
- 檢查方法長度(來自 checkBadSmell)
- 遵循服務層模式(來自 refactor-service)
- 避免 God Class 反模式
3.5 優先級與覆蓋規則
┌─────────────────────────────────────────┐
│ 最高優先級 │
│ User Explicit Context (#file, 選取文字) │
└─────────────────┬───────────────────────┘
↓ (覆蓋)
┌─────────────────────────────────────────┐
│ Specific .instructions.md │
│ (applyTo: 'src/service/UserService.java') │
└─────────────────┬───────────────────────┘
↓ (覆蓋)
┌─────────────────────────────────────────┐
│ Scoped .instructions.md │
│ (applyTo: '**/*.java') │
└─────────────────┬───────────────────────┘
↓ (覆蓋)
┌─────────────────────────────────────────┐
│ Global copilot-instructions.md │
│ (根目錄的全域指令) │
└─────────────────┬───────────────────────┘
↓ (增強,不覆蓋)
┌─────────────────────────────────────────┐
│ 最低優先級 │
│ Agent System Prompt │
└─────────────────────────────────────────┘
實際案例:
# Global: copilot-instructions.md
Use camelCase for variables
# Scoped: java-style.instructions.md (applyTo: '**/*.java')
Use PascalCase for class names
Use camelCase for methods
# Specific: mapper-style.instructions.md (applyTo: '**/mapper/*.java')
All mapper interfaces must use MapStruct annotations
當編輯 mapper/UserMapper.java 時:
- ✓ 套用 mapper-style(最具體)
- ✓ 套用 java-style(範圍次之)
- ✓ 套用 global(基礎規則)
- 如果有衝突,mapper-style 優先
四、.prompt.md - 可重用提示詞模板
4.1 作用與目的
.prompt.md 是可重用的提示詞模板,用於:
- 標準化工作流:常見任務的標準化提示
- 參數化輸入:支持變量替換
- 最佳實踐封裝:將專家知識固化為模板
- 一致性保證:確保相同任務產生一致輸出
4.2 格式與結構
---
name: CreateRESTEndpoint
description: Generate a REST API endpoint with best practices
parameters:
- name: entityName
type: string
required: true
- name: httpMethod
type: string
enum: [GET, POST, PUT, DELETE]
---
Create a RESTful API endpoint for ${entityName} with the following requirements:
## HTTP Method
${httpMethod}
## Implementation Checklist
- [ ] Controller with @RestController
- [ ] Service layer with @Transactional
- [ ] DTO for request/response
- [ ] Input validation with @Valid
- [ ] Error handling with @ExceptionHandler
- [ ] Unit tests with MockMvc
## Code Structure
\```java
@RestController
@RequestMapping("/api/v1/${entityName.toLowerCase()}")
public class ${entityName}Controller {
// Implementation here
}
\```
4.3 調用機制
方式 1:Agent Handoff 中使用
# Plan.agent.md
handoffs:
- label: Generate API
agent: agent
prompt: '#createFile based on CreateRESTEndpoint.prompt.md with entityName=User, httpMethod=POST'
send: true
方式 2:用戶直接引用
@workspace Use CreateRESTEndpoint.prompt.md to generate a POST endpoint for Order entity
方式 3:在 Workflow 中嵌入
<workflow>
## Step 3: Generate Endpoint
Load and execute CreateRESTEndpoint.prompt.md with:
- entityName from user input
- httpMethod = GET (default)
</workflow>
4.4 與其他組件的整合
User: "建立一個 User 的 CRUD API"
↓
Plan Agent 分析需求
↓
調用 CreateRESTEndpoint.prompt.md (4次,分別 GET/POST/PUT/DELETE)
↓
每次調用時:
- 載入 .prompt.md 模板
- 注入 entityName=User, httpMethod=X
- 套用 .instructions.md 規則(Java coding standards)
- 透過 RAG 找相似的現有代碼作為參考
- 生成代碼
↓
Implementation Agent 執行實際檔案創建
4.5 進階功能:條件邏輯
---
name: SmartRefactor
parameters:
- name: codeSmell
type: string
enum: [LongMethod, GodClass, DuplicatedCode]
---
Refactor the selected code to fix ${codeSmell}:
{{#if codeSmell == "LongMethod"}}
## Strategy: Extract Method
- Identify logical blocks > 10 lines
- Extract into private methods with descriptive names
- Preserve original behavior
{{/if}}
{{#if codeSmell == "GodClass"}}
## Strategy: Decompose Class
- Apply Single Responsibility Principle
- Create separate classes for distinct concerns
- Use composition over inheritance
{{/if}}
{{#if codeSmell == "DuplicatedCode"}}
## Strategy: Extract Common Logic
- Create utility methods or helper classes
- Apply DRY principle
- Consider Template Method pattern if needed
{{/if}}
五、RAG - 檢索增強生成
5.1 作用與目的
RAG (Retrieval-Augmented Generation) 透過智能檢索增強 LLM 的上下文: - 語義搜尋:理解意圖而非關鍵字匹配 - 相關代碼發現:找到相似實現作為參考 - 動態上下文:根據查詢實時檢索 - 減少幻覺:基於實際代碼庫生成答案
5.2 技術架構
┌────────────────────────────────────────────────┐
│ Offline Indexing Phase │
└────────────────────────────────────────────────┘
Codebase Files
↓
Code Chunking (按函數、類、檔案切分)
↓
Embedding Model (text-embedding-ada-002)
↓
Vector Database (存儲向量表示)
┌────────────────────────────────────────────────┐
│ Online Retrieval Phase │
└────────────────────────────────────────────────┘
User Query: "如何實作 DTO mapper"
↓
Embedding (查詢向量化)
↓
Similarity Search (餘弦相似度)
↓
Top-K Results (取前 5-10 個最相關片段)
↓
Re-ranking (根據新鮮度、重要性重新排序)
↓
Inject into LLM Context
5.3 在 VS Code Copilot 中的實現
工具:semantic_search
// 使用範例(在 Agent workflow 中)
<workflow>
## 1. Gather Context via RAG
Use #tool:semantic_search with query:
"DTO mapping patterns with MapStruct annotations"
This will return relevant code snippets from:
- Existing mapper interfaces
- DTO classes
- Entity classes
</workflow>
實際執行流程
1. Agent 收到請求:「建立 OrderDTO 映射」
2. semantic_search("DTO mapping patterns") 執行:
- 查詢向量化
- 在代碼庫中搜尋
- 返回結果:
✓ UserMapper.java (similarity: 0.92)
✓ ProductMapper.java (similarity: 0.88)
✓ OrderEntity.java (similarity: 0.85)
3. 注入到 LLM 上下文:
"""
Based on existing patterns in your codebase:
[UserMapper.java snippet]
@Mapper(componentModel = "spring")
public interface UserMapper {
UserDTO toDTO(User entity);
}
Create similar mapper for Order entity...
"""
4. LLM 生成代碼時參考這些範例,確保風格一致
5.4 與其他上下文的協作
User: "實作 PaymentService"
↓
┌──────────────────────────────────────┐
│ Context Pipeline │
├──────────────────────────────────────┤
│ 1. Agent System Prompt │ ← 來自 Implementation.agent.md
│ "You are an implementation agent" │
│ │
│ 2. Instructions │ ← 來自 refactor-service.instructions.md
│ - Use @Transactional │
│ - Follow Service layer pattern │
│ │
│ 3. RAG Retrieved Context │ ← 來自 semantic_search
│ [Existing UserService.java] │
│ [Existing OrderService.java] │ (作為實現參考)
│ │
│ 4. User Explicit Context │ ← 用戶選取的代碼片段
│ [Selected PaymentDTO class] │
└──────────────────────────────────────┘
↓
LLM 綜合所有上下文生成 PaymentService
5.5 RAG 的限制與優化
限制
- Token 預算:檢索過多會超出上下文窗口
- 相關性誤判:語義相似不等於邏輯相關
- 時效性:索引可能不包含最新改動
優化策略
<rag_optimization>
## 1. 分階段檢索
- First Pass: Broad semantic search
- Second Pass: Targeted file reads based on results
## 2. 智能過濾
- 排除測試檔案(除非明確需要)
- 優先最近修改的檔案
- 根據檔案大小加權(小檔案可能是配置,大檔案可能是核心邏輯)
## 3. 混合檢索
semantic_search("DTO mapping") # 語義理解
+
grep_search("@Mapper") # 精確匹配
=
更準確的結果
## 4. 上下文壓縮
- 只提取函數簽名和關鍵邏輯
- 省略註解和導入語句
- 使用摘要而非完整代碼
</rag_optimization>
六、MCP(Model Context Protocol)的角色
6.1 MCP 簡介
MCP (Model Context Protocol) 是連接 AI Agent 與外部工具/數據源的標準化協議: - 工具發現:動態列出可用工具 - 標準化調用:統一的工具調用介面 - 擴展生態:第三方可開發 MCP Server
6.2 MCP 在上下文工程中的位置
Agent (Plan.agent.md)
↓ 需要外部數據
MCP Client (VS Code Extension)
↓ 協議通訊
MCP Server (例如:microsoft-docs-mcp-server)
↓ 執行查詢
External Data Source (Microsoft Learn Docs)
↓ 返回結果
MCP Client 注入到 LLM Context
↓
LLM 生成回應時引用最新官方文檔
6.3 實際案例:Azure 最佳實踐
MCP Server 配置
{
"mcpServers": {
"azure-mcp": {
"command": "node",
"args": ["azure-mcp-server.js"],
"tools": [
"get_bestpractices",
"list_resources",
"run_diagnostics"
]
}
}
}
Agent 使用 MCP 工具
# Azure.agent.md
---
name: AzureExpert
tools: ['mcp_azure_get_bestpractices', 'semantic_search']
---
You are an Azure deployment specialist.
<workflow>
## 1. Fetch Best Practices
MANDATORY: Call #tool:mcp_azure_get_bestpractices with:
- resource: azurefunctions
- action: deployment
This retrieves latest official Azure recommendations.
## 2. Combine with RAG
Use semantic_search to find existing Azure config files in workspace.
## 3. Generate Deployment Script
Merge best practices + existing patterns + user requirements.
</workflow>
執行流程
User: "部署我的 Function App 到 Azure"
↓
AzureExpert Agent 載入
↓
1. MCP Call: get_bestpractices(resource="azurefunctions", action="deployment")
返回:
- Use managed identity for authentication
- Enable Application Insights
- Configure CORS properly
- Use deployment slots for zero-downtime
2. RAG Search: semantic_search("azure function configuration")
找到:
- host.json in workspace
- local.settings.json
3. Instructions 注入:azure.instructions.md
- Never hardcode connection strings
- Use Azure Key Vault for secrets
4. 綜合所有上下文生成部署計劃
6.4 MCP vs RAG
| 特性 | RAG | MCP |
|---|---|---|
| 數據來源 | 內部代碼庫 | 外部系統(API、數據庫、文檔) |
| 更新頻率 | 依賴索引更新 | 實時查詢 |
| 典型用途 | 找相似代碼、了解現有模式 | 獲取最新文檔、執行外部操作 |
| 範例 | semantic_search("error handling patterns") |
mcp_microsoft_docs_search("Azure Functions best practices") |
七、完整工作流範例
場景:建立一個新的 REST API 端點
┌─────────────────────────────────────────────────────────┐
│ Phase 1: 用戶請求 │
└─────────────────────────────────────────────────────────┘
User Input:
"建立一個 GET /api/v1/orders/{id} 端點,返回訂單詳情"
┌─────────────────────────────────────────────────────────┐
│ Phase 2: Agent 路由與載入 │
└─────────────────────────────────────────────────────────┘
VS Code 分析請求 → 識別為 API 開發任務
↓
載入 APIDesigner.agent.md
↓
System Prompt 注入:
"You are an API DESIGN AGENT specializing in RESTful API architecture..."
Tools 可用:['semantic_search', 'read_file', 'fetch_webpage']
┌─────────────────────────────────────────────────────────┐
│ Phase 3: 上下文收集(多源融合) │
└─────────────────────────────────────────────────────────┘
3.1 Instructions 自動注入
↓
檢測到當前工作在 Java 專案
↓
自動載入:
- java-coding-standards.instructions.md
- rest-api-conventions.instructions.md
內容包括:
• Use @GetMapping for GET endpoints
• Return ResponseEntity<T> for all responses
• Add @Valid for input validation
3.2 RAG 檢索相關代碼
↓
執行 semantic_search("REST API controller patterns")
↓
返回:
• UserController.java (similarity: 0.91)
```java
@GetMapping("/{id}")
public ResponseEntity<UserDTO> getUser(@PathVariable Long id) {
return ResponseEntity.ok(userService.findById(id));
}
```
• ProductController.java (similarity: 0.87)
3.3 MCP 獲取最新最佳實踐
↓
調用 mcp_microsoft_docs_search("Spring Boot REST API best practices")
↓
返回官方文檔摘錄:
• Use @PathVariable for URL parameters
• Implement proper error handling with @ExceptionHandler
• Document APIs with OpenAPI/Swagger
3.4 用戶選取的上下文
↓
用戶已選取:
• OrderDTO.java (明確指定返回類型)
• OrderService.java (可用的服務方法)
┌─────────────────────────────────────────────────────────┐
│ Phase 4: 上下文優先級排序與合併 │
└─────────────────────────────────────────────────────────┘
最終 LLM 收到的上下文(由高到低優先級):
1. User Explicit Context (最高優先級)
"""
User selected files:
- OrderDTO.java (defines order structure)
- OrderService.java (has findById method)
User instruction:
"建立一個 GET /api/v1/orders/{id} 端點,返回訂單詳情"
"""
2. Targeted Instructions
"""
From rest-api-conventions.instructions.md:
- Use @GetMapping for GET requests
- Return ResponseEntity<OrderDTO>
- Add @PathVariable for path parameters
"""
3. RAG Retrieved Examples
"""
Similar implementation from UserController.java:
[Code snippet showing the pattern]
"""
4. MCP External Knowledge
"""
Spring Boot best practices from Microsoft Docs:
- Use constructor injection for services
- Implement proper HTTP status codes
"""
5. Agent System Prompt
"""
You are an API DESIGN AGENT...
Follow REST principles...
"""
┌─────────────────────────────────────────────────────────┐
│ Phase 5: LLM 生成與驗證 │
└─────────────────────────────────────────────────────────┘
LLM 綜合所有上下文,生成:
```java
@RestController
@RequestMapping("/api/v1/orders")
@RequiredArgsConstructor // ← 來自 MCP 最佳實踐
public class OrderController {
private final OrderService orderService; // ← 來自用戶選取的 context
@GetMapping("/{id}") // ← 來自 Instructions
public ResponseEntity<OrderDTO> getOrder( // ← 來自 RAG 範例模式
@PathVariable Long id) { // ← 來自 Instructions
OrderDTO order = orderService.findById(id); // ← 來自用戶選取的 context
return ResponseEntity.ok(order); // ← 來自 RAG 範例
}
}
驗證步驟: ✓ 符合 Instructions 規定的命名和註解 ✓ 使用 RAG 找到的現有模式(保持一致性) ✓ 遵循 MCP 提供的最佳實踐 ✓ 滿足用戶明確需求
┌─────────────────────────────────────────────────────────┐ │ Phase 6: Handoff(如果需要) │ └─────────────────────────────────────────────────────────┘
APIDesigner Agent 完成設計後: ↓ 提供 Handoff 選項: [ Start Implementation ] → 轉給 Implementation Agent [ Generate Tests ] → 轉給 Testing Agent [ Create Documentation ] → 轉給 Documentation Agent
如果用戶選擇 "Start Implementation": ↓ Implementation Agent 接手 ↓ 使用 replace_string_in_file 創建實際檔案 ↓ 完成後運行測試驗證
---
## 八、優先級與衝突解決
### 8.1 上下文優先級金字塔
### 8.2 衝突解決策略
#### 情境 1:Instructions 之間的衝突
**問題**:
```markdown
# Global instructions
Use snake_case for all variables
# Java-specific instructions (applyTo: '**/*.java')
Use camelCase for Java variables
解決:
檔案類型決定 → Java 檔案使用 camelCase(更具體的規則優先)
情境 2:Instructions vs RAG
問題:
- Instructions 規定:「不要使用 @Autowired field injection」
- RAG 找到的現有代碼大量使用 @Autowired
解決:
Instructions 優先 → 生成新代碼使用 constructor injection
但 LLM 會在回應中說明:
"Note: Existing code uses field injection, but following current
best practices, I'm using constructor injection for the new code."
情境 3:User Input vs Instructions
問題: - User 明確說:「使用 field injection」 - Instructions 規定:「必須使用 constructor injection」
解決:
User Input 最高優先級 → 使用 field injection
但 LLM 可能會提示:
"⚠️ Warning: This violates project instructions which recommend
constructor injection. Proceeding as explicitly requested."
8.3 最佳實踐:設計無衝突的規則
# ✅ 良好設計:層次清晰
# 1. Global: 基礎原則
Use meaningful names
Write self-documenting code
# 2. Language-specific: 語言規範
## java.instructions.md
Use PascalCase for classes
Use camelCase for methods
# 3. Domain-specific: 領域規則
## mapper.instructions.md (applyTo: '**/mapper/*.java')
All mappers must use MapStruct
Avoid manual field mapping
# ❌ 不良設計:規則衝突
# global.instructions.md
Always use `var` for type inference
# java.instructions.md
Never use `var`, always declare explicit types
# 這會導致 LLM 困惑和不一致的輸出
九、實施建議與最佳實踐
9.1 建立上下文工程體系的步驟
Phase 1: 基礎設施
├── 1. 創建 .copilot-instructions.md (全域基礎規則)
├── 2. 設置關鍵的 .instructions.md
│ ├── 編碼標準 (coding-standards.instructions.md)
│ ├── 安全規範 (security-rules.instructions.md)
│ └── 測試要求 (testing-requirements.instructions.md)
└── 3. 配置 MCP servers (如果需要外部數據)
Phase 2: Agent 設計
├── 4. 識別核心工作流(規劃、實作、審查、測試)
├── 5. 為每個工作流創建專門的 .agent.md
└── 6. 設計 handoff 路徑連接 agents
Phase 3: 模板庫
├── 7. 提取常見任務為 .prompt.md 模板
├── 8. 參數化和文檔化每個模板
└── 9. 在 agent workflows 中引用模板
Phase 4: RAG 優化
├── 10. 確保代碼庫結構清晰(便於檢索)
├── 11. 添加有意義的註解和文檔(提升 RAG 質量)
└── 12. 定期更新索引
Phase 5: 迭代改進
├── 13. 收集使用反饋
├── 14. 分析失敗案例
└── 15. 持續優化規則和工作流
9.2 檔案組織建議
project-root/
├── .copilot-instructions.md # 全域規則
├── .vscode/
│ └── copilot/
│ ├── agents/ # Agent 定義
│ │ ├── planner.agent.md
│ │ ├── implementer.agent.md
│ │ ├── reviewer.agent.md
│ │ └── tester.agent.md
│ ├── prompts/ # 可重用模板
│ │ ├── create-rest-endpoint.prompt.md
│ │ ├── refactor-service.prompt.md
│ │ └── write-unit-test.prompt.md
│ └── instructions/ # 作用域規則
│ ├── java/
│ │ ├── coding-style.instructions.md
│ │ ├── mapper-rules.instructions.md
│ │ └── service-patterns.instructions.md
│ ├── typescript/
│ │ └── react-patterns.instructions.md
│ └── security/
│ └── auth-rules.instructions.md
├── src/
│ ├── main/
│ │ └── java/
│ │ └── com/company/
│ │ ├── controller/
│ │ ├── service/
│ │ ├── mapper/ # ← mapper-rules 自動生效
│ │ └── entity/
│ └── test/
└── docs/
└── copilot/
├── agent-design-guide.md # 本文件
└── context-engineering.md # 上下文工程指南
9.3 常見陷阱與解決方案
| 陷阱 | 問題 | 解決方案 |
|---|---|---|
| 規則過載 | 太多 instructions 導致上下文膨脹 | 合併相關規則,只保留關鍵約束 |
| 優先級不明 | 衝突規則導致行為不一致 | 明確文檔化優先級,使用層次化設計 |
| Agent 職責不清 | Agent 超出範圍或職責重疊 | 嚴格 stopping rules,明確 handoff 路徑 |
| RAG 噪音 | 檢索到無關代碼 | 改進查詢詞,使用過濾器(excludePattern) |
| MCP 延遲 | 外部調用拖慢響應 | 緩存常用結果,並行化獨立調用 |
| 模板僵化 | .prompt.md 過於具體無法復用 | 增加參數化,支持條件邏輯 |
9.4 性能優化策略
<performance_optimization>
## Token 預算管理
- 優先載入高價值上下文(核心邏輯 > 測試 > 註解)
- 使用摘要而非完整檔案(函數簽名 vs 完整實現)
- 設置 RAG 檢索上限(top-k = 5-10)
## 並行化策略
- 獨立的 semantic_search 可並行執行
- MCP 調用與 RAG 檢索同時進行
- 多個 read_file 操作批次處理
## 緩存機制
- Instructions 檔案在會話期間緩存
- RAG 索引定期更新而非每次查詢
- MCP 結果短期緩存(特別是靜態文檔)
## 漸進式載入
<workflow>
## Phase 1: 快速評估(低 token 消耗)
- 載入 agent prompt + instructions
- 執行一次 semantic_search
- 評估是否需要更多上下文
## Phase 2: 深度探索(根據需要)
- 如果 Phase 1 不足,再執行 targeted reads
- 調用 MCP 獲取外部知識
- 使用 runSubagent 處理複雜任務
</workflow>
</performance_optimization>
十、未來趨勢與演進
10.1 上下文工程的發展方向
- 自適應上下文選擇
- AI 自動判斷需要哪些上下文
- 動態調整檢索策略
-
基於任務複雜度優化 token 使用
-
多模態上下文
- 圖表、架構圖作為上下文
- UI 截圖輔助前端開發
-
數據庫 schema 視覺化
-
協作式上下文
- 團隊共享的 instructions 庫
- 版本控制的 agent 配置
-
跨專案的最佳實踐同步
-
增強型 RAG
- 圖神經網絡理解代碼關係
- 時間感知檢索(優先最新代碼)
- 上下文感知重排序
10.2 MCP 生態的擴展
預期未來會有更多 MCP Servers: - Database MCP: 直接查詢數據庫 schema - JIRA/GitHub MCP: 獲取 issue、PR 上下文 - CI/CD MCP: 讀取構建日誌、部署狀態 - Monitoring MCP: 取得生產環境指標 - Knowledge Base MCP: 連接企業 wiki、Confluence
10.3 Agent 網絡演進
Current: Linear Handoff
Plan Agent → Implementation Agent → Testing Agent
Future: Dynamic Collaboration
┌─────────┐
│ User │
└────┬────┘
│
┌──────▼──────┐
│ Orchestrator │ (智能路由)
└──────┬───────┘
│
┌──────┴──────┬─────────┬─────────┐
▼ ▼ ▼ ▼
┌────────┐ ┌─────────┐ ┌──────┐ ┌────────┐
│ Planner│ │ Reviewer│ │Coder │ │ Tester │
└───┬────┘ └────┬────┘ └──┬───┘ └───┬────┘
│ │ │ │
└────────────┴─────────┴─────────┘
│
(協同完成任務)
十一、總結
核心要點回顧
.agent.md- 定義專業化 AI 角色,控制行為邊界和工具權限.instructions.md- 自動注入的規則,確保代碼品質和一致性.prompt.md- 可重用模板,標準化常見工作流- RAG - 智能檢索相關代碼,提供實踐參考
協作機制
User Request
↓
┌────────────────────────┐
│ Agent 載入 │ ← .agent.md 定義角色
└────────┬───────────────┘
↓
┌────────────────────────┐
│ Instructions 注入 │ ← .instructions.md 設置規則
└────────┬───────────────┘
↓
┌────────────────────────┐
│ RAG 檢索相關上下文 │ ← 語義搜尋代碼庫
└────────┬───────────────┘
↓
┌────────────────────────┐
│ MCP 獲取外部知識 │ ← 最新文檔、最佳實踐
└────────┬───────────────┘
↓
┌────────────────────────┐
│ Template 應用 │ ← .prompt.md 標準化輸出
└────────┬───────────────┘
↓
LLM 生成
↓
┌────────────────────────┐
│ Handoff 到下個 Agent │ ← 工作流延續
└────────────────────────┘
設計原則
✓ 層次化:清晰的優先級和覆蓋規則
✓ 模組化:每個組件職責單一
✓ 可組合:靈活組合以應對複雜任務
✓ 可維護:文檔化、版本化、可測試
✓ 高效能:並行化、緩存、漸進式載入
透過深入理解這四大組件的作用與協作機制,團隊可以構建出強大、可靠、可維護的 AI 輔助開發系統。
最後更新: 2025-11-26
適用版本: GitHub Copilot Chat, VS Code Extension API
相關文件: Agent Design Guide