-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcheck.js
More file actions
332 lines (294 loc) · 11 KB
/
check.js
File metadata and controls
332 lines (294 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { findDbPath, openReadonlyOrFail } from '../db/index.js';
import { bfsTransitiveCallers } from '../domain/analysis/impact.js';
import { findCycles } from '../domain/graph/cycles.js';
import { loadConfig } from '../infrastructure/config.js';
import { isTestFile } from '../infrastructure/test-filter.js';
import { matchOwners, parseCodeowners } from './owners.js';
// ─── Diff Parser ──────────────────────────────────────────────────────
/**
* Parse unified diff output, extracting both new-side (+) and old-side (-) ranges.
* Old-side ranges are needed for signature detection (DB line numbers = pre-change).
*
* @param {string} diffOutput - Raw `git diff --unified=0` output
* @returns {{ changedRanges: Map<string, {start:number,end:number}[]>, oldRanges: Map<string, {start:number,end:number}[]>, newFiles: Set<string> }}
*/
export function parseDiffOutput(diffOutput) {
const changedRanges = new Map();
const oldRanges = new Map();
const newFiles = new Set();
let currentFile = null;
let prevIsDevNull = false;
for (const line of diffOutput.split('\n')) {
if (line.startsWith('--- /dev/null')) {
prevIsDevNull = true;
continue;
}
if (line.startsWith('--- ')) {
prevIsDevNull = false;
continue;
}
const fileMatch = line.match(/^\+\+\+ b\/(.+)/);
if (fileMatch) {
currentFile = fileMatch[1];
if (!changedRanges.has(currentFile)) changedRanges.set(currentFile, []);
if (!oldRanges.has(currentFile)) oldRanges.set(currentFile, []);
if (prevIsDevNull) newFiles.add(currentFile);
prevIsDevNull = false;
continue;
}
const hunkMatch = line.match(/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/);
if (hunkMatch && currentFile) {
const oldStart = parseInt(hunkMatch[1], 10);
const oldCount = parseInt(hunkMatch[2] || '1', 10);
if (oldCount > 0) {
oldRanges.get(currentFile).push({ start: oldStart, end: oldStart + oldCount - 1 });
}
const newStart = parseInt(hunkMatch[3], 10);
const newCount = parseInt(hunkMatch[4] || '1', 10);
if (newCount > 0) {
changedRanges.get(currentFile).push({ start: newStart, end: newStart + newCount - 1 });
}
}
}
return { changedRanges, oldRanges, newFiles };
}
// ─── Predicates ───────────────────────────────────────────────────────
/**
* Predicate 1: Assert no dependency cycles involve changed files.
*/
export function checkNoNewCycles(db, changedFiles, noTests) {
const cycles = findCycles(db, { fileLevel: true, noTests });
const involved = cycles.filter((cycle) => cycle.some((f) => changedFiles.has(f)));
return { passed: involved.length === 0, cycles: involved };
}
/**
* Predicate 2: Assert no function exceeds N transitive callers.
*/
export function checkMaxBlastRadius(db, changedRanges, threshold, noTests, maxDepth) {
const violations = [];
let maxFound = 0;
for (const [file, ranges] of changedRanges) {
if (noTests && isTestFile(file)) continue;
const defs = db
.prepare(
`SELECT * FROM nodes WHERE file = ? AND kind IN ('function', 'method', 'class') ORDER BY line`,
)
.all(file);
for (let i = 0; i < defs.length; i++) {
const def = defs[i];
const endLine = def.end_line || (defs[i + 1] ? defs[i + 1].line - 1 : 999999);
let overlaps = false;
for (const range of ranges) {
if (range.start <= endLine && range.end >= def.line) {
overlaps = true;
break;
}
}
if (!overlaps) continue;
const { totalDependents: totalCallers } = bfsTransitiveCallers(db, def.id, {
noTests,
maxDepth,
});
if (totalCallers > maxFound) maxFound = totalCallers;
if (totalCallers > threshold) {
violations.push({
name: def.name,
kind: def.kind,
file: def.file,
line: def.line,
transitiveCallers: totalCallers,
});
}
}
}
return { passed: violations.length === 0, maxFound, threshold, violations };
}
/**
* Predicate 3: Assert no function declaration lines were modified.
* Uses old-side hunk ranges (which correspond to DB line numbers from last build).
*/
export function checkNoSignatureChanges(db, oldRanges, noTests) {
const violations = [];
for (const [file, ranges] of oldRanges) {
if (ranges.length === 0) continue;
if (noTests && isTestFile(file)) continue;
const defs = db
.prepare(
`SELECT name, kind, file, line FROM nodes WHERE file = ? AND kind IN ('function', 'method', 'class') ORDER BY line`,
)
.all(file);
for (const def of defs) {
for (const range of ranges) {
if (def.line >= range.start && def.line <= range.end) {
violations.push({
name: def.name,
kind: def.kind,
file: def.file,
line: def.line,
});
break;
}
}
}
}
return { passed: violations.length === 0, violations };
}
/**
* Predicate 4: Assert no cross-owner boundary violations among changed files.
*/
export function checkNoBoundaryViolations(db, changedFiles, repoRoot, noTests) {
const parsed = parseCodeowners(repoRoot);
if (!parsed) {
return { passed: true, violations: [], note: 'No CODEOWNERS file found — skipped' };
}
const changedSet = changedFiles instanceof Set ? changedFiles : new Set(changedFiles);
const edges = db
.prepare(
`SELECT e.kind AS edgeKind,
s.file AS srcFile, t.file AS tgtFile
FROM edges e
JOIN nodes s ON e.source_id = s.id
JOIN nodes t ON e.target_id = t.id
WHERE e.kind = 'calls'`,
)
.all();
const violations = [];
for (const e of edges) {
if (noTests && (isTestFile(e.srcFile) || isTestFile(e.tgtFile))) continue;
if (!changedSet.has(e.srcFile) && !changedSet.has(e.tgtFile)) continue;
const srcOwners = matchOwners(e.srcFile, parsed.rules).sort().join(',');
const tgtOwners = matchOwners(e.tgtFile, parsed.rules).sort().join(',');
if (srcOwners !== tgtOwners) {
violations.push({
from: e.srcFile,
to: e.tgtFile,
edgeKind: e.edgeKind,
});
}
}
return { passed: violations.length === 0, violations };
}
// ─── Main ─────────────────────────────────────────────────────────────
/**
* Run validation predicates against git changes.
*
* @param {string} [customDbPath] - Path to graph.db
* @param {object} opts
* @param {string} [opts.ref] - Git ref to diff against
* @param {boolean} [opts.staged] - Analyze staged changes
* @param {boolean} [opts.cycles] - Enable cycles predicate
* @param {number} [opts.blastRadius] - Blast radius threshold
* @param {boolean} [opts.signatures] - Enable signatures predicate
* @param {boolean} [opts.boundaries] - Enable boundaries predicate
* @param {number} [opts.depth] - Max BFS depth (default: 3)
* @param {boolean} [opts.noTests] - Exclude test files
* @returns {{ predicates: object[], summary: object, passed: boolean }}
*/
export function checkData(customDbPath, opts = {}) {
const db = openReadonlyOrFail(customDbPath);
try {
const dbPath = findDbPath(customDbPath);
const repoRoot = path.resolve(path.dirname(dbPath), '..');
const noTests = opts.noTests || false;
const maxDepth = opts.depth || 3;
// Load config defaults for check predicates
// NOTE: opts.config is loaded from process.cwd() at startup (via CLI context),
// which may differ from the DB's parent repo root when --db points to an external
// project. This is an acceptable trade-off to avoid duplicate I/O on the hot path.
const config = opts.config || loadConfig(repoRoot);
const checkConfig = config.check || {};
// Resolve which predicates are enabled: CLI flags ?? config ?? built-in defaults
const enableCycles = opts.cycles ?? checkConfig.cycles ?? true;
const enableSignatures = opts.signatures ?? checkConfig.signatures ?? true;
const enableBoundaries = opts.boundaries ?? checkConfig.boundaries ?? true;
const blastRadiusThreshold = opts.blastRadius ?? checkConfig.blastRadius ?? null;
// Verify git repo
let checkDir = repoRoot;
let isGitRepo = false;
while (checkDir) {
if (fs.existsSync(path.join(checkDir, '.git'))) {
isGitRepo = true;
break;
}
const parent = path.dirname(checkDir);
if (parent === checkDir) break;
checkDir = parent;
}
if (!isGitRepo) {
return { error: `Not a git repository: ${repoRoot}` };
}
// Run git diff
let diffOutput;
try {
const args = opts.staged
? ['diff', '--cached', '--unified=0', '--no-color']
: ['diff', opts.ref || 'HEAD', '--unified=0', '--no-color'];
diffOutput = execFileSync('git', args, {
cwd: repoRoot,
encoding: 'utf-8',
maxBuffer: 10 * 1024 * 1024,
stdio: ['pipe', 'pipe', 'pipe'],
});
} catch (e) {
return { error: `Failed to run git diff: ${e.message}` };
}
if (!diffOutput.trim()) {
return {
predicates: [],
summary: { total: 0, passed: 0, failed: 0, changedFiles: 0, newFiles: 0 },
passed: true,
};
}
const { changedRanges, oldRanges, newFiles } = parseDiffOutput(diffOutput);
if (changedRanges.size === 0) {
return {
predicates: [],
summary: { total: 0, passed: 0, failed: 0, changedFiles: 0, newFiles: 0 },
passed: true,
};
}
const changedFiles = new Set(changedRanges.keys());
// Execute enabled predicates
const predicates = [];
if (enableCycles) {
const result = checkNoNewCycles(db, changedFiles, noTests);
predicates.push({ name: 'cycles', ...result });
}
if (blastRadiusThreshold != null) {
const result = checkMaxBlastRadius(
db,
changedRanges,
blastRadiusThreshold,
noTests,
maxDepth,
);
predicates.push({ name: 'blast-radius', ...result });
}
if (enableSignatures) {
const result = checkNoSignatureChanges(db, oldRanges, noTests);
predicates.push({ name: 'signatures', ...result });
}
if (enableBoundaries) {
const result = checkNoBoundaryViolations(db, changedFiles, repoRoot, noTests);
predicates.push({ name: 'boundaries', ...result });
}
const passedCount = predicates.filter((p) => p.passed).length;
const failedCount = predicates.length - passedCount;
return {
predicates,
summary: {
total: predicates.length,
passed: passedCount,
failed: failedCount,
changedFiles: changedFiles.size,
newFiles: newFiles.size,
},
passed: failedCount === 0,
};
} finally {
db.close();
}
}