# Architecture Agent

> SF-02 — Automated Architecture Generation from PRD

## Overview

The Architecture Agent consumes a structured PRD (from SF-01) and generates a complete technical architecture including tech stack selection, system diagram, database schema, API design, module decomposition, and directory structure.

It is **domain-aware**: architecture decisions are tailored to the PRD's domain (pet, ecommerce, education, enterprise, fitness, note, etc.) and platform constraints (iOS, Android, miniapp, web, desktop).

## Quick Start

```bash
# From PRD file (SF-01 output)
node scripts/architecture-agent.mjs --input prd-example.json --pretty

# From one-sentence requirement (auto-invokes SF-01)
node scripts/architecture-agent.mjs --input-text "做一个电商小程序" --output architecture.json
```

## Architecture

```
┌─────────────────────────────────────────────────┐
│              SF-02 Architecture Agent             │
│                                                  │
│  PRD ──▶ 1. Tech Stack Resolver                  │
│              Platform → Stack mapping            │
│              Extra features → stack adjustments  │
│                                                  │
│          2. Module Decomposer                     │
│              Feature → Module grouping           │
│              Keyword-based clustering            │
│              Domain-specific additions           │
│                                                  │
│          3. Database Designer                     │
│              API paths → resource tables         │
│              Domain → table schemas              │
│              Always: users table                 │
│                                                  │
│          4. API Designer                          │
│              Endpoint → resource grouping        │
│              Enriched endpoints                  │
│                                                  │
│          5. Architecture Diagramer                │
│              ASCII art 3-tier diagram            │
│              Client → API → DB flow              │
│                                                  │
│          6. Directory Structure                   │
│              Monorepo template                   │
│              apps/ + server/ + packages/         │
│              Module-specific directories         │
│                                                  │
│          7. Data Flow Mapper                      │
│              Page → API → DB trace               │
│                                                  │
│          8. Deployment Strategy                   │
│              Environments + CI/CD                │
│              Docker/native/build                  │
│                                                  │
│          ──────────────▶ Architecture JSON       │
└─────────────────────────────────────────────────┘
```

## Output Schema

```json
{
  "projectName": "PetCare",
  "domain": "pet",
  "techStack": {
    "frontend": "React Native 0.76 + Expo / Flutter 3.x",
    "backend": "NestJS + Prisma",
    "database": "PostgreSQL 15 + Redis 7 + MinIO（文件存储）",
    "deployment": "Docker Compose + Nginx / K8s（规模化）",
    "considerations": []
  },
  "architectureDiagram": "┌─────────────────────── ... ASCII art ...",
  "dataFlows": [
    {
      "page": "首页",
      "route": "/home",
      "description": "宠物卡片、今日提醒...",
      "dataFlow": ["GET /api/pets → ..."],
      "direction": "Client → API Gateway → Backend → Database → Response → Client"
    }
  ],
  "modules": [
    {
      "name": "pet",
      "label": "宠物管理",
      "features": ["宠物档案", "健康日程"],
      "responsibilities": ["提供 宠物档案 相关功能", "提供 健康日程 相关功能"]
    }
  ],
  "databaseSchema": [
    {
      "table": "users",
      "description": "用户表",
      "fields": [
        { "name": "id", "type": "UUID", "constraints": "PK, DEFAULT gen_random_uuid()" }
      ]
    }
  ],
  "apiDesign": [
    {
      "resource": "pets",
      "basePath": "/api/pets",
      "endpoints": [
        { "method": "GET", "path": "/api/pets", "description": "..." }
      ]
    }
  ],
  "directoryStructure": [
    "petcare/",
    "├── apps/",
    "├── server/",
    "└── docker-compose.yml"
  ],
  "deployment": {
    "environments": ["development", "staging", "production"],
    "strategy": "Docker Compose + Nginx / K8s（规模化）",
    "services": ["API Server (NestJS)", "PostgreSQL 15", "Redis 7"],
    "ci": "GitHub Actions → Build → Test → Deploy"
  }
}
```

## Tech Stack Selection

Automatic stack selection based on platforms:

| Platforms | Frontend | Backend | Database |
|-----------|----------|---------|----------|
| wechat-miniapp | 微信小程序原生 / Taro | 云函数 / Node.js | 云数据库 + MySQL |
| miniapp | uni-app 3.x | Node.js + Koa2/NestJS | PostgreSQL + Redis |
| ios | SwiftUI | Vapor / Node.js | PostgreSQL + Redis |
| android | Jetpack Compose | Spring Boot / Ktor | PostgreSQL + Redis |
| web | React 19 + Vite | NestJS / Fastify | PostgreSQL + Redis |
| mobile+web | React Native / Flutter | NestJS + Prisma | PostgreSQL + Redis + MinIO |
| default | React 19 + Vite | NestJS + Prisma | PostgreSQL + Redis |

Extra feature adjustments:
- `wechat-pay` / `alipay` → payment SDK integration note
- `logistics-tracking` → logistics API note
- `real-time` → WebSocket (Socket.io)
- `ai-powered` → AI service (OpenAI / 文心)

## Database Design

Domain-specific table generation:

| Domain | Tables |
|--------|--------|
| pet | users, pets, schedules, daily_logs |
| ecommerce | users, products, orders, order_items, logistics |
| education | users, courses, lessons, exercises, user_progress |
| enterprise | users, departments, approvals, approval_steps, attendance |
| fitness | users, checkins, training_plans |
| note | users, notes, tags, note_tags |
| generic | users, items |

All schemas include proper foreign keys, indexes, and constraints.

## Module Decomposition

Features are grouped into modules by keyword matching:

| Pattern | Module |
|---------|--------|
| 用户/登录/注册/权限 | auth |
| 设置/偏好/配置 | settings |
| 通知/提醒/推送 | notification |
| 上传/文件/图片 | storage |
| 统计/报告/分析 | analytics |
| 支付/订单/购物车 | payment |
| 审批/流程/考勤 | workflow |

Domain-specific modules are injected automatically (e.g., `product` + `order` for ecommerce).

## Downstream Integration

Architecture JSON is designed for:

- **SF-03 (Design Agent)**: Reads `pages`, `dataFlows` → UI wireframes
- **SF-04 (Dev Agent)**: Reads `directoryStructure`, `modules`, `databaseSchema` → project scaffolding
- **SF-05 (QA Agent)**: Reads `apiDesign`, `dataFlows` → test plans

## Test Coverage

57 tests across 16 suites.

```bash
node --test test/architecture-agent.test.mjs
```
