postgresai 0.14.0-dev.43 → 0.14.0-dev.45

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 (58) hide show
  1. package/bin/postgres-ai.ts +649 -310
  2. package/bun.lock +258 -0
  3. package/dist/bin/postgres-ai.js +29491 -1910
  4. package/dist/sql/01.role.sql +16 -0
  5. package/dist/sql/02.permissions.sql +37 -0
  6. package/dist/sql/03.optional_rds.sql +6 -0
  7. package/dist/sql/04.optional_self_managed.sql +8 -0
  8. package/dist/sql/05.helpers.sql +415 -0
  9. package/lib/auth-server.ts +58 -97
  10. package/lib/checkup-api.ts +175 -0
  11. package/lib/checkup.ts +837 -0
  12. package/lib/config.ts +3 -0
  13. package/lib/init.ts +106 -74
  14. package/lib/issues.ts +121 -194
  15. package/lib/mcp-server.ts +6 -17
  16. package/lib/metrics-loader.ts +156 -0
  17. package/package.json +13 -9
  18. package/sql/02.permissions.sql +9 -5
  19. package/sql/05.helpers.sql +415 -0
  20. package/test/checkup.test.ts +953 -0
  21. package/test/init.integration.test.ts +396 -0
  22. package/test/init.test.ts +345 -0
  23. package/test/schema-validation.test.ts +188 -0
  24. package/tsconfig.json +12 -20
  25. package/dist/bin/postgres-ai.d.ts +0 -3
  26. package/dist/bin/postgres-ai.d.ts.map +0 -1
  27. package/dist/bin/postgres-ai.js.map +0 -1
  28. package/dist/lib/auth-server.d.ts +0 -31
  29. package/dist/lib/auth-server.d.ts.map +0 -1
  30. package/dist/lib/auth-server.js +0 -263
  31. package/dist/lib/auth-server.js.map +0 -1
  32. package/dist/lib/config.d.ts +0 -45
  33. package/dist/lib/config.d.ts.map +0 -1
  34. package/dist/lib/config.js +0 -181
  35. package/dist/lib/config.js.map +0 -1
  36. package/dist/lib/init.d.ts +0 -85
  37. package/dist/lib/init.d.ts.map +0 -1
  38. package/dist/lib/init.js +0 -644
  39. package/dist/lib/init.js.map +0 -1
  40. package/dist/lib/issues.d.ts +0 -75
  41. package/dist/lib/issues.d.ts.map +0 -1
  42. package/dist/lib/issues.js +0 -336
  43. package/dist/lib/issues.js.map +0 -1
  44. package/dist/lib/mcp-server.d.ts +0 -9
  45. package/dist/lib/mcp-server.d.ts.map +0 -1
  46. package/dist/lib/mcp-server.js +0 -168
  47. package/dist/lib/mcp-server.js.map +0 -1
  48. package/dist/lib/pkce.d.ts +0 -32
  49. package/dist/lib/pkce.d.ts.map +0 -1
  50. package/dist/lib/pkce.js +0 -101
  51. package/dist/lib/pkce.js.map +0 -1
  52. package/dist/lib/util.d.ts +0 -27
  53. package/dist/lib/util.d.ts.map +0 -1
  54. package/dist/lib/util.js +0 -46
  55. package/dist/lib/util.js.map +0 -1
  56. package/dist/package.json +0 -46
  57. package/test/init.integration.test.cjs +0 -382
  58. package/test/init.test.cjs +0 -392
package/lib/checkup.ts ADDED
@@ -0,0 +1,837 @@
1
+ /**
2
+ * Express Checkup Module
3
+ * ======================
4
+ * Generates JSON health check reports directly from PostgreSQL without Prometheus.
5
+ *
6
+ * ARCHITECTURAL DECISIONS
7
+ * -----------------------
8
+ *
9
+ * 1. SINGLE SOURCE OF TRUTH FOR SQL QUERIES
10
+ * All SQL queries MUST be loaded from config/pgwatch-prometheus/metrics.yml
11
+ * via getMetricSql() from metrics-loader.ts.
12
+ *
13
+ * DO NOT copy-paste or inline SQL queries in this file!
14
+ *
15
+ * The metrics.yml file is the single source of truth for metric extraction
16
+ * logic, shared between:
17
+ * - Full-fledged monitoring (Prometheus/pgwatch)
18
+ * - Express checkup (this CLI tool)
19
+ *
20
+ * This ensures consistency and avoids maintenance burden of duplicate queries.
21
+ *
22
+ * 2. JSON SCHEMA COMPLIANCE
23
+ * All generated reports MUST comply with JSON schemas in reporter/schemas/.
24
+ * These schemas define the expected format for both:
25
+ * - Full-fledged monitoring reporter output
26
+ * - Express checkup output
27
+ *
28
+ * Before adding or modifying a report, verify the corresponding schema exists
29
+ * and ensure the output matches. Run schema validation tests to confirm.
30
+ *
31
+ * ADDING NEW REPORTS
32
+ * ------------------
33
+ * 1. Add/verify the metric exists in config/pgwatch-prometheus/metrics.yml
34
+ * 2. Add the metric name mapping to METRIC_NAMES in metrics-loader.ts
35
+ * 3. Verify JSON schema exists in reporter/schemas/{CHECK_ID}.schema.json
36
+ * 4. Implement the generator function using getMetricSql()
37
+ * 5. Add schema validation test in test/schema-validation.test.ts
38
+ */
39
+
40
+ import { Client } from "pg";
41
+ import * as fs from "fs";
42
+ import * as path from "path";
43
+ import * as pkg from "../package.json";
44
+ import { getMetricSql, transformMetricRow, METRIC_NAMES } from "./metrics-loader";
45
+
46
+ /**
47
+ * PostgreSQL version information
48
+ */
49
+ export interface PostgresVersion {
50
+ version: string;
51
+ server_version_num: string;
52
+ server_major_ver: string;
53
+ server_minor_ver: string;
54
+ }
55
+
56
+ /**
57
+ * Setting information from pg_settings
58
+ */
59
+ export interface SettingInfo {
60
+ setting: string;
61
+ unit: string;
62
+ category: string;
63
+ context: string;
64
+ vartype: string;
65
+ pretty_value: string;
66
+ }
67
+
68
+ /**
69
+ * Altered setting (A007) - subset of SettingInfo
70
+ */
71
+ export interface AlteredSetting {
72
+ value: string;
73
+ unit: string;
74
+ category: string;
75
+ pretty_value: string;
76
+ }
77
+
78
+ /**
79
+ * Cluster metric (A004)
80
+ */
81
+ export interface ClusterMetric {
82
+ value: string;
83
+ unit: string;
84
+ description: string;
85
+ }
86
+
87
+ /**
88
+ * Invalid index entry (H001) - matches H001.schema.json invalidIndex
89
+ */
90
+ export interface InvalidIndex {
91
+ schema_name: string;
92
+ table_name: string;
93
+ index_name: string;
94
+ relation_name: string;
95
+ index_size_bytes: number;
96
+ index_size_pretty: string;
97
+ supports_fk: boolean;
98
+ }
99
+
100
+ /**
101
+ * Unused index entry (H002) - matches H002.schema.json unusedIndex
102
+ */
103
+ export interface UnusedIndex {
104
+ schema_name: string;
105
+ table_name: string;
106
+ index_name: string;
107
+ index_definition: string;
108
+ reason: string;
109
+ idx_scan: number;
110
+ index_size_bytes: number;
111
+ idx_is_btree: boolean;
112
+ supports_fk: boolean;
113
+ index_size_pretty: string;
114
+ }
115
+
116
+ /**
117
+ * Stats reset info for H002 - matches H002.schema.json statsReset
118
+ */
119
+ export interface StatsReset {
120
+ stats_reset_epoch: number | null;
121
+ stats_reset_time: string | null;
122
+ days_since_reset: number | null;
123
+ postmaster_startup_epoch: number | null;
124
+ postmaster_startup_time: string | null;
125
+ }
126
+
127
+ /**
128
+ * Redundant index entry (H004) - matches H004.schema.json redundantIndex
129
+ */
130
+ export interface RedundantIndex {
131
+ schema_name: string;
132
+ table_name: string;
133
+ index_name: string;
134
+ relation_name: string;
135
+ access_method: string;
136
+ reason: string;
137
+ index_size_bytes: number;
138
+ table_size_bytes: number;
139
+ index_usage: number;
140
+ supports_fk: boolean;
141
+ index_definition: string;
142
+ index_size_pretty: string;
143
+ table_size_pretty: string;
144
+ }
145
+
146
+ /**
147
+ * Node result for reports
148
+ */
149
+ export interface NodeResult {
150
+ data: Record<string, any>;
151
+ postgres_version?: PostgresVersion;
152
+ }
153
+
154
+ /**
155
+ * Report structure matching JSON schemas
156
+ */
157
+ export interface Report {
158
+ version: string | null;
159
+ build_ts: string | null;
160
+ checkId: string;
161
+ checkTitle: string;
162
+ timestamptz: string;
163
+ nodes: {
164
+ primary: string;
165
+ standbys: string[];
166
+ };
167
+ results: Record<string, NodeResult>;
168
+ }
169
+
170
+ /**
171
+ * Parse PostgreSQL version number into major and minor components
172
+ */
173
+ export function parseVersionNum(versionNum: string): { major: string; minor: string } {
174
+ if (!versionNum || versionNum.length < 6) {
175
+ return { major: "", minor: "" };
176
+ }
177
+ try {
178
+ const num = parseInt(versionNum, 10);
179
+ return {
180
+ major: Math.floor(num / 10000).toString(),
181
+ minor: (num % 10000).toString(),
182
+ };
183
+ } catch {
184
+ return { major: "", minor: "" };
185
+ }
186
+ }
187
+
188
+ /**
189
+ * Format bytes to human readable string using binary units (1024-based).
190
+ * Uses IEC standard: KiB, MiB, GiB, etc.
191
+ *
192
+ * Note: PostgreSQL's pg_size_pretty() uses kB/MB/GB with 1024 base (technically
193
+ * incorrect SI usage), but we follow IEC binary units per project style guide.
194
+ */
195
+ export function formatBytes(bytes: number): string {
196
+ if (bytes === 0) return "0 B";
197
+ const units = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"];
198
+ const i = Math.floor(Math.log(bytes) / Math.log(1024));
199
+ return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i]}`;
200
+ }
201
+
202
+ /**
203
+ * Get PostgreSQL version information
204
+ * SQL loaded from config/pgwatch-prometheus/metrics.yml (express_version)
205
+ */
206
+ export async function getPostgresVersion(client: Client): Promise<PostgresVersion> {
207
+ const sql = getMetricSql(METRIC_NAMES.version);
208
+ const result = await client.query(sql);
209
+
210
+ let version = "";
211
+ let serverVersionNum = "";
212
+
213
+ for (const row of result.rows) {
214
+ if (row.name === "server_version") {
215
+ version = row.setting;
216
+ } else if (row.name === "server_version_num") {
217
+ serverVersionNum = row.setting;
218
+ }
219
+ }
220
+
221
+ const { major, minor } = parseVersionNum(serverVersionNum);
222
+
223
+ return {
224
+ version,
225
+ server_version_num: serverVersionNum,
226
+ server_major_ver: major,
227
+ server_minor_ver: minor,
228
+ };
229
+ }
230
+
231
+ /**
232
+ * Get all PostgreSQL settings
233
+ * SQL loaded from config/pgwatch-prometheus/metrics.yml (express_settings)
234
+ */
235
+ export async function getSettings(client: Client): Promise<Record<string, SettingInfo>> {
236
+ const sql = getMetricSql(METRIC_NAMES.settings);
237
+ const result = await client.query(sql);
238
+ const settings: Record<string, SettingInfo> = {};
239
+
240
+ for (const row of result.rows) {
241
+ settings[row.name] = {
242
+ setting: row.setting,
243
+ unit: row.unit || "",
244
+ category: row.category,
245
+ context: row.context,
246
+ vartype: row.vartype,
247
+ pretty_value: row.pretty_value,
248
+ };
249
+ }
250
+
251
+ return settings;
252
+ }
253
+
254
+ /**
255
+ * Get altered (non-default) PostgreSQL settings
256
+ * SQL loaded from config/pgwatch-prometheus/metrics.yml (express_altered_settings)
257
+ */
258
+ export async function getAlteredSettings(client: Client): Promise<Record<string, AlteredSetting>> {
259
+ const sql = getMetricSql(METRIC_NAMES.alteredSettings);
260
+ const result = await client.query(sql);
261
+ const settings: Record<string, AlteredSetting> = {};
262
+
263
+ for (const row of result.rows) {
264
+ settings[row.name] = {
265
+ value: row.setting,
266
+ unit: row.unit || "",
267
+ category: row.category,
268
+ pretty_value: row.pretty_value,
269
+ };
270
+ }
271
+
272
+ return settings;
273
+ }
274
+
275
+ /**
276
+ * Get database sizes
277
+ * SQL loaded from config/pgwatch-prometheus/metrics.yml (express_database_sizes)
278
+ */
279
+ export async function getDatabaseSizes(client: Client): Promise<Record<string, number>> {
280
+ const sql = getMetricSql(METRIC_NAMES.databaseSizes);
281
+ const result = await client.query(sql);
282
+ const sizes: Record<string, number> = {};
283
+
284
+ for (const row of result.rows) {
285
+ sizes[row.datname] = parseInt(row.size_bytes, 10);
286
+ }
287
+
288
+ return sizes;
289
+ }
290
+
291
+ /**
292
+ * Get cluster general info metrics
293
+ * SQL loaded from config/pgwatch-prometheus/metrics.yml (express_cluster_stats, express_connection_states, express_uptime)
294
+ */
295
+ export async function getClusterInfo(client: Client): Promise<Record<string, ClusterMetric>> {
296
+ const info: Record<string, ClusterMetric> = {};
297
+
298
+ // Get cluster statistics
299
+ const clusterStatsSql = getMetricSql(METRIC_NAMES.clusterStats);
300
+ const statsResult = await client.query(clusterStatsSql);
301
+ if (statsResult.rows.length > 0) {
302
+ const stats = statsResult.rows[0];
303
+
304
+ info.total_connections = {
305
+ value: String(stats.total_connections || 0),
306
+ unit: "connections",
307
+ description: "Total active database connections",
308
+ };
309
+
310
+ info.total_commits = {
311
+ value: String(stats.total_commits || 0),
312
+ unit: "transactions",
313
+ description: "Total committed transactions",
314
+ };
315
+
316
+ info.total_rollbacks = {
317
+ value: String(stats.total_rollbacks || 0),
318
+ unit: "transactions",
319
+ description: "Total rolled back transactions",
320
+ };
321
+
322
+ const blocksHit = parseInt(stats.blocks_hit || "0", 10);
323
+ const blocksRead = parseInt(stats.blocks_read || "0", 10);
324
+ const totalBlocks = blocksHit + blocksRead;
325
+ const cacheHitRatio = totalBlocks > 0 ? ((blocksHit / totalBlocks) * 100).toFixed(2) : "0.00";
326
+
327
+ info.cache_hit_ratio = {
328
+ value: cacheHitRatio,
329
+ unit: "%",
330
+ description: "Buffer cache hit ratio",
331
+ };
332
+
333
+ info.blocks_read = {
334
+ value: String(blocksRead),
335
+ unit: "blocks",
336
+ description: "Total disk blocks read",
337
+ };
338
+
339
+ info.blocks_hit = {
340
+ value: String(blocksHit),
341
+ unit: "blocks",
342
+ description: "Total buffer cache hits",
343
+ };
344
+
345
+ info.tuples_returned = {
346
+ value: String(stats.tuples_returned || 0),
347
+ unit: "rows",
348
+ description: "Total rows returned by queries",
349
+ };
350
+
351
+ info.tuples_fetched = {
352
+ value: String(stats.tuples_fetched || 0),
353
+ unit: "rows",
354
+ description: "Total rows fetched by queries",
355
+ };
356
+
357
+ info.tuples_inserted = {
358
+ value: String(stats.tuples_inserted || 0),
359
+ unit: "rows",
360
+ description: "Total rows inserted",
361
+ };
362
+
363
+ info.tuples_updated = {
364
+ value: String(stats.tuples_updated || 0),
365
+ unit: "rows",
366
+ description: "Total rows updated",
367
+ };
368
+
369
+ info.tuples_deleted = {
370
+ value: String(stats.tuples_deleted || 0),
371
+ unit: "rows",
372
+ description: "Total rows deleted",
373
+ };
374
+
375
+ info.total_deadlocks = {
376
+ value: String(stats.total_deadlocks || 0),
377
+ unit: "deadlocks",
378
+ description: "Total deadlocks detected",
379
+ };
380
+
381
+ info.temp_files_created = {
382
+ value: String(stats.temp_files_created || 0),
383
+ unit: "files",
384
+ description: "Total temporary files created",
385
+ };
386
+
387
+ const tempBytes = parseInt(stats.temp_bytes_written || "0", 10);
388
+ info.temp_bytes_written = {
389
+ value: formatBytes(tempBytes),
390
+ unit: "bytes",
391
+ description: "Total temporary file bytes written",
392
+ };
393
+ }
394
+
395
+ // Get connection states
396
+ const connStatesSql = getMetricSql(METRIC_NAMES.connectionStates);
397
+ const connResult = await client.query(connStatesSql);
398
+ for (const row of connResult.rows) {
399
+ const stateKey = `connections_${row.state.replace(/\s+/g, "_")}`;
400
+ info[stateKey] = {
401
+ value: String(row.count),
402
+ unit: "connections",
403
+ description: `Connections in '${row.state}' state`,
404
+ };
405
+ }
406
+
407
+ // Get uptime info
408
+ const uptimeSql = getMetricSql(METRIC_NAMES.uptimeInfo);
409
+ const uptimeResult = await client.query(uptimeSql);
410
+ if (uptimeResult.rows.length > 0) {
411
+ const uptime = uptimeResult.rows[0];
412
+ info.start_time = {
413
+ value: uptime.start_time.toISOString(),
414
+ unit: "timestamp",
415
+ description: "PostgreSQL server start time",
416
+ };
417
+ info.uptime = {
418
+ value: uptime.uptime,
419
+ unit: "interval",
420
+ description: "Server uptime",
421
+ };
422
+ }
423
+
424
+ return info;
425
+ }
426
+
427
+ /**
428
+ * Get invalid indexes (H001)
429
+ * SQL loaded from config/pgwatch-prometheus/metrics.yml (pg_invalid_indexes)
430
+ */
431
+ export async function getInvalidIndexes(client: Client): Promise<InvalidIndex[]> {
432
+ const sql = getMetricSql(METRIC_NAMES.H001);
433
+ const result = await client.query(sql);
434
+ return result.rows.map((row) => {
435
+ const transformed = transformMetricRow(row);
436
+ const indexSizeBytes = parseInt(String(transformed.index_size_bytes || 0), 10);
437
+ return {
438
+ schema_name: String(transformed.schema_name || ""),
439
+ table_name: String(transformed.table_name || ""),
440
+ index_name: String(transformed.index_name || ""),
441
+ relation_name: String(transformed.relation_name || ""),
442
+ index_size_bytes: indexSizeBytes,
443
+ index_size_pretty: formatBytes(indexSizeBytes),
444
+ supports_fk: transformed.supports_fk === true || transformed.supports_fk === 1,
445
+ };
446
+ });
447
+ }
448
+
449
+ /**
450
+ * Get unused indexes (H002)
451
+ * SQL loaded from config/pgwatch-prometheus/metrics.yml (unused_indexes)
452
+ */
453
+ export async function getUnusedIndexes(client: Client): Promise<UnusedIndex[]> {
454
+ const sql = getMetricSql(METRIC_NAMES.H002);
455
+ const result = await client.query(sql);
456
+ return result.rows.map((row) => {
457
+ const transformed = transformMetricRow(row);
458
+ const indexSizeBytes = parseInt(String(transformed.index_size_bytes || 0), 10);
459
+ return {
460
+ schema_name: String(transformed.schema_name || ""),
461
+ table_name: String(transformed.table_name || ""),
462
+ index_name: String(transformed.index_name || ""),
463
+ index_definition: String(transformed.index_definition || ""),
464
+ reason: String(transformed.reason || ""),
465
+ idx_scan: parseInt(String(transformed.idx_scan || 0), 10),
466
+ index_size_bytes: indexSizeBytes,
467
+ idx_is_btree: transformed.idx_is_btree === true || transformed.idx_is_btree === "t",
468
+ supports_fk: transformed.supports_fk === true || transformed.supports_fk === 1,
469
+ index_size_pretty: formatBytes(indexSizeBytes),
470
+ };
471
+ });
472
+ }
473
+
474
+ /**
475
+ * Get stats reset info (H002)
476
+ */
477
+ /**
478
+ * Get stats reset info (H002)
479
+ * SQL loaded from config/pgwatch-prometheus/metrics.yml (express_stats_reset)
480
+ */
481
+ export async function getStatsReset(client: Client): Promise<StatsReset> {
482
+ const sql = getMetricSql(METRIC_NAMES.statsReset);
483
+ const result = await client.query(sql);
484
+ const row = result.rows[0] || {};
485
+ return {
486
+ stats_reset_epoch: row.stats_reset_epoch ? parseFloat(row.stats_reset_epoch) : null,
487
+ stats_reset_time: row.stats_reset_time || null,
488
+ days_since_reset: row.days_since_reset ? parseInt(row.days_since_reset, 10) : null,
489
+ postmaster_startup_epoch: row.postmaster_startup_epoch ? parseFloat(row.postmaster_startup_epoch) : null,
490
+ postmaster_startup_time: row.postmaster_startup_time || null,
491
+ };
492
+ }
493
+
494
+ /**
495
+ * Get current database name and size
496
+ * SQL loaded from config/pgwatch-prometheus/metrics.yml (express_current_database)
497
+ */
498
+ export async function getCurrentDatabaseInfo(client: Client): Promise<{ datname: string; size_bytes: number }> {
499
+ const sql = getMetricSql(METRIC_NAMES.currentDatabase);
500
+ const result = await client.query(sql);
501
+ const row = result.rows[0] || {};
502
+ return {
503
+ datname: row.datname || "postgres",
504
+ size_bytes: parseInt(row.size_bytes, 10) || 0,
505
+ };
506
+ }
507
+
508
+ /**
509
+ * Get redundant indexes (H004)
510
+ * SQL loaded from config/pgwatch-prometheus/metrics.yml (redundant_indexes)
511
+ */
512
+ export async function getRedundantIndexes(client: Client): Promise<RedundantIndex[]> {
513
+ const sql = getMetricSql(METRIC_NAMES.H004);
514
+ const result = await client.query(sql);
515
+ return result.rows.map((row) => {
516
+ const transformed = transformMetricRow(row);
517
+ const indexSizeBytes = parseInt(String(transformed.index_size_bytes || 0), 10);
518
+ const tableSizeBytes = parseInt(String(transformed.table_size_bytes || 0), 10);
519
+ return {
520
+ schema_name: String(transformed.schema_name || ""),
521
+ table_name: String(transformed.table_name || ""),
522
+ index_name: String(transformed.index_name || ""),
523
+ relation_name: String(transformed.relation_name || ""),
524
+ access_method: String(transformed.access_method || ""),
525
+ reason: String(transformed.reason || ""),
526
+ index_size_bytes: indexSizeBytes,
527
+ table_size_bytes: tableSizeBytes,
528
+ index_usage: parseInt(String(transformed.index_usage || 0), 10),
529
+ supports_fk: transformed.supports_fk === true || transformed.supports_fk === 1,
530
+ index_definition: String(transformed.index_definition || ""),
531
+ index_size_pretty: formatBytes(indexSizeBytes),
532
+ table_size_pretty: formatBytes(tableSizeBytes),
533
+ };
534
+ });
535
+ }
536
+
537
+ /**
538
+ * Create base report structure
539
+ */
540
+ export function createBaseReport(
541
+ checkId: string,
542
+ checkTitle: string,
543
+ nodeName: string
544
+ ): Report {
545
+ const buildTs = resolveBuildTs();
546
+ return {
547
+ version: pkg.version || null,
548
+ build_ts: buildTs,
549
+ checkId,
550
+ checkTitle,
551
+ timestamptz: new Date().toISOString(),
552
+ nodes: {
553
+ primary: nodeName,
554
+ standbys: [],
555
+ },
556
+ results: {},
557
+ };
558
+ }
559
+
560
+ function readTextFileSafe(p: string): string | null {
561
+ try {
562
+ const value = fs.readFileSync(p, "utf8").trim();
563
+ return value || null;
564
+ } catch {
565
+ return null;
566
+ }
567
+ }
568
+
569
+ function resolveBuildTs(): string | null {
570
+ // Follow reporter.py approach: read BUILD_TS from filesystem, with env override.
571
+ // Default: /BUILD_TS (useful in container images).
572
+ const envPath = process.env.PGAI_BUILD_TS_FILE;
573
+ const p = (envPath && envPath.trim()) ? envPath.trim() : "/BUILD_TS";
574
+
575
+ const fromFile = readTextFileSafe(p);
576
+ if (fromFile) return fromFile;
577
+
578
+ // Fallback for packaged CLI: allow placing BUILD_TS next to dist/ (package root).
579
+ // dist/lib/checkup.js => package root: dist/..
580
+ try {
581
+ const pkgRoot = path.resolve(__dirname, "..");
582
+ const fromPkgFile = readTextFileSafe(path.join(pkgRoot, "BUILD_TS"));
583
+ if (fromPkgFile) return fromPkgFile;
584
+ } catch {
585
+ // ignore
586
+ }
587
+
588
+ // Last resort: use package.json mtime as an approximation (non-null, stable-ish).
589
+ try {
590
+ const pkgJsonPath = path.resolve(__dirname, "..", "package.json");
591
+ const st = fs.statSync(pkgJsonPath);
592
+ return st.mtime.toISOString();
593
+ } catch {
594
+ return new Date().toISOString();
595
+ }
596
+ }
597
+
598
+ /**
599
+ * Generate A002 report - Postgres major version
600
+ */
601
+ export async function generateA002(client: Client, nodeName: string = "node-01"): Promise<Report> {
602
+ const report = createBaseReport("A002", "Postgres major version", nodeName);
603
+ const postgresVersion = await getPostgresVersion(client);
604
+
605
+ report.results[nodeName] = {
606
+ data: {
607
+ version: postgresVersion,
608
+ },
609
+ };
610
+
611
+ return report;
612
+ }
613
+
614
+ /**
615
+ * Generate A003 report - Postgres settings
616
+ */
617
+ export async function generateA003(client: Client, nodeName: string = "node-01"): Promise<Report> {
618
+ const report = createBaseReport("A003", "Postgres settings", nodeName);
619
+ const settings = await getSettings(client);
620
+ const postgresVersion = await getPostgresVersion(client);
621
+
622
+ report.results[nodeName] = {
623
+ data: settings,
624
+ postgres_version: postgresVersion,
625
+ };
626
+
627
+ return report;
628
+ }
629
+
630
+ /**
631
+ * Generate A004 report - Cluster information
632
+ */
633
+ export async function generateA004(client: Client, nodeName: string = "node-01"): Promise<Report> {
634
+ const report = createBaseReport("A004", "Cluster information", nodeName);
635
+ const generalInfo = await getClusterInfo(client);
636
+ const databaseSizes = await getDatabaseSizes(client);
637
+ const postgresVersion = await getPostgresVersion(client);
638
+
639
+ report.results[nodeName] = {
640
+ data: {
641
+ general_info: generalInfo,
642
+ database_sizes: databaseSizes,
643
+ },
644
+ postgres_version: postgresVersion,
645
+ };
646
+
647
+ return report;
648
+ }
649
+
650
+ /**
651
+ * Generate A007 report - Altered settings
652
+ */
653
+ export async function generateA007(client: Client, nodeName: string = "node-01"): Promise<Report> {
654
+ const report = createBaseReport("A007", "Altered settings", nodeName);
655
+ const alteredSettings = await getAlteredSettings(client);
656
+ const postgresVersion = await getPostgresVersion(client);
657
+
658
+ report.results[nodeName] = {
659
+ data: alteredSettings,
660
+ postgres_version: postgresVersion,
661
+ };
662
+
663
+ return report;
664
+ }
665
+
666
+ /**
667
+ * Generate A013 report - Postgres minor version
668
+ */
669
+ export async function generateA013(client: Client, nodeName: string = "node-01"): Promise<Report> {
670
+ const report = createBaseReport("A013", "Postgres minor version", nodeName);
671
+ const postgresVersion = await getPostgresVersion(client);
672
+
673
+ report.results[nodeName] = {
674
+ data: {
675
+ version: postgresVersion,
676
+ },
677
+ };
678
+
679
+ return report;
680
+ }
681
+
682
+ /**
683
+ * Generate H001 report - Invalid indexes
684
+ */
685
+ export async function generateH001(client: Client, nodeName: string = "node-01"): Promise<Report> {
686
+ const report = createBaseReport("H001", "Invalid indexes", nodeName);
687
+ const invalidIndexes = await getInvalidIndexes(client);
688
+ const postgresVersion = await getPostgresVersion(client);
689
+
690
+ // Get current database name and size
691
+ const { datname: dbName, size_bytes: dbSizeBytes } = await getCurrentDatabaseInfo(client);
692
+
693
+ // Calculate totals
694
+ const totalCount = invalidIndexes.length;
695
+ const totalSizeBytes = invalidIndexes.reduce((sum, idx) => sum + idx.index_size_bytes, 0);
696
+
697
+ // Structure data by database name per schema
698
+ report.results[nodeName] = {
699
+ data: {
700
+ [dbName]: {
701
+ invalid_indexes: invalidIndexes,
702
+ total_count: totalCount,
703
+ total_size_bytes: totalSizeBytes,
704
+ total_size_pretty: formatBytes(totalSizeBytes),
705
+ database_size_bytes: dbSizeBytes,
706
+ database_size_pretty: formatBytes(dbSizeBytes),
707
+ },
708
+ },
709
+ postgres_version: postgresVersion,
710
+ };
711
+
712
+ return report;
713
+ }
714
+
715
+ /**
716
+ * Generate H002 report - Unused indexes
717
+ */
718
+ export async function generateH002(client: Client, nodeName: string = "node-01"): Promise<Report> {
719
+ const report = createBaseReport("H002", "Unused indexes", nodeName);
720
+ const unusedIndexes = await getUnusedIndexes(client);
721
+ const postgresVersion = await getPostgresVersion(client);
722
+ const statsReset = await getStatsReset(client);
723
+
724
+ // Get current database name and size
725
+ const { datname: dbName, size_bytes: dbSizeBytes } = await getCurrentDatabaseInfo(client);
726
+
727
+ // Calculate totals
728
+ const totalCount = unusedIndexes.length;
729
+ const totalSizeBytes = unusedIndexes.reduce((sum, idx) => sum + idx.index_size_bytes, 0);
730
+
731
+ // Structure data by database name per schema
732
+ report.results[nodeName] = {
733
+ data: {
734
+ [dbName]: {
735
+ unused_indexes: unusedIndexes,
736
+ total_count: totalCount,
737
+ total_size_bytes: totalSizeBytes,
738
+ total_size_pretty: formatBytes(totalSizeBytes),
739
+ database_size_bytes: dbSizeBytes,
740
+ database_size_pretty: formatBytes(dbSizeBytes),
741
+ stats_reset: statsReset,
742
+ },
743
+ },
744
+ postgres_version: postgresVersion,
745
+ };
746
+
747
+ return report;
748
+ }
749
+
750
+ /**
751
+ * Generate H004 report - Redundant indexes
752
+ */
753
+ export async function generateH004(client: Client, nodeName: string = "node-01"): Promise<Report> {
754
+ const report = createBaseReport("H004", "Redundant indexes", nodeName);
755
+ const redundantIndexes = await getRedundantIndexes(client);
756
+ const postgresVersion = await getPostgresVersion(client);
757
+
758
+ // Get current database name and size
759
+ const { datname: dbName, size_bytes: dbSizeBytes } = await getCurrentDatabaseInfo(client);
760
+
761
+ // Calculate totals
762
+ const totalCount = redundantIndexes.length;
763
+ const totalSizeBytes = redundantIndexes.reduce((sum, idx) => sum + idx.index_size_bytes, 0);
764
+
765
+ // Structure data by database name per schema
766
+ report.results[nodeName] = {
767
+ data: {
768
+ [dbName]: {
769
+ redundant_indexes: redundantIndexes,
770
+ total_count: totalCount,
771
+ total_size_bytes: totalSizeBytes,
772
+ total_size_pretty: formatBytes(totalSizeBytes),
773
+ database_size_bytes: dbSizeBytes,
774
+ database_size_pretty: formatBytes(dbSizeBytes),
775
+ },
776
+ },
777
+ postgres_version: postgresVersion,
778
+ };
779
+
780
+ return report;
781
+ }
782
+
783
+ /**
784
+ * Available report generators
785
+ */
786
+ export const REPORT_GENERATORS: Record<string, (client: Client, nodeName: string) => Promise<Report>> = {
787
+ A002: generateA002,
788
+ A003: generateA003,
789
+ A004: generateA004,
790
+ A007: generateA007,
791
+ A013: generateA013,
792
+ H001: generateH001,
793
+ H002: generateH002,
794
+ H004: generateH004,
795
+ };
796
+
797
+ /**
798
+ * Check IDs and titles
799
+ */
800
+ export const CHECK_INFO: Record<string, string> = {
801
+ A002: "Postgres major version",
802
+ A003: "Postgres settings",
803
+ A004: "Cluster information",
804
+ A007: "Altered settings",
805
+ A013: "Postgres minor version",
806
+ H001: "Invalid indexes",
807
+ H002: "Unused indexes",
808
+ H004: "Redundant indexes",
809
+ };
810
+
811
+ /**
812
+ * Generate all available reports
813
+ */
814
+ export async function generateAllReports(
815
+ client: Client,
816
+ nodeName: string = "node-01",
817
+ onProgress?: (info: { checkId: string; checkTitle: string; index: number; total: number }) => void
818
+ ): Promise<Record<string, Report>> {
819
+ const reports: Record<string, Report> = {};
820
+
821
+ const entries = Object.entries(REPORT_GENERATORS);
822
+ const total = entries.length;
823
+ let index = 0;
824
+
825
+ for (const [checkId, generator] of entries) {
826
+ index += 1;
827
+ onProgress?.({
828
+ checkId,
829
+ checkTitle: CHECK_INFO[checkId] || checkId,
830
+ index,
831
+ total,
832
+ });
833
+ reports[checkId] = await generator(client, nodeName);
834
+ }
835
+
836
+ return reports;
837
+ }