项目实战:全流程开发

实战场景:用 Hermes Agent 开发一个 Web 应用

本章将通过一个完整的实战项目,展示如何利用 Hermes Agent 完成从需求分析到部署上线的全流程开发。我们将开发一个"技术博客平台",包含文章管理、用户认证、评论系统和标签分类等功能模块。

这个实战案例将完整展示 Hermes Agent 在整个软件开发生命周期中的能力和工作方式。

需求分析阶段:Agent 如何理解需求

第一步:向 Agent 描述项目愿景

hermes-agent "我想开发一个技术博客平台,核心需求如下:
1. 用户注册和登录(JWT 认证)
2. 文章的 CRUD 操作(支持 Markdown)
3. 文章分类和标签系统
4. 读者评论功能
5. 搜索和分页
6. 管理后台(用户管理、文章审核)
请先帮我进行需求分析,输出功能列表和技术栈建议"

Agent 的反馈

Hermes Agent 会分析需求并输出结构化的分析结果:

## 需求分析报告

### 功能模块划分
| 模块 | 优先级 | 复杂度 | 估算工时 |
|------|--------|--------|----------|
| 用户认证 | P0 | 中 | 4h |
| 文章管理 | P0 | 高 | 8h |
| 评论系统 | P1 | 中 | 4h |
| 标签分类 | P1 | 低 | 2h |
| 搜索分页 | P1 | 中 | 3h |
| 管理后台 | P2 | 高 | 6h |

### 推荐技术栈
- **前端**: Next.js 14 + Tailwind CSS + shadcn/ui
- **后端**: Next.js API Routes(全栈方案)
- **数据库**: PostgreSQL + Prisma ORM
- **认证**: NextAuth.js
- **部署**: Docker + Vercel

架构设计阶段:Agent 生成技术方案

在确认需求后,Agent 会进一步生成详细的技术方案和项目结构。

// Agent 生成的项目目录结构
project/
├── prisma/
│   ├── schema.prisma          # 数据库模型
│   └── migrations/
├── src/
│   ├── app/
│   │   ├── api/
│   │   │   ├── auth/          # 认证接口
│   │   │   ├── posts/         # 文章接口
│   │   │   └── comments/      # 评论接口
│   │   ├── posts/             # 文章页面
│   │   ├── admin/             # 管理后台
│   │   └── layout.tsx
│   ├── components/
│   │   ├── ui/                # 通用 UI 组件
│   │   ├── posts/             # 文章相关组件
│   │   └── comments/          # 评论相关组件
│   ├── lib/
│   │   ├── auth.ts            # 认证逻辑
│   │   ├── prisma.ts          # 数据库客户端
│   │   └── markdown.ts        # Markdown 渲染
│   └── types/
│       └── index.ts
├── public/                    # 静态资源
├── docker-compose.yml         # Docker 编排
├── Dockerfile
└── package.json

数据库模型设计

Agent 会自动生成 Prisma schema:

model User {
  id        String    @id @default(cuid())
  name      String
  email     String    @unique
  password  String
  role      Role      @default(USER)
  posts     Post[]
  comments  Comment[]
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
}

model Post {
  id         String     @id @default(cuid())
  title      String
  content    String
  excerpt    String?
  slug       String     @unique
  published  Boolean    @default(false)
  authorId   String
  author     User       @relation(fields: [authorId], references: [id])
  tags       Tag[]
  comments   Comment[]
  createdAt  DateTime   @default(now())
  updatedAt  DateTime   @updatedAt
}

model Tag {
  id    String @id @default(cuid())
  name  String @unique
  posts Post[]
}

model Comment {
  id       String   @id @default(cuid())
  content  String
  postId   String
  post     Post     @relation(fields: [postId], references: [id])
  authorId String
  author   User     @relation(fields: [authorId], references: [id])
  createdAt DateTime @default(now())
}

enum Role {
  USER
  ADMIN
}

编码实现阶段:多文件并行开发

进入编码阶段后,Hermes Agent 展现出其最强大的能力——多文件并行开发。Agent 会制定执行计划,按模块依次实现。

API 路由实现片段

// src/app/api/posts/route.ts
import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { getServerSession } from "next-auth";

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const page = parseInt(searchParams.get("page") || "1");
  const limit = parseInt(searchParams.get("limit") || "10");
  const tag = searchParams.get("tag");
  const search = searchParams.get("q");

  const where = {
    published: true,
    ...(tag && { tags: { some: { name: tag } } }),
    ...(search && {
      OR: [
        { title: { contains: search } },
        { content: { contains: search } },
      ],
    }),
  };

  const [posts, total] = await Promise.all([
    prisma.post.findMany({
      where,
      include: { author: true, tags: true, _count: { select: { comments: true } } },
      orderBy: { createdAt: "desc" },
      skip: (page - 1) * limit,
      take: limit,
    }),
    prisma.post.count({ where }),
  ]);

  return NextResponse.json({
    posts,
    pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
  });
}

export async function POST(request: NextRequest) {
  const session = await getServerSession();
  if (!session?.user) {
    return NextResponse.json({ error: "未登录" }, { status: 401 });
  }

  const body = await request.json();
  const post = await prisma.post.create({
    data: {
      title: body.title,
      content: body.content,
      excerpt: body.excerpt,
      slug: body.title.toLowerCase().replace(/\s+/g, "-"),
      authorId: session.user.id,
      tags: {
        connectOrCreate: body.tags.map((name: string) => ({
          where: { name },
          create: { name },
        })),
      },
    },
    include: { author: true, tags: true },
  });

  return NextResponse.json(post, { status: 201 });
}

在执行过程中,Agent 会展示其实时进度——创建了多少文件、完成了哪些模块、正在执行什么操作。如果你需要调整,随时可以中断并给出新的指令。

测试阶段:自动生成与运行测试

编码完成后,Hermes Agent 会自动进入测试阶段,生成测试用例并运行。

// __tests__/api/posts.test.ts
import { describe, it, expect, beforeAll } from "vitest";
import { GET, POST } from "@/app/api/posts/route";

describe("Posts API", () => {
  describe("GET /api/posts", () => {
    it("should return paginated posts", async () => {
      const request = new Request("http://localhost:3000/api/posts?page=1&limit=10");
      const response = await GET(request);
      const data = await response.json();

      expect(response.status).toBe(200);
      expect(data).toHaveProperty("posts");
      expect(data).toHaveProperty("pagination");
      expect(data.pagination.page).toBe(1);
    });

    it("should filter by tag", async () => {
      const request = new Request("http://localhost:3000/api/posts?tag=nextjs");
      const response = await GET(request);
      const data = await response.json();

      expect(response.status).toBe(200);
      data.posts.forEach((post: any) => {
        expect(post.tags.some((t: any) => t.name === "nextjs")).toBe(true);
      });
    });

    it("should search posts", async () => {
      const request = new Request("http://localhost:3000/api/posts?q=typescript");
      const response = await GET(request);
      const data = await response.json();

      expect(response.status).toBe(200);
      expect(data.posts.length).toBeGreaterThan(0);
    });
  });
});

Agent 执行测试并修复失败用例:

# Agent 自动运行测试
hermes-agent "运行测试并修复失败的用例"

# 输出结果
✓ __tests__/api/posts.test.ts (3 tests) 2.31s
✓ __tests__/api/auth.test.ts (2 tests) 1.12s
✓ __tests__/components/PostCard.test.tsx (4 tests) 3.45s
---
Test Files  3 passed (3)
Tests       9 passed (9)
Time        6.88s

部署阶段:CI/CD 配置

在完成代码开发和测试后,Hermes Agent 会生成 CI/CD 配置文件,实现自动化部署。

# .github/workflows/deploy.yml
name: Deploy Blog Platform

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_USER: test
          POSTGRES_PASSWORD: test
          POSTGRES_DB: test
        ports:
          - 5432:5432
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
      - run: npm ci
      - run: npx prisma generate
      - run: npm run test
      - run: npm run build

  deploy:
    needs: test
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v4
      - name: Build and push Docker image
        run: |
          docker build -t blog-platform:${{ github.sha }} .
          docker tag blog-platform:${{ github.sha }} registry.example.com/blog:latest
          docker push registry.example.com/blog:latest
      - name: Deploy to production
        run: |
          ssh deploy@server "docker pull registry.example.com/blog:latest && docker-compose up -d"

完整开发流程回顾与效率分析

效率对比

开发阶段传统方式使用 Hermes Agent效率提升
需求分析1-2 天30 分钟16-32x
架构设计2-3 天1 小时16-24x
编码实现5-7 天2-3 小时20-56x
测试编写1-2 天30 分钟16-32x
部署配置0.5 天15 分钟16x
总计10-15 天4-6 小时30-60x

关键经验总结

  • 需求描述越精确,Agent 输出质量越高:提供详细的功能列表、技术约束和设计偏好,可以显著减少返工
  • 阶段性验证至关重要:在 Agent 完成每个阶段后及时审查结果,确保方向正确
  • Agent 擅长并行任务:在 Agent 执行编码时,可以同时进行其他工作,如编写文档或设计 UI 原型
  • 人机协作是最佳模式:Agent 处理标准化工作,开发者专注于架构决策和创新性设计
  • 迭代式开发效果更佳:先让 Agent 搭建 MVP,然后逐步迭代完善,而非一次性追求完美

通过这个完整的实战案例可以看出,Hermes Agent 已经从一个简单的编程辅助工具进化为能够独立完成全栈 Web 应用开发的智能代理系统。开发者从"写代码的人"转变为"指导 Agent 的人",角色的转变带来了开发效率的质的飞跃。