diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8dbb30c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,65 @@ +name: ci + +# Minimal CI for pgrun-cli: tests, cross-platform build, lint, vulnerability scan. +# Action SHAs and tool versions are pinned (as in pgrundev/pgbot) so a release upstream cannot +# change what CI enforces without a commit here. Go comes from go.mod (go + toolchain lines). +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + test: + name: vet + gofmt + unit tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + - run: go vet ./... + - name: gofmt + run: | + unformatted=$(gofmt -l cmd internal) + if [ -n "$unformatted" ]; then echo "gofmt needed:"; echo "$unformatted"; exit 1; fi + - run: go test -race ./... + + build: + name: build ${{ matrix.goos }}/${{ matrix.goarch }} + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + goos: [linux, darwin, windows] + goarch: [amd64, arm64] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + - name: build (same flags as the Makefile) + env: + GOOS: ${{ matrix.goos }} + GOARCH: ${{ matrix.goarch }} + CGO_ENABLED: "0" + run: go build -trimpath -ldflags "-s -w" -o "bin/pgrun-$GOOS-$GOARCH" ./cmd/pgrun + + lint: + name: golangci-lint + govulncheck + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: go.mod + - name: "golangci-lint (config: .golangci.yml)" + run: | + go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.14.0 + "$(go env GOPATH)/bin/golangci-lint" run ./... + - name: govulncheck + run: | + go install golang.org/x/vuln/cmd/govulncheck@v1.9.0 + "$(go env GOPATH)/bin/govulncheck" ./... diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..8d88de5 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,28 @@ +# Minimal lint baseline for pgrun-cli (golangci-lint v2, default linters: errcheck, govet, +# ineffassign, staticcheck, unused). The exclusions are the accepted patterns of a CLI, not bugs: +# - writes to the user's terminal (fmt/tabwriter/io to stdout/stderr) and best-effort cleanup +# (Close, Remove, RemoveAll, waiting on a launched browser) are intentionally unchecked; +# - tests: unchecked fixture writes, and staticcheck's quick-fix style hints. +version: "2" +linters: + settings: + errcheck: + exclude-functions: + - fmt.Fprint + - fmt.Fprintf + - fmt.Fprintln + - io.WriteString + - (io.Writer).Write + - (io.Closer).Close + - (*os.File).Close + - (*text/tabwriter.Writer).Flush + - (net/http.ResponseWriter).Write + - (*os/exec.Cmd).Wait + - os.Remove + - os.RemoveAll + exclusions: + rules: + - path: _test\.go + linters: [errcheck] + - linters: [staticcheck] + text: "QF1002" diff --git a/README.md b/README.md index aa1c290..bbac3fd 100644 --- a/README.md +++ b/README.md @@ -17,10 +17,36 @@ The agent-first path — three commands, then hand the work to Claude Code: ```sh pgrun auth login # opens your browser to authorize; --paste to paste a token instead -pgrun skill install # installs the pgrun-branching skill into ~/.claude/skills +pgrun setup # installs the pgrun-branching skill and PgBot (idempotent; --json for agents) claude # then: "Add an index to users.email and test it on a pgrun branch" ``` +`pgrun setup` is the one install path, whether you run it or the skill asks an agent to: +it installs or refreshes the skill (`--agent claude,codex`, `--project`, `--dir`), makes +[PgBot](https://github.com/pgrundev/pgbot) available (keeps a compatible `pgbot` already on +your PATH, else downloads the pinned release and verifies its checksum), and reports whether +auth is configured. It never edits `AGENTS.md`/`CLAUDE.md` unless you pass +`--agents-md `, and then only between its own markers. + +### PgBot: verify database changes + +```sh +pgrun bot verify -- bin/rails db:migrate # migration on a disposable PostgreSQL branch, reviewed, cleaned up +pgrun bot verify --compare-pgx --json -- npx prisma migrate deploy # same migration on PGX too, schemas compared +pgrun bot lint --json # schema findings (read-only) +pgrun bot schema # schema snapshot (catalog only) +pgrun bot explain "select * from orders where user_id = $1" +``` + +`pgrun bot` only inspects PGRun branches (never a connection string you pass it), runs pgbot +read-only, and never sends anything to an AI provider. + +`verify` reports one `verdict` — `fail`, `dangerous`, `unsupported` (PGX only), `incomplete` +(the review could not run; never a pass), `error` (infrastructure), `warning` or `pass` — and +`blocking` per an explicit policy (`--block-on`, default `fail,dangerous,incomplete,error`). +Exit 0 = not blocking, 1 = blocking, 3 = only infrastructure errors block. It reviews one +migration against the Safe Copy; it does not detect conflicts between parallel migrations. + The skill teaches Claude when to create a branch, how to inject its `DATABASE_URL` into only the commands that need it, and when to delete it. Claude does the branching; you never create a branch by hand. diff --git a/go.mod b/go.mod index a7e18ec..1892a76 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/pgrundev/pgrun-cli go 1.22 + +toolchain go1.27.4 diff --git a/internal/api/wait.go b/internal/api/wait.go index b871b3c..79a544d 100644 --- a/internal/api/wait.go +++ b/internal/api/wait.go @@ -50,10 +50,24 @@ func WaitFailureReason(name, status string) string { // when returning an error — so callers can still honor --json / isError with // whatever the API last said. func (c *Client) WaitForTerminal(ctx context.Context, project string, raw []byte, branch Branch) ([]byte, Branch, error) { + fetched := false for { if Terminal(branch.Status) { + // A create response can already say "ready" (an idempotent replay of a request_id, + // or a server that provisions synchronously) but never carries the connection URL: + // only a GET of the single branch does. Fetch it once instead of handing back a + // ready branch with no URL. + if branch.Status == StatusReady && branch.ConnectionURL == "" && !fetched { + fetched = true + var err error + if raw, branch, err = c.GetBranch(ctx, project, branch.Name); err != nil { + return raw, branch, err + } + continue + } return raw, branch, nil } + fetched = true select { case <-ctx.Done(): return raw, branch, ctx.Err() diff --git a/internal/api/wait_test.go b/internal/api/wait_test.go index b29f092..68045f7 100644 --- a/internal/api/wait_test.go +++ b/internal/api/wait_test.go @@ -79,3 +79,30 @@ func TestWaitForTerminal_DeletedStopsImmediately(t *testing.T) { t.Fatalf("took %s — looks like it ran out the 2s timeout instead of stopping on \"deleted\"", elapsed) } } + +// A create response that already says "ready" carries no connection URL (only a GET of the single +// branch does): WaitForTerminal fetches it once rather than returning a ready branch without one. +func TestWaitForTerminal_ReadyOnCreateFetchesURLOnce(t *testing.T) { + var gets int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&gets, 1) + w.Write([]byte(`{"id":"b1","name":"x","status":"ready","connection_url":"postgres://u:p@h/x"}`)) + })) + defer srv.Close() + c := New(srv.URL, "t") + _, b, err := c.WaitForTerminal(context.Background(), "p", nil, Branch{Name: "x", Status: StatusReady}) + if err != nil || b.ConnectionURL != "postgres://u:p@h/x" || atomic.LoadInt32(&gets) != 1 { + t.Fatalf("branch %+v err %v gets %d, want the URL from exactly one GET", b, err, gets) + } + // Ready and not yet credentialed on the GET as well: returned as is, no loop. + srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + atomic.AddInt32(&gets, 1) + w.Write([]byte(`{"id":"b1","name":"x","status":"ready"}`)) + })) + defer srv2.Close() + atomic.StoreInt32(&gets, 0) + _, b, err = New(srv2.URL, "t").WaitForTerminal(context.Background(), "p", nil, Branch{Name: "x", Status: StatusReady}) + if err != nil || b.ConnectionURL != "" || atomic.LoadInt32(&gets) != 1 { + t.Fatalf("branch %+v err %v gets %d", b, err, gets) + } +} diff --git a/internal/cli/bot.go b/internal/cli/bot.go new file mode 100644 index 0000000..129ff5d --- /dev/null +++ b/internal/cli/bot.go @@ -0,0 +1,350 @@ +package cli + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os/exec" + "strings" + "time" + + "github.com/pgrundev/pgrun-cli/internal/api" + "github.com/pgrundev/pgrun-cli/internal/pgbot" +) + +// `pgrun bot …` makes pgbot (read-only Postgres inspection) a standard part +// of pgrun. Every per-branch command resolves a PGRun branch through the API +// with the project-scoped token and hands its URL to pgbot in the +// environment only. `pgrun bot` never accepts a connection URL of its own: +// it inspects PGRun branches, nothing else, so it cannot be pointed at a +// production database. pgbot's optional AI layer (ask/explain/--ai) sends +// findings to an external model and is refused unless --allow-ai is given. + +const botUsage = `pgrun bot — pgbot, read-only inspection and verification of PGRun branches + +Usage: + pgrun bot status [--json] is pgbot installed, which version, what it can do + pgrun bot install [--version ] [--force] [--json] + pgrun bot inspect [] [--json] health findings (pgbot inspect --no-store) + pgrun bot lint [] [--json] schema-only findings (safe on any branch) + pgrun bot schema [] schema snapshot as JSON (catalog only, no data) + pgrun bot explain [] ""`) + } + sql, pos = pos[len(pos)-1], pos[:len(pos)-1] + } + switch len(pos) { + case 2: + project, branch = pos[0], pos[1] + case 1: + branch = pos[0] + var code int + var ok bool + if project, code, ok = resolveProject("", rest, stderr); !ok { + return code + } + default: + return usageErrf(stderr, "bot %s: expected [] ", sub) + } + if sub == "run" && len(extra) == 0 { + return usageErrf(stderr, "bot run: missing pgbot arguments after --") + } + if sub != "run" && len(extra) > 0 { + return usageErrf(stderr, "bot %s: unexpected argument %s (use `pgrun bot run … -- ` for anything else)", sub, redactedArg(extra[0])) + } + for _, a := range append(append([]string{}, extra...), sql) { + if containsConnectionURL(a) || strings.HasPrefix(a, "service=") { + return usageErrf(stderr, "bot %s: pgrun bot only inspects PGRun branches — it never takes a connection string (run pgbot directly for other databases)", sub) + } + } + if sub == "run" && !*allowAI { + if why := refusesAI(extra); why != "" { + return usageErrf(stderr, "bot run: %s; add --allow-ai if that is what you want", why) + } + } + + var pgbotArgs []string + switch sub { + case "inspect": + pgbotArgs = []string{"inspect", "--no-store"} + for _, id := range disposableBranchIgnores { + pgbotArgs = append(pgbotArgs, "--ignore", id) + } + fmt.Fprintf(stderr, "pgrun: suppressed for disposable branches: %s\n", strings.Join(disposableBranchIgnores, ", ")) + if *jsonOut { + pgbotArgs = append(pgbotArgs, "--json") + } + case "lint": + pgbotArgs = []string{"lint", "--fail-on", "none"} + if *jsonOut { + pgbotArgs = append(pgbotArgs, "--format", "json") + } + case "schema": + pgbotArgs = []string{"schema", "snapshot"} + case "explain": + pgbotArgs = []string{"sql", "explain"} + if *jsonOut { + pgbotArgs = append(pgbotArgs, "--json") + } + pgbotArgs = append(pgbotArgs, sql) + case "run": + pgbotArgs = extra + } + + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + bin, ok := requireBot(ctx, stderr) + if !ok { + return exitFailure + } + if sub == "schema" && !bin.Capabilities.SchemaReview { + fmt.Fprintf(stderr, "pgrun: pgbot %s has no `schema` command — install a newer pgbot\n", bin.Version) + return exitFailure + } + cfg, code, ok := resolveOrHint(*urlFlag, *tokenFlag, stderr) + if !ok { + return code + } + client := api.New(cfg.URL, cfg.Token) + _, b, err := client.GetBranch(ctx, project, branch) + if err != nil { + return handleAPIError(err, false, nil, stdout, stderr) + } + if b.Status != api.StatusReady || b.ConnectionURL == "" { + fmt.Fprintf(stderr, "pgrun: branch %s is not ready (status: %s)\n", branch, b.Status) + return exitFailure + } + red := newRedactor(b.ConnectionURL) + cmd := pgbot.Command(ctx, bin, b.ConnectionURL, *allowAI, pgbotArgs...) + cmd.Stdout, cmd.Stderr = redactWriter(stdout, red), redactWriter(stderr, red) + if err := cmd.Run(); err != nil { + var ee *exec.ExitError + if errors.As(err, &ee) { + return ee.ExitCode() // pgbot's own exit contract (1 warn, 2 critical, 3 connection) + } + fmt.Fprintf(stderr, "pgrun: run pgbot: %v\n", err) + return exitFailure + } + return exitSuccess +} diff --git a/internal/cli/bot_integration_test.go b/internal/cli/bot_integration_test.go new file mode 100644 index 0000000..ba67bd0 --- /dev/null +++ b/internal/cli/bot_integration_test.go @@ -0,0 +1,131 @@ +package cli + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "os/exec" + "strings" + "sync" + "testing" +) + +// TestBotVerify_RealPostgresAndPgbot runs `pgrun bot verify` end to end with a +// real pgbot binary against real PostgreSQL databases. Only the PGRun API is +// stood in for: creating a "branch" clones a golden database +// (CREATE DATABASE … TEMPLATE golden), deleting one drops it — the same +// copy-of-the-golden semantics a PGRun branch has. Needs: +// +// PGRUN_TEST_PG_DSN superuser URL of a scratch server (…/postgres?sslmode=disable) +// PGRUN_TEST_PGBOT path to a pgbot with the `schema` command +// PGRUN_TEST_PSQL path to psql +func TestBotVerify_RealPostgresAndPgbot(t *testing.T) { + dsn, bot, psql := os.Getenv("PGRUN_TEST_PG_DSN"), os.Getenv("PGRUN_TEST_PGBOT"), os.Getenv("PGRUN_TEST_PSQL") + if dsn == "" || bot == "" || psql == "" { + t.Skip("PGRUN_TEST_PG_DSN / PGRUN_TEST_PGBOT / PGRUN_TEST_PSQL not set") + } + withFastPoll(t) + sql := func(db, stmt string) { + t.Helper() + u, _ := url.Parse(dsn) + u.Path = "/" + db + out, err := exec.Command(psql, u.String(), "-v", "ON_ERROR_STOP=1", "-qAtc", stmt).CombinedOutput() + if err != nil { + t.Fatalf("%s: %v %s", stmt, err, out) + } + } + golden := fmt.Sprintf("golden_it_%d", os.Getpid()) + sql("postgres", "DROP DATABASE IF EXISTS "+golden) + sql("postgres", "CREATE DATABASE "+golden) + t.Cleanup(func() { sql("postgres", "DROP DATABASE IF EXISTS "+golden) }) + sql(golden, `CREATE TABLE users (id bigserial PRIMARY KEY, email text, legacy text); + INSERT INTO users (email, legacy) SELECT 'u'||g||'@x', 'l' FROM generate_series(1, 20000) g; + CREATE TABLE orders (id bigserial PRIMARY KEY, user_id bigint, total int); + INSERT INTO orders (user_id, total) SELECT (g % 20000) + 1, g FROM generate_series(1, 20000) g`) + + var mu sync.Mutex + live := map[string]bool{} + dbName := func(branch string) string { return "br_" + strings.ReplaceAll(branch, "-", "_") } + withServer(t, func(w http.ResponseWriter, r *http.Request) { + name := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:] + switch r.Method { + case http.MethodPost: + var body map[string]any + b, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(b, &body) + name = body["name"].(string) + sql("postgres", "CREATE DATABASE "+dbName(name)+" TEMPLATE "+golden) + mu.Lock() + live[name] = true + mu.Unlock() + w.WriteHeader(http.StatusCreated) + fmt.Fprintf(w, `{"id":"b","name":%q,"status":"creating"}`, name) + case http.MethodGet: + u, _ := url.Parse(dsn) + u.Path = "/" + dbName(name) + fmt.Fprintf(w, `{"id":"b","name":%q,"status":"ready","engine":"postgres","database":%q,"connection_url":%q}`, name, dbName(name), u.String()) + case http.MethodDelete: + sql("postgres", "DROP DATABASE IF EXISTS "+dbName(name)+" WITH (FORCE)") + mu.Lock() + delete(live, name) + mu.Unlock() + w.WriteHeader(http.StatusAccepted) + w.Write([]byte(`{"status":"deleting"}`)) + } + }) + t.Setenv("PGRUN_PGBOT", bot) + + // A migration with one safe step, one lock hazard and one data loss. + migration := []string{psql, "-v", "ON_ERROR_STOP=1", "-qc", + `ALTER TABLE users ADD COLUMN plan text NOT NULL DEFAULT 'free'; + ALTER TABLE orders ALTER COLUMN total TYPE bigint; + CREATE INDEX orders_user_idx ON orders (user_id); + ALTER TABLE users DROP COLUMN legacy`} + // psql takes the URL from $DATABASE_URL only via an explicit argument; wrap it. + cmd := []string{"/bin/sh", "-c", `exec "$0" "$DATABASE_URL" "$@"`} + cmd = append(cmd, migration...) + args := append([]string{"bot", "verify", "proj", "--json", "--"}, cmd...) + code, stdout, stderr := run(t, args...) + + var rep verifyReport + if err := json.Unmarshal([]byte(stdout), &rep); err != nil { + t.Fatalf("not JSON (code %d): %v\nstdout %s\nstderr %s", code, err, stdout, stderr) + } + if rep.Verdict != "dangerous" || code != exitFailure { + t.Fatalf("verdict %q code %d, want dangerous/1\n%s\n%s", rep.Verdict, code, stdout, stderr) + } + var review struct { + Findings []struct{ ID, Severity, Object string } `json:"findings"` + } + if err := json.Unmarshal(rep.SchemaReview, &review); err != nil { + t.Fatal(err) + } + got := map[string]string{} + for _, f := range review.Findings { + got[f.ID+" "+f.Object] = f.Severity + } + for k, sev := range map[string]string{ + "table_rewritten public.orders": "warning", + "index_created_on_existing_table public.orders_user_idx": "warning", + "column_dropped public.users.legacy": "critical", + "column_added public.users.plan": "info", + } { + if got[k] != sev { + t.Errorf("finding %q = %q, want %q (all: %v)", k, got[k], sev, got) + } + } + if _, rewritten := got["table_rewritten public.users"]; rewritten { + t.Error("constant-default ADD COLUMN reported as a rewrite") + } + mu.Lock() + defer mu.Unlock() + if len(live) != 0 { + t.Fatalf("verification databases left behind: %v", live) + } + if len(rep.Cleanup) != 1 || !rep.Cleanup[0].Deleted { + t.Fatalf("cleanup %+v", rep.Cleanup) + } +} diff --git a/internal/cli/bot_test.go b/internal/cli/bot_test.go new file mode 100644 index 0000000..1d3d466 --- /dev/null +++ b/internal/cli/bot_test.go @@ -0,0 +1,601 @@ +package cli + +import ( + "encoding/json" + "io" + "net/http" + "os" + "path/filepath" + "runtime" + "strings" + "sync" + "testing" +) + +// fakePgbot writes a shell-script pgbot that speaks just enough of pgbot's CLI +// for `pgrun bot` (version probe, schema snapshot/diff/compare, lint) and logs +// every invocation — argv and whether DATABASE_URL / an AI key reached it. +func fakePgbot(t *testing.T, diffSeverity string) (logPath, markPath string) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("shell-script fake pgbot") + } + dir := t.TempDir() + logPath = filepath.Join(dir, "calls.log") + markPath = filepath.Join(dir, "migrated") + script := `#!/bin/sh +echo "ARGS $* | URL=${DATABASE_URL:-none} | AIKEY=${ANTHROPIC_API_KEY:-none}" >> "` + logPath + `" +case "$1 $2" in + "--version "*) echo "pgbot version ${FAKE_PGBOT_VERSION:-0.10.0}"; exit 0;; + "schema snapshot") + if [ -n "$FAKE_PGBOT_NO_SCHEMA" ]; then echo "unknown command schema" >&2; exit 64; fi + if [ "$3" = "--help" ]; then echo "Usage: pgbot schema snapshot [connection-string]"; exit 0; fi + if [ -e "` + markPath + `" ]; then state=after; else state=before; fi + echo '{"kind":"pgbot-schema-snapshot","version":"1.0.0","captured_at":"'$state'","database":"d","server_version":"18","relations":[],"columns":[],"indexes":[],"constraints":[],"extensions":[]}' + exit 0;; + "schema diff") + if [ "` + diffSeverity + `" = "warning" ]; then + echo '{"kind":"pgbot-schema-diff","dangerous":false,"summary":{"critical":0,"warning":1,"info":0},"findings":[{"id":"index_created_on_existing_table","severity":"warning","object":"public.orders","detail":"new index","advice":"CONCURRENTLY"}]}' + elif [ "` + diffSeverity + `" = "critical" ]; then + echo '{"kind":"pgbot-schema-diff","dangerous":true,"summary":{"critical":1,"warning":0,"info":0},"findings":[{"id":"table_dropped","severity":"critical","object":"public.legacy","detail":"dropped","advice":"keep it"}]}' + else + echo '{"kind":"pgbot-schema-diff","dangerous":false,"summary":{"critical":0,"warning":0,"info":1},"findings":[{"id":"table_created","severity":"info","object":"public.audit","detail":"created"}]}' + fi + exit 0;; + "schema compare") + if [ -n "$FAKE_COMPARE_DIFF" ]; then echo '{"kind":"pgbot-schema-compare","identical":false,"differences":[{"kind":"column_type","object":"public.t.x"}]}'; exit 0; fi + echo '{"kind":"pgbot-schema-compare","identical":true,"differences":[]}'; exit 0;; + "lint "*) + if [ -n "$FAKE_LINT_FAIL" ]; then echo "lint: connection refused" >&2; exit 3; fi + if [ -e "` + markPath + `" ]; then + echo '{"findings":[{"id":"fk_without_index","severity":"warning","object":"public.orders","title":"FK without index"}]}' + else + echo '{"findings":[]}' + fi + exit 0;; + "inspect "*) echo '{"findings":[]}'; exit 0;; +esac +echo "unexpected: $*" >&2; exit 64 +` + bin := filepath.Join(dir, "pgbot") + if err := os.WriteFile(bin, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PGRUN_PGBOT", bin) + return logPath, markPath +} + +type fakeBranches struct { + mu sync.Mutex + created []map[string]any + deleted []string +} + +// verifyServer: every created branch becomes ready at once with an engine +// matching the request, except when the request asks for pgx and pgxOK is false +// (422 engine_unavailable, like the real API on an incompatible project). +func verifyServer(t *testing.T, fb *fakeBranches, pgxOK bool) { + withServer(t, func(w http.ResponseWriter, r *http.Request) { + name := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:] + switch r.Method { + case http.MethodPost: + var body map[string]any + b, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(b, &body) + if body["engine"] == "pgx" && !pgxOK { + w.WriteHeader(http.StatusUnprocessableEntity) + w.Write([]byte(`{"error":"engine_unavailable","engine":"pgx","reason":"incompatible","alternative":"postgres"}`)) + return + } + fb.mu.Lock() + fb.created = append(fb.created, body) + fb.mu.Unlock() + w.WriteHeader(http.StatusCreated) + w.Write([]byte(`{"id":"b1","name":"` + body["name"].(string) + `","status":"creating"}`)) + case http.MethodGet: + engine := "postgres" + if strings.HasSuffix(name, "-pgx") { + engine = "pgx" + } + w.Write([]byte(`{"id":"b1","name":"` + name + `","status":"ready","engine":"` + engine + `","connection_url":"postgres://u:sekretpassw0rd@` + name + `.example/db?sslmode=require"}`)) + case http.MethodDelete: + fb.mu.Lock() + fb.deleted = append(fb.deleted, name) + fb.mu.Unlock() + w.WriteHeader(http.StatusAccepted) + w.Write([]byte(`{"status":"deleting"}`)) + } + }) +} + +func migrationCommand(mark string, exit string) []string { + return []string{"/bin/sh", "-c", `echo "migrating $DATABASE_URL"; touch "` + mark + `"; exit ` + exit} +} + +func TestBotVerify_PassCleansUpAndKeepsURLOutOfOutput(t *testing.T) { + withFastPoll(t) + fb := &fakeBranches{} + verifyServer(t, fb, true) + logPath, mark := fakePgbot(t, "info") + t.Setenv("ANTHROPIC_API_KEY", "sk-should-not-reach-pgbot") + + args := append([]string{"bot", "verify", "proj1", "--json", "--"}, migrationCommand(mark, "0")...) + code, stdout, stderr := run(t, args...) + if code != 0 { + t.Fatalf("code %d, stderr %s, stdout %s", code, stderr, stdout) + } + var rep verifyReport + if err := json.Unmarshal([]byte(stdout), &rep); err != nil { + t.Fatalf("report is not JSON: %v\n%s", err, stdout) + } + // A new lint finding is informational: verdict warning, not blocking, exit 0. + if rep.Kind != VerifyKind || rep.Verdict != "warning" || rep.Blocking || rep.Summary.NewLint != 1 || + strings.Join(rep.Categories, ",") != "warning" { + t.Fatalf("report %+v", rep) + } + if len(fb.created) != 1 || fb.created[0]["engine"] != "postgres" || fb.created[0]["ttl"] != "1h" { + t.Fatalf("created %+v, want one postgres branch with a 1h TTL", fb.created) + } + if len(fb.deleted) != 1 || fb.deleted[0] != fb.created[0]["name"] { + t.Fatalf("deleted %v, want the verification branch", fb.deleted) + } + if len(rep.NewLintFindings) != 1 || rep.NewLintFindings[0].ID != "fk_without_index" { + t.Fatalf("new lint findings %+v", rep.NewLintFindings) + } + if strings.Contains(stdout+stderr, "sekretpassw0rd") { + t.Fatalf("branch password leaked into output:\n%s\n%s", stdout, stderr) + } + calls, _ := os.ReadFile(logPath) + for _, line := range strings.Split(strings.TrimSpace(string(calls)), "\n") { + args := strings.SplitN(line, " | ", 2)[0] + if strings.Contains(args, "sekretpassw0rd") { + t.Fatalf("connection URL passed on pgbot's argv: %s", line) + } + if !strings.Contains(line, "AIKEY=none") { + t.Fatalf("an AI key reached pgbot: %s", line) + } + } + if !strings.Contains(string(calls), "ARGS schema diff") { + t.Fatalf("schema diff never ran:\n%s", calls) + } +} + +func TestBotVerify_CriticalReviewIsDangerousAndStillDeletes(t *testing.T) { + withFastPoll(t) + fb := &fakeBranches{} + verifyServer(t, fb, true) + _, mark := fakePgbot(t, "critical") + args := append([]string{"bot", "verify", "proj1", "--json", "--"}, migrationCommand(mark, "0")...) + code, stdout, _ := run(t, args...) + var rep verifyReport + _ = json.Unmarshal([]byte(stdout), &rep) + if code != exitFailure || rep.Verdict != "dangerous" { + t.Fatalf("code %d verdict %q, want 1/dangerous", code, rep.Verdict) + } + if len(fb.deleted) != 1 { + t.Fatalf("deleted %v", fb.deleted) + } + // --fail-on none reports the same finding but passes. + fb2 := &fakeBranches{} + verifyServer(t, fb2, true) + os.Remove(mark) + args = append([]string{"bot", "verify", "proj1", "--json", "--fail-on", "none", "--"}, migrationCommand(mark, "0")...) + if code, stdout, _ := run(t, args...); code != 0 || !strings.Contains(stdout, `"table_dropped"`) { + t.Fatalf("--fail-on none: code %d\n%s", code, stdout) + } +} + +func TestBotVerify_FailedMigrationFailsAndDeletes(t *testing.T) { + withFastPoll(t) + fb := &fakeBranches{} + verifyServer(t, fb, true) + _, mark := fakePgbot(t, "info") + args := append([]string{"bot", "verify", "proj1", "--json", "--"}, migrationCommand(mark, "3")...) + code, stdout, _ := run(t, args...) + var rep verifyReport + _ = json.Unmarshal([]byte(stdout), &rep) + if code != exitFailure || rep.Verdict != "fail" || rep.Postgres.ExitCode == nil || *rep.Postgres.ExitCode != 3 { + t.Fatalf("code %d report %+v", code, rep) + } + if len(fb.deleted) != 1 { + t.Fatalf("deleted %v", fb.deleted) + } +} + +func TestBotVerify_ComparePGX(t *testing.T) { + withFastPoll(t) + fb := &fakeBranches{} + verifyServer(t, fb, true) + _, mark := fakePgbot(t, "info") + args := append([]string{"bot", "verify", "proj1", "--json", "--compare-pgx", "--"}, migrationCommand(mark, "0")...) + code, stdout, stderr := run(t, args...) + var rep verifyReport + _ = json.Unmarshal([]byte(stdout), &rep) + if code != 0 || rep.PGXCompatible == nil || !*rep.PGXCompatible || rep.PGX == nil || rep.PGX.Engine != "pgx" { + t.Fatalf("code %d report %+v stderr %s", code, rep, stderr) + } + if len(fb.created) != 2 || len(fb.deleted) != 2 { + t.Fatalf("created %d deleted %d, want 2/2", len(fb.created), len(fb.deleted)) + } +} + +func TestBotVerify_ComparePGXUnavailableIsReportedNotHidden(t *testing.T) { + withFastPoll(t) + fb := &fakeBranches{} + verifyServer(t, fb, false) + _, mark := fakePgbot(t, "info") + args := append([]string{"bot", "verify", "proj1", "--json", "--compare-pgx", "--"}, migrationCommand(mark, "0")...) + code, stdout, _ := run(t, args...) + var rep verifyReport + _ = json.Unmarshal([]byte(stdout), &rep) + if rep.PGXCompatible == nil || *rep.PGXCompatible || !strings.Contains(string(rep.PGX.Unavailable), "engine_unavailable") { + t.Fatalf("report %+v", rep) + } + // PostgreSQL verification itself was fine: PGX being unavailable is + // "unsupported", reported but not blocking under the default policy. + if rep.Verdict != "unsupported" || rep.Blocking || code != 0 || len(fb.deleted) != 1 { + t.Fatalf("verdict %q blocking %v code %d deleted %v", rep.Verdict, rep.Blocking, code, fb.deleted) + } +} + +func verifyJSON(t *testing.T, extra ...string) (int, verifyReport, string) { + t.Helper() + code, stdout, stderr := run(t, extra...) + var rep verifyReport + if err := json.Unmarshal([]byte(stdout), &rep); err != nil { + t.Fatalf("not JSON (code %d): %v\n%s\n%s", code, err, stdout, stderr) + } + return code, rep, stderr +} + +// The brief's rule: a skipped verification must never read as a pass. +func TestBotVerify_OldPgbotWithoutSchemaIsIncompleteAndBlocks(t *testing.T) { + withFastPoll(t) + fb := &fakeBranches{} + verifyServer(t, fb, true) + _, mark := fakePgbot(t, "info") + t.Setenv("FAKE_PGBOT_VERSION", "0.9.0") + t.Setenv("FAKE_PGBOT_NO_SCHEMA", "1") + code, rep, _ := verifyJSON(t, append([]string{"bot", "verify", "proj1", "--json", "--compare-pgx", "--"}, migrationCommand(mark, "0")...)...) + if rep.Verdict != "incomplete" || !rep.Blocking || code != exitFailure { + t.Fatalf("code %d report %+v", code, rep) + } + if !strings.Contains(rep.SchemaReviewSkipped, "0.10.0") { + t.Fatalf("skip reason should name the needed version: %q", rep.SchemaReviewSkipped) + } + if rep.PGXCompatible != nil { + t.Fatalf("pgx_compatible must be absent when no comparison ran, got %v", *rep.PGXCompatible) + } + if len(fb.deleted) != 2 { + t.Fatalf("deleted %v, want both branches", fb.deleted) + } + // An explicit policy may accept it — then it is reported, not hidden, and does not block. + os.Remove(mark) + code, rep, _ = verifyJSON(t, append([]string{"bot", "verify", "proj1", "--json", "--block-on", "fail,dangerous,error", "--"}, migrationCommand(mark, "0")...)...) + if rep.Verdict != "incomplete" || rep.Blocking || code != 0 { + t.Fatalf("accepted incomplete: code %d report %+v", code, rep) + } +} + +func TestBotVerify_WarningBelowThresholdInformsOnly(t *testing.T) { + withFastPoll(t) + verifyServer(t, &fakeBranches{}, true) + _, mark := fakePgbot(t, "warning") + code, rep, _ := verifyJSON(t, append([]string{"bot", "verify", "proj1", "--json", "--"}, migrationCommand(mark, "0")...)...) + if rep.Verdict != "warning" || rep.Blocking || code != 0 || rep.Summary.Warning != 1 { + t.Fatalf("code %d report %+v", code, rep) + } + os.Remove(mark) + code, rep, _ = verifyJSON(t, append([]string{"bot", "verify", "proj1", "--json", "--fail-on", "warning", "--"}, migrationCommand(mark, "0")...)...) + if rep.Verdict != "dangerous" || !rep.Blocking || code != exitFailure { + t.Fatalf("--fail-on warning: code %d report %+v", code, rep) + } + os.Remove(mark) + code, rep, _ = verifyJSON(t, append([]string{"bot", "verify", "proj1", "--json", "--block-on", "warning", "--"}, migrationCommand(mark, "0")...)...) + if !rep.Blocking || code != exitFailure { + t.Fatalf("--block-on warning: code %d report %+v", code, rep) + } +} + +func TestBotVerify_LintFailureIsIncomplete(t *testing.T) { + withFastPoll(t) + verifyServer(t, &fakeBranches{}, true) + _, mark := fakePgbot(t, "info") + t.Setenv("FAKE_LINT_FAIL", "1") + code, rep, _ := verifyJSON(t, append([]string{"bot", "verify", "proj1", "--json", "--"}, migrationCommand(mark, "0")...)...) + if rep.Verdict != "incomplete" || !rep.Blocking || code != exitFailure { + t.Fatalf("code %d report %+v", code, rep) + } +} + +func TestBotVerify_PGXSchemaDifferenceIsUnsupported(t *testing.T) { + withFastPoll(t) + verifyServer(t, &fakeBranches{}, true) + _, mark := fakePgbot(t, "info") + t.Setenv("FAKE_COMPARE_DIFF", "1") + code, rep, _ := verifyJSON(t, append([]string{"bot", "verify", "proj1", "--json", "--compare-pgx", "--"}, migrationCommand(mark, "0")...)...) + if rep.Verdict != "unsupported" || rep.PGXCompatible == nil || *rep.PGXCompatible || rep.Blocking || code != 0 { + t.Fatalf("code %d report %+v", code, rep) + } + os.Remove(mark) + code, rep, _ = verifyJSON(t, append([]string{"bot", "verify", "proj1", "--json", "--compare-pgx", "--block-on", "fail,dangerous,unsupported", "--"}, migrationCommand(mark, "0")...)...) + if !rep.Blocking || code != exitFailure { + t.Fatalf("blocking on unsupported: code %d report %+v", code, rep) + } +} + +// A branch that never becomes ready is an infrastructure error: exit 3, so CI +// can tell "the platform failed" from "your migration is unsafe". +func TestBotVerify_InfrastructureErrorExitsThree(t *testing.T) { + withFastPoll(t) + fb := &fakeBranches{} + withServer(t, func(w http.ResponseWriter, r *http.Request) { + name := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:] + switch r.Method { + case http.MethodPost: + w.WriteHeader(http.StatusCreated) + w.Write([]byte(`{"id":"b1","name":"x","status":"creating"}`)) + case http.MethodGet: + w.Write([]byte(`{"id":"b1","name":"` + name + `","status":"failed","engine":"postgres"}`)) + case http.MethodDelete: + fb.mu.Lock() + fb.deleted = append(fb.deleted, name) + fb.mu.Unlock() + w.WriteHeader(http.StatusAccepted) + w.Write([]byte(`{"status":"deleting"}`)) + } + }) + _, mark := fakePgbot(t, "info") + code, rep, _ := verifyJSON(t, append([]string{"bot", "verify", "proj1", "--json", "--"}, migrationCommand(mark, "0")...)...) + if rep.Verdict != "error" || !rep.Blocking || code != exitInfra { + t.Fatalf("code %d report %+v", code, rep) + } + if len(fb.deleted) != 1 { + t.Fatalf("a failed branch is still deleted, got %v", fb.deleted) + } + if _, err := os.Stat(mark); err == nil { + t.Fatal("the migration must not run without a ready branch") + } +} + +func TestBotVerify_CleanupFailureIsAWarning(t *testing.T) { + withFastPoll(t) + withServer(t, func(w http.ResponseWriter, r *http.Request) { + name := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:] + switch r.Method { + case http.MethodPost: + w.WriteHeader(http.StatusCreated) + w.Write([]byte(`{"id":"b1","name":"x","status":"creating"}`)) + case http.MethodGet: + w.Write([]byte(`{"id":"b1","name":"` + name + `","status":"ready","engine":"postgres","connection_url":"postgres://u:p@h/db"}`)) + case http.MethodDelete: + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(`{"error":"boom"}`)) + } + }) + _, mark := fakePgbot(t, "info") + code, rep, _ := verifyJSON(t, append([]string{"bot", "verify", "proj1", "--json", "--"}, migrationCommand(mark, "0")...)...) + if rep.Blocking || code != 0 || len(rep.Cleanup) != 1 || rep.Cleanup[0].Deleted { + t.Fatalf("code %d report %+v", code, rep) + } + found := false + for _, c := range rep.Categories { + found = found || c == "warning" + } + if !found { + t.Fatalf("categories %v, want warning for the undeleted branch", rep.Categories) + } +} + +func TestBotVerify_BlockOnValidation(t *testing.T) { + isolateHome(t) + fakePgbot(t, "info") + code, _, stderr := run(t, "bot", "verify", "proj1", "--block-on", "fail,maybe", "--", "true") + if code != exitUsage || !strings.Contains(stderr, "maybe") { + t.Fatalf("code %d stderr %s", code, stderr) + } +} + +func TestBotBranchCommands_RefuseConnectionStringsAndAI(t *testing.T) { + isolateHome(t) + fakePgbot(t, "info") + cases := [][]string{ + {"bot", "run", "proj", "br", "--", "inspect", "postgres://prod:pw@db.prod/app"}, + {"bot", "run", "proj", "br", "--", "inspect", "service=prod"}, + {"bot", "run", "proj", "br", "--", "ask", "why is it slow"}, + {"bot", "run", "proj", "br", "--", "sql", "explain", "--ai", "select 1"}, + {"bot", "explain", "proj", "br", "postgres://prod:pw@db.prod/app"}, + } + for _, c := range cases { + code, _, stderr := run(t, c...) + if code != exitUsage { + t.Errorf("%v: code %d, want usage refusal; stderr %s", c, code, stderr) + } + if strings.Contains(stderr, "pw@db.prod") { + t.Errorf("%v: echoed the connection string: %s", c, stderr) + } + } +} + +func TestBotLint_PassesBranchURLInEnvOnly(t *testing.T) { + withServer(t, func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"id":"b1","name":"br","status":"ready","connection_url":"postgres://u:sekretpassw0rd@br.example/db"}`)) + }) + logPath, _ := fakePgbot(t, "info") + code, stdout, stderr := run(t, "bot", "lint", "proj", "br", "--json") + if code != 0 || !strings.Contains(stdout, `"findings"`) { + t.Fatalf("code %d stdout %s stderr %s", code, stdout, stderr) + } + calls, _ := os.ReadFile(logPath) + if !strings.Contains(string(calls), "ARGS lint --fail-on none --format json | URL=postgres://u:sekretpassw0rd@br.example/db") { + t.Fatalf("pgbot did not get the branch URL via the environment:\n%s", calls) + } +} + +func TestBotInspect_SuppressesDisposableBranchSettings(t *testing.T) { + withServer(t, func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"id":"b1","name":"br","status":"ready","connection_url":"postgres://u:p@br.example/db"}`)) + }) + logPath, _ := fakePgbot(t, "info") + code, _, stderr := run(t, "bot", "inspect", "proj", "br", "--json") + calls, _ := os.ReadFile(logPath) + if code != 0 || !strings.Contains(string(calls), "ARGS inspect --no-store --ignore fsync_off --ignore full_page_writes_off --ignore checkpoints_forced --json") || + !strings.Contains(stderr, "suppressed for disposable branches") { + t.Fatalf("code %d stderr %s calls %s", code, stderr, calls) + } +} + +func TestBotStatus_NotInstalled(t *testing.T) { + home := isolateHome(t) + t.Setenv("PATH", home) // no pgbot anywhere + t.Setenv("PGRUN_PGBOT", "") + t.Setenv("PGRUN_HOME", filepath.Join(home, "pgrun")) + code, stdout, _ := run(t, "bot", "status", "--json") + var doc botStatusDoc + _ = json.Unmarshal([]byte(stdout), &doc) + if code != exitFailure || doc.Installed || !strings.Contains(doc.Hint, "pgrun bot install") { + t.Fatalf("code %d doc %+v", code, doc) + } +} + +func TestUpsertManagedBlock(t *testing.T) { + user := "# My project\n\nKeep this.\n" + once, err := upsertManagedBlock(user, "hello") + if err != nil || !strings.HasPrefix(once, user) || !strings.Contains(once, agentsBlockBegin+"\nhello\n"+agentsBlockEnd) { + t.Fatalf("first insert: %q %v", once, err) + } + twice, _ := upsertManagedBlock(once, "hello") + if twice != once { + t.Fatalf("not idempotent:\n%q\n%q", once, twice) + } + withTail := once + "\n## After\nuser text\n" + replaced, _ := upsertManagedBlock(withTail, "new body") + if !strings.HasPrefix(replaced, user) || !strings.HasSuffix(replaced, "\n## After\nuser text\n") || strings.Contains(replaced, "hello") { + t.Fatalf("replace touched user text: %q", replaced) + } + if _, err := upsertManagedBlock(user+agentsBlockBegin+"\nunterminated", "x"); err == nil { + t.Fatal("an unterminated block must be refused, not guessed") + } +} + +func TestSetup_InstallsSkillAndReportsBot(t *testing.T) { + home := isolateHome(t) + fakePgbot(t, "info") + agents := filepath.Join(home, "repo", "AGENTS.md") + os.MkdirAll(filepath.Dir(agents), 0o755) + os.WriteFile(agents, []byte("# Rules\n\nDo not touch.\n"), 0o644) + t.Setenv("PGRUN_API_URL", "https://pgrun.example") + t.Setenv("PGRUN_API_TOKEN", "tok") + + code, stdout, stderr := run(t, "setup", "--json", "--agent", "claude,codex", "--agents-md", agents) + if code != 0 { + t.Fatalf("code %d stderr %s stdout %s", code, stderr, stdout) + } + var doc setupDoc + if err := json.Unmarshal([]byte(stdout), &doc); err != nil { + t.Fatal(err) + } + if !doc.Ready || doc.Pgbot.Action != "found" { + t.Fatalf("doc %+v", doc) + } + for _, p := range []string{".claude/skills/pgrun-branching/SKILL.md", ".codex/skills/pgrun-branching/SKILL.md"} { + if _, err := os.Stat(filepath.Join(home, p)); err != nil { + t.Errorf("skill missing at %s", p) + } + } + want := map[string]bool{"bot.verify": false, "bot.schema_review": false, "engine.pgx": false} + for _, c := range doc.Capabilities { + if _, ok := want[c]; ok { + want[c] = true + } + } + for c, ok := range want { + if !ok { + t.Errorf("capability %s not reported", c) + } + } + md, _ := os.ReadFile(agents) + if !strings.HasPrefix(string(md), "# Rules\n\nDo not touch.\n") || !strings.Contains(string(md), "pgrun bot verify") { + t.Fatalf("AGENTS.md: %s", md) + } + // Second run: everything current, file unchanged. + code, stdout, _ = run(t, "setup", "--json", "--agent", "claude,codex", "--agents-md", agents) + md2, _ := os.ReadFile(agents) + if code != 0 || string(md2) != string(md) || !strings.Contains(stdout, `"status": "current"`) { + t.Fatalf("second run not idempotent: code %d\n%s", code, stdout) + } +} + +func TestSetup_WithoutAgentsMDFlagNeverWritesInstructions(t *testing.T) { + home := isolateHome(t) + fakePgbot(t, "info") + wd, _ := os.Getwd() + repo := filepath.Join(home, "repo") + os.MkdirAll(repo, 0o755) + os.WriteFile(filepath.Join(repo, "AGENTS.md"), []byte("mine\n"), 0o644) + os.WriteFile(filepath.Join(repo, "CLAUDE.md"), []byte("mine too\n"), 0o644) + os.Chdir(repo) + t.Cleanup(func() { os.Chdir(wd) }) + run(t, "setup", "--json") + for _, f := range []string{"AGENTS.md", "CLAUDE.md"} { + b, _ := os.ReadFile(filepath.Join(repo, f)) + if !strings.HasPrefix(string(b), "mine") || strings.Contains(string(b), "pgrun") { + t.Fatalf("%s changed without consent: %q", f, b) + } + } +} + +// A CI token may only create ci-… branches: verify renames once on 422 token_scope. +func TestBotVerify_CITokenNamingIsRetriedAsCiPrefix(t *testing.T) { + withFastPoll(t) + fb := &fakeBranches{} + withServer(t, func(w http.ResponseWriter, r *http.Request) { + name := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:] + switch r.Method { + case http.MethodPost: + var body map[string]any + b, _ := io.ReadAll(r.Body) + _ = json.Unmarshal(b, &body) + if !strings.HasPrefix(body["name"].(string), "ci-") { + w.WriteHeader(http.StatusUnprocessableEntity) + w.Write([]byte(`{"error":"token_scope","message":"a CI token can only create branches named ci-…"}`)) + return + } + fb.mu.Lock() + fb.created = append(fb.created, body) + fb.mu.Unlock() + w.WriteHeader(http.StatusCreated) + w.Write([]byte(`{"id":"b1","name":"` + body["name"].(string) + `","status":"creating"}`)) + case http.MethodGet: + w.Write([]byte(`{"id":"b1","name":"` + name + `","status":"ready","engine":"postgres","connection_url":"postgres://u:p@h/db"}`)) + case http.MethodDelete: + fb.mu.Lock() + fb.deleted = append(fb.deleted, name) + fb.mu.Unlock() + w.WriteHeader(http.StatusAccepted) + w.Write([]byte(`{"status":"deleting"}`)) + } + }) + _, mark := fakePgbot(t, "info") + code, rep, _ := verifyJSON(t, append([]string{"bot", "verify", "proj1", "--json", "--"}, migrationCommand(mark, "0")...)...) + if code != 0 || rep.Blocking || len(fb.created) != 1 || !strings.HasPrefix(rep.Postgres.Branch, "ci-verify-") { + t.Fatalf("code %d verdict %s created %v branch %s", code, rep.Verdict, fb.created, rep.Postgres.Branch) + } + if len(fb.deleted) != 1 || fb.deleted[0] != rep.Postgres.Branch { + t.Fatalf("deleted %v, want the renamed branch", fb.deleted) + } +} + +func TestBotVerify_MigrationNeverSeesTheAPIToken(t *testing.T) { + withFastPoll(t) + verifyServer(t, &fakeBranches{}, true) + _, mark := fakePgbot(t, "info") + out := filepath.Join(t.TempDir(), "env") + t.Setenv("PGRUN_API_TOKEN", "pgr_supersecrettoken0123456789") + cmd := []string{"/bin/sh", "-c", `echo "TOKEN=${PGRUN_API_TOKEN:-none} URL_SET=${DATABASE_URL:+yes}" > "` + out + `"; touch "` + mark + `"`} + code, _, stderr := run(t, append([]string{"bot", "verify", "proj1", "--json", "--"}, cmd...)...) + got, _ := os.ReadFile(out) + if code != 0 || strings.TrimSpace(string(got)) != "TOKEN=none URL_SET=yes" { + t.Fatalf("code %d env %q stderr %s", code, got, stderr) + } +} diff --git a/internal/cli/bot_verify.go b/internal/cli/bot_verify.go new file mode 100644 index 0000000..10b9aea --- /dev/null +++ b/internal/cli/bot_verify.go @@ -0,0 +1,747 @@ +package cli + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/pgrundev/pgrun-cli/internal/api" + "github.com/pgrundev/pgrun-cli/internal/pgbot" +) + +// `pgrun bot verify -- ` is the PostgreSQL verification +// workflow. On a DISPOSABLE branch of the project's Safe Copy (PostgreSQL by +// default, so the canonical engine) it: +// +// 1. snapshots the schema and runs pgbot lint (the "before"), +// 2. runs the migration command with DATABASE_URL in its environment only, +// 3. snapshots and lints again, and has pgbot classify what the migration did +// (rewrites, blocking index builds, validating scans, drops, renames), +// 4. with --compare-pgx, runs the same migration on a PGX branch and compares +// the resulting schema with PostgreSQL's, +// 5. deletes every branch it created (unless --keep), even on failure. +// +// It never touches the project's base branch or Safe Copy, and pgbot only +// reads. The migration command is the caller's own, run exactly like +// `pgrun branch exec` runs it. + +const ( + VerifyKind = "pgrun-verify" + VerifyVersion = "1.1.0" +) + +type verifyEngineRun struct { + Engine string `json:"engine"` + RequestedEngine string `json:"requested_engine"` + Branch string `json:"branch"` + Database string `json:"database,omitempty"` + ReadyMs int64 `json:"ready_ms"` + MigrateMs int64 `json:"migrate_ms"` + ExitCode *int `json:"migration_exit_code,omitempty"` + Error string `json:"error,omitempty"` + Unavailable json.RawMessage `json:"unavailable,omitempty"` // the API's engine_unavailable body +} + +type lintFinding struct { + ID string `json:"id"` + Severity string `json:"severity"` + Object string `json:"object,omitempty"` + Title string `json:"title"` +} + +type verifyCleanup struct { + Branch string `json:"branch"` + Deleted bool `json:"deleted"` + Error string `json:"error,omitempty"` + Kept bool `json:"kept,omitempty"` +} + +type verifyReport struct { + Kind string `json:"kind"` + Version string `json:"version"` + Project string `json:"project"` + Verdict string `json:"verdict"` // see verdictOrder + Categories []string `json:"categories"` + Blocking bool `json:"blocking"` + Policy verifyPolicy `json:"policy"` + Summary verifySummary `json:"summary"` + Reasons []string `json:"reasons"` + FailOn string `json:"fail_on"` // = policy.fail_on (1.0.0 field, kept) + Postgres *verifyEngineRun `json:"verification"` + SchemaReview json.RawMessage `json:"schema_review,omitempty"` + SchemaReviewSkipped string `json:"schema_review_skipped,omitempty"` + NewLintFindings []lintFinding `json:"new_lint_findings"` + PGX *verifyEngineRun `json:"pgx,omitempty"` + PGXComparison json.RawMessage `json:"pgx_comparison,omitempty"` + PGXCompatible *bool `json:"pgx_compatible,omitempty"` + Cleanup []verifyCleanup `json:"cleanup"` + Pgbot string `json:"pgbot_version"` + DurationMs int64 `json:"duration_ms"` +} + +// Verdicts, highest precedence first. A run collects every category that applies; +// the verdict is the highest one, and the run BLOCKS when any collected category +// is in the policy's block_on list. A review that could not run is "incomplete", +// never "pass". +// +// fail the migration exited non-zero on canonical PostgreSQL (confirmed failure) +// dangerous the schema review found a finding at/above --fail-on (rewrite, blocking +// index build, SET NOT NULL, drop, rename, type change, …) +// unsupported --compare-pgx: PGX was unavailable, failed where PostgreSQL succeeded, +// or produced a different schema (PostgreSQL itself was fine) +// incomplete the schema review or lint could not run (e.g. a pgbot without `schema`) +// error infrastructure or tool error (branch never ready, API, command not startable) +// warning informational: findings below --fail-on, new lint findings, a branch +// that could not be deleted (its TTL removes it) +// pass everything ran and nothing was found +var verdictOrder = []string{"fail", "dangerous", "unsupported", "incomplete", "error", "warning", "pass"} + +// DefaultBlockOn: warnings and PGX-only differences inform; they do not block. +var DefaultBlockOn = []string{"fail", "dangerous", "incomplete", "error"} + +const exitInfra = 3 // blocking, and every blocking category is "error" + +type verifyPolicy struct { + FailOn string `json:"fail_on"` + BlockOn []string `json:"block_on"` +} + +type verifySummary struct { + Critical int `json:"critical"` + Warning int `json:"warning"` + Info int `json:"info"` + NewLint int `json:"new_lint"` +} + +func parseBlockOn(s string) ([]string, error) { + out := []string{} + seen := map[string]bool{} + for _, c := range strings.Split(s, ",") { + c = strings.TrimSpace(c) + if c == "" || c == "none" { + continue + } + ok := false + for _, v := range verdictOrder { + ok = ok || (v == c && v != "pass") + } + if !ok { + return nil, fmt.Errorf("unknown category %q (want fail, dangerous, unsupported, incomplete, error, warning or none)", c) + } + if !seen[c] { + seen[c] = true + out = append(out, c) + } + } + return out, nil +} + +func (rep *verifyReport) add(category, reason string) { + for _, c := range rep.Categories { + if c == category { + goto reason + } + } + rep.Categories = append(rep.Categories, category) +reason: + if reason != "" { + rep.Reasons = append(rep.Reasons, reason) + } +} + +// finish derives verdict and blocking from the collected categories. +func (rep *verifyReport) finish() { + rank := map[string]int{} + for i, v := range verdictOrder { + rank[v] = i + } + if len(rep.Categories) == 0 { + rep.Categories = []string{"pass"} + } + sortByRank := func(cs []string) { + for i := 1; i < len(cs); i++ { + for j := i; j > 0 && rank[cs[j]] < rank[cs[j-1]]; j-- { + cs[j], cs[j-1] = cs[j-1], cs[j] + } + } + } + sortByRank(rep.Categories) + rep.Verdict = rep.Categories[0] + rep.Blocking = false + for _, c := range rep.Categories { + for _, b := range rep.Policy.BlockOn { + if c == b { + rep.Blocking = true + } + } + } +} + +// exitCode: 0 not blocking; 3 when only infrastructure errors block; else 1. +func (rep *verifyReport) exitCode() int { + if !rep.Blocking { + return exitSuccess + } + for _, c := range rep.Categories { + for _, b := range rep.Policy.BlockOn { + if c == b && c != "error" { + return exitFailure + } + } + } + return exitInfra +} + +func botVerify(args []string, stdout, stderr io.Writer) int { + pos, rest := leadingPositionals(args) + if len(pos) > 1 { + return usageErrf(stderr, "bot verify: unexpected argument %s", redactedArg(pos[1])) + } + fs := flag.NewFlagSet("bot verify", flag.ContinueOnError) + fs.SetOutput(stderr) + from := fs.String("from", "", "parent branch to verify on (default: the project's base — its Safe Copy)") + engine := fs.String("engine", "postgres", "engine of the verification branch: postgres (canonical) or pgx") + comparePGX := fs.Bool("compare-pgx", false, "also run the migration on a PGX branch and compare its schema with PostgreSQL's") + ttl := fs.String("ttl", "1h", "TTL of the verification branches (the backstop if pgrun is killed)") + keep := fs.Bool("keep", false, "keep the verification branches instead of deleting them") + failOn := fs.String("fail-on", "critical", "a schema-review finding at/above this is `dangerous`: critical|warning|none") + blockOn := fs.String("block-on", strings.Join(DefaultBlockOn, ","), "categories that make the run blocking (exit non-zero): fail,dangerous,unsupported,incomplete,error,warning, or none") + timeout := fs.Duration("timeout", 300*time.Second, "max wait for each branch to become ready") + jsonOut := fs.Bool("json", false, "print the verification report as JSON (pgrun-verify/1.0.0) on stdout") + urlFlag, tokenFlag := addAuthFlags(fs) + if ok, code := parseOrExit(fs, rest); !ok { + return code + } + command := fs.Args() + if len(command) == 0 { + return usageErrf(stderr, "bot verify: missing the migration command after --, e.g. pgrun bot verify -- bin/rails db:migrate") + } + if *engine != "postgres" && *engine != "pgx" { + return usageErrf(stderr, "bot verify: --engine must be postgres or pgx") + } + if *comparePGX && *engine == "pgx" { + return usageErrf(stderr, "bot verify: --compare-pgx compares PGX against a postgres verification branch; leave --engine at postgres") + } + switch *failOn { + case "critical", "warning", "none": + default: + return usageErrf(stderr, "bot verify: --fail-on must be critical, warning or none") + } + blocking, err := parseBlockOn(*blockOn) + if err != nil { + return usageErrf(stderr, "bot verify: --block-on: %v", err) + } + if !api.ValidTTL(*ttl) { + return usageErrf(stderr, "bot verify: --ttl must be one of 1h, 6h, 24h, 7d") + } + explicit := "" + if len(pos) == 1 { + explicit = pos[0] + } + project, code, ok := resolveProject(explicit, rest, stderr) + if !ok { + return code + } + bin, ok := requireBot(context.Background(), stderr) + if !ok { + return exitFailure + } + cfg, code, ok := resolveOrHint(*urlFlag, *tokenFlag, stderr) + if !ok { + return code + } + client := api.New(cfg.URL, cfg.Token) + client.OnCapacityWait = func(d time.Duration) { + fmt.Fprintf(stderr, "pgrun: the host is busy, retrying in %ds\n", int(d.Seconds())) + } + v := &verifier{client: client, bin: bin, project: project, from: *from, ttl: *ttl, timeout: *timeout, + command: command, stderr: stderr, keep: *keep} + rep := v.run(*engine, *comparePGX, verifyPolicy{FailOn: *failOn, BlockOn: blocking}) + // Every branch URL is scrubbed from the report too (an error string that + // echoed one must not print it). + for _, u := range v.redactorURLs { + stdout = redactWriter(stdout, newRedactor(u)) + } + if *jsonOut { + writeJSONDoc(stdout, rep) + } else { + printVerify(stdout, rep) + } + return rep.exitCode() +} + +type verifier struct { + client *api.Client + bin pgbot.Binary + project string + from string + ttl string + timeout time.Duration + command []string + stderr io.Writer + keep bool + mu sync.Mutex + created []string + redactorURLs []string +} + +func randSuffix() string { + b := make([]byte, 3) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +func (v *verifier) run(engine string, comparePGX bool, policy verifyPolicy) (rep verifyReport) { + began := time.Now() + failOn := policy.FailOn + rep = verifyReport{Kind: VerifyKind, Version: VerifyVersion, Project: v.project, FailOn: failOn, Policy: policy, + Pgbot: v.bin.Version, Categories: []string{}, Reasons: []string{}, NewLintFindings: []lintFinding{}, Cleanup: []verifyCleanup{}} + defer func() { + rep.Cleanup = v.cleanup() + for _, c := range rep.Cleanup { + if !c.Deleted && !c.Kept { + rep.add("warning", "verification branch "+c.Branch+" could not be deleted (its TTL removes it): "+c.Error) + } + } + rep.Summary.NewLint = len(rep.NewLintFindings) + rep.DurationMs = time.Since(began).Milliseconds() + rep.finish() + }() + work, err := os.MkdirTemp("", "pgrun-verify-*") + if err != nil { + rep.add("error", err.Error()) + return rep + } + defer os.RemoveAll(work) + + stamp := time.Now().UTC().Format("0102-1504") + "-" + randSuffix() + pgRun := &verifyEngineRun{RequestedEngine: engine, Branch: "verify-" + stamp + "-" + engineTag(engine)} + rep.Postgres = pgRun + var pgxRun *verifyEngineRun + if comparePGX { + pgxRun = &verifyEngineRun{RequestedEngine: "pgx", Branch: "verify-" + stamp + "-pgx"} + rep.PGX = pgxRun + } + + // Create every branch first, then wait: provisioning runs in parallel. + pgBranch, pgRaw := v.create(pgRun) + var pgxBranch api.Branch + var pgxRaw []byte + if pgxRun != nil { + pgxBranch, pgxRaw = v.create(pgxRun) + } + pgURL := v.wait(pgRun, pgBranch, pgRaw) + pgxURL := "" + if pgxRun != nil { + pgxURL = v.wait(pgxRun, pgxBranch, pgxRaw) + } + if pgURL == "" { + rep.add("error", "verification branch not ready: "+pgRun.Error) + return rep + } + + canReview := v.bin.Capabilities.SchemaReview + before := filepath.Join(work, "before.json") + after := filepath.Join(work, "after.json") + if canReview { + if err := v.pgbotToFile(pgURL, before, "schema", "snapshot"); err != nil { + canReview = false + rep.SchemaReviewSkipped = "schema snapshot before the migration failed: " + err.Error() + } + } else { + rep.SchemaReviewSkipped = fmt.Sprintf("pgbot %s has no `schema` command (needs pgbot %s or newer)", v.bin.Version, pgbot.SchemaMinVersion) + } + lintBefore, lintErr := v.lint(pgURL) + if lintErr != nil { + rep.add("incomplete", "lint before the migration failed: "+lintErr.Error()) + } + + code := v.migrate(pgRun, pgURL) + switch { + case pgRun.Error != "": + rep.add("error", "the migration command could not start: "+pgRun.Error) + case code != 0: + rep.add("fail", fmt.Sprintf("the migration exited %d on %s", code, pgRun.Engine)) + } + + if canReview { + if err := v.pgbotToFile(pgURL, after, "schema", "snapshot"); err != nil { + rep.SchemaReviewSkipped = "schema snapshot after the migration failed: " + err.Error() + } else { + out, _, err := pgbot.Output(context.Background(), v.bin, "", "schema", "diff", before, after, "--format", "json") + if err != nil { + rep.SchemaReviewSkipped = "schema diff failed: " + err.Error() + } else { + rep.SchemaReview = json.RawMessage(out) + rep.Summary.Critical, rep.Summary.Warning, rep.Summary.Info = reviewCounts(out) + switch sev := reviewSeverity(out); { + case atOrAbove(sev, failOn): + rep.add("dangerous", "schema review: "+summaryLine(out)) + case sev == "critical" || sev == "warning": + rep.add("warning", "schema review (below --fail-on "+failOn+"): "+summaryLine(out)) + } + } + } + } + if rep.SchemaReviewSkipped != "" { + rep.add("incomplete", "schema review did not run: "+rep.SchemaReviewSkipped) + } + if lintErr == nil { + if lintAfter, err := v.lint(pgURL); err == nil { + rep.NewLintFindings = newFindings(lintBefore, lintAfter) + if len(rep.NewLintFindings) > 0 { + rep.add("warning", fmt.Sprintf("%d new lint finding(s) after the migration", len(rep.NewLintFindings))) + } + } else { + rep.add("incomplete", "lint after the migration failed: "+err.Error()) + } + } + + if pgxRun != nil { + v.verifyPGX(&rep, pgxRun, pgxURL, after, canReview && rep.SchemaReviewSkipped == "", work) + } + return rep +} + +func reviewCounts(diff []byte) (critical, warning, info int) { + var d struct { + Summary struct{ Critical, Warning, Info int } `json:"summary"` + } + _ = json.Unmarshal(diff, &d) + return d.Summary.Critical, d.Summary.Warning, d.Summary.Info +} + +func engineTag(engine string) string { + if engine == "pgx" { + return "pgx" + } + return "pg" +} + +func (v *verifier) create(run *verifyEngineRun) (api.Branch, []byte) { + req := api.CreateBranchRequest{Name: run.Branch, TTL: v.ttl, ParentBranchID: v.from, Engine: run.RequestedEngine} + raw, b, err := v.client.CreateBranch(context.Background(), v.project, req) + // A project CI token may only create branches named ci-… (docs/ci-tokens.md): the + // server says so with 422 token_scope; the same branch is then named ci-verify-…. + if err != nil && strings.Contains(string(raw), `"token_scope"`) && !strings.HasPrefix(run.Branch, "ci-") { + run.Branch = "ci-" + run.Branch + req.Name = run.Branch + raw, b, err = v.client.CreateBranch(context.Background(), v.project, req) + } + if err != nil { + var apiErr *api.APIError + if errors.As(err, &apiErr) && strings.Contains(string(raw), `"engine_unavailable"`) { + run.Unavailable = json.RawMessage(raw) + } + run.Error = err.Error() + return api.Branch{}, nil + } + v.mu.Lock() + v.created = append(v.created, run.Branch) + v.mu.Unlock() + return b, raw +} + +func (v *verifier) wait(run *verifyEngineRun, b api.Branch, raw []byte) string { + if run.Error != "" { + return "" + } + began := time.Now() + ctx, cancel := context.WithTimeout(context.Background(), v.timeout) + defer cancel() + _, b, err := v.client.WaitForTerminal(ctx, v.project, raw, b) + run.ReadyMs = time.Since(began).Milliseconds() + switch { + case err != nil: + run.Error = err.Error() + case b.Status != api.StatusReady: + run.Error = api.WaitFailureReason(b.Name, b.Status) + case b.ConnectionURL == "": + run.Error = "ready but no connection_url" + } + run.Engine, run.Database = b.Engine, b.Database + if run.Error != "" { + return "" + } + v.mu.Lock() + v.redactorURLs = append(v.redactorURLs, b.ConnectionURL) + v.mu.Unlock() + return b.ConnectionURL +} + +// out redacts every branch URL this verifier has seen. +func (v *verifier) out() io.Writer { + w := v.stderr + v.mu.Lock() + defer v.mu.Unlock() + for _, u := range v.redactorURLs { + w = redactWriter(w, newRedactor(u)) + } + return w +} + +// migrate runs the caller's command; its output goes to stderr so stdout stays +// the report. +func (v *verifier) migrate(run *verifyEngineRun, url string) int { + fmt.Fprintf(v.stderr, "pgrun: running the migration on %s branch %s\n", run.Engine, run.Branch) + began := time.Now() + cmd := exec.Command(v.command[0], v.command[1:]...) + cmd.Stdout, cmd.Stderr = v.out(), v.out() + cmd.Env = append(migrationEnv(os.Environ()), "DATABASE_URL="+url) + err := cmd.Run() + run.MigrateMs = time.Since(began).Milliseconds() + code := 0 + if err != nil { + var ee *exec.ExitError + if errors.As(err, &ee) { + code = ee.ExitCode() + } else { + code = 127 + run.Error = err.Error() + } + } + run.ExitCode = &code + return code +} + +// migrationEnv: the caller's environment minus pgrun's own credentials and any +// DATABASE_URL — the migration needs the branch, never the API token. +func migrationEnv(env []string) []string { + out := make([]string, 0, len(env)) + for _, kv := range env { + k := kv + if i := strings.IndexByte(kv, '='); i >= 0 { + k = kv[:i] + } + switch k { + case "PGRUN_API_TOKEN", "DATABASE_URL": + continue + } + out = append(out, kv) + } + return out +} + +func (v *verifier) pgbotToFile(url, path string, args ...string) error { + out, _, err := pgbot.Output(context.Background(), v.bin, url, args...) + if err != nil { + return err + } + return os.WriteFile(path, out, 0o600) +} + +func (v *verifier) lint(url string) ([]lintFinding, error) { + out, _, err := pgbot.Output(context.Background(), v.bin, url, "lint", "--fail-on", "none", "--format", "json") + if err != nil { + return nil, err + } + var doc struct { + Findings []lintFinding `json:"findings"` + } + if err := json.Unmarshal(out, &doc); err != nil { + return nil, err + } + return doc.Findings, nil +} + +func newFindings(before, after []lintFinding) []lintFinding { + seen := map[string]bool{} + for _, f := range before { + seen[f.ID+"\x00"+f.Object] = true + } + out := []lintFinding{} + for _, f := range after { + if !seen[f.ID+"\x00"+f.Object] { + out = append(out, f) + } + } + return out +} + +func (v *verifier) verifyPGX(rep *verifyReport, run *verifyEngineRun, url, pgAfter string, comparable bool, work string) { + f := false + if url == "" { + rep.PGXCompatible = &f + if len(run.Unavailable) > 0 { + rep.add("unsupported", "PGX is not available for this project: "+run.Error) + } else { + rep.add("error", "pgx branch unavailable: "+run.Error) + } + return + } + code := v.migrate(run, url) + pgCode := 0 + if rep.Postgres.ExitCode != nil { + pgCode = *rep.Postgres.ExitCode + } + compatible := code == pgCode + if !compatible { + rep.add("unsupported", fmt.Sprintf("the migration exited %d on PGX but %d on PostgreSQL", code, pgCode)) + } + if !comparable { + // Without a schema review there is no PGX comparison either: say so, + // never report a match that was not checked. + rep.PGXCompatible = nil + if compatible { + rep.add("incomplete", "PGX schema comparison did not run (no schema review)") + } else { + rep.PGXCompatible = &f + } + return + } + pgxAfter := filepath.Join(work, "pgx-after.json") + if err := v.pgbotToFile(url, pgxAfter, "schema", "snapshot"); err != nil { + rep.add("incomplete", "pgx schema snapshot failed: "+err.Error()) + rep.PGXCompatible = nil + return + } + out, _, err := pgbot.Output(context.Background(), v.bin, "", "schema", "compare", pgxAfter, pgAfter, + "--format", "json", "--a-label", "pgx", "--b-label", "postgres") + if err != nil { + rep.add("incomplete", "pgx schema compare failed: "+err.Error()) + rep.PGXCompatible = nil + return + } + rep.PGXComparison = json.RawMessage(out) + var cmp struct { + Identical bool `json:"identical"` + Differences []json.RawMessage `json:"differences"` + } + if json.Unmarshal(out, &cmp) != nil { + rep.add("incomplete", "pgx schema compare returned an unreadable report") + rep.PGXCompatible = nil + return + } + if !cmp.Identical { + compatible = false + rep.add("unsupported", fmt.Sprintf("PGX produced a different schema than PostgreSQL (%d differences)", len(cmp.Differences))) + } + rep.PGXCompatible = &compatible +} + +func (v *verifier) cleanup() []verifyCleanup { + v.mu.Lock() + names := append([]string{}, v.created...) + v.mu.Unlock() + out := []verifyCleanup{} + for _, n := range names { + c := verifyCleanup{Branch: n} + if v.keep { + c.Kept = true + } else if _, _, err := v.client.DeleteBranch(context.Background(), v.project, n); err != nil { + c.Error = err.Error() + fmt.Fprintf(v.stderr, "pgrun: warning: could not delete verification branch %s (its %s TTL will): %v\n", n, v.ttl, err) + } else { + c.Deleted = true + } + out = append(out, c) + } + return out +} + +// reviewSeverity is the highest severity in a pgbot schema diff report. +func reviewSeverity(diff []byte) string { + var d struct { + Summary struct{ Critical, Warning, Info int } `json:"summary"` + } + if json.Unmarshal(diff, &d) != nil { + return "" + } + switch { + case d.Summary.Critical > 0: + return "critical" + case d.Summary.Warning > 0: + return "warning" + case d.Summary.Info > 0: + return "info" + } + return "" +} + +func atOrAbove(sev, failOn string) bool { + switch failOn { + case "critical": + return sev == "critical" + case "warning": + return sev == "critical" || sev == "warning" + } + return false +} + +func summaryLine(diff []byte) string { + var d struct { + Summary struct{ Critical, Warning, Info int } `json:"summary"` + Findings []struct { + ID, Severity, Object string + } `json:"findings"` + } + if json.Unmarshal(diff, &d) != nil { + return "unreadable" + } + var top []string + for _, f := range d.Findings { + if f.Severity != "info" && len(top) < 3 { + top = append(top, f.ID+" "+f.Object) + } + } + return fmt.Sprintf("%d critical, %d warning (%s)", d.Summary.Critical, d.Summary.Warning, strings.Join(top, "; ")) +} + +func printVerify(w io.Writer, rep verifyReport) { + block := "not blocking" + if rep.Blocking { + block = "BLOCKING (policy: " + strings.Join(rep.Policy.BlockOn, ",") + ")" + } + fmt.Fprintf(w, "verify %s: %s — %s; categories: %s\n", rep.Project, strings.ToUpper(rep.Verdict), block, strings.Join(rep.Categories, ", ")) + if r := rep.Postgres; r != nil { + code := "-" + if r.ExitCode != nil { + code = fmt.Sprint(*r.ExitCode) + } + fmt.Fprintf(w, " %s branch %s: ready in %dms, migration exit %s in %dms\n", dash(r.Engine), r.Branch, r.ReadyMs, code, r.MigrateMs) + } + for _, reason := range rep.Reasons { + fmt.Fprintf(w, " - %s\n", reason) + } + if rep.SchemaReviewSkipped != "" { + fmt.Fprintf(w, " schema review skipped: %s\n", rep.SchemaReviewSkipped) + } else if len(rep.SchemaReview) > 0 { + var d struct { + Findings []struct{ ID, Severity, Object, Detail, Advice string } `json:"findings"` + } + _ = json.Unmarshal(rep.SchemaReview, &d) + for _, f := range d.Findings { + if f.Severity == "info" { + continue + } + fmt.Fprintf(w, " %-8s %s %s\n %s\n", f.Severity, f.ID, f.Object, f.Advice) + } + } + for _, f := range rep.NewLintFindings { + fmt.Fprintf(w, " lint %-8s %s %s — %s\n", f.Severity, f.ID, f.Object, f.Title) + } + if rep.PGXCompatible != nil { + fmt.Fprintf(w, " pgx matches postgres: %v\n", *rep.PGXCompatible) + } + for _, c := range rep.Cleanup { + state := "deleted" + if c.Kept { + state = "kept" + } else if !c.Deleted { + state = "NOT deleted: " + c.Error + } + fmt.Fprintf(w, " cleanup %s: %s\n", c.Branch, state) + } + fmt.Fprintln(w, " --json for the full report") +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index d7dbc58..4a4fd3e 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -54,6 +54,12 @@ Usage: pgrun auth logout pgrun auth set --token [--url ] (advanced/CI — see PGRUN_API_TOKEN/PGRUN_API_URL below) pgrun auth status + pgrun setup [--agent claude,codex | --project | --dir ] [--agents-md ] [--no-bot] [--json] + (idempotent: skill + pgbot + auth check; the one install path) + pgrun bot status|install [--json] pgbot: read-only inspection and verification (see pgrun bot help) + pgrun bot inspect|lint|schema [] [--json] + pgrun bot explain [] "" --json`, `pgrun bot inspect --json`. +- Never print or commit a branch's `DATABASE_URL`; never ask the user to paste a token + (`pgrun auth login` is theirs to run). diff --git a/skills/embed.go b/skills/embed.go index 91fe9c1..465d87c 100644 --- a/skills/embed.go +++ b/skills/embed.go @@ -17,3 +17,10 @@ const PgrunBranchingName = "pgrun-branching" // //go:embed pgrun-branching/SKILL.md var PgrunBranching string + +// AgentsBlock is the short, pgrun-managed section `pgrun setup --agents-md +// ` writes between its markers in an AGENTS.md-style file, for agents +// that read project instructions rather than skills. +// +//go:embed agents-block.md +var AgentsBlock string diff --git a/skills/pgrun-branching/SKILL.md b/skills/pgrun-branching/SKILL.md index c5f057a..346e59b 100644 --- a/skills/pgrun-branching/SKILL.md +++ b/skills/pgrun-branching/SKILL.md @@ -1,6 +1,6 @@ --- name: pgrun-branching -description: Use when a coding task needs a real disposable Postgres — a migration, a schema change, a DB-dependent test, or "test this against real data." Creates an isolated PGRun branch, hands you its DATABASE_URL, and deletes it when you're done. Framework-independent (Rails, Django, Prisma, or anything else that reads DATABASE_URL). +description: Use when a coding task needs a real disposable Postgres — a migration, a schema change, a DB-dependent test, or "test this against real data" — or when you need to check a schema change before finishing. Creates an isolated PGRun branch (PGX by default where the project allows it, PostgreSQL otherwise), hands you its DATABASE_URL, deletes it when you're done, and verifies migrations against real PostgreSQL with PgBot (`pgrun bot verify`). Framework-independent (Rails, Django, Prisma, or anything else that reads DATABASE_URL). --- # pgrun branching @@ -16,6 +16,27 @@ A PGRun branch is copy-on-write off a project's base branch, ready in about the time a normal database takes to boot, gone the moment you delete it or its TTL expires. +## What you have + +1. **PGRun creates isolated database branches** — copy-on-write copies of the project's Safe + Copy (a privacy-safe copy of production), one per task, deleted when you are done. +2. **PGX is the default runtime** where the project allows it: a lightweight + PostgreSQL-compatible engine, so a branch is cheap and fast to start. The server decides per + branch and falls back to PostgreSQL when PGX cannot serve the project (an extension it lacks, + a large base); the branch JSON's `engine` and `engine_reason` say which and why. +3. **PgBot inspects and verifies database changes**, read-only: schema, lint findings, query + plans, and a migration review that flags table rewrites, blocking index builds, drops and + renames. +4. **PostgreSQL verification is on demand**: `pgrun bot verify` runs your migration on a + disposable *PostgreSQL* branch of the same Safe Copy, reports, and deletes it. + +**First use in a session:** run `pgrun setup --json` (idempotent). It installs or refreshes this +skill and PgBot and reports `ready`, the `capabilities` available, and any `next` steps. If +`auth` is `missing`, tell the user to run `pgrun auth login` themselves. If `pgrun` itself is not +installed (you got this skill some other way), ask the user to install it — +`curl -fsSL https://pgrun.dev/install | sh` — rather than running an installer yourself; then +`pgrun setup --json`. Both paths end in the same setup. + ## When to use this - A migration, a schema change, or anything with `ALTER`/`DROP` in it. @@ -69,8 +90,9 @@ normally — the rest of this skill applies unchanged. second call needed). The server picks the engine (PGX Beta when the project is eligible, else PostgreSQL); add `--engine postgres` when the task needs the source's exact engine, extensions or settings, or - `--engine pgx` to insist on PGX Beta (an `engine_unavailable` error - instead of a silent fallback). + `--engine pgx` to insist on PGX (an `engine_unavailable` error that + names the reason and offers PostgreSQL, never a silent switch). An + engine you name explicitly is always respected. - or reuse one you already created: `pgrun branch env `. > The URL is a TLS endpoint on a per-branch hostname and already contains > `sslmode=require`. Use it exactly as given — do not rewrite the host, the port @@ -115,6 +137,57 @@ is the command's own exit code. This is the default choice unless something about the task needs the branch to outlive one command (e.g., a migration followed by a separate manual verification step). +## Verify before you finish: PgBot + +PgBot is read-only. `pgrun bot` only ever inspects PGRun branches (it resolves them through the +API with the project's token and never accepts a connection string), so it cannot reach +production. Its optional AI layer is off: nothing is sent to a model provider. + +**When to invoke it** + +| Situation | Command | +|---|---| +| You wrote or changed a migration (any `ALTER`, `CREATE INDEX`, `DROP`, rename) | `pgrun bot verify --json -- ` before you report the task done | +| You developed against a PGX branch and the change is schema-level | add `--compare-pgx`: same migration on PGX and PostgreSQL, schemas compared | +| You need the current schema of a branch (tables, columns, indexes, constraints) | `pgrun bot schema ` (JSON, catalog only, no data) | +| A query is slow or you added a query on a large table | `pgrun bot explain "