Mục tiêu học tập

Sau bài này, bạn sẽ có thể:
  • ✅ 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

Mở đầu: “You get the answer without the journey”

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?” Bạn mở Claude Code và hỏi thẳng. Không có subagent, Claude bắt đầu một cuộc hành trình khám phá:
  • Đọc package.json để hiểu dependencies — 1.200 token
  • Scan src/ với glob pattern để tìm file liên quan — 2.400 token
  • Đọc src/app.ts, src/server.ts, src/routes/index.ts — 4.100 token
  • Grep “auth” toàn project — 3.800 kết quả, mỗi hit load vào context — 6.200 token
  • Đọc thêm 8 file middleware để trace request flow — 7.300 token
  • Cuối cùng: “Endpoint nằm ở src/api/auth/login.ts dòng 42”
Tổng thiệt hại: 25.000 token cho context window của bạn. Và Claude vẫn đang “nhớ” tất cả 15 file đó trong suốt phần còn lại của session, dù bạn không cần nữa. Có subagent, bạn chỉ thấy:
> Spawn Explore subagent để tìm authentication endpoint.

[Subagent đang chạy...]

Authentication endpoint: src/api/auth/login.ts:42
Handler: POST /api/auth/login
Middleware: rateLimiter → validateBody → verifyCredentials → issueJWT
Main context tiêu tốn: 500 token. Subagent đã đọc 15 file, chạy 8 lần grep — nhưng toàn bộ hành trình đó xảy ra trong context window riêng của nó, và bị discard ngay sau khi trả về summary. Đây chính là triết lý cốt lõi của subagent: “you get the answer without the journey.”

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

Thành phầnMô tả
Forked contextSubagent có context window riêng (cũng 200k token), độc lập hoàn toàn với main
Custom system promptDefined trong config file — hướng chuyên môn của subagent
Task descriptionParent viết dựa trên request của bạn — nhiệm vụ cụ thể cho lần chạy này
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. Lưu ý: Đây là đánh đổi có chủ ý. Main agent mất visibility vào “journey” của subagent. Nếu subagent đi sai hướng, bạn sẽ khó debug vì không thấy từng bước. (Xem Anti-patterns bên dưới để biết cách handle.)

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.
SubagentTools có sẵnUse caseContext budget điển hìnhKhi nào dùng
general-purposeBash, Read, Write, Grep, Web Search, MCPMulti-step tasks: vừa explore vừa action50-150k tokenTask phức tạp, không chắc scope, cần cả đọc lẫn sửa
ExploreRead, Grep, Glob (read-only)Fast codebase searching, không write10-40k tokenTìm kiếm thuần túy: “function này ở đâu?”, “ai đang dùng API này?”
PlanRead, Grep, Glob (read-only)Research + analysis trong Plan Mode trước khi lên kế hoạch20-60k tokenKhi bạn dùng Shift+Tab Plan Mode, cần Claude hiểu codebase trước khi plan
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

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

> /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:
---
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.

Scope: project-level vs user-level

ScopeLưu ởAi thấyKhi nào chọn
Project.claude/agents/ (check vào repo)Cả teamSubagent liên quan đến project cụ thể (e.g., check business rules của project đó)
User~/.claude/agents/Chỉ bạnSubagent dùng được mọi project (e.g., security checker tổng quát)
Mẹo: Commit .claude/agents/ vào repo để cả team dùng chung subagent. Tránh anti-pattern “chỉ mình tôi có” dẫn đến inconsistency.

Subagent vs Main Agent: Khi nào dùng cái nào?

Tiêu chíSubagentMain Agent
Context windowForked — riêng biệt, bị discard sau khi xongShared — tích lũy suốt session
VisibilityBạn chỉ thấy summary, không thấy journeyBạn thấy từng tool call, từng file đọc
Best forExploration, answer-only tasks, read-heavy workInteractive tasks, multi-turn, cần steering
SteerabilityThấp — one-shot, không interrupt giữa chừngCao — bạn có thể can thiệp bất kỳ lúc nào
Chi phí inferenceSeparate inference (subagent chạy riêng)Same inference session
Debug khi saiKhó hơn — phải xem summary, không thấy stepsDễ 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”
Quy tắc quyết định nhanh:

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:
---
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)
Bước 2: Spawn subagent với task cụ thể:
> 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/
Bước 3: Subagent chạy trong 1 giờ, hoàn toàn autonomous:
  • Đọ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
Bước 4: Main context nhận lại summary:
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)
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:
> 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.
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.

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.
> 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).
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 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ố.
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 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.
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 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.
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 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:
---
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: true
---
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: security-auditor
description: Full security audit with OWASP methodology preloaded.
tools:
- Read
- Grep
- Glob
skill:
- owasp-checker
- dependency-audit
color: red
---
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: 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: blue
---
Pattern phổ biến: 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

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:
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.
Performance 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.
Accessibility focus:
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

# 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]
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

Mẹo nâng cao

Parallel subagents: 4 cái cùng lúc = 4x throughput

> 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.
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:
> 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.

Chọn đúng built-in cho task

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

Subagent + skill combo cho specialized workflow

---
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: red
---
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

> [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.
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.

Á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ử:
> 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?).
Sau khi nhận kết quả:
  • 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?
  • 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:
  • 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
Option B — Security Checker:
  • Purpose: Scan code changes cho security vulnerabilities
  • Tools: Read, Grep, Glob (read-only)
  • System prompt focus: OWASP Top 10, input validation, authentication issues
Sau khi tạo:
  • 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

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.

Bài tiếp theo

Bạn đã biết cách dùng subagent để tách context và chạy parallel. Nhưng có một cơ chế khác để mở rộng Claude Code: Skills — reusable workflows bạn định nghĩa một lần và dùng lại nhiều lần bằng slash command. Điểm khác biệt then chốt: Skill không fork context, không chạy parallel — nó load instructions vào main conversation và bạn vẫn thấy toàn bộ execution. Đây là đánh đổi ngược lại so với subagent, phù hợp cho workflow khác nhau. Bài 2.9 sẽ đi sâu vào Skills: cách tạo, khi nào dùng skill vs subagent vs MCP, và cách kết hợp cả ba để build extension ecosystem mạnh nhất cho workflow của bạn. Cross-references:
  • Bài 2.5 — Subagent là một trong 5 chiến thuật tiết kiệm context (chiến thuật “outsource exploration”)
  • Bài 2.6 — Dùng subagent làm code reviewer trước khi commit
  • Bài 2.9 — Skill vs subagent: hai sides of the same coin (slash command không fork context vs có fork)
  • Bài 2.10 — Subagent kết hợp MCP: mở rộng tools available cho subagent
➡️ Bài tiếp theo: Bài 2.9 — Skills

Tài liệu tham khảo

  • 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”
Khoá học “Claude Code 101” — bản tiếng Việt v1.0Bản quyền 2026 Anthropic. Mọi quyền được bảo lưu.