postgresai 0.14.0-dev.7 → 0.14.0-dev.70

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 (82) hide show
  1. package/README.md +161 -61
  2. package/bin/postgres-ai.ts +1957 -404
  3. package/bun.lock +258 -0
  4. package/bunfig.toml +20 -0
  5. package/dist/bin/postgres-ai.js +29351 -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 +512 -156
  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/init.integration.test.ts +500 -0
  41. package/test/init.test.ts +527 -0
  42. package/test/issues.cli.test.ts +314 -0
  43. package/test/issues.test.ts +456 -0
  44. package/test/mcp-server.test.ts +988 -0
  45. package/test/schema-validation.test.ts +81 -0
  46. package/test/supabase.test.ts +568 -0
  47. package/test/test-utils.ts +128 -0
  48. package/tsconfig.json +12 -20
  49. package/dist/bin/postgres-ai.d.ts +0 -3
  50. package/dist/bin/postgres-ai.d.ts.map +0 -1
  51. package/dist/bin/postgres-ai.js.map +0 -1
  52. package/dist/lib/auth-server.d.ts +0 -31
  53. package/dist/lib/auth-server.d.ts.map +0 -1
  54. package/dist/lib/auth-server.js +0 -263
  55. package/dist/lib/auth-server.js.map +0 -1
  56. package/dist/lib/config.d.ts +0 -45
  57. package/dist/lib/config.d.ts.map +0 -1
  58. package/dist/lib/config.js +0 -181
  59. package/dist/lib/config.js.map +0 -1
  60. package/dist/lib/init.d.ts +0 -61
  61. package/dist/lib/init.d.ts.map +0 -1
  62. package/dist/lib/init.js +0 -359
  63. package/dist/lib/init.js.map +0 -1
  64. package/dist/lib/issues.d.ts +0 -75
  65. package/dist/lib/issues.d.ts.map +0 -1
  66. package/dist/lib/issues.js +0 -336
  67. package/dist/lib/issues.js.map +0 -1
  68. package/dist/lib/mcp-server.d.ts +0 -9
  69. package/dist/lib/mcp-server.d.ts.map +0 -1
  70. package/dist/lib/mcp-server.js +0 -168
  71. package/dist/lib/mcp-server.js.map +0 -1
  72. package/dist/lib/pkce.d.ts +0 -32
  73. package/dist/lib/pkce.d.ts.map +0 -1
  74. package/dist/lib/pkce.js +0 -101
  75. package/dist/lib/pkce.js.map +0 -1
  76. package/dist/lib/util.d.ts +0 -27
  77. package/dist/lib/util.d.ts.map +0 -1
  78. package/dist/lib/util.js +0 -46
  79. package/dist/lib/util.js.map +0 -1
  80. package/dist/package.json +0 -46
  81. package/test/init.integration.test.cjs +0 -269
  82. package/test/init.test.cjs +0 -69
@@ -0,0 +1,527 @@
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("resolveAdminConnection accepts positional URI", () => {
156
+ const r = init.resolveAdminConnection({ conn: "postgresql://u:p@h:5432/d" });
157
+ expect(r.clientConfig.connectionString).toBeTruthy();
158
+ expect(r.display).not.toMatch(/:p@/);
159
+ });
160
+
161
+ test("resolveAdminConnection accepts positional conninfo", () => {
162
+ const r = init.resolveAdminConnection({ conn: "dbname=mydb host=localhost user=alice" });
163
+ expect(r.clientConfig.database).toBe("mydb");
164
+ expect(r.clientConfig.host).toBe("localhost");
165
+ expect(r.clientConfig.user).toBe("alice");
166
+ });
167
+
168
+ test("resolveAdminConnection rejects invalid psql-like port", () => {
169
+ expect(() => init.resolveAdminConnection({ host: "localhost", port: "abc", username: "u", dbname: "d" }))
170
+ .toThrow(/Invalid port value/);
171
+ });
172
+
173
+ test("resolveAdminConnection rejects when only PGPASSWORD is provided (no connection details)", () => {
174
+ expect(() => init.resolveAdminConnection({ envPassword: "pw" })).toThrow(/Connection is required/);
175
+ });
176
+
177
+ test("resolveAdminConnection rejects when connection is missing", () => {
178
+ expect(() => init.resolveAdminConnection({})).toThrow(/Connection is required/);
179
+ });
180
+
181
+ test("resolveMonitoringPassword auto-generates a strong, URL-safe password by default", async () => {
182
+ const r = await init.resolveMonitoringPassword({ monitoringUser: DEFAULT_MONITORING_USER });
183
+ expect(r.generated).toBe(true);
184
+ expect(typeof r.password).toBe("string");
185
+ expect(r.password.length).toBeGreaterThanOrEqual(30);
186
+ expect(r.password).toMatch(/^[A-Za-z0-9_-]+$/);
187
+ });
188
+
189
+ test("applyInitPlan preserves Postgres error fields on step failures", async () => {
190
+ const plan = {
191
+ monitoringUser: DEFAULT_MONITORING_USER,
192
+ database: "mydb",
193
+ steps: [{ name: "01.role", sql: "select 1" }],
194
+ };
195
+
196
+ const pgErr = Object.assign(new Error("permission denied to create role"), {
197
+ code: "42501",
198
+ detail: "some detail",
199
+ hint: "some hint",
200
+ schema: "pg_catalog",
201
+ table: "pg_roles",
202
+ constraint: "some_constraint",
203
+ routine: "aclcheck_error",
204
+ });
205
+
206
+ const calls: string[] = [];
207
+ const client = {
208
+ query: async (sql: string) => {
209
+ calls.push(sql);
210
+ if (sql === "begin;") return { rowCount: 1 };
211
+ if (sql === "rollback;") return { rowCount: 1 };
212
+ if (sql === "select 1") throw pgErr;
213
+ throw new Error(`unexpected sql: ${sql}`);
214
+ },
215
+ };
216
+
217
+ try {
218
+ await init.applyInitPlan({ client: client as any, plan: plan as any });
219
+ expect(true).toBe(false); // Should not reach here
220
+ } catch (e: any) {
221
+ expect(e).toBeInstanceOf(Error);
222
+ expect(e.message).toMatch(/Failed at step "01\.role":/);
223
+ expect(e.code).toBe("42501");
224
+ expect(e.detail).toBe("some detail");
225
+ expect(e.hint).toBe("some hint");
226
+ expect(e.schema).toBe("pg_catalog");
227
+ expect(e.table).toBe("pg_roles");
228
+ expect(e.constraint).toBe("some_constraint");
229
+ expect(e.routine).toBe("aclcheck_error");
230
+ }
231
+
232
+ expect(calls).toEqual(["begin;", "select 1", "rollback;"]);
233
+ });
234
+
235
+ test("verifyInitSetup runs inside a repeatable read snapshot and rolls back", async () => {
236
+ const calls: string[] = [];
237
+ const client = {
238
+ query: async (sql: string, params?: any) => {
239
+ calls.push(String(sql));
240
+
241
+ if (String(sql).toLowerCase().startsWith("begin isolation level repeatable read")) {
242
+ return { rowCount: 1, rows: [] };
243
+ }
244
+ if (String(sql).toLowerCase() === "rollback;") {
245
+ return { rowCount: 1, rows: [] };
246
+ }
247
+ if (String(sql).includes("select rolconfig")) {
248
+ return { rowCount: 1, rows: [{ rolconfig: ['search_path=postgres_ai, "$user", public, pg_catalog'] }] };
249
+ }
250
+ if (String(sql).includes("from pg_catalog.pg_roles")) {
251
+ return { rowCount: 1, rows: [] };
252
+ }
253
+ if (String(sql).includes("has_database_privilege")) {
254
+ return { rowCount: 1, rows: [{ ok: true }] };
255
+ }
256
+ if (String(sql).includes("pg_has_role")) {
257
+ return { rowCount: 1, rows: [{ ok: true }] };
258
+ }
259
+ if (String(sql).includes("has_table_privilege") && String(sql).includes("pg_catalog.pg_index")) {
260
+ return { rowCount: 1, rows: [{ ok: true }] };
261
+ }
262
+ if (String(sql).includes("to_regclass('postgres_ai.pg_statistic')")) {
263
+ return { rowCount: 1, rows: [{ ok: true }] };
264
+ }
265
+ if (String(sql).includes("has_table_privilege") && String(sql).includes("postgres_ai.pg_statistic")) {
266
+ return { rowCount: 1, rows: [{ ok: true }] };
267
+ }
268
+ if (String(sql).includes("has_function_privilege")) {
269
+ return { rowCount: 1, rows: [{ ok: true }] };
270
+ }
271
+ if (String(sql).includes("has_schema_privilege")) {
272
+ return { rowCount: 1, rows: [{ ok: true }] };
273
+ }
274
+
275
+ throw new Error(`unexpected sql: ${sql} params=${JSON.stringify(params)}`);
276
+ },
277
+ };
278
+
279
+ const r = await init.verifyInitSetup({
280
+ client: client as any,
281
+ database: "mydb",
282
+ monitoringUser: DEFAULT_MONITORING_USER,
283
+ includeOptionalPermissions: false,
284
+ });
285
+ expect(r.ok).toBe(true);
286
+ expect(r.missingRequired.length).toBe(0);
287
+
288
+ expect(calls.length).toBeGreaterThan(2);
289
+ expect(calls[0].toLowerCase()).toMatch(/^begin isolation level repeatable read/);
290
+ expect(calls[calls.length - 1].toLowerCase()).toBe("rollback;");
291
+ });
292
+
293
+ test("redactPasswordsInSql redacts password literals with embedded quotes", async () => {
294
+ const plan = await init.buildInitPlan({
295
+ database: "mydb",
296
+ monitoringUser: DEFAULT_MONITORING_USER,
297
+ monitoringPassword: "pa'ss",
298
+ includeOptionalPermissions: false,
299
+ });
300
+ const step = plan.steps.find((s: { name: string }) => s.name === "01.role");
301
+ expect(step).toBeTruthy();
302
+ const redacted = init.redactPasswordsInSql(step.sql);
303
+ expect(redacted).toMatch(/password '<redacted>'/i);
304
+ });
305
+ });
306
+
307
+ describe("CLI commands", () => {
308
+ test("cli: prepare-db with missing connection prints help/options", () => {
309
+ const r = runCli(["prepare-db"]);
310
+ expect(r.status).not.toBe(0);
311
+ expect(r.stderr).toMatch(/--print-sql/);
312
+ expect(r.stderr).toMatch(/--monitoring-user/);
313
+ });
314
+
315
+ test("cli: prepare-db --print-sql works without connection (offline mode)", () => {
316
+ const r = runCli(["prepare-db", "--print-sql", "-d", "mydb", "--password", "monpw"]);
317
+ expect(r.status).toBe(0);
318
+ expect(r.stdout).toMatch(/SQL plan \(offline; not connected\)/);
319
+ expect(r.stdout).toMatch(new RegExp(`grant connect on database "mydb" to "${DEFAULT_MONITORING_USER}"`, "i"));
320
+ });
321
+
322
+ test("pgai wrapper forwards to postgresai CLI", () => {
323
+ const r = runPgai(["--help"]);
324
+ expect(r.status).toBe(0);
325
+ expect(r.stdout).toMatch(/postgresai|PostgresAI/i);
326
+ });
327
+
328
+ test("cli: prepare-db command exists and shows help", () => {
329
+ const r = runCli(["prepare-db", "--help"]);
330
+ expect(r.status).toBe(0);
331
+ expect(r.stdout).toMatch(/monitoring user/i);
332
+ expect(r.stdout).toMatch(/--print-sql/);
333
+ });
334
+
335
+ test("cli: mon local-install command exists and shows help", () => {
336
+ const r = runCli(["mon", "local-install", "--help"]);
337
+ expect(r.status).toBe(0);
338
+ expect(r.stdout).toMatch(/--demo/);
339
+ expect(r.stdout).toMatch(/--api-key/);
340
+ });
341
+
342
+ test("cli: mon local-install --api-key and --db-url skip interactive prompts", () => {
343
+ // This test verifies that when --api-key and --db-url are provided,
344
+ // the CLI uses them directly without prompting for input.
345
+ // The command will fail later (no Docker, invalid DB), but we check
346
+ // that the options were parsed and used correctly.
347
+ const r = runCli([
348
+ "mon", "local-install",
349
+ "--api-key", "test-api-key-12345",
350
+ "--db-url", "postgresql://user:pass@localhost:5432/testdb"
351
+ ]);
352
+
353
+ // Should show that API key was provided via CLI option (not prompting)
354
+ expect(r.stdout).toMatch(/Using API key provided via --api-key parameter/);
355
+ // Should show that DB URL was provided via CLI option (not prompting)
356
+ expect(r.stdout).toMatch(/Using database URL provided via --db-url parameter/);
357
+ });
358
+
359
+ test("cli: auth login --help shows --set-key option", () => {
360
+ const r = runCli(["auth", "login", "--help"]);
361
+ expect(r.status).toBe(0);
362
+ expect(r.stdout).toMatch(/--set-key/);
363
+ });
364
+
365
+ test("cli: mon local-install reads global --api-key option", () => {
366
+ // The fix ensures --api-key works when passed as a global option (before subcommand)
367
+ // Commander.js routes global options to program.opts(), not subcommand opts
368
+ const r = runCli([
369
+ "--api-key", "global-api-key-test",
370
+ "mon", "local-install",
371
+ "--db-url", "postgresql://user:pass@localhost:5432/testdb"
372
+ ]);
373
+
374
+ // Should detect the API key from global options
375
+ expect(r.stdout).toMatch(/Using API key provided via --api-key parameter/);
376
+ });
377
+
378
+ test("cli: mon local-install works with --api-key after subcommand", () => {
379
+ // Test that --api-key works when passed after the subcommand
380
+ // Note: Commander.js routes --api-key to global opts, the fix reads from both
381
+ const r = runCli([
382
+ "mon", "local-install",
383
+ "--api-key", "test-key-after-subcommand",
384
+ "--db-url", "postgresql://user:pass@localhost:5432/testdb"
385
+ ]);
386
+
387
+ // Should detect the API key regardless of position
388
+ expect(r.stdout).toMatch(/Using API key provided via --api-key parameter/);
389
+ // Verify the key was saved
390
+ expect(r.stdout).toMatch(/API key saved/);
391
+ });
392
+
393
+ test("cli: mon local-install with --yes and no --api-key skips API setup", () => {
394
+ // When --yes is provided without --api-key, the CLI should skip
395
+ // the interactive prompt and proceed without API key
396
+ const r = runCli([
397
+ "mon", "local-install",
398
+ "--db-url", "postgresql://user:pass@localhost:5432/testdb",
399
+ "--yes"
400
+ ]);
401
+
402
+ // Should indicate auto-yes mode without API key
403
+ expect(r.stdout).toMatch(/Auto-yes mode: no API key provided/);
404
+ expect(r.stdout).toMatch(/Reports will be generated locally only/);
405
+ });
406
+
407
+ test("cli: mon local-install --demo with global --api-key shows error", () => {
408
+ // When --demo is used with global --api-key, it should still be detected and error
409
+ const r = runCli([
410
+ "--api-key", "global-api-key-test",
411
+ "mon", "local-install",
412
+ "--demo"
413
+ ]);
414
+
415
+ // Should reject demo mode with API key (from global option)
416
+ expect(r.status).not.toBe(0);
417
+ expect(r.stderr).toMatch(/Cannot use --api-key with --demo mode/);
418
+ });
419
+ });
420
+
421
+ describe("imageTag priority behavior", () => {
422
+ // Tests for the imageTag priority: --tag flag > PGAI_TAG env var > pkg.version
423
+ // This verifies the fix that prevents stale .env PGAI_TAG from being used
424
+
425
+ let tempDir: string;
426
+
427
+ beforeAll(() => {
428
+ tempDir = fs.mkdtempSync(resolve(os.tmpdir(), "pgai-test-"));
429
+ });
430
+
431
+ afterAll(() => {
432
+ if (tempDir && fs.existsSync(tempDir)) {
433
+ fs.rmSync(tempDir, { recursive: true, force: true });
434
+ }
435
+ });
436
+
437
+ test("stale .env PGAI_TAG is NOT used - CLI version takes precedence", () => {
438
+ // Create a stale .env with an old tag value
439
+ const testDir = resolve(tempDir, "stale-tag-test");
440
+ fs.mkdirSync(testDir, { recursive: true });
441
+ fs.writeFileSync(resolve(testDir, ".env"), "PGAI_TAG=beta\n");
442
+ // Create minimal docker-compose.yml so resolvePaths() finds it
443
+ fs.writeFileSync(resolve(testDir, "docker-compose.yml"), "version: '3'\nservices: {}\n");
444
+
445
+ // Run from the test directory (so resolvePaths finds docker-compose.yml)
446
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
447
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
448
+ const result = Bun.spawnSync([bunBin, cliPath, "mon", "local-install", "--db-url", "postgresql://u:p@h:5432/d", "--yes"], {
449
+ env: { ...process.env, PGAI_TAG: undefined },
450
+ cwd: testDir,
451
+ });
452
+
453
+ // Read the .env that was written
454
+ const envContent = fs.readFileSync(resolve(testDir, ".env"), "utf8");
455
+
456
+ // The .env should NOT contain the stale "beta" tag - it should use pkg.version
457
+ expect(envContent).not.toMatch(/PGAI_TAG=beta/);
458
+ // It should contain the CLI version (0.0.0-dev.0 in dev)
459
+ expect(envContent).toMatch(/PGAI_TAG=\d+\.\d+\.\d+|PGAI_TAG=0\.0\.0-dev/);
460
+ });
461
+
462
+ test("--tag flag takes priority over pkg.version", () => {
463
+ const testDir = resolve(tempDir, "tag-flag-test");
464
+ fs.mkdirSync(testDir, { recursive: true });
465
+ fs.writeFileSync(resolve(testDir, "docker-compose.yml"), "version: '3'\nservices: {}\n");
466
+
467
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
468
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
469
+ const result = Bun.spawnSync([bunBin, cliPath, "mon", "local-install", "--tag", "v1.2.3-custom", "--db-url", "postgresql://u:p@h:5432/d", "--yes"], {
470
+ env: { ...process.env, PGAI_TAG: undefined },
471
+ cwd: testDir,
472
+ });
473
+
474
+ const envContent = fs.readFileSync(resolve(testDir, ".env"), "utf8");
475
+ expect(envContent).toMatch(/PGAI_TAG=v1\.2\.3-custom/);
476
+
477
+ // Verify stdout confirms the tag being used
478
+ const stdout = new TextDecoder().decode(result.stdout);
479
+ expect(stdout).toMatch(/Using image tag: v1\.2\.3-custom/);
480
+ });
481
+
482
+ test("PGAI_TAG env var is intentionally ignored (Bun auto-loads .env)", () => {
483
+ // Note: We do NOT use process.env.PGAI_TAG because Bun auto-loads .env files,
484
+ // which would cause stale .env values to pollute the environment.
485
+ // Users should use --tag flag to override, not env vars.
486
+ const testDir = resolve(tempDir, "env-var-ignored-test");
487
+ fs.mkdirSync(testDir, { recursive: true });
488
+ fs.writeFileSync(resolve(testDir, "docker-compose.yml"), "version: '3'\nservices: {}\n");
489
+
490
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
491
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
492
+ const result = Bun.spawnSync([bunBin, cliPath, "mon", "local-install", "--db-url", "postgresql://u:p@h:5432/d", "--yes"], {
493
+ env: { ...process.env, PGAI_TAG: "v2.0.0-from-env" },
494
+ cwd: testDir,
495
+ });
496
+
497
+ const envContent = fs.readFileSync(resolve(testDir, ".env"), "utf8");
498
+ // PGAI_TAG env var should be IGNORED - uses pkg.version instead
499
+ expect(envContent).not.toMatch(/PGAI_TAG=v2\.0\.0-from-env/);
500
+ expect(envContent).toMatch(/PGAI_TAG=\d+\.\d+\.\d+|PGAI_TAG=0\.0\.0-dev/);
501
+ });
502
+
503
+ test("existing registry and password are preserved while tag is updated", () => {
504
+ const testDir = resolve(tempDir, "preserve-test");
505
+ fs.mkdirSync(testDir, { recursive: true });
506
+ // Create .env with stale tag but valid registry and password
507
+ fs.writeFileSync(resolve(testDir, ".env"),
508
+ "PGAI_TAG=stale-tag\nPGAI_REGISTRY=my.registry.com\nGF_SECURITY_ADMIN_PASSWORD=secret123\n");
509
+ fs.writeFileSync(resolve(testDir, "docker-compose.yml"), "version: '3'\nservices: {}\n");
510
+
511
+ const cliPath = resolve(import.meta.dir, "..", "bin", "postgres-ai.ts");
512
+ const bunBin = typeof process.execPath === "string" && process.execPath.length > 0 ? process.execPath : "bun";
513
+ const result = Bun.spawnSync([bunBin, cliPath, "mon", "local-install", "--db-url", "postgresql://u:p@h:5432/d", "--yes"], {
514
+ env: { ...process.env, PGAI_TAG: undefined },
515
+ cwd: testDir,
516
+ });
517
+
518
+ const envContent = fs.readFileSync(resolve(testDir, ".env"), "utf8");
519
+
520
+ // Tag should be updated (not stale-tag)
521
+ expect(envContent).not.toMatch(/PGAI_TAG=stale-tag/);
522
+
523
+ // But registry and password should be preserved
524
+ expect(envContent).toMatch(/PGAI_REGISTRY=my\.registry\.com/);
525
+ expect(envContent).toMatch(/GF_SECURITY_ADMIN_PASSWORD=secret123/);
526
+ });
527
+ });