@subodh001/pg-safe-migrate 2.3.0 → 2.5.0

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.
package/README.md CHANGED
@@ -1,6 +1,4 @@
1
- > **Development candidate:** v2.1.0. See [MILESTONES.md](MILESTONES.md) for implemented features and explicitly unfinished v2.2/v3.0 work.
2
-
3
- > **Current release: v2.0.0.** Static migration risk detection is advisory, not a zero-downtime guarantee. See [UPGRADE-NOTES.md](UPGRADE-NOTES.md) for upgrade details and limitations.
1
+ > **Published npm CLI: v2.4.0.** **VS Code extension: v0.5.0.** Week 3 CI gate is a development candidate and is not published yet. Migration analysis does not guarantee zero downtime.
4
2
 
5
3
  # pg-safe-migrate
6
4
 
@@ -46,6 +44,27 @@ CREATE INDEX CONCURRENTLY idx_users_email ON users(email);
46
44
 
47
45
  `CREATE INDEX CONCURRENTLY` must run outside a transaction block.
48
46
 
47
+
48
+ ## Week 3 preview: opt-in CI policy gate (unreleased)
49
+
50
+ Run a deterministic, policy-driven static lint check in CI:
51
+
52
+ ```bash
53
+ node bin/cli.js db/migrations --gate-policy examples/week3-gate-policy.json --fail-on none
54
+ ```
55
+
56
+ The gate can block selected `PGxxx` rules, excessive warnings, and heuristic risk scores. It reports a block to stderr and exits with code `1`; malformed configuration exits `2`. This is a **development-only preview**, not available in the published v2.4.0 package. See [Week 3 implementation notes](WEEK3-DAY1-IMPLEMENTED.md).
57
+
58
+ [Install from npm](https://www.npmjs.com/package/@subodh001/pg-safe-migrate) · [Install the VS Code extension](https://marketplace.visualstudio.com/items?itemName=sukoaa.pg-safe-migrate-vscode) · [Report an issue](https://github.com/subodhsingh001/pg-safe-migrate/issues)
59
+
60
+ ## Adoption and developer resources (Week 3 candidate)
61
+
62
+ - [Safe onboarding and CI troubleshooting](docs/ADOPTION-GUIDE.md)
63
+ - [Short demonstration recording script](docs/DEMO-SCRIPT.md)
64
+ - [Proposed npm and VS Code Marketplace copy](docs/MARKETPLACE-COPY.md)
65
+
66
+ **Release distinction:** The Week 3 policy, baseline, production-context, and PR reporting features are currently source-checkout development features, not part of published npm v2.4.0. Review the policy and baseline before enabling blocking checks; passing a static gate is not a downtime guarantee.
67
+
49
68
  ## Installation
50
69
 
51
70
  Install as a development dependency:
@@ -57,7 +76,7 @@ npm install --save-dev @subodh001/pg-safe-migrate
57
76
  Or execute the published package without installing it in your project:
58
77
 
59
78
  ```bash
60
- npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate --help
79
+ npx --yes --package=@subodh001/pg-safe-migrate@2.4.0 pg-safe-migrate --help
61
80
  ```
62
81
 
63
82
  ## Quick start
@@ -173,7 +192,7 @@ For reproducible builds, pin the package to a reviewed version and upgrade delib
173
192
  From a clean directory, run:
174
193
 
175
194
  ```bash
176
- npx --yes --package=@subodh001/pg-safe-migrate@2.0.0 pg-safe-migrate --help
195
+ npx --yes --package=@subodh001/pg-safe-migrate@2.4.0 pg-safe-migrate --help
177
196
  ```
178
197
 
179
198
  Create a file named `unsafe.sql`:
@@ -338,3 +357,7 @@ The directory mode processes only top-level `.sql` files (maximum 100); nested O
338
357
  ## Consolidated experimental development capabilities
339
358
 
340
359
  See [ALL-MILESTONES-TESTING.md](ALL-MILESTONES-TESTING.md) for exact commands and verification limitations. `--assess` combines lint findings, lock classifications, heuristic risk score, deployment advice, Docker execution, optional `--verify-sql` assertions, and optional `--team-policy` checks. The Docker matrix script covers PostgreSQL 14–18 when Docker is available. `vscode-extension/` is a local VS Code extension prototype; team policy is a local JSON configuration, **not** a hosted team management service.
360
+
361
+ ## Markdown migration report (Week 2 Day 6)
362
+
363
+ Run `pg-safe-migrate migrations --format markdown --risk --output migration-report.md` to generate an actionable Markdown report with rule IDs, locations, recommended actions, and an optional heuristic risk breakdown. This does not predict production downtime.
package/bin/cli.js CHANGED
@@ -13,16 +13,18 @@ import { findMigrationFiles } from '../src/detector.js';
13
13
  import { getChangedSqlFiles } from '../src/gitDiff.js';
14
14
  import { loadConfig, isExcluded } from '../src/config.js';
15
15
  import { analyzeFiles } from '../src/analysis.js';
16
- import { toJson, toSarif } from '../src/reports.js';
16
+ import { toJson, toSarif, toMarkdownReport } from '../src/reports.js';
17
17
  import { inspectDatabaseUrl } from '../src/db-inspect.js';
18
18
  import { simulateSqlFile } from '../src/simulator.js';
19
19
  import { combinedAssessment } from '../src/combined.js';
20
- import { loadTeamPolicy, assessTeamPolicy } from '../src/team-policy.js';
20
+ import { loadTeamPolicy, assessTeamPolicy, assessLintPolicy } from '../src/team-policy.js';
21
+ import { loadProductionContext, productionAssessment } from '../src/production-context.js';
22
+ import { createRiskBaseline, loadRiskBaseline, compareRiskBaseline, writeRiskBaseline } from '../src/risk-baseline.js';
21
23
 
22
24
  program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk linter (not a downtime guarantee)').version(version)
23
25
  .argument('[target]', 'SQL file or migrations directory')
24
26
  .option('-c, --changed [baseBranch]', 'Lint changed SQL files')
25
- .option('--format <format>', 'text, json or sarif', 'text')
27
+ .option('--format <format>', 'text, json, sarif or markdown', 'text')
26
28
  .option('--output <file>', 'Write report to file')
27
29
  .option('--config <file>', 'JSON configuration file', 'pg-safe-migrate.config.json')
28
30
  .option('--postgres-version <version>', 'Target PostgreSQL major version')
@@ -32,9 +34,13 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
32
34
  .option('--github', 'Emit GitHub workflow annotations')
33
35
  .option('--summary <file>', 'Write Markdown PR summary')
34
36
  .option('--risk', 'Include heuristic risk score in text output')
37
+ .option('--production-context <file>', 'Optional read-only JSON production estimates for advisory output')
35
38
  .option('--assess', 'Combine static linting with disposable PostgreSQL simulation')
36
39
  .option('--verify-sql <file>', 'Run post-migration SQL assertions (SQL errors or exceptions fail verification)')
37
40
  .option('--team-policy <file>', 'Local JSON team policy for combined assessment')
41
+ .option('--gate-policy <file>', 'Opt-in static CI gate policy (JSON); blocks matching risks')
42
+ .option('--write-risk-baseline <file>', 'Write baseline of current static findings (review before committing)')
43
+ .option('--risk-baseline <file>', 'Compare findings with a previously reviewed baseline')
38
44
  .option('--simulate <sqlFile>', 'Execute one SQL file against a disposable Docker PostgreSQL container')
39
45
  .option('--baseline <sqlFile>', 'Apply baseline SQL before simulation')
40
46
  .option('--migrations-dir <directory>', 'Simulate top-level SQL migrations in filename order')
@@ -42,7 +48,7 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
42
48
  .option('--inspect-db', 'Inspect database catalog (requires DATABASE_URL and optional pg dependency)')
43
49
  .action(async (target,opts)=>{
44
50
  try {
45
- if (!['text','json','sarif'].includes(opts.format)) throw new Error('format must be text, json or sarif');
51
+ if (!['text','json','sarif','markdown'].includes(opts.format)) throw new Error('format must be text, json, sarif or markdown');
46
52
  if (!['none','warning','error'].includes(opts.failOn)) throw new Error('fail-on must be none, warning or error');
47
53
  const preset = getPreset(opts.preset);
48
54
  const userConfig = loadConfig(opts.config);
@@ -52,6 +58,7 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
52
58
  if (!Number.isInteger(version)||version<10||version>99) throw new Error('postgres-version must be an integer >= 10');
53
59
  config.postgresVersion=version;
54
60
  }
61
+ if ((opts.gatePolicy || opts.riskBaseline || opts.writeRiskBaseline || opts.productionContext) && (opts.assess || opts.simulate || opts.migrationsDir || opts.inspectDb)) throw new Error('--gate-policy is for static lint mode only');
55
62
  if (opts.assess) {
56
63
  const policy = opts.teamPolicy ? loadTeamPolicy(opts.teamPolicy) : null;
57
64
  const assessment = await combinedAssessment({ file: opts.simulate, migrationsDir: opts.migrationsDir, baseline: opts.baseline, verifySql: opts.verifySql, postgresVersion: String(opts.postgresVersion ?? '16'), config });
@@ -72,19 +79,34 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
72
79
  console.log(JSON.stringify(snapshot, null, 2));
73
80
  return;
74
81
  }
82
+ const gatePolicy = opts.gatePolicy ? loadTeamPolicy(opts.gatePolicy) : null;
83
+ if (gatePolicy?.requireSimulation) throw new Error('requireSimulation requires --assess with a disposable PostgreSQL simulation');
75
84
  const files=(opts.changed?getChangedSqlFiles(typeof opts.changed==='string'?opts.changed:undefined):findMigrationFiles(target)).filter(f=>!isExcluded(f,config.exclude));
76
85
  const entries=files.map(file=>({file:path.relative(process.cwd(),file)||file,sql:fs.readFileSync(file,'utf8')}));
77
86
  const findings=await analyzeFiles(entries,config,{advisor:opts.advisor});
87
+ const production = opts.productionContext ? productionAssessment(findings, loadProductionContext(opts.productionContext)) : null;
88
+ if (opts.writeRiskBaseline && opts.riskBaseline) throw new Error('Cannot combine --write-risk-baseline and --risk-baseline');
89
+ if (opts.writeRiskBaseline && opts.gatePolicy) throw new Error('Baseline creation cannot be combined with a gate policy');
90
+ const baselineComparison = opts.riskBaseline ? compareRiskBaseline(findings, entries, loadRiskBaseline(opts.riskBaseline)) : null;
91
+ // In baseline mode, only newly introduced findings are subject to the opt-in gate.
92
+ const gateFindings = baselineComparison ? baselineComparison.newFindings : findings;
93
+ const gate = opts.gatePolicy ? assessLintPolicy(gateFindings, gatePolicy, summarizeRisk(gateFindings)) : null;
94
+ if (opts.writeRiskBaseline) writeRiskBaseline(opts.writeRiskBaseline, createRiskBaseline(findings, entries));
78
95
  if (opts.github) process.stdout.write(toGitHubAnnotations(findings));
79
96
  if (opts.summary) {fs.mkdirSync(path.dirname(path.resolve(opts.summary)),{recursive:true});fs.writeFileSync(opts.summary,toMarkdownSummary(findings,files.length));}
80
- const report=opts.format==='json'?toJson(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion}):opts.format==='sarif'?toSarif(findings):[
97
+ const report=opts.format==='json'?toJson(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion}):opts.format==='sarif'?toSarif(findings):opts.format==='markdown'?toMarkdownReport(findings,{filesChecked:files.length,postgresVersion:config.postgresVersion,risk:opts.risk?summarizeRisk(findings):undefined}):[
81
98
  ...findings.flatMap(f=>[`${f.file}:${f.line}:${f.column} [${f.ruleId}] ${f.severity}: ${f.message}`,` Fix: ${f.fix}`,...(f.advisor?f.advisor.steps.map((s,i)=>` ${i+1}. ${s}`):[])]),
82
99
  ...(opts.risk?[`Risk: ${JSON.stringify(summarizeRisk(findings))}`]:[]),
83
100
  `Checked ${files.length} SQL file(s); found ${findings.length} configured risk(s). No downtime guarantee.`
84
101
  ].join('\n');
85
- if(opts.output) {fs.mkdirSync(path.dirname(path.resolve(opts.output)),{recursive:true});fs.writeFileSync(opts.output,report+'\n');}
86
- else console.log(opts.format==='text'?(findings.length?chalk.yellow(report):chalk.green(report)):report);
87
- process.exitCode=opts.failOn==='warning'?Number(findings.length>0):opts.failOn==='error'?Number(findings.some(f=>f.severity==='error')):0;
102
+ const gateReport = opts.format === 'json' && (gate || baselineComparison || production) ? JSON.stringify({ ...JSON.parse(report), ...(baselineComparison ? { baseline: { newCount: baselineComparison.newCount, existingCount: baselineComparison.existingCount, resolvedCount: baselineComparison.resolvedCount, newFindings: baselineComparison.newFindings } } : {}), ...(production ? { production } : {}), ...(gate ? { gate: { name: gate.name, decision: gate.passed ? 'PASS' : 'BLOCK', passed: gate.passed, reasons: gate.reasons, note: gate.note } } : {}) }, null, 2) : report;
103
+ if(opts.output) {fs.mkdirSync(path.dirname(path.resolve(opts.output)),{recursive:true});fs.writeFileSync(opts.output,gateReport+'\n');}
104
+ else console.log(opts.format==='text'?(findings.length?chalk.yellow(gateReport):chalk.green(gateReport)):gateReport);
105
+ if (production && opts.format !== 'json') console.error(`[PG Safe Migrate production] Advisory context evaluated for ${production.assessments.length} finding(s). Use --format json for details. No downtime guarantee.`);
106
+ if (baselineComparison && opts.format !== 'json') console.error(`[PG Safe Migrate baseline] ${baselineComparison.newCount} new, ${baselineComparison.existingCount} existing, ${baselineComparison.resolvedCount} resolved finding(s).`);
107
+ if (opts.writeRiskBaseline) console.error(`[PG Safe Migrate baseline] Wrote ${findings.length} finding fingerprint(s) to ${opts.writeRiskBaseline}; review before committing.`);
108
+ if (gate) console.error(`[PG Safe Migrate gate] ${gate.passed ? 'PASS' : 'BLOCK'} (${gate.name})${gate.reasons.length ? ': '+gate.reasons.join('; ') : ''}. ${gate.note}`);
109
+ process.exitCode=(gate && !gate.passed) || (opts.failOn==='warning' && gateFindings.length>0) || (opts.failOn==='error' && gateFindings.some(f=>f.severity==='error')) ? 1 : 0;
88
110
  }catch(e){console.error(`Error: ${e.message}`);process.exitCode=2;}
89
111
  });
90
112
  program.parse();
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "tool": "pg-safe-migrate",
4
+ "fingerprints": [
5
+ "ee03806a2ea992dae01c0042f8e7498f84ca5fe65f54d7b2dd58177e49cc565c"
6
+ ]
7
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "name": "pull-request-static-gate",
3
+ "blockedRules": ["PG001", "PG002", "PG003"],
4
+ "maxWarnings": 5,
5
+ "maxRiskScore": 60
6
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "tables": [
4
+ { "schema": "public", "table": "users", "estimatedRows": 1200000, "bytes": 2147483648, "writeQueriesPerSecond": 25 }
5
+ ],
6
+ "lockTimeoutMs": 2000,
7
+ "statementTimeoutMs": 300000
8
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@subodh001/pg-safe-migrate",
3
- "version": "2.3.0",
4
- "description": "PostgreSQL AST migration risk linter for Prisma, Drizzle and SQL",
3
+ "version": "2.5.0",
4
+ "description": "Detect risky PostgreSQL schema migrations before deployment: SQL linting, lock analysis, risk scoring and CI reports for Prisma, Drizzle and Flyway",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "pg-safe-migrate": "bin/cli.js"
@@ -22,7 +22,15 @@
22
22
  "prisma",
23
23
  "drizzle",
24
24
  "zero-downtime",
25
- "ast"
25
+ "ast",
26
+ "database-migration",
27
+ "migration-linter",
28
+ "schema-migration",
29
+ "migration-safety",
30
+ "database-safety",
31
+ "postgres-locks",
32
+ "flyway",
33
+ "sarif"
26
34
  ],
27
35
  "license": "MIT",
28
36
  "dependencies": {
package/src/advisor.js CHANGED
@@ -16,7 +16,62 @@ const plans = {
16
16
  PG016:['Check Drizzle runner transaction wrapping.','Execute CONCURRENTLY outside a transaction.','Verify the deployed migration in staging.'],
17
17
  PG017:['Inspect the earlier migration and dependency graph.','Confirm the final schema and deployment order.','Test the ordered migrations on staging.']
18
18
  };
19
+ // Illustrative templates only: never execute or apply them automatically.
20
+ // Identifiers, constraints and data predicates must be reviewed for each schema.
21
+ const alternatives = {
22
+ PG001: {
23
+ title: 'Build the index without blocking ordinary writes',
24
+ sql: '-- Run outside a transaction block; replace identifiers.\nCREATE INDEX CONCURRENTLY idx_orders_customer_id ON orders (customer_id);',
25
+ caveat: 'Concurrent builds can take longer, wait for transactions, and leave an invalid index after failure. Check for an existing index first.'
26
+ },
27
+ PG003: {
28
+ title: 'Use expand/backfill/contract for risky type changes',
29
+ sql: '-- Illustrative only: adapt types, conversion and names.\nALTER TABLE orders ADD COLUMN amount_new numeric;\n-- Backfill in bounded batches, with application dual-write.\n-- Switch reads, validate, then retire the old column in a later release.',
30
+ caveat: 'Column copying, conversion, triggers, application compatibility and constraints require a project-specific plan.'
31
+ },
32
+ PG004: {
33
+ title: 'Introduce required columns in stages',
34
+ sql: '-- Replace table/column/type and choose a real backfill policy.\nALTER TABLE customers ADD COLUMN region text;\n-- Backfill existing rows in bounded batches.\nALTER TABLE customers ADD CONSTRAINT customers_region_nn CHECK (region IS NOT NULL) NOT VALID;\nALTER TABLE customers VALIDATE CONSTRAINT customers_region_nn;\nALTER TABLE customers ALTER COLUMN region SET NOT NULL;',
35
+ caveat: 'Ensure new writes populate the column before validation. Validate PostgreSQL-version behavior and lock requirements.'
36
+ },
37
+ PG005: {
38
+ title: 'Add and validate a foreign key separately',
39
+ sql: '-- Replace identifiers and verify referenced keys.\nALTER TABLE orders ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers(id) NOT VALID;\nALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk;',
40
+ caveat: 'NOT VALID skips checking existing rows at creation, not enforcement for new rows. Validation still consumes resources and locks.'
41
+ },
42
+ PG010: {
43
+ title: 'Create unique index concurrently before attaching a constraint',
44
+ sql: '-- Check duplicates first; run outside transaction.\nCREATE UNIQUE INDEX CONCURRENTLY users_email_unique_idx ON users (email);\n-- For eligible plain-column indexes only:\nALTER TABLE users ADD CONSTRAINT users_email_unique UNIQUE USING INDEX users_email_unique_idx;',
45
+ caveat: 'Existing duplicates cause failure. Index eligibility, NULL semantics and transaction handling must be checked.'
46
+ },
47
+ PG012: {
48
+ title: 'Validate CHECK constraints in a separate step',
49
+ sql: '-- Replace predicate and identifiers.\nALTER TABLE orders ADD CONSTRAINT orders_total_nonnegative CHECK (total >= 0) NOT VALID;\nALTER TABLE orders VALIDATE CONSTRAINT orders_total_nonnegative;',
50
+ caveat: 'New or updated rows are checked immediately; validation of existing rows may fail and consumes resources.'
51
+ },
52
+ PG013: {
53
+ title: 'Prove non-null data before enforcing NOT NULL',
54
+ sql: '-- Replace identifiers. Ensure new writes cannot introduce NULLs.\nALTER TABLE users ADD CONSTRAINT users_email_nn CHECK (email IS NOT NULL) NOT VALID;\nALTER TABLE users VALIDATE CONSTRAINT users_email_nn;\nALTER TABLE users ALTER COLUMN email SET NOT NULL;',
55
+ caveat: 'On supported PostgreSQL versions, a validated CHECK may avoid a full scan for SET NOT NULL; lock requirements remain.'
56
+ },
57
+ PG025: {
58
+ title: 'Validate a non-null invariant first',
59
+ sql: '-- Replace identifiers. Backfill NULLs and prevent new NULLs first.\nALTER TABLE users ADD CONSTRAINT users_email_nn CHECK (email IS NOT NULL) NOT VALID;\nALTER TABLE users VALIDATE CONSTRAINT users_email_nn;\nALTER TABLE users ALTER COLUMN email SET NOT NULL;',
60
+ caveat: 'SET NOT NULL can still require a strong lock. Check version, traffic, existing NULLs and constraint lifecycle.'
61
+ },
62
+ PG023: {
63
+ title: 'Review destructive bulk removal',
64
+ sql: '-- No generally safe automatic rewrite for TRUNCATE.\n-- Consider retention, backup, maintenance window and bounded DELETE batches if appropriate.',
65
+ caveat: 'DELETE is not equivalent to TRUNCATE: triggers, identity sequences, foreign keys, MVCC and performance differ.'
66
+ },
67
+ PG024: {
68
+ title: 'Remove constraint dependencies in a separate deployment',
69
+ sql: '-- Review application and database dependencies first.\n-- Drop the constraint only after a compatible deployment and rollback plan.',
70
+ caveat: 'Dropping constraints can permit invalid data and requires appropriate locks. No universal safe SQL replacement exists.'
71
+ }
72
+ };
73
+
19
74
  export function advise(issue,framework='sql') {
20
- const context = framework==='prisma' ? 'Prisma migration: review migration.sql and the deployment runner.' : framework==='drizzle' ? 'Drizzle migration: review generated SQL and runner transaction behavior.' : 'Raw SQL: verify the execution transaction policy.';
21
- return {ruleId:issue.ruleId,steps:plans[issue.ruleId] || ['Review SQL dependencies.','Test on staging.','Deploy with lock and statement timeouts.'],note:`${context} Guidance only; not validated against a live database.`};
75
+ const context = framework==='prisma' ? 'Prisma migration: review migration.sql and the deployment runner.' : framework==='drizzle' ? 'Drizzle migration: review generated SQL and runner transaction behavior.' : framework==='flyway' ? 'Flyway migration: verify executeInTransaction settings, naming conventions and transaction grouping.' : 'Raw SQL: verify the execution transaction policy.';
76
+ return {ruleId:issue.ruleId,steps:plans[issue.ruleId] || ['Review SQL dependencies.','Test on staging.','Deploy with lock and statement timeouts.'],note:`${context} Guidance only; not validated against a live database.`,alternative: alternatives[issue.ruleId] ? {...alternatives[issue.ruleId], automatic: false} : null};
22
77
  }
package/src/analysis.js CHANGED
@@ -2,27 +2,44 @@
2
2
  import { parseSqlFile } from './parser.js';
3
3
  import { lintStatements } from './engine.js';
4
4
  import { advise } from './advisor.js';
5
-
6
5
  import { lockFor } from './locks.js';
7
- import { migrationPlan } from './plans.js';
8
6
 
9
7
  const ADVISORY_RULES = new Set(['PG015', 'PG016', 'PG017']);
10
8
 
11
9
  export function position(sql, offset = 0) {
12
- const prefix = sql.slice(0, Math.max(0, offset));
13
- const lines = prefix.split('\n');
10
+ const source = String(sql ?? '');
11
+ const numericOffset = Number(offset);
12
+
13
+ const safeOffset = Number.isFinite(numericOffset)
14
+ ? Math.min(
15
+ source.length,
16
+ Math.max(0, Math.floor(numericOffset))
17
+ )
18
+ : 0;
19
+
20
+ const prefix = source.slice(0, safeOffset);
21
+ const lastNewline = prefix.lastIndexOf('\n');
14
22
 
15
23
  return {
16
- line: lines.length,
17
- column: lines.at(-1).length + 1
24
+ line: prefix.split('\n').length,
25
+ column: safeOffset - lastNewline
18
26
  };
19
27
  }
20
28
 
21
29
  export function frameworkFor(file) {
22
- const p = file.replaceAll('\\', '/');
30
+ const p = file.replaceAll('\\', '/').toLowerCase();
31
+
32
+ if (/(^|\/)prisma\/migrations\//.test(p)) {
33
+ return 'prisma';
34
+ }
35
+
36
+ if (/(^|\/)drizzle\//.test(p)) {
37
+ return 'drizzle';
38
+ }
23
39
 
24
- if (/(^|\/)prisma\/migrations\//.test(p)) return 'prisma';
25
- if (/(^|\/)drizzle\//.test(p)) return 'drizzle';
40
+ if (/(^|\/)(?:sql\/)?(?:migrations\/)?(?:v[0-9][a-z0-9_.-]*__[^/]+|r__[^/]+)\.sql$/.test(p) || /(^|\/)db\/migration\/[^/]+\.sql$/.test(p)) {
41
+ return 'flyway';
42
+ }
26
43
 
27
44
  return 'sql';
28
45
  }
@@ -30,7 +47,10 @@ export function frameworkFor(file) {
30
47
  function txType(stmt) {
31
48
  const kind = stmt.TransactionStmt?.kind;
32
49
 
33
- if (kind === 'TRANS_STMT_BEGIN' || kind === 'TRANS_STMT_START') {
50
+ if (
51
+ kind === 'TRANS_STMT_BEGIN' ||
52
+ kind === 'TRANS_STMT_START'
53
+ ) {
34
54
  return 'begin';
35
55
  }
36
56
 
@@ -81,10 +101,13 @@ function extras(stmt, postgresVersion) {
81
101
  issues.push({ ruleId, message, fix });
82
102
  };
83
103
 
84
- if (!stmt.AlterTableStmt) return issues;
104
+ if (!stmt.AlterTableStmt) {
105
+ return issues;
106
+ }
85
107
 
86
108
  for (const wrapper of stmt.AlterTableStmt.cmds || []) {
87
109
  const cmd = wrapper.AlterTableCmd;
110
+
88
111
  if (!cmd) continue;
89
112
 
90
113
  if (cmd.subtype === 'AT_SetNotNull') {
@@ -142,15 +165,25 @@ function extras(stmt, postgresVersion) {
142
165
  return issues;
143
166
  }
144
167
 
145
- export async function analyzeFiles(entries, config = {}, options = {}) {
168
+ export async function analyzeFiles(
169
+ entries,
170
+ config = {},
171
+ options = {}
172
+ ) {
146
173
  const findings = [];
147
174
  const seen = new Map();
175
+
148
176
  const version = config.postgresVersion ?? null;
149
177
 
150
- const files = [...entries].sort((a, b) => a.file.localeCompare(b.file));
178
+ const files = [...entries].sort(
179
+ (a, b) => a.file.localeCompare(b.file)
180
+ );
151
181
 
152
182
  for (const { file, sql } of files) {
153
- const parsed = await parseSqlFile(sql, { details: true });
183
+ const parsed = await parseSqlFile(sql, {
184
+ details: true
185
+ });
186
+
154
187
  const framework = frameworkFor(file);
155
188
 
156
189
  let inTransaction = false;
@@ -159,41 +192,88 @@ export async function analyzeFiles(entries, config = {}, options = {}) {
159
192
  const loc = position(sql, offset);
160
193
  const transaction = txType(stmt);
161
194
 
195
+ // Track explicit transaction boundaries.
162
196
  if (transaction === 'begin') {
163
197
  inTransaction = true;
164
198
  }
165
199
 
200
+ // Findings generated by the main rule engine.
201
+ const ruleIssues = lintStatements(
202
+ [stmt],
203
+ { postgresVersion: version }
204
+ );
205
+
206
+ // Additional compatibility and advisory findings.
207
+ const extraIssues = extras(stmt, version);
208
+
209
+ // PG025 provides more specific SET NOT NULL guidance.
210
+ // Keep PG013 when PG025 is not generated.
211
+ const hasPG025 = ruleIssues.some(
212
+ issue => issue.ruleId === 'PG025'
213
+ );
214
+
166
215
  const issues = [
167
- ...lintStatements([stmt], { postgresVersion: version }),
168
- ...extras(stmt, version)
216
+ ...ruleIssues,
217
+ ...extraIssues.filter(
218
+ issue =>
219
+ !(hasPG025 && issue.ruleId === 'PG013')
220
+ )
169
221
  ];
170
222
 
223
+ // Concurrent index operations cannot run inside
224
+ // explicit PostgreSQL transactions.
171
225
  if (inTransaction && concurrently(stmt)) {
172
226
  issues.push({
173
227
  ruleId: 'PG008',
174
- message: 'CONCURRENTLY cannot execute inside an explicit transaction block.',
175
- fix: 'Run concurrent index operations outside BEGIN/COMMIT.'
228
+ message:
229
+ 'CONCURRENTLY cannot execute inside an explicit transaction block.',
230
+ fix:
231
+ 'Run concurrent index operations outside BEGIN/COMMIT.'
176
232
  });
177
233
  }
178
234
 
179
- if (framework === 'prisma' && concurrently(stmt)) {
235
+ // Prisma-specific migration guidance.
236
+ if (
237
+ framework === 'prisma' &&
238
+ concurrently(stmt)
239
+ ) {
180
240
  issues.push({
181
241
  ruleId: 'PG015',
182
- message: 'Prisma: use a standalone migration for CONCURRENTLY; combined SQL statements can fail in a transaction context.',
183
- fix: 'Review the generated migration and execution strategy; PostgreSQL forbids CONCURRENTLY inside a transaction.'
242
+ message:
243
+ 'Prisma: use a standalone migration for CONCURRENTLY; combined SQL statements can fail in a transaction context.',
244
+ fix:
245
+ 'Review the generated migration and execution strategy; PostgreSQL forbids CONCURRENTLY inside a transaction.'
184
246
  });
185
247
  }
186
248
 
187
- if (framework === 'drizzle' && concurrently(stmt)) {
249
+ // Drizzle-specific migration guidance.
250
+ if (
251
+ framework === 'drizzle' &&
252
+ concurrently(stmt)
253
+ ) {
188
254
  issues.push({
189
255
  ruleId: 'PG016',
190
- message: 'Drizzle node-postgres migrator uses a transaction in the tested version; CONCURRENTLY fails with PostgreSQL 25001.',
191
- fix: 'Execute the concurrent index through a separately managed non-transactional path; do not use the standard transactional migrator.'
256
+ message:
257
+ 'Drizzle node-postgres migrator uses a transaction in the tested version; CONCURRENTLY fails with PostgreSQL 25001.',
258
+ fix:
259
+ 'Execute the concurrent index through a separately managed non-transactional path; do not use the standard transactional migrator.'
260
+ });
261
+ }
262
+
263
+ // Flyway PostgreSQL migrations are normally transactional, unless the
264
+ // deployment configuration opts out. This is advice, not a claim about
265
+ // the actual runner's settings. Avoid inventing a new rule identifier.
266
+ if (framework === 'flyway' && concurrently(stmt)) {
267
+ issues.push({
268
+ ruleId: 'PG017',
269
+ message: 'Flyway: CONCURRENTLY requires non-transactional execution; verify executeInTransaction=false for this migration.',
270
+ fix: 'Configure this migration for non-transactional execution, review mixed statements, and verify Flyway edition/version behavior.'
192
271
  });
193
272
  }
194
273
 
195
274
  const target = ddlTarget(stmt);
196
275
 
276
+ // Detect potential cross-file dependencies.
197
277
  if (
198
278
  target &&
199
279
  seen.has(target) &&
@@ -207,8 +287,10 @@ export async function analyzeFiles(entries, config = {}, options = {}) {
207
287
  if (previous.file !== file) {
208
288
  issues.push({
209
289
  ruleId: 'PG017',
210
- message: `Potential cross-file dependency: ${target} was modified earlier in ${previous.file}.`,
211
- fix: 'Review migration order and deployed application compatibility; this is a heuristic, not proof of a conflict.'
290
+ message:
291
+ `Potential cross-file dependency: ${target} was modified earlier in ${previous.file}.`,
292
+ fix:
293
+ 'Review migration order and deployed application compatibility; this is a heuristic, not proof of a conflict.'
212
294
  });
213
295
  }
214
296
  }
@@ -217,9 +299,11 @@ export async function analyzeFiles(entries, config = {}, options = {}) {
217
299
  seen.set(target, { file });
218
300
  }
219
301
 
302
+ // Convert rule findings into report findings.
220
303
  for (const issue of issues) {
221
-
222
- const isAdvisory = ADVISORY_RULES.has(issue.ruleId);
304
+ const isAdvisory = ADVISORY_RULES.has(
305
+ issue.ruleId
306
+ );
223
307
 
224
308
  const defaultSeverity = isAdvisory
225
309
  ? 'warning'
@@ -227,12 +311,15 @@ export async function analyzeFiles(entries, config = {}, options = {}) {
227
311
 
228
312
  const severity =
229
313
  config.rules?.[issue.ruleId] ??
230
- (isAdvisory
231
- ? 'warning'
232
- : (config.severity ?? defaultSeverity));
233
-
234
-
235
- if (severity === 'off') continue;
314
+ (
315
+ isAdvisory
316
+ ? 'warning'
317
+ : (config.severity ?? defaultSeverity)
318
+ );
319
+
320
+ if (severity === 'off') {
321
+ continue;
322
+ }
236
323
 
237
324
  findings.push({
238
325
  ...issue,
@@ -243,11 +330,14 @@ export async function analyzeFiles(entries, config = {}, options = {}) {
243
330
  framework,
244
331
  lock: lockFor(stmt),
245
332
  ...(options.advisor
246
- ? { advisor: advise(issue, framework) }
333
+ ? {
334
+ advisor: advise(issue, framework)
335
+ }
247
336
  : {})
248
337
  });
249
338
  }
250
339
 
340
+ // Close the explicit transaction after processing.
251
341
  if (transaction === 'end') {
252
342
  inTransaction = false;
253
343
  }
package/src/combined.js CHANGED
@@ -45,7 +45,7 @@ export async function combinedAssessment({ file, migrationsDir, baseline, postgr
45
45
  const simulation = duplicate
46
46
  ? { passed: false, skipped: true, reason: 'Duplicate index definitions detected before simulation', steps: [] }
47
47
  : simulateSqlFile(file, { migrationsDir, baseline, postgresVersion, run, verifySql });
48
- const risk = summarizeRisk(findings);
48
+ const risk = summarizeRisk(findings, { operations });
49
49
  return {
50
50
  schemaVersion: 1, postgresVersion: Number(postgresVersion),
51
51
  execution: simulation, lint: { findings, count: findings.length, risk }, operations,
package/src/detector.js CHANGED
@@ -18,7 +18,7 @@ export function findMigrationFiles(targetPath) {
18
18
  }
19
19
  return scan(targetPath).sort();
20
20
  }
21
- const dirs = ['prisma/migrations', 'drizzle', 'migrations', 'db/migrations'];
21
+ const dirs = ['prisma/migrations', 'drizzle', 'migrations', 'db/migrations', 'db/migration', 'sql/migrations', 'sql'];
22
22
  const files = [...new Set(dirs.filter(d => fs.existsSync(d) && fs.statSync(d).isDirectory()).flatMap(scan))].sort();
23
23
  if (!files.length) throw new Error('No SQL migrations found. Supply a file or directory.');
24
24
  return files;
package/src/engine.js CHANGED
@@ -1,3 +1,4 @@
1
+
1
2
  import { additionalRules } from './rules/additionalRules.js';
2
3
  import { concurrentIndexRule } from './rules/concurrentIndex.js';
3
4
  import { dropColumnRule } from './rules/dropColumn.js';
@@ -19,16 +20,29 @@ const ACTIVE_RULES = [
19
20
 
20
21
  export function lintStatements(stmts, context = {}) {
21
22
  const violations = [];
23
+
22
24
  for (const stmt of stmts) {
25
+ const findings = [];
26
+
23
27
  for (const rule of ACTIVE_RULES) {
24
28
  const result = rule.check(stmt, context);
25
29
  if (!result) continue;
30
+
26
31
  if (Array.isArray(result)) {
27
- violations.push(...result);
32
+ findings.push(...result);
28
33
  } else {
29
- violations.push(result);
34
+ findings.push(result);
30
35
  }
31
36
  }
37
+
38
+ // PG025 provides more specific guidance for SET NOT NULL.
39
+ // Suppress PG013 only for this statement when PG025 exists.
40
+ const hasPG025 = findings.some(f => f.ruleId === 'PG025');
41
+
42
+ violations.push(
43
+ ...findings.filter(f => !(hasPG025 && f.ruleId === 'PG013'))
44
+ );
32
45
  }
46
+
33
47
  return violations;
34
48
  }
package/src/locks.js CHANGED
@@ -1,8 +1,18 @@
1
- // Conservative, statement-type classification. Does not model lock duration or contention.
1
+ // Conservative PostgreSQL table-lock inventory. These are planning hints, not
2
+ // predictions of wait time, lock duration, or production downtime.
3
+ function assessment(mode, impact, note, confidence = 'heuristic') {
4
+ return { mode, confidence, impact, note };
5
+ }
6
+
2
7
  export function lockFor(stmt) {
3
- if (stmt.AlterTableStmt || stmt.DropStmt?.removeType === 'OBJECT_TABLE' || stmt.RenameStmt) return { mode: 'ACCESS EXCLUSIVE', confidence: 'heuristic', note: 'May block readers/writers; exact mode varies by subcommand.' };
8
+ if (stmt.TruncateStmt) return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'TRUNCATE acquires ACCESS EXCLUSIVE on affected tables and can block readers and writers.', 'documented');
9
+ if (stmt.AlterTableStmt) return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'ALTER TABLE generally acquires ACCESS EXCLUSIVE; some subcommands use weaker locks. Check the specific operation.');
10
+ if (stmt.DropStmt?.removeType === 'OBJECT_TABLE') return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'DROP TABLE requires ACCESS EXCLUSIVE on the target table.', 'documented');
11
+ if (stmt.RenameStmt) return assessment('ACCESS EXCLUSIVE', 'reads-and-writes', 'Rename operations can require strong locks; verify the specific object and operation.');
4
12
  if (stmt.IndexStmt) return stmt.IndexStmt.concurrent
5
- ? { mode: 'SHARE UPDATE EXCLUSIVE', confidence: 'heuristic', note: 'Concurrent index builds still acquire locks and can wait.' }
6
- : { mode: 'SHARE', confidence: 'heuristic', note: 'Ordinary index creation can block writes.' };
7
- return { mode: 'unknown', confidence: 'unknown', note: 'Not classified.' };
13
+ ? assessment('SHARE UPDATE EXCLUSIVE', 'ddl-and-maintenance', 'CREATE INDEX CONCURRENTLY permits ordinary writes but can wait for transactions and conflicts with some maintenance.', 'documented')
14
+ : assessment('SHARE', 'writes', 'CREATE INDEX without CONCURRENTLY can block writes while the index is built.', 'documented');
15
+ if (stmt.VacuumStmt) return assessment('SHARE UPDATE EXCLUSIVE', 'ddl-and-maintenance', 'Ordinary VACUUM uses SHARE UPDATE EXCLUSIVE; VACUUM FULL uses ACCESS EXCLUSIVE. Verify the options.');
16
+ if (stmt.UpdateStmt || stmt.DeleteStmt || stmt.InsertStmt) return assessment('ROW EXCLUSIVE', 'conflicting-writers-and-ddl', 'DML acquires ROW EXCLUSIVE table locks; row-level contention and execution time are not assessed.', 'documented');
17
+ return assessment('unknown', 'unknown', 'Lock mode not classified; do not assume this operation is lock-free.', 'unknown');
8
18
  }
package/src/parser.js CHANGED
@@ -1,13 +1,50 @@
1
+
1
2
  import pgQuery from 'libpg-query';
2
3
 
3
4
  export async function parseSqlFile(sqlContent, options = {}) {
4
- if (!sqlContent || !sqlContent.trim()) return [];
5
+ if (!sqlContent || !sqlContent.trim()) {
6
+ return [];
7
+ }
8
+
5
9
  try {
6
10
  const result = await pgQuery.parse(sqlContent);
7
11
  const statements = result.stmts || [];
8
- if (!options.details) return statements.map(s => s.stmt);
9
- return statements.map(s => ({stmt:s.stmt,offset:typeof s.stmt_location==='number'?s.stmt_location:0}));
12
+
13
+ if (!options.details) {
14
+ return statements.map(s => s.stmt);
15
+ }
16
+
17
+ const source = String(sqlContent);
18
+
19
+ return statements.map(s => {
20
+ let offset =
21
+ typeof s.stmt_location === 'number'
22
+ ? s.stmt_location
23
+ : 0;
24
+
25
+ offset = Math.max(
26
+ 0,
27
+ Math.min(offset, source.length)
28
+ );
29
+
30
+ // PostgreSQL may report the beginning of the
31
+ // statement span before leading whitespace.
32
+ // Advance to the first non-whitespace character.
33
+ while (
34
+ offset < source.length &&
35
+ /\s/.test(source[offset])
36
+ ) {
37
+ offset++;
38
+ }
39
+
40
+ return {
41
+ stmt: s.stmt,
42
+ offset
43
+ };
44
+ });
10
45
  } catch (err) {
11
- throw new Error(`SQL Syntax Error: ${err.message}`);
46
+ throw new Error(
47
+ `SQL Syntax Error: ${err.message}`
48
+ );
12
49
  }
13
50
  }
@@ -0,0 +1,78 @@
1
+ import fs from 'node:fs';
2
+
3
+ const MAX_BYTES = 1024 * 1024;
4
+ const MAX_TABLES = 200;
5
+ const MAX_ROWS = 1e15;
6
+ const MAX_TABLE_BYTES = 1e18;
7
+ const MAX_MS = 3600000;
8
+ const allowed = new Set(['schema', 'table', 'estimatedRows', 'bytes', 'writeQueriesPerSecond']);
9
+
10
+ function plainObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); }
11
+ function boundedNumber(value, name, max) {
12
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > max) throw new Error(`${name} must be a finite non-negative number <= ${max}`);
13
+ return value;
14
+ }
15
+ export function validateProductionContext(input) {
16
+ if (!plainObject(input) || input.schemaVersion !== 1 || !Array.isArray(input.tables)) throw new Error('production context requires schemaVersion 1 and a tables array');
17
+ if (input.tables.length > MAX_TABLES) throw new Error(`production context supports at most ${MAX_TABLES} tables`);
18
+ for (const key of Object.keys(input)) if (!['schemaVersion', 'tables', 'lockTimeoutMs', 'statementTimeoutMs'].includes(key)) throw new Error(`Unknown production context field: ${key}`);
19
+ const tables = [];
20
+ const seen = new Set();
21
+ for (const row of input.tables) {
22
+ if (!plainObject(row)) throw new Error('production context table entry must be an object');
23
+ for (const key of Object.keys(row)) if (!allowed.has(key)) throw new Error(`Unknown production table field: ${key}`);
24
+ if (typeof row.schema !== 'string' || !/^[a-zA-Z_][\w$]{0,62}$/.test(row.schema) || typeof row.table !== 'string' || !/^[a-zA-Z_][\w$]{0,62}$/.test(row.table)) throw new Error('production table schema and table must be simple PostgreSQL identifiers');
25
+ const id = `${row.schema.toLowerCase()}.${row.table.toLowerCase()}`;
26
+ if (seen.has(id)) throw new Error(`Duplicate production table: ${id}`);
27
+ seen.add(id);
28
+ const entry = { schema: row.schema, table: row.table };
29
+ if (row.estimatedRows !== undefined) entry.estimatedRows = boundedNumber(row.estimatedRows, 'estimatedRows', MAX_ROWS);
30
+ if (row.bytes !== undefined) entry.bytes = boundedNumber(row.bytes, 'bytes', MAX_TABLE_BYTES);
31
+ if (row.writeQueriesPerSecond !== undefined) entry.writeQueriesPerSecond = boundedNumber(row.writeQueriesPerSecond, 'writeQueriesPerSecond', 1e7);
32
+ tables.push(entry);
33
+ }
34
+ const result = { schemaVersion: 1, tables };
35
+ if (input.lockTimeoutMs !== undefined) result.lockTimeoutMs = boundedNumber(input.lockTimeoutMs, 'lockTimeoutMs', MAX_MS);
36
+ if (input.statementTimeoutMs !== undefined) result.statementTimeoutMs = boundedNumber(input.statementTimeoutMs, 'statementTimeoutMs', MAX_MS);
37
+ return result;
38
+ }
39
+ export function loadProductionContext(file) {
40
+ const stat = fs.statSync(file);
41
+ if (stat.size > MAX_BYTES) throw new Error('production context file exceeds 1 MiB');
42
+ let parsed;
43
+ try { parsed = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { throw new Error('Invalid production context JSON'); }
44
+ return validateProductionContext(parsed);
45
+ }
46
+ function tableMention(message) {
47
+ const quoted = String(message).match(/(?:on|table)\s+["']?([a-zA-Z_][\w$]*(?:\.[a-zA-Z_][\w$]*)?)["']?/i);
48
+ return quoted?.[1]?.toLowerCase() || null;
49
+ }
50
+ export function productionAssessment(findings, context) {
51
+ const tables = context.tables;
52
+ const assessments = findings.map(finding => {
53
+ const mention = tableMention(finding.message);
54
+ const matches = mention ? tables.filter(t => `${t.schema}.${t.table}`.toLowerCase() === mention || t.table.toLowerCase() === mention) : [];
55
+ const table = matches.length === 1 ? matches[0] : null;
56
+ const mode = finding.lock?.mode || 'unknown';
57
+ const writesBlocked = ['ACCESS EXCLUSIVE', 'EXCLUSIVE', 'SHARE', 'SHARE ROW EXCLUSIVE'].includes(mode);
58
+ const readsBlocked = mode === 'ACCESS EXCLUSIVE';
59
+ const large = Boolean(table && ((table.estimatedRows ?? 0) >= 1000000 || (table.bytes ?? 0) >= 1073741824));
60
+ const busy = Boolean(table && (table.writeQueriesPerSecond ?? 0) >= 10);
61
+ const factors = [];
62
+ if (mode === 'unknown') factors.push('Lock behavior is unknown; manual review required');
63
+ else factors.push(`Classified lock: ${mode}${readsBlocked ? ' (may block reads and writes)' : writesBlocked ? ' (may block writes)' : ''}`);
64
+ if (large) factors.push('Supplied table estimate is large (>= 1M rows or >= 1 GiB)');
65
+ if (busy) factors.push('Supplied write rate is >= 10 queries/second');
66
+ if (!table) factors.push(matches.length > 1 ? 'Ambiguous table match; production statistics not applied' : 'No matching production table statistics supplied');
67
+ const guidance = [];
68
+ if (finding.ruleId === 'PG001') guidance.push('Consider CREATE INDEX CONCURRENTLY outside a transaction; check framework transaction settings and monitor index progress');
69
+ else if (['PG002', 'PG003', 'PG024', 'PG025'].includes(finding.ruleId)) guidance.push('Consider an expand/backfill/validate/contract rollout with application compatibility checks');
70
+ else if (finding.ruleId === 'PG023') guidance.push('Review data-loss consequences and schedule TRUNCATE with an explicit maintenance plan');
71
+ else guidance.push('Review lock scope, expected execution time, and rollback strategy before deployment');
72
+ if (writesBlocked || readsBlocked) guidance.push('Use a tested lock_timeout and monitor blocking sessions; a timeout does not eliminate lock risk');
73
+ if (context.lockTimeoutMs !== undefined) factors.push(`Provided lock_timeout: ${context.lockTimeoutMs} ms (not verified against server)`);
74
+ if (context.statementTimeoutMs !== undefined) factors.push(`Provided statement_timeout: ${context.statementTimeoutMs} ms (not verified against server)`);
75
+ return { ruleId: finding.ruleId, file: finding.file, line: finding.line, column: finding.column, table: table ? `${table.schema}.${table.table}` : null, lockMode: mode, potentialImpact: readsBlocked ? 'reads-and-writes' : writesBlocked ? 'writes' : 'review-required', attention: large && (writesBlocked || readsBlocked) ? 'elevated' : 'review', factors, guidance };
76
+ });
77
+ return { source: 'user-supplied estimates (not a live database inspection)', confidence: 'limited', assessments, limitations: ['Table statistics and workload rates may be stale or inaccurate', 'SQL table matching is heuristic; schema ambiguity prevents applying estimates', 'No measured lock waits, execution duration, or downtime prediction', 'Existing policy gate decisions are unchanged'] };
78
+ }
package/src/reports.js CHANGED
@@ -3,3 +3,33 @@ export function toSarif(findings) {
3
3
  const ids = [...new Set(findings.map(f => f.ruleId))].sort();
4
4
  return JSON.stringify({ version: '2.1.0', $schema: 'https://json.schemastore.org/sarif-2.1.0.json', runs: [{ tool: { driver: { name: 'pg-safe-migrate', informationUri: 'https://github.com/subodhsingh001/pg-safe-migrate', rules: ids.map(id => ({ id, shortDescription: { text: id } })) } }, results: findings.map(f => ({ ruleId: f.ruleId, level: f.severity === 'warning' ? 'warning' : 'error', message: { text: `${f.message} Fix: ${f.fix}` }, locations: [{ physicalLocation: { artifactLocation: { uri: f.file.replaceAll('\\','/') }, region: { startLine: Math.max(1, f.line || 1), startColumn: Math.max(1, f.column || 1) } } }] })) }] }, null, 2);
5
5
  }
6
+
7
+ // Human-readable report. Escapes Markdown cells and never includes untrusted HTML.
8
+ const mdCell = value => String(value ?? '').replace(/\r?\n/g, ' ').replace(/\|/g, '\\|').replace(/</g, '&lt;').replace(/>/g, '&gt;');
9
+ export function toMarkdownReport(findings = [], { filesChecked = 0, postgresVersion, risk } = {}) {
10
+ const errors = findings.filter(f => f.severity === 'error').length;
11
+ const warnings = findings.filter(f => f.severity === 'warning').length;
12
+ const lines = [
13
+ '# PG Safe Migrate report', '',
14
+ `Files checked: **${filesChecked}** | Errors: **${errors}** | Warnings: **${warnings}**${postgresVersion ? ` | PostgreSQL: **${mdCell(postgresVersion)}**` : ''}`, ''
15
+ ];
16
+ if (risk) {
17
+ lines.push('## Risk assessment', '', `**${risk.score}/100 (${mdCell(risk.band)})** — heuristic, not a downtime prediction.`, '');
18
+ if (risk.breakdown) {
19
+ lines.push('| Component | Points |', '|---|---:|');
20
+ for (const [name, value] of Object.entries(risk.breakdown)) lines.push(`| ${mdCell(name)} | ${Number(value) || 0} |`);
21
+ lines.push('');
22
+ }
23
+ if (risk.unknownLocks) lines.push('**Unclassified locks present:** review SQL manually.', '');
24
+ if (risk.limitations?.length) lines.push('Limitations: ' + risk.limitations.map(mdCell).join('; ') + '.', '');
25
+ }
26
+ lines.push('## Findings', '');
27
+ if (!findings.length) lines.push('No configured findings. This does not guarantee a safe migration.', '');
28
+ else {
29
+ lines.push('| Rule | Severity | File | Line | Message | Recommendation |', '|---|---|---|---:|---|---|');
30
+ for (const f of findings) lines.push(`| ${mdCell(f.ruleId)} | ${mdCell(f.severity)} | ${mdCell(f.file)} | ${Math.max(1, Number(f.line) || 1)} | ${mdCell(f.message)} | ${mdCell(f.fix)} |`);
31
+ lines.push('');
32
+ }
33
+ lines.push('> Static analysis is advisory. Review locks, data volume, transaction behavior, and production workload before deployment.', '');
34
+ return lines.join('\n');
35
+ }
@@ -0,0 +1,54 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+
5
+ const sha = value => crypto.createHash('sha256').update(value).digest('hex');
6
+ const normalizedPath = file => String(file).replaceAll('\\', '/').replace(/^\.\//, '').replace(/\/+/g, '/');
7
+ const normalizedSql = sql => String(sql).replace(/--[^\n]*/g, '').replace(/\/\*[\s\S]*?\*\//g, '').replace(/\s+/g, ' ').trim().toLowerCase();
8
+
9
+ // Statement boundaries are derived from the parser's starting positions when available.
10
+ // A conservative text fallback is used for baseline identity; it is not a SQL parser.
11
+ function statementAt(sql, line) {
12
+ const lines = String(sql).split(/\r?\n/);
13
+ const start = Math.max(0, Math.min(lines.length - 1, Number(line || 1) - 1));
14
+ let begin = start;
15
+ while (begin > 0 && !lines[begin - 1].includes(';')) begin--;
16
+ let end = start;
17
+ while (end < lines.length - 1 && !lines[end].includes(';')) end++;
18
+ return normalizedSql(lines.slice(begin, end + 1).join('\n'));
19
+ }
20
+
21
+ export function fingerprint(finding, sqlByFile = new Map()) {
22
+ const file = normalizedPath(finding.file);
23
+ const sql = sqlByFile.get(file);
24
+ const identity = sql === undefined ? String(finding.message || '') : statementAt(sql, finding.line);
25
+ return sha(JSON.stringify([file, finding.ruleId, finding.severity, identity]));
26
+ }
27
+ export function createRiskBaseline(findings, entries) {
28
+ const sqlByFile = new Map(entries.map(e => [normalizedPath(e.file), e.sql]));
29
+ const fingerprints = findings.map(f => fingerprint(f, sqlByFile)).sort();
30
+ return { schemaVersion: 1, tool: 'pg-safe-migrate', fingerprints };
31
+ }
32
+ export function loadRiskBaseline(filename) {
33
+ const obj = JSON.parse(fs.readFileSync(filename, 'utf8'));
34
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj) || obj.schemaVersion !== 1 || obj.tool !== 'pg-safe-migrate' || !Array.isArray(obj.fingerprints) || obj.fingerprints.length > 100000 || obj.fingerprints.some(x => typeof x !== 'string' || !/^[a-f0-9]{64}$/.test(x))) throw new Error('Invalid risk baseline (expected schemaVersion 1 and SHA-256 fingerprints)');
35
+ return obj;
36
+ }
37
+ export function compareRiskBaseline(findings, entries, baseline) {
38
+ const sqlByFile = new Map(entries.map(e => [normalizedPath(e.file), e.sql]));
39
+ const previous = new Map();
40
+ for (const id of baseline.fingerprints) previous.set(id, (previous.get(id) || 0) + 1);
41
+ const newFindings = [], existingFindings = [];
42
+ for (const f of findings) {
43
+ const id = fingerprint(f, sqlByFile);
44
+ if ((previous.get(id) || 0) > 0) { existingFindings.push(f); previous.set(id, previous.get(id) - 1); }
45
+ else newFindings.push(f);
46
+ }
47
+ const resolved = [...previous.values()].reduce((a,b)=>a+b,0);
48
+ return { newFindings, existingFindings, resolvedCount: resolved, newCount: newFindings.length, existingCount: existingFindings.length };
49
+ }
50
+ export function writeRiskBaseline(filename, baseline) {
51
+ const dest = path.resolve(filename);
52
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
53
+ fs.writeFileSync(dest, JSON.stringify(baseline, null, 2) + '\n', { flag: 'w' });
54
+ }
package/src/risk.js CHANGED
@@ -1,5 +1,29 @@
1
+ // A bounded, explainable heuristic; not a prediction of outage duration.
1
2
  const weights = { error: 20, warning: 5 };
2
- export function summarizeRisk(findings) {
3
- const score = Math.min(100, findings.reduce((sum, f) => sum + (weights[f.severity] || 0), 0));
4
- return { score, band: score >= 60 ? 'high' : score >= 20 ? 'moderate' : 'low', confidence: 'low', basis: 'Heuristic severity counts only; no database statistics or production workload context.' };
3
+ const lockWeights = { 'ACCESS EXCLUSIVE': 15, 'EXCLUSIVE': 12, 'SHARE ROW EXCLUSIVE': 10, 'SHARE': 8, 'SHARE UPDATE EXCLUSIVE': 4, 'ROW EXCLUSIVE': 2 };
4
+ const destructiveRules = new Set(['PG001', 'PG002', 'PG003', 'PG023', 'PG024']);
5
+ const clamp = n => Math.max(0, Math.min(100, n));
6
+
7
+ export function summarizeRisk(findings = [], context = {}) {
8
+ const operations = Array.isArray(context.operations) ? context.operations : [];
9
+ const severityPoints = findings.reduce((sum, f) => sum + (weights[f.severity] || 0), 0);
10
+ // Only count distinct rule/location combinations to avoid inflated scores.
11
+ const destructive = new Set(findings.filter(f => destructiveRules.has(f.ruleId)).map(f => `${f.file || ''}:${f.line || 0}:${f.ruleId}`));
12
+ const destructivePoints = Math.min(20, destructive.size * 5);
13
+ // Maximum lock impact, rather than summing every statement in a large migration.
14
+ const lockPoints = operations.reduce((max, operation) => Math.max(max, lockWeights[operation?.lock?.mode] || 0), 0);
15
+ const unknownLocks = operations.some(operation => !operation?.lock?.mode || operation.lock.mode === 'unknown');
16
+ const transactionPoints = context.transactionRisk === true ? 10 : 0;
17
+ // Optional metadata is advisory only: never infer table size from SQL text.
18
+ const stats = context.tableStats;
19
+ const tableSizePoints = stats && Number.isFinite(stats.estimatedRows) && stats.estimatedRows >= 1000000 ? 10 : 0;
20
+ const score = clamp(severityPoints + destructivePoints + lockPoints + transactionPoints + tableSizePoints);
21
+ return {
22
+ score, band: score >= 60 ? 'high' : score >= 20 ? 'moderate' : 'low',
23
+ confidence: 'low',
24
+ basis: 'Bounded heuristic based on lint severity, destructive operations, strongest classified table lock, optional transaction flag and supplied table statistics. Not a prediction of downtime.',
25
+ breakdown: { severity: clamp(severityPoints), destructive: destructivePoints, lock: lockPoints, transaction: transactionPoints, tableSize: tableSizePoints },
26
+ unknownLocks,
27
+ limitations: ['No production workload or lock wait measurements', 'Table statistics are optional estimates', 'Lock classifications may be conservative']
28
+ };
5
29
  }
@@ -1,13 +1,16 @@
1
1
  import fs from 'node:fs';
2
+ import { getRule } from './rules/ruleCatalog.js';
2
3
 
3
4
  export function loadTeamPolicy(file) {
4
5
  const policy = JSON.parse(fs.readFileSync(file, 'utf8'));
5
6
  if (!policy || typeof policy !== 'object' || Array.isArray(policy)) throw new Error('Team policy must be a JSON object');
6
7
  const allowed = ['name', 'maxRiskScore', 'maxWarnings', 'blockedRules', 'requireSimulation'];
7
8
  for (const key of Object.keys(policy)) if (!allowed.includes(key)) throw new Error(`Unknown team policy key: ${key}`);
9
+ if (policy.name !== undefined && (typeof policy.name !== 'string' || !policy.name.trim() || policy.name.length > 100)) throw new Error('name must be a nonempty string of at most 100 characters');
8
10
  if (policy.maxRiskScore !== undefined && (!Number.isInteger(policy.maxRiskScore) || policy.maxRiskScore < 0 || policy.maxRiskScore > 100)) throw new Error('maxRiskScore must be 0-100');
9
11
  if (policy.maxWarnings !== undefined && (!Number.isInteger(policy.maxWarnings) || policy.maxWarnings < 0)) throw new Error('maxWarnings must be >= 0');
10
- if (policy.blockedRules !== undefined && (!Array.isArray(policy.blockedRules) || policy.blockedRules.some(x => !/^PG\d{3}$/.test(x)))) throw new Error('blockedRules must be an array of PG rule IDs');
12
+ if (policy.blockedRules !== undefined && (!Array.isArray(policy.blockedRules) || policy.blockedRules.some(x => typeof x !== 'string' || !getRule(x)))) throw new Error('blockedRules must be an array of PG rule IDs');
13
+ if (policy.blockedRules && new Set(policy.blockedRules).size !== policy.blockedRules.length) throw new Error('blockedRules must not contain duplicates');
11
14
  if (policy.requireSimulation !== undefined && typeof policy.requireSimulation !== 'boolean') throw new Error('requireSimulation must be boolean');
12
15
  return policy;
13
16
  }
@@ -21,3 +24,25 @@ export function assessTeamPolicy(report, policy) {
21
24
  for (const f of findings) if (policy.blockedRules?.includes(f.ruleId)) reasons.push(`Blocked rule ${f.ruleId}: ${f.file}`);
22
25
  return { name: policy.name ?? 'local-team', passed: reasons.length === 0, reasons: [...new Set(reasons)] };
23
26
  }
27
+
28
+ // Week 3: static-only CI gate. The existing --assess policy behavior is unchanged.
29
+ export function validateLintPolicy(policy) {
30
+ if (policy.requireSimulation === true) throw new Error('requireSimulation requires --assess with a disposable PostgreSQL simulation');
31
+ return policy;
32
+ }
33
+
34
+ export function assessLintPolicy(findings, policy, risk = {}) {
35
+ validateLintPolicy(policy);
36
+ // A score is only a heuristic derived from the configured lint findings.
37
+ const reasons = [];
38
+ const warningCount = findings.filter(f => f.severity === 'warning').length;
39
+ if (policy.maxWarnings !== undefined && warningCount > policy.maxWarnings) reasons.push(`Warnings ${warningCount} exceed ${policy.maxWarnings}`);
40
+ if (policy.maxRiskScore !== undefined) {
41
+ const severityScore = Math.min(100, findings.reduce((n, f) => n + (f.severity === 'error' ? 20 : f.severity === 'warning' ? 5 : 0), 0));
42
+ // Actual heuristic is calculated by the caller and passed separately when available.
43
+ const score = risk.score ?? severityScore;
44
+ if (score > policy.maxRiskScore) reasons.push(`Heuristic risk score ${score} exceeds ${policy.maxRiskScore}`);
45
+ }
46
+ for (const f of findings) if (policy.blockedRules?.includes(f.ruleId)) reasons.push(`Blocked rule ${f.ruleId}: ${f.file}`);
47
+ return { name: policy.name ?? 'local-team', passed: reasons.length === 0, reasons: [...new Set(reasons)], note: 'Passing a static gate is not a safety guarantee; unknown locks and production workloads still require review.' };
48
+ }