Skip to content

docs\en\suggestion.md

maoxiaoyue edited this page May 14, 2026 · 1 revision

Practical Guide to AI-Human Collaborative Development

HypGo Framework — AI-Human Collaborative Development Guide Version: 0.8.0 | 2026-03


A Note for Developers

This document is not about theory — it's about what you should do next.

Whether you're new to HypGo or already using it but finding AI collaboration less effective than expected, this guide will show you: what materials to prepare, what commands to run, and how to get AI to make fewer mistakes.

The core idea is simple: The quality of information you give to AI determines the quality of code AI produces. HypGo's toolchain helps you prepare the highest-quality information with the least effort.


Chapter 1: Where to Start? What to Do First?

1.1 First Thing: Create the Project Skeleton

# API-only project (recommended starting point)
hyp api myservice && cd myservice && go mod tidy

# Full-stack project (with frontend templates)
hyp new myapp && cd myapp && go mod tidy

1.2 Second Thing: Write the Schema, Not the Handler

Most developers' instinct is to write the handler first, then add documentation later. In HypGo, the order is reversed:

❌ Write handler → write tests → write docs → AI has no idea what you're doing
✅ Write Schema → AI writes handler → Contract auto-validates → you review business logic

Schema is the starting point of the entire AI collaboration loop. Without Schema, the Manifest is empty, Contract Testing cannot work, and AI-generated code has no specification to follow.

1.3 Third Thing: Generate the Manifest and AI Config Files

Once your Schema routes are defined and the server is running, immediately run:

# Generate project snapshot (AI's "map")
hyp context -o .hyp/context.yaml

# Generate config files for all AI coding tools
hyp ai-rules

After these two steps, regardless of which AI tool a developer uses (Claude Code, Cursor, Copilot, Gemini, Codex), the AI will automatically read the config files and immediately know your project uses HypGo, what routes exist, and what conventions to follow.

1.4 Command Execution Order — Quick Reference

Order Command Purpose When to Run
1 hyp api myservice Create project Once
2 Write Schema routes Define API contracts Each time you add a route
3 hyp run Start server (AutoSync generates manifest) During development
4 hyp context -o .hyp/context.yaml Manually refresh manifest After Schema changes
5 hyp ai-rules Generate AI tool config files After route changes, new team member joins
6 hyp chkcomment <file> Check annotation completeness After writing code
7 hyp impact <file> Analyze change impact Before modifying shared packages
8 hyp migrate diff Generate DB migration SQL After model changes

1.5 What Materials Should You Provide to AI?

You don't need to dump all your source code to AI. HypGo compresses the essential information into a few key files:

Material File Token Cost Contents
Required .hyp/context.yaml ~500 All routes, types, server config
Required AGENTS.md or CLAUDE.md ~300 Framework conventions, build/test commands
As needed Single Schema definition ~50 Specific route's Input/Output struct
As needed Error Catalog excerpt ~30 Defined error code list
As needed hyp impact output ~50 Change impact scope

Key principle: Let AI read the manifest first, then your requirements. Don't let AI browse source files on its own.


Chapter 2: How to Start a New Feature?

2.1 Walkthrough: Adding an "Orders" Feature

Suppose you need to add a set of order APIs (create order, get order, list orders). Here's the recommended workflow:

Step 1: Define the Structs (You)

// app/models/order.go

type CreateOrderReq struct {
    UserID    int     `json:"user_id"`
    ProductID int     `json:"product_id"`
    Quantity  int     `json:"quantity"`
    Note      string  `json:"note,omitempty"`
}

type OrderResp struct {
    ID        int     `json:"id"`
    UserID    int     `json:"user_id"`
    ProductID int     `json:"product_id"`
    Quantity  int     `json:"quantity"`
    Total     float64 `json:"total"`
    Status    string  `json:"status"`
    CreatedAt string  `json:"created_at"`
}

Step 2: Define Schema Routes (You)

// app/controllers/order.go

r.Schema(schema.Route{
    Method:  "POST",
    Path:    "/api/orders",
    Summary: "Create order",
    Tags:    []string{"orders"},
    Input:   CreateOrderReq{},
    Output:  OrderResp{},
    Responses: map[int]schema.ResponseSchema{
        201: {Description: "Order created"},
        400: {Description: "Invalid input"},
    },
}).Handle(createOrderHandler)

r.Schema(schema.Route{
    Method:  "GET",
    Path:    "/api/orders/:id",
    Summary: "Get order by ID",
    Tags:    []string{"orders"},
    Output:  OrderResp{},
}).Handle(getOrderHandler)

Step 3: Ask AI to Implement (AI)

Read .hyp/context.yaml to understand the project structure.
Implement createOrderHandler and getOrderHandler based on the schema.
Use errors.Define for error codes (starting from E3001),
and Bun ORM for database access.

AI will see the Input/Output types in the manifest and generate handlers that conform to the contract.

Step 4: Validate (Automatic)

// app/controllers/order_test.go
func TestOrderContracts(t *testing.T) {
    contract.TestAll(t, router)
}

One line validates all schema routes' Input/Output contracts.

2.2 Why This Order?

You define "what" (Schema) → AI implements "how" (Handler) → Contract verifies "correct?"

This order maximizes AI collaboration efficiency:

  • What you're good at: Deciding what the API looks like, what the business logic is
  • What AI is good at: Turning your definitions into boilerplate code
  • What the framework is good at: Automatically verifying AI's output matches your definitions

Chapter 3: Schema, Manifest, Router, Contract — Which Matters Most?

3.1 How They Relate

Schema (defines the contract)
  │
  ├──→ Router (registers route + Schema metadata)
  │         │
  │         └──→ Manifest (project snapshot, for AI to read)
  │
  └──→ Contract (auto-validates Handler against Schema)

3.2 Importance Ranking

Rank Component Impact Scope Why
1 Schema Global It's the foundation for everything else. Without Schema, Manifest is empty, Contract can't validate, Router degrades to plain routing
2 Contract Quality assurance Schema without validation is like no Schema at all. Contract is the "last mile" that closes the loop
3 Manifest AI efficiency With Schema in place, Manifest is auto-generated. It affects how quickly and accurately AI understands your project
4 Router Runtime Router is infrastructure. Both Schema routes and traditional routes work — the difference is whether they carry metadata

In one sentence: Schema is the source, Contract is the verification, Manifest is the delivery, Router is the carrier.

3.3 Schema: How to Write It Well

The quality of your Schema directly determines the quality of AI-generated code. Here are practical recommendations:

Essential Fields

r.Schema(schema.Route{
    Method:  "POST",          // ← Required: HTTP method
    Path:    "/api/users",    // ← Required: route path
    Summary: "Create user",   // ← Strongly recommended: one-line description, AI relies on this
    Input:   CreateUserReq{}, // ← Strongly recommended: Input struct, Contract uses it to validate requests
    Output:  UserResp{},      // ← Strongly recommended: Output struct, Contract uses it to validate responses
}).Handle(handler)

Optional but Valuable Fields

r.Schema(schema.Route{
    // ...essential fields...

    Tags:        []string{"users", "admin"},  // AI can understand routes by module
    Description: "Create a new user account, requires admin privileges",

    Responses: map[int]schema.ResponseSchema{
        201: {Description: "User created successfully"},
        400: {Description: "Validation error"},
        409: {Description: "Email already exists"},
    },

    Params: []schema.ParamSchema{
        {Name: "id", In: "path", Required: true, Type: "int"},
    },
}).Handle(handler)

Schema Quality Checklist

Field Good Practice Bad Practice
Summary "Create user" "" (empty — AI can't tell what the route does)
Input CreateUserReq{} (explicit struct) nil (AI can't know what to send)
Output UserResp{} (explicit struct) nil (Contract can't validate response)
Tags []string{"users"} (clear categorization) nil (Manifest won't show module grouping)
Responses List 201/400/409 Omitted (AI can't anticipate error scenarios)

3.4 Manifest: How to Write It

You don't need to write the Manifest manually. It's auto-generated.

# Method 1: Manual generation
hyp context -o .hyp/context.yaml

# Method 2: Automatic (Server.Start() triggers AutoSync to write .hyp/context.yaml)
hyp run

Manifest quality depends on your Schema quality. Good Schema means the Manifest contains complete routes, types, and descriptions. Empty Schema means the Manifest only has server config.

The only thing to decide: whether to commit .hyp/context.yaml to version control, or add it to .gitignore and let it regenerate on each startup — your choice.

3.5 Contract: How to Write It

Simplest Usage (Recommended Starting Point)

func TestAllContracts(t *testing.T) {
    // Set up your router (with all Schema routes)
    r := setupRouter()

    // Test all schema routes in one line
    contract.TestAll(t, r)
}

TestAll automatically:

  1. Iterates all routes in the Schema Registry
  2. Generates minimal valid JSON for Input structs (numbers → 0, strings → "test")
  3. Sends HTTP requests
  4. Validates response status codes (POST → 201, DELETE → 204, others → 200)
  5. Validates response body matches Output struct fields

Manual Testing of Specific Routes

contract.Test(t, r, contract.TestCase{
    Route:        "POST /api/users",
    Input:        `{"name":"alice","email":"alice@example.com"}`,
    ExpectStatus: 201,
    ExpectSchema: true,  // Validates response matches UserResp schema
})

Route Existence Testing

// No schema validation — just verify the route exists and returns the correct status code
contract.TestRoute(t, r, "GET", "/health", 200)

3.6 Router: Traditional vs Schema Routes

Both can coexist — you don't need to migrate everything at once:

// Traditional route — simple, fast, but AI can't see metadata
r.GET("/health", healthHandler)
r.POST("/webhook", webhookHandler)

// Schema route — a few extra lines, but AI understands it and Contract can validate it
r.Schema(schema.Route{
    Method:  "POST",
    Path:    "/api/users",
    Summary: "Create user",
    Input:   CreateUserReq{},
    Output:  UserResp{},
}).Handle(createUserHandler)

When should you use Schema routes?

Scenario Recommendation
Public API (called by frontend or third parties) Always use Schema
Routes you'll ask AI to implement Always use Schema
Internal health checks, webhooks Traditional routing is fine
Static file routes Traditional routing is fine

Chapter 4: When Is hyp generate Most Useful?

4.1 What Does generate Do?

hyp generate controller user    → app/controllers/user.go
hyp generate model order        → app/models/order.go
hyp generate service payment    → app/services/payment.go

The generated code isn't empty stubs — it automatically integrates HypGo conventions:

  • Controller: Includes router.Schema() registration, errors.Define() error code definitions, CRUD handler skeletons
  • Model: Includes Bun ORM struct tags (bun:"table:users")
  • Service: Includes Error Catalog integration, interface definitions

4.2 Scenarios Where generate Helps

Scenario Why It Helps Concrete Effect
Early project scaffolding Generate 5-10 CRUD resource skeletons at once Skip repetitive boilerplate, complete API structure in minutes
New team member onboarding Generated code serves as a living example New members immediately see how Schema and Error codes are written
Starting point for AI interaction Generate skeleton, then let AI fill in business logic AI has the correct structure, won't invent non-idiomatic patterns
Maintaining consistency All resources use the same template No "everyone writes differently" problem across the team

4.3 Scenarios Where generate Doesn't Help

Scenario Reason Alternative
Complex custom route logic Templates are generic, can't cover special requirements Write Schema manually + let AI implement
Large existing codebase generate only creates new files, can't integrate into existing structure Manually add Schema to existing handlers
Non-CRUD scenarios (WebSocket, streaming) Templates are designed for REST CRUD Implement manually

4.4 Recommended generate Workflow

# 1. Batch generate resource skeletons
hyp generate controller user
hyp generate controller product
hyp generate controller order
hyp generate model user
hyp generate model product
hyp generate model order

# 2. Adjust Schema definitions (add correct Input/Output structs)

# 3. Update manifest
hyp context -o .hyp/context.yaml

# 4. Tell AI: "Based on the schema in the manifest, implement all handler business logic"

# 5. Run Contract Testing to verify
go test ./app/controllers/... -v

Chapter 5: Day-to-Day Best Practices

5.1 Before Each Development Session

# Ensure the manifest is up to date
hyp context -o .hyp/context.yaml

5.2 Before Modifying Shared Packages

# Check the blast radius first
hyp impact pkg/errors/catalog.go

# If risk is HIGH, discuss with the team before changing
# If risk is LOW/MEDIUM, change it and run affected tests
go test ./pkg/errors/... ./pkg/contract/... -v

5.3 After Writing Code

# Check annotation completeness
hyp chkcomment app/controllers/user.go

# Run contract tests
go test ./app/controllers/... -v

# If models changed, generate migration
hyp migrate diff

5.4 Prompt Templates for AI

Here are field-tested prompt templates that produce high-quality code from AI:

Adding a new feature:

Read .hyp/context.yaml to understand the project structure.
I need to add a [feature name] feature,
Input is [StructName], Output is [StructName].
Use router.Schema() to register routes,
errors.Define() to define error codes (starting from E[xxxx]),
and Bun ORM for database access.

Modifying an existing feature:

Read .hyp/context.yaml first,
then run hyp impact [file to modify] to check the blast radius.
I need to change [route path] behavior: [specific change].
After the change, run contract.TestAll() to ensure the contract isn't broken.

Debugging an issue:

Read .hyp/context.yaml to understand the project structure,
then look at [files related to the problem].
The issue is: [describe the problem].
Use hyp impact to confirm the fix won't affect other modules.

Chapter 6: FAQ

Q: How is Schema different from regular Go doc comments?

Go doc comments are free-form text — AI has to "understand" natural language. Schema is a structured Go struct — AI reads field names and types directly, with zero ambiguity.

Q: I already have Swagger/OpenAPI. Do I still need Schema?

Swagger generates documentation from code and can drift out of sync. HypGo Schema is part of the route registration process itself — it can never be out of sync, because it IS the route. Also, Schema directly drives Contract Testing, which Swagger can't do.

Q: Can Contract Testing replace unit tests?

No. Contract Testing validates "interface contracts" (are types correct, are status codes correct). Unit tests validate "business logic" (is the amount calculated right, are edge cases handled). They're complementary — you need both.

Q: My project is small (3-5 routes). Is Schema worth it?

Yes. Schema adds only ~5 lines of code per route, but you get:

  1. contract.TestAll() auto-validation (saves time writing manual tests)
  2. Manifest with complete route info (AI understands your project more accurately)
  3. As the project grows, Schema's value increases exponentially

Q: Should hyp ai-rules generated files be committed to git?

Yes, recommended. This way every team member using different AI tools will automatically get the same conventions.


Quick Reference: The Complete AI-Human Collaboration Loop

      You                       AI                       Framework
      │                         │                         │
      ├─ Define Structs ───────→│                         │
      ├─ Write Schema routes ──→│                         │
      ├─ hyp context ──────────→├─ Read manifest ────────→│
      │                         ├─ Understand API          │
      ├─ Describe requirement ─→├─ Generate Handler ─────→│
      │                         │                         ├─ Contract validation
      │                         │                         ├─ ✅ Pass → merge
      │                         │                         └─ ❌ Fail → feedback
      │                         ├─ Fix code ─────────────→│
      │                         │                         ├─ Re-validate
      ├─ Review business logic ←┤                         │
      ├─ hyp chkcomment ───────→│                         │
      ├─ hyp migrate diff ─────→│                         │
      └─ Done ✅                 │                         │

Remember: You own the "what" (Schema), AI owns the "how" (Handler), the framework owns the "is it correct" (Contract).


HypGo · AI-Human Collaborative Development Guide · 2026-03

HypGo

繁體中文 | English


中文文件

設計文件

套件

AI 協作工具鏈

CLI 命令


English Docs

Design Docs

Packages

AI Collaboration Toolchain

CLI Commands

Clone this wiki locally