postgresai 0.14.0-dev.7 → 0.14.0-dev.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +161 -61
  2. package/bin/postgres-ai.ts +1982 -404
  3. package/bun.lock +258 -0
  4. package/bunfig.toml +20 -0
  5. package/dist/bin/postgres-ai.js +29395 -1576
  6. package/dist/sql/01.role.sql +16 -0
  7. package/dist/sql/02.permissions.sql +37 -0
  8. package/dist/sql/03.optional_rds.sql +6 -0
  9. package/dist/sql/04.optional_self_managed.sql +8 -0
  10. package/dist/sql/05.helpers.sql +439 -0
  11. package/dist/sql/sql/01.role.sql +16 -0
  12. package/dist/sql/sql/02.permissions.sql +37 -0
  13. package/dist/sql/sql/03.optional_rds.sql +6 -0
  14. package/dist/sql/sql/04.optional_self_managed.sql +8 -0
  15. package/dist/sql/sql/05.helpers.sql +439 -0
  16. package/lib/auth-server.ts +124 -106
  17. package/lib/checkup-api.ts +386 -0
  18. package/lib/checkup.ts +1396 -0
  19. package/lib/config.ts +6 -3
  20. package/lib/init.ts +568 -155
  21. package/lib/issues.ts +400 -191
  22. package/lib/mcp-server.ts +213 -90
  23. package/lib/metrics-embedded.ts +79 -0
  24. package/lib/metrics-loader.ts +127 -0
  25. package/lib/supabase.ts +769 -0
  26. package/lib/util.ts +61 -0
  27. package/package.json +20 -10
  28. package/packages/postgres-ai/README.md +26 -0
  29. package/packages/postgres-ai/bin/postgres-ai.js +27 -0
  30. package/packages/postgres-ai/package.json +27 -0
  31. package/scripts/embed-metrics.ts +154 -0
  32. package/sql/01.role.sql +16 -0
  33. package/sql/02.permissions.sql +37 -0
  34. package/sql/03.optional_rds.sql +6 -0
  35. package/sql/04.optional_self_managed.sql +8 -0
  36. package/sql/05.helpers.sql +439 -0
  37. package/test/auth.test.ts +258 -0
  38. package/test/checkup.integration.test.ts +321 -0
  39. package/test/checkup.test.ts +1117 -0
  40. package/test/config-consistency.test.ts +36 -0
  41. package/test/init.integration.test.ts +500 -0
  42. package/test/init.test.ts +682 -0
  43. package/test/issues.cli.test.ts +314 -0
  44. package/test/issues.test.ts +456 -0
  45. package/test/mcp-server.test.ts +988 -0
  46. package/test/schema-validation.test.ts +81 -0
  47. package/test/supabase.test.ts +568 -0
  48. package/test/test-utils.ts +128 -0
  49. package/tsconfig.json +12 -20
  50. package/dist/bin/postgres-ai.d.ts +0 -3
  51. package/dist/bin/postgres-ai.d.ts.map +0 -1
  52. package/dist/bin/postgres-ai.js.map +0 -1
  53. package/dist/lib/auth-server.d.ts +0 -31
  54. package/dist/lib/auth-server.d.ts.map +0 -1
  55. package/dist/lib/auth-server.js +0 -263
  56. package/dist/lib/auth-server.js.map +0 -1
  57. package/dist/lib/config.d.ts +0 -45
  58. package/dist/lib/config.d.ts.map +0 -1
  59. package/dist/lib/config.js +0 -181
  60. package/dist/lib/config.js.map +0 -1
  61. package/dist/lib/init.d.ts +0 -61
  62. package/dist/lib/init.d.ts.map +0 -1
  63. package/dist/lib/init.js +0 -359
  64. package/dist/lib/init.js.map +0 -1
  65. package/dist/lib/issues.d.ts +0 -75
  66. package/dist/lib/issues.d.ts.map +0 -1
  67. package/dist/lib/issues.js +0 -336
  68. package/dist/lib/issues.js.map +0 -1
  69. package/dist/lib/mcp-server.d.ts +0 -9
  70. package/dist/lib/mcp-server.d.ts.map +0 -1
  71. package/dist/lib/mcp-server.js +0 -168
  72. package/dist/lib/mcp-server.js.map +0 -1
  73. package/dist/lib/pkce.d.ts +0 -32
  74. package/dist/lib/pkce.d.ts.map +0 -1
  75. package/dist/lib/pkce.js +0 -101
  76. package/dist/lib/pkce.js.map +0 -1
  77. package/dist/lib/util.d.ts +0 -27
  78. package/dist/lib/util.d.ts.map +0 -1
  79. package/dist/lib/util.js +0 -46
  80. package/dist/lib/util.js.map +0 -1
  81. package/dist/package.json +0 -46
  82. package/test/init.integration.test.cjs +0 -269
  83. package/test/init.test.cjs +0 -69
@@ -0,0 +1,682 @@
1
+ import { describe, test, expect, beforeAll, afterAll } from "bun:test";
2
+ import { resolve } from "path";
3
+ import * as fs from "fs";
4
+ import * as os from "os";
5
+
6
+ // Import from source directly since we're using Bun
7
+ import * as init from "../lib/init";
8
+ const DEFAULT_MONITORING_USER = init.DEFAULT_MONITORING_USER;
9
+
10
+ function runCli(args: string[], env: Record<string, string> = {}) {
11
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
12
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
13
+ const result = Bun.spawnSync([bunBin, cliPath, ...args], {
14
+ env: { ...process.env, ...env },
15
+ });
16
+ return {
17
+ status: result.exitCode,
18
+ stdout: new TextDecoder().decode(result.stdout),
19
+ stderr: new TextDecoder().decode(result.stderr),
20
+ };
21
+ }
22
+
23
+ function runPgai(args: string[], env: Record<string, string> = {}) {
24
+ // For testing, run the CLI directly since pgai is just a thin wrapper
25
+ // In production, pgai wrapper will properly resolve and spawn the postgresai CLI
26
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
27
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
28
+ const result = Bun.spawnSync([bunBin, cliPath, ...args], {
29
+ env: { ...process.env, ...env },
30
+ });
31
+ return {
32
+ status: result.exitCode,
33
+ stdout: new TextDecoder().decode(result.stdout),
34
+ stderr: new TextDecoder().decode(result.stderr),
35
+ };
36
+ }
37
+
38
+ describe("init module", () => {
39
+ test("maskConnectionString hides password when present", () => {
40
+ const masked = init.maskConnectionString("postgresql://user:secret@localhost:5432/mydb");
41
+ expect(masked).toMatch(/postgresql:\/\/user:\*{5}@localhost:5432\/mydb/);
42
+ expect(masked).not.toMatch(/secret/);
43
+ });
44
+
45
+ test("parseLibpqConninfo parses basic host/dbname/user/port/password", () => {
46
+ const cfg = init.parseLibpqConninfo("dbname=mydb host=localhost user=alice port=5432 password=secret");
47
+ expect(cfg.database).toBe("mydb");
48
+ expect(cfg.host).toBe("localhost");
49
+ expect(cfg.user).toBe("alice");
50
+ expect(cfg.port).toBe(5432);
51
+ expect(cfg.password).toBe("secret");
52
+ });
53
+
54
+ test("parseLibpqConninfo supports quoted values", () => {
55
+ const cfg = init.parseLibpqConninfo("dbname='my db' host='local host'");
56
+ expect(cfg.database).toBe("my db");
57
+ expect(cfg.host).toBe("local host");
58
+ });
59
+
60
+ test("buildInitPlan includes a race-safe role DO block", async () => {
61
+ const plan = await init.buildInitPlan({
62
+ database: "mydb",
63
+ monitoringUser: DEFAULT_MONITORING_USER,
64
+ monitoringPassword: "pw",
65
+ includeOptionalPermissions: false,
66
+ });
67
+
68
+ expect(plan.database).toBe("mydb");
69
+ const roleStep = plan.steps.find((s: { name: string }) => s.name === "01.role");
70
+ expect(roleStep).toBeTruthy();
71
+ expect(roleStep.sql).toMatch(/do\s+\$\$/i);
72
+ expect(roleStep.sql).toMatch(/create\s+user/i);
73
+ expect(roleStep.sql).toMatch(/alter\s+user/i);
74
+ expect(plan.steps.some((s: { optional?: boolean }) => s.optional)).toBe(false);
75
+ });
76
+
77
+ test("buildInitPlan handles special characters in monitoring user and database identifiers", async () => {
78
+ const monitoringUser = 'user "with" quotes ✓';
79
+ const database = 'db name "with" quotes ✓';
80
+ const plan = await init.buildInitPlan({
81
+ database,
82
+ monitoringUser,
83
+ monitoringPassword: "pw",
84
+ includeOptionalPermissions: false,
85
+ });
86
+
87
+ const roleStep = plan.steps.find((s: { name: string }) => s.name === "01.role");
88
+ expect(roleStep).toBeTruthy();
89
+ expect(roleStep.sql).toMatch(/create\s+user\s+"user ""with"" quotes ✓"/i);
90
+ expect(roleStep.sql).toMatch(/alter\s+user\s+"user ""with"" quotes ✓"/i);
91
+
92
+ const permStep = plan.steps.find((s: { name: string }) => s.name === "02.permissions");
93
+ expect(permStep).toBeTruthy();
94
+ expect(permStep.sql).toMatch(/grant connect on database "db name ""with"" quotes ✓" to "user ""with"" quotes ✓"/i);
95
+ });
96
+
97
+ test("buildInitPlan keeps backslashes in passwords (no unintended escaping)", async () => {
98
+ const pw = String.raw`pw\with\backslash`;
99
+ const plan = await init.buildInitPlan({
100
+ database: "mydb",
101
+ monitoringUser: DEFAULT_MONITORING_USER,
102
+ monitoringPassword: pw,
103
+ includeOptionalPermissions: false,
104
+ });
105
+ const roleStep = plan.steps.find((s: { name: string }) => s.name === "01.role");
106
+ expect(roleStep).toBeTruthy();
107
+ expect(roleStep.sql).toContain(`password '${pw}'`);
108
+ });
109
+
110
+ test("buildInitPlan rejects identifiers with null bytes", async () => {
111
+ await expect(
112
+ init.buildInitPlan({
113
+ database: "mydb",
114
+ monitoringUser: "bad\0user",
115
+ monitoringPassword: "pw",
116
+ includeOptionalPermissions: false,
117
+ })
118
+ ).rejects.toThrow(/Identifier cannot contain null bytes/);
119
+ });
120
+
121
+ test("buildInitPlan rejects literals with null bytes", async () => {
122
+ await expect(
123
+ init.buildInitPlan({
124
+ database: "mydb",
125
+ monitoringUser: DEFAULT_MONITORING_USER,
126
+ monitoringPassword: "pw\0bad",
127
+ includeOptionalPermissions: false,
128
+ })
129
+ ).rejects.toThrow(/Literal cannot contain null bytes/);
130
+ });
131
+
132
+ test("buildInitPlan inlines password safely for CREATE/ALTER ROLE grammar", async () => {
133
+ const plan = await init.buildInitPlan({
134
+ database: "mydb",
135
+ monitoringUser: DEFAULT_MONITORING_USER,
136
+ monitoringPassword: "pa'ss",
137
+ includeOptionalPermissions: false,
138
+ });
139
+ const step = plan.steps.find((s: { name: string }) => s.name === "01.role");
140
+ expect(step).toBeTruthy();
141
+ expect(step.sql).toMatch(/password 'pa''ss'/);
142
+ expect(step.params).toBeUndefined();
143
+ });
144
+
145
+ test("buildInitPlan includes optional steps when enabled", async () => {
146
+ const plan = await init.buildInitPlan({
147
+ database: "mydb",
148
+ monitoringUser: DEFAULT_MONITORING_USER,
149
+ monitoringPassword: "pw",
150
+ includeOptionalPermissions: true,
151
+ });
152
+ expect(plan.steps.some((s: { optional?: boolean }) => s.optional)).toBe(true);
153
+ });
154
+
155
+ test("buildInitPlan skips role creation for supabase provider", async () => {
156
+ const plan = await init.buildInitPlan({
157
+ database: "mydb",
158
+ monitoringUser: DEFAULT_MONITORING_USER,
159
+ monitoringPassword: "pw",
160
+ includeOptionalPermissions: false,
161
+ provider: "supabase",
162
+ });
163
+ expect(plan.steps.some((s) => s.name === "01.role")).toBe(false);
164
+ expect(plan.steps.some((s) => s.name === "02.permissions")).toBe(true);
165
+ });
166
+
167
+ test("buildInitPlan removes ALTER USER for supabase provider", async () => {
168
+ const plan = await init.buildInitPlan({
169
+ database: "mydb",
170
+ monitoringUser: DEFAULT_MONITORING_USER,
171
+ monitoringPassword: "pw",
172
+ includeOptionalPermissions: false,
173
+ provider: "supabase",
174
+ });
175
+ const permStep = plan.steps.find((s) => s.name === "02.permissions");
176
+ expect(permStep).toBeDefined();
177
+ expect(permStep!.sql.toLowerCase()).not.toMatch(/alter user/);
178
+ });
179
+
180
+ test("buildInitPlan includes role creation for unknown provider", async () => {
181
+ const plan = await init.buildInitPlan({
182
+ database: "mydb",
183
+ monitoringUser: DEFAULT_MONITORING_USER,
184
+ monitoringPassword: "pw",
185
+ includeOptionalPermissions: false,
186
+ provider: "some-custom-provider",
187
+ });
188
+ expect(plan.steps.some((s) => s.name === "01.role")).toBe(true);
189
+ });
190
+
191
+ test("resolveAdminConnection accepts positional URI", () => {
192
+ const r = init.resolveAdminConnection({ conn: "postgresql://u:p@h:5432/d" });
193
+ expect(r.clientConfig.connectionString).toBeTruthy();
194
+ expect(r.display).not.toMatch(/:p@/);
195
+ });
196
+
197
+ test("resolveAdminConnection accepts positional conninfo", () => {
198
+ const r = init.resolveAdminConnection({ conn: "dbname=mydb host=localhost user=alice" });
199
+ expect(r.clientConfig.database).toBe("mydb");
200
+ expect(r.clientConfig.host).toBe("localhost");
201
+ expect(r.clientConfig.user).toBe("alice");
202
+ });
203
+
204
+ test("resolveAdminConnection rejects invalid psql-like port", () => {
205
+ expect(() => init.resolveAdminConnection({ host: "localhost", port: "abc", username: "u", dbname: "d" }))
206
+ .toThrow(/Invalid port value/);
207
+ });
208
+
209
+ test("resolveAdminConnection rejects when only PGPASSWORD is provided (no connection details)", () => {
210
+ expect(() => init.resolveAdminConnection({ envPassword: "pw" })).toThrow(/Connection is required/);
211
+ });
212
+
213
+ test("resolveAdminConnection rejects when connection is missing", () => {
214
+ expect(() => init.resolveAdminConnection({})).toThrow(/Connection is required/);
215
+ });
216
+
217
+ test("resolveMonitoringPassword auto-generates a strong, URL-safe password by default", async () => {
218
+ const r = await init.resolveMonitoringPassword({ monitoringUser: DEFAULT_MONITORING_USER });
219
+ expect(r.generated).toBe(true);
220
+ expect(typeof r.password).toBe("string");
221
+ expect(r.password.length).toBeGreaterThanOrEqual(30);
222
+ expect(r.password).toMatch(/^[A-Za-z0-9_-]+$/);
223
+ });
224
+
225
+ test("applyInitPlan preserves Postgres error fields on step failures", async () => {
226
+ const plan = {
227
+ monitoringUser: DEFAULT_MONITORING_USER,
228
+ database: "mydb",
229
+ steps: [{ name: "01.role", sql: "select 1" }],
230
+ };
231
+
232
+ const pgErr = Object.assign(new Error("permission denied to create role"), {
233
+ code: "42501",
234
+ detail: "some detail",
235
+ hint: "some hint",
236
+ schema: "pg_catalog",
237
+ table: "pg_roles",
238
+ constraint: "some_constraint",
239
+ routine: "aclcheck_error",
240
+ });
241
+
242
+ const calls: string[] = [];
243
+ const client = {
244
+ query: async (sql: string) => {
245
+ calls.push(sql);
246
+ if (sql === "begin;") return { rowCount: 1 };
247
+ if (sql === "rollback;") return { rowCount: 1 };
248
+ if (sql === "select 1") throw pgErr;
249
+ throw new Error(`unexpected sql: ${sql}`);
250
+ },
251
+ };
252
+
253
+ try {
254
+ await init.applyInitPlan({ client: client as any, plan: plan as any });
255
+ expect(true).toBe(false); // Should not reach here
256
+ } catch (e: any) {
257
+ expect(e).toBeInstanceOf(Error);
258
+ expect(e.message).toMatch(/Failed at step "01\.role":/);
259
+ expect(e.code).toBe("42501");
260
+ expect(e.detail).toBe("some detail");
261
+ expect(e.hint).toBe("some hint");
262
+ expect(e.schema).toBe("pg_catalog");
263
+ expect(e.table).toBe("pg_roles");
264
+ expect(e.constraint).toBe("some_constraint");
265
+ expect(e.routine).toBe("aclcheck_error");
266
+ }
267
+
268
+ expect(calls).toEqual(["begin;", "select 1", "rollback;"]);
269
+ });
270
+
271
+ test("verifyInitSetup runs inside a repeatable read snapshot and rolls back", async () => {
272
+ const calls: string[] = [];
273
+ const client = {
274
+ query: async (sql: string, params?: any) => {
275
+ calls.push(String(sql));
276
+
277
+ if (String(sql).toLowerCase().startsWith("begin isolation level repeatable read")) {
278
+ return { rowCount: 1, rows: [] };
279
+ }
280
+ if (String(sql).toLowerCase() === "rollback;") {
281
+ return { rowCount: 1, rows: [] };
282
+ }
283
+ if (String(sql).includes("select rolconfig")) {
284
+ return { rowCount: 1, rows: [{ rolconfig: ['search_path=postgres_ai, "$user", public, pg_catalog'] }] };
285
+ }
286
+ if (String(sql).includes("from pg_catalog.pg_roles")) {
287
+ return { rowCount: 1, rows: [] };
288
+ }
289
+ if (String(sql).includes("has_database_privilege")) {
290
+ return { rowCount: 1, rows: [{ ok: true }] };
291
+ }
292
+ if (String(sql).includes("pg_has_role")) {
293
+ return { rowCount: 1, rows: [{ ok: true }] };
294
+ }
295
+ if (String(sql).includes("has_table_privilege") && String(sql).includes("pg_catalog.pg_index")) {
296
+ return { rowCount: 1, rows: [{ ok: true }] };
297
+ }
298
+ if (String(sql).includes("to_regclass('postgres_ai.pg_statistic')")) {
299
+ return { rowCount: 1, rows: [{ ok: true }] };
300
+ }
301
+ if (String(sql).includes("has_table_privilege") && String(sql).includes("postgres_ai.pg_statistic")) {
302
+ return { rowCount: 1, rows: [{ ok: true }] };
303
+ }
304
+ if (String(sql).includes("has_function_privilege")) {
305
+ return { rowCount: 1, rows: [{ ok: true }] };
306
+ }
307
+ if (String(sql).includes("has_schema_privilege")) {
308
+ return { rowCount: 1, rows: [{ ok: true }] };
309
+ }
310
+
311
+ throw new Error(`unexpected sql: ${sql} params=${JSON.stringify(params)}`);
312
+ },
313
+ };
314
+
315
+ const r = await init.verifyInitSetup({
316
+ client: client as any,
317
+ database: "mydb",
318
+ monitoringUser: DEFAULT_MONITORING_USER,
319
+ includeOptionalPermissions: false,
320
+ });
321
+ expect(r.ok).toBe(true);
322
+ expect(r.missingRequired.length).toBe(0);
323
+
324
+ expect(calls.length).toBeGreaterThan(2);
325
+ expect(calls[0].toLowerCase()).toMatch(/^begin isolation level repeatable read/);
326
+ expect(calls[calls.length - 1].toLowerCase()).toBe("rollback;");
327
+ });
328
+
329
+ test("verifyInitSetup skips search_path check for supabase provider", async () => {
330
+ const calls: string[] = [];
331
+ const client = {
332
+ query: async (sql: string, params?: any) => {
333
+ calls.push(String(sql));
334
+
335
+ if (String(sql).toLowerCase().startsWith("begin isolation level repeatable read")) {
336
+ return { rowCount: 1, rows: [] };
337
+ }
338
+ if (String(sql).toLowerCase() === "rollback;") {
339
+ return { rowCount: 1, rows: [] };
340
+ }
341
+ // Return empty rolconfig - would fail without provider=supabase
342
+ if (String(sql).includes("select rolconfig")) {
343
+ return { rowCount: 1, rows: [{ rolconfig: null }] };
344
+ }
345
+ if (String(sql).includes("from pg_catalog.pg_roles")) {
346
+ return { rowCount: 1, rows: [{ rolname: DEFAULT_MONITORING_USER }] };
347
+ }
348
+ if (String(sql).includes("has_database_privilege")) {
349
+ return { rowCount: 1, rows: [{ ok: true }] };
350
+ }
351
+ if (String(sql).includes("pg_has_role")) {
352
+ return { rowCount: 1, rows: [{ ok: true }] };
353
+ }
354
+ if (String(sql).includes("has_table_privilege")) {
355
+ return { rowCount: 1, rows: [{ ok: true }] };
356
+ }
357
+ if (String(sql).includes("to_regclass")) {
358
+ return { rowCount: 1, rows: [{ ok: true }] };
359
+ }
360
+ if (String(sql).includes("has_function_privilege")) {
361
+ return { rowCount: 1, rows: [{ ok: true }] };
362
+ }
363
+ if (String(sql).includes("has_schema_privilege")) {
364
+ return { rowCount: 1, rows: [{ ok: true }] };
365
+ }
366
+
367
+ throw new Error(`unexpected sql: ${sql} params=${JSON.stringify(params)}`);
368
+ },
369
+ };
370
+
371
+ // With provider=supabase, should pass even without search_path
372
+ const r = await init.verifyInitSetup({
373
+ client: client as any,
374
+ database: "mydb",
375
+ monitoringUser: DEFAULT_MONITORING_USER,
376
+ includeOptionalPermissions: false,
377
+ provider: "supabase",
378
+ });
379
+ expect(r.ok).toBe(true);
380
+ expect(r.missingRequired.length).toBe(0);
381
+ // Should not have queried for rolconfig since we skip search_path check
382
+ expect(calls.some((c) => c.includes("select rolconfig"))).toBe(false);
383
+ });
384
+
385
+ test("buildInitPlan preserves comments when filtering ALTER USER", async () => {
386
+ const plan = await init.buildInitPlan({
387
+ database: "mydb",
388
+ monitoringUser: DEFAULT_MONITORING_USER,
389
+ monitoringPassword: "pw",
390
+ includeOptionalPermissions: false,
391
+ provider: "supabase",
392
+ });
393
+ const permStep = plan.steps.find((s) => s.name === "02.permissions");
394
+ expect(permStep).toBeDefined();
395
+ // Should have removed ALTER USER but kept comments
396
+ expect(permStep!.sql.toLowerCase()).not.toMatch(/^\s*alter\s+user/m);
397
+ // Should still have comment lines
398
+ expect(permStep!.sql).toMatch(/^--/m);
399
+ });
400
+
401
+ test("validateProvider returns null for known providers", () => {
402
+ expect(init.validateProvider(undefined)).toBe(null);
403
+ expect(init.validateProvider("self-managed")).toBe(null);
404
+ expect(init.validateProvider("supabase")).toBe(null);
405
+ });
406
+
407
+ test("validateProvider returns warning for unknown providers", () => {
408
+ const warning = init.validateProvider("unknown-provider");
409
+ expect(warning).not.toBe(null);
410
+ expect(warning).toMatch(/Unknown provider/);
411
+ expect(warning).toMatch(/unknown-provider/);
412
+ });
413
+
414
+ test("redactPasswordsInSql redacts password literals with embedded quotes", async () => {
415
+ const plan = await init.buildInitPlan({
416
+ database: "mydb",
417
+ monitoringUser: DEFAULT_MONITORING_USER,
418
+ monitoringPassword: "pa'ss",
419
+ includeOptionalPermissions: false,
420
+ });
421
+ const step = plan.steps.find((s: { name: string }) => s.name === "01.role");
422
+ expect(step).toBeTruthy();
423
+ const redacted = init.redactPasswordsInSql(step.sql);
424
+ expect(redacted).toMatch(/password '<redacted>'/i);
425
+ });
426
+ });
427
+
428
+ describe("CLI commands", () => {
429
+ test("cli: prepare-db with missing connection prints help/options", () => {
430
+ const r = runCli(["prepare-db"]);
431
+ expect(r.status).not.toBe(0);
432
+ expect(r.stderr).toMatch(/--print-sql/);
433
+ expect(r.stderr).toMatch(/--monitoring-user/);
434
+ });
435
+
436
+ test("cli: prepare-db --print-sql works without connection (offline mode)", () => {
437
+ const r = runCli(["prepare-db", "--print-sql", "-d", "mydb", "--password", "monpw"]);
438
+ expect(r.status).toBe(0);
439
+ expect(r.stdout).toMatch(/SQL plan \(offline; not connected\)/);
440
+ expect(r.stdout).toMatch(new RegExp(`grant connect on database "mydb" to "${DEFAULT_MONITORING_USER}"`, "i"));
441
+ });
442
+
443
+ test("cli: prepare-db --print-sql with --provider supabase skips role step", () => {
444
+ const r = runCli(["prepare-db", "--print-sql", "-d", "mydb", "--password", "monpw", "--provider", "supabase"]);
445
+ expect(r.status).toBe(0);
446
+ expect(r.stdout).toMatch(/provider: supabase/);
447
+ // Should not have 01.role step
448
+ expect(r.stdout).not.toMatch(/-- 01\.role/);
449
+ // Should have 02.permissions step
450
+ expect(r.stdout).toMatch(/-- 02\.permissions/);
451
+ });
452
+
453
+ test("cli: prepare-db warns about unknown provider", () => {
454
+ const r = runCli(["prepare-db", "--print-sql", "-d", "mydb", "--password", "monpw", "--provider", "unknown-cloud"]);
455
+ expect(r.status).toBe(0);
456
+ // Should warn about unknown provider
457
+ expect(r.stderr).toMatch(/Unknown provider.*unknown-cloud/);
458
+ });
459
+
460
+ test("cli: prepare-db --reset-password with supabase provider would have no role step", async () => {
461
+ // When using supabase provider, the role creation step is skipped.
462
+ // This means --reset-password (which only runs 01.role) would have no steps.
463
+ // The CLI should error in this case. We test the underlying plan logic here.
464
+ const plan = await (await import("../lib/init")).buildInitPlan({
465
+ database: "mydb",
466
+ monitoringUser: "mon",
467
+ monitoringPassword: "pw",
468
+ includeOptionalPermissions: false,
469
+ provider: "supabase",
470
+ });
471
+ // Simulate what --reset-password does: filter to only 01.role step
472
+ const resetPasswordSteps = plan.steps.filter((s) => s.name === "01.role");
473
+ // For supabase, this should be empty (role creation is skipped)
474
+ expect(resetPasswordSteps.length).toBe(0);
475
+ });
476
+
477
+ test("pgai wrapper forwards to postgresai CLI", () => {
478
+ const r = runPgai(["--help"]);
479
+ expect(r.status).toBe(0);
480
+ expect(r.stdout).toMatch(/postgresai|PostgresAI/i);
481
+ });
482
+
483
+ test("cli: prepare-db command exists and shows help", () => {
484
+ const r = runCli(["prepare-db", "--help"]);
485
+ expect(r.status).toBe(0);
486
+ expect(r.stdout).toMatch(/monitoring user/i);
487
+ expect(r.stdout).toMatch(/--print-sql/);
488
+ });
489
+
490
+ test("cli: mon local-install command exists and shows help", () => {
491
+ const r = runCli(["mon", "local-install", "--help"]);
492
+ expect(r.status).toBe(0);
493
+ expect(r.stdout).toMatch(/--demo/);
494
+ expect(r.stdout).toMatch(/--api-key/);
495
+ });
496
+
497
+ test("cli: mon local-install --api-key and --db-url skip interactive prompts", () => {
498
+ // This test verifies that when --api-key and --db-url are provided,
499
+ // the CLI uses them directly without prompting for input.
500
+ // The command will fail later (no Docker, invalid DB), but we check
501
+ // that the options were parsed and used correctly.
502
+ const r = runCli([
503
+ "mon", "local-install",
504
+ "--api-key", "test-api-key-12345",
505
+ "--db-url", "postgresql://user:pass@localhost:5432/testdb"
506
+ ]);
507
+
508
+ // Should show that API key was provided via CLI option (not prompting)
509
+ expect(r.stdout).toMatch(/Using API key provided via --api-key parameter/);
510
+ // Should show that DB URL was provided via CLI option (not prompting)
511
+ expect(r.stdout).toMatch(/Using database URL provided via --db-url parameter/);
512
+ });
513
+
514
+ test("cli: auth login --help shows --set-key option", () => {
515
+ const r = runCli(["auth", "login", "--help"]);
516
+ expect(r.status).toBe(0);
517
+ expect(r.stdout).toMatch(/--set-key/);
518
+ });
519
+
520
+ test("cli: mon local-install reads global --api-key option", () => {
521
+ // The fix ensures --api-key works when passed as a global option (before subcommand)
522
+ // Commander.js routes global options to program.opts(), not subcommand opts
523
+ const r = runCli([
524
+ "--api-key", "global-api-key-test",
525
+ "mon", "local-install",
526
+ "--db-url", "postgresql://user:pass@localhost:5432/testdb"
527
+ ]);
528
+
529
+ // Should detect the API key from global options
530
+ expect(r.stdout).toMatch(/Using API key provided via --api-key parameter/);
531
+ });
532
+
533
+ test("cli: mon local-install works with --api-key after subcommand", () => {
534
+ // Test that --api-key works when passed after the subcommand
535
+ // Note: Commander.js routes --api-key to global opts, the fix reads from both
536
+ const r = runCli([
537
+ "mon", "local-install",
538
+ "--api-key", "test-key-after-subcommand",
539
+ "--db-url", "postgresql://user:pass@localhost:5432/testdb"
540
+ ]);
541
+
542
+ // Should detect the API key regardless of position
543
+ expect(r.stdout).toMatch(/Using API key provided via --api-key parameter/);
544
+ // Verify the key was saved
545
+ expect(r.stdout).toMatch(/API key saved/);
546
+ });
547
+
548
+ test("cli: mon local-install with --yes and no --api-key skips API setup", () => {
549
+ // When --yes is provided without --api-key, the CLI should skip
550
+ // the interactive prompt and proceed without API key
551
+ const r = runCli([
552
+ "mon", "local-install",
553
+ "--db-url", "postgresql://user:pass@localhost:5432/testdb",
554
+ "--yes"
555
+ ]);
556
+
557
+ // Should indicate auto-yes mode without API key
558
+ expect(r.stdout).toMatch(/Auto-yes mode: no API key provided/);
559
+ expect(r.stdout).toMatch(/Reports will be generated locally only/);
560
+ });
561
+
562
+ test("cli: mon local-install --demo with global --api-key shows error", () => {
563
+ // When --demo is used with global --api-key, it should still be detected and error
564
+ const r = runCli([
565
+ "--api-key", "global-api-key-test",
566
+ "mon", "local-install",
567
+ "--demo"
568
+ ]);
569
+
570
+ // Should reject demo mode with API key (from global option)
571
+ expect(r.status).not.toBe(0);
572
+ expect(r.stderr).toMatch(/Cannot use --api-key with --demo mode/);
573
+ });
574
+ });
575
+
576
+ describe("imageTag priority behavior", () => {
577
+ // Tests for the imageTag priority: --tag flag > PGAI_TAG env var > pkg.version
578
+ // This verifies the fix that prevents stale .env PGAI_TAG from being used
579
+
580
+ let tempDir: string;
581
+
582
+ beforeAll(() => {
583
+ tempDir = fs.mkdtempSync(resolve(os.tmpdir(), "pgai-test-"));
584
+ });
585
+
586
+ afterAll(() => {
587
+ if (tempDir && fs.existsSync(tempDir)) {
588
+ fs.rmSync(tempDir, { recursive: true, force: true });
589
+ }
590
+ });
591
+
592
+ test("stale .env PGAI_TAG is NOT used - CLI version takes precedence", () => {
593
+ // Create a stale .env with an old tag value
594
+ const testDir = resolve(tempDir, "stale-tag-test");
595
+ fs.mkdirSync(testDir, { recursive: true });
596
+ fs.writeFileSync(resolve(testDir, ".env"), "PGAI_TAG=beta\n");
597
+ // Create minimal docker-compose.yml so resolvePaths() finds it
598
+ fs.writeFileSync(resolve(testDir, "docker-compose.yml"), "version: '3'\nservices: {}\n");
599
+
600
+ // Run from the test directory (so resolvePaths finds docker-compose.yml)
601
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
602
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
603
+ const result = Bun.spawnSync([bunBin, cliPath, "mon", "local-install", "--db-url", "postgresql://u:p@h:5432/d", "--yes"], {
604
+ env: { ...process.env, PGAI_TAG: undefined },
605
+ cwd: testDir,
606
+ });
607
+
608
+ // Read the .env that was written
609
+ const envContent = fs.readFileSync(resolve(testDir, ".env"), "utf8");
610
+
611
+ // The .env should NOT contain the stale "beta" tag - it should use pkg.version
612
+ expect(envContent).not.toMatch(/PGAI_TAG=beta/);
613
+ // It should contain the CLI version (0.0.0-dev.0 in dev)
614
+ expect(envContent).toMatch(/PGAI_TAG=\d+\.\d+\.\d+|PGAI_TAG=0\.0\.0-dev/);
615
+ });
616
+
617
+ test("--tag flag takes priority over pkg.version", () => {
618
+ const testDir = resolve(tempDir, "tag-flag-test");
619
+ fs.mkdirSync(testDir, { recursive: true });
620
+ fs.writeFileSync(resolve(testDir, "docker-compose.yml"), "version: '3'\nservices: {}\n");
621
+
622
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
623
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
624
+ const result = Bun.spawnSync([bunBin, cliPath, "mon", "local-install", "--tag", "v1.2.3-custom", "--db-url", "postgresql://u:p@h:5432/d", "--yes"], {
625
+ env: { ...process.env, PGAI_TAG: undefined },
626
+ cwd: testDir,
627
+ });
628
+
629
+ const envContent = fs.readFileSync(resolve(testDir, ".env"), "utf8");
630
+ expect(envContent).toMatch(/PGAI_TAG=v1\.2\.3-custom/);
631
+
632
+ // Verify stdout confirms the tag being used
633
+ const stdout = new TextDecoder().decode(result.stdout);
634
+ expect(stdout).toMatch(/Using image tag: v1\.2\.3-custom/);
635
+ });
636
+
637
+ test("PGAI_TAG env var is intentionally ignored (Bun auto-loads .env)", () => {
638
+ // Note: We do NOT use process.env.PGAI_TAG because Bun auto-loads .env files,
639
+ // which would cause stale .env values to pollute the environment.
640
+ // Users should use --tag flag to override, not env vars.
641
+ const testDir = resolve(tempDir, "env-var-ignored-test");
642
+ fs.mkdirSync(testDir, { recursive: true });
643
+ fs.writeFileSync(resolve(testDir, "docker-compose.yml"), "version: '3'\nservices: {}\n");
644
+
645
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
646
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
647
+ const result = Bun.spawnSync([bunBin, cliPath, "mon", "local-install", "--db-url", "postgresql://u:p@h:5432/d", "--yes"], {
648
+ env: { ...process.env, PGAI_TAG: "v2.0.0-from-env" },
649
+ cwd: testDir,
650
+ });
651
+
652
+ const envContent = fs.readFileSync(resolve(testDir, ".env"), "utf8");
653
+ // PGAI_TAG env var should be IGNORED - uses pkg.version instead
654
+ expect(envContent).not.toMatch(/PGAI_TAG=v2\.0\.0-from-env/);
655
+ expect(envContent).toMatch(/PGAI_TAG=\d+\.\d+\.\d+|PGAI_TAG=0\.0\.0-dev/);
656
+ });
657
+
658
+ test("existing registry and password are preserved while tag is updated", () => {
659
+ const testDir = resolve(tempDir, "preserve-test");
660
+ fs.mkdirSync(testDir, { recursive: true });
661
+ // Create .env with stale tag but valid registry and password
662
+ fs.writeFileSync(resolve(testDir, ".env"),
663
+ "PGAI_TAG=stale-tag\nPGAI_REGISTRY=my.registry.com\nGF_SECURITY_ADMIN_PASSWORD=secret123\n");
664
+ fs.writeFileSync(resolve(testDir, "docker-compose.yml"), "version: '3'\nservices: {}\n");
665
+
666
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
667
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
668
+ const result = Bun.spawnSync([bunBin, cliPath, "mon", "local-install", "--db-url", "postgresql://u:p@h:5432/d", "--yes"], {
669
+ env: { ...process.env, PGAI_TAG: undefined },
670
+ cwd: testDir,
671
+ });
672
+
673
+ const envContent = fs.readFileSync(resolve(testDir, ".env"), "utf8");
674
+
675
+ // Tag should be updated (not stale-tag)
676
+ expect(envContent).not.toMatch(/PGAI_TAG=stale-tag/);
677
+
678
+ // But registry and password should be preserved
679
+ expect(envContent).toMatch(/PGAI_REGISTRY=my\.registry\.com/);
680
+ expect(envContent).toMatch(/GF_SECURITY_ADMIN_PASSWORD=secret123/);
681
+ });
682
+ });