Hãy tưởng tượng bạn vừa được assign vào một codebase mới — một hệ thống e-commerce mà team vừa mua lại. Sếp cần biết ngay: "Authentication endpoint nằm ở đâu?"
- Giải thích subagent là gì và cơ chế forked context hoạt động như thế nào
- Sử dụng thành thạo 3 built-in subagents: general-purpose, Explore, Plan
- Tạo custom subagent qua lệnh /agents với tools, scope, và system prompt riêng
- Phân biệt khi nào nên dùng subagent thay vì để main agent xử lý trực tiếp
- Customize subagent nâng cao: persistent memory, preloaded skills, tool restrictions
Subagent là gì?
Subagent là một specialized agent mà Claude Code spawn ra để xử lý một task cụ thể. Điểm khác biệt then chốt so với main agent: subagent chạy trong forked context window riêng — hoàn toàn tách biệt với context window của bạn.
Cơ chế hoạt động
3 thành phần cốt lõi
Sau khi subagent hoàn thành, nó trả về chỉ summary cho main agent. Toàn bộ intermediate work — các file đã đọc, grep results, function traces — bị discard. Main context của bạn vẫn sạch.
| Thành phần | Mô tả |
|---|---|
| Forked context | Subagent có context window riêng (cũng 200k token), độc lập hoàn toàn với main |
| Custom system prompt | Defined trong config file — hướng chuyên môn của subagent |
| Task description | Parent viết dựa trên request của bạn — nhiệm vụ cụ thể cho lần chạy này |
┌─────────────────────────────────────────────────────────────┐ │ MAIN AGENT (context window của bạn) │ │ │ │ Bạn: "Tìm auth endpoint trong codebase này" │ │ │ │ Claude: [spawn subagent] │ │ │ │ │ ▼ │ │ ┌─────────────────────────────────────────────────────┐ │ │ │ SUBAGENT (forked context window riêng) │ │ │ │ │ │ │ │ Input nhận từ parent: │ │ │ │ ├── Custom system prompt (từ config file) │ │ │ │ └── Task description (do parent viết) │ │ │ │ │ │ │ │ Làm việc autonomous: │ │ │ │ ├── Đọc 15 file │ │ │ │ ├── Grep 8 lần │ │ │ │ ├── Trace function calls │ │ │ │ └── [Toàn bộ tool calls KHÔNG xuất hiện ở main] │ │ │ │ │ │ │ │ Kết thúc: return summary → parent │ │ │ └──────────────────┬──────────────────────────────────┘ │ │ │ │ │ ▼ │ │ [Subagent context bị DISCARD hoàn toàn] │ │ │ │ Main nhận được: "auth endpoint tại src/api/auth/login.ts" │ │ Main context: +500 token (chỉ summary) │ └─────────────────────────────────────────────────────────────┘
Built-in Subagents
Claude Code đi kèm 3 built-in subagents sẵn dùng ngay — không cần cấu hình.
Quy tắc chọn built-in:
- Chỉ cần tìm kiếm, không sửa gì → Explore
- Đang trong Plan Mode, cần research → Plan (Claude tự spawn)
- Cần cả research lẫn thực thi → general-purpose
| Subagent | Tools có sẵn | Use case | Context budget điển hình | Khi nào dùng |
|---|---|---|---|---|
| general-purpose | Bash, Read, Write, Grep, Web Search, MCP | Multi-step tasks: vừa explore vừa action | 50-150k token | Task phức tạp, không chắc scope, cần cả đọc lẫn sửa |
| Explore | Read, Grep, Glob (read-only) | Fast codebase searching, không write | 10-40k token | Tìm kiếm thuần túy: "function này ở đâu?", "ai đang dùng API này?" |
| Plan | Read, Grep, Glob (read-only) | Research + analysis trong Plan Mode trước khi lên kế hoạch | 20-60k token | Khi bạn dùng Shift+Tab Plan Mode, cần Claude hiểu codebase trước khi plan |
Tạo custom subagent
Ngoài 3 built-in, bạn có thể tạo subagent chuyên biệt cho nhu cầu riêng của project.
Cách tạo qua /agents
Giao diện wizard hiện ra:
Claude tự generate name, description, và system prompt cho subagent dựa trên purpose bạn mô tả.
Output: file markdown với YAML frontmatter
Subagent được lưu dưới dạng markdown file tại .claude/agents/your-agent.md:
┌─────────────────────────────────────────┐ │ Agent Wizard │ ├─────────────────────────────────────────┤ │ 1. Scope: │ │ ○ Project (lưu vào .claude/agents/) │ │ ● User (lưu vào ~/.claude/agents/) │ │ │ │ 2. Purpose: │ │ > Security vulnerability checker │ │ │ │ 3. Tools: │ │ ☑ Read ☑ Grep ☑ Glob │ │ ☐ Write ☐ Bash ☐ Web Search │ │ │ │ 4. Color: 🔴 Red │ │ │ │ [Generate agent] │ └─────────────────────────────────────────┘
> /agentsOutput: file markdown với YAML frontmatter
Scope: project-level vs user-level
| Scope | Lưu ở | Ai thấy | Khi nào chọn |
|---|---|---|---|
| Project | .claude/agents/ (check vào repo) | Cả team | Subagent liên quan đến project cụ thể (e.g., check business rules của project đó) |
| User | ~/.claude/agents/ | Chỉ bạn | Subagent dùng được mọi project (e.g., security checker tổng quát) |
name: security-checker
description: Scans codebase for security vulnerabilities including SQL injection,
XSS, insecure dependencies, hardcoded secrets, and OWASP Top 10 issues.
Use when asked to review security, audit code, or check for vulnerabilities.
tools:
- Read
- Grep
- Glob
color: red
You are a security-focused code reviewer specializing in identifying vulnerabilities
in web applications.
When analyzing code, always check for:
1. **SQL Injection**: Raw string concatenation in queries, missing parameterized queries
2. **XSS vulnerabilities**: Unescaped user input rendered in HTML
3. **Hardcoded secrets**: API keys, passwords, tokens in source code
4. **Insecure dependencies**: Check package versions against known CVEs
5. **Authentication flaws**: Weak session management, missing rate limiting
6. **IDOR**: Insufficient authorization checks on resource access
Return findings as a structured report:
- Severity: Critical / High / Medium / Low
- File + line number
- Description of issue
- Recommended fix
Focus on actionable findings. Skip theoretical risks without concrete code evidence.Subagent vs Main Agent: Khi nào dùng cái nào?
Quy tắc quyết định nhanh:
| Tiêu chí | Subagent | Main Agent |
|---|---|---|
| Context window | Forked — riêng biệt, bị discard sau khi xong | Shared — tích lũy suốt session |
| Visibility | Bạn chỉ thấy summary, không thấy journey | Bạn thấy từng tool call, từng file đọc |
| Best for | Exploration, answer-only tasks, read-heavy work | Interactive tasks, multi-turn, cần steering |
| Steerability | Thấp — one-shot, không interrupt giữa chừng | Cao — bạn có thể can thiệp bất kỳ lúc nào |
| Chi phí inference | Separate inference (subagent chạy riêng) | Same inference session |
| Debug khi sai | Khó hơn — phải xem summary, không thấy steps | Dễ hơn — thấy từng bước |
| Phù hợp | "Tìm X, trả về Y" | "Giúp tôi implement X, tôi cần xem quá trình" |
Bạn chỉ cần kết quả cuối cùng, không cần xem quá trình? └── YES → Dùng subagent └── NO → Để main agent xử lý Task cần nhiều file reads nhưng answer ngắn? └── YES → Subagent (tránh nhồi hàng chục file vào main context) Task cần interactive back-and-forth nhiều bước? └── YES → Main agent (subagent là one-shot)
Ví dụ thực chiến: COBOL Modernization Case Study
Đây là ví dụ thực tế từ demo AWS Mainframe — một trong những ca phức tạp nhất về subagent workflow.
Tình huống
Một công ty financial services có hệ thống credit card core được viết bằng COBOL từ thập niên 1980. Tổng repo ~100 file, trong đó 94 file COBOL thực sự, còn lại là build scripts và README cũ. Gần như 0 documentation, không ai trong team hiện tại biết COBOL. Mục tiêu: hiểu hệ thống và migrate sang Java — mà không làm mất bất kỳ business rule nào.
Phase 1: Documentation từ subagent
Bước 1: Tạo custom subagent cobol-documentation-expert với CLAUDE.md chứa specialized instructions:
Bước 2: Spawn subagent với task cụ thể:
name: cobol-documentation-expert
description: Analyzes COBOL source files and generates comprehensive technical
documentation including data flow diagrams, business rule extraction, and
module dependency maps.
tools:
- Read
- Glob
- Grep
color: blue
You are an expert COBOL analyst with 30+ years of mainframe experience.
When analyzing COBOL files:
1. Extract all business rules (calculations, validations, decision points)
2. Map data flow between WORKING-STORAGE sections and PROCEDURE DIVISION
3. Identify inter-module dependencies (CALL statements)
4. Document each paragraph's purpose in plain English
5. Generate Mermaid diagram for data flow where appropriate
Output format per file:
- Business rules (numbered list)
- Data flow description
- Dependencies (which files/modules this calls or is called by)
- Plain-English summary (non-technical audience)Phase 1: Documentation từ subagent
Bước 3: Subagent chạy trong 1 giờ, hoàn toàn autonomous:
Bước 4: Main context nhận lại summary:
- Đọc và phân tích 94 file COBOL
- Extract business rules từng module
- Tạo Mermaid diagrams cho data flow
- Viết plain-English explanation cho từng paragraph
> Spawn cobol-documentation-expert subagent để analyze toàn bộ
94 file COBOL trong thư mục /src/cobol/. Tạo comprehensive
documentation cho từng module. Output: /docs/cobol-analysis/Ví dụ thực chiến: COBOL Modernization Case Study (tiếp)
Main context tiêu tốn: summary ngắn. Toàn bộ 94 file COBOL không nhồi vào main thread.
Phase 2: Migration COBOL → Java
Với documentation sẵn có, Phase 2 dùng dual test harness — chạy song song GNU COBOL và JavaScript để verify output bit-for-bit:
Documentation complete:
- 94 files analyzed
- 100+ pages documentation generated at /docs/cobol-analysis/
- 23 Mermaid data flow diagrams
- 847 business rules extracted and documented
- 12 critical calculation modules identified (highest migration risk)Phase 2: Migration COBOL → Java
Kết quả cuối: "Perfect bit-for-bit fidelity. Every calculation, business rule, edge case preserved."
Điều này chỉ khả thi vì subagent xử lý documentation phase trong context window riêng — nếu nhồi 94 file COBOL vào main context, session sẽ vượt giới hạn trước khi bắt đầu được Phase 2.
> Dùng docs tại /docs/cobol-analysis/ để implement Java equivalents
cho từng module. Ưu tiên theo danh sách critical calculation modules.
Mỗi module: implement → test với dual harness → verify fidelity.Case studies theo role
Backend Engineer — tìm deprecated function usage
Tình huống: Bạn cần deprecate function sendLegacyEmail() nhưng không biết nó đang được gọi ở bao nhiêu chỗ trong codebase 200k LOC.
Subagent grep qua 200k LOC, đọc 47 file để lấy context, trả về bảng tổng hợp 2 trang. Main context nhận 2 trang đó — không nhồi 47 file.
DevOps — phân tích log incident
Tình huống: Production alert lúc 3 giờ sáng. Log file đang có 50MB. Nhồi log vào main context là không tưởng.
> Spawn Explore subagent: tìm tất cả chỗ gọi sendLegacyEmail()
trong toàn project. Group theo module. Trả về danh sách file:line
và context của mỗi call (function bao ngoài là gì, điều kiện gọi).DevOps — phân tích log incident
Subagent xử lý 50MB log, trả về 1 trang root cause analysis. Main context: +800 token. Bạn có đủ thông tin để ra quyết định fix mà không bị overwhelm bởi log dump.
Architect — parallel review 5 modules
Tình huống: Trước khi kick off Q2 refactor, bạn cần architectural review của 5 service riêng biệt.
> Spawn general-purpose subagent: đọc /var/log/payments-api/2026-04-19.log
(50MB). Tìm error patterns xuất hiện lần đầu lúc 02:47:00.
Trace request flow dẫn đến lỗi. Trả về root cause analysis và
timeline 10 phút trước sự cố.Architect — parallel review 5 modules
5 subagents chạy parallel, mỗi cái analyze 1 service trong context window riêng. Bạn nhận 5 trang summary sau ~15 phút thay vì 75 phút sequential với main context bị nhồi đầy.
Frontend Engineer — WCAG accessibility audit
Tình huống: Design system có 30 components. Cần verify WCAG 2.1 AA compliance trước khi launch.
> Spawn 5 general-purpose subagents song song:
- Subagent 1: architectural review của payments-service
- Subagent 2: architectural review của user-service
- Subagent 3: architectural review của notification-service
- Subagent 4: architectural review của reporting-service
- Subagent 5: architectural review của auth-service
Mỗi cái: analyze coupling, cohesion, dependency graph, tech debt hotspots.
Trả về: executive summary 1 trang + top 3 issues cần address.Frontend Engineer — WCAG accessibility audit
Subagent scan 30 component files, trả về danh sách 8 components cần fix với chi tiết cụ thể. Main context: không cần thấy code của 22 components pass.
Open Source Maintainer — triage incoming issues
Tình huống: Repo nhận 20 issues mới mỗi tuần. Triage thủ công tốn 2 giờ.
> Spawn Explore subagent: audit accessibility của tất cả components
trong src/components/. Check:
- aria-label và role attributes
- keyboard navigation (tabIndex, onKeyDown handlers)
- color contrast ratios (từ CSS variables)
- focus management
Trả về: danh sách components FAIL với specific violations.Open Source Maintainer — triage incoming issues
> Spawn general-purpose subagent: đọc tất cả open issues chưa có label
qua GitHub MCP. Triage theo template:
- bug / feature request / question / duplicate
- severity (nếu bug): critical / high / medium / low
- module liên quan
Trả về: danh sách issues với suggested labels và 1-line triage note.
KHÔNG tự apply label — chỉ đề xuất để tôi review.Customization nâng cao
Persistent memory
Mặc định, subagent context bị discard sau mỗi lần chạy. Với persistent memory, subagent retain state across conversations — hữu ích cho long-running workflows trải dài nhiều sessions:
Dùng khi: migration project kéo dài nhiều ngày, subagent cần "nhớ" progress của hôm qua để tiếp tục hôm nay. Persistent memory là tính năng đang được refine qua các phiên bản Claude Code — tên key chính xác trong frontmatter có thể thay đổi (hiện tại persistent: true là phổ biến, nhưng luôn double-check bằng claude agents --help).
Preload skills
Thêm skill key trong frontmatter để subagent tự load skill khi khởi động:
name: project-tracker
description: Tracks implementation progress across sessions for large projects.
Maintains state about completed modules, pending tasks, and decisions made.
tools:
- Read
- Write
- Grep
color: green
# Bật persistent memory (kiểm tra `claude agents --help` để xem
# tên key chính xác trong phiên bản Claude Code bạn đang dùng)
persistent: truePreload skills
Lưu ý quan trọng: Khác với skill trong main conversation (chỉ load name + description cho đến khi match), subagent load toàn bộ skill vào context ngay từ đầu. Nếu skill dài 500 dòng → 500 dòng đó chiếm context của subagent. Cân nhắc trước khi preload nhiều skill.
Tool restrictions — subagent read-only
Một trong những customization quan trọng nhất: giới hạn tools để subagent không thể làm gì ngoài phạm vi cho phép.
name: security-auditor
description: Full security audit with OWASP methodology preloaded.
tools:
- Read
- Grep
- Glob
skill:
- owasp-checker
- dependency-audit
color: redTool restrictions — subagent read-only
Pattern phổ biến:
Custom system prompt — focus chuyên môn
System prompt quyết định "tính cách" và expertise của subagent. Ví dụ 3 hướng:
Security focus:
- Read-only subagent: chỉ Read, Grep, Glob — dùng cho analysis, audit, documentation
- CLI-only subagent: chỉ Bash — dùng cho automation script, không dùng MCP
- No-network subagent: không có Web Search — analysis offline, không fetch external data
name: code-explorer
description: Read-only codebase explorer. Cannot modify any files.
tools:
- Read
- Grep
- Glob
# Không có Write, Bash, MCP → subagent chỉ đọc, không thể sửa
color: blueCustom system prompt — focus chuyên môn
Performance focus:
You are a security engineer focused on OWASP Top 10. Every piece of code you
review, you ask: "How could an attacker abuse this?" Never assume input is safe.Customization nâng cao (tiếp)
Accessibility focus:
You are a performance engineer. Always consider: algorithmic complexity (Big-O),
database query patterns (N+1, missing indexes), memory allocation, and caching
opportunities. Quantify impact where possible.Customization nâng cao (tiếp)
You are a WCAG 2.1 specialist. Check every UI component against AA criteria.
Consider screen reader compatibility, keyboard navigation, color contrast ratios,
and focus management. Reference specific WCAG criteria (e.g., 1.4.3) in findings.Anti-patterns
Spawn subagent cho task cần interactive back-and-forth
Subagent là one-shot: nó nhận task, chạy, trả về result, xong. Không có cơ chế để bạn interrupt giữa chừng và nói "khoan, đổi hướng."
Nếu task cần: "Đọc file A, hỏi tôi về option X hay Y, rồi tiếp tục" → đây không phải task cho subagent. Để main agent xử lý để bạn có thể steer.
Custom subagent có ALL tools — mất đi ý nghĩa tách biệt
Nếu subagent có mọi tool giống main agent, tại sao không để main agent làm thẳng? Separation of concerns là lý do tồn tại của subagent. Mỗi custom subagent nên có tool set tối thiểu đủ để làm việc của nó.
Không check .claude/agents/ vào repo
Bạn tạo security-checker subagent, dùng mỗi ngày. Teammate mới join, clone repo, chạy Claude Code — subagent đó không có. Họ không biết nó tồn tại, tự làm lại từ đầu, inconsistent với cách bạn làm.
Fix: Luôn commit .claude/agents/ vào repo. Đây là team tooling, không phải personal preference.
Spawn subagent cho task tiny dưới 5 phút
Spawn subagent có overhead: khởi tạo context mới, load system prompt, setup tools. Nếu task chỉ mất 30 giây — "file này có bao nhiêu dòng?" — overhead spawn lớn hơn task.
Quy tắc ngón tay cái: Task mà main agent làm xong trong 1-2 tool call → không cần subagent.
Forget rằng main agent không "thấy" journey của subagent → khó debug
Nếu subagent trả về kết quả sai, bạn chỉ thấy summary sai — không thấy nó đã đọc file nào, grep gì, hiểu gì sai. Debug cực khó.
Cách phòng tránh:
- Nếu summary critical, ask Claude verify một sample cụ thể sau khi nhận
- Với task quan trọng, dùng main agent lần đầu để "thấy" journey, sau mới convert sang subagent workflow khi đã tin tưởng
- Viết system prompt của custom subagent thật cụ thể — ambiguous instructions dẫn đến ambiguous results
# SAI — subagent "toàn năng" không có lợi ích rõ ràng
tools:
- Read
- Write
- Bash
- Grep
- Glob
- Web Search
- [tất cả MCP tools]Mẹo nâng cao
Parallel subagents: 4 cái cùng lúc = 4x throughput
4 subagents chạy parallel → 10 phút thay vì 40 phút sequential. Main context nhận 4 summary gọn.
Subagent chain: A research → B implement
Pattern mạnh cho complex workflows:
> Spawn 4 Explore subagents song song:
- Subagent 1: tìm tất cả API endpoints trong src/api/
- Subagent 2: tìm tất cả database models trong src/models/
- Subagent 3: tìm tất cả background jobs trong src/jobs/
- Subagent 4: tìm tất cả event handlers trong src/events/
Mỗi cái trả về danh sách với file:line. Tổng hợp vào architectural map.Subagent chain: A research → B implement
Chọn đúng built-in cho task
Subagent + skill combo cho specialized workflow
- Không chắc scope → general-purpose (safe default)
- Pure search → Explore (nhanh hơn, focused hơn)
- Đang trong Plan Mode → Plan (Claude tự dùng khi cần)
- Kết hợp research + action → general-purpose
> Bước 1: Spawn Explore subagent research API documentation của
thư viện Stripe trong /docs/ và online. Trả về: list of methods
cần implement, required parameters, expected response format.
[Nhận summary từ Subagent A]
> Bước 2: Dùng research trên để implement Stripe integration
trong src/payments/stripe.ts. Spawn general-purpose subagent
với context đã có từ bước 1.Subagent + skill combo cho specialized workflow
Subagent này tự load OWASP checklist và secure code review methodology vào context trước khi bắt đầu review. Kết quả: review nhất quán, không bỏ sót category.
Verify subagent output khi critical
name: pr-security-reviewer
description: Reviews pull requests for security issues using OWASP methodology.
Use when asked to review a PR for security concerns.
tools:
- Read
- Grep
- Glob
skill:
- owasp-top10
- secure-code-review
color: redVerify subagent output khi critical
Bước verify nhỏ này có thể tránh false positive và đảm bảo summary đáng tin cậy trước khi bạn dựa vào đó để ra quyết định.
> [Sau khi nhận summary từ security-checker subagent]
> Summary nói có SQL injection tại src/api/users.ts:89. Đọc file đó,
dòng 85-95, và xác nhận lỗi có thực sự ở đó không.Áp dụng ngay
Bài tập 1 (15 phút): Spawn Explore subagent trên project của bạn
Mở Claude Code trong project bạn đang làm, thử:
Sau khi nhận kết quả:
Nếu summary thiếu chi tiết, thử refine task description cho cụ thể hơn.
Bài tập 2 (25 phút): Tạo custom subagent cho project
Chọn 1 trong 2 và tạo qua /agents:
Option A — Code Reviewer:
Option B — Security Checker:
Sau khi tạo:
- Mất bao nhiêu thời gian?
- Context window của bạn tăng thêm bao nhiêu? (gõ /context trước và sau)
- Summary có đủ chính xác không?
- Purpose: Review code changes theo coding standards của project
- Tools: Read, Grep, Glob (read-only)
- System prompt focus: consistency với existing patterns, naming conventions, test coverage
- Purpose: Scan code changes cho security vulnerabilities
- Tools: Read, Grep, Glob (read-only)
- System prompt focus: OWASP Top 10, input validation, authentication issues
- Check file được tạo tại .claude/agents/ — đọc frontmatter và system prompt
- Thử dùng: "Spawn [tên subagent] để review file [file bạn vừa edit]"
- Điều chỉnh system prompt nếu kết quả chưa đủ specific
> Spawn Explore subagent để describe architecture của codebase này
trong 5 bullets. Focus vào: main modules, data flow chính,
và pattern chủ đạo (MVC? Event-driven? Microservices?).Tóm tắt bài học
🎯 Subagent = forked context — chạy trong context window riêng, trả về chỉ summary, discard toàn bộ intermediate work. Main context của bạn không bị nhồi hành trình khám phá.
🎯 3 built-in sẵn dùng: Explore (search-only), Plan (Plan Mode research), general-purpose (explore + action). Chọn Explore cho pure search, general-purpose khi không chắc scope.
🎯 Custom subagent qua /agents: YAML frontmatter + markdown system prompt, lưu tại .claude/agents/ (project-level) hoặc ~/.claude/agents/ (user-level). Luôn commit project-level agents vào repo.
🎯 Subagent là one-shot — không phù hợp cho interactive tasks cần multi-turn steering. Dùng khi task rõ ràng đầu vào/đầu ra, không cần bạn can thiệp giữa chừng.
🎯 Parallel subagents = throughput multiplier — 4 subagents chạy song song thay thế 1 sequential session dài gấp 4 lần, giữ main context gọn.
- Introduction to Subagents — Dedicated course, Anthropic Skilljar
- Claude Code: Subagents documentation — Official docs
- COBOL Modernization demo — AWS Mainframe case study
- Lệnh trong session: /agents — gõ trực tiếp trong Claude Code để tạo hoặc manage subagents
- Transcript "The future of agentic coding" — Boris Cherny về skills vs subagents: "Two sides of same thing — slash commands without forked context, sub-agents with"