diff --git a/CHANGELOG.md b/CHANGELOG.md index e345e36..803926f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,25 @@ separately by `model.SchemaVersion` (currently 1.6.0). 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). +- `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). +- **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). +- `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). - `inspect --all-databases` now exits 3 when any database could not be inspected (#98); previously only `--all-instances` reported partial coverage in the exit code, so a script could mistake a partial run for a full one. diff --git a/README.md b/README.md index a2f0be8..a671be8 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. @@ -773,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 3a18ebd..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) + 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 { @@ -157,9 +172,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) @@ -167,23 +189,42 @@ 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() 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 { 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..3293c8a --- /dev/null +++ b/cmd/pgbot/explain_test.go @@ -0,0 +1,106 @@ +package main + +import ( + "context" + "errors" + "io" + "os" + "strings" + "testing" + + "github.com/pgrundev/pgbot/internal/ai" +) + +// 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 +} + +// 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") + } +} + +// 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. +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/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 06bfa98..1c790c8 100644 --- a/cmd/pgbot/sql.go +++ b/cmd/pgbot/sql.go @@ -59,14 +59,14 @@ 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) }, } 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 @@ -196,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 } 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", "") 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)