
Agentic Workflow Guide
- 107 installs
- 23 repo stars
- Updated August 4, 2026
- aktsmm/agent-skills
Design reliable multi-step agent workflows with clear roles, tool boundaries, checkpoints, and handoffs so coding agents complete complex tasks without loops, scope creep, or silent failures.
About
agentic-workflow-guide in aktsmm/agent-skills teaches agents how to structure dependable agentic workflows—roles, tool use, checkpoints, and recovery—so complex coding tasks run predictably in production agent environments.
- Multi-step orchestration patterns
- Tool boundary and role design
- Verification and checkpointing
- Failure recovery playbooks
- Reusable agent workflow templates
Agentic Workflow Guide by the numbers
- 107 all-time installs (skills.sh)
- Ranked #4,145 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/aktsmm/agent-skills --skill agentic-workflow-guideAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 107 |
|---|---|
| repo stars | ★ 23 |
| Last updated | August 4, 2026 |
| Repository | aktsmm/agent-skills ↗ |
What it does
Design reliable multi-step agent workflows with clear roles, tool boundaries, checkpoints, and handoffs so coding agents complete complex tasks without loops, scope creep, or silent failures.
Files
Agentic Workflow Guide
Design, review, and improve agent workflows based on proven principles.
この SKILL の基本姿勢は、agent を増やすことではなく、必要最小の primitive で解くこと。 context が膨らんだときも、まずは split / compact / reference 化を考え、いきなり multi-agent にしない。
Primitive First
Do not start with multi-agent by default.
- Single focused slash task -> Prompt
- Always-on or file-scoped guidance -> Instruction
- Reusable workflow with bundled assets -> Skill
- Persona, tool restrictions, delegation, or handoffs -> Agent
- Deterministic enforcement -> Hook
If the ask does not require an Agent, stop and use the simpler primitive.
この primitive 選択表が SSOT。skill-creator-plus / skill-finder などの判定表は「そのスキルを使うべきか」の即時ゲートとして扱い、基準がずれたらここに合わせる。
Selection details: references/customization-decision.md
When to Use
| Action | Triggers |
|---|---|
| Create | New .agent.md, .instructions.md, .prompt.md, AGENTS.md, or workflow architecture |
| Review | Orchestrator not delegating, design principle check, context overflow |
| Update | Adding Handoffs, improving delegation, tool configuration |
| Debug | Agent not found, subagent not working, picker visibility, access control |
| Decide | Determining whether multi-agent is justified or a simpler primitive is enough |
Core Principles
- Simplicity First: より単純な primitive で解けるなら agent 化しない
- SSOT / SRP: 情報源と責務の分割を守る
- Fail Fast: エラーは早く止める
- Feedback Loop: 各段で検証できるようにする
- Context Discipline: context が膨らんだら compact / split / retrieve を検討する
Principle details: references/design-principles.md
Pattern Selection
- Prompt Chaining: 順序のある段階処理
- Routing: 入力タイプで分岐する処理
- Parallelization: 独立タスクを並列で進める処理
- Orchestrator-Workers: 動的に subtasks を分解する処理
- Evaluator-Optimizer: 品質基準を満たすまで反復する処理
Every loop needs explicit stop conditions.
Pattern details: references/workflow-patterns/overview.md
Design Workflow
1. Extract from conversation Repeated behavior, tool preferences, workflow shape, and obvious specialization を先に拾う。 2. Choose primitive + scope Prompt / instruction / skill / agent / hook と workspace / profile を決める。 3. Clarify only the gaps 挙動を変える曖昧さだけ聞く。 4. Check escalation agent や multi-agent が本当に必要か確認する。 5. Choose pattern complexity が上がるなら pattern を明示して設計する。 6. Review before expanding split / compact / reference 化で済まないかを見る。 7. Implement and iterate 最初から完成形を狙わず、弱い箇所を見つけて詰める。
Rule Placement
- 汎用的な workflow 設計原則は、この SKILL と
references/を SSOT にする。 - repo local の
.instructions.mdには workspace 固有の差分だけを残す。差分が無い generic instruction は merge back して削除候補にする。 - IR は原則 in-memory で扱う。validator、script、deterministic handoff が必要な場合だけ中間 file を materialize し、不要になったら片付ける。
Escalation Rules
- L0: Single Prompt
- L1: Prompt + Instructions
- L2: Single Agent
- L3: Multi-Agent
Prefer the lowest level that solves the problem cleanly.
Quick signals:
- Prompt > 50 lines
- Steps > 5
- "missed" / "overlooked" errorsが続く
- Multiple responsibilities in one agent
- Context > 70%
Threshold details: references/splitting-criteria.md
Entry Boundary Smells
Instruction Elevation Smell
always-loaded entry において、強い命令語が直下の catalog、reference list、workflow map、rule inventory を会話の優先レイヤーへ昇格させる状態。
Always-Loaded Entry Budget
always-loaded entry は会話境界と最小 guardrail のみを持つ。catalog、詳細手順、広い参照一覧は docs、README、task-specific assets へ退避する。
Runtime Boundary Rule
Review assets improve design quality and detect structural problems. Default conversational behavior is controlled by always-loaded entries.
Casual Input Safety Check
Lightweight inputs such as greetings, short Q&A, and numeric-only replies should not be force-routed into task intake unless the task context is explicit.
Review Gates
- [ ] Primitive choice is simpler than agent if possible
- [ ] Placement is appropriate and always-loaded entry files stay thin
- [ ] New additions are proposed only after delete / merge / split / move options are checked
- [ ] Single responsibility per agent is preserved
- [ ] Errors can be detected and stopped early
- [ ] Results are verifiable at each step
- [ ] Deterministic parts are offloaded to scripts / IR / hooks (not LLM loops)
Full checklist: references/review-checklist.md
Reference Map
| Topic | Reference |
|---|---|
| Primitive decision | references/customization-decision.md |
| Design principles | references/design-principles.md |
| Workflow patterns | references/workflow-patterns/overview.md |
| Splitting criteria | references/splitting-criteria.md |
| Review checklist | references/review-checklist.md |
| Context management | references/context-engineering.md |
| External links | references/external-resources.md |
agent Quick Fix
Problem: Orchestrator says "I'll delegate" but does work directly.
Solution: Use MUST/MANDATORY language. See agent-guide.md.
## MANDATORY: Sub-agent Delegation
You MUST use agent for each file. Do NOT read files directly.Tools Reference
Use references/agent-template.md for tool mapping and stable agent scaffold details.
Done Criteria
- [ ] Primitive and scope selected intentionally
- [ ] Workflow pattern selected and confirmed with user
- [ ] New or updated assets have clear Role/Workflow/Done Criteria where applicable
- [ ] Design principles checklist passed
- [ ] Recommendations are classified as delete / merge / split / move / add / keep where applicable
- [ ] Always-on instruction boundaries and DRY / SSOT risks are explicitly reviewed when
copilot-instructions.mdorAGENTS.mdare in scope - [ ] New agent / workflow assets are registered in the appropriate catalog or docs when needed
- [ ]
AGENTS.mdis updated only when shared guardrails or entry behavior need to change - [ ] Long-running or ad-hoc terminals/tasks started during the workflow are closed, or remaining terminals are explicitly reported with a reason
- [ ] Async operations are verified by live state before being called complete; if blocked by retention/locks/background platform work, the blocker and next check condition are explicit
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
## English
Copyright (c) 2025-2026 yamapan (aktsmm)
This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0
International License.
You are free to:
- **Share** — copy and redistribute the material in any medium or format
- **Adapt** — remix, transform, and build upon the material
Under the following terms:
- **Attribution** — You must give appropriate credit, provide a link to the
license, and indicate if changes were made. You may do so in any reasonable manner,
but not in any way that suggests the licensor endorses you or your use.
- **NonCommercial** — You may not use the material for commercial purposes.
*(Please contact the author if you wish to use this material for commercial purposes.)*
- **ShareAlike** — If you remix, transform, or build upon the material, you must
distribute your contributions under the same license as the original.
No additional restrictions — You may not apply legal terms or technological
measures that legally restrict others from doing anything the license permits.
**AI/ML Training Restriction** — Use of this content for AI/ML training, data
mining, or other analytical purposes is prohibited without explicit permission.
Full license text: https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode
---
## 日本語
Copyright (c) 2025-2026 yamapan (aktsmm)
この作品はクリエイティブ・コモンズ 表示-非営利-継承 4.0 国際ライセンスの下に提供されています。
あなたは以下の条件に従う限り、自由に:
- **共有** — どのようなメディアやフォーマットでも資料を複製・再配布できます
- **翻案** — 資料をリミックス、変形、および加工することができます
以下の条件に従ってください:
- **表示** — あなたは適切なクレジットを表示し、ライセンスへのリンクを提供し、
変更があったらその旨を示さなければなりません。これらは合理的であればどのような方法で
行っても構いませんが、許諾者があなたやあなたの利用行為を支持していると示唆するような
方法は除きます。
- **非営利** — あなたは営利目的でこの資料を利用してはなりません。
(※商用利用をご希望の場合は、別途ご連絡ください。)
- **継承** — もしあなたがこの資料をリミックス、変形、または加工した場合、
あなたはあなたの貢献部分を元の作品と同じライセンスの下で配布しなければなりません。
追加的な制約は課せません — あなたは、このライセンスが他の者に許諾することを法的に
制限するような法的条項や技術的手段を適用してはなりません。
**AI/MLトレーニング制限** — 本コンテンツをAI/MLモデルのトレーニング、データマイニング、
その他の解析目的での使用は明示的な許可なく禁止されています。
ライセンス全文: https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode.ja
---
## Special Permission for Microsoft Employees / Microsoft 社員向け特別許諾
### English
Microsoft Corporation employees are granted permission to use, copy, modify, and
distribute this material for any purpose within the scope of their employment
duties at Microsoft, including internal business use and customer-facing
activities, without the NonCommercial restriction of this license.
This special permission applies only to work performed as part of official
Microsoft business activities.
### 日本語
Microsoft Corporation の社員は、Microsoft での業務の範疇において、本資料を社内業務
および顧客対応を含むあらゆる目的で使用、複製、改変、配布することが許諾されます。
この場合、本ライセンスの「非営利」制限は適用されません。
この特別許諾は、Microsoft の公式な業務活動の一環として行われる作業にのみ適用されます。
---
## Disclaimer / 免責事項
### English
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
### 日本語
本ソフトウェアは「現状のまま」で提供され、明示または黙示を問わず、商品性、
特定目的への適合性、および権利非侵害についての保証を含むがこれに限定されない、
いかなる種類の保証も伴いません。作者または著作権者は、契約行為、不法行為、
またはそれ以外であろうと、ソフトウェアに起因または関連し、あるいはソフトウェアの
使用またはその他の扱いによって生じる一切の請求、損害、その他の責任について
責任を負いません。
Agent Evaluation
A framework for measuring agent workflow effectiveness based on vscode-ai-toolkit best practices.
Table of Contents
- Overview - Why evaluation matters
- Three Core Metrics - Intent Resolution, Tool Call Accuracy, Task Adherence
- Evaluation Methodology - How to evaluate
- Evaluation Best Practices - Guidelines for effective evaluation
- Common Evaluation Pitfalls - Anti-patterns to avoid
- Evaluation Checklist - Quick check template
---
Overview
Effective agent evaluation goes beyond simple success/fail metrics. It requires assessing the quality of reasoning, tool usage, and task adherence across diverse scenarios.
Three Core Metrics
1. Intent Resolution
Does the agent correctly understand and fulfill user intent?
| Aspect | Description |
|---|---|
| What to Measure | Accuracy of understanding user's goal |
| Success Criteria | Agent addresses the actual need, not surface request |
| Common Failures | Misinterpreting ambiguous requests, literal parsing |
Evaluation Questions
- [ ] Did the agent clarify ambiguous requests?
- [ ] Did it address the underlying goal or just the explicit ask?
- [ ] Were edge cases and constraints considered?
- [ ] Did the output match user expectations?
Example Scenarios
| User Request | Poor Intent Resolution | Good Intent Resolution |
|---|---|---|
| "Fix the bug" | Changes random code without analysis | Reproduces bug, identifies root cause |
| "Add authentication" | Implements basic login | Asks about requirements (OAuth, JWT, etc) |
| "Make it faster" | Random optimizations | Profiles code, targets bottlenecks |
2. Tool Call Accuracy
Does the agent use tools correctly and efficiently?
| Aspect | Description |
|---|---|
| What to Measure | Correctness and appropriateness of tool selection |
| Success Criteria | Right tool, right parameters, right sequence |
| Common Failures | Wrong tool, hallucinated tools, inefficient usage |
Evaluation Questions
- [ ] Did the agent use available tools (not reimplementing)?
- [ ] Were tool parameters correct and complete?
- [ ] Was the tool sequence logical and efficient?
- [ ] Were errors handled gracefully?
Common Tool Usage Mistakes
| Mistake | Example | Fix |
|---|---|---|
| Hallucinated Tools | Calls search_web() when not defined | Validate tool availability |
| Wrong Parameters | Passes string when tool expects array | Strict parameter validation |
| Inefficient Chains | Reads same file 10 times | Cache results, batch operations |
| Missing Error Handling | Continues after tool failure | Check return codes, implement fallbacks |
| Tool Reimplementation | Writes grep-like logic instead of using grep tool | Document tool capabilities clearly |
Tool Call Metrics
**Accuracy:** (Correct Tool Calls) / (Total Tool Calls)
**Efficiency:** (Optimal Tool Count) / (Actual Tool Count)
**Coverage:** (Tools Used) / (Relevant Tools Available)3. Task Adherence
Does the agent follow instructions and constraints?
| Aspect | Description |
|---|---|
| What to Measure | Compliance with explicit and implicit rules |
| Success Criteria | Respects boundaries, doesn't overstep or skip |
| Common Failures | Scope creep, ignoring constraints, shortcuts |
Evaluation Questions
- [ ] Did the agent respect scope boundaries?
- [ ] Were constraints (time, resources, safety) followed?
- [ ] Did it avoid making unauthorized changes?
- [ ] Were deliverables complete per specification?
Adherence Violations
| Violation Type | Example | Impact |
|---|---|---|
| Scope Creep | Asked to fix bug, refactors entire codebase | Wasted time, new risks |
| Constraint Bypass | Ignores "don't delete files" rule | Data loss, trust breach |
| Premature Action | Starts execution before plan approval | Wasted work, misalignment |
| Incomplete Output | Returns half-finished documentation | User must finish work |
---
Evaluation Methodology
1. Test Data Generation
Create diverse, realistic test scenarios
Scenario Categories
| Category | Description | Example |
|---|---|---|
| Happy Path | Clear, straightforward requests | "List files in src/ directory" |
| Ambiguous | Requires clarification | "Make it better" (what aspect?) |
| Edge Cases | Boundary conditions, unusual inputs | Empty repository, large file counts |
| Error Handling | Simulated failures | File not found, API timeout |
| Multi-Step | Complex workflows | Analyze → Design → Implement → Test |
| Constraint-Heavy | Many restrictions | "Refactor but don't change API" |
Test Data Generation Process
Step 1: Identify Agent's Domain
- What tasks does it handle?
- What tools does it use?
Step 2: Create Baseline Scenarios
- 10-20 typical use cases
- Cover main functionality
Step 3: Add Variation
- Ambiguous phrasing
- Missing information
- Conflicting requirements
Step 4: Include Edge Cases
- Boundary values (empty, max size)
- Unusual file types or formats
- Concurrent requests
Step 5: Simulate Failures
- Tool unavailability
- Partial results
- Timeout scenariosExample Test Set (Code Review Agent)
test_cases:
- id: "happy-001"
input: "Review src/auth.py for security issues"
expected_tools: ["read", "grep"]
expected_output_type: "security_report"
success_criteria:
- Uses #tool:read to access file
- Identifies security patterns (SQL injection, XSS, etc.)
- Provides severity ratings
- id: "ambiguous-001"
input: "Check this"
expected_behavior: "Request clarification"
success_criteria:
- Asks what to check
- Offers options (code, tests, docs)
- Doesn't make assumptions
- id: "edge-001"
input: "Review all Python files"
context: "Repository has 1000+ .py files"
expected_behavior: "Plan-First approach"
success_criteria:
- Creates plan before execution
- Proposes batching or sampling
- Estimates time required
- id: "error-001"
input: "Review src/nonexistent.py"
expected_behavior: "Graceful error handling"
success_criteria:
- Detects file doesn't exist
- Informs user clearly
- Suggests alternatives (similar files, search)2. Evaluation Rubric
Score each dimension on a scale
Intent Resolution Rubric
| Score | Description |
|---|---|
| 5 | Perfect understanding, proactive clarification |
| 4 | Correct interpretation, addresses need |
| 3 | Mostly correct, minor misunderstanding |
| 2 | Partially correct, significant gaps |
| 1 | Misunderstood intent, wrong direction |
| 0 | Complete failure to understand or engage with request |
Tool Call Accuracy Rubric
| Score | Description |
|---|---|
| 5 | Optimal tool selection and usage, error-free |
| 4 | Correct tools, minor inefficiencies |
| 3 | Mostly correct, some suboptimal choices |
| 2 | Significant tool misuse, works but inefficient |
| 1 | Wrong tools or hallucinations, barely functional |
| 0 | Tool calls fail, agent cannot proceed |
Task Adherence Rubric
| Score | Description |
|---|---|
| 5 | Perfect compliance, respects all constraints |
| 4 | Minor deviations, core requirements met |
| 3 | Some scope creep or missed constraints |
| 2 | Significant violations, partial deliverables |
| 1 | Major violations, ignores instructions |
| 0 | Completely off-track, disregards requirements |
3. Automated Testing
Implement programmatic evaluation where possible
What Can Be Automated
| Aspect | Automation Approach |
|---|---|
| Tool Call Validation | Parse logs, check tool names and parameters |
| Output Format | Schema validation (JSON, YAML) |
| File Operations | Verify files created/modified as expected |
| Performance Metrics | Measure execution time, tool call count |
| Constraint Violations | Check against rule list (deleted files, etc.) |
Prefer Stable Assertions
Programmatic evaluation is strongest when assertions survive renames, workspace changes, and normal output variation.
Prefer:
- schema or heading checks over long exact-string matches
- tool-usage checks over replaying one transcript verbatim
- stable identifiers (file basenames, declared section names, output schema keys)
Avoid:
- temporary workspace paths
- machine-specific absolute paths
- exact output assertions copied from a single recorded run
What Requires Human Review
| Aspect | Why Human Needed |
|---|---|
| Intent Understanding | Nuanced interpretation of ambiguous requests |
| Output Quality | Subjective assessment (clarity, completeness) |
| Creativity | Innovation and problem-solving approach |
| Edge Case Handling | Appropriateness of fallback strategies |
Automation Example (Python)
def evaluate_tool_calls(log_file, expected_tools):
"""
Evaluate tool call accuracy from execution logs.
"""
with open(log_file) as f:
logs = json.load(f)
tool_calls = [entry for entry in logs if entry["type"] == "tool_call"]
metrics = {
"total_calls": len(tool_calls),
"unique_tools": len(set(call["tool_name"] for call in tool_calls)),
"hallucinated": sum(1 for call in tool_calls
if call["tool_name"] not in expected_tools),
"failed": sum(1 for call in tool_calls
if call["status"] == "error"),
}
metrics["accuracy"] = 1 - (metrics["hallucinated"] / metrics["total_calls"])
return metrics---
Evaluation Best Practices
1. Establish Baselines
Before making changes, measure current performance:
Baseline Evaluation (v1.0)
- Intent Resolution: 3.8/5.0
- Tool Call Accuracy: 4.2/5.0
- Task Adherence: 4.5/5.0
After Optimization (v1.1)
- Intent Resolution: 4.3/5.0 ✅ +13%
- Tool Call Accuracy: 4.6/5.0 ✅ +9.5%
- Task Adherence: 4.4/5.0 ⚠️ -2.2%2. Diverse Test Set
| Principle | Rationale |
|---|---|
| Coverage | Test all major features and edge cases |
| Realism | Use real-world scenarios, not synthetic examples |
| Difficulty Range | Include easy, medium, and hard tasks |
| Failure Scenarios | Don't just test happy paths |
| User Language | Use actual phrasing users would employ |
3. Iterative Improvement
graph LR
A[Baseline] --> B[Identify Weaknesses]
B --> C[Implement Fix]
C --> D[Re-evaluate]
D --> E{Improved?}
E -->|Yes| F[Deploy]
E -->|No| G[Different Approach]
G --> C4. Log Everything
Comprehensive logging enables debugging and improvement
{
"test_id": "happy-001",
"timestamp": "2024-01-15T10:30:00Z",
"user_input": "Review src/auth.py",
"agent_plan": "1. Read file 2. Scan for patterns 3. Report",
"tool_calls": [
{
"tool": "read",
"params": { "file": "src/auth.py" },
"status": "success"
},
{ "tool": "grep", "params": { "pattern": "eval\\(" }, "status": "success" }
],
"output": "Found 2 security issues...",
"scores": {
"intent_resolution": 5,
"tool_accuracy": 5,
"task_adherence": 5
},
"evaluator_notes": "Excellent handling, proactive security scan"
}Logs are valuable inputs for designing evals, but they should not become the assertion wholesale. Use logs to discover robust checks, then reduce them to stable criteria.
5. Continuous Monitoring
Evaluation isn't one-time; monitor in production
| Metric | Frequency | Action Threshold |
|---|---|---|
| User Satisfaction | After each task | <80% positive → investigate |
| Tool Call Failures | Real-time | >5% failure rate → alert |
| Task Completion Rate | Daily | <90% → review failures |
| Average Execution Time | Weekly | +20% vs baseline → profile |
---
Common Evaluation Pitfalls
1. Overfitting to Test Set
Problem: Agent performs well on tests but poorly on real tasks.
Solution:
- Use held-out test set
- Regularly refresh test scenarios
- Include user-reported issues
2. Ignoring User Feedback
Problem: Metrics look good, users are unhappy.
Solution:
- Collect qualitative feedback
- Review actual usage logs
- User interviews/surveys
3. Binary Pass/Fail
Problem: Doesn't capture nuance or areas for improvement.
Solution:
- Use rubrics with gradations
- Track multiple dimensions
- Identify specific failure modes
4. Testing Only Happy Paths
Problem: Agent fails when things go wrong.
Solution:
- Systematically test error conditions
- Simulate timeouts, missing resources
- Test with malformed inputs
5. Lack of Regression Testing
Problem: New features break existing functionality.
Solution:
- Maintain test suite
- Run before each release
- Automate where possible
6. Brittle Recorded Evaluations
Problem: A recorded test only passes for the original session because it encodes one temporary path or one exact output.
Solution:
- Rewrite assertions around structure, tool behavior, or schema
- Replace workspace-specific paths with stable identifiers
- Re-run evaluation after renames to confirm the checks still hold
---
Evaluation Checklist
Before deploying an agent workflow:
- [ ] Created diverse test set (happy, ambiguous, edge, error)
- [ ] Defined success criteria for each test
- [ ] Established baseline metrics
- [ ] Tested all major workflows
- [ ] Verified tool call accuracy
- [ ] Confirmed constraint adherence
- [ ] Assertions rely on stable structure or tool behavior, not one recorded run
- [ ] Logged evaluation results
- [ ] Identified improvement areas
- [ ] Documented known limitations
- [ ] Set up monitoring for production---
References
Agent (Sub-agent) Guide
Practical guide for using subagent tools in VS Code Copilot and Claude Code.
Table of Contents
- What is agent? - Key characteristics and purpose
- When to Use - Effective scenarios and anti-patterns
- How to Invoke - Enabling and invocation methods
- Prompt Engineering - Sub-agent prompt requirements
- Orchestrator-Workers Pattern - Architecture examples
- Common Pitfalls - Avoiding delegation failures
- Token Efficiency - Trade-offs and recommendations
- Handoffs vs agent - Comparison
- Checklist - Implementation checklist
Platform Note (2026/02 Updated):
>
- VS Code Copilot: Useagentintools:and#tool:agentin prompts (runSubagentis a legacy alias)
- Claude Code: UseTaskintools:
Legacy call patterns (avoid in new docs)
The following legacy forms may still work but should not be used in new documentation:
tools: ["runSubagent"]→ usetools: ["agent"]#tool:runSubagent→ use#tool:agentrunSubagent({ ... })→ useagent({ ... })agent/runSubagent(old tool path) → useagent
What is agent?
The agent tool launches an independent agent with a clean context window to handle complex, multi-step tasks autonomously.
Key Characteristics
| Aspect | Description |
|---|---|
| Context | Each sub-agent has its own context window (isolated from main) |
| Execution | Synchronous - main agent waits for result (NOT async/background) |
| Stateless | One-shot execution - no follow-up conversation possible |
| Return | Only final summary returns to main agent |
| Parallel | ✅ Supported (2026/01+) - multiple sub-agents can run in parallel |
| Nesting | ❌ NOT supported - sub-agents cannot call agent |
Primary Purpose
"agent is for context management, NOT for speed optimization."
Use when you want to:
- Keep main session context clean (avoid context rot)
- Isolate detailed exploration from synthesis
- Process large data without polluting main context
---
When to Use
→ See also [splitting-criteria.md](splitting-criteria.md) for the complete escalation ladder and quantitative thresholds.
✅ Effective Scenarios
| Scenario | Example |
|---|---|
| Research mid-session | "Investigate this library's API" during implementation |
| Log/data analysis | Parse thousands of log lines, return only conclusions |
| File-by-file operations | Fix ESLint errors in each file independently |
| Phase-based workflows | Plan → Implement → Review (each phase = sub-agent) |
When a workflow matches these scenarios or the thresholds in splitting-criteria.md, write delegation as a requirement, not permission. Prefer "MUST use agent for these files/logs/URLs" over "may use sub-agents if needed". If the orchestrator intentionally does not delegate, record the reason: small scope, enough context already loaded, tool unavailable, or overhead greater than benefit.
❌ When NOT to Use Sub-agents
→ [splitting-criteria.md#part-4-when-not-to-split](splitting-criteria.md#part-4-when-not-to-split) for detailed decision matrix and complexity scaling guidelines.
Quick reference: Avoid sub-agents for single file/< 5 min tasks, simple Q&A, or when follow-up conversation is needed.
---
How to Invoke
Enabling agent
Option 1: Tool Picker
- Open VS Code chat → Tool picker → Enable
agent
Option 2: Agent YAML (Recommended)
# VS Code Copilot
---
name: Orchestrator
tools: ["agent", "web/fetch", "readFile"]
---
# Claude Code
---
name: Orchestrator
tools: ["Task", "WebSearch", "Read"]
---Invocation Methods
Method 1: Direct Tool Reference (Most Reliable)
Use #tool:agent for each URL to fetch and summarize the content.Method 2: Natural Language
For each file, launch a sub-agent to analyze and return findings.Method 3: Explicit Tool Call (In Agent Definition)
## Workflow
1. Analyze requirements
2. For each identified file:
- Call #tool:agent with prompt:
"Read [filename], identify issues, suggest fixes"
3. Synthesize all sub-agent results---
Prompt Engineering for agent
Sub-agent Prompt Requirements
When calling agent, your prompt parameter must include:
| Element | Example |
|---|---|
| agentName | Researcher |
| Clear task | "Fetch and summarize the content of this URL" |
| Expected output | "Return a 100-word summary with key points" |
| Constraints | "Focus only on pricing information" |
| Return format | "Output as bullet points with source quotes" |
Zenn-compliant minimal template
# MyOrchestrator.agent.md
---
name: MyOrchestrator
tools: ['agent']
---
#tool:agent を使用して、Researcher エージェントを呼び出してください。
- prompt: ${調査したい内容}
- agentName: ResearcherGood Prompt Examples
# Research Sub-agent
Fetch https://example.com/docs and analyze:
1. Core features (max 3)
2. Pricing tiers
3. Limitations
Return as structured Markdown with:
- Feature list
- Price comparison table
- Recommendation# Code Review Sub-agent
Read the file at {filepath} and:
1. Identify potential bugs
2. Check for security issues
3. Suggest performance improvements
Return: JSON with {bugs: [], security: [], performance: []}Bad Prompt Examples
❌ Too vague: "Look at this and tell me what you think" ❌ Missing return format: "Analyze the logs" (what format?) ❌ Too broad: "Research everything about React" (unbounded)
---
Orchestrator-Workers Pattern with agent
Architecture
Main Agent (Orchestrator)
├── Decompose task into subtasks
├── For each subtask:
│ └── agent(subtask_prompt)
│ └── Returns: summary (1-2k tokens)
└── Synthesize all summariesExample: Multi-File Code Review
Orchestrator Agent Definition:
---
name: Code Review Orchestrator
description: Reviews code changes across multiple files using sub-agents
tools: ["agent", "read_file", "grep_search"]
---
# Code Review Orchestrator
## Workflow
1. **Identify changed files**
- Use grep_search or read_file to list modified files
2. **Dispatch review sub-agents** ⚠️ MUST USE agent
For each file, call #tool:agent with prompt:Review the file at [filepath]:
- Security issues (HIGH/MEDIUM/LOW)
- Logic bugs
- Style violations
Return as structured JSON: {security: [], bugs: [], style: []}
3. **Synthesize results**
- Aggregate all sub-agent outputs
- Prioritize by severity
- Generate final review report
## CRITICAL: Sub-agent Dispatch
You MUST use #tool:agent for file reviews.
Do NOT review files directly in main context.
Each sub-agent keeps file content isolated.---
Common Pitfalls
Pitfall 1: Orchestrator Does the Work Itself
❌ Problem: Orchestrator reads files directly instead of delegating
Symptoms:
- No #tool:agent calls in execution
- Main context fills up
- Agent says "I'll review each file" but doesn't spawn sub-agents
Solution: Use explicit, imperative instructions:
## MANDATORY: You MUST use #tool:agent
Do NOT read file contents directly.
Do NOT review code in main context.
For EACH file → agent with specific prompt.Pitfall 2: Parallel Execution Overhead
⚠️ Note: As of 2026/01, agent supports parallel execution, but with overhead.
Trade-off: Parallel sub-agents add VS Code processing overhead. In one test:
| Metric | Sequential | Parallel (8 sub-agents) |
|---|---|---|
| Total tokens | 33,000 | ~80,000 |
| Execution time | 5 sec | 33 sec |
| Main context | 33,000 | 10,000 |
Recommendation: Use parallel sub-agents when:
- Context isolation is the primary goal
- Tasks are truly independent
- Main session needs to stay clean for follow-up work
# For parallel execution, group related files into batches
# to reduce overhead while maintaining context isolationPitfall 3: Nested Sub-agent Calls (Not Supported)
❌ Problem: Sub-agent tries to call another sub-agent
Reality: Sub-agents cannot call agent themselves. Nesting is not supported.
Solution: Keep hierarchy flat:
✅ Correct:
Orchestrator → Worker A
→ Worker B
→ Worker C
❌ Wrong:
Orchestrator → Worker A → Sub-Worker (NOT ALLOWED)Pitfall 4: Vague Sub-agent Prompts
❌ Problem: "Analyze this file" → Sub-agent doesn't know what to return
Solution: Always specify output format:
Return as:
- Summary: (1 paragraph)
- Issues: (bullet list)
- Recommendation: (1 sentence)Pitfall 5: Sub-agent Handoff to Named Agents
❌ Problem: Trying to use subagentType=my-agent doesn't work
Reality: agent creates fresh agents, cannot handoff to existing agent definitions.
Solution: Define sub-agent behavior in the prompt parameter, not in separate files.
Pitfall 6: Custom Agent as Sub-agent (Experimental)
⚠️ Experimental Feature: As of 2026/01, you can invoke custom agents as sub-agents with additional configuration.
Enable in VS Code:
// settings.json
{
"chat.customAgentInSubagent.enabled": true
}Usage:
#tool:agent を使用して、以下の処理をサブエージェントで実行してください。
- prompt: {サブエージェントへの入力}
- agentName: my-custom-agentLimitations:
- Custom agent must NOT have
disable-model-invocation: true(default:false) - ℹ️
infer:は deprecated。user-invocable/disable-model-invocationを使用すること - Sub-agent cannot access main session context
- Parallel execution available (2026/01+) but with overhead
Pitfall 7: Restricting Orchestrator's tools Breaks Sub-agents
❌ Problem: Orchestrator の tools: から edit を外してSRPを強制 → サブエージェント(Writer等)が edit を使えなくなる
Reality: 親エージェントの tools: はサブエージェントのツール上限(ceiling)として機能する。親で許可されていないツールは、サブエージェントでも使用不可。
❌ Wrong: Orchestratorで edit を制限
---
name: Orchestrator
tools: ["agent", "read", "todo"] # edit がない
---
→ Writer サブエージェントが edit/editFiles を使えない!
✅ Correct: tools を省略(全ツール利用可)
---
name: Orchestrator
description: サブエージェントに作業を委譲
---
→ サブエージェントは全ツールを使えるSolution:
- Orchestrator は
tools:を省略する(= 全ツール利用可、agent-template.md推奨) - SRP の強制は
tools:ではなく、プロンプト内の MANDATORY 指示で行う tools:制限は Worker エージェント(末端)に対してのみ適用する
---
Inline Sub-agent Pattern (Recommended)
Instead of referencing external .agent.md files, embed the sub-agent's role definition directly in the prompt.
Why Inline?
| Approach | Pros | Cons |
|---|---|---|
External reference (agentName: developer) | Reusable, DRY | May not work reliably, dependency |
| Inline definition | Self-contained, reliable | Slightly longer prompts |
Example: Inline Developer Sub-agent
`markdown #tool:agent を使用してサブエージェントを起動してください。
prompt: 以下の内容を渡す
Developer Agent
Role
あなたは開発者です。バグ修正、コードの改善を行います。
Goals
- TypeScript のベストプラクティスに従う
- エラーなくコンパイルされることを確認
Done Criteria
npm run compileがエラーなしで完了
---
タスク
{具体的な修正内容} `
Benefits
1. Reliability: No dependency on external files 2. Portability: Single file works anywhere 3. Clarity: Sub-agent behavior is explicit in the orchestrator
Token Efficiency
Comparison
| Approach | Main Context | Total Tokens | Time |
|---|---|---|---|
| Direct (no sub-agents) | 33,000 | 33,000 | 5 sec |
| With sub-agents (8 URLs) | 9,000 | 40,000 | 71 sec |
Trade-off
- Speed: Direct is faster (no sub-agent overhead)
- Context quality: Sub-agents keep main context clean
- Long sessions: Sub-agents prevent context rot
Recommendation
| Session Length | Recommendation |
|---|---|
| < 30 min | Direct (no sub-agents) |
| 30 min - 2 hours | Selective sub-agents |
| > 2 hours | Mandatory sub-agents |
---
Handoffs vs agent
| Feature | Handoffs | agent |
|---|---|---|
| Context | Shared (via prompt) | Isolated (clean window) |
| User Control | Manual approval | Automatic execution |
| Use Case | Phase transitions | Context isolation |
| Workflow | Plan → Implement → Review | Research, log analysis |
Recommendation:
- Use Handoffs for human-in-the-loop phase transitions
- Use agent (旧 runSubagent) for context-heavy isolated tasks
---
Checklist
## agent Implementation Checklist
### Agent Definition
- [ ] tools includes "agent"
- [ ] Explicit instructions to USE sub-agents (not just "can use")
- [ ] Sub-agent prompt template defined
### Prompt Engineering
- [ ] Clear task description in sub-agent prompt
- [ ] Expected output format specified
- [ ] Constraints/scope defined
- [ ] Return structure (JSON/Markdown/etc.) specified
### Anti-patterns Avoided
- [ ] No "process in parallel" expectations
- [ ] No vague "analyze this" prompts
- [ ] No reliance on handoff to named agents
- [ ] Orchestrator doesn't do sub-agent work itself
### Testing
- [ ] Verified sub-agents are actually called (not skipped)
- [ ] Checked return summaries are appropriately sized
- [ ] Confirmed main context stays clean---
References
- Chat in IDE - GitHub Docs
- Custom Agents in VS Code
- GitHub Copilot agent (旧 runSubagent) - Zenn
- Context Engineering for Agents - LangChain Blog- Handoffs Guide - Alternative for human-in-the-loop workflows
- Splitting Criteria - When to use sub-agents
---
⚠️ tools 形式の注意点(2026/02 Updated)
VS Code Copilot のカスタムエージェントで正しくサブエージェントを呼び出すには、以下の形式を守る必要があります。
正しいツールエイリアス
| エイリアス | 説明 | 間違い例 |
|---|---|---|
| agent | サブエージェント呼び出し | runSubagent |
| read | ファイル読み取り | read/readFile |
| edit | ファイル編集 | edit/editFiles |
| search | 検索 | search/textSearch |
| execute | コマンド実行 | execute/runInTerminal |
| todo | タスク管理 | todos |
参考: GitHub Docs - Custom agents configuration
JSON配列形式を推奨
YAML配列形式は動作しない場合があります。JSON配列形式を使用してください。
正しい形式: tools: ["agent", "read", "edit", "search", "execute", "todo"]
間違い形式: tools:
- agent
- read
シンプルなプロンプト構造
複雑な450行のプロンプトより、シンプルな70行のプロンプトの方が効果的です。
Agent & Prompt Template
Standard structure and specification for .agent.md and .prompt.md files.
Note: Both file types use similar YAML front matter. The mode: field is deprecated for both.File Format Rules
⚠️ フェンスラッパーに関する重要な注意
.prompt.md と .instructions.md ファイルは 素の YAML フロントマター (`---`) で始めること。 コードフェンス( ``prompt 等)で囲む必要はない。フェンスで囲むと VS Code がフロントマターを認識できず、プロンプトピッカーに description が表示されなくなる。
| ファイル種別 | 正しい形式 | 不正な形式 |
|---|---|---|
.prompt.md | --- で始まる YAML フロントマター | ``prompt で囲む |
.instructions.md | # 見出しで始まる(フロントマター不要) | フェンスで囲む |
.agent.md | --- で始まる YAML フロントマター | ``chatagent で囲む |
`````yaml
✅ .prompt.md — 正しい
--- description: セッション内容をXポスト用に変換 ---
プロンプト本文...
❌ .prompt.md — 間違い(description が表示されない)
````prompt --- description: セッション内容をXポスト用に変換 ---
プロンプト本文...
`````
✅ .agent.md — 正しい(フェンス不要、素の --- だけ)
---
name: my-agent
description: Does something useful
---
# エージェント本文...````
YAML Front Matter
For .agent.md files
---
name: <agent-name> # Required: Identifier for @mention
description: <description> # Required: One-line role description
model: <model-name> # Optional: LLM model to use
tools: [...] # Optional: Tool whitelist
agents: [...] # Optional: Restrict which subagents may be invoked
handoffs: [...] # Optional: Agent transitions (must be objects with label/agent/prompt/send)
user-invocable: true # Optional: Show in agents dropdown (default: true)
disable-model-invocation: false # Optional: Prevent subagent invocation (default: false)
---Model note:model:is optional. Do not guess model names. If you have not verified the exact display name in the current environment, omitmodel:instead of using speculative values likegpt-4o.
When fallback matters, model: can be an ordered array and the first available model is used. Use only model display names verified in the current environment.
model: ["<verified-model-name-1>", "<verified-model-name-2>"]handoffs は文字列配列ではなく、label・agent・prompt・send を持つオブジェクト配列で定義する。
agents は親 agent が呼び出せる subagent 名の制限。省略すると全許可、[] なら subagent 呼び出し禁止。
⚠️ 非標準フィールド禁止(バリデーションエラーの原因)
author, repository, license, copyright 等のメタデータを YAML frontmatter に書くと バリデーションエラー になる。 これらは YAML の外、--- 終端の直後に HTMLコメント として記述すること。
# ✅ 正しい — メタデータはHTMLコメント
---
name: my-agent
description: Does something useful
---
<!-- author: aktsmm
repository: https://github.com/aktsmm/ghc_template
license: CC BY-NC-SA 4.0
copyright: Copyright (c) 2025 aktsmm -->
# エージェント本文...# ❌ 間違い — YAMLに非標準フィールドを追加
---
author: aktsmm ← バリデーションエラー
repository: https://...
name: my-agent
---For .prompt.md files
---
description: <description> # Required: Brief description of the prompt
# agent: <agent-name> # Optional: Bind to a specific agent
---Do not add tools: to .prompt.md by default. Prompt-level tools: is an allowlist that overrides the selected or referenced agent's tools for that prompt run. Use it only when losing unrelated built-in, extension, web, or MCP tools is intentional.
⚠️ Deprecated Fields
| Field | Status | Applies To | Use Instead |
|---|---|---|---|
mode: | ❌ Deprecated | .agent.md, .prompt.md | Use agent: field (see below) |
infer: | ❌ Deprecated | .agent.md | Use user-invocable: and disable-model-invocation: (see below) |
`infer:` Migration Guide:
infer: true (default) はプルダウン表示とサブエージェント呼び出しの両方を制御していたが、新しいフィールドでは独立制御が可能。
# ❌ Wrong (deprecated)
---
infer: false
---
# ✅ Correct: プルダウンに非表示(サブエージェントとしては呼び出し可能)
---
user-invocable: false
---
# ✅ Correct: サブエージェント呼び出しを禁止(プルダウンには表示)
---
disable-model-invocation: true
---
# ✅ Correct: 両方禁止
---
user-invocable: false
disable-model-invocation: true
---| フィールド | デフォルト | 説明 |
|---|---|---|
user-invocable | true | プルダウンに表示するか |
disable-model-invocation | false | サブエージェントとしての呼び出しを禁止するか |
⚠️ typo注意:user-invokableは誤記で無効。ピッカー非表示には必ずuser-invocable: falseを使うこと。
⚠️ サブディレクトリの罠(2026年2月時点): .github/agents/ は直下のファイルだけをスキャン。サブフォルダに入れると runSubagent でも呼び出せなくなる。フラットに置くこと。非表示にしたい場合はサブフォルダではなく user-invocable: false を使うこと。Manifest Validation Checklist
複数の .agent.md をまとめて編集したら、最低限次を確認すること。
user-invokableなどの誤記が front matter に混入していないuser-invocable: falseの agent が意図どおり subagent 専用になっている- front matter 編集後も本文先頭の
## Roleなど必須セクションが崩れていない
`mode:` Migration Guide:
# ❌ Wrong (deprecated)
---
mode: agent
---
# ✅ Correct: Specify agent name
---
description: Daily report generator
agent: report-generator
---
# ✅ Correct: Boolean value
---
description: Daily report generator
agent: true
---
# ✅ Correct: Omit (default behavior)
---
description: Daily report generator
---`agent:` Field Options:
| Value | Behavior |
|---|---|
agent: <name> | Use specific agent (e.g., report-generator) |
agent: true | Enable agent mode |
| _(omit field)_ | Default behavior |
Complete .prompt.md Example
---
description: デイリーレポート自動生成(業務ログから1日分のレポートを作成)
agent: report-generator
---Tools Pattern Reference:
| Pattern | Description | Example |
|---|---|---|
category/tool | Specific tool | read/readFile |
category/* | All tools in category | workiq/* |
| MCP tools | External MCP server tools | workiq/*, github/* |
Common Tool Categories:
| Category | Tools |
|---|---|
read | readFile |
edit | editFiles |
search | fileSearch, textSearch |
workiq | M365 integration (email, calendar, files) |
---
✅ Correct
---
name: my-agent description: Does something useful
---
`````
Tools Field Behavior
| Specification | Behavior |
|---|---|
| Omitted | All tools available (recommended for most) |
tools: [] | No tools available |
| Tool names | Only listed tools available (whitelist) |
Note: MCP server tools become available at runtime automatically. Unknown tool names cause errors.
Recommended tools: style for .agent.md
For custom agents, prefer the stable aliases below unless you specifically need a narrower tool path.
tools: [read, search]
tools: [read, search, edit]
tools: [agent, read, search]Use these aliases first:
| Purpose | Preferred alias |
|---|---|
| Read | read |
| Search | search |
| Edit | edit |
| Shell | execute |
| Web | web |
| Subagent | agent |
| Todo | todo |
Avoid raw runtime tool IDs in .agent.md frontmatter. Names such as read_file, grep_search, and semantic_search are chat/runtime tool identifiers, not portable custom-agent tool names, and they trigger validation errors.
Body から特定ツールを明示したい場合は #tool:<name> 参照を使う。
Use #tool:agent for each independent file review.
Use #tool:web when external documentation is required.⚠️ Orchestrator の tools 制限に注意: 親エージェントのtools:はサブエージェントの ツール上限(ceiling) として機能する。Orchestrator のtools:からeditを外すと、サブエージェント(Writer 等)もeditを使えなくなる。Orchestrator はtools:を省略する(= 全ツール利用可)のが推奨。SRP の強制はtools:ではなくプロンプト内の MANDATORY 指示で行うこと。詳細は agent-guide.md の Pitfall 7 を参照。
⚠️ tools フィールドの注意事項
ツール名は `category/toolName` 形式で指定すること。 カテゴリが間違っていると VS Code がエラーを出す。
| ツール | ✅ 正しい指定 | ❌ 間違い | 備考 |
|---|---|---|---|
| シェル実行 | execute/runInTerminal | run/runInTerminal | カテゴリは execute |
| ファイル読み | read/readFile | readFile | カテゴリ必須 |
| ファイル編集 | edit/editFiles | editFiles | カテゴリ必須 |
| テキスト検索 | search/textSearch | textSearch | カテゴリ必須 |
| ファイル検索 | search/fileSearch | fileSearch | カテゴリ必須 |
| Web フェッチ | web/fetch | fetch | カテゴリ必須 |
| サブエージェント | agent | runSubagent | カテゴリなし |
| タスク管理 | todo | todos | カテゴリなし |
`tools:` に登録できないもの(チャット変数としてのみ利用可):
problems/changes/usages/codebase/githubRepo→#problems等でチャット内参照は可能だが、tools:ホワイトリストには登録不可
Agent Body Structure
Built-in Aligned Minimal Template
If you do not need the full structured template, start from this smaller built-in aligned shape and expand only when required.
---
description: "Use when... trigger phrases for subagent discovery"
tools: [read, search]
user-invocable: false
---
You are a specialist at {specific task}. Your job is to {clear purpose}.
## Constraints
- DO NOT {thing this agent should never do}
- DO NOT {another restriction}
- ONLY {the core responsibility}
## Approach
1. {Step one}
2. {Step two}
3. {Step three}
## Output Format
{Exactly what this agent should return}Use the minimal template when:
- the agent is single-purpose
- tool boundaries matter more than rich documentation
- the return format is more important than a long workflow narrative
Use the full template below when you need explicit I/O contracts, progress reporting, or error handling tables.
Each agent should include these sections:
| Section | Required | Description |
|---|---|---|
| Role | ✅ | Single sentence defining responsibility |
| Goals | ✅ | List of objectives to achieve |
| Done Criteria | ✅ | Verifiable completion conditions (one place only) |
| Permissions | ✅ | What's allowed and forbidden |
| I/O Contract | ✅ | Input/output definitions |
| Non-Goals | Recommended | What this agent explicitly does NOT do |
| Workflow | Recommended | Step-by-step procedure |
| Progress Reporting | Recommended | How to report progress (e.g., manage_todo_list) |
| Error Handling | Recommended | Error patterns and responses |
| Idempotency | Recommended | How to guarantee safe retries |
⚠️ Critical: Done Criteria Placement
Define Done Criteria in exactly ONE place. Multiple definitions cause confusion.
Full Template
````markdown --- name: example-agent description: Brief description of what this agent does
VS Code Copilot tools (adjust for Claude Code: Read, Edit, Search)
tools: ["readFile", "editFiles", "textSearch"] ---
Example Agent
Role
[Single sentence defining this agent's responsibility]
Goals
- Goal 1: [Specific, measurable objective]
- Goal 2: [Another objective]
- Goal 3: [...]
Done Criteria
Task is complete when ALL of the following are true:
- [ ] Criterion 1 (verifiable condition)
- [ ] Criterion 2 (verifiable condition)
- [ ] Criterion 3 (verifiable condition)
Permissions
Allowed
- Action 1
- Action 2
Forbidden
- ❌ Action that should never be done
- ❌ Another prohibited action
Non-Goals
Explicitly define what this agent does NOT do:
- ❌ Do not write code directly (delegate to implementation agent)
- ❌ Do not review own output (delegate to review agent)
- ❌ Do not assume user intent (ask for clarification)
Why Non-Goals? Prevents orchestrators from doing work they should delegate.
I/O Contract
Input
| Field | Type | Required | Description |
|---|---|---|---|
| input_field | string | Yes | Description of input |
Output
| Field | Type | Description |
|---|---|---|
| output_field | string | Description of output |
Workflow
1. Step 1: [Action description]
- Details or sub-steps
2. Step 2: [Action description] 3. Step 3: [Action description]
Error Handling
| Error Pattern | Response |
|---|---|
| File not found | Report error, suggest alternatives |
| Invalid input format | Validate early, return clear error |
| External API failure | Retry with backoff, then escalate |
Progress Reporting
For long-running tasks, maintain visibility:
- Use
manage_todo_listtool to track task status - Update status at each sub-task completion
- Provide intermediate reports for tasks > 5 minutes
**Progress:**
- [x] Task 1: Analyze requirements
- [x] Task 2: Generate IR
- [ ] Task 3: Validate output
## Idempotency
- Check current state before making changes
- Use unique identifiers to prevent duplicates
- Design operations to be safely retried
Examples by Role
→ See design-principles.md for detailed design principles.
Orchestrator Agent
VS Code Copilot:
---
name: orchestrator
description: Coordinates workflow and delegates to specialist agents
tools: ["runSubagent", "readFile", "textSearch", "todos"]
---Claude Code:
---
name: orchestrator
description: Coordinates workflow and delegates to specialist agents
tools: ["Task", "Read", "Search", "TodoWrite"]
---Key characteristics:
- Uses subagent tool for delegation (
#tool:agent/Task) - Maintains high-level view
- Does NOT perform detailed work itself
Available Tools
Built-in tools for custom agents. Tool names differ by platform:
VS Code Copilot Tools (Official)
| Tool Name | Description | Tool Set |
|---|---|---|
#runInTerminal | Run shell command in integrated terminal | #runCommands |
#readFile | Read file contents | - |
#editFiles | Edit/create files | #edit |
#createFile | Create new file | #edit |
#textSearch | Search text in files | #search |
#fileSearch | Search files by glob pattern | #search |
#runSubagent | Spawn sub-agent with isolated context | - |
#web/fetch | Fetch web page content | #web |
#todos | Task list management | - |
#codebase | Search codebase for context | - |
#changes | List source control changes | - |
#problems | Get workspace issues | - |
#usages | Find references/implementations | - |
#githubRepo | Search GitHub repository | - |
Claude Code Tools (Anthropic)
| Tool Name | Description |
|---|---|
Bash | Shell command execution |
Read | Read file contents |
Write / Edit | Create/edit files |
Search / Grep | Search files/text |
Task | Spawn sub-agent |
TodoWrite | Task list management |
WebSearch | Web search (via MCP) |
Cross-Platform Mapping
| Purpose | VS Code Copilot | Claude Code |
|---|---|---|
| Shell execution | runInTerminal | Bash |
| Read file | readFile | Read |
| Edit file | editFiles | Write/Edit |
| Search | textSearch, fileSearch | Search, Grep |
| Subagent | runSubagent | Task |
| Web fetch | web/fetch | (MCP) |
| Todo list | todos | TodoWrite |
Tool Definition Examples
VS Code Copilot:
---
name: orchestrator
description: Coordinates workflow and delegates to specialist agents
tools: ["runSubagent", "readFile", "textSearch", "todos"]
---Claude Code:
---
name: orchestrator
description: Coordinates workflow and delegates to specialist agents
tools: ["Task", "Read", "Search", "TodoWrite"]
---Tool Reference Syntax
- VS Code Copilot: Use
#tool:<tool-name>in prompts (e.g.,#tool:runSubagent) - Claude Code: Reference tools directly by name
MCP Server Tools
Use <server-name>/* format to include all tools from an MCP server.
Troubleshooting: If tools are not recognized:
- VS Code: Check VS Code Chat Tools Reference
- Claude Code: Check Custom Agents Configuration - GitHub Docs
Handoffs (Agent Transitions)
Handoffs enable guided sequential workflows between agents with suggested next steps.
When to Use
- Plan → Implementation: Generate plan, then hand off to implementation agent
- Implementation → Review: Complete coding, then switch to code review agent
- Write Failing Tests → Pass Tests: Generate failing tests first, then implement code
Configuration
---
name: Planner
description: Generate an implementation plan
# VS Code Copilot tools
tools: ["textSearch", "web/fetch", "readFile"]
handoffs:
- label: Start Implementation
agent: implementation
prompt: Implement the plan outlined above.
send: false
---| Property | Description |
|---|---|
label | Button text shown to user |
agent | Target agent identifier |
prompt | Pre-filled prompt for next agent |
send | Auto-submit prompt (default: false) |
Benefits
- Human control: User reviews each phase before proceeding
- Context preservation: Relevant context passed via prompt
- Workflow orchestration: Multi-step tasks with clear boundaries
References
Built-in Customization Patterns
Patterns extracted from VS Code Copilot's built-in customization skills.
Use these as design heuristics for agent workflows and customization creation. Do not copy the built-in commands verbatim.
1. Extract Before You Interview
Built-in create-agent, create-prompt, create-instructions, create-skill, and create-hook all start by reviewing the conversation and generalizing what the user has already been doing.
Use this pattern when:
- The user has already demonstrated a repeated workflow
- Tool preferences or role boundaries are visible from context
- You want to minimize clarification churn
Apply it as:
1. Extract repeated task shape 2. Extract constraints and tool preferences 3. Extract desired output style 4. Ask only for what is still missing
Anti-pattern:
- Starting with a large requirements interview when the conversation already contains the specialization
2. Clarify the Weakest Ambiguity Only
The built-in create flows do not ask every possible setup question. They draft first, then focus on the most ambiguous or behavior-changing part.
Good clarification targets:
- scope: workspace or user profile
- role boundary: when to use this over the default agent
- enforcement: should it guide, warn, ask, or block
- output contract: expected structure or return format
Avoid:
- asking for details that do not change the file design
- collecting exhaustive requirements before a first draft
3. Guidance and Enforcement Are Different Primitives
The built-in agent-customization skill draws a hard line:
- prompts, instructions, skills, and agents are guidance
- hooks are deterministic enforcement at lifecycle events
Use this distinction when designing workflow systems:
| Situation | Best fit |
|---|---|
| Encourage a workflow or style | Prompt / Instruction / Skill |
| Restrict tools or specialize a role | Agent |
| Guarantee a check runs before or after an event | Hook |
If a requirement includes words like "always block", "must ask", "inject at session start", or "run automatically before tool use", evaluate Hook explicitly.
4. Discovery Surface Matters
Built-in customization docs consistently treat descriptions as the routing surface.
Implications:
- descriptions need trigger phrases, not generic summaries
- vague labels reduce agent discovery and slash-command usability
- agent, skill, and instruction discovery all benefit from a strong "Use when..." shape
Use this when reviewing workflow assets:
- can another agent discover this from its description alone?
- would a user understand when to invoke it from the picker?
5. Draft, Then Iterate
The built-in creation flow is not "requirements -> perfect file". It is:
1. extract 2. clarify 3. draft file 4. identify weak spots 5. refine 6. suggest related next customizations
This is a strong pattern for agent workflow design too, especially when creating an orchestrator plus adjacent prompts, instructions, or hooks.
6. Bootstrap and Debug Are First-Class Workflows
Two built-in skills are especially worth borrowing conceptually:
init
What to absorb:
- explore the codebase before writing customization assets
- prefer linking to existing docs instead of copying them
- create or update only customization files, not product code
When useful:
- initializing workflow assets for a repo
- upgrading AGENTS.md and related instructions without touching app code
troubleshoot
What to absorb:
- base conclusions on evidence
- do not guess about why a workflow did or did not trigger
- separate root cause, evidence, and remediation
When useful:
- debugging why an agent was not invoked
- debugging why a prompt, skill, or instruction did not load
- explaining unexpected workflow choices
7. Minimal Reusable Loop
When designing or reviewing agent customizations, this is the compact loop worth keeping:
1. Extract from conversation 2. Choose primitive and scope 3. Clarify only the missing ambiguity 4. Draft the file or workflow 5. Review the weakest part 6. Refine and suggest adjacent assets
If the process starts turning into a large wizard, you are probably over-designing the customization.
Context Engineering
Strategies for curating and managing context in long-running AI agents.
"Context engineering is the art and science of curating what will go into the limited context window."
— Anthropic
Overview
| Concept | Description | Use Case |
|---|---|---|
| Prompt Engineering | Writing effective prompts (system prompts) | One-shot tasks |
| Context Engineering | Managing entire context state across multiple turns | Long-running agents |
| Compaction | Summarizing and compressing context to continue | Context window limits |
| Structured Note-taking | Persisting notes outside the context window | Multi-hour tasks, progress tracking |
| Sub-agent Architectures | Specialized sub-agents with clean context windows | Complex research, parallel tasks |
---
Why Context Engineering Matters
Context Rot
As tokens increase, recall accuracy decreases. This is called context rot.
Token Count vs. Recall Accuracy
Low tokens ████████████████ High accuracy
Medium ██████████░░░░░░ Moderate
High tokens ████░░░░░░░░░░░░ Low accuracy (context rot)Key Insight
"Context must be treated as a finite resource with diminishing marginal returns."
Principle: Find the smallest set of high-signal tokens that maximize the likelihood of desired outcomes.
---
Techniques
1. Compaction
Summarize context when approaching limits, reinitialize with summary.
When to Use
- Context window is 70-80% full
- Long conversation with accumulated tool outputs
- Need to continue with fresh focus
Implementation
Original Context (90% full):
- System prompt
- 50 conversation turns
- 100 tool call results
- Accumulated state
↓ Compaction
Compacted Context (30% full):
- System prompt (preserved)
- Summary of key decisions
- Unresolved issues
- 5 most recent files/resourcesWhat to Keep vs. Discard
| Keep (High Signal) | Discard (Low Signal) |
|---|---|
| Architectural decisions | Verbose tool outputs |
| Unresolved bugs/issues | Completed successful tasks |
| Critical implementation details | Redundant conversation turns |
| Current goals and constraints | Exploratory dead-ends |
Anthropic's Tip
"Start by maximizing recall to ensure your compaction prompt captures every relevant piece of information, then iterate to improve precision by eliminating superfluous content."
---
2. Structured Note-taking (Agentic Memory)
Persist notes outside the context window for later retrieval.
When to Use
- Multi-hour tasks with clear milestones
- Progress tracking across context resets
- Learning and improvement over time
Implementation Patterns
Pattern A: File-based Memory
└── NOTES.md or TODO.md persisted to disk
Pattern B: Structured JSON
└── state.json with typed fields
Pattern C: Key-Value Store
└── Database or MCP memory toolExample: NOTES.md
# Agent Notes
## Current Objective
Training Pikachu to level 25 in Route 1
## Progress
- Steps completed: 1,234
- Pikachu level: 18 → 23 (+5)
- Remaining: 2 levels
## Learned Strategies
- Thunder Shock effective vs. Pidgey
- Avoid Rattata (wastes HP)
## Next Actions
1. Continue grinding until level 25
2. Move to Route 2Benefits
- Survives context resets
- Agent can read own notes and continue
- Enables long-horizon coherence
---
3. Sub-agent Architectures
Delegate to specialized sub-agents with clean context windows.
When to Use
- Complex research requiring deep exploration
- Parallel exploration of multiple paths
- Need to isolate detailed work from main context
Architecture
graph TD
A[Main Agent] --> B[Sub-agent 1: Search]
A --> C[Sub-agent 2: Analysis]
A --> D[Sub-agent 3: Code Review]
B --> |Summary 1-2k tokens| E[Synthesis]
C --> |Summary 1-2k tokens| E
D --> |Summary 1-2k tokens| E
E --> AKey Pattern
| Sub-agent Work | Return to Main Agent |
|---|---|
| 50,000+ tokens explored | 1,000-2,000 token summary |
| Deep file reading | Key findings only |
| Multiple tool calls | Synthesized conclusions |
Benefits
- Clean separation of concerns
- Detailed search context stays isolated
- Main agent focuses on synthesis
---
Just-in-Time Context Retrieval
Load context dynamically at runtime instead of pre-loading everything.
Pattern
Traditional (Pre-load):
1. Load all relevant files into context
2. Process
3. Respond
→ Wastes context on unused information
Just-in-Time:
1. Keep lightweight references (file paths, queries, links)
2. Load specific data when needed
3. Discard after use
→ Efficient, focused contextImplementation
# Instead of loading entire codebase:
context = read_all_files("src/") # ❌ Wasteful
# Use just-in-time retrieval:
relevant_files = grep_search("function_name") # ✅ Targeted
context = read_file(relevant_files[0]) # ✅ On-demandProgressive Disclosure
"Agents can assemble understanding layer by layer, maintaining only what's necessary in working memory."
---
Hybrid Strategy
Combine pre-retrieval and just-in-time for optimal performance.
Example: Claude Code Approach
| Pre-loaded (Upfront) | Just-in-Time (On-demand) |
|---|---|
| CLAUDE.md / copilot-instructions | File contents via glob/grep |
| Project structure overview | Specific function definitions |
| Key configuration | Test results, logs |
Decision Matrix
| Task Characteristic | Strategy |
|---|---|
| Static reference docs | Pre-load |
| Dynamic file contents | Just-in-time |
| Frequently accessed | Pre-load |
| Rarely accessed | Just-in-time |
| Large volume, low relevance | Just-in-time |
| Small volume, high relevance | Pre-load |
---
Split / Compact / Reference Loop
When workflow assets keep growing, do not default to adding another agent or another long instruction block.
Use this order instead:
1. Split Separate responsibilities, phases, or heavy examples that are polluting the main context. 2. Compact Rewrite repeated guidance into a smaller rule or decision point. 3. Referenceize Move deep recipes, long tables, and infrequent detail into files loaded on demand.
Practical Rule of Thumb
| Symptom | First Move |
|---|---|
| Main file keeps gaining new sections | Compact existing sections before adding |
| Same rule appears in multiple headings | Merge into one SSOT section |
| Long examples dominate the file | Move examples to references/ |
| Deep detail is only needed occasionally | Keep a summary in main context and link out |
| Context usage rises because of static guidance | Trim always-loaded files before adding orchestration |
Apply to Customization Files
For .instructions.md, .prompt.md, .agent.md, and SKILL.md:
- Keep the routing surface and decision points in the main file
- Move recipes, variants, and long examples into references
- Prefer a curated small external-links section over a giant link dump in the main file
- Treat append-only growth as a smell, not as normal maintenance
For always-loaded workspace entry files such as .github/copilot-instructions.md:
- Keep only repo-wide routing and a few global guardrails in the entry file
- Move domain workflows, review rules, upload procedures, and long failure playbooks into dedicated
.github/instructions/**/*.instructions.md - Do not turn the entry file into a Markdown-linked index of rules, skills, or docs. Even when the body stays short, linked references can still make the entry behave like a heavy context surface
- If the entry file starts mixing persona, routing, workflow details, and domain-specific prohibitions, treat that as context-hoarding rather than good documentation
- If removing or renaming the entry file suddenly makes casual chat behave normally again, that is a strong signal the entry file has become too heavy for its role
---
Long-Horizon Task Checklist
## Context Engineering Checklist
### Before Starting
- [ ] Is this a long-horizon task (>30 min continuous work)?
- [ ] Will context window likely fill up?
- [ ] Are there clear milestones to track?
### Technique Selection
- [ ] **Compaction**: Set up summarization trigger at 70% context
- [ ] **Note-taking**: Create NOTES.md or state file
- [ ] **Sub-agents**: Identify tasks suitable for delegation
### During Execution
- [ ] Monitor context usage
- [ ] Write notes at milestones
- [ ] Compact when needed
- [ ] Use just-in-time retrieval for large data
### After Completion
- [ ] Archive notes for future reference
- [ ] Document lessons learned---
4. Instruction File Optimization
Reduce token cost of definition files that are loaded into every session.
.instructions.md, .prompt.md, .agent.md are loaded in full on every conversation turn. Verbose files waste tokens before the task even starts.
What to Keep vs. Remove
| Keep (AI can't know this) | Remove (AI already knows) |
|---|---|
| User-specific facts: IDs, paths, env names | Command syntax (az login, git commit) |
| Policies & conventions unique to the team | Error-handling recipes |
| Workflow intent & delegation rules | Step-by-step tutorials |
| Identifiers (subscription IDs, tenant IDs) | Checklists of general best practices |
Loading Locations (VS Code Copilot)
| Scope | Path |
|---|---|
| Global | %APPDATA%/Code/User/prompts/*.instructions.md |
| Workspace | .github/copilot-instructions.md |
| Workspace | .github/instructions/**/*.instructions.md |
| Workspace | .github/prompts/*.prompt.md / *.agent.md |
| Workspace | .vscode/settings.json (github.copilot.chat.*) |
Duplicate content across global and workspace scopes doubles token cost.
Checklist
- [ ] Each file contains only user-specific / AI-unknowable information
- [ ] No duplicate content between global and workspace scopes
- [ ] All
.prompt.mdfiles have adescriptionfrontmatter - [ ] Stale IDs, paths, or settings removed
- [ ] No conflicting instructions across files
- [ ] Workspace entry files still read like a short routing layer, not like a full operating manual
Red Flags
| Smell | Why it hurts |
|---|---|
.github/copilot-instructions.md keeps absorbing workflow-specific sections | The file is loaded too often to be a safe place for deep procedure detail |
| The same rule appears in the entry file and again in domain instructions | Duplicate always-loaded guidance increases token cost and conflict risk |
| The entry file becomes a Markdown-linked catalog of instructions, agents, or docs | Even with a short body, the entry can still act like a large retrieval surface |
| Persona, routing, task policy, and domain-specific operations are all mixed together | The agent spends context budget resolving instruction priority before it can do the task |
| Casual chat improves only after disabling the workspace entry file | The entry file is likely over-scoped rather than merely verbose |
Diagnosis Order
When workspace behavior becomes unstable, do not jump straight to AGENTS.md mismatch.
Check in this order:
1. Is the always-loaded workspace entry file (.github/copilot-instructions.md) trying to do too many jobs at once? 2. Is the same rule duplicated across entry file, domain instructions, and prompt / agent assets? 3. Has the entry file become a Markdown-linked index that keeps pulling deeper material into the conversational surface? 4. Only after that, check whether AGENTS.md and agent definitions disagree about workflow entry points or role boundaries.
Reason:
AGENTS.mdinconsistency can matter, but over-scoped always-loaded instructions usually create broader symptoms first, especially when casual chat normalizes as soon as the entry file is removed or renamed.
---
Anti-Patterns
| Anti-Pattern | Problem | Solution |
|---|---|---|
| Context Hoarding | Loading everything "just in case" | Just-in-time retrieval |
| No Compaction | Running until context exhausted | Proactive summarization |
| Stateless Loops | Forgetting progress on reset | Structured note-taking |
| Monolithic Agent | One agent doing everything | Sub-agent delegation |
| Premature Retrieval | Loading data before knowing needs | Lazy loading |
| Verbose Instructions | Definition files bloated with general knowledge | Instruction file optimization |
---
References
Copilot Cloud Agent CI/CD Pitfalls
GitHub Actions で Copilot Cloud Agent の自動 PR パイプラインを組むときの落とし穴と対策。
Token Anti-Recursion
GitHub App トークン(Copilot Cloud Agent 含む)で作成・push した PR は、pull_request イベントで後続ワークフローをトリガーしない。GitHub の再帰防止ルール。
GITHUB_TOKENでも同様pull_request_targetは制限を受けない
対策
後続ワークフロー(validate、auto-merge 等)は pull_request_target をトリガーにする。
on:
pull_request_target:
types: [opened, synchronize, reopened, ready_for_review, edited]注意: pull_request_target はベースブランチのワークフローコードで実行される。fork からの PR でコード実行すると危険なため、同一リポジトリ制約を付ける。
jobs:
validate:
if: github.event.pull_request.head.repo.full_name == github.repositoryworkflow_run 連携時の PR 解決
pull_request_target を起点にした workflow を、別 workflow の workflow_run で受ける場合、context.payload.workflow_run.pull_requests が空になることがある。
pull_requests[0].numberを前提にしないworkflow_run.head_branchから open PR を逆引きする fallback を持つ
let pullRequests = context.payload.workflow_run.pull_requests || [];
if (pullRequests.length === 0 && context.payload.workflow_run.head_branch) {
const { data: prs } = await github.rest.pulls.list({
owner: context.repo.owner,
repo: context.repo.repo,
state: "open",
head: `${context.repo.owner}:${context.payload.workflow_run.head_branch}`,
per_page: 1,
});
pullRequests = prs;
}pull_request_target で PR head を実行する場合の注意
pull_request_target は base branch の workflow 定義で動くが、checkout を PR head SHA に向けると PR 側の script / package.json / build code を実行する。
- same-repo guard を必須にする
- 実行を許す script / 生成物の allowlist を絞る
- fork PR や不特定 contributor を対象に同じ設計を使わない
参照
Self-Healing Reconcile Pattern
自動生成 PR パイプラインでは、チェーンの途中が壊れると PR と issue が stuck する。
- in-band 回復: validate failure の直後に PR コメントで修正指示を返し、Copilot に再修正させる
- scheduled reconcile: それでも取りこぼした stuck PR / 孤立 issue を定期ジョブで掃除する
rerun failed workflow だけでは直らない。content / policy failure は、失敗理由に応じた修正指示を PR 上に返す設計が必要。
回復対象
| 状態 | 条件 | アクション |
|---|---|---|
| stuck PR | open, not draft, 条件合致, 2h+ 経過 | squash merge + issue close |
| コンフリクト PR | merge 失敗, 24h+ 経過 | PR close + issue close |
| 孤立 issue | 対応 PR なし, 48h+ 経過 | issue close |
| 重複 PR | 同一トピックに複数 PR | 古い方を close |
設計ポイント
- merge 前にファイル allowlist を検証する(auto-merge と同じ基準)
needs-human-reviewラベル付き PR はスキップする- merge 後の副作用(deploy、release、通知)は 1 workflow に責務を寄せる。
pull_request_target: closedなど別 workflow が拾うなら、merge job 側で同じ dispatch を重複実行しない - PR body を正規化し、
Generated from data/events/YYYY-MM-DD.jsonとCloses #XXを必ず入れる Closes #XXパターンを PR body から抽出して linked issue を閉じる- 閉じた PR/issue にはコメントで理由を残す
Generated Data Invariants
collector が自動修復を持っていても、壊れた生成物が main に入らない guard を別に置く。
collect後に generated data validator を実行する- generated PR validation でも同じ validator を実行する
- validator は source 実装ではなく生成済み artifact の不変条件を見る
例:
- 同じ stable article URL が複数の日次 JSON に出ない
- source marker や closing reference のような canonical metadata が欠落しない
- generated output に既知の不正状態(generic fallback、同一記事の日跨ぎ重複など)が残らない
重要なのは、collect can repair だけで終わらず、repair に失敗した run は CI を落とす まで入れること。
Generated Output Diff Targets
生成物 workflow では、git diff --quiet、git add、canonical drift check の対象を必ず一致させる。
- collector が書き換える generated artifact を一覧化する(例: data, summaries, drafts, translation/summary cache)
- no-change 判定、commit staging、PR auto-fix、final drift check の対象を同じ集合にする
- cache-only drift も publish される品質に影響するなら generated output として扱う
- この集合を workflow invariant validator で固定し、対象漏れを CI で落とす
- workflow / validator / runbook 変更時は、同じ invariant validator を GitHub Actions でも実行する
In-Band Self-Heal Rules
- validate failure 時は、失敗ステップ名だけでなく修正ルールを PR コメントに書く
- self-heal コメント後に Copilot reviewer を再要求し、再修正の起点を明示する
- 同じ原因の自動修正は最大 3 回まで。超えたら PR を close し、linked issue / PR の両方に
needs-human-reviewを付ける already gave up状態では重複コメントを増やさない- PR だけでなく linked issue にも escalation コメントを残し、
なぜ blocked なのかを issue 単体で読めるようにする
Metadata and Closing Discipline
- generated PR の title / body は opened / synchronize 時に正規化する
- linked issue を閉じたいなら、merge job 側の best effort close だけに頼らず、PR body に closing reference を注入する
- source marker と closing reference が missing のままだと、PR merge 後に issue が残留しやすい
Human-Review Block Discipline
needs-human-reviewが付いた linked issue は、authoring workflow 側で 自動 assignment と shepherd を止める- blocked issue を定期実行や手動再実行で勝手に再開しない
- issue のラベル再設定時に
needs-human-reviewを消さない - 再開条件は明示する。例:
ラベルを外すと再度自動化できます
Resume Semantics
- blocked issue を再開するとき、Copilot が assignee に残っていても
already assignedだけでは不十分 - 対応する open generated PR が無いなら、assignment を再実行して作業を再開する
- open PR が既にある場合だけ
already assigned / in progressと判定する
Duplicate PR Canonicalization
- 同一トピック(例: 同じ date key)で generated PR が複数 open になったら、最新 1 本を canonical にする
- stale duplicate PR は comment を残して自動 close する
- canonical PR の source marker / closing reference を SSOT にする
Failure-Specific Feedback
- build failure は
build を直してだけでは弱い。失敗している policy を具体化する - 例: pages build が published output 内の generic fallback copy を検出して落ちるなら、
generic な仮置き文言を対象更新に即した運用影響へ書き換えるまで指示する - self-heal コメントには validate run へのリンクを残し、人が読むときも追跡できるようにする
Customization Decision Guide
Choose the simplest customization primitive that can solve the problem.
Decision Matrix
| Need | Best Fit | Why | Avoid When |
|---|---|---|---|
| One focused slash task | Prompt | Fastest path, minimal ceremony | The task needs bundled scripts or reusable references |
| Always-on or file-scoped guidance | Instruction | Loads automatically or on demand | The behavior is really a workflow |
| Reusable workflow with bundled scripts, references, or templates | Skill | Best for repeatable task packages | The ask is only persona or tool restrictions |
| Persona, tool restrictions, delegation, or handoffs | Agent | Gives role boundaries and orchestration | The task can be solved without role isolation |
| Deterministic blocking, validation, or auto-execution | Hook | Enforces behavior at runtime | Guidance alone is enough |
Guidance vs Enforcement
This distinction is easy to blur when designing workflow customizations.
| Need | Use | Why |
|---|---|---|
| Tell the model what it should usually do | Prompt / Instruction / Skill / Agent | Guidance is flexible and conversational |
| Guarantee that something runs, blocks, or asks at a lifecycle event | Hook | Runtime enforcement must be deterministic |
Examples:
- "Always prefer this review style" -> instruction or skill
- "Ask before running this tool" -> hook
- "Use a specialist with limited tools" -> agent
- "Package a repeatable workflow with resources" -> skill
Escalation Ladder
Use complexity only when required.
1. Prompt 2. Prompt + instructions 3. Skill or single agent 4. Multi-agent workflow 5. Hooks for deterministic enforcement
Questions to Ask First
1. Is this a one-off task or a reusable workflow? 2. Does it need bundled assets, scripts, or references? 3. Does it need a specialist persona or tool restrictions? 4. Must the behavior be enforced deterministically? 5. Should this live in the workspace or the user profile?
Scope Guidance
| Scope | Use When |
|---|---|
| Workspace | Shared with the team or tied to a repo |
| User profile | Personal preference across repos |
Overdesign Smells
- Multi-agent proposed before confirming a single agent is insufficient
- Agent created only to hold long instructions
- Skill created even though there are no bundled assets or reusable resources
- Hook proposed for guidance that could stay as instructions
- Workspace asset proposed for a purely personal preference
- Questions asked before extracting obvious specialization from the conversation
- Hook proposed before confirming a lifecycle event or deterministic need
- Prompt file lists tools only to make them available; in VS Code
tools:is an allowlist and should be omitted unless narrowing is intentional
Prompt Tool Boundary Rule
In .prompt.md, tools: is an allowlist, not a hint. Omit it unless the slash prompt must intentionally narrow the selected agent's tools.
If tool boundaries are stable and role-like, prefer a custom agent over prompt-level tools:.
Creation Loop
Built-in customization flows follow a lightweight loop that is worth reusing:
1. Extract the reusable pattern from the conversation 2. Clarify only the missing ambiguity 3. Draft the customization file directly 4. Identify the weakest or most ambiguous part 5. Iterate and then suggest the next adjacent customization
Use this loop for prompt / instruction / skill / agent / hook creation unless the task is already fully specified.
Output Pattern
When designing a workflow, include this decision explicitly.
## Primitive Decision
- Best fit: agent
- Why not prompt: needs delegation and tool boundaries
- Why not skill: persona and orchestration are the core requirement
- Scope: workspaceDeep Agent Patterns
Patterns for building research-oriented agents with recursive information gathering and quality evaluation.
Overview
Deep Agents are specialized for comprehensive information gathering with citation-backed outputs. Key characteristics:
- Exhaustive Coverage: Multi-perspective investigation
- Recursive Collection: Follow links to original sources (max 3 levels)
- Quality Gates: Evaluator sub-agent validates output
- Citation Required: Every non-trivial fact needs a reference
Core Structure
---
name: DeepResearch
description: "Comprehensive topic research with citations"
tools: ["search", "web/fetch", "agent", "edit/editFiles", "todo"]
---Four Phases
| Phase | Purpose | Key Actions |
|---|---|---|
| 0. Clarification | Understand intent | Ask: purpose, focus areas, constraints |
| 1. Preparation | Plan investigation | List perspectives, check for duplicates |
| 2. Execution | Gather information | Sub-agents per perspective, recursive collection |
| 3. Evaluation | Quality check | Evaluator sub-agent, iterate if needed |
| 4. Completion | Finalize | Update status, report to user |
Scaling by Complexity
| Complexity | Example | Perspectives |
|---|---|---|
| Simple | Definition check | 1-2 |
| Medium | Feature investigation | 3-4 |
| Complex | Comparative analysis | 5+ |
Recursive Collection Strategy
Depth Levels
| Level | Target | Example |
|---|---|---|
| L0 | Entry point | Official blog, docs page |
| L1 | In-article links | Referenced specs, related docs |
| L2 | Spec links | Best practices, implementations |
Stop Conditions
- Same domain: max 3 levels
- Per entry point: max 10 sources
Source Priority
1. Official Docs (Microsoft Docs, GitHub Docs) 2. Official Blogs (Azure Blog, GitHub Blog) 3. Tech Blogs (Zenn, Qiita, dev.to) 4. Community (Stack Overflow, Reddit) 5. Social (Twitter/X) ← Last resort
Sub-agent Definitions
Research Sub-agent
**Purpose**: Search and document findings for a specific perspective.
**Input**:
- Topic: <research target>
- Perspective: <focus area>
- Output file: <report path> (use `-part-N.md` suffix for parallel execution)
**Search Strategy**:
1. Start broad: Short general queries for overview
2. Narrow down: Refine based on discoveries
3. Recursive collect: Follow in-article links
4. Cross-reference: Compare across vendors/specs
5. Alternative paths: Try official sites if paywalled
**Output**: NULL (writes directly to its own dedicated file)
**Parallel Safety**: Each sub-agent writes only to its assigned `-part-N.md` fileParallel Execution
Overview
Research sub-agents can be launched in parallel by placing multiple runSubagent (or #tool:agent) calls in the same tool-call block. This significantly reduces total execution time when perspectives are independent.
Note:run_in_terminalandsemantic_searchcannot be called in parallel.runSubagent,read_file,grep_search,file_searchcan.
File Collision Avoidance
Each sub-agent must write to a dedicated file to prevent write conflicts:
research/YYYY-MM-DD-<slug>-part-1.md ← Perspective A
research/YYYY-MM-DD-<slug>-part-2.md ← Perspective B
research/YYYY-MM-DD-<slug>-part-3.md ← Perspective CAfter all sub-agents complete, the orchestrator merges the parts:
1. Deduplicate overlapping content 2. Renumber citation footnotes 3. Add cross-perspective connections 4. Output final research/YYYY-MM-DD-<slug>.md 5. Delete -part-N.md files
When to Parallelize vs Serialize
| Condition | Strategy |
|---|---|
| Perspectives are independent | Parallel |
| Later perspective depends on earlier | Sequential |
| Shared external API with rate limits | Sequential or staggered |
| Perspectives build on each other | Sequential |
Cautions
- API Rate Limits: Parallel sub-agents hitting the same API (e.g., Brave Search
1 req/s) may trigger 429 errors. Each sub-agent should handle retries independently. - Context Isolation: Parallel sub-agents cannot see each other's results. Cross-referencing happens only in the merge step.
Evaluator Sub-agent
**Purpose**: Analyze report quality and identify gaps.
**Input**:
- Path: <report file>
- Topic: <original topic>
**Detection Criteria** (by priority):
1. **Missing information** (high): Gaps in coverage
2. **Missing citations** (high): Facts without references
3. **Unsubstantiated claims** (high): Opinions as facts
4. **Insufficient explanation** (medium): Key concepts unclear
5. **Stale information** (low): Outdated data
**Output**: JSON list of issues foundStop Conditions
Coverage (early exit OK)
- Each sub-question has 2+ independent sources
- New searches yield no new information
- Contradictions resolved or documented
Budget Limits (hard stop)
| Limit | Value |
|---|---|
| Time | 30 min |
| Sources | 20 |
| Per entry point | 10 URLs |
| Recursion depth | 3 levels |
| Reflection cycles | 5 |
Error Handling
| Error | Action |
|---|---|
| Search error | Retry 3x, then try alternative query |
| Source inaccessible | Skip, find alternative |
| 3 consecutive failures | Report to user, ask to continue |
Output Format
Report Template
---
topic: <topic>
date: YYYY-MM-DD
status: draft|review|final
sources_count: <N>
reflection_count: <N>
---
# <Topic> Research Report
## TL;DR
<1-3 sentence summary>
## Findings
### <Section 1>
<content>[^1]
### <Section 2>
<content>[^2]
## References
[^1]: <URL> - <description>
[^2]: <URL> - <description>
## Limitations
- <points not verified>
- <areas needing more research>Manifest (History)
Track research sessions in research/manifest.md:
## Research History
| Date | Topic | File | Status | Sources |
| ---------- | ------- | ------ | ----------- | ------- |
| YYYY-MM-DD | <topic> | <file> | draft/final | N |
## Latest Session
### YYYY-MM-DD: <topic>
- **Perspectives**: <list>
- **Reflections**: N/5
- **Stop reason**: Coverage / Budget / User
- **Unresolved**: <remaining issues>Permissions Pattern
### Allowed
- Web page fetch and analysis
- Documentation search
- File creation in `research/`
- Sub-agent invocation
### Forbidden
- ❌ Don't present inference as fact
- ❌ Don't cite unusual facts without reference
- ❌ Don't edit files outside `research/`Anti-patterns
| ❌ Don't | ✅ Do Instead |
|---|---|
| Mix opinions with facts | Clearly separate or exclude opinions |
| Skip citations | Add footnote for every claim |
| Single-source findings | Require 2+ independent sources |
| Unlimited recursion | Set hard depth/count limits |
| No quality check | Always run evaluator sub-agent |
Key Principles
1. Facts Only: No inference, no opinions, no recommendations 2. Citation Everything: Every non-trivial fact needs a source 3. Recursive but Bounded: Follow links, but with hard limits 4. Quality Gates: Evaluator sub-agent before finalization 5. Transparent Limitations: Document what wasn't verified
External References
- Anthropic: Multi-Agent Research System - 8 principles for multi-agent design
- LangChain: Deep Agents - 4 elements of Deep Agents
- PromptLayer: How Deep Research Works - 5-phase process, stop conditions
- openjny: なんちゃって Deep Research - VS Code Copilot implementation
- OpenAI: Introducing Deep Research - Official specification
External Resources for AI Agents
AI エージェント開発に役立つ外部リソース集。
First-Hop References
まず最初に当たるリンク。設計判断や platform behavior を確認したいときはここから入る。
| リソース | 説明 | URL |
|---|---|---|
| GitHub Docs: Chat in IDE | Copilot Chat / IDE 内での基本動作 | https://docs.github.com/en/copilot/how-tos/chat-with-copilot/chat-in-ide |
| VS Code: Custom Agents | VS Code 側の custom agents 全体像 | https://code.visualstudio.com/docs/copilot/customization/custom-agents |
| GitHub Docs: Create Custom Agents | GitHub Copilot agents の作成手順 | https://docs.github.com/en/copilot/how-tos/use-copilot-agents/coding-agent/create-custom-agents |
| Anthropic: Building Effective Agents | workflow pattern と agent 設計の基本原則 | https://www.anthropic.com/engineering/building-effective-agents |
| Anthropic: Effective Context Engineering | context engineering / compaction / retrieval の考え方 | https://www.anthropic.com/engineering/effective-context-engineering-for-ai-agents |
| Anthropic: Writing Tools for Agents | agent 向け tool 設計 | https://www.anthropic.com/engineering/writing-tools-for-agents |
Deep References
深掘り用。設計原則の確認後に、具体的な prompt / skill / hook / orchestration の実装例を探すときに使う。
プロンプト・インストラクション
| リソース | 説明 | URL |
|---|---|---|
| Awesome Copilot | GitHub 公式コミュニティプロンプト | https://github.com/github/awesome-copilot |
| Awesome Claude Prompts | Claude 向けプロンプト集 (4.2k★) | https://github.com/langgptai/awesome-claude-prompts |
| Awesome Reviewers | 3000+ コードレビュープロンプト | https://github.com/baz-scm/awesome-reviewers |
Claude Code 関連
| リソース | 説明 | URL |
|---|---|---|
| Awesome Claude Code | スキル・フック・コマンド集 (22k★) | https://github.com/hesreallyhim/awesome-claude-code |
| Anthropic: Lessons from building Claude Code skills | skill の分類、配布、計測、progressive disclosure の運用知見 | https://claude.com/blog/lessons-from-building-claude-code-how-we-use-skills |
| Claude Code System Prompts | 公式システムプロンプト抽出 | https://github.com/Piebald-AI/claude-code-system-prompts |
| Claude Code Docs Mirror | Anthropic ドキュメントミラー | https://github.com/ericbuess/claude-code-docs |
VS Code カスタマイズ
| リソース | 説明 | URL |
|---|---|---|
| VS Code Custom Instructions | 公式ドキュメント | https://code.visualstudio.com/docs/copilot/customization/custom-instructions |
| VS Code Prompt Files | 公式ドキュメント | https://code.visualstudio.com/docs/copilot/customization/prompt-files |
| VS Code Custom Agents | 公式ドキュメント | https://code.visualstudio.com/docs/copilot/customization/custom-agents |
| VS Code Agent Skills | 公式ドキュメント | https://code.visualstudio.com/docs/copilot/customization/agent-skills |
ツール・ユーティリティ
| リソース | 説明 | URL |
|---|---|---|
| claudekit | 20+ 専門サブエージェント | https://github.com/carlrannaberg/claudekit |
| Trail of Bits Security Skills | セキュリティ監査スキル | https://github.com/trailofbits/skills |
| Claude Squad | マルチエージェントオーケストレータ | https://github.com/smtg-ai/claude-squad |
Community Exploration
コミュニティ資産の探索用。first-hop の代わりではなく補助として使う。
注目カテゴリ(Awesome Claude Code より)
Agent Skills
- DevOps スキル、セキュリティスキル、Web 資産生成など
Workflows & Knowledge Guides
- AB Method, RIPER Workflow, Ralph Wiggum パターン
Tooling
- IDE 統合、使用量モニター、オーケストレータ
Hooks
- TDD Guard, TypeScript Quality Hooks, Britfix
How to Use This List
1. プロジェクトに合わせて選択: 全てを導入せず、必要なものだけ 2. カスタマイズ: そのまま使わず、プロジェクト固有の要件を追加 3. 定期更新: これらのリソースは頻繁に更新されるのでチェック 4. ライセンス確認: 各リソースのライセンスを確認してから使用
Selection Rule
- 設計判断に迷ったら First-Hop References を先に使う
- 実装パターンや周辺事例を広く探したいときだけ Deep References / Community Exploration へ進む
- 本体 SKILL に戻す外部リンクは First-Hop の中から少数だけ選ぶ
Hooks Guide
Hooks are deterministic lifecycle automation for agent sessions.
Use hooks when workflow behavior must run, block, ask, or inject context at a known event. Do not use hooks for guidance that can remain conversational.
When to Use
Good fit
- block dangerous commands before execution
- require confirmation at specific lifecycle events
- inject standard runtime context at session start
- run validation or formatting after successful tool use
Bad fit
- style guidance that can live in instructions
- role specialization that belongs in an agent
- reusable workflows with assets that belong in a skill
Guidance vs Enforcement
| Need | Use |
|---|---|
| Encourage preferred behavior | Prompt / Instruction / Skill / Agent |
| Guarantee lifecycle behavior | Hook |
If the requirement includes "always block", "must ask", "auto-run", or "inject at session start", evaluate Hook first.
Locations
| Path | Scope |
|---|---|
.github/hooks/*.json | Workspace |
Prefer workspace hooks for team policy. Keep personal automation outside the repo when it should not be shared.
Lifecycle Events
| Event | Trigger |
|---|---|
SessionStart | First prompt of a new session |
UserPromptSubmit | User submits a prompt |
PreToolUse | Before tool invocation |
PostToolUse | After successful tool invocation |
PreCompact | Before context compaction |
SubagentStart | Subagent starts |
SubagentStop | Subagent ends |
Stop | Agent session ends |
Minimal Shape
{
"hooks": {
"PreToolUse": [
{
"type": "command",
"command": "./scripts/validate-tool.sh",
"timeout": 15
}
]
}
}Each command can define platform-specific overrides, cwd, env, and timeout.
Decision Heuristic
Choose Hook only if all of these are true:
1. The behavior must happen at a specific lifecycle event 2. Guidance alone is insufficient 3. A shell command can evaluate or enforce the rule safely
If any of the three is false, prefer prompt / instruction / skill / agent.
Core Principles
1. Keep hooks small and auditable 2. Prefer explicit block/ask rules over opaque automation 3. Avoid hardcoded secrets or environment-specific values 4. Do not let long-running hooks stall normal workflow
Common Patterns
Ask before dangerous tool use
Use PreToolUse when a command or tool category needs human confirmation.
Auto-validate after edits
Use PostToolUse when formatting, linting, or policy checks should run after successful file changes.
Inject startup context
Use SessionStart when the agent should receive deterministic context before normal work begins.
Session-scoped guardrails
If the platform supports hooks that are activated only for a specific skill, command, or session, use them for safeguards that would be too noisy as always-on policy.
Good fits:
- stricter destructive-command blocking while touching production or infrastructure
- write-freeze rules during debugging or audit-only work
- temporary validation that belongs to one workflow but not normal chat
Keep these hooks narrow, visible, and easy to disable when the workflow ends.
Lightweight telemetry
Hooks can also record small routing or workflow signals when you need evidence for improvement.
Good fits:
- skill name or workflow name
- manual vs automatic trigger
- success, fallback, or blocked outcome
- missing expected trigger, when the platform exposes it
Use local append-only logs or aggregated counters. Do not log prompt text, secrets, personal data, customer data, or raw tool payloads.
Anti-patterns
- using hooks for soft preferences that belong in instructions
- building large workflow logic inside hooks
- creating hooks before you can name the lifecycle event they depend on
- running slow hooks that make ordinary tasks feel broken
- making a high-friction hook always-on when it only belongs to one risky workflow
- collecting telemetry broadly without a concrete routing or quality question
VS Code Custom Agents — 配置・アクセス制御リファレンス
Merged from former vscode-custom-agents skill (2026-02-26)配置ルール(Critical)
.github/agents/ は直下のみスキャンされる
✅ 認識される
.github/agents/
├── orchestrator.agent.md
├── coding.executor.md
└── quality.reviewer.md
❌ 認識されない
.github/agents/
├── executors/
│ └── coding.executor.md ← 無視される
└── reviewers/
└── quality.reviewer.md ← 無視される根拠: VS Code 公式ドキュメント (2026-02 時点)
"VS Code detects any .md files in the .github/agents folder of your workspace as custom agents."サブディレクトリの再帰スキャンは非対応(実証テスト済み)。
配置場所の選択肢
| 場所 | 用途 |
|---|---|
.github/agents/ (ワークスペース) | チーム共有。そのワークスペースでのみ有効 |
| ユーザープロファイル | 個人用。全ワークスペースで有効 |
chat.agentFilesLocations 設定 | 追加パスを指定。サブフォルダ指定にも使える |
ファイル拡張子
| 場所 | 拡張子 |
|---|---|
.github/agents/ | .agent.md または .md(どちらも認識される) |
.claude/agents/ | .md(Claude Code 互換) |
アクセス制御(3段階)
frontmatter プロパティ
| プロパティ | デフォルト | 効果 |
|---|---|---|
user-invocable | true | false → ピッカーに非表示 |
disable-model-invocation | false | true → サブエージェントとして呼ばれない |
agents (親側) | * (全許可) | 特定エージェント名リスト → 許可リスト |
重要:agentsリストに明示するとdisable-model-invocation: trueをオーバーライドできる。
パターン早見表
# 1. ユーザーが直接呼ぶ + サブエージェントとしても呼ばれる(デフォルト)
user-invocable: true # (省略可)
# 2. サブエージェント専用(ピッカー非表示)
user-invocable: false
# 3. ユーザー専用(他エージェントから呼ばれない)
disable-model-invocation: true
# 4. 特定の親からのみ呼ばれるサブエージェント
user-invocable: false
disable-model-invocation: true
# → 親側の agents リストに明示して呼ぶ⚠️ Deprecated プロパティ
| 旧 | 新 | 移行方法 |
|---|---|---|
infer: true | user-invocable: true (デフォルト) | 行を削除するか置換 |
infer: false | user-invocable: false | 置換 |
target: vscode | — | 削除(不要) |
Orchestrator + Workers パターン
# orchestrator.agent.md
---
name: orchestrator
user-invocable: true
disable-model-invocation: true
tools: ["codebase", "terminal", "agent"] # "agent" が必須
agents:
- coding-executor
- quality-reviewer
---# coding.executor.md
---
name: coding-executor
user-invocable: false
tools: ["codebase", "terminal"]
---ポイント:
- orchestrator に
agentツールを含めないとサブエージェント呼び出しが機能しない agentsリストで呼び出せるサブエージェントを制限するagents: []で全サブエージェント利用を禁止agents: '*'で全許可(デフォルト)
トラブルシューティング
| 症状 | 原因 | 対処 |
|---|---|---|
| ピッカーに出ない | サブフォルダに配置 | .github/agents/ 直下に移動 |
| ピッカーに出ない | user-invocable: false | 意図的なら OK |
runSubagent で "not found" | 認識されていない | 直下に配置されているか確認 |
| サブエージェントが呼ばれない | 親に agent ツールがない | tools に "agent" を追加 |
| 意図しないエージェントが呼ばれる | agents リスト未指定 | 親側で agents: [...] を明示 |
デバッグ方法
1. Chat Diagnostics: チャットビューで右クリック → Diagnostics で認識エージェント一覧を確認 2. `runSubagent` テスト: サブエージェントを直接呼び出して応答確認 3. セッションコンテキスト確認: <agents> タグに何が注入されているかで認識状態を判定
Pattern 0: Plan-First (Meta-Pattern)
Always create a plan before execution
Back to overview.md
Diagram
graph LR
A[Task Request] --> B[Create Plan]
B --> C[User Reviews Plan]
C -->|Approved| D[Execute]
C -->|Changes Needed| B
D --> E[Track Progress]
E --> F[Complete]Characteristics
| Aspect | Description |
|---|---|
| Purpose | Ensure alignment before investing effort in execution |
| Structure | Plan -> Review -> Execute |
| Benefits | Avoids wasted work, enables early course correction |
| Use Cases | Any non-trivial task with multiple steps or uncertainty |
When to Use
- Task is complex or multi-step
- Execution is costly (time, resources, or reversibility)
- Ambiguity exists in requirements
- Risk of misunderstanding user intent
Implementation Pattern
Step 1: Analyze Request
- Understand goal and constraints
- Identify subtasks and dependencies
Step 2: Generate Plan
- List concrete steps with rationale
- Estimate effort/time per step
- Identify risks and alternatives
Step 3: Present for Approval
- Show plan in clear format
- Ask: "Does this plan meet your expectations?"
Step 4: Execute (only after approval)
- Follow plan systematically
- Report progress at key milestonesPlan Format Example
## Plan for [Task Name]
**Goal:** [Clear statement of what will be accomplished]
**Steps:**
1. [Action] - [Rationale] (Est: [time/effort])
2. [Action] - [Rationale] (Est: [time/effort])
**Risks:**
- [Risk 1]: [Mitigation approach]
**Approval Needed:** Please confirm before I proceed.Why This Matters
From vscode-ai-toolkit best practices:
"Generate a plan first and ask the user for approval. This prevents wasted effort on the wrong approach."
Anti-Pattern: Plan-Free Execution
Bad: Jump straight to implementation without discussing approach Good: Propose plan, get feedback, adjust, then execute