From 588d206809c0f332f9dc43580f760b1e491efa71 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Sat, 14 Nov 2026 10:08:08 -0800 Subject: [PATCH 01/11] pgrun setup + pgrun bot: PgBot as a standard pgrun component - internal/pgbot: locate (PGRUN_PGBOT > PATH > managed copy), version/capability probe in a scrubbed env, pinned checksum-verified install (atomic, no exec before the sha256 matches). - pgrun bot status|install|inspect|lint|schema|explain|run: branch-scoped (URL from the API, env only), refuses connection strings, AI layer off unless --allow-ai. - pgrun bot verify -- : disposable PostgreSQL branch of the Safe Copy, schema snapshot + lint before/after, pgbot schema diff (rewrites, blocking index builds, drops, renames), optional --compare-pgx; always cleans up; pgrun-verify/1.0.0. - pgrun setup: idempotent skill + pgbot + auth report, --agents-md managed block only on request; pgrun-setup/1.0.0. - MCP: pgrun_bot_lint / pgrun_bot_schema / pgrun_bot_explain. - npm: @pgrun/cli depends on @pgbot/cli; the wrapper hands its binary over via PGRUN_PGBOT. - Skill: PGX default, PgBot when/how, reading the verify report. Co-Authored-By: Claude Opus 5.5 --- README.md | 22 +- internal/cli/bot.go | 339 ++++++++++++++++ internal/cli/bot_integration_test.go | 131 +++++++ internal/cli/bot_test.go | 366 ++++++++++++++++++ internal/cli/bot_verify.go | 552 +++++++++++++++++++++++++++ internal/cli/cli.go | 10 + internal/cli/setup.go | 283 ++++++++++++++ internal/mcpserver/bot_tools.go | 109 ++++++ internal/mcpserver/server.go | 3 +- internal/mcpserver/server_test.go | 7 +- internal/pgbot/install.go | 215 +++++++++++ internal/pgbot/pgbot.go | 258 +++++++++++++ internal/pgbot/pgbot_test.go | 182 +++++++++ npm/pgrun/bin/pgrun.js | 35 +- npm/pgrun/package.json | 5 +- skills/agents-block.md | 21 + skills/embed.go | 7 + skills/pgrun-branching/SKILL.md | 73 +++- 18 files changed, 2605 insertions(+), 13 deletions(-) create mode 100644 internal/cli/bot.go create mode 100644 internal/cli/bot_integration_test.go create mode 100644 internal/cli/bot_test.go create mode 100644 internal/cli/bot_verify.go create mode 100644 internal/cli/setup.go create mode 100644 internal/mcpserver/bot_tools.go create mode 100644 internal/pgbot/install.go create mode 100644 internal/pgbot/pgbot.go create mode 100644 internal/pgbot/pgbot_test.go create mode 100644 skills/agents-block.md diff --git a/README.md b/README.md index aa1c290..9f9bf29 100644 --- a/README.md +++ b/README.md @@ -17,10 +17,30 @@ 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. + 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/internal/cli/bot.go b/internal/cli/bot.go new file mode 100644 index 0000000..468aba2 --- /dev/null +++ b/internal/cli/bot.go @@ -0,0 +1,339 @@ +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"} + 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..49632d9 --- /dev/null +++ b/internal/cli/bot_test.go @@ -0,0 +1,366 @@ +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 0.10.0"; exit 0;; + "schema snapshot") + 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 + `" = "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") echo '{"kind":"pgbot-schema-compare","identical":true,"differences":[]}'; exit 0;; + "lint "*) + 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) + } + if rep.Kind != VerifyKind || rep.Verdict != "pass" { + 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")...) + _, 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 still passed; only the PGX side is reported. + if rep.Verdict != "pass" || len(fb.deleted) != 1 { + t.Fatalf("verdict %q deleted %v", rep.Verdict, fb.deleted) + } +} + +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 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) + } + } +} diff --git a/internal/cli/bot_verify.go b/internal/cli/bot_verify.go new file mode 100644 index 0000000..8595b26 --- /dev/null +++ b/internal/cli/bot_verify.go @@ -0,0 +1,552 @@ +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.0.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"` // pass | dangerous | fail | error + Reasons []string `json:"reasons"` + FailOn string `json:"fail_on"` + 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"` +} + +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", "exit 1 when the schema review has a finding at/above: critical|warning|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") + } + 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, *failOn) + // 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) + } + switch rep.Verdict { + case "pass": + return exitSuccess + default: + return exitFailure + } +} + +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, failOn string) (rep verifyReport) { + began := time.Now() + rep = verifyReport{Kind: VerifyKind, Version: VerifyVersion, Project: v.project, FailOn: failOn, + Pgbot: v.bin.Version, Reasons: []string{}, NewLintFindings: []lintFinding{}, Cleanup: []verifyCleanup{}} + defer func() { + rep.Cleanup = v.cleanup() + rep.DurationMs = time.Since(began).Milliseconds() + }() + work, err := os.MkdirTemp("", "pgrun-verify-*") + if err != nil { + rep.Verdict, rep.Reasons = "error", []string{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.Verdict = "error" + rep.Reasons = append(rep.Reasons, "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 a newer pgbot)", v.bin.Version) + } + lintBefore, lintErr := v.lint(pgURL) + + code := v.migrate(pgRun, pgURL) + if code != 0 { + rep.Verdict = "fail" + rep.Reasons = append(rep.Reasons, 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) + if sev := reviewSeverity(out); atOrAbove(sev, failOn) { + rep.Reasons = append(rep.Reasons, "schema review: "+summaryLine(out)) + if rep.Verdict == "" { + rep.Verdict = "dangerous" + } + } + } + } + } + if lintErr == nil { + if lintAfter, err := v.lint(pgURL); err == nil { + rep.NewLintFindings = newFindings(lintBefore, lintAfter) + } + } + + if pgxRun != nil { + v.verifyPGX(&rep, pgxRun, pgxURL, after, canReview && rep.SchemaReviewSkipped == "", work) + } + if rep.Verdict == "" { + rep.Verdict = "pass" + } + return rep +} + +func engineTag(engine string) string { + if engine == "pgx" { + return "pgx" + } + return "pg" +} + +func (v *verifier) create(run *verifyEngineRun) (api.Branch, []byte) { + raw, b, err := v.client.CreateBranch(context.Background(), v.project, api.CreateBranchRequest{ + Name: run.Branch, TTL: v.ttl, ParentBranchID: v.from, Engine: run.RequestedEngine}) + 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(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 +} + +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 + reason := "pgx branch unavailable: " + run.Error + rep.Reasons = append(rep.Reasons, reason) + return + } + code := v.migrate(run, url) + pgCode := 0 + if rep.Postgres.ExitCode != nil { + pgCode = *rep.Postgres.ExitCode + } + compatible := code == pgCode + if !compatible { + rep.Reasons = append(rep.Reasons, fmt.Sprintf("the migration exited %d on PGX but %d on PostgreSQL", code, pgCode)) + } + if comparable { + pgxAfter := filepath.Join(work, "pgx-after.json") + if err := v.pgbotToFile(url, pgxAfter, "schema", "snapshot"); err != nil { + rep.Reasons = append(rep.Reasons, "pgx schema snapshot failed: "+err.Error()) + compatible = false + } else if out, _, err := pgbot.Output(context.Background(), v.bin, "", "schema", "compare", pgxAfter, pgAfter, + "--format", "json", "--a-label", "pgx", "--b-label", "postgres"); err == nil { + rep.PGXComparison = json.RawMessage(out) + var cmp struct { + Identical bool `json:"identical"` + Differences []json.RawMessage `json:"differences"` + } + if json.Unmarshal(out, &cmp) == nil && !cmp.Identical { + compatible = false + rep.Reasons = append(rep.Reasons, 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) { + fmt.Fprintf(w, "verify %s: %s\n", rep.Project, strings.ToUpper(rep.Verdict)) + 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..952a706 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..91b4488 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,24 @@ 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. + ## When to use this - A migration, a schema change, or anything with `ALTER`/`DROP` in it. @@ -69,8 +87,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 +134,48 @@ 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 "" [--json] - pgrun bot verify [] [--compare-pgx] [--fail-on critical|warning|none] [--json] -- + pgrun bot verify [] [--compare-pgx] [--fail-on critical|warning|none] [--block-on ] [--json] -- pgrun skill install [--project | --dir ] (install the pgrun-branching skill for Claude Code; default ~/.claude/skills) pgrun skill status [--project | --dir ] pgrun skill show diff --git a/internal/pgbot/pgbot.go b/internal/pgbot/pgbot.go index cb818e1..f3a5f78 100644 --- a/internal/pgbot/pgbot.go +++ b/internal/pgbot/pgbot.go @@ -36,6 +36,11 @@ const MinVersion = "0.9.0" // this pgrun was tested against. const PinnedVersion = "0.9.0" +// SchemaMinVersion is the first pgbot release with `schema snapshot|diff|compare` +// (the migration review `pgrun bot verify` needs). Until PinnedVersion reaches it, +// verify reports `incomplete` — never `pass` — on a pgbot without it. +const SchemaMinVersion = "0.10.0" + // Capabilities are probed, not inferred from the version, so a dev build or a // newer release is judged by what it actually has. type Capabilities struct { diff --git a/skills/pgrun-branching/SKILL.md b/skills/pgrun-branching/SKILL.md index 7b2ea4b..3368bba 100644 --- a/skills/pgrun-branching/SKILL.md +++ b/skills/pgrun-branching/SKILL.md @@ -159,9 +159,14 @@ Run it once per migration change, and again only if you change the migration. **Reading `pgrun bot verify --json`** (`kind: pgrun-verify`): -- `verdict`: `pass` · `dangerous` (a schema-review finding at/above `--fail-on`, default - `critical`) · `fail` (the migration exited non-zero on PostgreSQL) · `error` (no branch). - Exit code 0 only for `pass`. +- `verdict` (the highest of `categories`): `fail` (the migration exited non-zero on + PostgreSQL) · `dangerous` (a schema-review finding at/above `--fail-on`, default `critical`) · + `unsupported` (`--compare-pgx`: PGX could not run it or produced a different schema) · + `incomplete` (the review or lint could not run — this is NOT a pass) · `error` (no branch, + API or tool failure) · `warning` (informational findings) · `pass`. +- `blocking`: whether a category is in `policy.block_on` (default `fail,dangerous,incomplete,error`; + change it with `--block-on`). Exit 0 = not blocking, 1 = blocking, 3 = only infrastructure + errors block. - `schema_review.findings[]`: `id`, `severity`, `object`, `detail`, `advice`. Act on `critical`/`warning`: `table_rewritten`, `index_created_on_existing_table`, `constraint_validated_on_existing_table`, `not_null_added` are lock hazards on large tables; @@ -176,8 +181,9 @@ Report the verdict and the non-info findings to the user in plain words; fix wha example `algorithm: :concurrently`, `NOT VALID` + `VALIDATE CONSTRAINT`) and verify again. If `pgrun bot status` says pgbot is not installed, run `pgrun bot install` (or `pgrun setup`). -If it says the `schema` review is unavailable, `verify` still runs the migration on PostgreSQL -and lints; say that the rewrite/lock review was skipped. +If it says the `schema` review is unavailable (pgbot older than 0.10.0), `verify` still runs the +migration on PostgreSQL and lints, and reports `incomplete`: tell the user the rewrite/lock review +did not run — never present that as verified. ## Framework detection (examples, not the whole story) From 005e7907310745832401bcb06858defb4b7f0326 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Sat, 14 Nov 2026 14:52:11 -0800 Subject: [PATCH 06/11] bot verify: work with a project CI token (ci- names) and keep the API token out of the migration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A CI token may only create ci-… branches (422 token_scope): verify retries once as ci-verify-…. The migration child no longer inherits PGRUN_API_TOKEN or an outer DATABASE_URL. Both found by the ci-action integration. Co-Authored-By: Claude Opus 5.5 --- internal/cli/bot_test.go | 55 ++++++++++++++++++++++++++++++++++++++ internal/cli/bot_verify.go | 31 ++++++++++++++++++--- 2 files changed, 83 insertions(+), 3 deletions(-) diff --git a/internal/cli/bot_test.go b/internal/cli/bot_test.go index 0e82f57..1d3d466 100644 --- a/internal/cli/bot_test.go +++ b/internal/cli/bot_test.go @@ -544,3 +544,58 @@ func TestSetup_WithoutAgentsMDFlagNeverWritesInstructions(t *testing.T) { } } } + +// 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 index dd1ab97..10b9aea 100644 --- a/internal/cli/bot_verify.go +++ b/internal/cli/bot_verify.go @@ -430,8 +430,15 @@ func engineTag(engine string) string { } func (v *verifier) create(run *verifyEngineRun) (api.Branch, []byte) { - raw, b, err := v.client.CreateBranch(context.Background(), v.project, api.CreateBranchRequest{ - Name: run.Branch, TTL: v.ttl, ParentBranchID: v.from, Engine: run.RequestedEngine}) + 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"`) { @@ -491,7 +498,7 @@ func (v *verifier) migrate(run *verifyEngineRun, url string) int { began := time.Now() cmd := exec.Command(v.command[0], v.command[1:]...) cmd.Stdout, cmd.Stderr = v.out(), v.out() - cmd.Env = append(os.Environ(), "DATABASE_URL="+url) + cmd.Env = append(migrationEnv(os.Environ()), "DATABASE_URL="+url) err := cmd.Run() run.MigrateMs = time.Since(began).Milliseconds() code := 0 @@ -508,6 +515,24 @@ func (v *verifier) migrate(run *verifyEngineRun, url string) int { 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 { From 8088596fb5e9e23ba3b9edf764b0238516314774 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Sat, 14 Nov 2026 15:33:40 -0800 Subject: [PATCH 07/11] skill: findings pgrun bot inspect marks suppressed are deliberate on branches Found by the real-API e2e: pgbot keeps suppressed findings in its JSON (suppressed: true). Co-Authored-By: Claude Opus 5.5 --- skills/pgrun-branching/SKILL.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/skills/pgrun-branching/SKILL.md b/skills/pgrun-branching/SKILL.md index 3368bba..346e59b 100644 --- a/skills/pgrun-branching/SKILL.md +++ b/skills/pgrun-branching/SKILL.md @@ -154,6 +154,9 @@ production. Its optional AI layer is off: nothing is sent to a model provider. | Schema health after a change (missing FK indexes, invalid/duplicate indexes) | `pgrun bot lint --json` | | A database error you don't understand, or "is this database healthy?" | `pgrun bot inspect --json` | +In `pgrun bot inspect` output, skip findings marked `"suppressed": true` (`fsync_off`, +`full_page_writes_off`, `checkpoints_forced`): disposable branches run that way on purpose. + Don't run `verify` after every small query or test edit — it provisions a PostgreSQL branch. Run it once per migration change, and again only if you change the migration. From 96cb5dab6c1a953ef711dcd0a5c06184960d434b Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Sun, 15 Nov 2026 09:23:37 -0800 Subject: [PATCH 08/11] =?UTF-8?q?Build=20with=20go1.27.4=20(GO-2026-6859,?= =?UTF-8?q?=20net/http)=20=E2=80=94=20govulncheck=20clean?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- go.mod | 2 ++ 1 file changed, 2 insertions(+) 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 From d5b4ba9950ec74b0b41db286aea2b7d3c7ef95a1 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Sat, 14 Nov 2026 14:29:41 -0800 Subject: [PATCH 09/11] =?UTF-8?q?Pin=20pgbot=200.10.0=20(schema=20review)?= =?UTF-8?q?=20=E2=80=94=20DO=20NOT=20merge=20or=20release=20before=20pgbot?= =?UTF-8?q?=20v0.10.0=20is=20published?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MinVersion stays 0.9.0: an older pgbot still works and verify reports incomplete. Co-Authored-By: Claude Opus 5.5 --- internal/pgbot/pgbot.go | 2 +- npm/pgrun/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/pgbot/pgbot.go b/internal/pgbot/pgbot.go index f3a5f78..861ef34 100644 --- a/internal/pgbot/pgbot.go +++ b/internal/pgbot/pgbot.go @@ -34,7 +34,7 @@ const MinVersion = "0.9.0" // PinnedVersion is what `pgrun bot install` downloads by default: the release // this pgrun was tested against. -const PinnedVersion = "0.9.0" +const PinnedVersion = "0.10.0" // SchemaMinVersion is the first pgbot release with `schema snapshot|diff|compare` // (the migration review `pgrun bot verify` needs). Until PinnedVersion reaches it, diff --git a/npm/pgrun/package.json b/npm/pgrun/package.json index 9b73d9c..0ace891 100644 --- a/npm/pgrun/package.json +++ b/npm/pgrun/package.json @@ -25,7 +25,7 @@ "README.md" ], "dependencies": { - "@pgbot/cli": "^0.9.0" + "@pgbot/cli": "^0.10.0" }, "optionalDependencies": { "@pgrun/linux-x64": "0.0.0-dev", From 1d5b36e45eb2901111f92ca64e08633d6d6a8e6d Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Sun, 15 Nov 2026 18:25:24 -0800 Subject: [PATCH 10/11] =?UTF-8?q?ci:=20minimal=20GitHub=20Actions=20?= =?UTF-8?q?=E2=80=94=20vet/gofmt/race=20tests,=206-platform=20build,=20gol?= =?UTF-8?q?angci-lint,=20govulncheck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pgrun-cli had no CI. Pinned action SHAs and tool versions (as pgbot). .golangci.yml keeps the default linters and lists the accepted CLI patterns (terminal writes, best-effort cleanup; test fixture writes) instead of changing code; 0 issues on this branch. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 65 ++++++++++++++++++++++++++++++++++++++++ .golangci.yml | 28 +++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .golangci.yml 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" From 82a178ffcbdae836479e780bdd8cef05392dad8b Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Sun, 15 Nov 2026 18:25:24 -0800 Subject: [PATCH 11/11] =?UTF-8?q?ci:=20minimal=20GitHub=20Actions=20?= =?UTF-8?q?=E2=80=94=20vet/gofmt/race=20tests,=206-platform=20build,=20gol?= =?UTF-8?q?angci-lint,=20govulncheck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit pgrun-cli had no CI. Pinned action SHAs and tool versions (as pgbot). .golangci.yml keeps the default linters and lists the accepted CLI patterns (terminal writes, best-effort cleanup; test fixture writes) instead of changing code; 0 issues on this branch. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 65 ++++++++++++++++++++++++++++++++++++++++ .golangci.yml | 28 +++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 .github/workflows/ci.yml create mode 100644 .golangci.yml 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"