CLAUDE.md

150 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## What This Is

Congo is a single-binary Go framework CLI. It scaffolds web projects with vendored source code (copied into `internal/`), runs dev servers, builds production binaries, and deploys them. The module path is `congo.gg`.

## Build & Verify

```bash
go build -o /dev/null ./cmd                 # Quick check: CLI compiles
go build -o /dev/null ./web                 # Website compiles
go build -o /dev/null ./dev                 # Workspace compiles

# Tests
go test ./pkg/...                           # All framework tests
go test ./pkg/database/...                  # Single package
go test -run TestCollectionCRUD ./pkg/...   # Single test
```

After any change, verify with: `go build -o /dev/null ./cmd && go build -o /dev/null ./web`

## Structure

```
congo.go        Root — embeds res/scaffold/, pkg/, res/claude-context.md as ScaffoldFS, SourceFS, ClaudeContext
cmd/main.go     CLI dispatcher (switch on os.Args[1])
cmd/commands/   Subcommands: init, new, dev, test, build, launch, connect, claude, source, status, logs, destroy
cmd/internal/   Scaffold rendering, deployment, provisioning, image building, infra config
pkg/            Framework source (vendored into user projects via congo init)
  application/  MVC — App embeds *http.ServeMux, controllers, views, functional options, emailer
  database/     Data storage — Collection[T], auto-migration, LibSQL engines
  router/       Networking — domain proxy, TLS autocert, logging, server lifecycle
  security/     HTTP security — nonce, CSP headers, rate limiting, JWT, bcrypt
  assistant/    AI — provider abstraction (Anthropic/OpenAI/mock), streaming, tool calling
  platform/     Infrastructure — provider abstraction (DigitalOcean/metal/mock), Docker, SSH
  frontend/     Client rendering — React islands, esbuild bundler, HMR via SSE
res/scaffold/   Project templates (*.tmpl files using <<>> delimiters)
res/            Also contains claude-context.md, dev-setup.sh, cloud-init.sh
web/            Marketing website — dogfoods the framework (congo.gg)
dev/            Workspace app — code-server, Docker hosting, AI agent, domain routing
infra.json      Deployment config (platforms, servers, services, instances)
```

## Declarative Composition

Applications are composed with functional options (Dave Cheney pattern):

```go
router.Listen(
    router.WithLogger(),
    security.New(security.WithNonce(), security.WithHeaders()),
    application.New(views,
        application.WithController(controllers.Home()),
    ),
)
```

`router.Listen` composes the middleware chain and starts the server.
`security.New` creates composable security middleware backed by a database.
`application.New` creates the MVC application as terminal middleware.
App embeds `*http.ServeMux` — controllers register routes via `app.Handle`.

## Package Dependency Graph

```
database        (no deps)     — foundation
router          (no deps)     — foundation
assistant       (no deps)     — foundation
platform        (no deps)     — foundation

security        → database    — composite
application     → router      — composite (currently; router dep being removed)
frontend        → application — composite
```

## Key Architecture

### App Embeds ServeMux

`App` embeds `*http.ServeMux`. Controllers call `app.Handle("GET /path", handler)` and `app.HandleFunc("GET /path", fn)` directly — inherited methods, no wrappers. The terminal middleware returns `app.ServeMux`.

### Embed & Vendor Pattern

`congo.go` embeds the entire source tree via `//go:embed`. `congo init` extracts `pkg/` into `internal/`, rewrites imports. `congo source` extracts the full buildable source tree. Every binary can reproduce itself.

### Scaffold Template Delimiters

Scaffold templates in `res/scaffold/` use `<<.Field>>` syntax (not `{{.Field}}`) to avoid conflicts with Go templates in the scaffolded project.

### CLI Dispatch

`cmd/main.go` uses a switch on `os.Args[1]`. Each command in `cmd/commands/` uses its own `flag.FlagSet`.

### Deployment Flow (congo launch)

Reads `infra.json` → provisions servers → builds Docker images → uploads via SSH → starts containers. Setup scripts are idempotent.

### web/ — Marketing Website

Controllers: Home, Downloads, Source, Stars, Git, MailingList. Pages: /, /philosophy, /framework, /workspace, /source, /download. Serves congo.gg.

### dev/ — Congo Workspace

Single-server development workspace. Controllers: Auth, Dashboard, Services, Repos, Explorer, Routes, Agent, Tasks, Work.

```
         INTERNET
            |
    ┌───────┴───────┐
    │  Go autocert  │  :80/:443
    └───────┬───────┘
  ┌─────────┼──────────────┐
  │         │              │
your.gg   app.your.gg   code.your.gg
  │         │              │
┌─┴──┐  ┌──┴────┐    ┌────┴────┐
│web │  │hosted │    │ code-   │
│app │  │ app   │    │ server  │
└────┘  └───────┘    └─────────┘
   all on Docker internal network
```

Go handles TLS via autocert. No Caddy. All containers on internal Docker network.

**Models**: User, Repository, Domain, Conversation, Task, LogEntry, Plan.

**Auth**: Single-user setup wizard → JWT session cookies (HS256, 30-day). `RequireAuth()` bouncer.

## Code Conventions

- IDs are always strings (UUIDs)
- SQL columns use PascalCase: `WHERE UserID = ?`
- Value receiver on `Handle()` for request isolation
- Templates referenced by filename only: `{{template "nav.html" .}}`
- `cmp.Or()` for env var defaults
- App embeds `*http.ServeMux` — routes via `app.Handle`, `app.HandleFunc`
- Package-level vars as runtime state (no config structs)

## Critical: Build Artifacts

Never put build outputs in source directories. `congo.go` uses `//go:embed all:` which will embed binaries. Always build to `build/` or `/tmp/`.

## Editing Guidelines

- Changes to `pkg/` affect the framework source users receive via `congo init`
- Changes to `res/scaffold/*.tmpl` use `<<.Field>>` syntax, not `{{.Field}}`
- Changes to `cmd/internal/` affect deployment, provisioning, and scaffolding
- Each `pkg/` package file should own one concept — avoid single-file packages