Skip to content

manifest_en.md

maoxiaoyue edited this page May 14, 2026 · 2 revisions

pkg/manifest -- Project Manifest Auto-generation

Scans a HypGo application's routes, middleware, and server configuration to produce a machine-readable YAML/JSON description, allowing AI to grasp the full project picture with minimal tokens.

Design Philosophy

The biggest bottleneck in AI-assisted development is "understanding the project." The traditional approach has AI read source files one by one, consuming massive tokens. Manifest lets the framework automatically produce a structured project description:

Bad:  AI reads 20 files to understand API structure (thousands of tokens)
Good: AI reads 1 manifest to grasp the full picture (hundreds of tokens)

Quick Start

Generate from Code

import (
    "os"
    "github.com/maoxiaoyue/hypgo/pkg/manifest"
    "github.com/maoxiaoyue/hypgo/pkg/router"
    "github.com/maoxiaoyue/hypgo/pkg/config"
)

// 1. Create Collector (collects from Router + Config)
c := manifest.NewCollector(myRouter, myConfig)

// 2. Generate Manifest
m := c.Collect()

// 3. Output YAML to stdout
manifest.WriteYAML(os.Stdout, m)

// 4. Or save to file
manifest.SaveToFile(".hyp/manifest.yaml", m, "yaml")
manifest.SaveToFile(".hyp/manifest.json", m, "json")

Generate Directly from Server

srv := server.New(cfg, logger)

// After registering routes...
m := srv.Manifest()
manifest.WriteYAML(os.Stdout, m)

Via CLI

# Output YAML to stdout
hyp context

# Output JSON format
hyp context -f json

# Save to file
hyp context -o .hyp/manifest.yaml
hyp context -o .hyp/manifest.json -f json

Output Examples

YAML

version: "1.0"
framework: HypGo
generated_at: 2026-03-26T20:00:00+08:00
server:
  addr: ":8080"
  protocol: http2
  tls: true
routes:
  - method: POST
    path: /api/users
    handler_names:
      - controllers.CreateUser
    summary: "Create user"
    tags:
      - users
    input_type: CreateUserRequest
    output_type: UserResponse
    responses:
      201: "User created"
      400: "Invalid input"
  - method: GET
    path: /api/users/:id
    handler_names:
      - controllers.GetUser
    summary: "Get user by ID"
    tags:
      - users
    output_type: UserResponse
  - method: GET
    path: /health
    handler_names:
      - main.healthHandler
database:
  driver: postgres
  has_replicas: true

JSON

{
  "version": "1.0",
  "framework": "HypGo",
  "server": {
    "addr": ":8080",
    "protocol": "http2",
    "tls": true
  },
  "routes": [
    {
      "method": "POST",
      "path": "/api/users",
      "handler_names": ["controllers.CreateUser"],
      "summary": "Create user",
      "tags": ["users"],
      "input_type": "CreateUserRequest",
      "output_type": "UserResponse",
      "responses": { "201": "User created" }
    }
  ]
}

Core Types

Manifest

type Manifest struct {
    Version     string          // Fixed "1.0"
    Framework   string          // Fixed "HypGo"
    GeneratedAt time.Time       // Generation timestamp
    Server      ServerInfo      // Server configuration
    Routes      []RouteManifest // All routes
    Middleware  []string        // Global middleware
    Database    *DatabaseInfo   // Database configuration (optional)
}

RouteManifest (Multi-Protocol)

type RouteManifest struct {
    // Multi-protocol support
    Protocol     string         // "rest", "grpc", "bot", "mcp", "websocket", "cli"
    Command      string         // Non-REST command identifier
    Platform     string         // Bot-specific platform (telegram, line, discord...)

    // REST fields
    Method       string         // HTTP method
    Path         string         // Route path
    HandlerNames []string       // Handler function names (via runtime reflection)

    // Shared metadata
    Summary      string         // Route description (from schema)
    Description  string         // Detailed description (from schema)
    Tags         []string       // Classification tags (from schema)
    InputType    string         // Request type name (from schema)
    OutputType   string         // Response type name (from schema)
    Responses    map[int]string // Status code -> description (from schema)
}

Manifest includes both REST and non-REST routes — AI reads one manifest to understand all protocol APIs.

Data Sources

The Collector gathers information from three sources:

Source Provides
Router.Routes() Method, Path, HandlerNames
schema.Global() Summary, Tags, InputType, OutputType, Responses
config.Config Server (addr, protocol, TLS), Database (driver, replicas)

Routes not registered with Schema() will still appear in the manifest but without schema metadata.

Collector Flow

Router.Routes()
    |
    +-->  Each RouteInfo
    |       |
    |       +--> schema.Global().Get(method, path)
    |               |
    |               +--> Merge into RouteManifest
    |
    +-->  sort by Path + Method
    |
config.Config --> ServerInfo + DatabaseInfo
    |
    +--> Assemble Manifest

Writer API

// Write to io.Writer
manifest.WriteYAML(w, m)   // YAML format, 2-space indent
manifest.WriteJSON(w, m)   // JSON format, 2-space indent

// Save to file (auto-creates directories)
manifest.SaveToFile(path, m, "yaml")
manifest.SaveToFile(path, m, "json")

LLM Smart Enrichment

v0.8.5+ Manifest smart enrichment (Layer 2 LLM enrichment, llm.yaml config) is new in v0.8.5. v0.8.1 Manifest only includes Layer 1 pure Go inference.

Manifest supports a two-layer enrichment mechanism that auto-fills Summary, Tags, and Description fields:

Layer 1: Pure Go Inference (Default, Zero Cost)

Automatically infers from handler names and paths, no external dependencies needed:

// handler name → Summary
"(*UserController).Create""Create User"

// path → Tags
"/api/users/:id" → ["users"]

Layer 2: LLM Enrichment (Optional, Requires Configuration)

Enabled via config/llm.yaml, supporting three modes:

Mode Description Use Case
ollama Connect to local Ollama Development, zero cost
api OpenAI / Anthropic / Gemini Production, highest quality
rag Vector DB + embedding + LLM Large projects, most accurate

Usage

1. Create Config File config/llm.yaml

# Minimal config — connect to local Ollama
mode: ollama
ollama:
  model: llama3
# API mode — use OpenAI
mode: api
api:
  provider: openai
  model: gpt-4o-mini
  api_key: "${OPENAI_API_KEY}"    # supports env vars
# RAG mode — vector retrieval + LLM generation
mode: rag
rag:
  embedding_model: nomic-embed-text
  vector_store: chroma
  vector_store_url: "http://localhost:8000"
  collection: my_codebase
  generator_model: llama3

2. Use from Code

// Load LLM configuration
llmCfg, err := config.LoadLLMConfig("config/llm.yaml")

// Create Collector with LLM enrichment
c, err := manifest.NewCollectorWithLLM(myRouter, myConfig, llmCfg)
m := c.Collect()

3. Use from CLI

# Auto-detects config/llm.yaml or .hyp/llm.yaml
hyp context

# Specify config file
hyp context --llm config/llm.yaml

# With output options
hyp context --llm config/llm.yaml -o .hyp/manifest.yaml -f yaml

Mode Comparison: Accuracy vs Cost

mode: none     | Zero cost  | ★★☆ Basic inference
mode: ollama   | Free       | ★★★ Local model generation
mode: api      | Pay-per-use| ★★★★ Cloud model generation
mode: rag      | Pay-per-use| ★★★★★ With code context

Security Design

  • api_key supports ${ENV_VAR} syntax to avoid storing keys in plaintext
  • Manifest output does not include LLM configuration (no API key leakage)
  • LLM responses are sanitized to prevent unexpected content injection
  • Ollama defaults to localhost only, not exposed to external networks

EnrichConfig Full Configuration

cfg := manifest.EnrichConfig{
    InferSummary:  true,           // Infer Summary from handler name
    InferTags:     true,           // Infer Tags from path
    IncludeFields: true,           // Include InputFields/OutputFields
    LLMEnricher:   myLLMEnricher,  // LLM enricher (optional)
}
c := manifest.NewCollectorWithEnrich(router, config, cfg)

Architecture

pkg/manifest/
├── manifest.go          Manifest, ServerInfo, RouteManifest, DatabaseInfo types
├── collector.go         Collector: collects from Router + Config + Schema Registry
├── enricher.go          EnrichConfig, pure Go inference logic, LLMEnricher interface
├── llm_enricher.go      OllamaEnricher, APIEnricher, RAGEnricher implementations
├── writer.go            WriteYAML, WriteJSON, SaveToFile output
├── manifest_test.go     Collector + Writer tests
└── llm_enricher_test.go LLM Enricher tests (with httptest mocks)

Dependencies

pkg/manifest -> pkg/router  (Routes() to get route list)
             -> pkg/config  (get server/database settings)
             -> pkg/schema  (get schema metadata)
             -> gopkg.in/yaml.v3 (YAML output)

AutoSync Automatic Synchronization

Server.Start() automatically calls pkg/autosync on startup, writing the Manifest to .hyp/context.yaml to ensure AI always has the latest project structure:

// Automatically executed inside Server.Start():
sync := autosync.New(autosync.Config{Enabled: true}, router, config, logger)
sync.SyncSafe()  // Won't panic on failure, only logs warning

Features:

  • Atomic writes: temp file + os.Rename() prevents mid-write corruption
  • Secure: Does not include passwords, tokens, DSN, or other sensitive information
  • Zero configuration: Syncs on Server startup, no manual action needed

HypGo

繁體中文 | English


中文文件

設計文件

套件

AI 協作工具鏈

CLI 命令


English Docs

Design Docs

Packages

AI Collaboration Toolchain

CLI Commands

Clone this wiki locally