jvinhit//lab

Search posts

Type to search across journal entries.

navigate open esc close

Coding Agent Mastery — Tư duy, prompt và patterns làm việc hiệu quả

Từ mindset đúng (agent là cộng sự, không phải autocomplete), công thức CARET cho prompt, chuyển spec thành task, đến 5 patterns thực chiến và anti-patterns khi làm việc với coding agent.

Bạn có thể cài đặt coding agent trong 5 phút. Nhưng dùng nó hiệu quả — đó là kỹ năng mất vài tuần đến vài tháng để refine.

Dưới đây là interactive reference tổng hợp mindset, kỹ thuật prompt, quy trình specs-to-task, và các patterns thực chiến — bấm vào từng tab để khám phá.

Coding Agent Mastery
Mindset · Setup · Prompt · Rules · Skills · Sub-agents
Agent không phải autocomplete — nó là cộng sự
Sai lầm lớn nhất: dùng coding agent như "tab completion" thông minh hơn. Đúng mindset là bạn đang delegate task, không phải gợi ý code. Bạn là tech lead, agent là junior dev giỏi nhưng cần context rõ ràng.
Sai ❌
"Viết hàm sort array" → nhận code → dùng

"Fix lỗi này" → paste error → chờ

Mỗi lần hỏi một câu nhỏ, tự build từng mảnh
Đúng ✅
"Implement feature X theo spec, dùng pattern Y, test coverage trên 80%"

Giao task có đầu có đuôi, agent tự quyết chi tiết

Review output, iterate nếu cần
Mental model: Vòng lặp Agent
Nhận task + context Plan Execute tool calls Observe kết quả Done / iterate

Context window = "bộ nhớ làm việc". Agent không nhớ conversation cũ. Mỗi session phải có đủ context.

5 nguyên tắc vàng
1. Specificity beats brevity
Prompt dài và rõ tốt hơn prompt ngắn và mơ hồ. Tốn 30 giây viết context tiết kiệm 10 phút sửa lại.
2. Constraints trước, freedom sau
Nói rõ những gì KHÔNG được làm: "không thay đổi API interface", "không thêm dependencies mới", "giữ nguyên naming convention".
3. Think in tasks, not in lines
Đừng nghĩ "agent viết dòng code này". Nghĩ "agent hoàn thành task này theo acceptance criteria này".
4. Trust but verify
Review output là bắt buộc. Agent confident nhưng có thể sai. Tests + code review vẫn là trách nhiệm của bạn.
5. Rules/Skills là đầu tư một lần
Thay vì lặp lại "dùng TypeScript strict mode" mỗi lần, viết một lần vào rules. Agent tự áp dụng mọi lúc.
Claude Code — setup nhanh
CLI agent chạy trực tiếp trong terminal, có quyền đọc/ghi file, chạy lệnh.
npm install -g @anthropic-ai/claude-code
cd your-project
claude
Cursor — 4 chế độ
Agent mode (Composer)
Multi-file task, refactor lớn, implement feature.
Ask mode (Chat)
Hỏi về codebase, explain code, brainstorm.
Inline Edit (Cmd+K)
Sửa đoạn code được chọn. Nhanh, focused.
Terminal Agent
Chạy command, install dep, debug runtime.
Cấu trúc project tốt cho agent
your-project/
├── .claude/
│   ├── CLAUDE.md          # rules cho claude code
│   └── commands/          # custom slash commands
├── .cursor/
│   └── rules/             # .mdc rules cho Cursor
├── docs/
│   ├── ARCHITECTURE.md    # context quan trọng nhất
│   └── specs/             # feature specs
├── src/
└── tests/
Agent tự đọc CLAUDE.md / .mdc mỗi session. Đây là nơi bạn "lập trình" hành vi agent.
Context management — quan trọng nhất
Luôn có ARCHITECTURE.md ngắn gọn (dưới 200 dòng)
Khi cần @mention file liên quan trực tiếp
Tránh paste toàn bộ codebase — agent bị overwhelm
Không nên để context window đầy rồi mới bắt đầu task
Rules = instructions luôn được inject vào mỗi conversation. Viết một lần, agent tự nhớ. Coi như "personality + constraints" của agent.
Anatomy — 4 phần
Phần 1: Project context ai cũng cần
Agent đọc đầu tiên, cần hiểu ngay đang ở project gì.
# Project: E-commerce API (Node.js + TypeScript)

## Stack
- Runtime: Node.js 20, TypeScript strict mode
- Framework: Fastify (KHÔNG dùng Express)
- DB: PostgreSQL via Prisma ORM
- Auth: JWT + refresh tokens
- Testing: Vitest, coverage > 80%

## Architecture
- Clean Architecture: domain / application / infrastructure
- Không để business logic trong route handlers
- Tất cả DB calls phải qua repository pattern
Phần 2: Coding conventions
Quy tắc cứng về naming, style, patterns.
## Conventions
- Naming: camelCase cho functions/vars, PascalCase cho types/classes
- Files: kebab-case (user-service.ts, không userService.ts)
- Error handling: custom error classes, không throw generic Error
- Async: async/await, tránh .then() chains
- Comments: chỉ comment "tại sao", không comment "cái gì"
Phần 3: Behaviors quan trọng
Điều khiển cách agent làm việc.
## Agent Behavior
- Trước khi implement: tóm tắt approach và hỏi confirm nếu thay đổi lớn
- Luôn viết unit tests cho function mới
- Nếu thấy bug ngoài scope task: comment TODO, không tự sửa
- Không thêm dependencies mới mà chưa hỏi
- Prefer immutability: const > let, readonly khi có thể
Phần 4: Prohibitions không bỏ qua
Danh sách tuyệt đối không làm.
## KHÔNG được
- Thay đổi database schema mà không có migration file
- Xóa hoặc rename public API endpoints
- Disable TypeScript strict checks
- Commit credentials, API keys vào code
- Dùng any type — dùng unknown nếu cần
Chia rules thành 4 phần: Context, Conventions, Behaviors, Prohibitions. Mỗi phần có mục đích riêng.
Công thức CARET cho mọi prompt
C Context — Tình huống hiện tại là gì?
A Action — Cần làm gì cụ thể?
R Result — Output mong muốn trông như thế nào?
E Examples/Exclusions — Ví dụ tốt và không muốn?
T Test criteria — Làm sao biết xong và đúng?
Ví dụ prompt tệ vs tốt
❌ Tệ:
Viết API endpoint tạo user
✅ Tốt (theo CARET):
Context: Đang build user management cho SaaS app.
Đã có: UserRepository (src/repositories/user.repo.ts),
AuthService (src/services/auth.service.ts)

Action: Tạo POST /users endpoint trong src/routes/users.ts

Result cần:
- Validate input: email (unique), password (min 8 chars), name
- Hash password qua AuthService.hashPassword()
- Lưu qua UserRepository.create()
- Return: { id, email, name, createdAt } (không return password)
- Error handling: 400 nếu validation fail, 409 nếu email đã tồn tại

Exclusion: Không tự tạo JWT, không implement login ở đây

Test: Viết test cho happy path + email duplicate + validation error
Kỹ thuật prompt nâng cao
Step-by-step thinking
Trước khi code, hãy:
1. List tất cả files cần đọc để hiểu context
2. Mô tả approach ngắn gọn
3. List potential side effects
4. Sau đó mới bắt đầu implement
Negative examples (quan trọng!)
Tạo config loader.

KHÔNG làm như này:
- if (env === 'production') { ... } else { ... }
- require('./config.json')
- process.env.MY_VAR || 'default'

Thay vào đó: centralized config object với Zod validation
Structured output request
Sau khi xong, trả lời theo format:

## Changes
- [file] [reason]

## Testing
- Lệnh để chạy test
- Expected output

## Potential issues
- Điều gì cần chú ý khi deploy?
Anchoring với existing code
Implement UserService tương tự cách ProductService
đã được implement trong @src/services/product.service.ts.
Giữ nguyên pattern dependency injection và error handling.
Đừng paste nguyên spec vào agent. Phải xử lý spec thành task có structure trước.
Bước 1: Phân tích spec
Đây là spec feature [tên feature]:
[paste spec]

Hãy phân tích và trả lời:
1. Danh sách acceptance criteria (numbered)
2. Danh sách technical tasks (ordered by dependency)
3. Files cần tạo mới / sửa
4. Potential risks và edge cases
5. Questions cần clarify trước khi code
Bước 2: Tạo task breakdown
# Feature: User Authentication

## Tasks (ordered)
1. [ ] Create User model + migration
2. [ ] Implement UserRepository
3. [ ] Implement AuthService (hash, jwt)
4. [ ] Create /register endpoint
5. [ ] Create /login endpoint
6. [ ] Create auth middleware
7. [ ] Protect existing routes
8. [ ] Integration tests

## Acceptance Criteria
- [ ] User có thể register với email/password
- [ ] Login trả về JWT valid 24h
- [ ] Token được verify ở protected routes
- [ ] Sai password trả về 401
Giữ task list trong TASKS.md. Agent tick khi xong. Session mới đọc file này.
Bước 3: Giao từng task
Thực hiện task #3 trong TASKS.md:
'Implement AuthService (hash, jwt)'

Đọc:
- @TASKS.md để biết context toàn dự án
- @src/types/user.types.ts để biết User type
- @src/config/index.ts để lấy JWT_SECRET

Khi xong: update TASKS.md, tick [x] vào task #3
Template: Feature spec đầy đủ
# Spec: [Tên feature]

## Overview
[1-2 câu mô tả]

## User story
As [người dùng], I want [action], so that [benefit]

## Functional requirements
- FR1: ...
- FR2: ...

## Non-functional requirements
- Performance: response time dưới 200ms
- Security: ...

## API Design (nếu có)
POST /api/endpoint
Request: { ... }
Response 200: { ... }

## Out of scope
- Những gì KHÔNG implement trong sprint này

## Definition of Done
- [ ] Unit tests viết xong
- [ ] Integration test pass
- [ ] Code review approved
Sub-agents = nhiều agent instances, mỗi cái chịu trách nhiệm một phần. Claude Code hỗ trợ spawning sub-agents.
Pattern 1: Parallel workers
Khi nào dùng
Tasks độc lập, không phụ thuộc nhau.
Spawn 3 sub-agents chạy song song:
Agent 1: Viết unit tests cho src/services/user.service.ts
Agent 2: Viết unit tests cho src/services/product.service.ts
Agent 3: Viết unit tests cho src/services/order.service.ts
Mỗi agent không cần đợi agent kia.
Pattern 2: Pipeline (sequential)
Khi nào dùng
Output của agent này là input của agent tiếp theo.
Agent 1 (Analyzer):
→ Đọc codebase, tạo ANALYSIS.md
→ Output: danh sách vấn đề + recommended fixes

Agent 2 (Implementer):
→ Đọc ANALYSIS.md
→ Implement fixes
→ Output: code changes + CHANGES.md

Agent 3 (Tester):
→ Đọc CHANGES.md
→ Viết/chạy tests cho code mới
→ Output: test report
Pattern 3: Orchestrator + Workers
Mô hình phức tạp nhất — dùng cho large tasks
Orchestrator agent:
- Nhận high-level task
- Break down thành sub-tasks
- Giao cho worker agents
- Collect results
- Resolve conflicts

Worker agents:
├── Worker-backend: API changes
├── Worker-frontend: UI changes
├── Worker-tests: test updates
└── Worker-docs: documentation
Viết shared context vào SHARED_CONTEXT.md. Orchestrator cập nhật, workers đọc.
Cẩn thận race conditions khi nhiều agents cùng edit 1 file. Thiết kế để mỗi agent "sở hữu" files riêng.
Pattern 1: Explore → Plan → Implement
Bước 1 — Explore (read-only)
"Đọc và tóm tắt: codebase structure,
conventions đang dùng, patterns lặp lại.
KHÔNG edit gì. Chỉ report."

Bước 2 — Plan
"Dựa trên exploration, propose implementation plan
cho [feature]. List files sẽ tạo/sửa."

Bước 3 — Implement
"Implement theo plan đã approve ở bước 2."
Giảm thiểu "surprise changes" — agent không tự ý làm những gì bạn không expect.
Pattern 2: TDD với agent
Bước 1 — Tests first
"Viết failing tests cho UserService.createUser().
Tests nên cover: happy path, duplicate email,
invalid data. Chưa implement logic."

Bước 2 — Make tests pass
"Implement UserService.createUser() để
tất cả tests pass. Không sửa test file."
Pattern 3: Incremental review
"Implement [task] theo từng bước nhỏ.
Sau mỗi bước, dừng lại và show diff.
Chờ tôi approve trước khi tiếp tục."
Tốn thời gian hơn nhưng safe hơn. Dùng cho task risk cao.
Pattern 4: Context handoff
"Tóm tắt session này vào HANDOFF.md:
- Task đã xong
- Task còn lại
- Decisions đã make và tại sao
- Files đã thay đổi
- Next steps cho session mới"
Session mới: "Đọc HANDOFF.md và tiếp tục từ đó."
Pattern 5: Debugging có cấu trúc
Bug report: [mô tả bug]
Error: [paste full error + stack trace]
Reproduction steps: [steps]
Expected vs actual: [...]

Hãy:
1. Hypothesize nguyên nhân (3-5 candidates)
2. Propose cách verify từng hypothesis
3. Sau khi tôi confirm, mới fix
Anti-patterns cần tránh
❌ Vague iteration
"Sửa lại cho đẹp hơn"
"Clean code này lên"
→ Agent không biết "đẹp" là gì
❌ God prompt
Một prompt làm mọi thứ: design DB + API + frontend + docs
→ Chất lượng từng phần đều tệ
❌ No verification
Accept code mà không run/test
→ Agent confident nhưng có thể sai
❌ Context starvation
Không cung cấp existing patterns
→ Agent tự phát minh convention

Tổng kết

  • Mindset shift: từ “autocomplete” sang “delegate task” — bạn là tech lead, agent là dev nhận việc.
  • 5 nguyên tắc vàng: specificity, constraints, think in tasks, trust but verify, invest in rules.
  • Rules file 4 phần: context → conventions → behaviors → prohibitions.
  • CARET formula: Context, Action, Result, Examples/Exclusions, Test.
  • Spec → Task: phân tích → breakdown → giao từng task. Không paste nguyên spec.
  • Sub-agents: parallel (tasks độc lập), pipeline (sequential), orchestrator (large tasks).
  • 5 patterns: Explore→Plan→Implement, TDD, incremental review, context handoff, structured debugging.
  • Anti-patterns: vague iteration, god prompt, no verification, context starvation.

Đọc thêm