@subodh001/pg-safe-migrate 2.4.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`:
package/bin/cli.js CHANGED
@@ -17,7 +17,9 @@ 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')
@@ -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')
@@ -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,9 +79,19 @@ 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
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}):[
@@ -82,9 +99,14 @@ program.name('pg-safe-migrate').description('AST-based PostgreSQL migration risk
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.4.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": {
@@ -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
+ }
@@ -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
+ }
@@ -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
+ }