-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathaudit.js
More file actions
337 lines (300 loc) · 10.5 KB
/
Copy pathaudit.js
File metadata and controls
337 lines (300 loc) · 10.5 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
333
334
335
336
337
/**
* audit.js — Composite report: explain + impact + health metrics per function.
*
* Combines explainData (structure, callers, callees, basic complexity),
* full function_complexity health metrics, BFS impact analysis, and
* manifesto threshold breach detection into a single call.
*/
import path from 'node:path';
import { loadConfig } from './config.js';
import { openReadonlyOrFail } from './db.js';
import { isTestFile } from './infrastructure/test-filter.js';
import { RULE_DEFS } from './manifesto.js';
import { explainData } from './queries.js';
// ─── Threshold resolution ───────────────────────────────────────────
const FUNCTION_RULES = RULE_DEFS.filter((d) => d.level === 'function');
function resolveThresholds(customDbPath) {
try {
const dbDir = path.dirname(customDbPath);
const repoRoot = path.resolve(dbDir, '..');
const cfg = loadConfig(repoRoot);
const userRules = cfg.manifesto || {};
const resolved = {};
for (const def of FUNCTION_RULES) {
const user = userRules[def.name];
resolved[def.name] = {
metric: def.metric,
warn: user?.warn !== undefined ? user.warn : def.defaults.warn,
fail: def.reportOnly ? null : user?.fail !== undefined ? user.fail : def.defaults.fail,
};
}
return resolved;
} catch {
// Fall back to defaults if config loading fails
const resolved = {};
for (const def of FUNCTION_RULES) {
resolved[def.name] = {
metric: def.metric,
warn: def.defaults.warn,
fail: def.reportOnly ? null : def.defaults.fail,
};
}
return resolved;
}
}
// Column name in DB → threshold rule name mapping
const METRIC_TO_RULE = {
cognitive: 'cognitive',
cyclomatic: 'cyclomatic',
max_nesting: 'maxNesting',
};
function checkBreaches(row, thresholds) {
const breaches = [];
for (const [col, ruleName] of Object.entries(METRIC_TO_RULE)) {
const t = thresholds[ruleName];
if (!t) continue;
const value = row[col];
if (value == null) continue;
if (t.fail != null && value >= t.fail) {
breaches.push({ metric: ruleName, value, threshold: t.fail, level: 'fail' });
} else if (t.warn != null && value >= t.warn) {
breaches.push({ metric: ruleName, value, threshold: t.warn, level: 'warn' });
}
}
return breaches;
}
// ─── BFS impact (inline, same algorithm as fnImpactData) ────────────
function computeImpact(db, nodeId, noTests, maxDepth) {
const visited = new Set([nodeId]);
const levels = {};
let frontier = [nodeId];
for (let d = 1; d <= maxDepth; d++) {
const nextFrontier = [];
for (const fid of frontier) {
const callers = db
.prepare(
`SELECT DISTINCT n.id, n.name, n.kind, n.file, n.line
FROM edges e JOIN nodes n ON e.source_id = n.id
WHERE e.target_id = ? AND e.kind = 'calls'`,
)
.all(fid);
for (const c of callers) {
if (!visited.has(c.id) && (!noTests || !isTestFile(c.file))) {
visited.add(c.id);
nextFrontier.push(c.id);
if (!levels[d]) levels[d] = [];
levels[d].push({ name: c.name, kind: c.kind, file: c.file, line: c.line });
}
}
}
frontier = nextFrontier;
if (frontier.length === 0) break;
}
return { totalDependents: visited.size - 1, levels };
}
// ─── Phase 4.4 fields (graceful null fallback) ─────────────────────
function readPhase44(db, nodeId) {
try {
const row = db
.prepare('SELECT risk_score, complexity_notes, side_effects FROM nodes WHERE id = ?')
.get(nodeId);
if (row) {
return {
riskScore: row.risk_score ?? null,
complexityNotes: row.complexity_notes ?? null,
sideEffects: row.side_effects ?? null,
};
}
} catch {
/* columns don't exist yet */
}
return { riskScore: null, complexityNotes: null, sideEffects: null };
}
// ─── auditData ──────────────────────────────────────────────────────
export function auditData(target, customDbPath, opts = {}) {
const noTests = opts.noTests || false;
const maxDepth = opts.depth || 3;
const file = opts.file;
const kind = opts.kind;
// 1. Get structure via explainData
const explained = explainData(target, customDbPath, { noTests, depth: 0 });
// Apply --file and --kind filters for function targets
let results = explained.results;
if (explained.kind === 'function') {
if (file) results = results.filter((r) => r.file.includes(file));
if (kind) results = results.filter((r) => r.kind === kind);
}
if (results.length === 0) {
return { target, kind: explained.kind, functions: [] };
}
// 2. Open DB for enrichment
const db = openReadonlyOrFail(customDbPath);
const thresholds = resolveThresholds(customDbPath);
let functions;
try {
if (explained.kind === 'file') {
// File target: explainData returns file-level info with publicApi + internal
// We need to enrich each symbol
functions = [];
for (const fileResult of results) {
const allSymbols = [...(fileResult.publicApi || []), ...(fileResult.internal || [])];
if (kind) {
const filtered = allSymbols.filter((s) => s.kind === kind);
for (const sym of filtered) {
functions.push(enrichSymbol(db, sym, fileResult.file, noTests, maxDepth, thresholds));
}
} else {
for (const sym of allSymbols) {
functions.push(enrichSymbol(db, sym, fileResult.file, noTests, maxDepth, thresholds));
}
}
}
} else {
// Function target: explainData returns per-function results
functions = results.map((r) => enrichFunction(db, r, noTests, maxDepth, thresholds));
}
} finally {
db.close();
}
return { target, kind: explained.kind, functions };
}
// ─── Enrich a function result from explainData ──────────────────────
function enrichFunction(db, r, noTests, maxDepth, thresholds) {
const nodeRow = db
.prepare('SELECT id FROM nodes WHERE name = ? AND file = ? AND line = ?')
.get(r.name, r.file, r.line);
const nodeId = nodeRow?.id;
const health = nodeId ? buildHealth(db, nodeId, thresholds) : defaultHealth();
const impact = nodeId
? computeImpact(db, nodeId, noTests, maxDepth)
: { totalDependents: 0, levels: {} };
const phase44 = nodeId
? readPhase44(db, nodeId)
: { riskScore: null, complexityNotes: null, sideEffects: null };
return {
name: r.name,
kind: r.kind,
file: r.file,
line: r.line,
endLine: r.endLine,
role: r.role,
lineCount: r.lineCount,
summary: r.summary,
signature: r.signature,
callees: r.callees,
callers: r.callers,
relatedTests: r.relatedTests,
impact,
health,
...phase44,
};
}
// ─── Enrich a symbol from file-level explainData ────────────────────
function enrichSymbol(db, sym, file, noTests, maxDepth, thresholds) {
const nodeRow = db
.prepare('SELECT id, end_line FROM nodes WHERE name = ? AND file = ? AND line = ?')
.get(sym.name, file, sym.line);
const nodeId = nodeRow?.id;
const endLine = nodeRow?.end_line || null;
const lineCount = endLine ? endLine - sym.line + 1 : null;
// Get callers/callees for this symbol
let callees = [];
let callers = [];
let relatedTests = [];
if (nodeId) {
callees = db
.prepare(
`SELECT n.name, n.kind, n.file, n.line
FROM edges e JOIN nodes n ON e.target_id = n.id
WHERE e.source_id = ? AND e.kind = 'calls'`,
)
.all(nodeId)
.map((c) => ({ name: c.name, kind: c.kind, file: c.file, line: c.line }));
callers = db
.prepare(
`SELECT n.name, n.kind, n.file, n.line
FROM edges e JOIN nodes n ON e.source_id = n.id
WHERE e.target_id = ? AND e.kind = 'calls'`,
)
.all(nodeId)
.map((c) => ({ name: c.name, kind: c.kind, file: c.file, line: c.line }));
if (noTests) callers = callers.filter((c) => !isTestFile(c.file));
const testCallerRows = db
.prepare(
`SELECT DISTINCT n.file FROM edges e JOIN nodes n ON e.source_id = n.id
WHERE e.target_id = ? AND e.kind = 'calls'`,
)
.all(nodeId);
relatedTests = testCallerRows.filter((r) => isTestFile(r.file)).map((r) => ({ file: r.file }));
}
const health = nodeId ? buildHealth(db, nodeId, thresholds) : defaultHealth();
const impact = nodeId
? computeImpact(db, nodeId, noTests, maxDepth)
: { totalDependents: 0, levels: {} };
const phase44 = nodeId
? readPhase44(db, nodeId)
: { riskScore: null, complexityNotes: null, sideEffects: null };
return {
name: sym.name,
kind: sym.kind,
file,
line: sym.line,
endLine,
role: sym.role || null,
lineCount,
summary: sym.summary || null,
signature: sym.signature || null,
callees,
callers,
relatedTests,
impact,
health,
...phase44,
};
}
// ─── Build health metrics from function_complexity ──────────────────
function buildHealth(db, nodeId, thresholds) {
try {
const row = db
.prepare(
`SELECT cognitive, cyclomatic, max_nesting, maintainability_index,
halstead_volume, halstead_difficulty, halstead_effort, halstead_bugs,
loc, sloc, comment_lines
FROM function_complexity WHERE node_id = ?`,
)
.get(nodeId);
if (!row) return defaultHealth();
return {
cognitive: row.cognitive,
cyclomatic: row.cyclomatic,
maxNesting: row.max_nesting,
maintainabilityIndex: row.maintainability_index || 0,
halstead: {
volume: row.halstead_volume || 0,
difficulty: row.halstead_difficulty || 0,
effort: row.halstead_effort || 0,
bugs: row.halstead_bugs || 0,
},
loc: row.loc || 0,
sloc: row.sloc || 0,
commentLines: row.comment_lines || 0,
thresholdBreaches: checkBreaches(row, thresholds),
};
} catch {
/* table may not exist */
return defaultHealth();
}
}
function defaultHealth() {
return {
cognitive: null,
cyclomatic: null,
maxNesting: null,
maintainabilityIndex: null,
halstead: { volume: 0, difficulty: 0, effort: 0, bugs: 0 },
loc: 0,
sloc: 0,
commentLines: 0,
thresholdBreaches: [],
};
}