# AgentGuard — Design & Implementation Plan

> A quality-assurance engine for LLM-generated code.
> Python engine + HTTP protocol + MCP server + thin SDKs for any language.
> Open-core: MIT library + paid cloud dashboard + archetype marketplace.
>
> Working name: **AgentGuard** (rename before launch)
> Status: **Ready for implementation**

---

## Table of Contents

1. [Vision & Value Proposition](#1-vision--value-proposition)
2. [How It Works (30-Second Overview)](#2-how-it-works-30-second-overview)
3. [Engine Architecture](#3-engine-architecture)
4. [Integration Models](#4-integration-models)
5. [HTTP Service & Protocol](#5-http-service--protocol)
6. [MCP Server (Model Context Protocol)](#6-mcp-server-model-context-protocol)
7. [Thin SDKs (Non-Python Languages)](#7-thin-sdks-non-python-languages)
8. [Package Structure](#8-package-structure)
9. [Module 1: LLM Abstraction](#9-module-1-llm-abstraction)
10. [Module 2: Project Archetypes](#10-module-2-project-archetypes)
11. [Module 3: Context Recipes](#11-module-3-context-recipes)
12. [Module 4: Top-Down Generation](#12-module-4-top-down-generation)
13. [Module 5: Structural Validation](#13-module-5-structural-validation)
14. [Module 6: Self-Challenge](#14-module-6-self-challenge)
15. [Module 7: Tracing & Cost Tracking](#15-module-7-tracing--cost-tracking)
16. [Module 8: Prompt Management](#16-module-8-prompt-management)
17. [The Pipeline — Putting It All Together](#17-the-pipeline--putting-it-all-together)
18. [Framework-Specific Integrations](#18-framework-specific-integrations)
19. [Built-in Archetypes (Free Tier)](#19-built-in-archetypes-free-tier)
20. [API Reference (Public Surface)](#20-api-reference-public-surface)
21. [Business Model](#21-business-model)
22. [Implementation Plan](#22-implementation-plan)
23. [Go-to-Market](#23-go-to-market)
24. [Technical Decisions](#24-technical-decisions)
25. [Open Questions](#25-open-questions)

---

## 1. Vision & Value Proposition

### The Problem

Every team building AI coding agents faces the same failure modes:

1. **Hallucination** — The LLM invents APIs, modules, or libraries that don't exist
2. **Scope explosion** — A simple script gets an enterprise architecture
3. **No verification** — Code ships without even checking if it parses
4. **Context chaos** — The LLM gets too much, too little, or the wrong context
5. **Invisible cost** — Nobody knows how much each LLM call costs or which model works best
6. **No consistency** — Every generation is a dice roll; same prompt gives different quality

### The Solution

AgentGuard is a **quality infrastructure layer** for LLM code generation. It sits between your agent and the LLM, ensuring that every piece of generated code is:

- **Structurally sound** — Parses, lints, type-checks before any human sees it
- **Properly scoped** — Project archetypes prevent over/under-engineering
- **Built top-down** — Skeleton → contracts → wiring → logic (general to particular)
- **Self-verified** — The LLM reviews its own output against explicit criteria
- **Cost-tracked** — Every token, every dollar, every model comparison — visible

### One Sentence

> AgentGuard is pytest for AI-generated code — you wouldn't ship untested code, so why ship unvalidated AI code?

### Who Uses It

| User | Language | How They Use It |
|------|----------|----------------|
| Teams building AI coding agents (Python) | Python | `pip install agentguard` — direct library import |
| Teams building AI coding agents (TypeScript, Go, etc.) | Any | `agentguard serve` → HTTP API → thin SDK in their language |
| Solo developers using LLMs for code | Any | CLI or library — generate better code with less manual review |
| Enterprises evaluating AI code gen | Any | Cloud dashboard — cost, quality, and model comparison |
| Agent framework authors (LangGraph, CrewAI) | Python | Built-in integration wrappers |

---

## 2. How It Works (30-Second Overview)

```python
from agentguard import Pipeline, Archetype

# 1. Pick a project type
arch = Archetype.load("api_backend")

# 2. Create a quality pipeline
pipe = Pipeline(archetype=arch, llm="anthropic/claude-sonnet-4-20250514")

# 3. Generate code top-down (skeleton → contracts → wiring → logic)
project = pipe.generate(
    spec="A user authentication API with JWT tokens, registration, and login",
)
# Returns: validated, self-challenged, traced code at every level

# 4. See what happened
print(project.trace.summary())
# → 12 LLM calls | $0.34 total | 3 structural fixes | 1 self-challenge rework
# → 6 functions generated | 0 hallucinated imports | all types resolve
```

That's it. One import, four lines, and you get reliable code with full traceability.

---

## 3. Engine Architecture

AgentGuard is a **Python engine** that can be consumed in three ways:
1. **Direct import** — Python agents import the library natively (zero overhead)
2. **HTTP service** — Any language calls `agentguard serve` over HTTP/JSON
3. **MCP server** — AI tools (Claude Desktop, Cursor, Windsurf, Cline) discover AgentGuard tools automatically via the [Model Context Protocol](https://modelcontextprotocol.io/)

All three modes run the exact same engine. Same quality, same features, same traces.

```
┌─────────────────────────────────────────────────────┐
│                   YOUR AGENT / APP                   │
│         (OpenHands, LangGraph, CrewAI, raw)          │
└────────────────────────┬────────────────────────────┘
                         │  uses
┌────────────────────────▼────────────────────────────┐
│                     AGENTGUARD                       │
│                                                      │
│  ┌──────────────────────────────────────────────┐   │
│  │              Pipeline (orchestrates)           │   │
│  └──────┬───────┬───────┬───────┬───────┬───────┘   │
│         │       │       │       │       │            │
│  ┌──────▼──┐ ┌──▼────┐ ┌▼─────┐ ┌▼────┐ ┌▼───────┐ │
│  │Top-Down │ │Context│ │Struc.│ │Self-│ │Tracing │ │
│  │Generator│ │Recipes│ │Valid.│ │Chall│ │& Cost  │ │
│  └────┬────┘ └───┬───┘ └──┬───┘ └──┬──┘ └───┬────┘ │
│       │          │        │        │         │      │
│  ┌────▼──────────▼────────▼────────▼─────────▼───┐  │
│  │         Archetype (configures everything)      │  │
│  └────────────────────────┬──────────────────────┘  │
│                           │                          │
│  ┌────────────────────────▼──────────────────────┐  │
│  │     LLM Abstraction + Prompt Management        │  │
│  └────────────────────────┬──────────────────────┘  │
│                           │                          │
│  ┌────────────────────────▼──────────────────────┐  │
│  │        Trace Store (local JSON / cloud)        │  │
│  └───────────────────────────────────────────────┘  │
└──────────────────────────────────────────────────────┘
                         │  calls
              ┌──────────┼──────────┐
              │          │          │
         ┌────▼──┐  ┌───▼────┐ ┌───▼─────┐
         │OpenAI │  │ Google │ │Anthropic│  ... any LLM
         └───────┘  └────────┘ └─────────┘
```

### Key Principle: Write the Brain Once

All intelligence (top-down generation, self-challenge, validation, context recipes) lives in the Python engine. Other languages get a thin HTTP client; AI tools get MCP. Bug fix once → every language and every tool gets it.

**Prior art**: Docker (Go engine, HTTP API, thin CLIs in every language), Terraform (Go engine, CDK wrappers in Python/TS/Go/Java), Redis (C engine, thin clients in 50+ languages), Language Server Protocol (one server, any editor), MCP (one tool server, any AI client).

### Design Principles

1. **Engine + Protocol** — Python engine is the single source of truth; HTTP/JSON + MCP are the universal protocols
2. **Python-native fast path** — Python agents import directly, zero overhead, no HTTP
3. **Works with any LLM** — OpenAI, Anthropic, Google, local models, anything with a chat API
4. **Works with any agent, any language** — Python direct, HTTP service for TS/Go/Rust/etc., MCP for AI tools
5. **Zero-config for AI tools** — MCP server lets Claude Desktop, Cursor, Windsurf, Cline use AgentGuard with no code
6. **Archetype-driven** — The archetype configures the entire pipeline
7. **Trace everything** — Every LLM call, validation, and decision is recorded
7. **Fail fast** — Structural validation catches errors before spending tokens on self-challenge
8. **Composable** — Use the full pipeline, or just the validator, or just top-down generation

---

## 4. Integration Models

How developers connect their agents to AgentGuard depends on their language and preferences.

### Mode A: Direct Python Import (Python agents)

Your agent imports AgentGuard as a library. No server, no HTTP, no overhead.

```python
# Your Python agent
from agentguard import Pipeline

class MyAgent:
    def __init__(self):
        self.pipe = Pipeline(archetype="api_backend", llm="anthropic/claude-sonnet-4-20250514")

    async def handle_request(self, user_request: str):
        # Your agent logic: understand the request, decide what to build
        spec = self.understand(user_request)

        # AgentGuard handles reliable code generation
        result = await self.pipe.generate(spec)

        # Your agent logic: write files, run tests, deploy
        self.write_to_disk(result.files)
        self.run_tests()
```

### Mode B: HTTP Service (TypeScript, Go, Rust, any language)

Run AgentGuard as a local service. Your agent talks to it over HTTP.

```bash
# Start the engine (one command)
$ agentguard serve --port 8420
```

```typescript
// Your TypeScript agent
import { AgentGuard } from "@agentguard/sdk";

const ag = new AgentGuard({ url: "http://localhost:8420" });

const result = await ag.generate({
  spec: "A user auth API with JWT tokens",
  archetype: "api_backend",
  llm: "anthropic/claude-sonnet-4-20250514",
});

console.log(result.files);          // { "src/auth/service.py": "..." }
console.log(result.trace.summary);  // 12 calls, $0.34, 3 fixes
```

```go
// Your Go agent
client := agentguard.NewClient("http://localhost:8420")
result, err := client.Generate(ctx, agentguard.GenerateRequest{
    Spec:      "A user auth API with JWT tokens",
    Archetype: "api_backend",
    LLM:       "anthropic/claude-sonnet-4-20250514",
})
```

### Mode C: Composable Pieces (use only what you need)

Your agent already generates code its own way. You just want validation, or just self-challenge.

```python
# Python: just validate
from agentguard import Validator
report = Validator.check({"main.py": my_code})

# Python: just self-challenge
from agentguard import SelfChallenger
result = await SelfChallenger.challenge(my_code, criteria=["No hardcoded secrets"])
```

```typescript
// TypeScript: just validate (via HTTP)
const report = await ag.validate({ files: { "main.py": myCode } });

// TypeScript: just challenge
const result = await ag.challenge({
  code: myCode,
  criteria: ["No hardcoded secrets"],
});
```

### Mode D: AgentGuard as Your Agent's Foundation

You're building a new agent from scratch. AgentGuard provides the code generation backbone;
you build the brain (user interaction, deployment, project management) around it.

```python
class MyProductAgent:
    """Your agent. AgentGuard is the code engine underneath."""

    def __init__(self):
        self.pipe = Pipeline(archetype="api_backend", llm="anthropic/claude-sonnet-4-20250514")

    async def chat(self, message: str) -> str:
        # YOUR logic: understand what the user wants
        spec = await self.refine_requirements(message)
        # YOUR logic: estimate cost
        estimate = await self.estimate_cost(spec)
        # AGENTGUARD: generate reliable code
        result = await self.pipe.generate(spec)
        # YOUR logic: deploy, test, deliver
        await self.deploy(result.files)
        return f"Done! {result.trace.summary()}"
```

### Mode E: MCP Server (zero-code integration)

AI tools that support the [Model Context Protocol](https://modelcontextprotocol.io/) (Claude Desktop, Cursor, Windsurf, Cline, OpenHands) discover AgentGuard tools **automatically**. No SDK, no HTTP calls, no integration code.

```jsonc
// Claude Desktop — ~/.claude/claude_desktop_config.json
// Cursor — .cursor/mcp.json
// Windsurf, Cline — similar config files
{
  "mcpServers": {
    "agentguard": {
      "command": "agentguard",
      "args": ["mcp-serve"]
    }
  }
}
```

That's it. The AI tool now has access to all AgentGuard capabilities as native tools:

```
Tools auto-discovered by the AI tool:
  • agentguard_generate     — Generate code from spec using an archetype
  • agentguard_validate     — Validate existing code against an archetype
  • agentguard_challenge    — Self-challenge code against quality criteria
  • agentguard_list_archetypes — List available archetypes
  • agentguard_get_archetype   — Get details of a specific archetype
  • agentguard_trace_summary   — Get trace summary for a generation run
```

The AI tool's LLM decides when to invoke these tools based on conversation context — no glue code needed.

### Integration Summary

| Mode | Language | What Your Agent Does | What AgentGuard Does |
|------|----------|---------------------|---------------------|
| A — Direct import | Python | Everything else (UI, deploy, logic) | Reliable code generation |
| B — HTTP service | Any | Everything else | Same, over HTTP |
| C — Composable | Any | Generates code itself | Validates / challenges it |
| D — Foundation | Python | Brain (users, deploy, PM) | Hands (code generation) |
| E — MCP server | Any MCP client | Just talks to the user | Everything (generation, validation, tools) |

---

## 5. HTTP Service & Protocol

### Starting the Service

```bash
# Default: localhost:8420
$ agentguard serve

# Custom port, expose to network
$ agentguard serve --host 0.0.0.0 --port 9000

# With authentication (required for cloud / shared environments)
$ agentguard serve --port 8420 --api-key "my-secret-key"
```

### REST API Endpoints

| Method | Path | Maps To | Description |
|--------|------|---------|-------------|
| `POST` | `/v1/generate` | `Pipeline.generate()` | Full top-down generation |
| `POST` | `/v1/validate` | `Validator.check()` | Structural validation |
| `POST` | `/v1/challenge` | `SelfChallenger.challenge()` | LLM self-review |
| `POST` | `/v1/skeleton` | `Pipeline.skeleton()` | L1 only |
| `POST` | `/v1/contracts` | `Pipeline.contracts()` | L2 only |
| `POST` | `/v1/wiring` | `Pipeline.wiring()` | L3 only |
| `POST` | `/v1/logic` | `Pipeline.logic()` | L4 only |
| `GET`  | `/v1/archetypes` | `Archetype.list_available()` | List archetypes |
| `GET`  | `/v1/archetypes/{id}` | `Archetype.load()` | Get archetype details |
| `GET`  | `/v1/traces` | `Tracer.list()` | List recent traces |
| `GET`  | `/v1/traces/{id}` | `Tracer.get()` | Get trace details |
| `GET`  | `/health` | — | Health check |

### Request / Response Examples

```json
// POST /v1/generate
{
  "spec": "A user auth API with JWT tokens",
  "archetype": "api_backend",
  "llm": "anthropic/claude-sonnet-4-20250514",
  "options": {
    "skip_challenge": false,
    "parallel_l4": true,
    "max_challenge_retries": 3
  }
}

// Response
{
  "files": {
    "src/auth/main.py": "from fastapi import FastAPI...",
    "src/auth/service.py": "...",
    "src/auth/models.py": "..."
  },
  "trace": {
    "id": "tr_abc123",
    "total_llm_calls": 12,
    "total_cost": { "total": "0.34", "currency": "USD" },
    "structural_fixes": 3,
    "challenge_reworks": 1,
    "duration_ms": 45000,
    "levels_completed": ["skeleton", "contracts", "wiring", "logic"]
  }
}
```

```json
// POST /v1/validate
{
  "files": {
    "main.py": "import fastapi\n\napp = FastAPI()..."
  },
  "archetype": "api_backend",
  "checks": ["syntax", "lint", "types", "imports"]
}

// Response
{
  "passed": true,
  "checks": [
    { "check": "syntax", "passed": true, "duration_ms": 1 },
    { "check": "lint", "passed": true, "duration_ms": 95 }
  ],
  "auto_fixed": [
    { "file": "main.py", "fix": "removed unused import os", "line": 3 }
  ],
  "errors": []
}
```

### Protocol Design

| Property | Choice | Rationale |
|----------|--------|-----------|
| Format | JSON over HTTP | Universal — every language has HTTP + JSON |
| Auth | API key in header (`X-Api-Key`) | Simple, same as cloud dashboard |
| Streaming | SSE for `/v1/generate` (optional) | Long-running — stream level completions |
| Errors | RFC 7807 problem detail | Standard error format |
| Versioning | URL prefix (`/v1/`) | Stable protocol across upgrades |

### Same Protocol, Local and Cloud

```typescript
// Local engine (free)
const ag = new AgentGuard({ url: "http://localhost:8420" });

// Cloud engine (paid — no local Python needed!)
const ag = new AgentGuard({ url: "https://api.agentguard.dev", apiKey: "ag_xxx" });

// EXACT same code works with both — just change the URL
const result = await ag.generate({ spec: "...", archetype: "api_backend" });
```

This means the cloud dashboard isn't just a viewer — it **is** the hosted engine.
TypeScript/Go teams that don't want to install Python can just use the cloud directly.

---

## 6. MCP Server (Model Context Protocol)

The [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) is an open standard that lets AI tools discover and use external capabilities. AgentGuard exposes its entire engine as MCP tools — enabling **zero-code integration** with any MCP-compatible client.

### Why MCP Matters for AgentGuard

| Integration Mode | Integration Effort | Who Writes Code? |
|-----------------|-------------------|-------------------|
| Python import | `pip install` + code changes | Developer |
| HTTP service | `agentguard serve` + SDK + code changes | Developer |
| **MCP server** | **Add 3 lines to a JSON config** | **Nobody — the AI tool does it** |

MCP is the **lowest-friction** way to adopt AgentGuard. A developer adds AgentGuard to their AI tool's config, and the tool's LLM autonomously decides when to use generation, validation, and self-challenge.

### Starting the MCP Server

```bash
# stdio transport (default — for local AI tools like Claude Desktop, Cursor)
$ agentguard mcp-serve

# SSE transport (for remote/network MCP clients)
$ agentguard mcp-serve --transport sse --port 8421
```

### Tool Definitions

AgentGuard exposes the following MCP tools. Each tool maps directly to a Pipeline method.

#### `agentguard_generate`

Generate code from a natural language specification using an archetype.

```json
{
  "name": "agentguard_generate",
  "description": "Generate production-quality code from a spec using top-down generation, structural validation, and self-challenge. Returns a set of files that form a valid project.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "spec":      { "type": "string", "description": "Natural language description of what to build" },
      "archetype": { "type": "string", "description": "Project archetype (e.g. api_backend, cli_tool, web_app)", "default": "api_backend" },
      "llm":       { "type": "string", "description": "LLM model identifier (e.g. anthropic/claude-sonnet-4-20250514)", "default": "anthropic/claude-sonnet-4-20250514" }
    },
    "required": ["spec"]
  }
}
```

#### `agentguard_validate`

Validate existing code against an archetype's quality checks.

```json
{
  "name": "agentguard_validate",
  "description": "Run structural validation on code: syntax, lint, types, imports, structure. Returns a pass/fail report with details.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "files":     { "type": "object", "description": "Map of file paths to file contents", "additionalProperties": { "type": "string" } },
      "archetype": { "type": "string", "description": "Archetype to validate against", "default": "api_backend" }
    },
    "required": ["files"]
  }
}
```

#### `agentguard_challenge`

Self-challenge code against quality criteria using an LLM.

```json
{
  "name": "agentguard_challenge",
  "description": "LLM-based self-review: checks code against criteria (security, performance, correctness, hallucination). Returns issues found and suggested fixes.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "code":     { "type": "string", "description": "Code to challenge (or map of files)" },
      "criteria": { "type": "array", "items": { "type": "string" }, "description": "Quality criteria to evaluate against" },
      "llm":      { "type": "string", "description": "LLM to use for challenge", "default": "anthropic/claude-sonnet-4-20250514" }
    },
    "required": ["code"]
  }
}
```

#### `agentguard_list_archetypes`

```json
{
  "name": "agentguard_list_archetypes",
  "description": "List all available project archetypes with their descriptions.",
  "inputSchema": { "type": "object", "properties": {} }
}
```

#### `agentguard_get_archetype`

```json
{
  "name": "agentguard_get_archetype",
  "description": "Get detailed configuration for a specific archetype (tech stack, validation rules, challenge criteria).",
  "inputSchema": {
    "type": "object",
    "properties": {
      "name": { "type": "string", "description": "Archetype name (e.g. api_backend)" }
    },
    "required": ["name"]
  }
}
```

#### `agentguard_trace_summary`

```json
{
  "name": "agentguard_trace_summary",
  "description": "Get a summary of the last generation trace: LLM calls, cost, validation results, challenge results.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "trace_id": { "type": "string", "description": "Trace ID (returned by agentguard_generate). Omit for last trace." }
    }
  }
}
```

### MCP Resources (Read-Only Context)

In addition to tools, AgentGuard exposes MCP **resources** that AI tools can read for context:

| Resource URI | Description |
|-------------|-------------|
| `agentguard://archetypes` | List of all available archetypes |
| `agentguard://archetype/{name}` | Full archetype definition (YAML) |
| `agentguard://traces/latest` | Most recent generation trace |
| `agentguard://traces/{id}` | Specific trace by ID |

### Client Configuration Examples

**Claude Desktop** (`~/.claude/claude_desktop_config.json`):
```json
{
  "mcpServers": {
    "agentguard": {
      "command": "agentguard",
      "args": ["mcp-serve"]
    }
  }
}
```

**Cursor** (`.cursor/mcp.json`):
```json
{
  "mcpServers": {
    "agentguard": {
      "command": "agentguard",
      "args": ["mcp-serve"]
    }
  }
}
```

**Windsurf** (`~/.codeium/windsurf/mcp_config.json`):
```json
{
  "mcpServers": {
    "agentguard": {
      "command": "agentguard",
      "args": ["mcp-serve"]
    }
  }
}
```

**Remote (SSE transport)** — for shared environments or cloud:
```json
{
  "mcpServers": {
    "agentguard": {
      "url": "http://your-server:8421/sse"
    }
  }
}
```

### How It Works Internally

```
┌──────────────────────────────────┐
│  AI Tool (Claude Desktop, etc.)  │
│                                  │
│  User: "Build me a REST API      │
│         with auth and JWT"       │
│                                  │
│  LLM decides to call:           │
│    agentguard_generate(          │
│      spec="REST API with auth    │
│           and JWT",              │
│      archetype="api_backend"     │
│    )                             │
└──────────────┬───────────────────┘
               │  MCP protocol (stdio or SSE)
               │
┌──────────────▼───────────────────┐
│         AgentGuard MCP Server    │
│                                  │
│  mcp/server.py                   │
│    ├── Receives tool call        │
│    ├── Maps to Pipeline method   │
│    ├── Runs engine (same as      │
│    │   Python import / HTTP)     │
│    └── Returns result as MCP     │
│        tool response             │
└──────────────┬───────────────────┘
               │  uses (direct Python import)
               │
┌──────────────▼───────────────────┐
│       AgentGuard Engine          │
│  (Pipeline, Validation, etc.)    │
└──────────────────────────────────┘
```

### MCP vs. HTTP: When to Use Which

| Use Case | Recommended | Why |
|----------|-------------|-----|
| AI coding tools (Claude Desktop, Cursor, Windsurf, Cline) | **MCP** | Zero-code setup, tool auto-discovery |
| Custom agents (TypeScript, Go, Rust) | **HTTP** | Full programmatic control, typed SDKs |
| Python agents | **Direct import** | Zero overhead, full API surface |
| CI/CD pipelines | **HTTP** or **CLI** | Script-friendly, stateless |
| Shared/remote engine | **HTTP** or **MCP (SSE)** | Network transport |

---

## 7. Thin SDKs (Non-Python Languages)

Thin SDKs are **typed HTTP wrappers** — no logic, no duplication. They exist to provide a native developer experience in each language.

### What a Thin SDK Contains

| Component | Lines (approx.) | Purpose |
|-----------|-----------------|---------|
| Client class | ~100 | HTTP connection, auth, base URL |
| Request/response types | ~200 | Typed structs matching JSON schema |
| Method wrappers | ~100 | `generate()`, `validate()`, `challenge()` |
| Error handling | ~50 | Parse error responses, throw typed exceptions |
| SSE streaming (optional) | ~50 | Stream level-by-level progress |
| **Total** | **~500** | |

### TypeScript SDK (`@agentguard/sdk`)

```typescript
// Published to npm
import { AgentGuard, GenerateResult, ValidationReport } from "@agentguard/sdk";

const ag = new AgentGuard({
  url: "http://localhost:8420",  // or https://api.agentguard.dev
  apiKey: "ag_xxx",             // optional for local
});

// Full pipeline
const result: GenerateResult = await ag.generate({
  spec: "A user auth API",
  archetype: "api_backend",
  llm: "anthropic/claude-sonnet-4-20250514",
});

// Just validate
const report: ValidationReport = await ag.validate({
  files: { "main.py": code },
});

// Stream progress (SSE)
for await (const event of ag.generateStream({ spec: "...", archetype: "..." })) {
  console.log(`Level ${event.level} complete: ${event.files.length} files`);
}
```

### Go SDK (`agentguard-go`)

```go
import "github.com/agentguard/agentguard-go"

client := agentguard.NewClient(
    agentguard.WithURL("http://localhost:8420"),
    agentguard.WithAPIKey("ag_xxx"),  // optional for local
)

result, err := client.Generate(ctx, &agentguard.GenerateRequest{
    Spec:      "A user auth API",
    Archetype: "api_backend",
    LLM:       "anthropic/claude-sonnet-4-20250514",
})
if err != nil { log.Fatal(err) }

for path, content := range result.Files {
    os.WriteFile(path, []byte(content), 0644)
}
```

### SDK Priority (Based on Market)

| SDK | Priority | Rationale |
|-----|----------|-----------|
| TypeScript | **P0** (build first) | Vercel AI SDK, LangChain.js, huge agent ecosystem |
| Go | P1 (build if demand) | Growing agent ecosystem, enterprise |
| Rust | P2 (build if demand) | Niche but passionate community |
| Java/Kotlin | P2 (build if demand) | Enterprise |

Only the TypeScript SDK is in the initial implementation plan. Others are added based on user demand.

---

## 8. Package Structure

```
agentguard/
├── __init__.py                   # Public API: Pipeline, Archetype, Validator, ...
├── py.typed                      # PEP 561 type marker
│
├── pipeline.py                   # Pipeline orchestrator (ties everything together)
│
├── llm/                          # Module 1: LLM Abstraction
│   ├── __init__.py
│   ├── base.py                   # LLMProvider ABC
│   ├── openai_provider.py        # OpenAI / Azure OpenAI
│   ├── anthropic_provider.py     # Anthropic Claude
│   ├── google_provider.py        # Google Gemini
│   ├── litellm_provider.py       # LiteLLM passthrough (100+ models)
│   ├── factory.py                # LLMProvider.from_string("anthropic/claude-sonnet-4-20250514")
│   └── types.py                  # LLMResponse, TokenUsage, CostEstimate
│
├── archetypes/                   # Module 2: Project Archetypes
│   ├── __init__.py
│   ├── registry.py               # Load, query, register archetypes
│   ├── base.py                   # Archetype dataclass
│   ├── resolver.py               # Tech stack resolution
│   └── builtin/                  # Built-in archetype YAML definitions
│       ├── script.yaml
│       ├── cli_tool.yaml
│       ├── api_backend.yaml
│       ├── web_app.yaml
│       └── library.yaml
│
├── context/                      # Module 3: Context Recipes
│   ├── __init__.py
│   ├── recipe.py                 # ContextRecipe definitions
│   ├── bundle.py                 # ContextBundle (what the LLM receives)
│   ├── window.py                 # Token budget management
│   └── summarizer.py             # Hierarchical summarization for large artifacts
│
├── topdown/                      # Module 4: Top-Down Generation
│   ├── __init__.py
│   ├── generator.py              # TopDownGenerator (L1→L4 protocol)
│   ├── levels.py                 # Level definitions (SKELETON, CONTRACTS, WIRING, LOGIC)
│   ├── skeleton.py               # L1: file tree + responsibilities
│   ├── contracts.py              # L2: typed stubs with signatures
│   ├── wiring.py                 # L3: import graph + call chain
│   └── logic.py                  # L4: function implementation
│
├── validation/                   # Module 5: Structural Validation
│   ├── __init__.py
│   ├── validator.py              # Validator (runs all checks)
│   ├── checks/
│   │   ├── __init__.py
│   │   ├── syntax.py             # AST parse check
│   │   ├── lint.py               # Ruff (Python), ESLint (JS/TS)
│   │   ├── types.py              # mypy (Python), tsc (TypeScript)
│   │   ├── imports.py            # Import resolution — do all imports exist?
│   │   ├── structure.py          # File structure vs. archetype template
│   │   └── circular.py           # Circular dependency detection
│   └── autofix.py                # Auto-fix for trivial issues (formatting, unused imports)
│
├── challenge/                    # Module 6: Self-Challenge
│   ├── __init__.py
│   ├── challenger.py             # SelfChallenger (LLM-based self-review)
│   ├── criteria.py               # ChallengeResult, CriterionResult
│   └── grounding.py              # Hallucination detection (did the LLM invent things?)
│
├── tracing/                      # Module 7: Tracing & Cost
│   ├── __init__.py
│   ├── tracer.py                 # Tracer context manager
│   ├── trace.py                  # Trace, Span, TraceEvent dataclasses
│   ├── cost.py                   # Cost computation per provider/model
│   ├── store/
│   │   ├── __init__.py
│   │   ├── base.py               # TraceStore ABC
│   │   ├── json_store.py         # Local JSON files (free tier)
│   │   ├── sqlite_store.py       # Local SQLite (free tier, queryable)
│   │   └── cloud_store.py        # Cloud API (paid tier, streams to dashboard)
│   └── pricing.py                # LLM pricing table (auto-updated)
│
├── prompts/                      # Module 8: Prompt Management
│   ├── __init__.py
│   ├── template.py               # PromptTemplate with version + rendering
│   ├── registry.py               # Load templates from YAML
│   └── builtin/                  # Built-in prompt templates
│       ├── skeleton.yaml
│       ├── contracts.yaml
│       ├── wiring.yaml
│       ├── logic.yaml
│       ├── self_challenge.yaml
│       └── grounding_check.yaml
│
├── integrations/                 # Framework integrations (thin wrappers)
│   ├── __init__.py
│   ├── langgraph.py              # LangGraph nodes
│   ├── crewai.py                 # CrewAI tools
│   ├── openhands.py              # OpenHands micro-agent
│   └── llamaindex.py             # LlamaIndex tool
│
├── cli.py                        # CLI: agentguard init, generate, validate, serve, mcp-serve
│
├── server/                       # HTTP service (agentguard serve)
│   ├── __init__.py
│   ├── app.py                    # FastAPI application factory
│   ├── routes.py                 # REST endpoints (generate, validate, challenge, ...)
│   ├── schemas.py                # Pydantic request/response models (JSON contract)
│   ├── sse.py                    # Server-Sent Events for streaming
│   └── auth.py                   # API key middleware
│
├── mcp/                          # MCP server (agentguard mcp-serve)
│   ├── __init__.py
│   ├── server.py                 # MCP server setup (stdio + SSE transports)
│   ├── tools.py                  # Tool definitions (generate, validate, challenge, ...)
│   └── resources.py              # MCP resources (archetypes, traces)
│
└── _version.py                   # Package version
```

Separate repositories for thin SDKs:

```
agentguard-sdk-typescript/        # @agentguard/sdk on npm (~500 lines)
├── src/
│   ├── client.ts                 # AgentGuard class — HTTP client
│   ├── types.ts                  # Request/response types
│   ├── streaming.ts              # SSE streaming support
│   └── errors.ts                 # Typed error handling
├── package.json
├── tsconfig.json
└── README.md

agentguard-go/                    # Go module (~500 lines)
├── client.go
├── types.go
├── errors.go
├── go.mod
└── README.md
```

---

## 9. Module 1: LLM Abstraction

### Purpose

Unified interface to any LLM provider. Every call returns a typed response with token counts and cost estimates.

### Core Interface

```python
class LLMProvider(ABC):
    """Abstract base for all LLM providers."""

    provider_name: str
    model_name: str
    temperature: float

    @abstractmethod
    async def generate(self, messages: list[Message], **kwargs) -> LLMResponse:
        """Generate a completion."""

    @abstractmethod
    async def generate_structured(
        self, messages: list[Message], schema: type[T]
    ) -> T:
        """Generate a structured response matching a Pydantic model."""

    def count_tokens(self, text: str) -> int:
        """Count tokens for this model's tokenizer."""


@dataclass(frozen=True)
class LLMResponse:
    content: str
    model: str
    provider: str
    tokens: TokenUsage
    cost: CostEstimate
    latency_ms: int

@dataclass(frozen=True)
class TokenUsage:
    prompt_tokens: int
    completion_tokens: int
    total_tokens: int

@dataclass(frozen=True)
class CostEstimate:
    input_cost: Decimal
    output_cost: Decimal
    total_cost: Decimal
    currency: str = "USD"
```

### Factory

```python
# String-based construction (for config files)
llm = LLMProvider.from_string("anthropic/claude-sonnet-4-20250514", temperature=0)
llm = LLMProvider.from_string("openai/gpt-4o", temperature=0)
llm = LLMProvider.from_string("google/gemini-2.0-flash", temperature=0.3)

# LiteLLM passthrough (100+ models including local)
llm = LLMProvider.from_string("litellm/ollama/llama3", temperature=0)
```

### Deterministic Settings

| Use Case | Temperature | Rationale |
|----------|-------------|-----------|
| Code generation (L1–L4) | 0 | Deterministic output |
| Self-challenge | 0 | Analytical, not creative |
| Summarization | 0.3 | Slight flexibility for compression |
| Archetype matching | 0.3 | Slight flexibility for matching |

Temperature defaults are set by the pipeline based on the task. Users can override.

---

## 10. Module 2: Project Archetypes

### Purpose

An archetype is a blueprint that tells the entire pipeline **what kind of project this is**. It configures everything: which pipeline steps run, what tech stack to use, what validation checks to apply, what self-challenge criteria matter, and how much context the LLM needs.

### Archetype Definition (YAML)

```yaml
# archetypes/builtin/api_backend.yaml
id: "api_backend"
name: "API Backend Service"
description: "REST API with database, authentication, and business logic"
version: "1.0.0"

tech_stack:
  defaults:
    language: "python"
    framework: "fastapi"
    database: "postgresql"
    testing: "pytest"
    linter: "ruff"
    type_checker: "mypy"
  overridable: true

pipeline:
  levels: ["skeleton", "contracts", "wiring", "logic"]
  enable_self_challenge: true
  enable_structural_validation: true
  max_self_challenge_retries: 3

structure:
  expected_dirs:
    - "src/{project_name}/"
    - "src/{project_name}/models/"
    - "src/{project_name}/routes/"
    - "src/{project_name}/services/"
    - "tests/"
    - "tests/unit/"
    - "tests/integration/"
  expected_files:
    - "src/{project_name}/__init__.py"
    - "src/{project_name}/main.py"
    - "pyproject.toml"
    - "README.md"
    - ".env.example"

context_recipes:
  skeleton:
    include: ["spec", "archetype_structure"]
    max_tokens: 3000
  contracts:
    include: ["spec", "skeleton", "reference_patterns"]
    max_tokens: 6000
  wiring:
    include: ["contracts", "skeleton"]
    max_tokens: 8000
  logic:
    include: ["function_stub", "function_tests", "function_deps", "reference_patterns"]
    max_tokens: 5000

validation:
  checks: ["syntax", "lint", "types", "imports", "structure"]
  lint_rules: "ruff:default"
  type_strictness: "basic"

self_challenge:
  criteria:
    - "All endpoints match the spec"
    - "Authentication implemented as specified"
    - "No hardcoded secrets or credentials"
    - "All referenced imports actually exist"
    - "No invented API endpoints or methods"
    - "Error handling present on all endpoints"
    - "Database models match data requirements"
  grounding_check: true
  assumptions_must_declare: true

reference_patterns:
  - "fastapi_crud_pattern"
  - "jwt_auth_pattern"
  - "sqlalchemy_model_pattern"
  - "pydantic_schema_pattern"
  - "pytest_async_pattern"
```

### Archetype API

```python
# Load built-in
arch = Archetype.load("api_backend")

# Load with overrides
arch = Archetype.load("api_backend", overrides={
    "tech_stack.defaults.framework": "flask",
    "tech_stack.defaults.database": "mongodb",
})

# Load custom (from YAML file)
arch = Archetype.from_file("./my_company_archetype.yaml")

# List available
Archetype.list_available()
# → ["script", "cli_tool", "api_backend", "web_app", "library"]

# Register custom archetype globally
Archetype.register("fintech_api", "./archetypes/fintech_api.yaml")
```

---

## 11. Module 3: Context Recipes

### Purpose

The #1 cause of LLM hallucination in code generation is **wrong context**. Too much → the LLM gets confused. Too little → it invents things. Wrong stuff → it hallucinates based on irrelevant information.

Context recipes solve this by defining **exactly what the LLM should see** for each task type and generation level.

### How It Works

```python
@dataclass
class ContextRecipe:
    """Defines what goes into the LLM's context for a specific task."""
    include: list[str]          # What to include
    exclude: list[str] = []     # Explicit exclusions
    max_tokens: int = 5000      # Token budget
    summarize_if_over: bool = True  # Summarize large items

@dataclass(frozen=True)
class ContextBundle:
    """Immutable context snapshot delivered to the LLM."""
    items: dict[str, str]       # Named context pieces
    token_count: int            # Actual token count
    token_budget: int           # Budget we aimed for
    was_summarized: list[str]   # Which items got summarized
    recipe_id: str              # Which recipe produced this
```

### Recipes per Level

```
Level 1 — SKELETON
  Context: spec + archetype structure template
  Tokens: ~2–3K
  LLM sees: "Build a user auth API" + "Expected files: main.py, routes/, models/, ..."

Level 2 — CONTRACTS
  Context: spec + skeleton output + reference patterns
  Tokens: ~5–6K
  LLM sees: The file list it just generated + example patterns for typed stubs

Level 3 — WIRING
  Context: contracts (all stubs) + skeleton
  Tokens: ~6–8K
  LLM sees: All function signatures + file structure → wire them together

Level 4 — LOGIC (per function)
  Context: this function's stub + its test cases + its dependencies' signatures + reference pattern
  Tokens: ~3–5K
  LLM sees: ONLY what it needs to implement THIS function — nothing else
```

### Why This Matters — The Math

Without context recipes (what most agents do):
```
"Here's the spec (2K tokens) + design doc (8K tokens) + all existing code (15K tokens)
+ all tests (5K tokens) + conversation history (3K tokens) = 33K tokens"

→ LLM is overwhelmed, focuses on wrong things, hallucinates
```

With context recipes (AgentGuard):
```
L4 function implementation:
"Here's the function signature (200 tokens) + its tests (400 tokens)
+ signatures of functions it calls (300 tokens) + relevant pattern (500 tokens)
= 1,400 tokens"

→ LLM has exactly what it needs, nothing more
```

### Summarization for Large Artifacts

```python
class HierarchicalSummarizer:
    """Compress large artifacts to fit token budget."""

    async def summarize(
        self,
        artifact: str,
        target_tokens: int,
        llm: LLMProvider,
        focus: str | None = None,  # "summarize with focus on auth module"
    ) -> str:
        ...
```

Uses a cheap/fast model (Gemini Flash) for summarization to minimize cost.

---

## 12. Module 4: Top-Down Generation

### Purpose

The core innovation. Instead of asking the LLM to generate an entire project at once (which causes hallucination and inconsistency), we generate **level by level**, validating at each gate.

### The Four Levels

```
L1: SKELETON      → "What files do I need?"
    Input:  spec + archetype structure
    Output: File list with one-line purpose per file
    Gate:   Matches archetype structure? No extras? No missing?

L2: CONTRACTS     → "What does each file expose?"
    Input:  skeleton + spec + reference patterns
    Output: Function/class stubs with typed signatures (valid, parseable code)
    Gate:   Syntax? Types resolve? Imports exist?

L3: WIRING        → "How do the files connect?"
    Input:  contracts + skeleton
    Output: Import graph + function calls (business logic = NotImplementedError)
    Gate:   No circular imports? Call chain complete? All imports resolve?

L4: LOGIC         → "Implement one function at a time"
    Input:  function stub + its tests + dependency signatures + pattern
    Output: Complete function implementation
    Gate:   Tests pass? Lint clean? Types check?
```

### Generator API

```python
class TopDownGenerator:
    """Generates code level-by-level with validation gates between levels."""

    def __init__(
        self,
        llm: LLMProvider,
        archetype: Archetype,
        tracer: Tracer,
        validator: Validator,
        challenger: SelfChallenger,
        context_engine: ContextEngine,
    ): ...

    async def generate(self, spec: str) -> GenerationResult:
        """Run the full L1→L4 pipeline."""
        skeleton  = await self.skeleton(spec)
        contracts = await self.contracts(skeleton)
        wiring    = await self.wiring(contracts)
        logic     = await self.logic(wiring)
        return GenerationResult(skeleton, contracts, wiring, logic)

    async def skeleton(self, spec: str) -> SkeletonResult:
        """L1: Generate file tree with responsibilities."""

    async def contracts(self, skeleton: SkeletonResult) -> ContractsResult:
        """L2: Generate typed stubs for each file."""

    async def wiring(self, contracts: ContractsResult) -> WiringResult:
        """L3: Wire imports and call chains."""

    async def logic(
        self,
        wiring: WiringResult,
        functions: list[str] | None = None  # Specific functions, or all
    ) -> LogicResult:
        """L4: Implement function bodies (parallelizable)."""


@dataclass
class GenerationResult:
    skeleton: SkeletonResult
    contracts: ContractsResult
    wiring: WiringResult
    logic: LogicResult
    trace: Trace                     # Full trace of all LLM calls
    files: dict[str, str]            # Final file contents
    total_cost: CostEstimate
    validation_fixes: int            # How many structural fixes were auto-applied
    challenge_reworks: int           # How many self-challenge reworks happened
```

### L2 Output Example (Real, Parseable Code)

```python
# L2 output for src/auth/service.py — valid Python, parseable, type-checkable
from dataclasses import dataclass
from .models import User, AuthToken
from .repository import UserRepository


@dataclass
class AuthService:
    """Handles user authentication and token management."""

    repo: UserRepository

    def register(self, email: str, password: str) -> User:
        """Register a new user. Raises ValueError if email exists."""
        raise NotImplementedError  # → L4

    def authenticate(self, email: str, password: str) -> AuthToken:
        """Authenticate user, return JWT. Raises AuthError if invalid."""
        raise NotImplementedError  # → L4

    def validate_token(self, token: str) -> User | None:
        """Validate JWT, return user. Returns None if expired/invalid."""
        raise NotImplementedError  # → L4
```

This is **real code** — it parses, lints, and type-checks. The only thing missing is the function bodies. That's L4's job.

### L4 Context (Why It's Anti-Hallucination)

```
To implement `register()`, the LLM receives ONLY:

1. Function stub:         register(email: str, password: str) -> User
2. Docstring:             "Register a new user. Raises ValueError if email exists."
3. Test cases:            test_register_success, test_register_duplicate_email
4. Dependencies:          UserRepository.create(email, hashed_pw) -> User
                          UserRepository.get_by_email(email) -> User | None
5. Reference pattern:     "Create entity with duplicate check" from archetype

Total: ~1,400 tokens. The LLM cannot hallucinate because there's nothing
irrelevant to be confused by.
```

### Parallel L4 Generation

L4 functions within the same module are **independent** — they can be generated in parallel:

```python
# Pipeline generates L4 in parallel batches
async def logic(self, wiring: WiringResult) -> LogicResult:
    functions = wiring.get_all_functions()
    # Group by file, generate in parallel
    results = await asyncio.gather(*[
        self._implement_function(fn) for fn in functions
    ])
    return LogicResult(results)
```

---

## 13. Module 5: Structural Validation

### Purpose

Mechanical checks that run **before** the LLM-based self-challenge. No tokens spent — just tools. Catches ~60% of issues at zero cost.

### Validator API

```python
class Validator:
    """Runs structural checks on generated code."""

    def check(
        self,
        code: str | dict[str, str],  # Single file or {filename: content}
        checks: list[str] | None = None,  # Subset, or all from archetype
        archetype: Archetype | None = None,
        autofix: bool = True,  # Auto-fix trivial issues (formatting, unused imports)
    ) -> ValidationReport:
        ...

@dataclass
class ValidationReport:
    passed: bool
    checks: list[CheckResult]
    auto_fixed: list[AutoFix]
    errors: list[ValidationError]

    @property
    def blocking_errors(self) -> list[ValidationError]:
        """Errors that must be fixed (not auto-fixable)."""

@dataclass
class CheckResult:
    check: str           # "syntax", "lint", "types", "imports", "structure"
    passed: bool
    details: str
    duration_ms: int
```

### Available Checks

| Check | Tool | What It Catches | Cost |
|-------|------|-----------------|------|
| `syntax` | `ast.parse()` (Python), `esprima` (JS) | Code that doesn't parse | Free, <1ms |
| `lint` | Ruff (Python), ESLint (JS/TS) | Style violations, common bugs, unused imports | Free, ~100ms |
| `types` | mypy (Python), tsc (TypeScript) | Type mismatches, missing annotations | Free, ~500ms |
| `imports` | Static analysis | Nonexistent modules, wrong import paths | Free, ~50ms |
| `structure` | Archetype template compare | Missing files, wrong directory layout | Free, ~10ms |
| `circular` | Import graph analysis | Circular dependencies | Free, ~50ms |

### Auto-Fix

Trivial issues are fixed automatically without re-prompting the LLM:

```
Auto-fixable:
  ✅ Unused imports → remove them
  ✅ Formatting issues → reformat with Ruff
  ✅ Missing trailing newline → add it
  ✅ Wrong import order → reorder

NOT auto-fixable (requires LLM rework):
  ❌ Function calls wrong API
  ❌ Missing type annotation on complex type
  ❌ Circular dependency between modules
  ❌ Import for module that doesn't exist
```

---

## 14. Module 6: Self-Challenge

### Purpose

After structural validation passes, the LLM reviews its own output against explicit acceptance criteria. This is the **semantic** quality gate — it catches logical issues that tools can't detect.

### Challenger API

```python
class SelfChallenger:
    """LLM-based self-evaluation against criteria."""

    async def challenge(
        self,
        output: str,
        criteria: list[str],
        context: ContextBundle,
        level: Level,
        max_retries: int = 3,
        grounding_check: bool = True,
    ) -> ChallengeResult:
        ...

    async def rework(
        self,
        output: str,
        feedback: str,
        context: ContextBundle,
    ) -> str:
        """Re-generate output incorporating challenge feedback."""

@dataclass
class ChallengeResult:
    passed: bool
    attempt: int
    criteria_results: list[CriterionResult]
    assumptions: list[str]            # What the LLM assumed (must declare)
    grounding_violations: list[str]   # Things the LLM invented
    feedback: str | None              # If failed: what to fix
    rework_output: str | None         # If reworked: the new output

@dataclass
class CriterionResult:
    criterion: str
    passed: bool
    explanation: str
```

### Challenge Prompt (Internal)

```
You completed: {task_description}
Your output:
```
{output}
```

Evaluate your output against each criterion below. For each, answer PASS or FAIL
with a one-line explanation:

{criteria_list}

Then answer these grounding questions:
1. Did you use any API, function, class, or module that was NOT in your provided context?
   If yes, list each one.
2. List every assumption you made that was not explicitly stated in the spec.

Be strict. If in doubt, FAIL.
```

### Challenge Flow

```
Output from L2/L3/L4
    │
    ▼
Structural Validation (free, fast)
    │ pass
    ▼
Self-Challenge (LLM call, ~2K tokens)
    │
    ├── All criteria pass + no grounding violations → ✅ DONE
    │
    └── Some criteria fail or grounding violation detected
         │
         ▼
    Rework (LLM call with feedback)
         │
         ▼
    Structural Validation (re-check)
         │
         ▼
    Self-Challenge (attempt 2)
         │
         └── Max retries reached → return best attempt + warning
```

---

## 15. Module 7: Tracing & Cost Tracking

### Purpose

Every LLM call, validation, and decision is recorded. This serves two purposes:
1. **Free tier**: Local traces for debugging and understanding what happened
2. **Paid tier**: Cloud dashboard for cost analytics, quality metrics, model comparison

### Trace Model

```python
@dataclass
class Trace:
    """Top-level trace for one pipeline run."""
    id: str
    started_at: datetime
    ended_at: datetime | None
    archetype: str
    spec_summary: str
    spans: list[Span]

    def summary(self) -> TraceSummary: ...
    def to_json(self) -> str: ...

@dataclass
class Span:
    """One operation within a trace."""
    id: str
    parent_id: str | None
    type: SpanType
    name: str
    started_at: datetime
    ended_at: datetime
    metadata: dict
    children: list[Span]

class SpanType(str, Enum):
    PIPELINE = "pipeline"           # Full pipeline run
    LEVEL = "level"                 # L1, L2, L3, L4
    LLM_CALL = "llm_call"          # Single LLM request
    VALIDATION = "validation"       # Structural validation run
    CHALLENGE = "challenge"         # Self-challenge evaluation
    REWORK = "rework"               # Challenge-triggered rework
    AUTOFIX = "autofix"             # Structural auto-fix
    SUMMARIZATION = "summarization" # Context summarization

@dataclass
class TraceSummary:
    total_llm_calls: int
    total_tokens: TokenUsage
    total_cost: CostEstimate
    levels_completed: list[str]
    structural_fixes: int
    challenge_reworks: int
    grounding_violations: int
    duration_ms: int
    model_breakdown: dict[str, CostEstimate]  # Cost per model used
```

### Trace Storage

```python
# Free: local JSON (default)
tracer = Tracer(store=JsonTraceStore("./traces/"))

# Free: local SQLite (queryable)
tracer = Tracer(store=SqliteTraceStore("./traces.db"))

# Paid: cloud dashboard
tracer = Tracer(store=CloudTraceStore(api_key="ag_xxx"))

# Combine: local + cloud
tracer = Tracer(store=MultiStore([
    SqliteTraceStore("./traces.db"),
    CloudTraceStore(api_key="ag_xxx"),
]))
```

### Cost Table (Auto-Updated)

```python
# Built-in pricing for major providers (updated monthly)
PRICING = {
    "anthropic/claude-sonnet-4-20250514": {
        "input_per_1k": Decimal("0.003"),
        "output_per_1k": Decimal("0.015"),
    },
    "openai/gpt-4o": {
        "input_per_1k": Decimal("0.0025"),
        "output_per_1k": Decimal("0.01"),
    },
    "google/gemini-2.0-flash": {
        "input_per_1k": Decimal("0.0001"),
        "output_per_1k": Decimal("0.0004"),
    },
    # ... more models
}
```

---

## 16. Module 8: Prompt Management

### Purpose

Versioned, template-based prompts for every LLM call. Enables A/B testing, debugging, and improvement over time.

### Template Structure

```yaml
# prompts/builtin/contracts.yaml
id: "contracts"
version: "1.0.0"
description: "Generate typed function/class stubs for a file"

system: |
  You are a code architect. Your job is to create typed function and class stubs.
  RULES:
  - Output valid, parseable {language} code
  - Every function body must be: raise NotImplementedError
  - Include complete type annotations on all parameters and return types
  - Include docstrings explaining what each function does
  - Use ONLY imports from modules listed in your context
  - Do NOT invent any modules, classes, or functions not in your context

user: |
  Create typed stubs for file: {file_path}

  Project specification:
  {spec_summary}

  File skeleton (L1):
  {skeleton_entry}

  Reference patterns:
  {reference_patterns}

  Other files in this module (for cross-references):
  {module_files}

  Output ONLY the Python code. No explanations.
```

### Prompt API

```python
template = PromptTemplate.load("contracts")
messages = template.render(
    language="python",
    file_path="src/auth/service.py",
    spec_summary="User auth API with JWT...",
    skeleton_entry="AuthService class with register, authenticate, validate",
    reference_patterns="...",
    module_files="...",
)
# messages = [{"role": "system", ...}, {"role": "user", ...}]

# Version is tracked in traces
template.version  # "1.0.0"
```

---

## 17. The Pipeline — Putting It All Together

### Pipeline API

```python
class Pipeline:
    """The main entry point. Orchestrates the full quality pipeline."""

    def __init__(
        self,
        archetype: Archetype | str,
        llm: LLMProvider | str,
        challenge_llm: LLMProvider | str | None = None,  # Cheaper model for challenges
        trace_store: TraceStore | None = None,
        prompt_overrides: dict[str, PromptTemplate] | None = None,
    ): ...

    async def generate(
        self,
        spec: str,
        *,
        levels: list[Level] | None = None,       # Run specific levels only
        skip_challenge: bool = False,              # Skip self-challenge (faster, less safe)
        skip_validation: bool = False,             # Skip structural validation
        parallel_l4: bool = True,                  # Parallel function generation
        max_challenge_retries: int | None = None,  # Override archetype default
    ) -> GenerationResult: ...

    # Individual steps (composable)
    async def skeleton(self, spec: str) -> SkeletonResult: ...
    async def contracts(self, skeleton: SkeletonResult) -> ContractsResult: ...
    async def wiring(self, contracts: ContractsResult) -> WiringResult: ...
    async def logic(self, wiring: WiringResult) -> LogicResult: ...

    # Standalone operations
    async def validate(self, code: dict[str, str]) -> ValidationReport: ...
    async def challenge(self, code: str, criteria: list[str]) -> ChallengeResult: ...
```

### Usage Patterns

```python
# Pattern 1: Full pipeline (recommended)
pipe = Pipeline(archetype="api_backend", llm="anthropic/claude-sonnet-4-20250514")
result = await pipe.generate("A user auth API with JWT tokens")
for path, content in result.files.items():
    Path(path).write_text(content)

# Pattern 2: Just validation (use with any code, not just generated)
report = await pipe.validate({"main.py": my_code})

# Pattern 3: Just self-challenge (use with any output)
challenge = await pipe.challenge(my_code, criteria=["No hardcoded secrets"])

# Pattern 4: Step by step (maximum control)
skeleton = await pipe.skeleton("A CLI that converts CSV to JSON")
# inspect, modify, then continue
contracts = await pipe.contracts(skeleton)

# Pattern 5: Different models per step
pipe = Pipeline(
    archetype="api_backend",
    llm="anthropic/claude-sonnet-4-20250514",           # Main generation
    challenge_llm="google/gemini-2.0-flash",  # Cheaper for self-challenge
)
```

### Pipeline Flow (Internal)

```
spec
 │
 ▼
LOAD ARCHETYPE → configure pipeline, validation, criteria, recipes
 │
 ▼
L1: SKELETON
 │ context recipe: spec + structure template (~2K tokens)
 │ → LLM generates file list
 │ → Validate: files match archetype structure?
 │ → Self-challenge: anything missing? unnecessary?
 │
 ▼
L2: CONTRACTS
 │ context recipe: spec + skeleton + patterns (~5K tokens)
 │ → LLM generates typed stubs per file
 │ → Structural validation: parse? lint? types? imports?
 │   └─ auto-fix trivials, re-prompt on blockers
 │ → Self-challenge: interfaces match spec? no inventions?
 │
 ▼
L3: WIRING
 │ context recipe: contracts + skeleton (~7K tokens)
 │ → LLM wires imports and call chains
 │ → Structural validation: circular deps? all imports resolve?
 │ → Self-challenge: call chain matches design? complete?
 │
 ▼
L4: LOGIC (parallel per function)
 │ context recipe per function: stub + tests + deps + pattern (~3K tokens)
 │ → LLM implements function body
 │ → Structural validation: parse? lint? types?
 │ → Self-challenge: matches spec? no hardcoded values? tests should pass?
 │
 ▼
ASSEMBLE → merge all files → final validation → return result + trace
```

---

## 18. Framework-Specific Integrations

These are Python-specific convenience wrappers for popular agent frameworks.
Non-Python frameworks use the HTTP service (see §4 Mode B and §7), or MCP (see §6).

### LangGraph

```python
from agentguard.integrations.langgraph import (
    make_skeleton_node,
    make_contracts_node,
    make_wiring_node,
    make_logic_node,
    make_validation_node,
    make_challenge_node,
)

# Each returns a LangGraph-compatible node
graph.add_node("skeleton", make_skeleton_node(archetype="api_backend"))
graph.add_node("contracts", make_contracts_node())
graph.add_node("validate", make_validation_node())
graph.add_node("challenge", make_challenge_node())
# Wire them into your existing graph
```

### CrewAI

```python
from agentguard.integrations.crewai import (
    TopDownGeneratorTool,
    StructuralValidatorTool,
    SelfChallengeTool,
)

# Use as tools within CrewAI agents
dev_agent = Agent(
    role="Developer",
    tools=[
        TopDownGeneratorTool(archetype="api_backend"),
        StructuralValidatorTool(),
        SelfChallengeTool(),
    ],
)
```

### OpenHands

```python
from agentguard.integrations.openhands import AgentGuardMicroAgent

# Register as a micro-agent in OpenHands
micro_agent = AgentGuardMicroAgent(archetype="api_backend")
```

### Raw Python (no framework)

```python
from agentguard import Pipeline
# Already shown above — no framework needed
```

---

## 19. Built-in Archetypes (Free Tier)

Five archetypes ship with the MIT-licensed library:

| Archetype | Pipeline | Target |
|-----------|----------|--------|
| `script` | L1→L4 (no L2/L3 for simple scripts) | "Parse CSV and email summary" |
| `cli_tool` | L1→L2→L3→L4 | "Docker management CLI with Click" |
| `api_backend` | L1→L2→L3→L4 (full) | "User auth API with FastAPI" |
| `web_app` | L1→L2→L3→L4 (full, frontend+backend) | "Todo app with React + FastAPI" |
| `library` | L1→L2→L3→L4 (heavy on contracts) | "Python SDK for Stripe API" |

### What Archetypes Include

Each archetype bundles:
- **Structure template**: Expected directories and files
- **Context recipes**: Token budgets per level
- **Validation config**: Which checks to run, linter config
- **Self-challenge criteria**: Acceptance criteria per level
- **Reference patterns**: Idiomatic code patterns (e.g., "FastAPI CRUD route")
- **Anti-patterns**: Known mistakes (e.g., "Don't use sync DB calls in async FastAPI")

### Pro Archetypes (Paid)

| Archetype | What's Extra |
|-----------|-------------|
| `data_pipeline` | Airflow/Prefect patterns, data validation, schema evolution |
| `infrastructure` | Terraform patterns, security groups, least-privilege IAM |
| `mobile_backend` | Firebase patterns, push notification, offline-first API design |
| `fintech_api` | PCI-DSS patterns, audit logging, transaction handling |
| `healthcare_api` | HIPAA patterns, data encryption, consent management |
| `saas_starter` | Multi-tenant patterns, auth, billing, subscription management |
| `microservice` | gRPC patterns, service mesh, circuit breakers |
| `ml_pipeline` | MLflow integration, experiment tracking, model serving |

---

## 20. API Reference (Public Surface)

### Top-Level Exports

```python
from agentguard import (
    # Main entry point
    Pipeline,

    # Configuration
    Archetype,
    configure,                  # Global config (API key, defaults)

    # Individual components (composable)
    TopDownGenerator,
    Validator,
    SelfChallenger,
    ContextRecipe,
    ContextBundle,

    # LLM
    LLMProvider,

    # Tracing
    Tracer,
    Trace,
    TraceSummary,

    # Results
    GenerationResult,
    SkeletonResult,
    ContractsResult,
    WiringResult,
    LogicResult,
    ValidationReport,
    ChallengeResult,

    # Enums
    Level,                      # SKELETON, CONTRACTS, WIRING, LOGIC
)
```

### Configuration

```python
import agentguard

# Global configuration (optional, for cloud features)
agentguard.configure(
    api_key="ag_xxx",                     # Cloud dashboard API key
    default_llm="anthropic/claude-sonnet-4-20250514",  # Default model
    default_archetype="api_backend",      # Default archetype
    trace_store="sqlite://./traces.db",   # Default trace storage
)
```

### CLI

```bash
# Initialize a project with an archetype
agentguard init --archetype api_backend --name my_project

# Generate code from spec
agentguard generate --spec "A user auth API with JWT" --archetype api_backend

# Validate existing code
agentguard validate ./src/ --archetype api_backend

# Start HTTP service (for non-Python agents)
agentguard serve --port 8420
agentguard serve --host 0.0.0.0 --port 9000 --api-key "my-key"

# Start MCP server (for AI tools: Claude Desktop, Cursor, Windsurf, Cline)
agentguard mcp-serve                           # stdio transport (default)
agentguard mcp-serve --transport sse --port 8421  # SSE transport (remote)

# View traces
agentguard traces list
agentguard traces show <trace-id>

# Cost summary
agentguard costs --last 30d
```

---

## 21. Business Model

### Revenue Streams

```
                    ┌─────────────────────────────┐
                    │       OPEN SOURCE (MIT)      │
                    │                               │
                    │  • Pipeline engine            │
                    │  • Top-down generation        │
                    │  • Self-challenge             │
                    │  • Structural validation      │
                    │  • Context recipes            │
                    │  • 5 built-in archetypes      │
                    │  • Local tracing (JSON/SQLite)│
                    │  • HTTP service + protocol    │
                    │  • MCP server                 │
                    │  • All LLM providers          │
                    │  • Framework integrations     │
                    │  • TypeScript SDK (@npm)      │
                    │  • CLI                        │
                    │                               │
                    │  Gets: adoption, stars, trust │
                    └──────────────┬────────────────┘
                                   │
              ┌────────────────────┼────────────────────┐
              │                    │                    │
    ┌─────────▼──────────┐ ┌──────▼──────────┐ ┌──────▼──────────┐
    │  CLOUD DASHBOARD   │ │ PRO ARCHETYPES  │ │  ENTERPRISE     │
    │  $29/seat/month    │ │ $49/month       │ │  Custom pricing │
    │                    │ │                 │ │                 │
    │ • Trace viewer     │ │ • 20+ curated   │ │ • Self-hosted   │
    │ • Cost analytics   │ │   archetypes    │ │   dashboard     │
    │ • Quality metrics  │ │ • Reference     │ │ • Private       │
    │ • Model comparison │ │   implementations│ │   archetypes    │
    │ • Team dashboards  │ │ • Anti-patterns │ │ • SSO/SAML      │
    │ • Alerts           │ │ • Security      │ │ • Audit logs    │
    │ • Export reports    │ │   checklists    │ │ • Support SLA   │
    │                    │ │ • Marketplace   │ │ • Custom model  │
    │ Revenue: recurring │ │   access        │ │   evaluation    │
    │ per seat           │ │                 │ │                 │
    │                    │ │ Revenue:        │ │ Revenue:        │
    │                    │ │ recurring       │ │ high-value      │
    │                    │ │ + marketplace   │ │ contracts       │
    │                    │ │ commission      │ │                 │
    └────────────────────┘ └─────────────────┘ └─────────────────┘
```

### Archetype Marketplace (Long-Term)

```
Community authors create archetypes:
  → "django_rest_api" by @djangodev (free)
  → "terraform_aws_production" by @cloudguru ($19 one-time)
  → "hipaa_compliant_api" by @healthtech ($49 one-time)
  → "stripe_integration" by @paymentpro ($29 one-time)

AgentGuard takes 25% commission on paid archetypes.
Authors keep 75%.

Network effect:
  More archetypes → more users → more archetypes → moat
```

### Unit Economics

```
Cloud Dashboard:
  $29/seat/month → at 1000 seats: $29K MRR → $348K ARR
  Infrastructure cost: ~$3/seat/month (trace storage, API hosting)
  Margin: ~90%

Pro Archetypes:
  $49/month → at 500 subscribers: $24.5K MRR → $294K ARR
  Infrastructure cost: negligible (YAML files + reference code)
  Margin: ~95%

Marketplace:
  Assume 100 paid archetypes, avg $30, 50 sales/month each
  Gross: $150K/month → $1.8M/year
  Commission (25%): $450K/year
```

---

## 22. Implementation Plan

### Phase 0: Core Engine (Weeks 1–2)

> The skeleton of the library. At the end: top-down generation works with one archetype.

| # | Task | Deliverable |
|---|------|-------------|
| 0.1 | Initialize repo: `pyproject.toml`, `uv`, `ruff`, `mypy`, `pytest` | Clean Python project |
| 0.2 | Build `llm/` — LLMProvider ABC + Anthropic implementation | Can call Claude and get typed responses with token counts |
| 0.3 | Build `llm/` — OpenAI implementation | Can call GPT and get typed responses |
| 0.4 | Build `llm/factory.py` — String-based construction | `LLMProvider.from_string("anthropic/claude-sonnet-4-20250514")` works |
| 0.5 | Build `tracing/` — Tracer + Span + JsonTraceStore | Every LLM call creates a trace span with cost |
| 0.6 | Build `tracing/cost.py` — Pricing table | Cost computed per call |
| 0.7 | Build `prompts/` — PromptTemplate + builtin templates | Template rendering with version tracking |
| 0.8 | Build `archetypes/` — Archetype loader + `api_backend.yaml` | One archetype loads and configures pipeline |
| 0.9 | Build `topdown/skeleton.py` — L1 generator | Generates file list from spec |
| 0.10 | Build `topdown/contracts.py` — L2 generator | Generates typed stubs |
| 0.11 | Build `topdown/wiring.py` — L3 generator | Generates import graph |
| 0.12 | Build `topdown/logic.py` — L4 generator | Implements function bodies |
| 0.13 | Build `pipeline.py` — Pipeline (wires L1→L4) | `Pipeline.generate()` works end to end |
| 0.14 | Test: generate a simple FastAPI project with the pipeline | Proof it works |

**Exit criteria**: `Pipeline(archetype="api_backend", llm="anthropic/...").generate("A user auth API")` produces a set of Python files that form a valid project. Traces show every LLM call with cost.

---

### Phase 1: Quality Layer (Weeks 3–4)

> Add structural validation and self-challenge. At the end: generated code is verified.

| # | Task | Deliverable |
|---|------|-------------|
| 1.1 | Build `validation/checks/syntax.py` — AST parse check | Can detect unparseable Python |
| 1.2 | Build `validation/checks/lint.py` — Ruff integration | Lint errors detected |
| 1.3 | Build `validation/checks/types.py` — mypy integration | Type errors detected |
| 1.4 | Build `validation/checks/imports.py` — Import resolution | Phantom imports caught |
| 1.5 | Build `validation/checks/structure.py` — Archetype structure check | Missing files detected |
| 1.6 | Build `validation/autofix.py` — Auto-fix trivial issues | Formatting fixed automatically |
| 1.7 | Build `validation/validator.py` — Validator orchestrator | `Validator.check()` runs all checks |
| 1.8 | Build `challenge/challenger.py` — SelfChallenger | LLM self-evaluates against criteria |
| 1.9 | Build `challenge/grounding.py` — Hallucination detector | Catches invented APIs/modules |
| 1.10 | Integrate validation + challenge into Pipeline | Gate between every level |
| 1.11 | Build `context/recipe.py` — ContextRecipe engine | Recipes limit what the LLM sees |
| 1.12 | Build `context/window.py` — Token budget management | Context fits within budget |
| 1.13 | Build `context/summarizer.py` — Hierarchical summarizer | Large artifacts compressed |
| 1.14 | Test: generate API project, verify all validation catches | Prove quality works |

**Exit criteria**: A generated project passes structural validation. Self-challenge catches at least one issue and reworks it. Context recipes produce appropriately scoped bundles. Traces show validation + challenge results.

---

### Phase 2: HTTP Service + MCP Server + Archetypes + Polish (Weeks 5–8)

> Add HTTP service, MCP server, remaining archetypes, CLI, docs. At the end: ready for PyPI launch + any language and any AI tool can use it.

| # | Task | Deliverable |
|---|------|-------------|
| 2.1 | Build `server/app.py` — FastAPI HTTP wrapper around Pipeline | Engine exposed over HTTP |
| 2.2 | Build `server/routes.py` — All REST endpoints (generate, validate, challenge, etc.) | Full API surface |
| 2.3 | Build `server/schemas.py` — Pydantic request/response models | JSON contract for thin SDKs |
| 2.4 | Build `server/sse.py` — Server-Sent Events for streaming | Level-by-level progress |
| 2.5 | Build `server/auth.py` — API key middleware | Secure shared deployments |
| 2.6 | Add `agentguard serve` CLI command | One command starts the service |
| 2.7 | Build `mcp/server.py` — MCP server with stdio + SSE transports | MCP server runs |
| 2.8 | Build `mcp/tools.py` — Tool definitions (generate, validate, challenge, list/get archetypes, trace) | All tools discoverable by MCP clients |
| 2.9 | Build `mcp/resources.py` — MCP resources (archetypes, traces) | AI tools can read archetype definitions |
| 2.10 | Add `agentguard mcp-serve` CLI command | One command starts MCP server |
| 2.11 | Test MCP server with Claude Desktop + Cursor | Verified zero-config integration |
| 2.12 | Build archetype: `script.yaml` (simplified pipeline) | Scripts use fast path |
| 2.13 | Build archetype: `cli_tool.yaml` | CLI tools properly structured |
| 2.14 | Build archetype: `web_app.yaml` | Full-stack projects supported |
| 2.15 | Build archetype: `library.yaml` | Library projects (heavy on contracts/API) |
| 2.16 | Add reference patterns per archetype | `fastapi_crud`, `jwt_auth`, `click_cli`, etc. |
| 2.17 | Build CLI with `init`, `generate`, `validate`, `traces`, `serve`, `mcp-serve` | Full CLI |
| 2.18 | Build Google Gemini LLM provider | Third provider |
| 2.19 | Build LiteLLM passthrough provider | 100+ models supported |
| 2.20 | Write documentation (README, quickstart, API reference, protocol spec, MCP setup guide) | Docs site (mkdocs) |
| 2.21 | Write 3 example projects (script, API, CLI tool) | Runnable examples |
| 2.22 | Comprehensive test suite (library + HTTP service + MCP server) | >80% coverage |
| 2.23 | PyPI packaging + publish | `pip install agentguard` works |
| 2.24 | Export OpenAPI spec from server | Auto-generated, used by SDK generators |

**Exit criteria**: Library published on PyPI. `agentguard serve` starts an HTTP server. `agentguard mcp-serve` starts an MCP server. Claude Desktop and Cursor can discover and use AgentGuard tools. OpenAPI spec exported. 5 archetypes work. CLI works. Any language can call the HTTP API. Documentation complete.

---

### Phase 3: TypeScript SDK + Framework Integrations + Launch (Weeks 9–11)

> TypeScript SDK, Python framework integrations, public launch.

| # | Task | Deliverable |
|---|------|-------------|
| 3.1 | Build `@agentguard/sdk` TypeScript package — client class | `npm install @agentguard/sdk` works |
| 3.2 | Build TS SDK — typed request/response interfaces | Full type safety |
| 3.3 | Build TS SDK — SSE streaming support | Stream level completions |
| 3.4 | Build TS SDK — error handling | Typed exceptions |
| 3.5 | Write TS SDK tests | >90% coverage (it's small) |
| 3.6 | Publish `@agentguard/sdk` to npm | TypeScript agents can use AgentGuard |
| 3.7 | Build LangGraph integration (Python) | LangGraph nodes for each pipeline step |
| 3.8 | Build CrewAI integration (Python) | CrewAI tools for generation + validation |
| 3.9 | Build OpenHands integration (Python) | OpenHands micro-agent |
| 3.10 | Write integration guides (one per framework + TypeScript + MCP) | How-to docs |
| 3.11 | Write TS example: "TypeScript agent using AgentGuard" | Proof it works cross-language |
| 3.12 | Write launch blog post: "Why Your AI Coding Agent Needs a Quality Layer" | Marketing content |
| 3.13 | Write technical blog: "Top-Down Generation Eliminates Hallucination" | Technical credibility |
| 3.14 | Write blog: "Use AgentGuard from TypeScript, Go, or Any Language" | Cross-language reach |
| 3.15 | Write blog: "Add Code Quality to Claude Desktop in 30 Seconds (MCP)" | MCP adoption content |
| 3.16 | Launch on GitHub (MIT license) | Public repo |
| 3.17 | Post on Hacker News, Reddit, X/Twitter | Community awareness |
| 3.18 | Submit to awesome-llm lists, MCP server directories, and AI newsletters | Distribution |

**Exit criteria**: Python library + HTTP service + MCP server + TypeScript SDK all public. Any TypeScript agent can `npm install @agentguard/sdk` and use the full engine. Claude Desktop and Cursor users can add 3 lines of config and get AgentGuard tools. Integrations work with at least 2 Python frameworks. Blog posts published.

---

### Phase 4: Cloud Dashboard MVP (Weeks 12–15)

> The first paid product. Trace viewer + cost analytics. Cloud IS the hosted engine.

| # | Task | Deliverable |
|---|------|-------------|
| 4.1 | Design dashboard data model (PostgreSQL) | Schema for traces, costs, users |
| 4.2 | Build cloud trace ingestion API (FastAPI) | Library streams traces to cloud |
| 4.3 | Build `tracing/store/cloud_store.py` in library | Cloud store sends traces via HTTPS |
| 4.4 | Build dashboard frontend: trace viewer | See every LLM call, validation, challenge |
| 4.5 | Build dashboard frontend: cost analytics | Cost per project, per model, per level |
| 4.6 | Build dashboard frontend: quality metrics | Challenge pass rates, validation catch rates |
| 4.7 | Build dashboard frontend: model comparison | "Claude costs $X with Y% quality, GPT costs..." |
| 4.8 | Build authentication (GitHub OAuth or email) | Users can sign in |
| 4.9 | Build API key management | Users generate `ag_xxx` keys |
| 4.10 | Build Stripe integration | Subscriptions at $29/seat/month |
| 4.11 | Deploy cloud (Vercel + Railway or Fly.io) | Hosted and live |
| 4.12 | Cloud acts as hosted engine — same HTTP API | TS/Go teams use cloud without installing Python |

**Exit criteria**: Users can `configure(api_key="ag_xxx")`, traces stream to cloud, dashboard shows cost and quality analytics. Cloud serves as hosted engine for non-Python teams. Stripe processes payments.

---

### Phase 5: Pro Archetypes + Marketplace + Go SDK (Weeks 16–18)

> More archetypes, marketplace infrastructure, second thin SDK if demand exists.

| # | Task | Deliverable |
|---|------|-------------|
| 5.1 | Build 5 pro archetypes (data_pipeline, infrastructure, saas_starter, fintech_api, microservice) | Pro tier content |
| 5.2 | Build archetype packaging format | Standard for community submissions |
| 5.3 | Build archetype marketplace UI | Browse, search, install archetypes |
| 5.4 | Build author submission flow | Community can create + submit |
| 5.5 | Build Pro tier gating in library | `Archetype.load("fintech_api", tier="pro")` checks license |
| 5.6 | Add Stripe subscription for Pro ($49/month) | Pro billing works |
| 5.7 | If demand: Build `agentguard-go` Go SDK | Go agents can use AgentGuard |

**Exit criteria**: Pro archetypes available. Marketplace exists and accepts community submissions. Revenue from dashboard + pro subscriptions. Go SDK if user demand exists.

---

### Timeline Summary

```
Week  1–2   Phase 0: Core engine (top-down generation works)
Week  3–4   Phase 1: Quality layer (validation + self-challenge)
Week  5–8   Phase 2: HTTP service + MCP server + archetypes + CLI + docs + PyPI
                    ◄── agentguard serve + mcp-serve work (any language / any AI tool)
Week  9–11  Phase 3: TypeScript SDK + framework integrations + launch
                    ◄── OPEN SOURCE LAUNCH (Python + TypeScript + MCP)
Week 12–15  Phase 4: Cloud dashboard MVP (hosted engine + analytics)
                    ◄── FIRST REVENUE (Week ~14)
Week 16–18  Phase 5: Pro archetypes + marketplace + Go SDK
                    ◄── SECOND REVENUE STREAM

Week 1–11:  Building the free engine + SDKs + MCP (adoption)
Week 12–18: Building paid products (revenue)
```

---

## 23. Go-to-Market

### Audience Tiers

```
Tier 1: Individual developers using LLMs for code
  → Find via: Hacker News, Reddit, X/Twitter, Dev.to
  → Hook: "pip install agentguard — your AI code is now validated"
  → Converts to: GitHub stars, word of mouth

Tier 2: Teams building AI coding agents
  → Find via: LangGraph/CrewAI/OpenHands communities, AI engineering newsletters
  → Hook: Integration guide for their framework
  → Converts to: Cloud dashboard subscriptions

Tier 3: Enterprises evaluating AI code gen
  → Find via: Blog posts on quality/cost, conference talks
  → Hook: "See exactly how much your AI code generation costs and how reliable it is"
  → Converts to: Enterprise contracts
```

### Content Strategy

| Week | Content | Channel |
|------|---------|---------|
| 9 (launch) | "Why Your AI Coding Agent Needs a Quality Layer" | Blog + HN + Reddit |
| 9 | "Top-Down Generation: How to Eliminate Hallucination in AI Code" | Blog + X |
| 9 | "Add Code Quality to Claude Desktop in 30 Seconds" (MCP demo) | Blog + X + YouTube |
| 10 | "AgentGuard + LangGraph: Reliable Code in 10 Lines" | LangGraph community |
| 11 | "How Much Does Your AI Code Actually Cost? (We Built a Dashboard)" | Blog + HN |
| 12 | "AgentGuard vs. Raw GPT-4: Quality Comparison on 50 Projects" | Blog + Reddit |
| 13 | "Building a Custom Archetype for Django" (tutorial) | YouTube + blog |
| 15 | "AgentGuard Marketplace: Share Your Code Quality Blueprints" | Blog + X |

### Community Strategy

1. **GitHub Discussions**: Support, feature requests, archetype ideas
2. **Discord**: Real-time community for agent builders
3. **Office hours**: Monthly live stream showing new features and answering questions
4. **Archetype bounties**: Pay community members to build popular archetypes

---

## 24. Technical Decisions

| Decision | Choice | Rationale |
|----------|--------|-----------|
| Engine language | Python 3.11+ | AI/ML ecosystem is Python-first |
| Cross-language protocol | HTTP/JSON (REST) | Universal — every language has HTTP + JSON |
| AI tool protocol | MCP (Model Context Protocol) | Open standard, supported by Claude Desktop, Cursor, Windsurf, Cline |
| MCP SDK | `mcp` Python package (official) | Maintained by Anthropic, handles stdio + SSE transports |
| Service framework | FastAPI | Already a dependency; auto-generates OpenAPI spec |
| First thin SDK | TypeScript | Largest non-Python agent ecosystem (Vercel AI SDK, LangChain.js) |
| SDK generation | Hand-written (not auto-gen) | ~500 lines, hand-written is higher quality for v1 |
| Package manager | uv | Fast, modern |
| Linting | Ruff | Extremely fast, used for both library dev and as validation check |
| Type checking | mypy | Standard, also used as validation check |
| Testing | pytest + pytest-asyncio | Standard for async Python |
| LLM abstraction | Custom (not LangChain) | Lighter, typed, cost-tracked — LangChain is too heavy for a library |
| LiteLLM | Optional integration | Covers 100+ models without us maintaining providers |
| Serialization | Pydantic v2 | Industry standard, fast; also used for HTTP request/response schemas |
| Templating | Jinja2 | Prompts are templates with variables |
| CLI | Click | Standard for Python CLIs |
| Docs | MkDocs + Material | Clean, searchable, code-friendly |
| Dashboard backend | FastAPI | Same as service — consistent ecosystem |
| Dashboard frontend | React + Tailwind (or Next.js) | SaaS-ready |
| Dashboard DB | PostgreSQL | Proven for analytics queries |
| Dashboard hosting | Fly.io or Railway | Simple, affordable for MVP |
| Payments | Stripe | Standard |

### What We Don't Build

| Thing | Why Not |
|-------|---------|
| Agent framework | There are many (LangGraph, CrewAI, OpenHands). We integrate, not compete. |
| Full SDKs per language | Engine is Python; other languages get thin HTTP wrappers (~500 lines) |
| Code execution sandbox | Not our concern — the caller handles execution |
| Git integration | Not our concern — the caller handles version control |
| Web UI for code generation | We're a library/engine, not an app |
| Deployment pipeline | Not our concern — we generate code, others deploy it |

---

## 25. Open Questions

| # | Question | Impact | Decision Needed By |
|---|----------|--------|--------------------|
| Q1 | Library name — "AgentGuard"? Something else? | Branding | Before Week 8 (launch) |
| Q2 | LiteLLM as a hard dependency or optional? | Install size | Phase 0 |
| Q3 | ~~Support non-Python agents?~~ **RESOLVED**: HTTP service + thin SDKs | — | — |
| Q4 | How to handle archetype versioning in marketplace? | Architecture | Phase 5 |
| Q5 | Dashboard: build custom or use PostHog/Grafana? | Build vs. buy | Phase 4 |
| Q6 | Pricing: $29 too low? Too high? | Revenue | Phase 4 |
| Q7 | Should the cloud service allow BYO-LLM-key or proxy through us? | Revenue/UX | Phase 4 |
| Q8 | Auto-generate thin SDKs from OpenAPI spec or hand-write? | Maintenance | Phase 3 |
| Q9 | npm scope: `@agentguard/sdk` or `agentguard`? | Branding | Phase 3 |
| Q10 | MCP: Should `agentguard_generate` stream progress via MCP notifications, or return all at once? | UX | Phase 2 |
| Q11 | MCP: List on official MCP server directories at launch, or wait for traction? | Go-to-market | Phase 3 |
| Q12 | MCP: Should MCP server support custom archetype loading from user's working directory? | UX | Phase 2 |

---

## Appendix: How This Reuses the ADT Design

Almost everything designed for the full ADT platform maps to a library module:

| ADT Design Section | Library Module | Reuse |
|--------------------|---------------|-------|
| §10 Top-Down Generation | `topdown/` | Direct — same L1→L4 protocol |
| §11 Self-Challenge Protocol | `challenge/` | Direct — same criteria-based evaluation |
| §12 Structural Validation | `validation/` | Direct — same checks |
| §8 Context Manager | `context/` | Simplified — recipes without task queue |
| §9 Project Archetypes | `archetypes/` | Direct — same YAML format |
| §16 Tracing & Cost | `tracing/` | Simplified — no hierarchical project traces |
| §15 Prompt Versioning | `prompts/` | Direct — same versioned templates |
| §13 LLM Abstraction | `llm/` | Direct — same multi-provider design |
| §23 Escalation Protocol | Removed | Library throws exception, caller decides |
| §7 Agent Coordinator | Removed | No agents, no coordination needed |
| §5 Task Model | Removed | No persistent tasks — pipeline is synchronous |
| §18 Data Model | Simplified | Only traces table for cloud dashboard |
| §17 Web UI | Dashboard only | Cost/quality analytics, not project management |

**Time saved**: ~60% of the design work for the library was already done in the ADT design sessions.

---

*This document is the complete specification for AgentGuard. Ready to start Phase 0.*
