Chuyển đến nội dung chính

Bài 6: Plan Agent — Lập kế hoạch trước khi code

Plan Agent workflow: analyze → plan → hand off. Tạo structured implementation plan, review và điều chỉnh plan, hand off sang Agent mode để thực thi. Best practices cho planning complex features. So sánh plan-first vs code-first.

💻 Lập trình — Bài 6 Bài 6: Plan Agent — Lập kế hoạch trước khi code

Vibe Coding với GitHub Copilot: Từ Cơ bản đến Nâng cao

Phần 2: Agent Mode — AI tự động viết code

xdev.asia

1. Tại sao cần Plan trước khi Code?

Một trong những sai lầm phổ biến nhất khi Vibe Coding là nhảy thẳng vào code mà không có plan. Kết quả thường là:

  • Agent đi sai hướng, phải redo từ đầu
  • Code structure không phù hợp cho scale
  • Thiếu edge cases quan trọng
  • Tốn nhiều iterations (và tokens/requests)

Plan Agent giải quyết vấn đề này bằng cách tách riêng giai đoạn planning và implementation.

2. Plan Agent Workflow

┌─────────────────────────────────────────────────┐
│            PLAN-FIRST WORKFLOW                   │
├─────────────────────────────────────────────────┤
│                                                  │
│  1. 📝 USER: Mô tả feature/task                 │
│           ↓                                      │
│  2. 🔍 PLAN AGENT: Phân tích codebase           │
│     - Đọc files liên quan                       │
│     - Hiểu architecture hiện tại                │
│     - Hỏi clarifying questions nếu cần          │
│           ↓                                      │
│  3. 📋 PLAN AGENT: Tạo implementation plan      │
│     - Step-by-step tasks                        │
│     - Files cần tạo/sửa                         │
│     - Dependencies cần install                  │
│     - Potential risks/trade-offs                │
│           ↓                                      │
│  4. 👀 USER: Review + điều chỉnh plan           │
│           ↓                                      │
│  5. 🚀 HAND OFF: Plan → Agent để implement      │
│                                                  │
└─────────────────────────────────────────────────┘

3. Sử dụng Plan Agent

Bước 1: Chọn Plan Agent

Trong Chat view, chọn "Plan" từ agent dropdown.

Bước 2: Mô tả task

I want to add a real-time notification system to our Express.js app.
Requirements:
- WebSocket-based (Socket.IO)
- Notification types: info, warning, error, success
- Persist notifications in PostgreSQL
- Mark as read/unread
- Bell icon with unread count badge
- Dropdown showing recent notifications
- API endpoints for CRUD operations
- Only authenticated users receive notifications

Bước 3: Plan Agent phân tích và trả về plan

Plan Agent sẽ tạo một structured plan như:

## Implementation Plan: Real-time Notification System

### Phase 1: Database & Models
1. Create `notifications` table migration
   - Fields: id, user_id, type, title, message, is_read, created_at
2. Create Notification model (Sequelize/Prisma)
3. Add relations to User model

### Phase 2: Backend API
4. Install socket.io dependency
5. Create NotificationService (create, getByUser, markAsRead, delete)
6. Create NotificationController with REST endpoints
   - GET /api/notifications (with pagination)
   - PATCH /api/notifications/:id/read
   - DELETE /api/notifications/:id
7. Add authentication middleware to notification routes

### Phase 3: WebSocket Integration
8. Setup Socket.IO server alongside Express
9. Implement auth for WebSocket connections (JWT verification)
10. Create room-per-user pattern for targeted notifications
11. Emit events on notification create/update

### Phase 4: Frontend Components
12. Create NotificationBell component (badge with unread count)
13. Create NotificationDropdown component
14. Setup Socket.IO client with auto-reconnect
15. Add toast notifications for new incoming notifications

### Trade-offs & Risks:
- Socket.IO adds complexity; consider SSE for simpler use case
- Need Redis adapter for multi-server deployment
- Consider rate limiting notification creation

Bước 4: Review và điều chỉnh

Bạn có thể respond:

Good plan! But let's make these changes:
- Use Prisma instead of Sequelize
- Add a Phase 0 with unit test setup
- Skip the toast notifications for now
- Add rate limiting in Phase 2

Bước 5: Hand off sang Agent

Khi plan OK, chọn hand off to Agent. Agent sẽ thực thi plan step-by-step, và bạn có thể theo dõi progress trong session.

4. Plan cho các scenarios khác nhau

4.1. New Feature

Plan adding OAuth2 social login (Google, GitHub) to our Next.js app.
We currently use JWT with email/password auth.
Consider: NextAuth.js vs custom implementation.

4.2. Refactoring

Plan migrating our REST API from Express.js to Fastify.
Current codebase has 15 route files, 8 middleware, Sequelize ORM.
We want zero downtime migration — propose a phased approach.

4.3. Bug Investigation

Plan debugging this issue: Users report that their session expires
randomly after 10-15 minutes, even though token expiry is set to 24h.
Analyze our auth flow and create a debugging plan.

4.4. Architecture Decision

Plan the data layer for our e-commerce app. Compare these options:
1. PostgreSQL + Prisma
2. MongoDB + Mongoose
3. PostgreSQL + Drizzle ORM
Consider: our team knows SQL, we need transactions, Vercel deployment.

5. Plan-First vs Code-First

Tiêu chí Plan-First Code-First (Agent trực tiếp)
Khi nào dùng Tasks phức tạp, multi-file, ảnh hưởng architecture Tasks đơn giản, single feature, well-defined
Thời gian setup Lâu hơn (plan + review) Nhanh (code ngay)
Chất lượng output Cao hơn, ít phải redo Tùy thuộc prompt quality
Rủi ro Thấp (catch issues sớm) Cao hơn (có thể sai hướng)
Token efficiency Tốt hơn (ít iterations) Có thể tốn nhiều iterations

Rule of thumb:

  • Task < 30 phút → Code-First (Agent mode trực tiếp)
  • Task > 30 phút hoặc ảnh hưởng nhiều files → Plan-First
  • Migration hoặc refactoring → Luôn Plan-First

6. Tips để Plan hiệu quả

  • Cung cấp context đầy đủ: tech stack, conventions hiện tại, constraints
  • Nêu rõ trade-offs bạn đã biết: giúp Plan Agent focus vào quyết định đúng
  • Yêu cầu phân tích risks: "What could go wrong?" hoặc "What are the edge cases?"
  • Hỏi về alternatives: "Compare approach A vs B" trước khi commit
  • Review plan kỹ trước hand off: sửa plan dễ hơn sửa code đã implement

7. Bài tập thực hành

  1. Mở Chat view → chọn Plan agent
  2. Prompt: "Plan building a markdown blog engine with: file-based posts, tags, categories, search, RSS feed, dark mode. Use Next.js 15 and Tailwind."
  3. Review plan từ Plan Agent
  4. Yêu cầu điều chỉnh ít nhất 2 điểm
  5. Hand off sang Agent để implement Phase 1

8. Tổng kết

Plan Agent là "kiến trúc sư" — nó giúp bạn tư duy trước khi hành động. Trong series này, chúng ta sẽ dùng Plan-First approach cho tất cả dự án thực chiến ở Phần 5.

Workflow Steps
Plan-First Describe → Plan → Review → Adjust → Hand off → Implement
Code-First Describe → Implement → Review → Iterate

Bài tiếp theo sẽ cover Cloud Agent & Copilot CLI — cách chạy agent ở mọi nơi: local, background, cloud, và qua pull requests.