1 Commits

Author SHA1 Message Date
Ryan Hamamura
f4d5a52cf9 Switch to datastar-pro and stop tracking downloaded libs
All checks were successful
CI / Deploy / test (pull_request) Successful in 20s
CI / Deploy / lint (pull_request) Successful in 34s
CI / Deploy / deploy (pull_request) Has been skipped
Datastar-pro is fetched from a private Gitea repo (ryan/vendor-libs)
using VENDOR_TOKEN for CI/Docker builds, with a local fallback from
../optional/ for development. DaisyUI is pinned to v5.5.19 instead of
tracking latest. Downloaded files are now gitignored and fetched at
build time via 'task download', which is a dependency of both build
and live tasks.
2026-03-11 11:33:38 -10:00

237
AGENTS.md
View File

@@ -9,7 +9,6 @@ Instructions for AI coding agents working in this repository.
task live # Hot-reload dev server (templ + tailwind + air) task live # Hot-reload dev server (templ + tailwind + air)
task build # Production build to bin/games task build # Production build to bin/games
task run # Build and run server task run # Build and run server
task download # Download pinned client-side libs (datastar-pro, daisyui)
# Quality # Quality
task test # Run all tests: go test ./... task test # Run all tests: go test ./...
@@ -17,80 +16,106 @@ task lint # Run linter: golangci-lint run
# Single test # Single test
go test -run TestName ./path/to/package go test -run TestName ./path/to/package
go test -v -run TestHandleLogin_Success ./features/auth
# Code generation # Code generation
task build:templ # Compile .templ files (go tool templ generate) task build:templ # Compile .templ files
task build:styles # Build TailwindCSS (go tool gotailwind) task build:styles # Build TailwindCSS
go generate ./... # Run sqlc for DB queries
``` ```
Tools (templ, air, gotailwind, goose, sqlc) are managed via Go 1.25's `tool` directive in go.mod — no separate installs needed.
## Workflow Rules ## Workflow Rules
- **Never merge PRs without explicit user approval.** Create the PR, push changes, then wait. - **Never merge PRs without explicit user approval.** Create the PR, push changes, then wait.
- Always use PRs via `tea` CLI never push directly to main. - Always use PRs via `tea` CLI - never push directly to main.
- Write semantic commit messages focusing on "why" not "what". - Write semantic commit messages focusing on "why" not "what".
## Project Structure ## Project Structure
``` ```
games/ games/
├── connect4/, snake/ # Game logic packages (pure Go, no HTTP) ├── connect4/, snake/ # Game logic packages (pure Go)
├── features/ # Feature modules (handlers, routes, templates) ├── features/ # Feature modules (handlers, routes, templates)
│ ├── auth/ # Login/register (standard HTTP, not SSE) │ ├── auth/ # Login/register
│ ├── c4game/ # Connect 4 UI + services │ ├── c4game/ # Connect 4 UI
│ ├── snakegame/ # Snake UI + services │ ├── snakegame/ # Snake UI
│ ├── lobby/ # Game lobby │ ├── lobby/ # Game lobby
│ └── common/ # Shared components, layouts │ └── common/ # Shared components, layouts
├── chat/ # Reusable chat room (NATS + optional DB persistence) ├── chat/ # Reusable chat room (NATS + persistence)
├── auth/ # Password hashing/validation (pure, no HTTP)
├── db/ # SQLite, migrations, sqlc queries ├── db/ # SQLite, migrations, sqlc queries
├── cmd/downloader/ # Build-time tool: fetches datastar-pro + daisyui ├── assets/ # Static files (embedded)
── assets/ # Static files (embedded in prod, filesystem in dev) ── config/, logging/, nats/, sessions/, router/ # Infrastructure
└── config/, logging/, nats/, sessions/, router/, player/, version/
``` ```
## Code Style ## Code Style
### Imports ### Imports
Three groups separated by blank lines: stdlib, third-party, local. Enforced by goimports with `local-prefixes: github.com/ryanhamamura/games`. Organize in three groups: stdlib, third-party, local. The linter enforces this.
```go ```go
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5"
"github.com/rs/zerolog/log"
"github.com/ryanhamamura/games/connect4" "github.com/ryanhamamura/games/connect4"
"github.com/ryanhamamura/games/db/repository"
) )
``` ```
### Naming Conventions
| Type | Convention | Examples |
|------|------------|----------|
| Files | lowercase, underscores | `config_dev.go`, `handlers.go` |
| HTTP handlers | `Handle` prefix | `HandleGamePage`, `HandleLogin` |
| Constructors | `New` prefix | `NewStore`, `NewRoom` |
| Getters | `Get` prefix | `GetPlayerID`, `GetGame` |
| Setup functions | `Setup` prefix | `SetupRoutes`, `SetupLogger` |
| Types | PascalCase | `Game`, `Player`, `Instance` |
| Status enums | `Status` prefix | `StatusWaitingForPlayer`, `StatusInProgress` |
| Session keys | `Key` prefix | `KeyPlayerID`, `KeyUserID` |
### Error Handling ### Error Handling
1. **Wrap errors with context:**
```go ```go
// Wrap errors with context
return fmt.Errorf("loading game %s: %w", id, err) return fmt.Errorf("loading game %s: %w", id, err)
```
// Combine cleanup errors with errors.Join 2. **Return (result, error) tuples:**
return nil, errors.Join(fmt.Errorf("pinging database: %w", err), DB.Close()) ```go
func loadGame(queries *repository.Queries, id string) (*Game, error)
```
// Best-effort operations 3. **Best-effort operations** - use nolint comment:
```go
nc.Publish(subject, nil) //nolint:errcheck // best-effort notification nc.Publish(subject, nil) //nolint:errcheck // best-effort notification
```
// HTTP errors 4. **HTTP errors:**
```go
http.Error(w, "game not found", http.StatusNotFound) http.Error(w, "game not found", http.StatusNotFound)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
``` ```
### Comments ### Comments
- Focus on **why**, not **how**. Avoid superfluous comments. - Focus on **why**, not **how**. Avoid superfluous comments.
- Package comments at top of primary file. - Package comments at top of primary file:
- Function comments for exported functions. ```go
// Package connect4 implements Connect 4 game logic, state management, and persistence.
package connect4
```
- Function comments for exported functions:
```go
// DropPiece attempts to drop a piece in the given column.
// Returns (row placed, success).
func (g *Game) DropPiece(col, playerColor int) (int, bool)
```
## Go Patterns ## Go Patterns
@@ -100,119 +125,129 @@ Handlers receive dependencies and return `http.HandlerFunc`:
```go ```go
func HandleGamePage(store *connect4.Store, sm *scs.SessionManager) http.HandlerFunc { func HandleGamePage(store *connect4.Store, sm *scs.SessionManager) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { /* ... */ } return func(w http.ResponseWriter, r *http.Request) {
// use store, sm here
}
} }
``` ```
### Cleanup Function Returns ### Mutex for Concurrent Access
Infrastructure init functions return a cleanup func the caller defers:
```go ```go
cleanupDB, err := db.Init(cfg.DBPath) type Store struct {
defer cleanupDB() games map[string]*Instance
gamesMu sync.RWMutex
}
func (s *Store) Get(id string) (*Instance, bool) {
s.gamesMu.RLock()
defer s.gamesMu.RUnlock()
inst, ok := s.games[id]
return inst, ok
}
``` ```
### Store/Instance Pattern ### Build Tags for Environment
Game state uses a two-tier pattern: a thread-safe **Store** (map + RWMutex) holding **Instance** wrappers (individual game + own mutex + DB queries). Stores lazy-load from DB on cache miss. ```go
//go:build dev
### Build Tags //go:build !dev
```
`//go:build dev` and `//go:build !dev` switch behavior for static asset serving (filesystem vs embedded hashfs) and config loading. ### Embedded Filesystems
```go
//go:embed assets
var assets embed.FS
//go:embed migrations/*.sql
var MigrationFS embed.FS
```
### Graceful Shutdown
```go
eg, egctx := errgroup.WithContext(ctx)
eg.Go(func() error { return server.ListenAndServe() })
eg.Go(func() error {
<-egctx.Done()
return server.Shutdown(context.Background())
})
return eg.Wait()
```
## Templ + Datastar Patterns ## Templ + Datastar Patterns
### Architecture: Everything Is a Stream ### SSE Connection with Disabled Cancellation
The core mental model: **the server owns all state and continuously projects it to the browser over SSE**. There is no client-side state management. The browser connects to an event stream, and the server pushes full HTML fragments whenever something changes. Datastar morphs these into the DOM — the client is a thin rendering surface. Datastar cancels SSE on user interaction by default. Disable for persistent connections:
User actions (clicks, keypresses) trigger short POST/DELETE requests back to the server. The server mutates state, publishes a NATS signal, and every connected SSE stream picks up the change and re-renders. The client never needs to know what changed — it just receives the new truth and morphs to match.
This means: **always send whole components down the wire.** Don't try to diff or send minimal patches. Render the full templ component, call `sse.PatchElementTempl()`, and let Datastar's morph handle the rest. The only exception is appending to a list (e.g. chat messages).
**Signals follow command-query segregation.** Signals are *commands* — they carry the user's intent to the server (form input values, button clicks). The SSE stream is the *query* — it continuously projects the server's truth into the DOM. Keep signals thin: form input buffers (`chatMsg`, `nickname`), pure UI state the server never needs (`activeTab`), and request indicators. Don't use signals to hold application state — that arrives from the server via SSE.
### SSE Event Loop
Both game event handlers follow the same structure:
1. Subscribe to NATS channels **before** creating SSE (avoids missed messages)
2. Send initial full-state patch
3. `select` loop over: context done, game updates (drain channel first), chat messages (append), 1-second heartbeat (full re-render)
```go ```go
// Handler side — long-lived SSE with Brotli compression
sse := datastar.NewSSE(w, r, datastar.WithCompression(
datastar.WithBrotli(datastar.WithBrotliLevel(5)),
))
sse.PatchElementTempl(components.GameBoard(game))
// Template side — disable Datastar's default SSE cancellation on interaction
data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) } data-init={ fmt.Sprintf("@get('/games/%s/events',{requestCancellation:'disabled'})", g.ID) }
``` ```
### Client-Server Interactions ### Prevent Script Duplication on SSE Patches
Use `templ.NewOnceHandle()` for scripts in components that get patched:
```go ```go
// Trigger SSE actions from templates var scriptHandle = templ.NewOnceHandle()
data-on:click={ datastar.PostSSE("/games/%s/drop?col=%d", g.ID, colIdx) }
data-on:click={ datastar.DeleteSSE("/games/%s", g.ID) }
// Read client signals in handlers templ MyComponent() {
var signals struct { ChatMsg string `json:"chatMsg"` } <div id="my-component">...</div>
datastar.ReadSignals(r, &signals) @scriptHandle.Once() {
@myScript()
// Clear input after submission }
sse.MarshalAndPatchSignals(map[string]any{"chatMsg": ""}) }
// Redirect via SSE
sse.Redirectf("/games/%s", newGame.ID())
``` ```
### Appending Elements (Chat Messages) ### Conditional Classes with templ.KV
The one exception to whole-component morphing is chat, where messages are appended individually:
```go ```go
sse.PatchElementTempl( class={
chatcomponents.ChatMessage(msg, cfg), "status status-sm",
datastar.WithSelectorID("c4-chat-history"), templ.KV("status-success", isConnected),
datastar.WithModeAppend(), templ.KV("status-error", !isConnected),
) }
``` ```
### Datastar Template Attributes ### Datastar SSE Responses
- `data-signals` — declare reactive state ```go
- `data-bind` — two-way input binding sse := datastar.NewSSE(w, r)
- `data-show` — conditional visibility sse.MergeFragmentTempl(components.GameBoard(game))
- `data-class` — reactive CSS classes
- `data-morph-ignore` — prevent SSE from overwriting an element (e.g. chat input)
## Testing
```bash
task test # All tests
go test -run TestHandleLogin_Success ./features/auth # Single test
go test -v ./features/auth # Verbose package
``` ```
- Use `testutil.NewTestDB(t)` for tests needing a database
- Use `testutil.NewTestSessionManager(db)` for session-aware tests
- Use `config.LoadForTest()` to set safe defaults without .env
- Tests use external test packages (`package auth_test`)
## Tech Stack ## Tech Stack
| Layer | Technology | | Layer | Technology |
|-------|------------| |-------|------------|
| Templates | templ (type-safe HTML) | | Templates | templ (type-safe HTML) |
| Reactivity | Datastar Pro (SSE-driven) | | Reactivity | Datastar (SSE-driven) |
| CSS | TailwindCSS v4 + daisyUI | | CSS | TailwindCSS v4 + daisyUI |
| Router | chi/v5 | | Router | chi/v5 |
| Sessions | scs/v2 (SQLite-backed) | | Sessions | scs/v2 |
| Database | SQLite (modernc.org/sqlite) | | Database | SQLite (modernc.org/sqlite) |
| Migrations | goose (embedded SQL) | | Migrations | goose |
| SQL codegen | sqlc | | SQL codegen | sqlc |
| Pub/sub | Embedded NATS (nil-payload signals) | | Pub/sub | Embedded NATS |
| Logging | zerolog + slog (bridged via slog-zerolog) | | Logging | zerolog |
## Testing
```bash
# All tests
task test
# Single test
go test -run TestDropPiece ./connect4
# With verbose output
go test -v -run TestDropPiece ./connect4
# Test a package
go test ./connect4/...
```
Use `testutil.SetupTestDB()` for tests requiring database access.