From 7f830746126317a09d062b29362568417c2c3770 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Mon, 23 Nov 2026 14:02:18 -0800 Subject: [PATCH 1/5] fix(plan): ignore $N inside dollar-quoted literals in HasPlaceholders (#141) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HasPlaceholders only tracked single-quote state, so a "$1" inside a dollar-quoted string constant ($$ … $$ or $tag$ … $tag$) was reported as a parameter placeholder and `sql explain` printed the generic-plan "parameter values unknown" caveat for a query that has no parameters. The scanner now recognises a dollar-quote opening delimiter and skips to its matching close (or to the end of the query when unterminated). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +++++ internal/plan/plan.go | 28 +++++++++++++++++++++++++++- internal/plan/plan_test.go | 3 +++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 428a0d7..25dce1e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,11 @@ separately by `model.SchemaVersion` (currently 1.5.0). Other platforms get "PgBot Monitor currently supports macOS only"; every other command is unchanged. The `--json` contract is unchanged. +### Fixed +- `pgbot sql explain` no longer treats a `$1` inside a dollar-quoted literal + (`$$ … $$`, `$tag$ … $tag$`) as a parameter placeholder, so the generic-plan + "parameter values unknown" caveat is no longer shown for such queries (#141). + ## [0.10.0] - 2026-11-16 ### Added diff --git a/internal/plan/plan.go b/internal/plan/plan.go index 6e79c53..bdbcb2b 100644 --- a/internal/plan/plan.go +++ b/internal/plan/plan.go @@ -223,7 +223,8 @@ func firstNonEmpty(vals ...string) string { // HasPlaceholders reports whether the query uses $N parameter placeholders // outside string literals — the case where a GENERIC_PLAN's "parameter values -// unknown" caveat applies. +// unknown" caveat applies. Both '…' and dollar-quoted ($$…$$, $tag$…$tag$) +// literals are skipped. func HasPlaceholders(q string) bool { inLiteral := false for i := 0; i < len(q); i++ { @@ -238,6 +239,31 @@ func HasPlaceholders(q string) bool { if i+1 < len(q) && q[i+1] >= '0' && q[i+1] <= '9' { return true } + if tag := dollarQuoteTag(q[i:]); tag != "" { + end := strings.Index(q[i+len(tag):], tag) + if end < 0 { + return false // unterminated: the rest is the literal's body + } + i += len(tag) + end + len(tag) - 1 + } } return false } + +// dollarQuoteTag returns the opening delimiter of a dollar-quoted literal at the +// start of s — "$$" or "$tag$", where tag is an identifier that does not start +// with a digit — or "" when s does not start one. +func dollarQuoteTag(s string) string { + for j := 1; j < len(s); j++ { + c := s[j] + switch { + case c == '$': + return s[:j+1] + case c == '_' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= 0x80: + case c >= '0' && c <= '9' && j > 1: + default: + return "" + } + } + return "" +} diff --git a/internal/plan/plan_test.go b/internal/plan/plan_test.go index 8ea8425..a10be17 100644 --- a/internal/plan/plan_test.go +++ b/internal/plan/plan_test.go @@ -284,6 +284,9 @@ func TestPrepare_refusesAnythingButOneSelect(t *testing.T) { func TestHasPlaceholders(t *testing.T) { yes := []string{"SELECT * FROM t WHERE id = $1", "select $2, $10 from t", "SELECT * FROM t WHERE a=$1AND b=2"} no := []string{"SELECT 1", "SELECT '$1' FROM t", "SELECT '$' || 'x'", "SELECT * FROM t WHERE price > 5$"} + // Dollar-quoted literals are string constants too (#141): a $1 inside one is text. + yes = append(yes, "SELECT $$ $1 $$, $2", "SELECT $tag$ x $tag$ WHERE id = $1") + no = append(no, "SELECT $$ $1 $$", "SELECT $tag$ $1 $$ $2 $tag$ FROM t", "SELECT $q$ it's $1 $q$", "SELECT $$ unterminated $1") for _, q := range yes { if !HasPlaceholders(q) { t.Errorf("HasPlaceholders(%q) = false", q) From f3d933db4a6ec5f62df5312e4e6651a12c2d3223 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Mon, 23 Nov 2026 14:02:49 -0800 Subject: [PATCH 2/5] fix(sql): refuse --json together with --ai in sql explain (#139) The --json branch of runSQLExplain printed the raw plan and returned before the `if llm != nil` block, so --json --ai resolved the model, asked for consent to send the SQL, then silently dropped the AI explanation. Appending prose to --json output would break parsers, so the combination is now rejected up front as a usage error (exit 64), before a model is resolved, consent is requested, or a connection made. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ README.md | 3 ++- cmd/pgbot/sql.go | 7 ++++++- cmd/pgbot/sql_test.go | 13 +++++++++++++ 4 files changed, 24 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 25dce1e..82a958e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,9 @@ separately by `model.SchemaVersion` (currently 1.5.0). - `pgbot sql explain` no longer treats a `$1` inside a dollar-quoted literal (`$$ … $$`, `$tag$ … $tag$`) as a parameter placeholder, so the generic-plan "parameter values unknown" caveat is no longer shown for such queries (#141). +- `pgbot sql explain --json --ai` is now refused as a usage error (exit 64) + instead of printing the raw plan and silently dropping the requested AI + explanation — after already asking consent to send the SQL (#139). ## [0.10.0] - 2026-11-16 diff --git a/README.md b/README.md index 0a72416..e270ed4 100644 --- a/README.md +++ b/README.md @@ -756,7 +756,8 @@ are case-insensitive). placeholders need no values; older servers plan queries with literal values. - Only a **single plain SELECT** is accepted — no writes, no `WITH`, no multiple statements (exit 64 otherwise). pgbot never uses the executing form of EXPLAIN. -- `--json` prints the raw `EXPLAIN (FORMAT JSON)` output. +- `--json` prints the raw `EXPLAIN (FORMAT JSON)` output; it cannot be combined + with `--ai` (exit 64). - `--ai` appends a model's prose reading of the same rendered plan, behind the disclosure prompt below. Unlike the findings, **your SQL text can carry literal values**, so the prompt names exactly what is sent: the query and its plan. diff --git a/cmd/pgbot/sql.go b/cmd/pgbot/sql.go index 06bfa98..d5e84ea 100644 --- a/cmd/pgbot/sql.go +++ b/cmd/pgbot/sql.go @@ -66,7 +66,7 @@ func newSQLExplainCmd() *cobra.Command { }, } fl := cmd.Flags() - fl.BoolVar(&f.jsonOut, "json", false, "print the raw EXPLAIN (FORMAT JSON) output instead of the reading") + fl.BoolVar(&f.jsonOut, "json", false, "print the raw EXPLAIN (FORMAT JSON) output instead of the reading (not with --ai)") fl.BoolVar(&f.useAI, "ai", false, "append a model's plain-language explanation (needs an AI key in the environment)") fl.BoolVar(&f.yes, "yes", false, "skip the data-disclosure confirmation prompt (--ai)") fl.BoolVar(&f.noColor, "no-color", false, "disable ANSI color") @@ -128,6 +128,11 @@ func looksLikeConnString(s string) bool { } func runSQLExplain(cmd *cobra.Command, args []string, f sqlExplainFlags) error { + // --json is the raw, machine-readable plan; prose appended to it would break + // every parser. Refuse the pair up front rather than silently dropping --ai. + if f.jsonOut && f.useAI { + return usageErrf("--json and --ai cannot be combined — --json prints only the raw EXPLAIN output") + } connString, query, err := resolveSQLExplainInput(args, os.Stdin, isInteractive()) if err != nil { return err diff --git a/cmd/pgbot/sql_test.go b/cmd/pgbot/sql_test.go index 893af43..918fdbd 100644 --- a/cmd/pgbot/sql_test.go +++ b/cmd/pgbot/sql_test.go @@ -1,10 +1,23 @@ package main import ( + "errors" "strings" "testing" ) +// --json prints machine-readable EXPLAIN output, so it cannot also carry the +// --ai prose; the combination is refused as a usage error before a model is +// resolved, consent is asked, or a connection is made (#139). +func TestSQLExplainRejectsJSONWithAI(t *testing.T) { + t.Setenv("DATABASE_URL", "postgres://u@127.0.0.1:1/none") + err := runSQLExplain(nil, []string{"SELECT 1"}, sqlExplainFlags{jsonOut: true, useAI: true}) + var ue usageError + if !errors.As(err, &ue) || !strings.Contains(err.Error(), "--json") || !strings.Contains(err.Error(), "--ai") { + t.Fatalf("--json --ai: want a usage error naming both flags, got %v", err) + } +} + func TestResolveSQLExplainInput(t *testing.T) { t.Setenv("DATABASE_URL", "") t.Setenv("PGBOT_DATABASE_URL", "") From 4c5baa7153e9ebfa7e6f664665f0e32e4b610a1c Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Mon, 23 Nov 2026 14:03:26 -0800 Subject: [PATCH 3/5] fix(sql): word the sql explain AI section around the plan, not findings (#140) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit printAISection was written for `pgbot explain`/`ask` and hard-coded "The findings above are complete/authoritative…". `sql explain --ai` reused it, so a command that computes no findings told the reader the findings were complete — including on model error, when only a plan had been printed. printAISection now takes what the section explains (findings or a query plan) and words the fallback note and footer accordingly; the findings commands keep their existing text. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ cmd/pgbot/explain.go | 23 +++++++++++++++---- cmd/pgbot/explain_test.go | 48 +++++++++++++++++++++++++++++++++++++++ cmd/pgbot/sql.go | 2 +- 4 files changed, 71 insertions(+), 5 deletions(-) create mode 100644 cmd/pgbot/explain_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 82a958e..0c295e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,9 @@ separately by `model.SchemaVersion` (currently 1.5.0). - `pgbot sql explain --json --ai` is now refused as a usage error (exit 64) instead of printing the raw plan and silently dropping the requested AI explanation — after already asking consent to send the SQL (#139). +- `pgbot sql explain --ai` no longer labels the query plan as "the findings + above" in the AI section's footer and fallback note; it now refers to the + query plan that was actually printed (#140). ## [0.10.0] - 2026-11-16 diff --git a/cmd/pgbot/explain.go b/cmd/pgbot/explain.go index 3a18ebd..9e08be8 100644 --- a/cmd/pgbot/explain.go +++ b/cmd/pgbot/explain.go @@ -122,7 +122,7 @@ func runExplain(cmd *cobra.Command, args []string, f inspectFlags, yes bool) err aiCtx, aiCancel := context.WithTimeout(cmd.Context(), 3*time.Minute) defer aiCancel() explanation, aiErr := ai.Explain(aiCtx, llm, c) - printAISection(color, llm.Model(), explanation, aiErr) + printAISection(color, llm.Model(), explanation, aiErr, aiOnFindings) // The destructive-action guards, reasserted by code AFTER the model text — so a // reworded or truncated explanation can never be the thing that drops them. if aiErr == nil { @@ -167,9 +167,24 @@ func confirmDisclosureOf(cmdName, payload string, llm ai.LanguageModel, yes bool return r == "y" || r == "yes" } +// aiSubject is what the AI section explains — it decides how the footer names +// the deterministic output printed above it. +type aiSubject int + +const ( + aiOnFindings aiSubject = iota // explain / ask: pgbot's computed findings + aiOnPlan // sql explain: PostgreSQL's query plan +) + // printAISection renders the labeled AI block. The banner makes it unmistakable // that this text is model-generated and must be verified before acting. -func printAISection(color bool, modelName, text string, aiErr error) { +func printAISection(color bool, modelName, text string, aiErr error, subject aiSubject) { + unavailable := "The findings above are complete and were computed without the model." + authoritative := "The findings above are authoritative and computed deterministically; the text" + if subject == aiOnPlan { + unavailable = "The query plan above is complete and was read without the model." + authoritative = "The query plan above is PostgreSQL's own (estimated) plan; the text" + } st := render.NewStyler(color) rule := strings.Repeat("─", 64) fmt.Println() @@ -179,11 +194,11 @@ func printAISection(color bool, modelName, text string, aiErr error) { fmt.Println() if aiErr != nil { fmt.Println(st.Dim(" (explanation unavailable: " + aiErr.Error() + ")")) - fmt.Println(st.Dim(" The findings above are complete and were computed without the model.")) + fmt.Println(st.Dim(" " + unavailable)) return } fmt.Println(text) fmt.Println() - fmt.Println(st.Dim("The findings above are authoritative and computed deterministically; the text")) + fmt.Println(st.Dim(authoritative)) fmt.Println(st.Dim("in this section is a model's interpretation and may be wrong.")) } diff --git a/cmd/pgbot/explain_test.go b/cmd/pgbot/explain_test.go new file mode 100644 index 0000000..1589626 --- /dev/null +++ b/cmd/pgbot/explain_test.go @@ -0,0 +1,48 @@ +package main + +import ( + "errors" + "io" + "os" + "strings" + "testing" +) + +// captureStdout returns what fn printed to os.Stdout. +func captureStdout(t *testing.T, fn func()) string { + t.Helper() + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + orig := os.Stdout + os.Stdout = w + defer func() { os.Stdout = orig }() + done := make(chan string) + go func() { + b, _ := io.ReadAll(r) + done <- string(b) + }() + fn() + _ = w.Close() + return <-done +} + +// `sql explain --ai` renders a query plan, not findings, so its AI section must +// not tell the reader that "the findings above" are complete or authoritative +// (#140). The findings commands keep their wording. +func TestPrintAISectionWording(t *testing.T) { + for _, aiErr := range []error{nil, errors.New("boom")} { + plan := captureStdout(t, func() { printAISection(false, "m", "prose", aiErr, aiOnPlan) }) + if strings.Contains(plan, "findings") { + t.Errorf("plan AI section (err=%v) mentions findings:\n%s", aiErr, plan) + } + if !strings.Contains(plan, "query plan above") { + t.Errorf("plan AI section (err=%v) should refer to the query plan:\n%s", aiErr, plan) + } + findings := captureStdout(t, func() { printAISection(false, "m", "prose", aiErr, aiOnFindings) }) + if !strings.Contains(findings, "The findings above are") { + t.Errorf("findings AI section (err=%v) lost its wording:\n%s", aiErr, findings) + } + } +} diff --git a/cmd/pgbot/sql.go b/cmd/pgbot/sql.go index d5e84ea..aeb7d50 100644 --- a/cmd/pgbot/sql.go +++ b/cmd/pgbot/sql.go @@ -201,7 +201,7 @@ func runSQLExplain(cmd *cobra.Command, args []string, f sqlExplainFlags) error { aiCtx, aiCancel := context.WithTimeout(cmd.Context(), 3*time.Minute) defer aiCancel() text, aiErr := ai.ExplainPlan(aiCtx, llm, query, plain.String()) - printAISection(color, llm.Model(), text, aiErr) + printAISection(color, llm.Model(), text, aiErr, aiOnPlan) } return nil } From 68983249849233c1720bb0e250df353014aac7b1 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Mon, 23 Nov 2026 14:04:10 -0800 Subject: [PATCH 4/5] fix(ai): do not treat a non-TTY stdin as consent to send data (#143) confirmDisclosureOf returned true for `yes || !isInteractive()`, so in CI, pipes, containers and agent shells the disclosure line was printed and the payload sent without any confirmation or --yes. For `sql explain --ai` that payload is the user's SQL text, which can carry literal values; `explain` and `ask` share the same gate. Only --yes now short-circuits the prompt for a remote endpoint. With no terminal to answer it, the command refuses before connecting and tells the user to re-run with --yes. Local endpoints keep auto-consent since nothing leaves the machine. isInteractive becomes a variable so the regression test can pin it; the piped `sql explain --ai` help example now shows --yes. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++++++ README.md | 5 +++-- cmd/pgbot/explain.go | 9 ++++++++- cmd/pgbot/explain_test.go | 36 ++++++++++++++++++++++++++++++++++++ cmd/pgbot/helpers.go | 4 ++-- cmd/pgbot/sql.go | 2 +- 6 files changed, 56 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c295e4..a6eb6da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,12 @@ separately by `model.SchemaVersion` (currently 1.5.0). - `pgbot sql explain --ai` no longer labels the query plan as "the findings above" in the AI section's footer and fallback note; it now refers to the query plan that was actually printed (#140). +- **AI consent now defaults to NO when stdin is not a terminal.** `pgbot sql + explain --ai`, `pgbot explain` and `pgbot ask` treated a non-TTY stdin (CI, + pipes, containers, agent shells) as consent and sent data — for `sql explain`, + your SQL text including literals — to a remote provider without asking. They + now refuse with a message to re-run with `--yes`; local endpoints still need + no confirmation (#143). ## [0.10.0] - 2026-11-16 diff --git a/README.md b/README.md index e270ed4..34e4b00 100644 --- a/README.md +++ b/README.md @@ -774,8 +774,9 @@ or the key is unset, the deterministic report still stands. With a remote model, this sends the same PII-free Context shown by `inspect --json`. Before sending it, pgbot identifies the provider, host, and -model and asks for confirmation. Local endpoints are identified as local and do -not require confirmation. +model and asks for confirmation. When stdin is not a terminal (CI, a pipe, a +container) there is no one to ask, so pgbot refuses to send unless `--yes` is +given. Local endpoints are identified as local and do not require confirmation. | Provider | Key | Default model | API | |---|---|---|---| diff --git a/cmd/pgbot/explain.go b/cmd/pgbot/explain.go index 9e08be8..a8fc2fd 100644 --- a/cmd/pgbot/explain.go +++ b/cmd/pgbot/explain.go @@ -157,9 +157,16 @@ func confirmDisclosureOf(cmdName, payload string, llm ai.LanguageModel, yes bool fmt.Fprintf(os.Stderr, "%s: WARNING — %s is plain http, so the key and the payload travel unencrypted.\n", cmdName, ai.Host(llm.Endpoint())) } - if yes || !isInteractive() { + if yes { return true } + if !isInteractive() { + // No one can answer the prompt (CI, a pipe, an agent's shell). Silence is + // not consent: only --yes sends data off the machine unattended. + fmt.Fprintf(os.Stderr, "%s: stdin is not a terminal, so consent cannot be asked — re-run with --yes to send %s to %s.\n", + cmdName, payload, ai.Host(llm.Endpoint())) + return false + } fmt.Fprint(os.Stderr, "Continue? [y/N] ") var resp string fmt.Fscanln(os.Stdin, &resp) diff --git a/cmd/pgbot/explain_test.go b/cmd/pgbot/explain_test.go index 1589626..a515704 100644 --- a/cmd/pgbot/explain_test.go +++ b/cmd/pgbot/explain_test.go @@ -1,11 +1,14 @@ package main import ( + "context" "errors" "io" "os" "strings" "testing" + + "github.com/pgrundev/pgbot/internal/ai" ) // captureStdout returns what fn printed to os.Stdout. @@ -28,6 +31,39 @@ func captureStdout(t *testing.T, fn func()) string { return <-done } +// stubModel is an ai.LanguageModel that only answers the consent questions. +type stubModel struct{ endpoint string } + +func (stubModel) Generate(context.Context, ai.Call) (*ai.Response, error) { + return nil, errors.New("stubModel.Generate must not be called") +} +func (stubModel) Provider() string { return "openai" } +func (stubModel) Model() string { return "stub" } +func (m stubModel) Endpoint() string { return m.endpoint } + +// With no terminal to answer the prompt, consent to send data to a remote +// provider must default to NO unless --yes was given (#143). Local endpoints +// keep auto-consent: nothing leaves the machine. +func TestConfirmDisclosureNonInteractive(t *testing.T) { + orig := isInteractive + isInteractive = func() bool { return false } + defer func() { isInteractive = orig }() + + remote := stubModel{endpoint: "https://api.openai.com/v1"} + if confirmDisclosureOf("pgbot sql explain", "your SQL text and its query plan", remote, false) { + t.Error("non-interactive without --yes must not consent to a remote send") + } + if confirmDisclosure("pgbot explain", remote, false) { + t.Error("explain: non-interactive without --yes must not consent to a remote send") + } + if !confirmDisclosureOf("pgbot sql explain", "your SQL text and its query plan", remote, true) { + t.Error("--yes must consent") + } + if !confirmDisclosureOf("pgbot sql explain", "your SQL text and its query plan", stubModel{endpoint: "http://127.0.0.1:11434/v1"}, false) { + t.Error("a local endpoint needs no consent") + } +} + // `sql explain --ai` renders a query plan, not findings, so its AI section must // not tell the reader that "the findings above" are complete or authoritative // (#140). The findings commands keep their wording. diff --git a/cmd/pgbot/helpers.go b/cmd/pgbot/helpers.go index ffdcb72..e133236 100644 --- a/cmd/pgbot/helpers.go +++ b/cmd/pgbot/helpers.go @@ -38,8 +38,8 @@ func pgServiceFallback() string { } // isInteractive reports whether stdin is a terminal — used to decide whether to -// prompt for confirmation (skip the prompt when piped/scripted). -func isInteractive() bool { +// prompt for confirmation. A variable so tests can pin it. +var isInteractive = func() bool { return term.IsTerminal(int(os.Stdin.Fd())) } diff --git a/cmd/pgbot/sql.go b/cmd/pgbot/sql.go index aeb7d50..1c790c8 100644 --- a/cmd/pgbot/sql.go +++ b/cmd/pgbot/sql.go @@ -59,7 +59,7 @@ func newSQLExplainCmd() *cobra.Command { "names exactly what is sent: the query and its plan.", Example: " pgbot sql explain \"SELECT * FROM orders WHERE customer_id = $1\"\n" + " pgbot sql explain \"$DATABASE_URL\" \"SELECT count(*) FROM events WHERE kind = 'click'\"\n" + - " cat slow.sql | pgbot sql explain --ai", + " cat slow.sql | pgbot sql explain --ai --yes # piped: no prompt possible, so --yes is required", Args: cobra.MaximumNArgs(2), RunE: func(cmd *cobra.Command, args []string) error { return runSQLExplain(cmd, args, f) From 675b64950d4fa993db2308aa8686a803be3a6049 Mon Sep 17 00:00:00 2001 From: Alex Shapalov Date: Mon, 23 Nov 2026 14:05:07 -0800 Subject: [PATCH 5/5] fix(explain): print the deterministic report when no AI key is set (#156) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit runExplain resolved the model first and returned ai.Resolve's error before connecting, so with no key `pgbot explain` printed nothing and exited 3 (the connection/execution-failure code) — contrary to the README's promise that the deterministic report still stands when the key is unset. Only a failed model call after rendering degraded gracefully. A missing model is now not a command error: resolveExplainModel returns the resolve error as the AI section's "unavailable" reason, the inspection runs and renders as usual, and the process exits on the findings' code. Consent is still asked before connecting when a model is configured, and a refused consent still aborts. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ cmd/pgbot/explain.go | 41 ++++++++++++++++++++++++++++----------- cmd/pgbot/explain_test.go | 22 +++++++++++++++++++++ 3 files changed, 56 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6eb6da..c0e3572 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,6 +43,10 @@ separately by `model.SchemaVersion` (currently 1.5.0). your SQL text including literals — to a remote provider without asking. They now refuse with a message to re-run with `--yes`; local endpoints still need no confirmation (#143). +- `pgbot explain` with no AI key configured now runs the inspection, prints the + deterministic report and marks the AI section unavailable, exiting on the + findings' code — as the README documents — instead of exiting 3 with no + report before connecting (#156). ## [0.10.0] - 2026-11-16 diff --git a/cmd/pgbot/explain.go b/cmd/pgbot/explain.go index a8fc2fd..2f8d14c 100644 --- a/cmd/pgbot/explain.go +++ b/cmd/pgbot/explain.go @@ -57,15 +57,10 @@ func runExplain(cmd *cobra.Command, args []string, f inspectFlags, yes bool) err if !validFailOn(f.failOn) { return usageErrf("--fail-on must be critical|warn|info|none, got %q", f.failOn) } - // Build the model client first — fail fast before we connect if the key is - // missing, so the user isn't surprised after a full inspection. - llm, err := ai.Resolve() + llm, aiUnavailable, err := resolveExplainModel(yes) if err != nil { return err } - if !confirmDisclosure("pgbot explain", llm, yes) { - return fmt.Errorf("aborted") - } connString := firstNonEmpty(argAt(args, 0), os.Getenv("DATABASE_URL"), os.Getenv("PGBOT_DATABASE_URL"), pgServiceFallback()) if connString == "" { @@ -119,10 +114,14 @@ func runExplain(cmd *cobra.Command, args []string, f inspectFlags, yes bool) err // unavailable and exit on the findings' code. // Give the model its own deadline instead of the remainder of collection's // budget. Local models may need substantially longer than hosted providers. - aiCtx, aiCancel := context.WithTimeout(cmd.Context(), 3*time.Minute) - defer aiCancel() - explanation, aiErr := ai.Explain(aiCtx, llm, c) - printAISection(color, llm.Model(), explanation, aiErr, aiOnFindings) + explanation, aiErr, modelName := "", aiUnavailable, "" + if llm != nil { + aiCtx, aiCancel := context.WithTimeout(cmd.Context(), 3*time.Minute) + defer aiCancel() + explanation, aiErr = ai.Explain(aiCtx, llm, c) + modelName = llm.Model() + } + printAISection(color, modelName, explanation, aiErr, aiOnFindings) // The destructive-action guards, reasserted by code AFTER the model text — so a // reworded or truncated explanation can never be the thing that drops them. if aiErr == nil { @@ -133,6 +132,22 @@ func runExplain(cmd *cobra.Command, args []string, f inspectFlags, yes bool) err return nil } +// resolveExplainModel builds the model and asks for consent BEFORE connecting, +// so the user knows what leaves the machine before a full inspection. The model +// is optional for `explain`: when none is configured (no key), the inspection +// still runs and the reason becomes the AI section's "unavailable" note — the +// deterministic report always stands. Only a refused consent is an error. +func resolveExplainModel(yes bool) (llm ai.LanguageModel, unavailable, err error) { + llm, rerr := ai.Resolve() + if rerr != nil { + return nil, rerr, nil + } + if !confirmDisclosure("pgbot explain", llm, yes) { + return nil, nil, fmt.Errorf("aborted") + } + return llm, nil, nil +} + // confirmDisclosure identifies the remote destination before data is sent. // Local endpoints do not send findings off the machine and need no confirmation. func confirmDisclosure(cmdName string, llm ai.LanguageModel, yes bool) bool { @@ -196,7 +211,11 @@ func printAISection(color bool, modelName, text string, aiErr error, subject aiS rule := strings.Repeat("─", 64) fmt.Println() fmt.Println(st.Dim(rule)) - fmt.Println(st.AI(fmt.Sprintf("🤖 AI explanation · generated by %s — verify before acting", modelName))) + if modelName == "" { + fmt.Println(st.AI("🤖 AI explanation · no model configured")) + } else { + fmt.Println(st.AI(fmt.Sprintf("🤖 AI explanation · generated by %s — verify before acting", modelName))) + } fmt.Println(st.Dim(rule)) fmt.Println() if aiErr != nil { diff --git a/cmd/pgbot/explain_test.go b/cmd/pgbot/explain_test.go index a515704..3293c8a 100644 --- a/cmd/pgbot/explain_test.go +++ b/cmd/pgbot/explain_test.go @@ -64,6 +64,28 @@ func TestConfirmDisclosureNonInteractive(t *testing.T) { } } +// With no model configured, `pgbot explain` must still run the inspection and +// print the deterministic report: the missing key becomes the AI section's +// "unavailable" reason, not a command error that skips the report (#156). +func TestResolveExplainModelWithoutKey(t *testing.T) { + for _, k := range []string{"PGBOT_AI_PROVIDER", "PGBOT_AI_API_KEY", "PGBOT_AI_BASE_URL", "PGBOT_OPENAI_URL", "PGBOT_GEMINI_URL", + "GEMINI_API_KEY", "GOOGLE_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY", "OPENROUTER_API_KEY", + "XAI_API_KEY", "GROK_API_KEY", "AWS_BEARER_TOKEN_BEDROCK"} { + t.Setenv(k, "") + } + llm, unavailable, err := resolveExplainModel(false) + if err != nil { + t.Fatalf("a missing key must not fail the command (that skips the report): %v", err) + } + if llm != nil || unavailable == nil { + t.Fatalf("want no model and an unavailable reason, got llm=%v reason=%v", llm, unavailable) + } + out := captureStdout(t, func() { printAISection(false, "", "", unavailable, aiOnFindings) }) + if !strings.Contains(out, "explanation unavailable") || !strings.Contains(out, "The findings above are complete") { + t.Errorf("AI section should degrade, got:\n%s", out) + } +} + // `sql explain --ai` renders a query plan, not findings, so its AI section must // not tell the reader that "the findings above" are complete or authoritative // (#140). The findings commands keep their wording.