项目文件夹

文件
Asim Aslam d3c4981326
goreleaser / goreleaser (push) Has been cancelled
Enhance AI service generation with prompt-based architecture and logic (#2926)
* feat: add micro new --prompt and micro run --prompt

Add AI-powered service generation: describe a system in natural
language and get real go-micro services with proto definitions,
handlers, doc comments, and MCP support.

micro new --prompt "a contact book with notes and tags" \
  --provider anthropic

Generates:
  contacts/ — CRUD service with name, email, phone fields
  notes/    — notes linked to contacts
  tags/     — tagging system

Each service gets:
  proto/{name}.proto   — domain model + CRUD endpoints
  handler/{name}.go    — in-memory store, @example tags for MCP
  main.go              — MCP-enabled, proper imports
  go.mod + Makefile     — compiles with go mod tidy + make proto

micro run --prompt does the same then starts all services.

The LLM designs the architecture (service names, fields, endpoints,
descriptions) and returns structured JSON. Code generation uses
the existing template patterns — the output is standard go-micro
code that compiles, runs, and is immediately callable via MCP
and micro chat. No AI dependency at runtime.

* feat: LLM generates real business logic with compile-fix loop

Rebuild the generate package so the LLM writes actual handler
code with business logic, not just CRUD scaffolding.

The flow is now:
1. LLM designs architecture (service names, fields, endpoints)
   → returns structured JSON
2. Proto, main.go, go.mod, Makefile generated deterministically
   from the design (guaranteed to be correct)
3. go mod tidy + make proto compiles the protos
4. LLM generates handler code with REAL business logic
   → given the proto, endpoint descriptions, and go-micro patterns
5. go build — does it compile?
6. If no: feed errors back to LLM, get fixed code (up to 3 attempts)
7. If yes: service is ready

The handler prompt instructs the LLM to:
- Use sync.RWMutex for thread-safe in-memory state
- Include validation, edge cases, meaningful errors
- Write doc comments with @example tags for MCP
- Implement actual domain logic, not just map operations

Proto generation still uses deterministic templates (CRUD +
custom endpoints from the design spec) to guarantee correctness.
The compile-fix loop catches LLM mistakes automatically.

Both micro new --prompt and micro run --prompt use this flow.

* fix: handle edge cases in prompt-based generation

- Fix PATH for protoc-gen-micro in child processes
- Handle existing directories: skip structural files (main.go,
  go.mod, Makefile) if dir exists, always regenerate proto,
  only write placeholder handler if none exists
- Allow re-running micro new --prompt on same directory to
  iterate on business logic without clobbering user edits

Tested end-to-end: "a simple todo list with tasks and categories"
generates 2 services (task-service, category-service) with real
business logic (validation, toggle complete, etc.), compiles
after 1 fix iteration, and runs with 6 MCP tools discovered.

* feat: auto-detect modified handlers on regeneration

Instead of requiring a --keep-handlers flag, the generate package now
tracks a SHA-256 hash of each generated handler in a .micro metadata
file. On re-run, if the user has edited the handler since generation,
it's left untouched. Unmodified handlers are regenerated normally.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: add tests, fix go.mod, gitignore, proto tracking, spinner

- Add 12 tests covering helpers, proto generation, hash tracking
- Fix go.mod: write minimal module file, let go mod tidy resolve deps
- Add .gitignore to prompt-generated services
- Protect user-edited proto files (same hash tracking as handlers)
- Add spinner during LLM calls so it doesn't look hung

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: signal handling, existing service discovery, help text

- Ctrl+C during generation now cancels LLM calls immediately via
  signal-aware context; re-run picks up where it left off
- Design() scans for existing services in the working directory and
  includes their proto definitions in the prompt, so the LLM extends
  the system rather than redesigning from scratch
- Updated --prompt help text with usage examples on both new and run
- Listed all supported providers in flag descriptions
- Added discoverExisting test

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: show endpoints in run --prompt output, add micro chat hint

Print endpoint names and descriptions when designing services so users
see what was built. Add a micro chat hint to the run banner so users
know how to interact with their services after startup.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: generated go.mod uses go 1.24 with explicit go-micro require

go 1.22 with no explicit require caused Go to resolve sub-packages
(gateway/mcp, client, server) as separate modules, hitting stale v1.18
tags. Pin to go 1.24 + require go-micro.dev/v5 v5.24.0 so go mod tidy
resolves all sub-packages from the root module correctly.

Tested end-to-end: 4 services generated and compiled successfully.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: skip handler regeneration when proto unchanged

Compare proto hash before and after structure generation. If the proto
didn't change and the handler wasn't edited by the user, skip go mod
tidy, make proto, LLM handler generation, and compile-fix entirely.
Prints "(unchanged)" instead.

Reduces re-run of 4-service project from ~2 minutes to ~10 seconds.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: confirm design before generating code

Show the service design (names, endpoints) and prompt "Generate? [Y/n]"
before spending LLM time on handler generation. Applies to both
micro new --prompt and micro run --prompt. Default is yes (enter).

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: use port :0 for MCP in generated multi-service projects

Each generated service had mcp.WithMCP(":3001") hardcoded, causing
port conflicts when running multiple services. Use :0 to auto-assign
a free port. micro run's central gateway handles unified MCP access.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: truncation detection, tool result display in chat

- Detect truncated LLM responses (unbalanced braces, doesn't end
  with '}') and retry with a conciseness hint before falling through
  to compile-fix
- Show tool call results in micro chat output (← for success, ✗ for
  errors) so users can see what the LLM did
- Add Result/Error fields to ToolCall, populated by Anthropic provider
  after tool execution
- Add isTruncated tests

Tested end-to-end with Anthropic: services generate, compile, start,
register, respond to RPC calls, and micro chat discovers and calls
tools correctly.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: Anthropic tool loop, service naming, chat tool results

Anthropic provider:
- Fix tool execution loop to properly iterate (was re-processing all
  tool calls instead of only new ones each round)
- Clean assistant content blocks before sending back (strip 'id' from
  text blocks that Anthropic rejects on input)
- Include tools in follow-up requests so model can make additional calls
- Loop up to 10 rounds until model responds with text only

Service naming:
- Strip '-service' suffix from micro.New() name so services register
  as 'task', 'category' instead of 'taskservice', 'categoryservice'

Chat:
- Show tool results (← for success) and errors (✗) in chat output

Tested end-to-end: create task → list tasks works as multi-step
orchestration through micro chat with Anthropic Claude.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: blog post 13 — from prompt to production

Covers the full micro run --prompt flow: design, generate, compile-fix,
run, and chat orchestration. Positions agent-as-orchestrator as the
answer to service coordination.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* fix: timeouts, max_tokens, TTY detection, smaller services

- Add 60s timeout on design, 90s on handler generation, 60s on
  compile-fix LLM calls so hung providers don't block forever
- Bump Anthropic max_tokens from 4096 to 8192 to reduce truncation
- Add TTY detection: spinner prints static message in non-TTY (CI/pipes)
  instead of ANSI escape codes
- Tighten prompts: max 200 lines per handler, 2-4 services, 5-8 fields,
  explicit "services don't call each other" rule

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: chat suggests creating services when capabilities are missing

Update system prompt with the list of available services. When the user
asks for something no existing service can handle, the agent explains
what's available and suggests the exact micro new --prompt command to
create the missing service.

This is the natural evolution path: start with a few services, talk to
them via chat, and when the domain grows, the agent tells you what to
add. Each service stays small and focused.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: chat generates and starts services inline, drop -service suffix

Chat agent now has a micro_generate_service tool. When the user asks
for a capability that doesn't exist, the agent generates the service,
compiles it, starts it as a background process, waits for registration,
re-discovers tools, and uses the new endpoints immediately — all within
the conversation.

Service naming: design prompt now instructs LLM to return names without
'-service' suffix (e.g. 'task' not 'task-service'). buildMain keeps
TrimSuffix as safety net for backward compatibility.

Spawned processes are cleaned up when chat exits.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* docs: rewrite blog post 13 with inline service generation

Updated to reflect the full UX: services generate and start within
the chat conversation. Added the shipping example showing the agent
creating a service mid-conversation. Removed -service suffix from
all examples. Tightened the narrative around agent-as-orchestrator.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

* feat: persistent storage, README quickstart, auto-detect new services

Storage: generated handlers now use go-micro's store package instead
of in-memory maps. Data persists across restarts. The handler prompt
includes store API examples so the LLM generates correct store usage.

README: added "Generate From a Prompt" section with micro run --prompt
and micro chat examples, linking to blog post 13.

Watcher: micro run now scans for new service directories every 5s. When
micro chat generates a service, micro run detects the new directory,
builds it, starts it, and adds it to the watcher — fully automatic.
Added AddDir/Dirs methods to the watcher.

Blog: updated post 13 with persistent storage example and watcher note.

https://claude.ai/code/session_01QTp4SshuVmLAvvEGJe4TJd

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-03 20:31:01 +01:00

422 行
11 KiB
Go

package generate
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestToTitle(t *testing.T) {
tests := []struct {
in, want string
}{
{"order-service", "OrderService"},
{"task", "Task"},
{"inventory_item", "InventoryItem"},
{"hello world", "HelloWorld"},
{"a-b-c", "ABC"},
{"already", "Already"},
}
for _, tt := range tests {
if got := toTitle(tt.in); got != tt.want {
t.Errorf("toTitle(%q) = %q, want %q", tt.in, got, tt.want)
}
}
}
func TestProtoType(t *testing.T) {
tests := []struct {
in, want string
}{
{"string", "string"},
{"int64", "int64"},
{"int32", "int32"},
{"bool", "bool"},
{"float64", "double"},
{"unknown", "string"},
{"", "string"},
}
for _, tt := range tests {
if got := protoType(tt.in); got != tt.want {
t.Errorf("protoType(%q) = %q, want %q", tt.in, got, tt.want)
}
}
}
func TestFirstNonEmpty(t *testing.T) {
if got := firstNonEmpty("", "", "c"); got != "c" {
t.Errorf("got %q, want %q", got, "c")
}
if got := firstNonEmpty("a", "b"); got != "a" {
t.Errorf("got %q, want %q", got, "a")
}
if got := firstNonEmpty("", ""); got != "" {
t.Errorf("got %q, want %q", got, "")
}
}
func TestExtractJSON(t *testing.T) {
tests := []struct {
name, in, want string
}{
{
"fenced json",
"Here's the design:\n```json\n{\"services\": []}\n```\nDone.",
`{"services": []}`,
},
{
"fenced no lang",
"```\n{\"a\": 1}\n```",
`{"a": 1}`,
},
{
"raw json",
`some text {"key": "val"} trailing`,
`{"key": "val"}`,
},
{
"nested braces",
`{"a": {"b": 1}}`,
`{"a": {"b": 1}}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := extractJSON(tt.in)
if got != tt.want {
t.Errorf("extractJSON() = %q, want %q", got, tt.want)
}
})
}
}
func TestExtractCode(t *testing.T) {
tests := []struct {
name, in string
wantPrefix string
}{
{
"go fence",
"Here:\n```go\npackage handler\n\nfunc Foo() {}\n```\nDone.",
"package handler",
},
{
"generic fence",
"```\npackage main\n```",
"package main",
},
{
"raw code",
"Sure, here's the code:\npackage handler\n\ntype X struct{}",
"package handler",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := extractCode(tt.in)
if !strings.HasPrefix(got, tt.wantPrefix) {
t.Errorf("extractCode() = %q, want prefix %q", got, tt.wantPrefix)
}
})
}
}
func TestBuildProto(t *testing.T) {
svc := ServiceSpec{
Name: "task-service",
Description: "Manages tasks",
Fields: []FieldSpec{
{Name: "id", Type: "string", Description: "Task ID"},
{Name: "title", Type: "string", Description: "Task title"},
{Name: "done", Type: "bool", Description: "Completion status"},
{Name: "created", Type: "int64", Description: "Created timestamp"},
{Name: "updated", Type: "int64", Description: "Updated timestamp"},
},
Endpoints: []EndpointSpec{
{Name: "Create", Description: "Create a task"},
{Name: "Read", Description: "Get a task"},
{Name: "Update", Description: "Update a task"},
{Name: "Delete", Description: "Delete a task"},
{Name: "List", Description: "List tasks"},
{Name: "ToggleComplete", Description: "Toggle completion"},
},
}
proto := buildProto("taskservice", "TaskService", svc)
checks := []string{
`syntax = "proto3"`,
`package taskservice`,
`service TaskService`,
`rpc Create(CreateRequest) returns (CreateResponse)`,
`rpc ToggleComplete(ToggleCompleteRequest) returns (ToggleCompleteResponse)`,
`message TaskServiceRecord`,
`string title = 2`,
`bool done = 3`,
`message CreateRequest`,
`message ReadRequest`,
`message DeleteRequest`,
`message ListRequest`,
`message ToggleCompleteRequest`,
}
for _, c := range checks {
if !strings.Contains(proto, c) {
t.Errorf("buildProto() missing %q", c)
}
}
// Create should not include id, created, updated
createIdx := strings.Index(proto, "message CreateRequest")
createEnd := strings.Index(proto[createIdx:], "}")
createBlock := proto[createIdx : createIdx+createEnd]
for _, skip := range []string{"string id", "int64 created", "int64 updated"} {
if strings.Contains(createBlock, skip) {
t.Errorf("CreateRequest should not contain %q", skip)
}
}
}
func TestBuildMain(t *testing.T) {
// New naming: no -service suffix
main := buildMain("order", "Order")
checks := []string{
`"order/handler"`,
`pb "order/proto"`,
`micro.New("order"`,
`pb.RegisterOrderHandler`,
`handler.New()`,
}
for _, c := range checks {
if !strings.Contains(main, c) {
t.Errorf("buildMain(order) missing %q", c)
}
}
// Legacy naming: -service suffix stripped
main = buildMain("order-service", "OrderService")
checks = []string{
`"order-service/handler"`,
`pb "order-service/proto"`,
`micro.New("order"`,
`pb.RegisterOrderServiceHandler`,
`handler.New()`,
}
for _, c := range checks {
if !strings.Contains(main, c) {
t.Errorf("buildMain() missing %q", c)
}
}
}
func TestHandlerModifiedTracking(t *testing.T) {
dir := t.TempDir()
handlerDir := filepath.Join(dir, "handler")
os.MkdirAll(handlerDir, 0755)
handlerFile := filepath.Join(handlerDir, "test.go")
// No .micro file → not modified
os.WriteFile(handlerFile, []byte("package handler\n"), 0644)
if handlerModified(dir, handlerFile) {
t.Error("expected not modified when no .micro exists")
}
// Record hash → not modified
recordHandlerHash(dir, handlerFile)
if handlerModified(dir, handlerFile) {
t.Error("expected not modified after recording hash")
}
// Edit the file → modified
os.WriteFile(handlerFile, []byte("package handler\n\nfunc Foo() {}\n"), 0644)
if !handlerModified(dir, handlerFile) {
t.Error("expected modified after editing file")
}
// Re-record → not modified again
recordHandlerHash(dir, handlerFile)
if handlerModified(dir, handlerFile) {
t.Error("expected not modified after re-recording hash")
}
}
func TestMetaReadWrite(t *testing.T) {
dir := t.TempDir()
m := readMeta(dir)
if len(m) != 0 {
t.Error("expected empty meta for new dir")
}
m["handler_hash"] = "abc123"
m["version"] = "1"
writeMeta(dir, m)
m2 := readMeta(dir)
if m2["handler_hash"] != "abc123" || m2["version"] != "1" {
t.Errorf("readMeta() = %v, want handler_hash=abc123, version=1", m2)
}
}
func TestGenerateStructure(t *testing.T) {
dir := t.TempDir()
svcDir := filepath.Join(dir, "test-svc")
svc := ServiceSpec{
Name: "test-svc",
Description: "Test service",
Fields: []FieldSpec{
{Name: "id", Type: "string"},
{Name: "name", Type: "string"},
},
Endpoints: []EndpointSpec{
{Name: "Create"},
{Name: "Read"},
},
}
if err := generateStructure(svcDir, svc); err != nil {
t.Fatal(err)
}
// Check files exist
for _, f := range []string{
"proto/test-svc.proto",
"handler/test-svc.go",
"main.go",
"go.mod",
"Makefile",
".gitignore",
} {
if _, err := os.Stat(filepath.Join(svcDir, f)); err != nil {
t.Errorf("missing %s: %v", f, err)
}
}
// Check .micro was created with handler hash
meta := readMeta(svcDir)
if meta["handler_hash"] == "" {
t.Error("expected handler_hash in .micro after generateStructure")
}
// Run again — should not overwrite main.go
mainBefore, _ := os.ReadFile(filepath.Join(svcDir, "main.go"))
os.WriteFile(filepath.Join(svcDir, "main.go"), []byte("// user edited\n"), 0644)
if err := generateStructure(svcDir, svc); err != nil {
t.Fatal(err)
}
mainAfter, _ := os.ReadFile(filepath.Join(svcDir, "main.go"))
if string(mainAfter) == string(mainBefore) {
t.Error("expected main.go to keep user edit on re-run")
}
// Proto should be protected if user modified it
protoFile := filepath.Join(svcDir, "proto", "test-svc.proto")
protoBefore, _ := os.ReadFile(protoFile)
os.WriteFile(protoFile, []byte("// user-edited proto\n"), 0644)
if err := generateStructure(svcDir, svc); err != nil {
t.Fatal(err)
}
protoAfter, _ := os.ReadFile(protoFile)
if string(protoAfter) != "// user-edited proto\n" {
t.Error("expected proto to be preserved after user edit")
}
// Proto should regenerate if NOT modified
recordFileHash(svcDir, "proto_hash", protoFile)
if err := generateStructure(svcDir, svc); err != nil {
t.Fatal(err)
}
protoAfter2, _ := os.ReadFile(protoFile)
if string(protoAfter2) == string(protoBefore) {
// ok — regenerated from spec
}
}
func TestFileModified(t *testing.T) {
dir := t.TempDir()
f := filepath.Join(dir, "test.txt")
os.WriteFile(f, []byte("original"), 0644)
// No hash → not modified
if fileModified(dir, "test_hash", f) {
t.Error("expected not modified with no saved hash")
}
recordFileHash(dir, "test_hash", f)
// Same content → not modified
if fileModified(dir, "test_hash", f) {
t.Error("expected not modified with matching hash")
}
// Changed content → modified
os.WriteFile(f, []byte("changed"), 0644)
if !fileModified(dir, "test_hash", f) {
t.Error("expected modified after content change")
}
}
func TestDiscoverExisting(t *testing.T) {
dir := t.TempDir()
// Empty directory → empty string
if got := discoverExisting(dir); got != "" {
t.Errorf("expected empty for empty dir, got %q", got)
}
// Non-service directory (no proto) → empty
os.MkdirAll(filepath.Join(dir, "not-a-service"), 0755)
if got := discoverExisting(dir); got != "" {
t.Errorf("expected empty for dir without proto, got %q", got)
}
// Create a real service directory with proto
svcDir := filepath.Join(dir, "order-service")
os.MkdirAll(filepath.Join(svcDir, "proto"), 0755)
os.WriteFile(filepath.Join(svcDir, "proto", "order-service.proto"),
[]byte("syntax = \"proto3\";\nservice OrderService {}"), 0644)
got := discoverExisting(dir)
if !strings.Contains(got, "order-service") {
t.Errorf("expected to find order-service, got %q", got)
}
if !strings.Contains(got, "OrderService") {
t.Errorf("expected to find proto content, got %q", got)
}
// Add a second service
svc2Dir := filepath.Join(dir, "user-service")
os.MkdirAll(filepath.Join(svc2Dir, "proto"), 0755)
os.WriteFile(filepath.Join(svc2Dir, "proto", "user-service.proto"),
[]byte("syntax = \"proto3\";\nservice UserService {}"), 0644)
got = discoverExisting(dir)
if !strings.Contains(got, "order-service") || !strings.Contains(got, "user-service") {
t.Errorf("expected both services, got %q", got)
}
}
func TestIsTruncated(t *testing.T) {
tests := []struct {
name string
code string
want bool
}{
{"complete", "package handler\n\nfunc New() *H { return &H{} }\n", false},
{"empty", "", true},
{"no closing brace", "package handler\n\nfunc Foo() {", true},
{"unbalanced", "package handler\n\nfunc Foo() {\n\tif true {", true},
{"balanced", "package handler\n\nfunc Foo() {\n\tif true {\n\t}\n}", false},
{"trailing whitespace ok", "package handler\n\ntype X struct{}\n\n", false},
{"mid-expression", "package handler\n\nfunc F() {\n\tx := 1 +", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := isTruncated(tt.code); got != tt.want {
t.Errorf("isTruncated() = %v, want %v", got, tt.want)
}
})
}
}