Skip to main content

Agent模式

Agent模式是我用Claude Code最喜欢的功能之一。它不再只是被动回答问题,而是能主动思考、探索项目、制定计划并逐步执行。

这篇文章详细介绍Agent模式的工作原理和使用场景。

什么是Agent模式

传统对话模式 vs Agent模式

先看传统AI助手怎么工作的:

传统模式:

你: 帮我找到处理用户认证的代码
AI: 你可以在auth.js文件中查看
你: 认证逻辑在哪个函数?
AI: 应该在verifyToken函数中
你: 帮我添加刷新token的功能
AI: [等待你提供更多信息]

这种模式下,AI只能被动回答,每次都需要你明确指示下一步。

Agent模式:

你: 帮我添加刷新token的功能

Agent: I'll help you add refresh token functionality. Let me first explore
your authentication setup.

[Agent自主工作流程]
1. 探索项目结构
✓ Found auth middleware in src/middleware/auth.js
✓ Found JWT config in src/config/jwt.js
✓ Found User model in src/models/User.js

2. 分析现有认证逻辑
✓ Using JWT for access tokens (15min expiry)
✓ No refresh token mechanism currently
✓ Token stored in Authorization header

3. 设计实现方案
✓ Add refreshToken field to User model
✓ Create /auth/refresh endpoint
✓ Update login to return both tokens
✓ Add token rotation mechanism

4. 执行实现
✓ Modified User model
✓ Created refresh token endpoint
✓ Updated authentication middleware
✓ Added token cleanup logic

✓ Refresh token functionality has been implemented!

Next steps you might want:
- Add tests for refresh token flow
- Update API documentation
- Configure token expiry times

看到区别了吗?Agent模式下,Claude Code会:

  • 主动探索: 自己查找相关文件和代码
  • 自主分析: 理解现有架构和实现
  • 制定计划: 设计完整的实现方案
  • 执行任务: 逐步完成所有必要的修改
  • 提供建议: 主动提出后续优化方向

Agent的核心特征

1. 自主性(Autonomy)

Agent不需要你手把手指导每一步:

传统模式:
你: 创建一个API
AI: 好的,需要什么端点?
你: GET /users 和 POST /users
AI: 需要什么字段?
你: name, email, password
AI: 需要验证吗?
你: 是的
AI: 需要什么验证规则?
[...无穷无尽的来回...]

Agent模式:
你: 创建一个用户管理API,包含常见功能

Agent: I'll create a complete user management API for you.
[自主完成]
✓ RESTful endpoints (GET, POST, PUT, DELETE)
✓ Input validation with proper error messages
✓ Password hashing with bcrypt
✓ Email format validation
✓ Error handling middleware
✓ API documentation

2. 探索能力(Exploration)

Agent会主动探索项目环境:

  • 自动发现项目结构
  • 识别技术栈和框架
  • 找到相关配置文件
  • 理解代码依赖关系
  • 发现潜在问题

3. 规划能力(Planning)

Agent会在执行前制定详细计划:

Task: 重构数据库查询层

Agent Planning:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 Execution Plan

Phase 1: Discovery & Analysis
├─ Scan all database queries in the project
├─ Identify duplicate query patterns
├─ Find N+1 query problems
└─ Map query-to-file relationships

Phase 2: Design
├─ Design unified query builder interface
├─ Plan migration strategy
├─ Define error handling approach
└─ Design caching layer

Phase 3: Implementation
├─ Create base QueryBuilder class
├─ Refactor user queries
├─ Refactor product queries
├─ Refactor order queries
└─ Add caching mechanism

Phase 4: Validation
├─ Run existing tests
├─ Add new tests for QueryBuilder
└─ Performance benchmarking

Estimated impact: ~15 files, ~500 lines modified
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Proceed with execution? (yes/no)

4. 执行能力(Execution)

Agent会逐步执行计划并实时报告进度:

🤖 Executing Phase 1: Discovery & Analysis
├─ [1/4] Scanning database queries... ✓ Found 23 queries
├─ [2/4] Identifying patterns... ✓ Found 5 duplicate patterns
├─ [3/4] Analyzing N+1 problems... ✓ Found 3 instances
└─ [4/4] Mapping relationships... ✓ 12 files affected

🤖 Executing Phase 2: Design
├─ [1/4] Designing QueryBuilder... ✓ Interface defined
├─ [2/4] Planning migration... ✓ Strategy documented
├─ [3/4] Defining error handling... ✓ ErrorHandler created
└─ [4/4] Designing caching... ✓ Cache layer planned

🤖 Executing Phase 3: Implementation
[Working on user queries...]

如何启动和使用Agent

启动Agent模式

Agent模式有多种启动方式:

方式1:通过Slash命令启动

# 在Claude Code中输入
/agent 帮我重构认证模块,使其支持多种登录方式

方式2:使用agent命令行参数

# 启动时直接进入Agent模式
claude --agent

# 或者带任务启动
claude --agent "优化数据库查询性能"

方式3:自然语言触发

对于复杂任务,Claude Code会自动建议使用Agent模式:

你: 我需要将整个项目从JavaScript迁移到TypeScript

Claude: This is a complex task that would benefit from Agent mode.
Agent can autonomously:
- Analyze your entire codebase
- Create migration plan
- Convert files systematically
- Fix type errors
- Update configurations

Switch to Agent mode? (yes/no)

Agent的工作界面

启动Agent后,你会看到专门的Agent界面:

╔═══════════════════════════════════════════════════════════╗
║ AGENT MODE ACTIVE ║
║ ║
║ Status: Idle ║
║ Task: None ║
║ Files Monitored: 0 ║
║ Context: 2.5K / 200K tokens ║
╚═══════════════════════════════════════════════════════════╝

Agent Controls:
/pause - Pause agent execution
/resume - Resume agent execution
/stop - Stop current task
/status - Show detailed status
/plan - Show execution plan
/exit - Exit agent mode

Ready for task. What should I work on?

给Agent分配任务

简单任务描述

添加用户头像上传功能

Agent会自动扩展理解:

  • 需要文件上传API
  • 需要图片处理(裁剪、压缩)
  • 需要存储方案(本地/云存储)
  • 需要数据库字段更新
  • 需要前端上传组件

详细任务描述

我需要实现一个完整的评论系统:
1. 用户可以对文章发表评论
2. 支持评论回复(嵌套评论)
3. 支持点赞评论
4. 实时通知被回复的用户
5. 支持举报不当评论
6. 管理员可以审核和删除评论

问题导向型任务

用户反馈系统响应很慢,请帮我找出问题并优化

Agent会:

  1. 分析性能瓶颈
  2. 检查数据库查询
  3. 查看API响应时间
  4. 检查前端渲染
  5. 提出优化方案
  6. 实施改进

Agent的自主探索能力详解

项目结构探索

当你给Agent一个任务时,它首先会探索项目结构:

🔍 Exploring Project Structure...

📁 Project Analysis:
├─ Type: Node.js application
├─ Framework: Express.js
├─ Language: JavaScript (ES6+)
├─ Database: MongoDB with Mongoose
├─ Testing: Jest
└─ Package Manager: npm

📂 Directory Structure:
├─ src/
│ ├─ controllers/ (7 files)
│ ├─ models/ (5 files)
│ ├─ routes/ (8 files)
│ ├─ middleware/ (4 files)
│ ├─ utils/ (6 files)
│ └─ config/ (3 files)
├─ tests/ (12 files)
└─ public/ (static assets)

📊 Code Metrics:
├─ Total Files: 45
├─ Lines of Code: ~3,200
├─ Dependencies: 23
└─ Dev Dependencies: 15

🔗 Key Dependencies:
├─ express: ^4.18.0
├─ mongoose: ^7.0.0
├─ jsonwebtoken: ^9.0.0
└─ bcryptjs: ^2.4.3

智能文件发现

Agent会智能地找到相关文件:

Task: 添加邮件通知功能

🔍 Agent Discovery Process:

Step 1: Looking for existing email/notification code...
✓ No email service found
✓ Found notification mention in User model (line 45)

Step 2: Checking configuration files...
✓ Found config/index.js
✗ No email configuration present

Step 3: Analyzing dependencies...
✗ No email library installed
✓ Need to add nodemailer

Step 4: Identifying integration points...
✓ User registration (controllers/auth.js:56)
✓ Password reset (controllers/auth.js:123)
✓ Order creation (controllers/orders.js:78)

📋 Discovery Summary:
Files to create: 3 (email service, templates, config)
Files to modify: 4 (auth controller, orders, config, package.json)
Dependencies to add: 2 (nodemailer, email-templates)

代码依赖分析

Agent会分析代码之间的依赖关系:

🔍 Analyzing Dependencies for "refactor User authentication"

📊 Dependency Graph:
controllers/auth.js
├─ requires models/User.js
├─ requires middleware/validateInput.js
├─ requires utils/jwt.js
└─ requires utils/password.js

middleware/auth.js
├─ requires models/User.js
└─ requires utils/jwt.js

routes/auth.js
├─ requires controllers/auth.js
└─ requires middleware/auth.js

⚠️ Impact Analysis:
└─ Modifying utils/jwt.js will affect:
├─ controllers/auth.js (3 usage points)
├─ middleware/auth.js (2 usage points)
└─ controllers/admin.js (1 usage point)

💡 Recommendation:
Create new jwt.js with backward compatibility
Migrate usage points one by one
Remove old implementation last

问题识别

Agent会主动识别潜在问题:

🔍 Project Health Check...

⚠️ Issues Discovered:

Security Issues:
├─ [HIGH] Passwords stored in plain text (models/User.js:23)
├─ [HIGH] SQL injection risk (controllers/users.js:45)
└─ [MEDIUM] Missing rate limiting on auth routes

Performance Issues:
├─ [HIGH] N+1 query in getOrders (controllers/orders.js:67)
├─ [MEDIUM] No database indexing on email field
└─ [LOW] Large payload in /api/users response

Code Quality:
├─ [MEDIUM] Duplicate code in 3 controllers
├─ [LOW] Missing error handling in 5 async functions
└─ [LOW] Inconsistent naming conventions

Missing Features:
├─ No input validation on 4 routes
├─ No logging system
└─ No API documentation

Would you like me to address these issues?

Agent的规划和执行流程

任务分解

Agent会将复杂任务分解为可管理的子任务:

Task: 实现完整的博客系统

🎯 Task Breakdown:

EPIC: Blog System Implementation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Module 1: Data Layer ⏱️ ~30min
├─ Task 1.1: Create Post model
│ ├─ Define schema (title, content, author, tags, status)
│ ├─ Add timestamps and soft delete
│ └─ Create indexes

├─ Task 1.2: Create Comment model
│ ├─ Define schema with post reference
│ ├─ Support nested comments
│ └─ Add moderation status

└─ Task 1.3: Create Category model
├─ Define schema with hierarchy support
└─ Add slug generation

Module 2: API Layer ⏱️ ~45min
├─ Task 2.1: Post CRUD endpoints
│ ├─ GET /posts (with pagination, filtering)
│ ├─ GET /posts/:id
│ ├─ POST /posts (auth required)
│ ├─ PUT /posts/:id (auth + ownership check)
│ └─ DELETE /posts/:id (soft delete)

├─ Task 2.2: Comment endpoints
│ ├─ GET /posts/:id/comments
│ ├─ POST /posts/:id/comments
│ └─ DELETE /comments/:id

└─ Task 2.3: Category endpoints
├─ GET /categories
└─ POST /categories (admin only)

Module 3: Business Logic ⏱️ ~40min
├─ Task 3.1: Post publishing workflow
│ ├─ Draft/Published status
│ ├─ Scheduled publishing
│ └─ SEO optimization (meta tags, slug)

├─ Task 3.2: Search functionality
│ ├─ Full-text search
│ ├─ Tag-based filtering
│ └─ Category filtering

└─ Task 3.3: Analytics
├─ View counter
├─ Popular posts
└─ User activity tracking

Module 4: Testing ⏱️ ~35min
├─ Task 4.1: Model tests
├─ Task 4.2: API endpoint tests
└─ Task 4.3: Integration tests

Module 5: Documentation ⏱️ ~20min
├─ Task 5.1: API documentation
├─ Task 5.2: Setup guide
└─ Task 5.3: Architecture overview

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Total Estimated Time: ~2h 50min
Total Tasks: 20
Files to Create: ~25
Files to Modify: ~8
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Start execution? (yes/no/customize)

智能执行顺序

Agent会选择最优的执行顺序:

🎯 Optimizing Execution Order...

Original Plan Order: Task 1.1 → 1.2 → 1.3 → 2.1 → 2.2 → 2.3...

⚡ Optimized Execution Order:

Parallel Batch 1 (Independent tasks):
├─ Task 1.1: Create Post model
├─ Task 1.2: Create Comment model
└─ Task 1.3: Create Category model

Sequential Batch 2 (Depends on Batch 1):
├─ Task 2.1: Post CRUD endpoints
├─ Task 2.2: Comment endpoints
└─ Task 2.3: Category endpoints

Parallel Batch 3 (Can run together):
├─ Task 3.1: Publishing workflow
├─ Task 3.2: Search functionality
└─ Task 3.3: Analytics

Sequential Batch 4 (Needs working code):
├─ Task 4.1: Model tests
├─ Task 4.2: API tests
└─ Task 4.3: Integration tests

Final Task:
└─ Task 5: Documentation

💡 Optimization Results:
Original estimated time: 2h 50min
Optimized time: 1h 45min (38% faster)
Parallel tasks: 9
Sequential tasks: 11

实时进度报告

Agent会实时报告执行进度:

🚀 Executing Blog System Implementation

Overall Progress: ████████░░░░░░░░░░░░ 40% (8/20 tasks)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Module 1: Data Layer ✅ COMPLETED
├─ ✅ Task 1.1: Create Post model (2m 15s)
├─ ✅ Task 1.2: Create Comment model (1m 45s)
└─ ✅ Task 1.3: Create Category model (1m 30s)

Module 2: API Layer 🔄 IN PROGRESS
├─ ✅ Task 2.1: Post CRUD endpoints (4m 20s)
├─ ✅ Task 2.2: Comment endpoints (2m 55s)
└─ 🔄 Task 2.3: Category endpoints
Progress: [Step 3/5] Implementing GET /categories

✓ Created route file
✓ Implemented controller logic
⏳ Adding input validation...
⏺️ Pending: Error handling
⏺️ Pending: API documentation

Module 3: Business Logic ⏺️ PENDING
Module 4: Testing ⏺️ PENDING
Module 5: Documentation ⏺️ PENDING

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Files Modified: 12
Files Created: 8
Tests Passing: 23/23
Estimated Remaining Time: 1h 5min

Latest Changes:
├─ Modified: src/routes/categories.js
├─ Modified: src/controllers/categories.js
└─ Created: src/middleware/validateCategory.js

错误处理和恢复

当遇到错误时,Agent会智能处理:

❌ Error Encountered

Task: Task 2.3 - Implementing GET /categories
Error: Validation middleware test failed

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Error Details:
File: src/middleware/validateCategory.js
Line: 23
Issue: Schema validation not handling nested categories
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🤖 Agent Analysis:
Root Cause: Joi schema doesn't support recursive validation
Impact: Blocks category hierarchy feature

🔧 Agent Resolution Strategy:
Option 1: Use custom validation function ⭐ RECOMMENDED
├─ Pros: Full control, supports recursion
├─ Cons: More code
└─ Time: +5 minutes

Option 2: Flatten category structure
├─ Pros: Simple schema
├─ Cons: Loses hierarchy feature
└─ Time: +10 minutes (requires model change)

Option 3: Use different validation library
├─ Pros: Built-in recursion support
├─ Cons: New dependency
└─ Time: +15 minutes

🎯 Agent Decision: Proceeding with Option 1

🔄 Retrying Task 2.3 with new approach...
✓ Created custom recursive validator
✓ Updated middleware
✓ Added tests for nested categories
✓ All tests passing (26/26)

✅ Task 2.3 Completed (with error recovery)

监控和控制Agent的工作过程

实时监控

Agent提供多种监控方式:

1. 状态查看

/status

Agent Status Dashboard
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Current Task: Implementing search functionality
Status: ACTIVE ⚡
Started: 14:23:45
Running Time: 8m 32s

Resources:
├─ CPU Usage: 45%
├─ Memory: 1.2 GB / 8 GB
├─ Context Tokens: 45,231 / 200,000
└─ Files Open: 12

Active Operations:
├─ Reading: src/services/search.js
├─ Writing: src/controllers/search.js
└─ Testing: Running search tests

Recent Activity (last 1 minute):
├─ 14:31:45 - Created search index
├─ 14:31:32 - Modified Post model
├─ 14:31:18 - Installed elasticsearch client
└─ 14:31:05 - Updated package.json

2. 详细日志

/logs --verbose

Agent Execution Log
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

[14:23:45] INFO Starting task: Implement search functionality
[14:23:46] DEBUG Analyzing project structure
[14:23:47] DEBUG Found 23 searchable fields across 3 models
[14:23:48] INFO Planning search implementation
[14:23:49] DEBUG Considering options:
- MongoDB text search
- Elasticsearch
- Algolia
[14:23:50] INFO Selected: Elasticsearch (best for scalability)
[14:23:51] DEBUG Installing elasticsearch client
[14:24:02] INFO Package installed: @elastic/elasticsearch@8.0.0
[14:24:03] DEBUG Creating search service
[14:24:15] INFO Created: src/services/search.js (125 lines)
[14:24:16] DEBUG Implementing index creation
[14:24:28] INFO Created search index with mappings
[14:24:29] DEBUG Updating Post model
[14:24:35] INFO Added search hooks to Post model
[14:24:36] DEBUG Creating search controller
[14:24:48] INFO Created: src/controllers/search.js (89 lines)

3. 文件变更追踪

/changes

File Changes Tracker
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Modified Files (8):
├─ src/models/Post.js
│ ├─ +15 lines (search index hooks)
│ └─ Last change: 2 min ago

├─ src/services/search.js [NEW]
│ ├─ +125 lines
│ └─ Created: 8 min ago

├─ src/controllers/search.js [NEW]
│ ├─ +89 lines
│ └─ Created: 4 min ago

└─ package.json
├─ +1 dependency
└─ Last change: 9 min ago

Pending Changes (not committed):
Total: +12 files, +456 lines, -23 lines

View diff? (yes/no)

控制Agent执行

暂停和恢复

# 暂停Agent
/pause

⏸️ Agent Paused

Current State:
├─ Task: Creating search tests
├─ Progress: 67% complete
└─ Safe to pause: ✅ Yes

State saved. You can:
├─ Review current changes
├─ Ask questions
├─ Modify the plan
└─ /resume when ready

──────────────────────────────────────

# 在暂停期间查看进度
你: 你现在做到哪里了?

Agent: I've completed the search service implementation and
I'm currently creating tests. So far:

✅ Completed:
- Elasticsearch client setup
- Search service with full-text search
- Search controller with filtering
- API routes for search

🔄 In Progress:
- Writing tests for search service (67%)

⏺️ Pending:
- API endpoint tests
- Integration tests
- Documentation

你: 可以先添加分页功能吗?

Agent: Sure! I'll add pagination to the search results before
continuing with tests.

# 恢复执行
/resume

▶️ Agent Resumed

Modified plan:
↻ Insert: Add pagination to search (before tests)

Continuing execution...

调整计划

/plan

Current Execution Plan
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

✅ 1. Setup Elasticsearch client
✅ 2. Create search service
✅ 3. Implement search controller
🔄 4. Create search tests (IN PROGRESS)
⏺️ 5. Create API tests
⏺️ 6. Integration tests
⏺️ 7. Add documentation

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Modify plan? Available commands:
/skip [task] - Skip a task
/add [task] - Add new task
/reorder - Change task order
/priority - Reprioritize tasks

──────────────────────────────────────

/add "Add pagination support" --before "Create search tests"

✅ Plan Updated

New plan:
✅ 1. Setup Elasticsearch client
✅ 2. Create search service
✅ 3. Implement search controller
⏺️ 4. Add pagination support [NEW]
🔄 5. Create search tests
⏺️ 6. Create API tests
⏺️ 7. Integration tests
⏺️ 8. Add documentation

介入和纠正

Agent: Creating user authentication with JWT...

[Agent working...]

你: 等等,我们用的是session-based认证,不是JWT

Agent: ⏸️ Paused automatically

I apologize for the misunderstanding. Let me adjust:

Current work:
❌ Discarding JWT implementation
✓ Preserving reusable code (validation, etc.)

New approach:
✓ Use express-session
✓ Redis for session storage
✓ Maintain similar API structure

Should I:
1. Start fresh with session-based auth
2. Convert JWT code to session-based
3. Show you both approaches for comparison

你的选择?

停止执行

/stop

⏹️ Stopping Agent...

Safely stopping current operations:
├─ ✓ Completed current file write
├─ ✓ Saved all buffers
├─ ✓ Cancelled pending operations
└─ ✓ Cleaned up temporary files

Work Summary:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Tasks Completed: 5/10
Files Modified: 8
Time Spent: 23 minutes

Completed Tasks:
✅ Setup Elasticsearch client
✅ Create search service
✅ Implement search controller
✅ Add pagination
✅ Create basic tests

Incomplete Tasks:
⏺️ API endpoint tests
⏺️ Integration tests
⏺️ Performance optimization
⏺️ Documentation
⏺️ Error handling improvements

All changes are saved. You can:
├─ Review changes: git diff
├─ Resume later: /agent --resume
└─ Or start new task: /agent [new task]

Agent模式的最佳使用场景

1. 大规模重构

Agent模式最擅长处理需要修改多个文件的重构任务:

任务:将项目从CommonJS迁移到ES Modules

为什么适合Agent模式:
✅ 需要修改所有.js文件(50+文件)
✅ 需要更新import/export语句
✅ 需要修改package.json配置
✅ 需要处理依赖关系
✅ 需要确保所有功能正常

Agent的工作流程:
1. 扫描所有JS文件,分析依赖关系
2. 创建迁移计划,确定转换顺序
3. 逐文件转换,处理边缘情况
4. 更新配置文件
5. 运行测试确保无破坏性更改
6. 生成迁移报告

人工需要:2-3天
Agent完成:30-45分钟

2. 复杂功能开发

多模块、多文件的功能实现:

任务:实现完整的权限系统(RBAC)

为什么适合Agent模式:
✅ 涉及多个层面(数据库、后端、中间件)
✅ 需要创建多个文件
✅ 需要修改现有文件
✅ 需要集成到现有系统
✅ 需要全面的测试

Agent的优势:
- 自动规划完整架构
- 并行创建独立模块
- 自动处理文件间依赖
- 集成时自动调整现有代码
- 自动生成测试用例

3. 代码质量提升

系统性地改进代码质量:

任务:提升项目代码质量和安全性

Agent的执行计划:
Phase 1: 分析
├─ 扫描所有代码
├─ 识别安全漏洞
├─ 发现性能问题
├─ 检查代码异味
└─ 生成优先级列表

Phase 2: 修复
├─ 修复安全漏洞(高优先级)
├─ 优化性能瓶颈
├─ 重构重复代码
├─ 添加错误处理
└─ 统一代码风格

Phase 3: 增强
├─ 添加输入验证
├─ 改进错误消息
├─ 添加日志记录
├─ 更新文档
└─ 添加测试覆盖

完全自动化,无需手动干预

4. 技术栈迁移

从一个技术栈迁移到另一个:

任务:从Vue 2升级到Vue 3

为什么需要Agent:
✅ 语法变化多(Options API → Composition API)
✅ 影响所有组件文件(40+文件)
✅ 需要更新依赖和配置
✅ 需要处理破坏性更改
✅ 需要验证功能完整性

Agent的处理:
1. 分析Vue 2代码模式
2. 创建组件迁移策略
3. 自动转换组件语法
4. 更新所有依赖
5. 处理破坏性API更改
6. 运行测试并修复问题
7. 生成迁移文档

5. Bug追踪和修复

复杂的bug需要跨文件追踪:

任务:修复"用户数据偶尔不同步"的bug

为什么适合Agent:
✅ 需要追踪数据流
✅ 可能涉及多个文件
✅ 需要分析异步逻辑
✅ 需要检查所有更新点
✅ 需要添加防御性代码

Agent的调试流程:
1. 分析用户数据的所有写入点
2. 追踪数据流经的所有文件
3. 识别可能的竞态条件
4. 检查缓存一致性
5. 发现根本原因
6. 实施修复
7. 添加测试防止复发

6. 文档和测试生成

系统性地补充文档和测试:

任务:为整个项目添加完整的测试和文档

Agent的优势:
✅ 理解所有代码功能
✅ 生成全面的测试用例
✅ 创建准确的API文档
✅ 添加代码注释
✅ 生成使用示例

Agent的执行:
- 为每个函数生成单元测试
- 为每个API端点生成集成测试
- 创建API文档(OpenAPI/Swagger)
- 添加JSDoc/TypeDoc注释
- 生成README和使用指南
- 创建架构图和流程图

Agent的限制和注意事项

技术限制

1. 上下文窗口限制

⚠️  Context Limit Warning

Current Usage: 185,420 / 200,000 tokens (93%)

Large projects may exceed context limits.

Recommendations:
├─ Work on specific modules separately
├─ Use /focus to narrow scope
├─ Clear old conversations
└─ Split large tasks into phases

Agent will automatically:
├─ Summarize old context
├─ Keep relevant information
└─ Warn before limit

2. 执行时间限制

⚠️  Long-Running Task Detected

Current task running: 45 minutes
Estimated remaining: 2 hours

Recommendations:
├─ Consider breaking into smaller tasks
├─ Review and approve intermediate results
├─ Save progress regularly
└─ Use background mode for very long tasks

Background mode available:
claude --agent --background "task description"
(Get notified when complete)

3. 文件系统限制

⚠️  File System Limitations

Agent cannot:
├─ ❌ Access files outside project directory
├─ ❌ Modify system files
├─ ❌ Execute arbitrary system commands
└─ ❌ Access network resources directly

Agent can:
├─ ✅ Read/write project files
├─ ✅ Run project scripts (npm, git)
├─ ✅ Install packages
└─ ✅ Run tests and builds

使用注意事项

1. 代码审查必不可少

⚠️  IMPORTANT: Always Review Agent Changes

虽然Agent很智能,但你仍需:

必须做:
├─ ✅ Review all generated code
├─ ✅ Test functionality thoroughly
├─ ✅ Check for security issues
├─ ✅ Verify performance
└─ ✅ Ensure code quality

建议工作流:
1. Let Agent complete task
2. Review changes: git diff
3. Run tests: npm test
4. Manual testing for critical features
5. Request improvements if needed
6. Commit approved changes

Remember: Agent是助手,不是替代

2. 敏感操作需要确认

Agent会自动请求确认敏感操作:

🛡️ Confirmation Required

Action: Delete 15 files
Reason: Cleaning up old migration files

Files to delete:
├─ migrations/old/2021/*.js (12 files)
└─ migrations/backup/*.js (3 files)

⚠️ This action cannot be undone!

Options:
├─ [y] Proceed with deletion
├─ [n] Cancel operation
├─ [r] Review file list first
└─ [b] Create backup first

Your choice:

3. 版本控制很重要

💡 Best Practice: Use Git with Agent

Recommended workflow:

Before starting:
git checkout -b feature/agent-work
git commit -am "Save current state"

During Agent work:
# Agent auto-commits at checkpoints
# Or manually: /checkpoint "description"

After completion:
git diff main # Review changes
npm test # Verify functionality
git commit -am "Agent: [task]" # Final commit
git checkout main # Switch back
git merge feature/agent-work # Merge if satisfied

If something goes wrong:
git reset --hard HEAD~1 # Undo last commit
git checkout main # Abandon branch

4. 清晰的任务边界

✅ 好的任务描述:
"在用户认证模块中添加两步验证功能,
包括TOTP支持、备用码、QR码生成,
并添加相应的API端点和测试"

明确了:
├─ 范围:用户认证模块
├─ 功能:两步验证
├─ 技术:TOTP
├─ 输出:API + 测试
└─ 边界:清晰

❌ 不好的任务描述:
"改进安全性"

问题:
├─ 范围不明确
├─ 目标太宽泛
├─ 没有具体方向
└─ 难以评估完成度

Agent会请求澄清:

🤔 Need More Information

"Improve security" is too broad. Could you specify:

1. Which aspect of security?
├─ Authentication?
├─ Authorization?
├─ Data protection?
├─ API security?
└─ Input validation?

2. What level of improvement?
├─ Fix critical vulnerabilities?
├─ Meet compliance standards?
├─ Follow best practices?
└─ Implement specific features?

3. Any specific concerns or requirements?

性能考虑

Token使用优化

💡 Optimizing Token Usage

大型项目的建议:

策略1:模块化工作
claude --agent "Focus on auth module only"
# 完成后
claude --agent "Focus on payment module"

策略2:使用/focus命令
/focus src/auth/**
/agent "Refactor authentication"

策略3:清理上下文
/clear-history # 清理旧对话
/summarize # 总结并压缩上下文

Token节省对比:
完整项目扫描: ~150K tokens
模块化工作: ~30K tokens per module
使用/focus: ~20K tokens

执行效率优化

💡 Improving Agent Efficiency

策略1:提供足够上下文
❌ "添加缓存"
✅ "使用Redis为用户API添加缓存,
TTL 5分钟,缓存键格式user:{id}"

策略2:利用并行执行
# Agent会自动并行化独立任务
"创建Post、Comment、Like三个模型"
→ Agent并行创建,节省时间

策略3:提供示例
"按照User模型的风格创建Product模型"
→ Agent复用模式,减少探索时间

策略4:增量任务
分步骤比一次性更高效:
1. "创建基础模型"
2. "添加验证逻辑"
3. "添加业务方法"
4. "添加测试"

实际使用案例

案例1:电商平台大重构

项目背景:
- 老旧电商系统,3年历史
- 20+ 开发者贡献过
- 代码不一致,技术债务多
- 需要现代化改造

重构目标:
1. 统一API风格(RESTful)
2. 添加TypeScript类型
3. 重构数据库查询层
4. 添加全面测试
5. 优化性能

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

使用Agent模式执行:

🎯 Phase 1: Analysis & Planning (Day 1, 2 hours)

/agent "分析项目并创建重构计划"

Agent Output:
├─ 分析了 156 个文件
├─ 识别了 8 种不同的API模式
├─ 发现 23 个性能问题
├─ 发现 15 个安全问题
└─ 生成详细重构计划

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🎯 Phase 2: API Standardization (Day 1-2, 6 hours)

/agent "统一所有API端点为RESTful风格"

Agent执行:
├─ 重构 45 个API端点
├─ 统一错误响应格式
├─ 添加请求验证
├─ 更新API文档
└─ 确保向后兼容

人工工作量估计:3-4天
Agent完成时间:6小时

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🎯 Phase 3: TypeScript Migration (Day 3-4, 12 hours)

/agent "将项目迁移到TypeScript"

Agent执行:
├─ 配置TypeScript环境
├─ 转换 156 个JS文件
├─ 添加类型定义
├─ 修复类型错误
├─ 更新构建脚本
└─ 确保100%编译通过

人工工作量估计:1-2周
Agent完成时间:12小时

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🎯 Phase 4: Database Query Optimization (Day 5, 8 hours)

/agent "重构数据库查询层,解决N+1问题"

Agent执行:
├─ 识别所有N+1查询(找到18处)
├─ 创建统一查询构建器
├─ 添加查询缓存层
├─ 优化关联查询
├─ 添加数据库索引
└─ 性能提升65%

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🎯 Phase 5: Test Coverage (Day 6-7, 10 hours)

/agent "为整个项目添加全面测试"

Agent执行:
├─ 创建 234 个单元测试
├─ 创建 67 个集成测试
├─ 创建 23 个E2E测试
├─ 测试覆盖率:87%
└─ 所有测试通过

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📊 总体结果:

时间对比:
├─ 预估人工时间:6-8周
├─ 实际Agent时间:7天
└─ 效率提升:80%+

质量提升:
├─ 代码一致性:100%
├─ 类型安全:完整TypeScript
├─ 测试覆盖:87%
├─ 性能提升:65%
└─ 安全问题:全部修复

团队反馈:
"Agent在一周内完成了我们需要2个月的工作,
而且质量和一致性都很好。这让我们能专注于新功能开发。"

案例2:开源项目贡献加速

场景:为大型开源项目贡献新功能

项目:某流行的Node.js框架
任务:添加WebSocket支持
挑战:
├─ 陌生的代码库(10万+行代码)
├─ 严格的代码规范
├─ 需要全面测试
└─ 需要文档和示例

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🎯 Step 1: 项目理解 (30分钟)

/agent "分析项目架构,理解网络层实现"

Agent输出:
├─ 项目架构图
├─ 核心模块说明
├─ 现有HTTP实现分析
├─ WebSocket集成点建议
└─ 潜在冲突识别

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🎯 Step 2: 实现WebSocket (2小时)

/agent "参照现有HTTP实现的风格,添加WebSocket支持"

Agent自动:
├─ 遵循项目代码风格
├─ 使用项目约定的模式
├─ 集成现有中间件系统
├─ 添加错误处理
└─ 实现连接管理

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🎯 Step 3: 测试 (1.5小时)

/agent "按照项目测试标准添加WebSocket测试"

Agent创建:
├─ 单元测试(遵循项目模式)
├─ 集成测试
├─ 连接管理测试
├─ 错误场景测试
└─ 性能测试

测试覆盖:95%

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🎯 Step 4: 文档 (1小时)

/agent "创建WebSocket文档和示例"

Agent生成:
├─ API文档(符合项目风格)
├─ 使用示例
├─ 迁移指南
├─ 最佳实践
└─ FAQ

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

📊 成果:

PR状态:一次通过所有CI检查
维护者反馈:"这是我见过最完整的PR之一"
合并时间:2天(通常需要几周)

工作量对比:
├─ 传统方式:2-3周
├─ Agent辅助:5小时
└─ 代码质量:优于平均水平

案例3:紧急Bug修复

场景:生产环境严重性能问题

问题:API响应时间从200ms飙升到5秒
影响:所有用户
压力:需要立即修复

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

🚨 Emergency Response with Agent

09:00 - 问题发现

09:05 - 启动Agent诊断

/agent "紧急:分析API性能问题,响应时间从200ms到5秒"

Agent立即开始:
├─ 扫描所有API端点
├─ 分析数据库查询
├─ 检查缓存命中率
├─ 查看最近代码更改
└─ 监控资源使用

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

09:08 - Agent发现问题

🔍 Root Cause Identified:

Issue: N+1 query in getUserOrders endpoint
Location: src/controllers/orders.js:145
Introduced: 2 hours ago (commit a3f9c2)
Impact: Each user order triggers separate query
Load: 10 queries → 1000+ queries per request

Performance Impact:
├─ Database: 4.2s (was 50ms)
├─ Network: 0.6s
├─ Processing: 0.2s
└─ Total: ~5s (was 200ms)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

09:10 - Agent提供修复方案

🔧 Proposed Solutions:

Option 1: Quick Fix (5 min) ⭐ RECOMMENDED
├─ Use .populate() for eager loading
├─ Impact: Immediate 90% improvement
└─ Risk: Low

Option 2: Comprehensive (30 min)
├─ Implement query optimization
├─ Add caching layer
├─ Impact: 95% improvement + future-proof
└─ Risk: Medium (more changes)

Emergency situation: Recommend Option 1

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

09:12 - 批准快速修复

你: 执行Option 1,但也准备Option 2的方案

Agent:
✓ Implementing quick fix...
✓ Modified orders.js with populate
✓ Tested locally: 4.8s → 180ms ✅
✓ Running full test suite...
✓ All tests passing (234/234)
✓ Ready for deployment

Also preparing comprehensive solution:
✓ Created feature branch
✓ Implementing caching layer
✓ Will be ready for review in 25min

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

09:15 - 部署修复

09:18 - 性能恢复正常

09:40 - Agent完成长期方案

📊 Incident Summary:

Problem detected: 09:00
Root cause found: 09:08 (8 min)
Fix deployed: 09:15 (15 min)
Normal service: 09:18 (18 min)

Long-term solution ready: 09:40 (40 min)

Impact:
├─ Downtime: 18 minutes
├─ Users affected: ~500
└─ Data loss: None

Prevention:
├─ Added query performance tests
├─ Implemented monitoring alerts
├─ Created optimization guidelines
└─ Scheduled team review

Traditional Response Time: 2-4 hours
Agent-Assisted Response: 18 minutes

总结

Agent模式代表了AI辅助编程的未来方向。它不只是工具,更像是一个能独立思考、自主行动的编程伙伴。

Agent模式的核心价值

  1. 自主性: 不需要手把手指导,自己探索和解决问题
  2. 智能性: 理解复杂任务,制定合理方案
  3. 高效性: 并行处理,大幅提升开发效率
  4. 可靠性: 系统化工作,减少遗漏
  5. 可控性: 全程透明,随时可以介入

何时使用Agent模式

推荐用:

  • 大规模重构
  • 复杂功能开发
  • 技术栈迁移
  • 代码质量提升
  • 系统性问题修复

不推荐用:

  • 简单的单文件修改
  • 需要创造性设计的任务
  • 高度定制化的逻辑
  • 需要深度领域知识的任务

最佳实践

  1. 明确任务边界: 清晰描述目标和范围
  2. 保持监控: 关注Agent的执行过程
  3. 及时介入: 发现问题立即纠正
  4. 代码审查: 始终审查Agent生成的代码
  5. 版本控制: 配合Git使用,方便回滚
  6. 循序渐进: 从小任务开始,逐步增加复杂度
  7. 提供反馈: 帮助Agent理解你的偏好

展望未来

随着AI能力的提升,Agent模式会变得更强大:

  • 更好的代码理解能力
  • 更智能的决策能力
  • 更长的上下文窗口
  • 更快的执行速度
  • 更丰富的集成能力

但无论技术怎么进步,Agent始终是助手,不是替代。最好的开发实践是把Agent的效率和人类的创造力、判断力结合起来,实现1+1>2的协作效果。

下一步学习

开始使用Agent模式,体验真正的AI辅助编程吧!