postgresai 0.12.0-beta.6 → 0.14.0-dev.10

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.
@@ -49,6 +49,7 @@ const url_1 = require("url");
49
49
  const mcp_server_1 = require("../lib/mcp-server");
50
50
  const issues_1 = require("../lib/issues");
51
51
  const util_2 = require("../lib/util");
52
+ const init_1 = require("../lib/init");
52
53
  const execPromise = (0, util_1.promisify)(child_process_1.exec);
53
54
  const execFilePromise = (0, util_1.promisify)(child_process_1.execFile);
54
55
  /**
@@ -71,6 +72,25 @@ function getConfig(opts) {
71
72
  }
72
73
  return { apiKey };
73
74
  }
75
+ // Human-friendly output helper: YAML for TTY by default, JSON when --json or non-TTY
76
+ function printResult(result, json) {
77
+ if (typeof result === "string") {
78
+ process.stdout.write(result);
79
+ if (!/\n$/.test(result))
80
+ console.log();
81
+ return;
82
+ }
83
+ if (json || !process.stdout.isTTY) {
84
+ console.log(JSON.stringify(result, null, 2));
85
+ }
86
+ else {
87
+ let text = yaml.dump(result);
88
+ if (Array.isArray(result)) {
89
+ text = text.replace(/\n- /g, "\n\n- ");
90
+ }
91
+ console.log(text);
92
+ }
93
+ }
74
94
  const program = new commander_1.Command();
75
95
  program
76
96
  .name("postgres-ai")
@@ -79,6 +99,163 @@ program
79
99
  .option("--api-key <key>", "API key (overrides PGAI_API_KEY)")
80
100
  .option("--api-base-url <url>", "API base URL for backend RPC (overrides PGAI_API_BASE_URL)")
81
101
  .option("--ui-base-url <url>", "UI base URL for browser routes (overrides PGAI_UI_BASE_URL)");
102
+ program
103
+ .command("init [conn]")
104
+ .description("Create a monitoring user and grant all required permissions (idempotent)")
105
+ .option("--db-url <url>", "PostgreSQL connection URL (admin) to run the setup against (deprecated; pass it as positional arg)")
106
+ .option("-h, --host <host>", "PostgreSQL host (psql-like)")
107
+ .option("-p, --port <port>", "PostgreSQL port (psql-like)")
108
+ .option("-U, --username <username>", "PostgreSQL user (psql-like)")
109
+ .option("-d, --dbname <dbname>", "PostgreSQL database name (psql-like)")
110
+ .option("--admin-password <password>", "Admin connection password (otherwise uses PGPASSWORD if set)")
111
+ .option("--monitoring-user <name>", "Monitoring role name to create/update", "postgres_ai_mon")
112
+ .option("--password <password>", "Monitoring role password (overrides PGAI_MON_PASSWORD)")
113
+ .option("--skip-optional-permissions", "Skip optional permissions (RDS/self-managed extras)", false)
114
+ .option("--print-sql", "Print SQL steps before applying (passwords redacted by default)", false)
115
+ .option("--show-secrets", "When printing SQL, do not redact secrets (DANGEROUS)", false)
116
+ .option("--dry-run", "Print SQL steps and exit without applying changes", false)
117
+ .action(async (conn, opts) => {
118
+ let adminConn;
119
+ try {
120
+ adminConn = (0, init_1.resolveAdminConnection)({
121
+ conn,
122
+ dbUrlFlag: opts.dbUrl,
123
+ host: opts.host,
124
+ port: opts.port,
125
+ username: opts.username,
126
+ dbname: opts.dbname,
127
+ adminPassword: opts.adminPassword,
128
+ envPassword: process.env.PGPASSWORD,
129
+ });
130
+ }
131
+ catch (e) {
132
+ const msg = e instanceof Error ? e.message : String(e);
133
+ console.error(`✗ ${msg}`);
134
+ process.exitCode = 1;
135
+ return;
136
+ }
137
+ const includeOptionalPermissions = !opts.skipOptionalPermissions;
138
+ console.log(`Connecting to: ${adminConn.display}`);
139
+ console.log(`Monitoring user: ${opts.monitoringUser}`);
140
+ console.log(`Optional permissions: ${includeOptionalPermissions ? "enabled" : "skipped"}`);
141
+ const shouldPrintSql = !!opts.printSql || !!opts.dryRun;
142
+ // Use native pg client instead of requiring psql to be installed
143
+ const { Client } = require("pg");
144
+ const client = new Client(adminConn.clientConfig);
145
+ try {
146
+ await client.connect();
147
+ const roleRes = await client.query("select 1 from pg_catalog.pg_roles where rolname = $1", [
148
+ opts.monitoringUser,
149
+ ]);
150
+ const roleExists = roleRes.rowCount > 0;
151
+ const dbRes = await client.query("select current_database() as db");
152
+ const database = dbRes.rows?.[0]?.db;
153
+ if (typeof database !== "string" || !database) {
154
+ throw new Error("Failed to resolve current database name");
155
+ }
156
+ let monPassword;
157
+ try {
158
+ const resolved = await (0, init_1.resolveMonitoringPassword)({
159
+ passwordFlag: opts.password,
160
+ passwordEnv: process.env.PGAI_MON_PASSWORD,
161
+ monitoringUser: opts.monitoringUser,
162
+ });
163
+ monPassword = resolved.password;
164
+ if (resolved.generated) {
165
+ console.log(`Generated password for monitoring user ${opts.monitoringUser}: ${monPassword}`);
166
+ console.log("Store it securely (or rerun with --password / PGAI_MON_PASSWORD to set your own).");
167
+ }
168
+ }
169
+ catch (e) {
170
+ const msg = e instanceof Error ? e.message : String(e);
171
+ console.error(`✗ ${msg}`);
172
+ process.exitCode = 1;
173
+ return;
174
+ }
175
+ const plan = await (0, init_1.buildInitPlan)({
176
+ database,
177
+ monitoringUser: opts.monitoringUser,
178
+ monitoringPassword: monPassword,
179
+ includeOptionalPermissions,
180
+ roleExists,
181
+ });
182
+ if (shouldPrintSql) {
183
+ const redact = !opts.showSecrets;
184
+ const redactPasswords = (sql) => {
185
+ if (!redact)
186
+ return sql;
187
+ // Replace PASSWORD '<literal>' (handles doubled quotes inside).
188
+ return sql.replace(/password\s+'(?:''|[^'])*'/gi, "password '<redacted>'");
189
+ };
190
+ console.log("\n--- SQL plan ---");
191
+ for (const step of plan.steps) {
192
+ console.log(`\n-- ${step.name}${step.optional ? " (optional)" : ""}`);
193
+ console.log(redactPasswords(step.sql));
194
+ }
195
+ console.log("\n--- end SQL plan ---\n");
196
+ if (redact) {
197
+ console.log("Note: passwords are redacted in the printed SQL (use --show-secrets to print them).");
198
+ }
199
+ }
200
+ if (opts.dryRun) {
201
+ console.log("✓ dry-run completed (no changes were applied)");
202
+ return;
203
+ }
204
+ const { applied, skippedOptional } = await (0, init_1.applyInitPlan)({ client, plan });
205
+ console.log("✓ init completed");
206
+ if (skippedOptional.length > 0) {
207
+ console.log("⚠ Some optional steps were skipped (not supported or insufficient privileges):");
208
+ for (const s of skippedOptional)
209
+ console.log(`- ${s}`);
210
+ }
211
+ // Keep output compact but still useful
212
+ if (process.stdout.isTTY) {
213
+ console.log(`Applied ${applied.length} steps`);
214
+ }
215
+ }
216
+ catch (error) {
217
+ const errAny = error;
218
+ let message = "";
219
+ if (error instanceof Error && error.message) {
220
+ message = error.message;
221
+ }
222
+ else if (errAny && typeof errAny === "object" && typeof errAny.message === "string" && errAny.message) {
223
+ message = errAny.message;
224
+ }
225
+ else {
226
+ message = String(error);
227
+ }
228
+ if (!message || message === "[object Object]") {
229
+ message = "Unknown error";
230
+ }
231
+ console.error(`✗ init failed: ${message}`);
232
+ if (errAny && typeof errAny === "object") {
233
+ if (typeof errAny.code === "string" && errAny.code) {
234
+ console.error(`Error code: ${errAny.code}`);
235
+ }
236
+ if (typeof errAny.detail === "string" && errAny.detail) {
237
+ console.error(`Detail: ${errAny.detail}`);
238
+ }
239
+ if (typeof errAny.hint === "string" && errAny.hint) {
240
+ console.error(`Hint: ${errAny.hint}`);
241
+ }
242
+ }
243
+ if (errAny && typeof errAny === "object" && typeof errAny.code === "string") {
244
+ if (errAny.code === "42501") {
245
+ console.error("Hint: connect as a superuser (or a role with CREATEROLE and sufficient GRANT privileges).");
246
+ }
247
+ }
248
+ process.exitCode = 1;
249
+ }
250
+ finally {
251
+ try {
252
+ await client.end();
253
+ }
254
+ catch {
255
+ // ignore
256
+ }
257
+ }
258
+ });
82
259
  /**
83
260
  * Stub function for not implemented commands
84
261
  */
@@ -206,23 +383,284 @@ const mon = program.command("mon").description("monitoring services management")
206
383
  mon
207
384
  .command("quickstart")
208
385
  .description("complete setup (generate config, start monitoring services)")
209
- .option("--demo", "demo mode", false)
210
- .action(async () => {
386
+ .option("--demo", "demo mode with sample database", false)
387
+ .option("--api-key <key>", "Postgres AI API key for automated report uploads")
388
+ .option("--db-url <url>", "PostgreSQL connection URL to monitor")
389
+ .option("-y, --yes", "accept all defaults and skip interactive prompts", false)
390
+ .action(async (opts) => {
391
+ console.log("\n=================================");
392
+ console.log(" PostgresAI Monitoring Quickstart");
393
+ console.log("=================================\n");
394
+ console.log("This will install, configure, and start the monitoring system\n");
395
+ // Validate conflicting options
396
+ if (opts.demo && opts.dbUrl) {
397
+ console.log("⚠ Both --demo and --db-url provided. Demo mode includes its own database.");
398
+ console.log("⚠ The --db-url will be ignored in demo mode.\n");
399
+ opts.dbUrl = undefined;
400
+ }
401
+ if (opts.demo && opts.apiKey) {
402
+ console.error("✗ Cannot use --api-key with --demo mode");
403
+ console.error("✗ Demo mode is for testing only and does not support API key integration");
404
+ console.error("\nUse demo mode without API key: postgres-ai mon quickstart --demo");
405
+ console.error("Or use production mode with API key: postgres-ai mon quickstart --api-key=your_key");
406
+ process.exitCode = 1;
407
+ return;
408
+ }
211
409
  // Check if containers are already running
212
410
  const { running, containers } = checkRunningContainers();
213
411
  if (running) {
214
- console.log(`Monitoring services are already running: ${containers.join(", ")}`);
215
- console.log("Use 'postgres-ai mon restart' to restart them");
412
+ console.log(`⚠ Monitoring services are already running: ${containers.join(", ")}`);
413
+ console.log("Use 'postgres-ai mon restart' to restart them\n");
216
414
  return;
217
415
  }
416
+ // Step 1: API key configuration (only in production mode)
417
+ if (!opts.demo) {
418
+ console.log("Step 1: Postgres AI API Configuration (Optional)");
419
+ console.log("An API key enables automatic upload of PostgreSQL reports to Postgres AI\n");
420
+ if (opts.apiKey) {
421
+ console.log("Using API key provided via --api-key parameter");
422
+ config.writeConfig({ apiKey: opts.apiKey });
423
+ console.log("✓ API key saved\n");
424
+ }
425
+ else if (opts.yes) {
426
+ // Auto-yes mode without API key - skip API key setup
427
+ console.log("Auto-yes mode: no API key provided, skipping API key setup");
428
+ console.log("⚠ Reports will be generated locally only");
429
+ console.log("You can add an API key later with: postgres-ai add-key <api_key>\n");
430
+ }
431
+ else {
432
+ const rl = readline.createInterface({
433
+ input: process.stdin,
434
+ output: process.stdout
435
+ });
436
+ const question = (prompt) => new Promise((resolve) => rl.question(prompt, resolve));
437
+ try {
438
+ const answer = await question("Do you have a Postgres AI API key? (Y/n): ");
439
+ const proceedWithApiKey = !answer || answer.toLowerCase() === "y";
440
+ if (proceedWithApiKey) {
441
+ while (true) {
442
+ const inputApiKey = await question("Enter your Postgres AI API key: ");
443
+ const trimmedKey = inputApiKey.trim();
444
+ if (trimmedKey) {
445
+ config.writeConfig({ apiKey: trimmedKey });
446
+ console.log("✓ API key saved\n");
447
+ break;
448
+ }
449
+ console.log("⚠ API key cannot be empty");
450
+ const retry = await question("Try again or skip API key setup, retry? (Y/n): ");
451
+ if (retry.toLowerCase() === "n") {
452
+ console.log("⚠ Skipping API key setup - reports will be generated locally only");
453
+ console.log("You can add an API key later with: postgres-ai add-key <api_key>\n");
454
+ break;
455
+ }
456
+ }
457
+ }
458
+ else {
459
+ console.log("⚠ Skipping API key setup - reports will be generated locally only");
460
+ console.log("You can add an API key later with: postgres-ai add-key <api_key>\n");
461
+ }
462
+ }
463
+ finally {
464
+ rl.close();
465
+ }
466
+ }
467
+ }
468
+ else {
469
+ console.log("Step 1: Demo mode - API key configuration skipped");
470
+ console.log("Demo mode is for testing only and does not support API key integration\n");
471
+ }
472
+ // Step 2: Add PostgreSQL instance (if not demo mode)
473
+ if (!opts.demo) {
474
+ console.log("Step 2: Add PostgreSQL Instance to Monitor\n");
475
+ // Clear instances.yml in production mode (start fresh)
476
+ const instancesPath = path.resolve(process.cwd(), "instances.yml");
477
+ const emptyInstancesContent = "# PostgreSQL instances to monitor\n# Add your instances using: postgres-ai mon targets add\n\n";
478
+ fs.writeFileSync(instancesPath, emptyInstancesContent, "utf8");
479
+ if (opts.dbUrl) {
480
+ console.log("Using database URL provided via --db-url parameter");
481
+ console.log(`Adding PostgreSQL instance from: ${opts.dbUrl}\n`);
482
+ const match = opts.dbUrl.match(/^postgresql:\/\/[^@]+@([^:/]+)/);
483
+ const autoInstanceName = match ? match[1] : "db-instance";
484
+ const connStr = opts.dbUrl;
485
+ const m = connStr.match(/^postgresql:\/\/([^:]+):([^@]+)@([^:\/]+)(?::(\d+))?\/(.+)$/);
486
+ if (!m) {
487
+ console.error("✗ Invalid connection string format");
488
+ process.exitCode = 1;
489
+ return;
490
+ }
491
+ const host = m[3];
492
+ const db = m[5];
493
+ const instanceName = `${host}-${db}`.replace(/[^a-zA-Z0-9-]/g, "-");
494
+ 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`;
495
+ fs.appendFileSync(instancesPath, body, "utf8");
496
+ console.log(`✓ Monitoring target '${instanceName}' added\n`);
497
+ // Test connection
498
+ console.log("Testing connection to the added instance...");
499
+ try {
500
+ const { Client } = require("pg");
501
+ const client = new Client({ connectionString: connStr });
502
+ await client.connect();
503
+ const result = await client.query("select version();");
504
+ console.log("✓ Connection successful");
505
+ console.log(`${result.rows[0].version}\n`);
506
+ await client.end();
507
+ }
508
+ catch (error) {
509
+ const message = error instanceof Error ? error.message : String(error);
510
+ console.error(`✗ Connection failed: ${message}\n`);
511
+ }
512
+ }
513
+ else if (opts.yes) {
514
+ // Auto-yes mode without database URL - skip database setup
515
+ console.log("Auto-yes mode: no database URL provided, skipping database setup");
516
+ console.log("⚠ No PostgreSQL instance added");
517
+ console.log("You can add one later with: postgres-ai mon targets add\n");
518
+ }
519
+ else {
520
+ const rl = readline.createInterface({
521
+ input: process.stdin,
522
+ output: process.stdout
523
+ });
524
+ const question = (prompt) => new Promise((resolve) => rl.question(prompt, resolve));
525
+ try {
526
+ console.log("You need to add at least one PostgreSQL instance to monitor");
527
+ const answer = await question("Do you want to add a PostgreSQL instance now? (Y/n): ");
528
+ const proceedWithInstance = !answer || answer.toLowerCase() === "y";
529
+ if (proceedWithInstance) {
530
+ console.log("\nYou can provide either:");
531
+ console.log(" 1. A full connection string: postgresql://user:pass@host:port/database");
532
+ console.log(" 2. Press Enter to skip for now\n");
533
+ const connStr = await question("Enter connection string (or press Enter to skip): ");
534
+ if (connStr.trim()) {
535
+ const m = connStr.match(/^postgresql:\/\/([^:]+):([^@]+)@([^:\/]+)(?::(\d+))?\/(.+)$/);
536
+ if (!m) {
537
+ console.error("✗ Invalid connection string format");
538
+ console.log("⚠ Continuing without adding instance\n");
539
+ }
540
+ else {
541
+ const host = m[3];
542
+ const db = m[5];
543
+ const instanceName = `${host}-${db}`.replace(/[^a-zA-Z0-9-]/g, "-");
544
+ 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`;
545
+ fs.appendFileSync(instancesPath, body, "utf8");
546
+ console.log(`✓ Monitoring target '${instanceName}' added\n`);
547
+ // Test connection
548
+ console.log("Testing connection to the added instance...");
549
+ try {
550
+ const { Client } = require("pg");
551
+ const client = new Client({ connectionString: connStr });
552
+ await client.connect();
553
+ const result = await client.query("select version();");
554
+ console.log("✓ Connection successful");
555
+ console.log(`${result.rows[0].version}\n`);
556
+ await client.end();
557
+ }
558
+ catch (error) {
559
+ const message = error instanceof Error ? error.message : String(error);
560
+ console.error(`✗ Connection failed: ${message}\n`);
561
+ }
562
+ }
563
+ }
564
+ else {
565
+ console.log("⚠ No PostgreSQL instance added - you can add one later with: postgres-ai mon targets add\n");
566
+ }
567
+ }
568
+ else {
569
+ console.log("⚠ No PostgreSQL instance added - you can add one later with: postgres-ai mon targets add\n");
570
+ }
571
+ }
572
+ finally {
573
+ rl.close();
574
+ }
575
+ }
576
+ }
577
+ else {
578
+ console.log("Step 2: Demo mode enabled - using included demo PostgreSQL database\n");
579
+ }
580
+ // Step 3: Update configuration
581
+ console.log(opts.demo ? "Step 3: Updating configuration..." : "Step 3: Updating configuration...");
218
582
  const code1 = await runCompose(["run", "--rm", "sources-generator"]);
219
583
  if (code1 !== 0) {
220
584
  process.exitCode = code1;
221
585
  return;
222
586
  }
223
- const code2 = await runCompose(["up", "-d"]);
224
- if (code2 !== 0)
587
+ console.log(" Configuration updated\n");
588
+ // Step 4: Ensure Grafana password is configured
589
+ console.log(opts.demo ? "Step 4: Configuring Grafana security..." : "Step 4: Configuring Grafana security...");
590
+ const cfgPath = path.resolve(process.cwd(), ".pgwatch-config");
591
+ let grafanaPassword = "";
592
+ try {
593
+ if (fs.existsSync(cfgPath)) {
594
+ const stats = fs.statSync(cfgPath);
595
+ if (!stats.isDirectory()) {
596
+ const content = fs.readFileSync(cfgPath, "utf8");
597
+ const match = content.match(/^grafana_password=([^\r\n]+)/m);
598
+ if (match) {
599
+ grafanaPassword = match[1].trim();
600
+ }
601
+ }
602
+ }
603
+ if (!grafanaPassword) {
604
+ console.log("Generating secure Grafana password...");
605
+ const { stdout: password } = await execPromise("openssl rand -base64 12 | tr -d '\n'");
606
+ grafanaPassword = password.trim();
607
+ let configContent = "";
608
+ if (fs.existsSync(cfgPath)) {
609
+ const stats = fs.statSync(cfgPath);
610
+ if (!stats.isDirectory()) {
611
+ configContent = fs.readFileSync(cfgPath, "utf8");
612
+ }
613
+ }
614
+ const lines = configContent.split(/\r?\n/).filter((l) => !/^grafana_password=/.test(l));
615
+ lines.push(`grafana_password=${grafanaPassword}`);
616
+ fs.writeFileSync(cfgPath, lines.filter(Boolean).join("\n") + "\n", "utf8");
617
+ }
618
+ console.log("✓ Grafana password configured\n");
619
+ }
620
+ catch (error) {
621
+ console.log("⚠ Could not generate Grafana password automatically");
622
+ console.log("Using default password: demo\n");
623
+ grafanaPassword = "demo";
624
+ }
625
+ // Step 5: Start services
626
+ console.log(opts.demo ? "Step 5: Starting monitoring services..." : "Step 5: Starting monitoring services...");
627
+ const code2 = await runCompose(["up", "-d", "--force-recreate"]);
628
+ if (code2 !== 0) {
225
629
  process.exitCode = code2;
630
+ return;
631
+ }
632
+ console.log("✓ Services started\n");
633
+ // Final summary
634
+ console.log("=================================");
635
+ console.log(" 🎉 Quickstart setup completed!");
636
+ console.log("=================================\n");
637
+ console.log("What's running:");
638
+ if (opts.demo) {
639
+ console.log(" ✅ Demo PostgreSQL database (monitoring target)");
640
+ }
641
+ console.log(" ✅ PostgreSQL monitoring infrastructure");
642
+ console.log(" ✅ Grafana dashboards (with secure password)");
643
+ console.log(" ✅ Prometheus metrics storage");
644
+ console.log(" ✅ Flask API backend");
645
+ console.log(" ✅ Automated report generation (every 24h)");
646
+ console.log(" ✅ Host stats monitoring (CPU, memory, disk, I/O)\n");
647
+ if (!opts.demo) {
648
+ console.log("Next steps:");
649
+ console.log(" • Add more PostgreSQL instances: postgres-ai mon targets add");
650
+ console.log(" • View configured instances: postgres-ai mon targets list");
651
+ console.log(" • Check service health: postgres-ai mon health\n");
652
+ }
653
+ else {
654
+ console.log("Demo mode next steps:");
655
+ console.log(" • Explore Grafana dashboards at http://localhost:3000");
656
+ console.log(" • Connect to demo database: postgresql://postgres:postgres@localhost:55432/target_database");
657
+ console.log(" • Generate some load on the demo database to see metrics\n");
658
+ }
659
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
660
+ console.log("🚀 MAIN ACCESS POINT - Start here:");
661
+ console.log(" Grafana Dashboard: http://localhost:3000");
662
+ console.log(` Login: monitor / ${grafanaPassword}`);
663
+ console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n");
226
664
  });
227
665
  mon
228
666
  .command("start")
@@ -289,10 +727,12 @@ mon
289
727
  .option("--wait <seconds>", "wait time in seconds for services to become healthy", parseInt, 0)
290
728
  .action(async (opts) => {
291
729
  const services = [
292
- { name: "Grafana", url: "http://localhost:3000/api/health" },
293
- { name: "Prometheus", url: "http://localhost:59090/-/healthy" },
294
- { name: "PGWatch (Postgres)", url: "http://localhost:58080/health" },
295
- { name: "PGWatch (Prometheus)", url: "http://localhost:58089/health" },
730
+ { name: "Grafana", container: "grafana-with-datasources" },
731
+ { name: "Prometheus", container: "sink-prometheus" },
732
+ { name: "PGWatch (Postgres)", container: "pgwatch-postgres" },
733
+ { name: "PGWatch (Prometheus)", container: "pgwatch-prometheus" },
734
+ { name: "Target DB", container: "target-db" },
735
+ { name: "Sink Postgres", container: "sink-postgres" },
296
736
  ];
297
737
  const waitTime = opts.wait || 0;
298
738
  const maxAttempts = waitTime > 0 ? Math.ceil(waitTime / 5) : 1;
@@ -306,19 +746,16 @@ mon
306
746
  allHealthy = true;
307
747
  for (const service of services) {
308
748
  try {
309
- // Use native fetch instead of requiring curl to be installed
310
- const controller = new AbortController();
311
- const timeoutId = setTimeout(() => controller.abort(), 5000);
312
- const response = await fetch(service.url, {
313
- signal: controller.signal,
314
- method: 'GET',
315
- });
316
- clearTimeout(timeoutId);
317
- if (response.status === 200) {
749
+ const { execSync } = require("child_process");
750
+ const status = execSync(`docker inspect -f '{{.State.Status}}' ${service.container} 2>/dev/null`, {
751
+ encoding: 'utf8',
752
+ stdio: ['pipe', 'pipe', 'pipe']
753
+ }).trim();
754
+ if (status === 'running') {
318
755
  console.log(`✓ ${service.name}: healthy`);
319
756
  }
320
757
  else {
321
- console.log(`✗ ${service.name}: unhealthy (HTTP ${response.status})`);
758
+ console.log(`✗ ${service.name}: unhealthy (status: ${status})`);
322
759
  allHealthy = false;
323
760
  }
324
761
  }
@@ -1041,12 +1478,30 @@ mon
1041
1478
  console.log(` Password: ${password}`);
1042
1479
  console.log("");
1043
1480
  });
1481
+ /**
1482
+ * Interpret escape sequences in a string (e.g., \n -> newline)
1483
+ * Note: In regex, to match literal backslash-n, we need \\n in the pattern
1484
+ * which requires \\\\n in the JavaScript string literal
1485
+ */
1486
+ function interpretEscapes(str) {
1487
+ // First handle double backslashes by temporarily replacing them
1488
+ // Then handle other escapes, then restore double backslashes as single
1489
+ return str
1490
+ .replace(/\\\\/g, '\x00') // Temporarily mark double backslashes
1491
+ .replace(/\\n/g, '\n') // Match literal backslash-n (\\\\n in JS string -> \\n in regex -> matches \n)
1492
+ .replace(/\\t/g, '\t')
1493
+ .replace(/\\r/g, '\r')
1494
+ .replace(/\\"/g, '"')
1495
+ .replace(/\\'/g, "'")
1496
+ .replace(/\x00/g, '\\'); // Restore double backslashes as single
1497
+ }
1044
1498
  // Issues management
1045
1499
  const issues = program.command("issues").description("issues management");
1046
1500
  issues
1047
1501
  .command("list")
1048
1502
  .description("list issues")
1049
1503
  .option("--debug", "enable debug output")
1504
+ .option("--json", "output raw JSON")
1050
1505
  .action(async (opts) => {
1051
1506
  try {
1052
1507
  const rootOpts = program.opts();
@@ -1059,14 +1514,90 @@ issues
1059
1514
  }
1060
1515
  const { apiBaseUrl } = (0, util_2.resolveBaseUrls)(rootOpts, cfg);
1061
1516
  const result = await (0, issues_1.fetchIssues)({ apiKey, apiBaseUrl, debug: !!opts.debug });
1062
- if (typeof result === "string") {
1063
- process.stdout.write(result);
1064
- if (!/\n$/.test(result))
1065
- console.log();
1517
+ const trimmed = Array.isArray(result)
1518
+ ? result.map((r) => ({
1519
+ id: r.id,
1520
+ title: r.title,
1521
+ status: r.status,
1522
+ created_at: r.created_at,
1523
+ }))
1524
+ : result;
1525
+ printResult(trimmed, opts.json);
1526
+ }
1527
+ catch (err) {
1528
+ const message = err instanceof Error ? err.message : String(err);
1529
+ console.error(message);
1530
+ process.exitCode = 1;
1531
+ }
1532
+ });
1533
+ issues
1534
+ .command("view <issueId>")
1535
+ .description("view issue details and comments")
1536
+ .option("--debug", "enable debug output")
1537
+ .option("--json", "output raw JSON")
1538
+ .action(async (issueId, opts) => {
1539
+ try {
1540
+ const rootOpts = program.opts();
1541
+ const cfg = config.readConfig();
1542
+ const { apiKey } = getConfig(rootOpts);
1543
+ if (!apiKey) {
1544
+ console.error("API key is required. Run 'pgai auth' first or set --api-key.");
1545
+ process.exitCode = 1;
1546
+ return;
1066
1547
  }
1067
- else {
1068
- console.log(JSON.stringify(result, null, 2));
1548
+ const { apiBaseUrl } = (0, util_2.resolveBaseUrls)(rootOpts, cfg);
1549
+ const issue = await (0, issues_1.fetchIssue)({ apiKey, apiBaseUrl, issueId, debug: !!opts.debug });
1550
+ if (!issue) {
1551
+ console.error("Issue not found");
1552
+ process.exitCode = 1;
1553
+ return;
1554
+ }
1555
+ const comments = await (0, issues_1.fetchIssueComments)({ apiKey, apiBaseUrl, issueId, debug: !!opts.debug });
1556
+ const combined = { issue, comments };
1557
+ printResult(combined, opts.json);
1558
+ }
1559
+ catch (err) {
1560
+ const message = err instanceof Error ? err.message : String(err);
1561
+ console.error(message);
1562
+ process.exitCode = 1;
1563
+ }
1564
+ });
1565
+ issues
1566
+ .command("post_comment <issueId> <content>")
1567
+ .description("post a new comment to an issue")
1568
+ .option("--parent <uuid>", "parent comment id")
1569
+ .option("--debug", "enable debug output")
1570
+ .option("--json", "output raw JSON")
1571
+ .action(async (issueId, content, opts) => {
1572
+ try {
1573
+ // Interpret escape sequences in content (e.g., \n -> newline)
1574
+ if (opts.debug) {
1575
+ // eslint-disable-next-line no-console
1576
+ console.log(`Debug: Original content: ${JSON.stringify(content)}`);
1577
+ }
1578
+ content = interpretEscapes(content);
1579
+ if (opts.debug) {
1580
+ // eslint-disable-next-line no-console
1581
+ console.log(`Debug: Interpreted content: ${JSON.stringify(content)}`);
1069
1582
  }
1583
+ const rootOpts = program.opts();
1584
+ const cfg = config.readConfig();
1585
+ const { apiKey } = getConfig(rootOpts);
1586
+ if (!apiKey) {
1587
+ console.error("API key is required. Run 'pgai auth' first or set --api-key.");
1588
+ process.exitCode = 1;
1589
+ return;
1590
+ }
1591
+ const { apiBaseUrl } = (0, util_2.resolveBaseUrls)(rootOpts, cfg);
1592
+ const result = await (0, issues_1.createIssueComment)({
1593
+ apiKey,
1594
+ apiBaseUrl,
1595
+ issueId,
1596
+ content,
1597
+ parentCommentId: opts.parent,
1598
+ debug: !!opts.debug,
1599
+ });
1600
+ printResult(result, opts.json);
1070
1601
  }
1071
1602
  catch (err) {
1072
1603
  const message = err instanceof Error ? err.message : String(err);