postgresai 0.12.0-beta.6 → 0.14.0-beta.1

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.
@@ -12,9 +12,11 @@ import { promisify } from "util";
12
12
  import * as readline from "readline";
13
13
  import * as http from "https";
14
14
  import { URL } from "url";
15
+ import { Client } from "pg";
15
16
  import { startMcpServer } from "../lib/mcp-server";
16
- import { fetchIssues } from "../lib/issues";
17
+ import { fetchIssues, fetchIssueComments, createIssueComment, fetchIssue } from "../lib/issues";
17
18
  import { resolveBaseUrls } from "../lib/util";
19
+ import { applyInitPlan, buildInitPlan, resolveAdminConnection, resolveMonitoringPassword, verifyInitSetup } from "../lib/init";
18
20
 
19
21
  const execPromise = promisify(exec);
20
22
  const execFilePromise = promisify(execFile);
@@ -59,14 +61,6 @@ interface PathResolution {
59
61
  instancesFile: string;
60
62
  }
61
63
 
62
- /**
63
- * Health check service
64
- */
65
- interface HealthService {
66
- name: string;
67
- url: string;
68
- }
69
-
70
64
  /**
71
65
  * Get configuration from various sources
72
66
  * @param opts - Command line options
@@ -90,6 +84,24 @@ function getConfig(opts: CliOptions): ConfigResult {
90
84
  return { apiKey };
91
85
  }
92
86
 
87
+ // Human-friendly output helper: YAML for TTY by default, JSON when --json or non-TTY
88
+ function printResult(result: unknown, json?: boolean): void {
89
+ if (typeof result === "string") {
90
+ process.stdout.write(result);
91
+ if (!/\n$/.test(result)) console.log();
92
+ return;
93
+ }
94
+ if (json || !process.stdout.isTTY) {
95
+ console.log(JSON.stringify(result, null, 2));
96
+ } else {
97
+ let text = yaml.dump(result as any);
98
+ if (Array.isArray(result)) {
99
+ text = text.replace(/\n- /g, "\n\n- ");
100
+ }
101
+ console.log(text);
102
+ }
103
+ }
104
+
93
105
  const program = new Command();
94
106
 
95
107
  program
@@ -106,6 +118,339 @@ program
106
118
  "UI base URL for browser routes (overrides PGAI_UI_BASE_URL)"
107
119
  );
108
120
 
121
+ program
122
+ .command("init [conn]")
123
+ .description("Create a monitoring user and grant all required permissions (idempotent)")
124
+ .option("--db-url <url>", "PostgreSQL connection URL (admin) to run the setup against (deprecated; pass it as positional arg)")
125
+ .option("-h, --host <host>", "PostgreSQL host (psql-like)")
126
+ .option("-p, --port <port>", "PostgreSQL port (psql-like)")
127
+ .option("-U, --username <username>", "PostgreSQL user (psql-like)")
128
+ .option("-d, --dbname <dbname>", "PostgreSQL database name (psql-like)")
129
+ .option("--admin-password <password>", "Admin connection password (otherwise uses PGPASSWORD if set)")
130
+ .option("--monitoring-user <name>", "Monitoring role name to create/update", "postgres_ai_mon")
131
+ .option("--password <password>", "Monitoring role password (overrides PGAI_MON_PASSWORD)")
132
+ .option("--skip-optional-permissions", "Skip optional permissions (RDS/self-managed extras)", false)
133
+ .option("--verify", "Verify that monitoring role/permissions are in place (no changes)", false)
134
+ .option("--reset-password", "Reset monitoring role password only (no other changes)", false)
135
+ .option("--print-sql", "Print SQL plan and exit (no changes applied)", false)
136
+ .option("--show-secrets", "When printing SQL, do not redact secrets (DANGEROUS)", false)
137
+ .option("--print-password", "Print generated monitoring password (DANGEROUS in CI logs)", false)
138
+ .addHelpText(
139
+ "after",
140
+ [
141
+ "",
142
+ "Examples:",
143
+ " postgresai init postgresql://admin@host:5432/dbname",
144
+ " postgresai init \"dbname=dbname host=host user=admin\"",
145
+ " postgresai init -h host -p 5432 -U admin -d dbname",
146
+ "",
147
+ "Admin password:",
148
+ " --admin-password <password> or PGPASSWORD=... (libpq standard)",
149
+ "",
150
+ "Monitoring password:",
151
+ " --password <password> or PGAI_MON_PASSWORD=... (otherwise auto-generated)",
152
+ " If auto-generated, it is printed only on TTY by default.",
153
+ " To print it in non-interactive mode: --print-password",
154
+ "",
155
+ "Inspect SQL without applying changes:",
156
+ " postgresai init <conn> --print-sql",
157
+ "",
158
+ "Verify setup (no changes):",
159
+ " postgresai init <conn> --verify",
160
+ "",
161
+ "Reset monitoring password only:",
162
+ " postgresai init <conn> --reset-password --password '...'",
163
+ "",
164
+ "Offline SQL plan (no DB connection):",
165
+ " postgresai init --print-sql -d dbname --password '...' --show-secrets",
166
+ ].join("\n")
167
+ )
168
+ .action(async (conn: string | undefined, opts: {
169
+ dbUrl?: string;
170
+ host?: string;
171
+ port?: string;
172
+ username?: string;
173
+ dbname?: string;
174
+ adminPassword?: string;
175
+ monitoringUser: string;
176
+ password?: string;
177
+ skipOptionalPermissions?: boolean;
178
+ verify?: boolean;
179
+ resetPassword?: boolean;
180
+ printSql?: boolean;
181
+ showSecrets?: boolean;
182
+ printPassword?: boolean;
183
+ }, cmd: Command) => {
184
+ if (opts.verify && opts.resetPassword) {
185
+ console.error("✗ Provide only one of --verify or --reset-password");
186
+ process.exitCode = 1;
187
+ return;
188
+ }
189
+ if (opts.verify && opts.printSql) {
190
+ console.error("✗ --verify cannot be combined with --print-sql");
191
+ process.exitCode = 1;
192
+ return;
193
+ }
194
+
195
+ const shouldPrintSql = !!opts.printSql;
196
+ const shouldRedactSecrets = !opts.showSecrets;
197
+ const redactPasswords = (sql: string): string => {
198
+ if (!shouldRedactSecrets) return sql;
199
+ // Replace PASSWORD '<literal>' (handles doubled quotes inside).
200
+ return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
201
+ };
202
+
203
+ // Offline mode: allow printing SQL without providing/using an admin connection.
204
+ // Useful for audits/reviews; caller can provide -d/PGDATABASE and an explicit monitoring password.
205
+ if (!conn && !opts.dbUrl && !opts.host && !opts.port && !opts.username && !opts.adminPassword) {
206
+ if (shouldPrintSql) {
207
+ const database = (opts.dbname ?? process.env.PGDATABASE ?? "postgres").trim();
208
+ const includeOptionalPermissions = !opts.skipOptionalPermissions;
209
+
210
+ // Use explicit password/env if provided; otherwise use a placeholder (will be redacted unless --show-secrets).
211
+ const monPassword =
212
+ (opts.password ?? process.env.PGAI_MON_PASSWORD ?? "CHANGE_ME").toString();
213
+
214
+ const plan = await buildInitPlan({
215
+ database,
216
+ monitoringUser: opts.monitoringUser,
217
+ monitoringPassword: monPassword,
218
+ includeOptionalPermissions,
219
+ roleExists: undefined,
220
+ });
221
+
222
+ console.log("\n--- SQL plan (offline; not connected) ---");
223
+ console.log(`-- database: ${database}`);
224
+ console.log(`-- monitoring user: ${opts.monitoringUser}`);
225
+ console.log(`-- optional permissions: ${includeOptionalPermissions ? "enabled" : "skipped"}`);
226
+ for (const step of plan.steps) {
227
+ console.log(`\n-- ${step.name}${step.optional ? " (optional)" : ""}`);
228
+ console.log(redactPasswords(step.sql));
229
+ }
230
+ console.log("\n--- end SQL plan ---\n");
231
+ if (shouldRedactSecrets) {
232
+ console.log("Note: passwords are redacted in the printed SQL (use --show-secrets to print them).");
233
+ }
234
+ return;
235
+ }
236
+ }
237
+
238
+ let adminConn;
239
+ try {
240
+ adminConn = resolveAdminConnection({
241
+ conn,
242
+ dbUrlFlag: opts.dbUrl,
243
+ // Allow libpq standard env vars as implicit defaults (common UX).
244
+ host: opts.host ?? process.env.PGHOST,
245
+ port: opts.port ?? process.env.PGPORT,
246
+ username: opts.username ?? process.env.PGUSER,
247
+ dbname: opts.dbname ?? process.env.PGDATABASE,
248
+ adminPassword: opts.adminPassword,
249
+ envPassword: process.env.PGPASSWORD,
250
+ });
251
+ } catch (e) {
252
+ const msg = e instanceof Error ? e.message : String(e);
253
+ console.error(`✗ ${msg}`);
254
+ // When connection details are missing, show full init help (options + examples).
255
+ if (typeof msg === "string" && msg.startsWith("Connection is required.")) {
256
+ console.error("");
257
+ cmd.outputHelp({ error: true });
258
+ }
259
+ process.exitCode = 1;
260
+ return;
261
+ }
262
+
263
+ const includeOptionalPermissions = !opts.skipOptionalPermissions;
264
+
265
+ console.log(`Connecting to: ${adminConn.display}`);
266
+ console.log(`Monitoring user: ${opts.monitoringUser}`);
267
+ console.log(`Optional permissions: ${includeOptionalPermissions ? "enabled" : "skipped"}`);
268
+
269
+ // Use native pg client instead of requiring psql to be installed
270
+ const client = new Client(adminConn.clientConfig);
271
+
272
+ try {
273
+ await client.connect();
274
+
275
+ const roleRes = await client.query("select 1 from pg_catalog.pg_roles where rolname = $1", [
276
+ opts.monitoringUser,
277
+ ]);
278
+ const roleExists = (roleRes.rowCount ?? 0) > 0;
279
+
280
+ const dbRes = await client.query("select current_database() as db");
281
+ const database = dbRes.rows?.[0]?.db;
282
+ if (typeof database !== "string" || !database) {
283
+ throw new Error("Failed to resolve current database name");
284
+ }
285
+
286
+ if (opts.verify) {
287
+ const v = await verifyInitSetup({
288
+ client,
289
+ database,
290
+ monitoringUser: opts.monitoringUser,
291
+ includeOptionalPermissions,
292
+ });
293
+ if (v.ok) {
294
+ console.log("✓ init verify: OK");
295
+ if (v.missingOptional.length > 0) {
296
+ console.log("⚠ Optional items missing:");
297
+ for (const m of v.missingOptional) console.log(`- ${m}`);
298
+ }
299
+ return;
300
+ }
301
+ console.error("✗ init verify failed: missing required items");
302
+ for (const m of v.missingRequired) console.error(`- ${m}`);
303
+ if (v.missingOptional.length > 0) {
304
+ console.error("Optional items missing:");
305
+ for (const m of v.missingOptional) console.error(`- ${m}`);
306
+ }
307
+ process.exitCode = 1;
308
+ return;
309
+ }
310
+
311
+ let monPassword: string;
312
+ try {
313
+ const resolved = await resolveMonitoringPassword({
314
+ passwordFlag: opts.password,
315
+ passwordEnv: process.env.PGAI_MON_PASSWORD,
316
+ monitoringUser: opts.monitoringUser,
317
+ });
318
+ monPassword = resolved.password;
319
+ if (resolved.generated) {
320
+ const canPrint = process.stdout.isTTY || !!opts.printPassword;
321
+ if (canPrint) {
322
+ console.log("");
323
+ console.log(`Generated monitoring password for ${opts.monitoringUser} (copy/paste):`);
324
+ console.log(`PGAI_MON_PASSWORD=${monPassword}`);
325
+ console.log("");
326
+ console.log("Store it securely (or rerun with --password / PGAI_MON_PASSWORD to set your own).");
327
+ } else {
328
+ console.error(
329
+ [
330
+ `✗ Monitoring password was auto-generated for ${opts.monitoringUser} but not printed in non-interactive mode.`,
331
+ "",
332
+ "Provide it explicitly:",
333
+ " --password <password> or PGAI_MON_PASSWORD=...",
334
+ "",
335
+ "Or (NOT recommended) print the generated password:",
336
+ " --print-password",
337
+ ].join("\n")
338
+ );
339
+ process.exitCode = 1;
340
+ return;
341
+ }
342
+ }
343
+ } catch (e) {
344
+ const msg = e instanceof Error ? e.message : String(e);
345
+ console.error(`✗ ${msg}`);
346
+ process.exitCode = 1;
347
+ return;
348
+ }
349
+
350
+ const plan = await buildInitPlan({
351
+ database,
352
+ monitoringUser: opts.monitoringUser,
353
+ monitoringPassword: monPassword,
354
+ includeOptionalPermissions,
355
+ roleExists,
356
+ });
357
+
358
+ const effectivePlan = opts.resetPassword
359
+ ? { ...plan, steps: plan.steps.filter((s) => s.name === "01.role") }
360
+ : plan;
361
+
362
+ if (shouldPrintSql) {
363
+ console.log("\n--- SQL plan ---");
364
+ for (const step of effectivePlan.steps) {
365
+ console.log(`\n-- ${step.name}${step.optional ? " (optional)" : ""}`);
366
+ console.log(redactPasswords(step.sql));
367
+ }
368
+ console.log("\n--- end SQL plan ---\n");
369
+ if (shouldRedactSecrets) {
370
+ console.log("Note: passwords are redacted in the printed SQL (use --show-secrets to print them).");
371
+ }
372
+ return;
373
+ }
374
+
375
+ const { applied, skippedOptional } = await applyInitPlan({ client, plan: effectivePlan });
376
+
377
+ console.log(opts.resetPassword ? "✓ init password reset completed" : "✓ init completed");
378
+ if (skippedOptional.length > 0) {
379
+ console.log("⚠ Some optional steps were skipped (not supported or insufficient privileges):");
380
+ for (const s of skippedOptional) console.log(`- ${s}`);
381
+ }
382
+ // Keep output compact but still useful
383
+ if (process.stdout.isTTY) {
384
+ console.log(`Applied ${applied.length} steps`);
385
+ }
386
+ } catch (error) {
387
+ const errAny = error as any;
388
+ let message = "";
389
+ if (error instanceof Error && error.message) {
390
+ message = error.message;
391
+ } else if (errAny && typeof errAny === "object" && typeof errAny.message === "string" && errAny.message) {
392
+ message = errAny.message;
393
+ } else {
394
+ message = String(error);
395
+ }
396
+ if (!message || message === "[object Object]") {
397
+ message = "Unknown error";
398
+ }
399
+ console.error(`✗ init failed: ${message}`);
400
+ // If this was a plan step failure, surface the step name explicitly to help users diagnose quickly.
401
+ const stepMatch =
402
+ typeof message === "string" ? message.match(/Failed at step "([^"]+)":/i) : null;
403
+ const failedStep = stepMatch?.[1];
404
+ if (failedStep) {
405
+ console.error(`Step: ${failedStep}`);
406
+ }
407
+ if (errAny && typeof errAny === "object") {
408
+ if (typeof errAny.code === "string" && errAny.code) {
409
+ console.error(`Error code: ${errAny.code}`);
410
+ }
411
+ if (typeof errAny.detail === "string" && errAny.detail) {
412
+ console.error(`Detail: ${errAny.detail}`);
413
+ }
414
+ if (typeof errAny.hint === "string" && errAny.hint) {
415
+ console.error(`Hint: ${errAny.hint}`);
416
+ }
417
+ }
418
+ if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
419
+ if (errAny.code === "42501") {
420
+ console.error("");
421
+ console.error("Permission error: your admin connection is not allowed to complete the setup.");
422
+ if (failedStep === "01.role") {
423
+ console.error("What failed: create/update the monitoring role (needs CREATEROLE or superuser).");
424
+ } else if (failedStep === "02.permissions") {
425
+ console.error("What failed: grant required permissions / create view / set role search_path.");
426
+ }
427
+ console.error("How to fix:");
428
+ console.error("- Connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges).");
429
+ console.error("- On managed Postgres, use the provider's admin/master user.");
430
+ console.error("Tip: run with --print-sql to review the exact SQL plan.");
431
+ console.error("");
432
+ console.error("Hint: connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges).");
433
+ }
434
+ if (errAny.code === "ECONNREFUSED") {
435
+ console.error("Hint: check host/port and ensure Postgres is reachable from this machine.");
436
+ }
437
+ if (errAny.code === "ENOTFOUND") {
438
+ console.error("Hint: DNS resolution failed; double-check the host name.");
439
+ }
440
+ if (errAny.code === "ETIMEDOUT") {
441
+ console.error("Hint: connection timed out; check network/firewall rules.");
442
+ }
443
+ }
444
+ process.exitCode = 1;
445
+ } finally {
446
+ try {
447
+ await client.end();
448
+ } catch {
449
+ // ignore
450
+ }
451
+ }
452
+ });
453
+
109
454
  /**
110
455
  * Stub function for not implemented commands
111
456
  */
@@ -249,23 +594,308 @@ const mon = program.command("mon").description("monitoring services management")
249
594
  mon
250
595
  .command("quickstart")
251
596
  .description("complete setup (generate config, start monitoring services)")
252
- .option("--demo", "demo mode", false)
253
- .action(async () => {
597
+ .option("--demo", "demo mode with sample database", false)
598
+ .option("--api-key <key>", "Postgres AI API key for automated report uploads")
599
+ .option("--db-url <url>", "PostgreSQL connection URL to monitor")
600
+ .option("-y, --yes", "accept all defaults and skip interactive prompts", false)
601
+ .action(async (opts: { demo: boolean; apiKey?: string; dbUrl?: string; yes: boolean }) => {
602
+ console.log("\n=================================");
603
+ console.log(" PostgresAI Monitoring Quickstart");
604
+ console.log("=================================\n");
605
+ console.log("This will install, configure, and start the monitoring system\n");
606
+
607
+ // Validate conflicting options
608
+ if (opts.demo && opts.dbUrl) {
609
+ console.log("⚠ Both --demo and --db-url provided. Demo mode includes its own database.");
610
+ console.log("⚠ The --db-url will be ignored in demo mode.\n");
611
+ opts.dbUrl = undefined;
612
+ }
613
+
614
+ if (opts.demo && opts.apiKey) {
615
+ console.error("✗ Cannot use --api-key with --demo mode");
616
+ console.error("✗ Demo mode is for testing only and does not support API key integration");
617
+ console.error("\nUse demo mode without API key: postgres-ai mon quickstart --demo");
618
+ console.error("Or use production mode with API key: postgres-ai mon quickstart --api-key=your_key");
619
+ process.exitCode = 1;
620
+ return;
621
+ }
622
+
254
623
  // Check if containers are already running
255
624
  const { running, containers } = checkRunningContainers();
256
625
  if (running) {
257
- console.log(`Monitoring services are already running: ${containers.join(", ")}`);
258
- console.log("Use 'postgres-ai mon restart' to restart them");
626
+ console.log(`⚠ Monitoring services are already running: ${containers.join(", ")}`);
627
+ console.log("Use 'postgres-ai mon restart' to restart them\n");
259
628
  return;
260
629
  }
261
630
 
631
+ // Step 1: API key configuration (only in production mode)
632
+ if (!opts.demo) {
633
+ console.log("Step 1: Postgres AI API Configuration (Optional)");
634
+ console.log("An API key enables automatic upload of PostgreSQL reports to Postgres AI\n");
635
+
636
+ if (opts.apiKey) {
637
+ console.log("Using API key provided via --api-key parameter");
638
+ config.writeConfig({ apiKey: opts.apiKey });
639
+ console.log("✓ API key saved\n");
640
+ } else if (opts.yes) {
641
+ // Auto-yes mode without API key - skip API key setup
642
+ console.log("Auto-yes mode: no API key provided, skipping API key setup");
643
+ console.log("⚠ Reports will be generated locally only");
644
+ console.log("You can add an API key later with: postgres-ai add-key <api_key>\n");
645
+ } else {
646
+ const rl = readline.createInterface({
647
+ input: process.stdin,
648
+ output: process.stdout
649
+ });
650
+
651
+ const question = (prompt: string): Promise<string> =>
652
+ new Promise((resolve) => rl.question(prompt, resolve));
653
+
654
+ try {
655
+ const answer = await question("Do you have a Postgres AI API key? (Y/n): ");
656
+ const proceedWithApiKey = !answer || answer.toLowerCase() === "y";
657
+
658
+ if (proceedWithApiKey) {
659
+ while (true) {
660
+ const inputApiKey = await question("Enter your Postgres AI API key: ");
661
+ const trimmedKey = inputApiKey.trim();
662
+
663
+ if (trimmedKey) {
664
+ config.writeConfig({ apiKey: trimmedKey });
665
+ console.log("✓ API key saved\n");
666
+ break;
667
+ }
668
+
669
+ console.log("⚠ API key cannot be empty");
670
+ const retry = await question("Try again or skip API key setup, retry? (Y/n): ");
671
+ if (retry.toLowerCase() === "n") {
672
+ console.log("⚠ Skipping API key setup - reports will be generated locally only");
673
+ console.log("You can add an API key later with: postgres-ai add-key <api_key>\n");
674
+ break;
675
+ }
676
+ }
677
+ } else {
678
+ console.log("⚠ Skipping API key setup - reports will be generated locally only");
679
+ console.log("You can add an API key later with: postgres-ai add-key <api_key>\n");
680
+ }
681
+ } finally {
682
+ rl.close();
683
+ }
684
+ }
685
+ } else {
686
+ console.log("Step 1: Demo mode - API key configuration skipped");
687
+ console.log("Demo mode is for testing only and does not support API key integration\n");
688
+ }
689
+
690
+ // Step 2: Add PostgreSQL instance (if not demo mode)
691
+ if (!opts.demo) {
692
+ console.log("Step 2: Add PostgreSQL Instance to Monitor\n");
693
+
694
+ // Clear instances.yml in production mode (start fresh)
695
+ const instancesPath = path.resolve(process.cwd(), "instances.yml");
696
+ const emptyInstancesContent = "# PostgreSQL instances to monitor\n# Add your instances using: postgres-ai mon targets add\n\n";
697
+ fs.writeFileSync(instancesPath, emptyInstancesContent, "utf8");
698
+
699
+ if (opts.dbUrl) {
700
+ console.log("Using database URL provided via --db-url parameter");
701
+ console.log(`Adding PostgreSQL instance from: ${opts.dbUrl}\n`);
702
+
703
+ const match = opts.dbUrl.match(/^postgresql:\/\/[^@]+@([^:/]+)/);
704
+ const autoInstanceName = match ? match[1] : "db-instance";
705
+
706
+ const connStr = opts.dbUrl;
707
+ const m = connStr.match(/^postgresql:\/\/([^:]+):([^@]+)@([^:\/]+)(?::(\d+))?\/(.+)$/);
708
+
709
+ if (!m) {
710
+ console.error("✗ Invalid connection string format");
711
+ process.exitCode = 1;
712
+ return;
713
+ }
714
+
715
+ const host = m[3];
716
+ const db = m[5];
717
+ const instanceName = `${host}-${db}`.replace(/[^a-zA-Z0-9-]/g, "-");
718
+
719
+ const body = `- name: ${instanceName}\n conn_str: ${connStr}\n preset_metrics: full\n custom_metrics:\n is_enabled: true\n group: default\n custom_tags:\n env: production\n cluster: default\n node_name: ${instanceName}\n sink_type: ~sink_type~\n`;
720
+ fs.appendFileSync(instancesPath, body, "utf8");
721
+ console.log(`✓ Monitoring target '${instanceName}' added\n`);
722
+
723
+ // Test connection
724
+ console.log("Testing connection to the added instance...");
725
+ try {
726
+ const { Client } = require("pg");
727
+ const client = new Client({ connectionString: connStr });
728
+ await client.connect();
729
+ const result = await client.query("select version();");
730
+ console.log("✓ Connection successful");
731
+ console.log(`${result.rows[0].version}\n`);
732
+ await client.end();
733
+ } catch (error) {
734
+ const message = error instanceof Error ? error.message : String(error);
735
+ console.error(`✗ Connection failed: ${message}\n`);
736
+ }
737
+ } else if (opts.yes) {
738
+ // Auto-yes mode without database URL - skip database setup
739
+ console.log("Auto-yes mode: no database URL provided, skipping database setup");
740
+ console.log("⚠ No PostgreSQL instance added");
741
+ console.log("You can add one later with: postgres-ai mon targets add\n");
742
+ } else {
743
+ const rl = readline.createInterface({
744
+ input: process.stdin,
745
+ output: process.stdout
746
+ });
747
+
748
+ const question = (prompt: string): Promise<string> =>
749
+ new Promise((resolve) => rl.question(prompt, resolve));
750
+
751
+ try {
752
+ console.log("You need to add at least one PostgreSQL instance to monitor");
753
+ const answer = await question("Do you want to add a PostgreSQL instance now? (Y/n): ");
754
+ const proceedWithInstance = !answer || answer.toLowerCase() === "y";
755
+
756
+ if (proceedWithInstance) {
757
+ console.log("\nYou can provide either:");
758
+ console.log(" 1. A full connection string: postgresql://user:pass@host:port/database");
759
+ console.log(" 2. Press Enter to skip for now\n");
760
+
761
+ const connStr = await question("Enter connection string (or press Enter to skip): ");
762
+
763
+ if (connStr.trim()) {
764
+ const m = connStr.match(/^postgresql:\/\/([^:]+):([^@]+)@([^:\/]+)(?::(\d+))?\/(.+)$/);
765
+ if (!m) {
766
+ console.error("✗ Invalid connection string format");
767
+ console.log("⚠ Continuing without adding instance\n");
768
+ } else {
769
+ const host = m[3];
770
+ const db = m[5];
771
+ const instanceName = `${host}-${db}`.replace(/[^a-zA-Z0-9-]/g, "-");
772
+
773
+ const body = `- name: ${instanceName}\n conn_str: ${connStr}\n preset_metrics: full\n custom_metrics:\n is_enabled: true\n group: default\n custom_tags:\n env: production\n cluster: default\n node_name: ${instanceName}\n sink_type: ~sink_type~\n`;
774
+ fs.appendFileSync(instancesPath, body, "utf8");
775
+ console.log(`✓ Monitoring target '${instanceName}' added\n`);
776
+
777
+ // Test connection
778
+ console.log("Testing connection to the added instance...");
779
+ try {
780
+ const { Client } = require("pg");
781
+ const client = new Client({ connectionString: connStr });
782
+ await client.connect();
783
+ const result = await client.query("select version();");
784
+ console.log("✓ Connection successful");
785
+ console.log(`${result.rows[0].version}\n`);
786
+ await client.end();
787
+ } catch (error) {
788
+ const message = error instanceof Error ? error.message : String(error);
789
+ console.error(`✗ Connection failed: ${message}\n`);
790
+ }
791
+ }
792
+ } else {
793
+ console.log("⚠ No PostgreSQL instance added - you can add one later with: postgres-ai mon targets add\n");
794
+ }
795
+ } else {
796
+ console.log("⚠ No PostgreSQL instance added - you can add one later with: postgres-ai mon targets add\n");
797
+ }
798
+ } finally {
799
+ rl.close();
800
+ }
801
+ }
802
+ } else {
803
+ console.log("Step 2: Demo mode enabled - using included demo PostgreSQL database\n");
804
+ }
805
+
806
+ // Step 3: Update configuration
807
+ console.log(opts.demo ? "Step 3: Updating configuration..." : "Step 3: Updating configuration...");
262
808
  const code1 = await runCompose(["run", "--rm", "sources-generator"]);
263
809
  if (code1 !== 0) {
264
810
  process.exitCode = code1;
265
811
  return;
266
812
  }
267
- const code2 = await runCompose(["up", "-d"]);
268
- if (code2 !== 0) process.exitCode = code2;
813
+ console.log(" Configuration updated\n");
814
+
815
+ // Step 4: Ensure Grafana password is configured
816
+ console.log(opts.demo ? "Step 4: Configuring Grafana security..." : "Step 4: Configuring Grafana security...");
817
+ const cfgPath = path.resolve(process.cwd(), ".pgwatch-config");
818
+ let grafanaPassword = "";
819
+
820
+ try {
821
+ if (fs.existsSync(cfgPath)) {
822
+ const stats = fs.statSync(cfgPath);
823
+ if (!stats.isDirectory()) {
824
+ const content = fs.readFileSync(cfgPath, "utf8");
825
+ const match = content.match(/^grafana_password=([^\r\n]+)/m);
826
+ if (match) {
827
+ grafanaPassword = match[1].trim();
828
+ }
829
+ }
830
+ }
831
+
832
+ if (!grafanaPassword) {
833
+ console.log("Generating secure Grafana password...");
834
+ const { stdout: password } = await execPromise("openssl rand -base64 12 | tr -d '\n'");
835
+ grafanaPassword = password.trim();
836
+
837
+ let configContent = "";
838
+ if (fs.existsSync(cfgPath)) {
839
+ const stats = fs.statSync(cfgPath);
840
+ if (!stats.isDirectory()) {
841
+ configContent = fs.readFileSync(cfgPath, "utf8");
842
+ }
843
+ }
844
+
845
+ const lines = configContent.split(/\r?\n/).filter((l) => !/^grafana_password=/.test(l));
846
+ lines.push(`grafana_password=${grafanaPassword}`);
847
+ fs.writeFileSync(cfgPath, lines.filter(Boolean).join("\n") + "\n", "utf8");
848
+ }
849
+
850
+ console.log("✓ Grafana password configured\n");
851
+ } catch (error) {
852
+ console.log("⚠ Could not generate Grafana password automatically");
853
+ console.log("Using default password: demo\n");
854
+ grafanaPassword = "demo";
855
+ }
856
+
857
+ // Step 5: Start services
858
+ console.log(opts.demo ? "Step 5: Starting monitoring services..." : "Step 5: Starting monitoring services...");
859
+ const code2 = await runCompose(["up", "-d", "--force-recreate"]);
860
+ if (code2 !== 0) {
861
+ process.exitCode = code2;
862
+ return;
863
+ }
864
+ console.log("✓ Services started\n");
865
+
866
+ // Final summary
867
+ console.log("=================================");
868
+ console.log(" 🎉 Quickstart setup completed!");
869
+ console.log("=================================\n");
870
+
871
+ console.log("What's running:");
872
+ if (opts.demo) {
873
+ console.log(" ✅ Demo PostgreSQL database (monitoring target)");
874
+ }
875
+ console.log(" ✅ PostgreSQL monitoring infrastructure");
876
+ console.log(" ✅ Grafana dashboards (with secure password)");
877
+ console.log(" ✅ Prometheus metrics storage");
878
+ console.log(" ✅ Flask API backend");
879
+ console.log(" ✅ Automated report generation (every 24h)");
880
+ console.log(" ✅ Host stats monitoring (CPU, memory, disk, I/O)\n");
881
+
882
+ if (!opts.demo) {
883
+ console.log("Next steps:");
884
+ console.log(" • Add more PostgreSQL instances: postgres-ai mon targets add");
885
+ console.log(" • View configured instances: postgres-ai mon targets list");
886
+ console.log(" • Check service health: postgres-ai mon health\n");
887
+ } else {
888
+ console.log("Demo mode next steps:");
889
+ console.log(" • Explore Grafana dashboards at http://localhost:3000");
890
+ console.log(" • Connect to demo database: postgresql://postgres:postgres@localhost:55432/target_database");
891
+ console.log(" • Generate some load on the demo database to see metrics\n");
892
+ }
893
+
894
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
895
+ console.log("🚀 MAIN ACCESS POINT - Start here:");
896
+ console.log(" Grafana Dashboard: http://localhost:3000");
897
+ console.log(` Login: monitor / ${grafanaPassword}`);
898
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
269
899
  });
270
900
 
271
901
  mon
@@ -328,11 +958,13 @@ mon
328
958
  .description("health check for monitoring services")
329
959
  .option("--wait <seconds>", "wait time in seconds for services to become healthy", parseInt, 0)
330
960
  .action(async (opts: { wait: number }) => {
331
- const services: HealthService[] = [
332
- { name: "Grafana", url: "http://localhost:3000/api/health" },
333
- { name: "Prometheus", url: "http://localhost:59090/-/healthy" },
334
- { name: "PGWatch (Postgres)", url: "http://localhost:58080/health" },
335
- { name: "PGWatch (Prometheus)", url: "http://localhost:58089/health" },
961
+ const services = [
962
+ { name: "Grafana", container: "grafana-with-datasources" },
963
+ { name: "Prometheus", container: "sink-prometheus" },
964
+ { name: "PGWatch (Postgres)", container: "pgwatch-postgres" },
965
+ { name: "PGWatch (Prometheus)", container: "pgwatch-prometheus" },
966
+ { name: "Target DB", container: "target-db" },
967
+ { name: "Sink Postgres", container: "sink-postgres" },
336
968
  ];
337
969
 
338
970
  const waitTime = opts.wait || 0;
@@ -350,20 +982,16 @@ mon
350
982
  allHealthy = true;
351
983
  for (const service of services) {
352
984
  try {
353
- // Use native fetch instead of requiring curl to be installed
354
- const controller = new AbortController();
355
- const timeoutId = setTimeout(() => controller.abort(), 5000);
985
+ const { execSync } = require("child_process");
986
+ const status = execSync(`docker inspect -f '{{.State.Status}}' ${service.container} 2>/dev/null`, {
987
+ encoding: 'utf8',
988
+ stdio: ['pipe', 'pipe', 'pipe']
989
+ }).trim();
356
990
 
357
- const response = await fetch(service.url, {
358
- signal: controller.signal,
359
- method: 'GET',
360
- });
361
- clearTimeout(timeoutId);
362
-
363
- if (response.status === 200) {
991
+ if (status === 'running') {
364
992
  console.log(`✓ ${service.name}: healthy`);
365
993
  } else {
366
- console.log(`✗ ${service.name}: unhealthy (HTTP ${response.status})`);
994
+ console.log(`✗ ${service.name}: unhealthy (status: ${status})`);
367
995
  allHealthy = false;
368
996
  }
369
997
  } catch (error) {
@@ -1167,6 +1795,24 @@ mon
1167
1795
  console.log("");
1168
1796
  });
1169
1797
 
1798
+ /**
1799
+ * Interpret escape sequences in a string (e.g., \n -> newline)
1800
+ * Note: In regex, to match literal backslash-n, we need \\n in the pattern
1801
+ * which requires \\\\n in the JavaScript string literal
1802
+ */
1803
+ function interpretEscapes(str: string): string {
1804
+ // First handle double backslashes by temporarily replacing them
1805
+ // Then handle other escapes, then restore double backslashes as single
1806
+ return str
1807
+ .replace(/\\\\/g, '\x00') // Temporarily mark double backslashes
1808
+ .replace(/\\n/g, '\n') // Match literal backslash-n (\\\\n in JS string -> \\n in regex -> matches \n)
1809
+ .replace(/\\t/g, '\t')
1810
+ .replace(/\\r/g, '\r')
1811
+ .replace(/\\"/g, '"')
1812
+ .replace(/\\'/g, "'")
1813
+ .replace(/\x00/g, '\\'); // Restore double backslashes as single
1814
+ }
1815
+
1170
1816
  // Issues management
1171
1817
  const issues = program.command("issues").description("issues management");
1172
1818
 
@@ -1174,7 +1820,8 @@ issues
1174
1820
  .command("list")
1175
1821
  .description("list issues")
1176
1822
  .option("--debug", "enable debug output")
1177
- .action(async (opts: { debug?: boolean }) => {
1823
+ .option("--json", "output raw JSON")
1824
+ .action(async (opts: { debug?: boolean; json?: boolean }) => {
1178
1825
  try {
1179
1826
  const rootOpts = program.opts<CliOptions>();
1180
1827
  const cfg = config.readConfig();
@@ -1188,12 +1835,96 @@ issues
1188
1835
  const { apiBaseUrl } = resolveBaseUrls(rootOpts, cfg);
1189
1836
 
1190
1837
  const result = await fetchIssues({ apiKey, apiBaseUrl, debug: !!opts.debug });
1191
- if (typeof result === "string") {
1192
- process.stdout.write(result);
1193
- if (!/\n$/.test(result)) console.log();
1194
- } else {
1195
- console.log(JSON.stringify(result, null, 2));
1838
+ const trimmed = Array.isArray(result)
1839
+ ? (result as any[]).map((r) => ({
1840
+ id: (r as any).id,
1841
+ title: (r as any).title,
1842
+ status: (r as any).status,
1843
+ created_at: (r as any).created_at,
1844
+ }))
1845
+ : result;
1846
+ printResult(trimmed, opts.json);
1847
+ } catch (err) {
1848
+ const message = err instanceof Error ? err.message : String(err);
1849
+ console.error(message);
1850
+ process.exitCode = 1;
1851
+ }
1852
+ });
1853
+
1854
+ issues
1855
+ .command("view <issueId>")
1856
+ .description("view issue details and comments")
1857
+ .option("--debug", "enable debug output")
1858
+ .option("--json", "output raw JSON")
1859
+ .action(async (issueId: string, opts: { debug?: boolean; json?: boolean }) => {
1860
+ try {
1861
+ const rootOpts = program.opts<CliOptions>();
1862
+ const cfg = config.readConfig();
1863
+ const { apiKey } = getConfig(rootOpts);
1864
+ if (!apiKey) {
1865
+ console.error("API key is required. Run 'pgai auth' first or set --api-key.");
1866
+ process.exitCode = 1;
1867
+ return;
1868
+ }
1869
+
1870
+ const { apiBaseUrl } = resolveBaseUrls(rootOpts, cfg);
1871
+
1872
+ const issue = await fetchIssue({ apiKey, apiBaseUrl, issueId, debug: !!opts.debug });
1873
+ if (!issue) {
1874
+ console.error("Issue not found");
1875
+ process.exitCode = 1;
1876
+ return;
1196
1877
  }
1878
+
1879
+ const comments = await fetchIssueComments({ apiKey, apiBaseUrl, issueId, debug: !!opts.debug });
1880
+ const combined = { issue, comments };
1881
+ printResult(combined, opts.json);
1882
+ } catch (err) {
1883
+ const message = err instanceof Error ? err.message : String(err);
1884
+ console.error(message);
1885
+ process.exitCode = 1;
1886
+ }
1887
+ });
1888
+
1889
+ issues
1890
+ .command("post_comment <issueId> <content>")
1891
+ .description("post a new comment to an issue")
1892
+ .option("--parent <uuid>", "parent comment id")
1893
+ .option("--debug", "enable debug output")
1894
+ .option("--json", "output raw JSON")
1895
+ .action(async (issueId: string, content: string, opts: { parent?: string; debug?: boolean; json?: boolean }) => {
1896
+ try {
1897
+ // Interpret escape sequences in content (e.g., \n -> newline)
1898
+ if (opts.debug) {
1899
+ // eslint-disable-next-line no-console
1900
+ console.log(`Debug: Original content: ${JSON.stringify(content)}`);
1901
+ }
1902
+ content = interpretEscapes(content);
1903
+ if (opts.debug) {
1904
+ // eslint-disable-next-line no-console
1905
+ console.log(`Debug: Interpreted content: ${JSON.stringify(content)}`);
1906
+ }
1907
+
1908
+ const rootOpts = program.opts<CliOptions>();
1909
+ const cfg = config.readConfig();
1910
+ const { apiKey } = getConfig(rootOpts);
1911
+ if (!apiKey) {
1912
+ console.error("API key is required. Run 'pgai auth' first or set --api-key.");
1913
+ process.exitCode = 1;
1914
+ return;
1915
+ }
1916
+
1917
+ const { apiBaseUrl } = resolveBaseUrls(rootOpts, cfg);
1918
+
1919
+ const result = await createIssueComment({
1920
+ apiKey,
1921
+ apiBaseUrl,
1922
+ issueId,
1923
+ content,
1924
+ parentCommentId: opts.parent,
1925
+ debug: !!opts.debug,
1926
+ });
1927
+ printResult(result, opts.json);
1197
1928
  } catch (err) {
1198
1929
  const message = err instanceof Error ? err.message : String(err);
1199
1930
  console.error(message);