Published on

Day 14 - Subagents cho workflow chuyên biệt

Authors

1. Mục tiêu bài học

Sau khoảng 2 tiếng, học viên có thể:

  • Giải thích subagent là gì và vì sao context window riêng giúp giảm nhiễu trong workflow agentic coding.
  • Phân biệt vai trò của main agent, planner, implementer, code reviewer, test engineer, security auditor.
  • Tạo project subagent trong .claude/agents/<name>.md.
  • Viết frontmatter và system prompt cho subagent có scope rõ.
  • Giới hạn tools để subagent không vượt vai trò.
  • Chạy workflow plan -> implement -> review -> test trên taskflow-ai.
  • Nhận diện khi nào không nên dùng subagent vì overhead lớn hơn lợi ích.

2. Bối cảnh thực tế

Khi taskflow-ai lớn dần, một session Claude Code duy nhất dễ trộn nhiều việc:

  • Lập plan feature.
  • Sửa code.
  • Review diff.
  • Viết test.
  • Chạy test và đọc log.
  • Kiểm tra security.
  • Viết summary hoặc PR description.

Nếu cùng một agent vừa implement vừa review, nó dễ bị ảnh hưởng bởi reasoning của chính nó. Nó có thể bảo vệ lựa chọn đã làm trước đó, bỏ sót test gap, hoặc review quá nhẹ. Subagent giúp tách vai trò: reviewer chỉ tập trung tìm lỗi, test engineer chỉ tập trung evidence, security auditor chỉ tập trung rủi ro bảo mật.

Workflow thực tế:

Main agent nhận yêu cầu
  -> planner chia nhỏ việc
  -> main agent hoặc implementer sửa code
  -> code-reviewer review diff
  -> main agent sửa finding được chấp nhận
  -> test-engineer chạy test và phân tích output
  -> main agent tổng hợp quyết định merge/rollback

Không nên dùng subagent cho thay đổi quá nhỏ như sửa typo, đổi text một dòng, hoặc task chưa rõ mục tiêu. Khi đó overhead context, latency và coordination lớn hơn lợi ích.

3. Kiến thức nền

Subagent là AI assistant chuyên biệt, chạy với context riêng. Mỗi subagent có thể có:

  • System prompt riêng.
  • Tool access riêng.
  • Model riêng hoặc kế thừa main session.
  • Màu hiển thị riêng trong UI.

Vị trí phổ biến:

.claude/agents/<name>.md
~/.claude/agents/<name>.md

.claude/agents là project scope, phù hợp với workflow team và nên commit nếu cả team dùng chung. ~/.claude/agents là user scope, phù hợp thói quen cá nhân. Nếu trùng name, project subagent có ưu tiên cao hơn user subagent. Danh tính agent lấy từ field name, không nhất thiết lấy từ tên file.

Có 2 cách tạo subagent:

  • Dùng /agents trong Claude Code: cách an toàn nhất vì UI giúp chọn scope, tools, model và có hiệu lực ngay.
  • Tạo file markdown thủ công trong .claude/agents/: phù hợp khi muốn review/commit như code. Nếu tạo hoặc sửa file trực tiếp trên disk, restart Claude Code session để agent mới được load.

Một subagent file có YAML frontmatter và markdown prompt:

---
name: code-reviewer
description: Use this agent after implementation to review code quality, maintainability, security risks, regressions, and missing tests before merge.
model: sonnet
tools: Read, Grep, Glob, Bash
color: blue
---

You are a senior code reviewer for taskflow-ai.
Review changes. Do not edit files.

Body sau frontmatter là system prompt của subagent. Subagent không nhận nguyên default Claude Code system prompt như main session, nên prompt phải tự nói rõ vai trò, phạm vi, output format, guardrails và cách xử lý khi thiếu dữ kiện. Subagent bắt đầu ở current working directory của main conversation, nhưng cd trong mỗi lệnh shell không nên được xem là state bền vững giữa các tool call.

Các field thường gặp:

FieldÝ nghĩa
nameTên định danh duy nhất, nên dùng lowercase và hyphen như code-reviewer
descriptionKhi nào nên dùng agent; ảnh hưởng auto-delegation
modelModel override như sonnet, opus, haiku, full model ID, hoặc inherit; nếu bỏ trống thường kế thừa model của session chính
toolsAllowlist tools agent được dùng; nếu bỏ field này agent có thể inherit toàn bộ tools từ main conversation, gồm cả MCP tools
disallowedToolsDenylist tools cần chặn khi muốn inherit phần lớn tools nhưng loại vài tool nguy hiểm
permissionModePermission mode riêng của agent; vẫn chịu ảnh hưởng mode của parent session
maxTurnsGiới hạn số lượt agentic để tránh agent chạy quá lâu
effortEffort level riêng cho agent khi cần cân bằng chất lượng và latency
backgroundCho phép agent chạy nền khi tác vụ dài hoặc có thể song song
memoryPersistent memory theo scope user, project, hoặc local; lưu ý bật memory tự động cần quyền đọc/ghi memory files
mcpServersMCP servers riêng cho agent, hữu ích khi muốn browser/database tools chỉ nằm trong subagent
isolationCó thể đặt worktree để chạy trong temporary git worktree khi cần cô lập thay đổi
colorMàu hiển thị trong UI

Cách gọi phổ biến:

Use the code-reviewer agent to review the recent changes.
@"code-reviewer (agent)" review the auth changes.

Nếu nhập thủ công mà không dùng typeahead, dùng dạng local agent:

@agent-code-reviewer review the current git diff. Do not edit files.

Có thể chạy cả session với system prompt của agent:

claude --agent code-reviewer

Lưu ý: cấu hình an toàn nhất trong bài này là dùng tools như allowlist. Nếu reviewer/tester không cần sửa file, không đưa Write, Edit, MultiEdit, hoặc tool ghi file tương đương vào danh sách tools. Không dựa vào prompt tự nguyện "do not edit files" như guardrail duy nhất. Bash vẫn là tool mạnh: reviewer có thể chạy git diff, npm test, npm run lint, nhưng cần guardrail/hook nếu team muốn chặn command ghi file hoặc thao tác destructive.

4. Step-by-step thực hành

Mục tiêu: tạo 2 project subagents cho taskflow-ai:

.claude/agents/code-reviewer.md
.claude/agents/test-engineer.md

Bước 1: Tạo thư mục agents

Chạy ở root taskflow-ai:

mkdir -p .claude/agents

PowerShell:

New-Item -ItemType Directory -Force .claude/agents

Giải thích:

  • Thư mục chạy: root của project taskflow-ai, nơi có package.json, backend/, frontend/ hoặc cấu trúc tương đương.
  • Bash mkdir -p .claude/agents: tạo thư mục agent nếu chưa tồn tại; nếu đã tồn tại thì không lỗi.
  • PowerShell New-Item -ItemType Directory -Force .claude/agents: tương đương trên Windows.
  • Output kỳ vọng: có thể không in gì hoặc in metadata thư mục vừa tạo.
  • Rủi ro: thấp; không ghi đè nội dung file agent hiện có. Vẫn cần kiểm tra đúng thư mục để không tạo .claude nhầm repo.

Kiểm tra:

ls .claude/agents

PowerShell:

Get-ChildItem .claude/agents

Output kỳ vọng ban đầu là thư mục rỗng hoặc danh sách agent đã có. Nếu thấy agent cũ, đọc trước khi sửa để không phá workflow của team.

Bước 2: Tạo code-reviewer

Tạo .claude/agents/code-reviewer.md:

---
name: code-reviewer
description: Use this agent after implementation to review code quality, maintainability, security risks, regressions, and missing tests before merge.
model: sonnet
tools: Read, Grep, Glob, Bash
color: blue
---

You are a senior code reviewer for the taskflow-ai project.

Your job is to review changes, not to edit files.

Review priorities:
1. Correctness bugs and behavioral regressions.
2. Security risks: auth, authorization, injection, secrets, unsafe file or shell usage.
3. Missing or weak tests.
4. Maintainability: duplication, unclear boundaries, brittle abstractions, confusing names.
5. Performance and context/cost issues.

When reviewing:
- Start with findings ordered by severity.
- Use file paths and line references when possible.
- Explain the concrete failure mode.
- Suggest the smallest practical fix.
- If no issue is found, say that clearly and mention residual risks.
- Do not modify files.
- Do not run destructive commands.

Vì reviewer cần xem diff và có thể chạy command read-only như git diff, cho phép Bash, nhưng không đưa Write hoặc Edit vào tools để giữ vai trò review độc lập. Trong prompt vẫn nhắc "Do not edit files" để tăng rõ ràng về hành vi.

Bước 3: Tạo test-engineer

Tạo .claude/agents/test-engineer.md:

---
name: test-engineer
description: Use this agent to design, run, and analyze tests for taskflow-ai after a feature or bug fix is implemented.
model: sonnet
tools: Read, Grep, Glob, Bash
color: green
---

You are a test engineer for the taskflow-ai project.

Your job is to validate behavior through focused tests and clear evidence.

Responsibilities:
1. Identify the behavior that changed.
2. Select the smallest useful test scope first.
3. Run existing tests before suggesting new tests.
4. Analyze failures with concrete hypotheses.
5. Recommend missing tests, edge cases, and regression coverage.
6. Avoid editing files unless the main agent explicitly asks for test implementation.

Testing strategy:
- Start with targeted tests if available.
- Then run broader test suites.
- Capture exact commands and important output.
- Separate product bug, test bug, and environment issue.
- Call out flaky or slow tests.

Nếu project dùng pnpm hoặc yarn, test engineer cần đọc package.json trước khi chạy command.

Bước 4: Kiểm tra agent files

Chạy:

git status --short

Output kỳ vọng:

?? .claude/agents/code-reviewer.md
?? .claude/agents/test-engineer.md

Giải thích:

  • Thư mục chạy: root taskflow-ai.
  • git status --short: chỉ đọc trạng thái Git, không sửa file.
  • Output kỳ vọng: 2 file agent mới ở trạng thái untracked hoặc modified nếu đã tồn tại.
  • Rủi ro: thấp. Nếu output có file ngoài .claude/agents, không động vào vì có thể là thay đổi của người khác.

Trong Claude Code, mở /agents để xác nhận agent đã được nhận diện. Nếu tạo file thủ công nhưng không thấy agent, restart Claude Code session rồi kiểm tra lại.

Nếu team dùng chung, commit các file này. Nếu chỉ thử nghiệm cá nhân, cân nhắc dùng ~/.claude/agents.

Bước 5: Chạy workflow plan -> implement -> review -> test

Chọn feature nhỏ:

Add task priority with values low, medium, high.

Prompt plan:

Plan adding task priority to taskflow-ai.
Split the plan into data model, API changes, UI changes, tests, migration or compatibility concerns, rollback risks, and acceptance criteria.
Do not edit files yet.

Sau khi approve plan:

Implement the approved task priority plan with minimal scope.
Preserve existing behavior, avoid unrelated refactors, and run relevant checks if available.

Gọi reviewer:

@"code-reviewer (agent)" review the current git diff.
Focus on correctness, maintainability, security risks, regressions, and missing tests.
Return findings ordered by severity. Do not edit files.

Nếu không dùng typeahead, prompt tương đương:

@agent-code-reviewer review the current git diff.
Focus on correctness, maintainability, security risks, regressions, and missing tests.
Return findings ordered by severity. Do not edit files.

Gọi tester:

@"test-engineer (agent)" validate the current changes.
Run the smallest relevant tests first, then broader checks if useful.
Report exact commands, exit status, important output, and whether this blocks merge.

Các command tester thường kiểm tra trước khi chạy:

CommandThư mục chạyLàm gìOutput kỳ vọngRủi ro
npm runRoot package liên quan hoặc root monorepo taskflow-aiLiệt kê scripts trong package.jsonDanh sách script như test, lint, typecheckThấp; chỉ đọc scripts
npm test hoặc pnpm testPackage có testChạy test suite mặc địnhExit code 0, test pass; hoặc failure có stack trace rõCó thể tốn thời gian, cần DB/test service nếu integration test
npm run lint hoặc pnpm lintPackage có lint configKiểm tra style/static analysisKhông có errorCó thể fail vì lỗi cũ không liên quan; cần phân biệt baseline
npm run typecheck hoặc pnpm typecheckPackage TypeScriptKiểm tra typeKhông có TypeScript errorCó thể chậm ở repo lớn

Không để subagent tự ý chạy migration, seed hoặc command ghi dữ liệu nếu chưa hiểu environment. Với taskflow-ai, mọi command dùng database nên chạy trên local/dev database, không dùng production credential.

Bước 6: Rollback khi review/test phát hiện lỗi lớn

Xem diff:

git diff --stat
git diff

Rollback một file:

git restore path/to/file

Rollback staged changes:

git restore --staged .

Giải thích rollback:

  • Thư mục chạy: root taskflow-ai.
  • git diff --stat tóm tắt file thay đổi; git diff hiển thị nội dung diff để quyết định rollback.
  • git restore path/to/file khôi phục một file về trạng thái HEAD. Rủi ro: mất toàn bộ sửa đổi chưa commit trong file đó.
  • git restore --staged . chỉ bỏ staged changes khỏi index, không xóa nội dung working tree.
  • Không dùng git reset --hard nếu chưa chắc chắn toàn bộ thay đổi chưa commit đều có thể mất, đặc biệt khi nhiều agent đang sửa các phần khác nhau của repo.

5. Prompt mẫu nên dùng

Prompt gọi planner:

Use a planner-style workflow to break down this change before implementation.
Output phases, affected files, acceptance criteria, test plan, risks, and rollback.
Do not edit files.

Prompt gọi reviewer:

@"code-reviewer (agent)" review only the current git diff.
For each finding, include severity, file path, line reference if possible, failure mode, and smallest fix.
If there are no high-confidence findings, say so clearly.
Do not edit files.

Prompt gọi tester:

@"test-engineer (agent)" run the smallest relevant checks for the recent changes.
Report exact commands, exit status, key output lines, and whether each result blocks merge.
Do not edit files.

Prompt gọi security auditor nếu có:

@"security-auditor (agent)" audit the current diff for auth, authorization, injection, secrets, unsafe shell usage, and sensitive data exposure.
Report only high-confidence findings. Put speculative concerns under residual risks.
Do not edit files.

Prompt tổng hợp:

Summarize the plan, implementation, review findings, test results, unresolved risks, and rollback steps.
Conclude with: ready to merge, needs changes, or blocked.

6. Trade-offs

Subagent có lợi khi:

  • Task có vai trò rõ ràng.
  • Cần review độc lập sau implementation.
  • Cần tách output lớn như test logs khỏi context chính.
  • Cần tool scope khác nhau cho từng vai trò.
  • Cần chạy phân tích song song.

Chi phí:

  • Tốn thêm token vì mỗi subagent có context riêng.
  • Tốn thời gian đọc lại diff/file.
  • Dễ tạo quá nhiều agent.
  • Prompt agent mơ hồ dẫn tới output chung chung.
  • Permission quá rộng làm tăng rủi ro.
Tình huốngNên dùng subagent?Lý do
Sửa typo trong READMEKhôngOverhead lớn hơn lợi ích
Thêm field ảnh hưởng API, UI, testCần review và test độc lập
Debug test flakyTest engineer giữ context riêng về test
Review auth middlewareCần security lens
Đổi tên biến cục bộKhôngMain agent xử lý nhanh hơn

7. Best practices

  • Đặt subagent theo vai trò ổn định: code-reviewer, test-engineer, security-auditor.
  • Không đặt theo task quá hẹp như fix-priority-bug-agent.
  • Giữ description cụ thể vì Claude dùng field này để quyết định delegation.
  • Reviewer mặc định read-only, không có Edit/Write.
  • Tester có Bash để chạy test, nhưng không nên tự sửa file nếu nhiệm vụ chỉ validate.
  • Security auditor dùng allowlist tools tối thiểu; không cấp tool ghi file hoặc command nguy hiểm nếu chỉ audit.
  • Project subagents nên commit nếu team dùng chung.
  • Tạo hoặc chỉnh agent bằng /agents khi có thể; nếu sửa file markdown thủ công, restart Claude Code để tránh dùng agent definition cũ.
  • Khi cần chắc chắn agent chạy, dùng @ typeahead hoặc dạng thủ công @agent-<name> thay vì chỉ nhắc tên trong câu.
  • Permission mode của parent session vẫn quan trọng. Nếu session chính đang auto-approve hoặc bypass permission, subagent không phải sandbox bảo mật tuyệt đối.
  • Output của reviewer/tester phải có evidence, command hoặc file reference.
  • Main agent vẫn là coordinator: quyết định finding nào chấp nhận, sửa gì, test gì, và khi nào merge.

8. Performance / cost / context

Subagent giúp context chính sạch hơn, nhưng tổng chi phí có thể tăng. Dùng subagent khi lợi ích từ isolation lớn hơn token/latency.

Cách tối ưu:

  • Gọi subagent sau khi có diff rõ.
  • Giới hạn scope: review current git diff, không phải review whole project.
  • Yêu cầu output concise.
  • Không gọi 4-5 subagents cho thay đổi nhỏ.
  • Dùng tools tối thiểu.
  • Đặt maxTurns cho agent dễ lan man như reviewer toàn repo hoặc log analyzer.
  • Dùng model: inherit hoặc model rẻ hơn cho task lặp lại nếu chất lượng vẫn đủ; dùng model mạnh hơn cho audit phức tạp.
  • Nếu test log dài, yêu cầu test engineer trả key lines và root cause, không paste toàn bộ log.
  • Subagent transcripts tách khỏi main conversation; main context sạch hơn, nhưng tổng token vẫn tăng vì mỗi agent phải đọc lại diff/file cần thiết.

Prompt tiết kiệm context:

@"code-reviewer (agent)" review only files changed in git diff. Inspect related files only to validate a concrete finding.

Prompt tốn context:

@"code-reviewer (agent)" review the whole project and list everything that can be improved.

9. Checklist cuối bài

  • Tôi giải thích được subagent là gì.
  • Tôi biết subagent có context, prompt và tools riêng.
  • Tôi tạo được .claude/agents/code-reviewer.md.
  • Tôi tạo được .claude/agents/test-engineer.md.
  • code-reviewer không có quyền edit file.
  • test-engineer có quyền chạy command test.
  • Tôi chạy được workflow plan -> implement -> review -> test.
  • Tôi biết khi nào không nên dùng subagent.
  • Tôi hiểu rủi ro của việc cấp tools quá rộng cho subagent.
  • Tôi có rollback plan nếu review/test phát hiện lỗi.

10. Bài tập

Bài cơ bản: tạo code-reviewertest-engineer trong .claude/agents.

Bài thực tế: chọn feature nhỏ như task priority hoặc due date, chạy workflow plan -> implement -> review -> test, lưu prompt và kết quả.

Bài nâng cao: tạo security-auditor read-only cho diff có auth, input validation hoặc sensitive data.

Bài reflection: so sánh chất lượng review giữa main agent tự review và subagent code-reviewer. Ghi rõ subagent phát hiện thêm gì, bỏ sót gì, và overhead có đáng không.


Tài liệu

Tóm tắt kiến thức

Subagent trong Claude Code là assistant chuyên biệt chạy trong context window riêng. Mục tiêu là tách vai trò và giảm nhiễu: planner lập kế hoạch, implementer sửa code, code reviewer tìm lỗi, test engineer tạo evidence, security auditor kiểm tra rủi ro bảo mật.

Vị trí:

.claude/agents/<name>.md
~/.claude/agents/<name>.md

Project subagents trong .claude/agents nên commit nếu team dùng chung. User subagents trong ~/.claude/agents phù hợp workflow cá nhân.

Ví dụ invoke:

@"code-reviewer (agent)" review the current git diff. Do not edit files.

Nếu không dùng typeahead:

@agent-code-reviewer review the current git diff. Do not edit files.

Subagent nên có tool scope tối thiểu. Reviewer thường chỉ cần Read, Grep, Glob, Bash; không cần Edit, Write, hoặc MultiEdit. Tester cần Bash để chạy test và đọc output. Theo cấu trúc frontmatter hiện hành, dùng tools như allowlist; nếu không khai báo tools, subagent có thể inherit nhiều tool hơn từ main conversation, gồm cả MCP tools. Bash không phải read-only tuyệt đối, nên team production nên dùng permission rules hoặc hook để chặn command destructive.

Sơ đồ tư duy hoặc luồng xử lý

Subagents
├── Vì sao dùng?
│   ├── Tách context window
│   ├── Tách vai trò
│   ├── Giảm bias sau implementation
│   └── Scope tools theo allowlist
├── Nơi định nghĩa
│   ├── .claude/agents/<name>.md
│   └── ~/.claude/agents/<name>.md
├── Cách gọi
│   ├── Natural language: Use the code-reviewer agent...
│   ├── @ typeahead: @"code-reviewer (agent)"
│   ├── Manual mention: @agent-code-reviewer
│   └── Session-wide: claude --agent code-reviewer
├── Vai trò tốt
│   ├── planner
│   ├── code-reviewer
│   ├── test-engineer
│   └── security-auditor
├── Rủi ro
│   ├── Token/latency tăng
│   ├── Permission quá rộng
│   ├── Agent prompt mơ hồ
│   └── Tools allowlist quá rộng
└── Khi không nên dùng
    ├── Thay đổi nhỏ
    ├── Task một bước
    └── Không cần review độc lập

Luồng đề xuất:

User request
  -> Main agent clarify scope
  -> Planner creates plan
  -> Main/implementer edits code
  -> code-reviewer reviews diff
  -> Main fixes accepted findings
  -> test-engineer runs targeted tests
  -> Main summarizes risk and merge decision

Bảng so sánh

Tiêu chíMain agentSubagent
ContextChứa toàn bộ cuộc trò chuyện chínhContext riêng
Vai tròĐiều phối, tổng hợp, sửa trực tiếpChuyên biệt
Tool accessTheo session chínhCó thể giới hạn riêng
BiasDễ bị ảnh hưởng bởi implementation trước đóÍt hơn nếu prompt tốt
Chi phíÍt overheadTốn thêm token/latency
Phù hợpTask đơn giản, orchestrationReview, test, audit, planning
AgentKhi dùngTools gợi ýKhông nên cho
plannerTrước feature lớnRead, Grep, GlobEdit, Write
code-reviewerSau implementationRead, Grep, Glob, BashWrite, Edit
test-engineerSau fix/featureRead, Grep, Glob, BashEdit nếu chỉ validate
security-auditorAuth, data, shell, secretsRead, Grep, Glob, BashWrite, Edit, tools ghi file

Lỗi thường gặp

  1. description quá mơ hồ description: Helps with code không đủ để Claude chọn đúng agent. Viết use case cụ thể.

  2. Reviewer có quyền edit Reviewer tự sửa code làm mất tính độc lập. Chặn Write, Edit, MultiEdit.

  3. Cấp tools quá rộng cho agent chưa kiểm soát Nếu reviewer hoặc auditor có Write, Edit, hoặc command shell không giới hạn, agent có thể vượt vai trò phân tích. Tránh trong lab.

  4. Gọi quá nhiều subagents cho thay đổi nhỏ Tốn token và thời gian, nhưng không tăng chất lượng.

  5. Không yêu cầu output có cấu trúc Prompt what do you think? thường cho review chung chung. Yêu cầu severity, file, failure mode, smallest fix.

  6. Quên commit project subagents Nếu team cần workflow chung mà không commit .claude/agents, mỗi người sẽ có agent khác nhau.

  7. Không đặt đúng thư mục agent Project agents nên đặt trong .claude/agents/<name>.md để Claude Code auto-discover trong project. User agents đặt trong ~/.claude/agents/<name>.md.

  8. Tạo file thủ công nhưng không restart Claude Code Nếu không dùng /agents mà tự tạo file markdown, Claude Code có thể chưa load agent mới trong session hiện tại. Restart session rồi kiểm tra lại.

  9. Dùng cú pháp @code-reviewer như text thường Cú pháp chắc chắn hơn là chọn agent từ typeahead hoặc nhập thủ công @agent-code-reviewer. Nếu chỉ viết tên agent trong câu, Claude vẫn có thể tự quyết định có delegate hay không.

Cách debug

Kiểm tra file agent:

ls .claude/agents

PowerShell:

Get-ChildItem .claude/agents

Giải thích: chạy ở root taskflow-ai; lệnh chỉ liệt kê file agent, output kỳ vọng có code-reviewer.mdtest-engineer.md; rủi ro thấp.

Trong Claude Code, dùng /agents để xem agent đã được nhận diện chưa. Nếu không thấy, restart Claude Code session.

Kiểm tra frontmatter:

sed -n '1,60p' .claude/agents/code-reviewer.md

PowerShell:

Get-Content .claude/agents/code-reviewer.md -TotalCount 60

Giải thích: chạy ở root taskflow-ai; lệnh chỉ đọc 60 dòng đầu để kiểm tra YAML frontmatter; output kỳ vọng có name, description, tools, model; rủi ro thấp, nhưng không paste nội dung chứa secret vào chat nếu prompt agent vô tình ghi secret.

Nếu agent không chạy, gọi rõ:

Use the code-reviewer subagent defined in .claude/agents/code-reviewer.md to review the current git diff. Do not edit files.

Nếu tester không chạy được test, kiểm tra toolsBash không:

tools: Read, Grep, Glob, Bash

Nếu reviewer có nguy cơ sửa file ngoài ý muốn, kiểm tra allowlist không có tool ghi file:

tools: Read, Grep, Glob, Bash

Nếu output review chung chung:

@"code-reviewer (agent)" review only files changed in git diff. For each finding, include severity, file path, line reference if possible, failure mode, and smallest fix.

Nếu output test thiếu evidence:

@"test-engineer (agent)" rerun the relevant checks and include exact commands, exit status, key output lines, and whether the result blocks merge.

Bài tập

Bài 1 — Cơ bản

Mục tiêu: tạo 2 project subagents:

.claude/agents/code-reviewer.md
.claude/agents/test-engineer.md

Tạo thư mục:

mkdir -p .claude/agents

PowerShell:

New-Item -ItemType Directory -Force .claude/agents

Giải thích lệnh:

  • Thư mục chạy: root taskflow-ai.
  • mkdir -p hoặc New-Item -Force: tạo .claude/agents nếu chưa có.
  • Output kỳ vọng: thư mục được tạo, không có lỗi.
  • Rủi ro: thấp; nếu chạy nhầm repo sẽ tạo thư mục .claude nhầm chỗ.

code-reviewer phải có:

  • name: code-reviewer.
  • description rõ khi nào dùng.
  • tools: Read, Grep, Glob, Bash.
  • Không đưa Write, Edit, hoặc tool ghi file vào allowlist.
  • Prompt yêu cầu review theo severity.
  • Guardrail không sửa file.

test-engineer phải có:

  • name: test-engineer.
  • description rõ khi nào dùng.
  • tools gồm Bash.
  • Prompt yêu cầu chạy test có command cụ thể.
  • Phân biệt product bug, test bug, environment issue.
  • Guardrail không sửa file nếu chưa được yêu cầu.

Kiểm tra:

git status --short

Output kỳ vọng:

?? .claude/agents/code-reviewer.md
?? .claude/agents/test-engineer.md

Giải thích lệnh:

  • Thư mục chạy: root taskflow-ai.
  • git status --short: xác nhận chỉ có 2 agent files mới hoặc modified.
  • Output kỳ vọng: không xuất hiện file ngoài phạm vi bài tập.
  • Rủi ro: thấp; đây là lệnh read-only. Nếu thấy thay đổi của người khác, không rollback toàn repo.

Rollback:

rm .claude/agents/code-reviewer.md .claude/agents/test-engineer.md

PowerShell:

Remove-Item .claude/agents/code-reviewer.md, .claude/agents/test-engineer.md

Giải thích rollback:

  • Chỉ chạy nếu muốn xóa 2 agent tạo trong bài tập.
  • Thư mục chạy: root taskflow-ai.
  • Output kỳ vọng: 2 file bị xóa, git status --short không còn hiển thị chúng nếu chưa commit.
  • Rủi ro: mất nội dung agent nếu bạn đã chỉnh tay. Không dùng wildcard như Remove-Item .claude/agents/* khi team đã có agent khác.

Bài 2 — Thực tế

Mục tiêu: dùng subagents trong workflow thật.

Chọn một feature nhỏ:

Add task priority with low, medium, high.

hoặc:

Add due date to tasks and show overdue state.

Workflow:

  1. Plan.
  2. Implement.
  3. Review bằng code-reviewer.
  4. Fix findings hợp lý.
  5. Test bằng test-engineer.
  6. Tổng hợp kết quả.

Prompt plan:

Plan adding task priority to taskflow-ai. Split the plan into data model, API changes, UI changes, tests, migration or compatibility concerns, rollback risks, and acceptance criteria. Do not edit files yet.

Prompt review:

@"code-reviewer (agent)" review the current git diff. Focus on correctness, maintainability, security risks, regressions, and missing tests. Return findings ordered by severity. Do not edit files.

Prompt test:

@"test-engineer (agent)" validate the current changes. Run the smallest relevant tests first, then broader checks if useful. Report exact commands, exit status, important output, and whether this blocks merge.

Command nên chạy:

git diff --stat
git diff
npm run
npm test
npm run lint
npm run typecheck

Nếu repo dùng pnpm:

pnpm test
pnpm lint
pnpm typecheck

Giải thích command:

CommandThư mục chạyLàm gìOutput kỳ vọngRủi ro
git diff --statRoot taskflow-aiTóm tắt file thay đổiDanh sách file và số dòng đổiThấp; read-only
git diffRoot taskflow-aiXem chi tiết diff để reviewer/tester hiểu scopePatch của feature hiện tạiCó thể lộ secret nếu diff chứa secret; không paste bừa ra ngoài
npm runPackage hoặc root có package.jsonLiệt kê scripts khả dụngtest, lint, typecheck nếu project đã cấu hìnhThấp
npm test / pnpm testPackage liên quanChạy test mặc địnhExit code 0 hoặc failure rõCó thể cần service local như PostgreSQL/Redis
npm run lint / pnpm lintPackage liên quanChạy lint/static checksKhông có errorCó thể fail do lỗi cũ; ghi rõ nếu không liên quan feature
npm run typecheck / pnpm typecheckPackage TypeScriptChạy kiểm tra typeKhông có TypeScript errorCó thể chậm ở monorepo

Không chạy migration, seed hoặc command xóa dữ liệu nếu prompt/tester chưa giải thích rõ environment. Với bài này, ưu tiên local/dev database.

Bài 3 — Nâng cao

Mục tiêu: tạo security-auditor.

Tạo .claude/agents/security-auditor.md:

---
name: security-auditor
description: Use this agent to audit security-sensitive changes involving authentication, authorization, user data, external APIs, secrets, file access, or shell commands.
model: sonnet
tools: Read, Grep, Glob, Bash
color: red
---

You are a security auditor for taskflow-ai.

Audit code without editing files.

Focus areas:
1. Authentication and authorization bypass.
2. Injection: SQL, NoSQL, command, prompt, HTML/XSS.
3. Secrets committed to code or logs.
4. Unsafe file access or shell execution.
5. Sensitive data exposure.
6. Insecure error handling.
7. Missing validation on user-controlled input.

For each finding, include severity, file, exploit scenario, impact, recommended fix, and whether it blocks merge.
If there are no high-confidence findings, say so clearly.

Prompt chạy audit:

@"security-auditor (agent)" audit the current git diff for security issues. Focus on user-controlled input, authorization, secrets, unsafe shell usage, and sensitive data exposure. Do not edit files.

Expected result:

Findings
- High: No high-confidence findings.
- Medium: ...

Residual risk
- ...

Bài 4 — Review & Reflection

Trả lời:

  1. Subagent khác main agent ở điểm nào?
  2. Vì sao reviewer nên có context window riêng?
  3. Khi nào không nên dùng subagent?
  4. Vì sao không nên cho code-reviewer quyền Edit?
  5. test-engineer cần Bash để làm gì?
  6. Rủi ro của việc cấp tools quá rộng cho subagent là gì?
  7. Project subagents nên đặt ở đâu?
  8. User subagents nên đặt ở đâu?
  9. Vì sao project subagents nên commit nếu team dùng chung?
  10. Trong workflow plan -> implement -> review -> test, bước nào giảm bias nhất?

Expected answer ngắn:

Subagent có prompt, context và tools riêng. Reviewer nên có context riêng để review độc lập hơn, ít bị ảnh hưởng bởi reasoning của implementer. Không nên dùng subagent cho thay đổi quá nhỏ hoặc task một bước. code-reviewer không nên có Edit vì reviewer cần giữ vai trò review. test-engineer cần Bash để chạy test/lint/typecheck. Cấp tools quá rộng có thể làm subagent vượt vai trò, sửa file hoặc chạy command không cần thiết. Project subagents đặt ở .claude/agents, user subagents đặt ở ~/.claude/agents. Nếu team dùng chung, project subagents nên commit để cùng tiêu chuẩn. Bước review bằng subagent sau implementation giảm bias nhất.

Tiêu chí hoàn thành

  • .claude/agents/code-reviewer.md.
  • .claude/agents/test-engineer.md.
  • Mỗi file có frontmatter hợp lệ.
  • code-reviewer không có quyền edit file.
  • test-engineer có quyền chạy command test.
  • Đã chạy ít nhất một workflow plan -> implement -> review -> test.
  • Có ghi lại prompt đã dùng.
  • Có output review theo severity.
  • Có output test với command và kết quả rõ.
  • Có rollback plan.
  • Có ghi chú security và maintainability risk.

Gợi ý nếu bí

Nếu Claude không nhận subagent:

ls .claude/agents

Trong Claude Code, mở /agents. Nếu vừa tạo file markdown thủ công mà chưa thấy agent, restart Claude Code session.

Kiểm tra name:

name: code-reviewer

Nếu chỉ nhắc code-reviewer trong câu nhưng Claude không delegate:

Use the code-reviewer subagent defined in .claude/agents/code-reviewer.md to review the current git diff. Do not edit files.

Hoặc dùng cú pháp mention thủ công:

@agent-code-reviewer review the current git diff. Do not edit files.

Nếu tester không chạy được test:

tools: Read, Grep, Glob, Bash

Nếu không biết test command:

npm run

Nếu review quá chung chung:

For each finding, include severity, file, line, failure mode, recommended fix, and merge blocking status.

Đáp án tham khảo hoặc expected result

Expected workflow summary:

Change:
- Added task priority with low, medium, high.

Review:
- No high-confidence correctness issues.
- Medium test gap: invalid priority value should be covered.
- Low maintainability concern: priority constants should be reused across UI and validation.

Tests:
- npm test: passed.
- npm run lint: passed.
- npm run typecheck: passed.

Security:
- Server-side validation exists for priority.
- No secrets or unsafe shell usage added.

Rollback:
- Before commit: git restore .
- After commit: git revert <commit-sha>

Decision:
- Ready to merge after adding invalid priority regression test.