Phase 0: backend + frontend scaffold, single-binary build
Gadfly review (reusable) / review (pull_request) Successful in 10m8s
Adversarial Review (Gadfly) / review (pull_request) Successful in 10m9s

Implements the Pansy v1 scaffold (epic #20, phase 0).

#1 Backend: Go module (pure-Go, builds with CGO_ENABLED=0), env config,
   gin server with slog + recovery + /api/v1/healthz, modernc SQLite store
   with WAL/busy_timeout/foreign_keys pragmas, embedded numbered-migration
   runner, full initial schema (users, sessions, gardens, garden_shares,
   garden_objects, plants, plantings), domain structs + sentinel errors,
   graceful shutdown.

#2 Frontend: Vite + React 19 + TS (strict) + Tailwind 4 + TanStack
   Router/Query, typed /api/v1 fetch wrapper (ApiError carries status +
   body so later issues can read 409 conflict rows), dev proxy /api -> :8080,
   responsive app shell with stub pages for all five routes.

#3 Single binary: //go:embed of the web build with a committed placeholder,
   SPA fallback (deep links, immutable asset caching, JSON 404 for unmatched
   /api and missing assets), Makefile (web/build/dev/test), README quickstart
   + env var table.

Verified: go build/vet/test clean (CGO off); binary migrates idempotently and
serves healthz; web tsc + build clean; integrated binary serves the SPA, deep
links, and correct cache headers; app mounts and navigates all five routes at
desktop and 375px widths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01JdQpdYYsTgtkJBxbcpAszi
This commit is contained in:
2026-07-18 14:52:05 -04:00
co-authored by Claude Opus 4.8
parent 76d18da542
commit 91da9ff945
36 changed files with 4578 additions and 0 deletions
+135
View File
@@ -0,0 +1,135 @@
package store
import (
"context"
"embed"
"fmt"
"io/fs"
"log/slog"
"sort"
"strconv"
"strings"
)
//go:embed migrations/*.sql
var migrationsFS embed.FS
// migration is one numbered SQL file: version parsed from the filename prefix.
type migration struct {
version int
name string
sql string
}
// Migrate applies every embedded migration whose version has not yet been
// recorded, in ascending order, each in its own transaction. It is idempotent:
// a second run with no new files is a no-op. Migration files are named
// NNNN_description.sql (e.g. 0001_init.sql); NNNN is the version.
func (d *DB) Migrate(ctx context.Context) error {
if _, err := d.sql.ExecContext(ctx,
`CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY)`,
); err != nil {
return fmt.Errorf("store: create schema_migrations: %w", err)
}
applied, err := d.appliedVersions(ctx)
if err != nil {
return err
}
migrations, err := loadMigrations()
if err != nil {
return err
}
for _, m := range migrations {
if applied[m.version] {
continue
}
if err := d.applyMigration(ctx, m); err != nil {
return err
}
slog.Info("store: applied migration", "version", m.version, "name", m.name)
}
return nil
}
func (d *DB) appliedVersions(ctx context.Context) (map[int]bool, error) {
rows, err := d.sql.QueryContext(ctx, `SELECT version FROM schema_migrations`)
if err != nil {
return nil, fmt.Errorf("store: read schema_migrations: %w", err)
}
defer rows.Close()
applied := map[int]bool{}
for rows.Next() {
var v int
if err := rows.Scan(&v); err != nil {
return nil, fmt.Errorf("store: scan schema_migrations: %w", err)
}
applied[v] = true
}
return applied, rows.Err()
}
func (d *DB) applyMigration(ctx context.Context, m migration) error {
tx, err := d.sql.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("store: begin migration %d: %w", m.version, err)
}
defer tx.Rollback() //nolint:errcheck // no-op after a successful commit
if _, err := tx.ExecContext(ctx, m.sql); err != nil {
return fmt.Errorf("store: apply migration %d (%s): %w", m.version, m.name, err)
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO schema_migrations (version) VALUES (?)`, m.version,
); err != nil {
return fmt.Errorf("store: record migration %d: %w", m.version, err)
}
return tx.Commit()
}
// loadMigrations reads and parses every embedded migration file, sorted by
// version ascending.
func loadMigrations() ([]migration, error) {
entries, err := fs.ReadDir(migrationsFS, "migrations")
if err != nil {
return nil, fmt.Errorf("store: read migrations dir: %w", err)
}
var migrations []migration
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".sql") {
continue
}
version, err := parseVersion(e.Name())
if err != nil {
return nil, err
}
body, err := fs.ReadFile(migrationsFS, "migrations/"+e.Name())
if err != nil {
return nil, fmt.Errorf("store: read migration %s: %w", e.Name(), err)
}
migrations = append(migrations, migration{version: version, name: e.Name(), sql: string(body)})
}
sort.Slice(migrations, func(i, j int) bool {
return migrations[i].version < migrations[j].version
})
return migrations, nil
}
// parseVersion extracts the leading integer from a migration filename such as
// "0001_init.sql".
func parseVersion(name string) (int, error) {
prefix, _, ok := strings.Cut(name, "_")
if !ok {
return 0, fmt.Errorf("store: migration %q missing NNNN_ prefix", name)
}
v, err := strconv.Atoi(prefix)
if err != nil {
return 0, fmt.Errorf("store: migration %q has non-numeric version: %w", name, err)
}
return v, nil
}
+139
View File
@@ -0,0 +1,139 @@
-- 0001_init.sql — pansy initial schema.
--
-- Conventions (see DESIGN.md § Domain model):
-- * All measurements are centimeters (REAL); imperial is a display concern.
-- * `version INTEGER NOT NULL DEFAULT 1` on every user-mutable row; PATCH/DELETE
-- carry it and the service layer increments on write for 409 conflict detection.
-- * Enumerations are enforced with CHECK constraints.
-- * Timestamps are ISO-8601 TEXT (UTC); dates are 'YYYY-MM-DD' TEXT.
-- * Foreign keys cascade on owner/parent deletion; enforcement is on (PRAGMA foreign_keys).
-- users -----------------------------------------------------------------------
-- A user may authenticate locally (password_hash), via OIDC (oidc_issuer+subject),
-- or both (linked by email on first OIDC login). First registered user is admin.
CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
display_name TEXT NOT NULL,
password_hash TEXT, -- argon2id; NULL for OIDC-only users
oidc_issuer TEXT, -- NULL for local-only users
oidc_subject TEXT,
is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)),
version INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
-- NULLs compare distinct in SQLite, so this only constrains real (issuer, subject) pairs.
CREATE UNIQUE INDEX idx_users_oidc ON users (oidc_issuer, oidc_subject);
-- sessions --------------------------------------------------------------------
-- Opaque bearer token stored only as a sha256 hash; the raw token lives in the
-- HttpOnly cookie. 30-day sliding expiry (expires_at bumped on use).
CREATE TABLE sessions (
token_hash TEXT PRIMARY KEY, -- sha256 of the 32-byte random token
user_id INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
expires_at TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
CREATE INDEX idx_sessions_user ON sessions (user_id);
-- gardens ---------------------------------------------------------------------
CREATE TABLE gardens (
id INTEGER PRIMARY KEY,
owner_id INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
name TEXT NOT NULL,
width_cm REAL NOT NULL,
height_cm REAL NOT NULL,
unit_pref TEXT NOT NULL DEFAULT 'metric' CHECK (unit_pref IN ('metric', 'imperial')),
notes TEXT NOT NULL DEFAULT '',
version INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
CREATE INDEX idx_gardens_owner ON gardens (owner_id);
-- garden_shares ---------------------------------------------------------------
-- The owner is implicit via gardens.owner_id and never has a share row.
CREATE TABLE garden_shares (
id INTEGER PRIMARY KEY,
garden_id INTEGER NOT NULL REFERENCES gardens (id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
role TEXT NOT NULL CHECK (role IN ('viewer', 'editor')),
created_by INTEGER NOT NULL REFERENCES users (id) ON DELETE CASCADE,
version INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
UNIQUE (garden_id, user_id)
);
CREATE INDEX idx_garden_shares_garden ON garden_shares (garden_id);
CREATE INDEX idx_garden_shares_user ON garden_shares (user_id);
-- garden_objects --------------------------------------------------------------
-- One polymorphic table for every placeable object. Positioned by CENTER point +
-- rotation about center, in garden space (origin top-left, x→right, y→down).
-- shape='polygon' and the points JSON column are reserved for post-v1; the v1
-- editor emits only 'rect' and 'circle' (circle: width_cm = diameter).
CREATE TABLE garden_objects (
id INTEGER PRIMARY KEY,
garden_id INTEGER NOT NULL REFERENCES gardens (id) ON DELETE CASCADE,
kind TEXT NOT NULL CHECK (kind IN ('bed', 'grow_bag', 'container', 'in_ground', 'tree', 'path', 'structure')),
name TEXT NOT NULL DEFAULT '',
shape TEXT NOT NULL DEFAULT 'rect' CHECK (shape IN ('rect', 'circle', 'polygon')),
points TEXT, -- reserved: JSON [[x,y],...] for shape='polygon'
x_cm REAL NOT NULL, -- center in garden space
y_cm REAL NOT NULL,
width_cm REAL NOT NULL,
height_cm REAL NOT NULL,
rotation_deg REAL NOT NULL DEFAULT 0, -- clockwise about center
z_index INTEGER NOT NULL DEFAULT 0,
plantable INTEGER NOT NULL DEFAULT 0 CHECK (plantable IN (0, 1)),
color TEXT, -- optional hex override
props TEXT, -- kind-specific extras (JSON)
notes TEXT NOT NULL DEFAULT '',
version INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
CREATE INDEX idx_garden_objects_garden ON garden_objects (garden_id);
-- plants ----------------------------------------------------------------------
-- Catalog. owner_id NULL = built-in (seeded, read-only; clone to customize).
-- Users see built-ins plus their own.
CREATE TABLE plants (
id INTEGER PRIMARY KEY,
owner_id INTEGER REFERENCES users (id) ON DELETE CASCADE, -- NULL = built-in
name TEXT NOT NULL,
category TEXT NOT NULL CHECK (category IN ('vegetable', 'herb', 'flower', 'fruit', 'tree_shrub', 'cover')),
spacing_cm REAL NOT NULL, -- mature spacing
color TEXT NOT NULL, -- hex
icon TEXT NOT NULL DEFAULT '', -- emoji (zero image assets in v1)
days_to_maturity INTEGER,
notes TEXT NOT NULL DEFAULT '',
version INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
CREATE INDEX idx_plants_owner ON plants (owner_id);
-- plantings ("plops") ---------------------------------------------------------
-- A circular patch of one plant, positioned in the PARENT OBJECT's local frame
-- (origin at object center, unrotated axes) so moving/rotating the bed moves its
-- plants for free. count NULL = derived max(1, round(pi*r^2 / spacing_cm^2)).
-- "Clear bed" sets removed_at; v1 lists rows where removed_at IS NULL.
CREATE TABLE plantings (
id INTEGER PRIMARY KEY,
object_id INTEGER NOT NULL REFERENCES garden_objects (id) ON DELETE CASCADE,
plant_id INTEGER NOT NULL REFERENCES plants (id) ON DELETE RESTRICT,
x_cm REAL NOT NULL, -- center in object-local frame
y_cm REAL NOT NULL,
radius_cm REAL NOT NULL,
count INTEGER, -- NULL = derived from area / spacing^2
label TEXT,
planted_at TEXT, -- 'YYYY-MM-DD'
removed_at TEXT, -- 'YYYY-MM-DD'; NULL = currently planted
version INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now')),
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))
);
CREATE INDEX idx_plantings_object ON plantings (object_id);
CREATE INDEX idx_plantings_plant ON plantings (plant_id);
+68
View File
@@ -0,0 +1,68 @@
// Package store provides pansy's durable persistence layer: a pure-Go SQLite
// database (modernc.org/sqlite — no cgo, so the binary stays static) with a
// tiny embedded migration runner. Entity query methods are added per feature
// issue; this file only handles opening and the connection pragmas.
package store
import (
"database/sql"
"fmt"
"net/url"
"strings"
_ "modernc.org/sqlite" // pure-Go driver, registered as "sqlite"
)
// DB is a handle to the SQLite database backing pansy. Safe for concurrent use:
// WAL mode allows many readers with one writer, and busy_timeout makes a
// contended writer wait rather than fail with SQLITE_BUSY.
type DB struct {
sql *sql.DB
}
// Open opens (creating if absent) the SQLite database at path and returns a DB.
// The pragmas — busy_timeout, WAL journal, and foreign-key enforcement — are
// applied per connection via the DSN so every pooled connection inherits them.
// A path of ":memory:" yields an ephemeral in-memory database (useful in tests);
// the pool is pinned to a single connection so all queries see the same DB.
// The caller owns the returned DB and must Close it.
func Open(path string) (*DB, error) {
dsn, memory := buildDSN(path)
sqldb, err := sql.Open("sqlite", dsn)
if err != nil {
return nil, fmt.Errorf("store: open %q: %w", path, err)
}
if memory {
// Each new connection to a bare ":memory:" DSN gets its OWN empty database,
// so a pooled second connection wouldn't see the migrated schema. Pin the
// pool to one connection to keep an in-memory DB coherent.
sqldb.SetMaxOpenConns(1)
}
if err := sqldb.Ping(); err != nil {
sqldb.Close()
return nil, fmt.Errorf("store: ping %q: %w", path, err)
}
return &DB{sql: sqldb}, nil
}
// buildDSN turns a filesystem path (or ":memory:") into a modernc DSN carrying
// the pragmas we want on every connection, and reports whether it is in-memory.
// A path that already looks like a DSN (has a scheme or query) is passed through
// untouched.
func buildDSN(path string) (dsn string, memory bool) {
memory = path == ":memory:" || strings.Contains(path, ":memory:") || strings.Contains(path, "mode=memory")
if strings.HasPrefix(path, "file:") || strings.Contains(path, "?") {
return path, memory
}
pragmas := url.Values{}
pragmas.Add("_pragma", "busy_timeout(5000)")
pragmas.Add("_pragma", "journal_mode(WAL)")
pragmas.Add("_pragma", "foreign_keys(1)")
return "file:" + path + "?" + pragmas.Encode(), memory
}
// Close closes the underlying database.
func (d *DB) Close() error { return d.sql.Close() }
// SQL exposes the underlying *sql.DB for the per-entity query files.
func (d *DB) SQL() *sql.DB { return d.sql }
+122
View File
@@ -0,0 +1,122 @@
package store
import (
"context"
"path/filepath"
"testing"
)
// openTestDB opens a fresh file-backed DB in a temp dir and migrates it.
func openTestDB(t *testing.T) *DB {
t.Helper()
db, err := Open(filepath.Join(t.TempDir(), "test.db"))
if err != nil {
t.Fatalf("Open: %v", err)
}
t.Cleanup(func() { db.Close() })
if err := db.Migrate(context.Background()); err != nil {
t.Fatalf("Migrate: %v", err)
}
return db
}
func TestMigrateCreatesSchema(t *testing.T) {
db := openTestDB(t)
want := []string{
"users", "sessions", "gardens", "garden_shares",
"garden_objects", "plants", "plantings", "schema_migrations",
}
for _, table := range want {
var name string
err := db.SQL().QueryRow(
`SELECT name FROM sqlite_master WHERE type='table' AND name=?`, table,
).Scan(&name)
if err != nil {
t.Errorf("expected table %q to exist: %v", table, err)
}
}
var version int
if err := db.SQL().QueryRow(`SELECT max(version) FROM schema_migrations`).Scan(&version); err != nil {
t.Fatalf("read schema_migrations: %v", err)
}
if version != 1 {
t.Errorf("schema version = %d, want 1", version)
}
}
func TestMigrateIsIdempotent(t *testing.T) {
db := openTestDB(t)
// A second Migrate must be a no-op and leave exactly one recorded version.
if err := db.Migrate(context.Background()); err != nil {
t.Fatalf("second Migrate: %v", err)
}
var count int
if err := db.SQL().QueryRow(`SELECT count(*) FROM schema_migrations`).Scan(&count); err != nil {
t.Fatalf("count schema_migrations: %v", err)
}
if count != 1 {
t.Errorf("schema_migrations rows = %d, want 1", count)
}
}
func TestForeignKeysEnforced(t *testing.T) {
db := openTestDB(t)
// The DSN sets foreign_keys(1) per connection; a planting referencing a
// nonexistent object must be rejected. This guards the pragma actually
// reaching the app's pooled connections, not just the sqlite3 CLI.
_, err := db.SQL().Exec(
`INSERT INTO plantings (object_id, plant_id, x_cm, y_cm, radius_cm) VALUES (999, 999, 0, 0, 10)`,
)
if err == nil {
t.Fatal("expected foreign-key violation, got nil")
}
}
func TestCheckConstraintRejectsBadEnum(t *testing.T) {
db := openTestDB(t)
// Seed a user + garden so the FK is satisfied and only the CHECK can fail.
res, err := db.SQL().Exec(
`INSERT INTO users (email, display_name) VALUES ('[email protected]', 'A')`)
if err != nil {
t.Fatalf("insert user: %v", err)
}
uid, _ := res.LastInsertId()
res, err = db.SQL().Exec(
`INSERT INTO gardens (owner_id, name, width_cm, height_cm) VALUES (?, 'G', 100, 100)`, uid)
if err != nil {
t.Fatalf("insert garden: %v", err)
}
gid, _ := res.LastInsertId()
// kind='invalid' violates the CHECK constraint.
_, err = db.SQL().Exec(
`INSERT INTO garden_objects (garden_id, kind, x_cm, y_cm, width_cm, height_cm)
VALUES (?, 'invalid', 0, 0, 10, 10)`, gid)
if err == nil {
t.Fatal("expected CHECK constraint violation for bad kind, got nil")
}
}
func TestInMemoryDBIsCoherentAcrossQueries(t *testing.T) {
// A bare ":memory:" DSN gives each connection its own DB; Open must pin the
// pool so the migrated schema is visible to subsequent queries.
db, err := Open(":memory:")
if err != nil {
t.Fatalf("Open(:memory:): %v", err)
}
defer db.Close()
if err := db.Migrate(context.Background()); err != nil {
t.Fatalf("Migrate: %v", err)
}
var name string
if err := db.SQL().QueryRow(
`SELECT name FROM sqlite_master WHERE type='table' AND name='gardens'`,
).Scan(&name); err != nil {
t.Fatalf("in-memory schema not visible: %v", err)
}
}