-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathstructure.ts
More file actions
1220 lines (1128 loc) · 44.2 KB
/
Copy pathstructure.ts
File metadata and controls
1220 lines (1128 loc) · 44.2 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from 'node:path';
import { getBuildMeta, getNodeId, setBuildMeta, testFilterSQL } from '../db/index.js';
import { cachedStmt } from '../db/repository/cached-stmt.js';
import { debug } from '../infrastructure/logger.js';
import { getOrCreateChunkStmt } from '../shared/chunked-stmt-cache.js';
import { getAncestorDirs, normalizePath } from '../shared/constants.js';
import type {
BetterSqlite3Database,
SqliteStatement as DbSqliteStatement,
StmtCache,
} from '../types.js';
// isBarrelProdReachable's two queries are identical text on every call (the
// interpolated test-file filter is a fixed set of LIKE patterns keyed only
// by column name) — cache them per-db so repeated calls (1-3 barrels per
// incremental build) skip re-preparing the same statement. Mirrors
// `prepare_cached` in the Rust `is_barrel_prod_reachable`.
const _barrelDirectStmt: StmtCache<{ reachable: number }> = new WeakMap();
const _barrelBackwardStmt: StmtCache<{ reachable: number }> = new WeakMap();
// ─── Build-time helpers ───────────────────────────────────────────────
interface NodeIdStmt {
get(name: string, kind: string, file: string, line: number): { id: number } | undefined;
}
interface FileSymbolData {
definitions: { name: string; kind: string; line: number }[];
imports: unknown[];
exports: unknown[];
calls?: unknown[];
}
function cleanupPreviousData(
db: BetterSqlite3Database,
getNodeIdStmt: NodeIdStmt,
isIncremental: boolean,
changedFiles: string[] | null,
): void {
if (isIncremental) {
const affectedDirs = getAncestorDirs(changedFiles ?? []);
const deleteContainsForDir = db.prepare(
"DELETE FROM edges WHERE kind = 'contains' AND source_id IN (SELECT id FROM nodes WHERE name = ? AND kind = 'directory')",
);
const deleteMetricForNode = db.prepare('DELETE FROM node_metrics WHERE node_id = ?');
db.transaction(() => {
for (const dir of affectedDirs) {
deleteContainsForDir.run(dir);
}
for (const f of changedFiles ?? []) {
const fileRow = getNodeIdStmt.get(f, 'file', f, 0);
if (fileRow) deleteMetricForNode.run(fileRow.id);
}
for (const dir of affectedDirs) {
const dirRow = getNodeIdStmt.get(dir, 'directory', dir, 0);
if (dirRow) deleteMetricForNode.run(dirRow.id);
}
})();
} else {
db.exec(`
DELETE FROM edges WHERE kind = 'contains'
AND source_id IN (SELECT id FROM nodes WHERE kind = 'directory');
DELETE FROM node_metrics;
DELETE FROM nodes WHERE kind = 'directory';
`);
}
}
function collectAllDirectories(
directories: Set<string> | Iterable<string>,
fileSymbols: Map<string, FileSymbolData>,
): Set<string> {
const allDirs = new Set<string>();
for (const dir of directories) {
let d = dir;
while (d && d !== '.') {
allDirs.add(d);
d = normalizePath(path.dirname(d));
}
}
for (const relPath of fileSymbols.keys()) {
let d = normalizePath(path.dirname(relPath));
while (d && d !== '.') {
allDirs.add(d);
d = normalizePath(path.dirname(d));
}
}
return allDirs;
}
interface SqliteStatement {
run(...params: unknown[]): unknown;
}
/** Insert file→parent-directory contains edges (incremental-aware). */
function insertFileToParentEdges(
insertEdge: SqliteStatement,
getNodeIdStmt: NodeIdStmt,
fileSymbols: Map<string, FileSymbolData>,
affectedDirs: Set<string> | null,
): void {
for (const relPath of fileSymbols.keys()) {
const dir = normalizePath(path.dirname(relPath));
if (!dir || dir === '.') continue;
if (affectedDirs && !affectedDirs.has(dir)) continue;
const dirRow = getNodeIdStmt.get(dir, 'directory', dir, 0);
const fileRow = getNodeIdStmt.get(relPath, 'file', relPath, 0);
if (dirRow && fileRow) {
insertEdge.run(dirRow.id, fileRow.id, 'contains', 1.0, 0);
}
}
}
/** Insert child-directory→parent-directory contains edges (incremental-aware). */
function insertDirToParentEdges(
insertEdge: SqliteStatement,
getNodeIdStmt: NodeIdStmt,
allDirs: Set<string>,
affectedDirs: Set<string> | null,
): void {
for (const dir of allDirs) {
const parent = normalizePath(path.dirname(dir));
if (!parent || parent === '.' || parent === dir) continue;
if (affectedDirs && !affectedDirs.has(parent)) continue;
const parentRow = getNodeIdStmt.get(parent, 'directory', parent, 0);
const childRow = getNodeIdStmt.get(dir, 'directory', dir, 0);
if (parentRow && childRow) {
insertEdge.run(parentRow.id, childRow.id, 'contains', 1.0, 0);
}
}
}
function insertContainsEdges(
db: BetterSqlite3Database,
insertEdge: SqliteStatement,
getNodeIdStmt: NodeIdStmt,
fileSymbols: Map<string, FileSymbolData>,
allDirs: Set<string>,
changedFiles: string[] | null,
): void {
const isIncremental = changedFiles != null && changedFiles.length > 0;
const affectedDirs = isIncremental ? getAncestorDirs(changedFiles ?? []) : null;
db.transaction(() => {
insertFileToParentEdges(insertEdge, getNodeIdStmt, fileSymbols, affectedDirs);
insertDirToParentEdges(insertEdge, getNodeIdStmt, allDirs, affectedDirs);
})();
}
interface ImportEdge {
source_file: string;
target_file: string;
}
function computeImportEdgeMaps(db: BetterSqlite3Database): {
fanInMap: Map<string, number>;
fanOutMap: Map<string, number>;
importEdges: ImportEdge[];
} {
const fanInMap = new Map<string, number>();
const fanOutMap = new Map<string, number>();
const importEdges = db
.prepare(`
SELECT n1.file AS source_file, n2.file AS target_file
FROM edges e
JOIN nodes n1 ON e.source_id = n1.id
JOIN nodes n2 ON e.target_id = n2.id
WHERE e.kind IN ('imports', 'imports-type')
AND n1.file != n2.file
AND n2.kind = 'file'
`)
.all() as ImportEdge[];
for (const { source_file, target_file } of importEdges) {
fanOutMap.set(source_file, (fanOutMap.get(source_file) || 0) + 1);
fanInMap.set(target_file, (fanInMap.get(target_file) || 0) + 1);
}
return { fanInMap, fanOutMap, importEdges };
}
function computeFileMetrics(
db: BetterSqlite3Database,
upsertMetric: SqliteStatement,
getNodeIdStmt: NodeIdStmt,
fileSymbols: Map<string, FileSymbolData>,
lineCountMap: Map<string, number>,
fanInMap: Map<string, number>,
fanOutMap: Map<string, number>,
): void {
db.transaction(() => {
// Batch-load import counts per file (distinct imported files,
// matching the fast-path semantics in updateChangedFileMetrics).
// Runs inside the transaction for parity with the Rust path.
const importCountMap = new Map<string, number>();
for (const row of db
.prepare(
`SELECT n1.file AS src, COUNT(DISTINCT n2.file) AS cnt FROM edges e
JOIN nodes n1 ON e.source_id = n1.id
JOIN nodes n2 ON e.target_id = n2.id
WHERE e.kind = 'imports'
GROUP BY n1.file`,
)
.all() as { src: string; cnt: number }[]) {
importCountMap.set(row.src, row.cnt);
}
for (const [relPath, symbols] of fileSymbols) {
const fileRow = getNodeIdStmt.get(relPath, 'file', relPath, 0);
if (!fileRow) continue;
const lineCount = lineCountMap.get(relPath) || 0;
const seen = new Set<string>();
let symbolCount = 0;
for (const d of symbols.definitions) {
const key = `${d.name}|${d.kind}|${d.line}`;
if (!seen.has(key)) {
seen.add(key);
symbolCount++;
}
}
const importCount = importCountMap.get(relPath) || 0;
const exportCount = symbols.exports.length;
const fanIn = fanInMap.get(relPath) || 0;
const fanOut = fanOutMap.get(relPath) || 0;
upsertMetric.run(
fileRow.id,
lineCount,
symbolCount,
importCount,
exportCount,
fanIn,
fanOut,
null,
null,
);
}
})();
}
/** Map each directory to the files it transitively contains. */
function buildDirFilesMap(
allDirs: Set<string>,
fileSymbols: Map<string, FileSymbolData>,
): Map<string, string[]> {
const dirFiles = new Map<string, string[]>();
for (const dir of allDirs) {
dirFiles.set(dir, []);
}
for (const relPath of fileSymbols.keys()) {
let d = normalizePath(path.dirname(relPath));
while (d && d !== '.') {
if (dirFiles.has(d)) {
dirFiles.get(d)?.push(relPath);
}
d = normalizePath(path.dirname(d));
}
}
return dirFiles;
}
/** Build reverse map: file -> set of ancestor directories. */
function buildFileToAncestorDirs(dirFiles: Map<string, string[]>): Map<string, Set<string>> {
const fileToAncestorDirs = new Map<string, Set<string>>();
for (const [dir, files] of dirFiles) {
for (const f of files) {
if (!fileToAncestorDirs.has(f)) fileToAncestorDirs.set(f, new Set());
fileToAncestorDirs.get(f)?.add(dir);
}
}
return fileToAncestorDirs;
}
/** Initialise a zero-count map for all known directories. */
function initDirEdgeCounts(
allDirs: Set<string>,
): Map<string, { intra: number; fanIn: number; fanOut: number }> {
const m = new Map<string, { intra: number; fanIn: number; fanOut: number }>();
for (const dir of allDirs) m.set(dir, { intra: 0, fanIn: 0, fanOut: 0 });
return m;
}
/** Accumulate source-side (intra / fanOut) counts for one import edge. */
function accumulateSrcDirCounts(
srcDirs: Set<string>,
tgtDirs: Set<string> | undefined,
dirEdgeCounts: Map<string, { intra: number; fanIn: number; fanOut: number }>,
): void {
for (const dir of srcDirs) {
const counts = dirEdgeCounts.get(dir);
if (!counts) continue;
if (tgtDirs?.has(dir)) {
counts.intra++;
} else {
counts.fanOut++;
}
}
}
/** Accumulate target-side (fanIn) counts for one import edge. */
function accumulateTgtDirCounts(
tgtDirs: Set<string>,
srcDirs: Set<string> | undefined,
dirEdgeCounts: Map<string, { intra: number; fanIn: number; fanOut: number }>,
): void {
for (const dir of tgtDirs) {
if (srcDirs?.has(dir)) continue;
const counts = dirEdgeCounts.get(dir);
if (!counts) continue;
counts.fanIn++;
}
}
/** Count intra-directory, fan-in, and fan-out edges per directory. */
function countDirectoryEdges(
allDirs: Set<string>,
importEdges: ImportEdge[],
fileToAncestorDirs: Map<string, Set<string>>,
): Map<string, { intra: number; fanIn: number; fanOut: number }> {
const dirEdgeCounts = initDirEdgeCounts(allDirs);
for (const { source_file, target_file } of importEdges) {
const srcDirs = fileToAncestorDirs.get(source_file);
const tgtDirs = fileToAncestorDirs.get(target_file);
if (!srcDirs && !tgtDirs) continue;
if (srcDirs) accumulateSrcDirCounts(srcDirs, tgtDirs, dirEdgeCounts);
if (tgtDirs) accumulateTgtDirCounts(tgtDirs, srcDirs, dirEdgeCounts);
}
return dirEdgeCounts;
}
/** Count unique symbols in a list of files. */
function countSymbolsInFiles(files: string[], fileSymbols: Map<string, FileSymbolData>): number {
let symbolCount = 0;
for (const f of files) {
const sym = fileSymbols.get(f);
if (sym) {
const seen = new Set<string>();
for (const d of sym.definitions) {
const key = `${d.name}|${d.kind}|${d.line}`;
if (!seen.has(key)) {
seen.add(key);
symbolCount++;
}
}
}
}
return symbolCount;
}
function computeDirectoryMetrics(
db: BetterSqlite3Database,
upsertMetric: SqliteStatement,
getNodeIdStmt: NodeIdStmt,
fileSymbols: Map<string, FileSymbolData>,
allDirs: Set<string>,
importEdges: ImportEdge[],
): void {
const dirFiles = buildDirFilesMap(allDirs, fileSymbols);
const fileToAncestorDirs = buildFileToAncestorDirs(dirFiles);
const dirEdgeCounts = countDirectoryEdges(allDirs, importEdges, fileToAncestorDirs);
db.transaction(() => {
for (const [dir, files] of dirFiles) {
const dirRow = getNodeIdStmt.get(dir, 'directory', dir, 0);
if (!dirRow) continue;
const fileCount = files.length;
const symbolCount = countSymbolsInFiles(files, fileSymbols);
const counts = dirEdgeCounts.get(dir) || { intra: 0, fanIn: 0, fanOut: 0 };
const totalEdges = counts.intra + counts.fanIn + counts.fanOut;
const cohesion = totalEdges > 0 ? counts.intra / totalEdges : null;
upsertMetric.run(
dirRow.id,
null,
symbolCount,
null,
null,
counts.fanIn,
counts.fanOut,
cohesion,
fileCount,
);
}
})();
}
// ─── Build-time: insert directory nodes, contains edges, and metrics ────
export function buildStructure(
db: BetterSqlite3Database,
fileSymbols: Map<string, FileSymbolData>,
_rootDir: string,
lineCountMap: Map<string, number>,
directories: Set<string>,
changedFiles?: string[] | null,
): void {
const insertNode = db.prepare(
'INSERT OR IGNORE INTO nodes (name, kind, file, line, end_line) VALUES (?, ?, ?, ?, ?)',
);
const getNodeIdStmt: NodeIdStmt = {
get: (name: string, kind: string, file: string, line: number) => {
const id = getNodeId(db, name, kind, file, line);
return id != null ? { id } : undefined;
},
};
const insertEdge = db.prepare(
'INSERT INTO edges (source_id, target_id, kind, confidence, dynamic) VALUES (?, ?, ?, ?, ?)',
);
const upsertMetric = db.prepare(`
INSERT OR REPLACE INTO node_metrics
(node_id, line_count, symbol_count, import_count, export_count, fan_in, fan_out, cohesion, file_count)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
const isIncremental = changedFiles != null && changedFiles.length > 0;
cleanupPreviousData(db, getNodeIdStmt, isIncremental, changedFiles ?? null);
const allDirs = collectAllDirectories(directories, fileSymbols);
db.transaction(() => {
for (const dir of allDirs) {
insertNode.run(dir, 'directory', dir, 0, null);
}
})();
insertContainsEdges(db, insertEdge, getNodeIdStmt, fileSymbols, allDirs, changedFiles ?? null);
const { fanInMap, fanOutMap, importEdges } = computeImportEdgeMaps(db);
computeFileMetrics(
db,
upsertMetric,
getNodeIdStmt,
fileSymbols,
lineCountMap,
fanInMap,
fanOutMap,
);
computeDirectoryMetrics(db, upsertMetric, getNodeIdStmt, fileSymbols, allDirs, importEdges);
debug(`Structure: ${allDirs.size} directories, ${fileSymbols.size} files with metrics`);
}
// ─── Node role classification ─────────────────────────────────────────
// Re-export from classifier for backward compatibility
export { FRAMEWORK_ENTRY_PREFIXES } from '../graph/classifiers/roles.js';
import { classifyRoles, median } from '../graph/classifiers/roles.js';
interface RoleSummary {
entry: number;
core: number;
utility: number;
adapter: number;
dead: number;
'dead-leaf': number;
'dead-entry': number;
'dead-ffi': number;
'dead-unresolved': number;
'test-only': number;
leaf: number;
[key: string]: number;
}
/**
* Classify every node in the graph into a role (core, entry, utility, etc.).
*
* When `changedFiles` is provided, only nodes from those files (and their
* edge neighbours) are reclassified. The returned `RoleSummary` in that case
* reflects **only the affected subset**, not the entire graph. Callers that
* need graph-wide totals should perform a full classification (omit
* `changedFiles`) or query the DB directly.
*/
export function classifyNodeRoles(
db: BetterSqlite3Database,
changedFiles?: string[] | null,
): RoleSummary {
const emptySummary: RoleSummary = {
entry: 0,
core: 0,
utility: 0,
adapter: 0,
dead: 0,
'dead-leaf': 0,
'dead-entry': 0,
'dead-ffi': 0,
'dead-unresolved': 0,
'test-only': 0,
leaf: 0,
};
// Incremental path: only reclassify nodes from affected files
if (changedFiles && changedFiles.length > 0) {
return classifyNodeRolesIncremental(db, changedFiles, emptySummary);
}
return classifyNodeRolesFull(db, emptySummary);
}
// ─── Shared role-classification helpers ───────────────────────────────
/**
* Build a role summary and group node IDs by role from classifier output.
* Shared between full and incremental classification paths.
*/
function buildRoleSummary(
rows: { id: number }[],
leafRows: { id: number }[],
roleMap: Map<string, string>,
emptySummary: RoleSummary,
): { summary: RoleSummary; idsByRole: Map<string, number[]> } {
const summary: RoleSummary = { ...emptySummary };
const idsByRole = new Map<string, number[]>();
// Leaf kinds are always dead-leaf — skip classifier
if (leafRows.length > 0) {
const leafIds: number[] = [];
for (const row of leafRows) leafIds.push(row.id);
idsByRole.set('dead-leaf', leafIds);
summary.dead += leafRows.length;
summary['dead-leaf'] += leafRows.length;
}
for (const row of rows) {
const role = roleMap.get(String(row.id)) || 'leaf';
if (role.startsWith('dead')) summary.dead++;
summary[role] = (summary[role] || 0) + 1;
let ids = idsByRole.get(role);
if (!ids) {
ids = [];
idsByRole.set(role, ids);
}
ids.push(row.id);
}
return { summary, idsByRole };
}
/**
* Batch-update node roles in the database. Executes a reset callback
* first (full resets all nodes, incremental resets only affected files),
* then writes new roles in chunks.
*/
function batchUpdateRoles(
db: BetterSqlite3Database,
idsByRole: Map<string, number[]>,
resetFn: () => void,
): void {
const ROLE_CHUNK = 500;
const roleStmtCache = new Map<number, DbSqliteStatement>();
db.transaction(() => {
resetFn();
for (const [role, ids] of idsByRole) {
for (let i = 0; i < ids.length; i += ROLE_CHUNK) {
const end = Math.min(i + ROLE_CHUNK, ids.length);
const chunkSize = end - i;
const stmt = getOrCreateChunkStmt(roleStmtCache, db, chunkSize, (n) => {
const placeholders = Array.from({ length: n }, () => '?').join(',');
return `UPDATE nodes SET role = ? WHERE id IN (${placeholders})`;
});
const vals: unknown[] = [role];
for (let j = i; j < end; j++) vals.push(ids[j]);
stmt.run(...vals);
}
}
})();
}
interface CallableNodeRow {
id: number;
name: string;
kind: string;
file: string;
fan_in: number;
fan_out: number;
}
/**
* Kinds that are consumed via annotations/references rather than calls.
* These do not count as "active callables" for the hasActiveFileSiblings heuristic.
*/
const ANNOTATION_ONLY_KINDS = new Set([
'constant',
'struct',
'enum',
'trait',
'type',
'interface',
'record',
]);
/**
* Build two active-files sets from callable rows:
*
* - `activeFiles`: files with at least one non-annotation-only callable with
* `fan_in > 0 || fan_out > 0`. Used for annotation-only kinds (constants,
* type defs) which have no callers by design.
*
* - `calledActiveFiles`: files with at least one non-annotation-only callable
* with `fan_in > 0` (strictly called). Used for method/function kinds to
* prevent a self-sibling loop: a function with `fanIn=0, fanOut>0` as the
* only callable in its file must NOT count itself as an "active sibling" and
* thus promote itself to `leaf`.
*/
function buildActiveFilesSet(rows: CallableNodeRow[]): {
activeFiles: Set<string>;
calledActiveFiles: Set<string>;
} {
const activeFiles = new Set<string>();
const calledActiveFiles = new Set<string>();
for (const r of rows) {
if (!ANNOTATION_ONLY_KINDS.has(r.kind)) {
if (r.fan_in > 0 || r.fan_out > 0) {
activeFiles.add(r.file);
}
if (r.fan_in > 0) {
calledActiveFiles.add(r.file);
}
}
}
return { activeFiles, calledActiveFiles };
}
/** Map callable rows to classifier input objects, attaching exported/prod-fan-in/active-file metadata. */
function buildClassifierInput(
rows: CallableNodeRow[],
exportedIds: Set<number>,
prodFanInMap: Map<number, number>,
activeFiles: Set<string>,
calledActiveFiles: Set<string>,
): Array<{
id: string;
name: string;
kind: string;
file: string;
fanIn: number;
fanOut: number;
isExported: boolean;
productionFanIn: number;
hasActiveFileSiblings: boolean | undefined;
}> {
return rows.map((r) => ({
id: String(r.id),
name: r.name,
kind: r.kind,
file: r.file,
fanIn: r.fan_in,
fanOut: r.fan_out,
isExported: exportedIds.has(r.id),
productionFanIn: prodFanInMap.get(r.id) || 0,
// Set hasActiveFileSiblings for annotation-only kinds (constants, type defs)
// AND for method/function — the latter two can have fanIn === 0 due to
// untraced call-site patterns (interface dispatch, logical-or defaults).
// The classifier interprets this field differently per kind (see classifyUnreferencedNode).
//
// IMPORTANT: method/function use calledActiveFiles (fan_in > 0 only) to
// prevent a self-sibling false negative: a function with fanIn=0, fanOut>0
// as the sole callable in its file must NOT see its own file as "active"
// and promote itself to leaf.
hasActiveFileSiblings: ANNOTATION_ONLY_KINDS.has(r.kind)
? activeFiles.has(r.file)
: r.kind === 'method' || r.kind === 'function'
? calledActiveFiles.has(r.file)
: undefined,
}));
}
// ─── Median cache helpers ─────────────────────────────────────────────────────
const ROLES_MEDIANS_KEY = 'roles_medians';
// Invalidate cached medians when the edge count drifts past this threshold.
// A 1-file rebuild adds/removes < 100 edges — well within the margin.
const MEDIAN_INVALIDATION_DELTA = 500;
/**
* Full edge-table GROUP BY scan — O(M). Only runs on cache miss.
*
* Joins `nodes` to restrict to the same non-leaf kinds that
* `classifyNodeRolesFull` uses when computing medians from in-memory rows
* (excludes 'file', 'directory', 'parameter', 'property'). This keeps the
* two paths consistent so a cold-cache fallback produces the same distribution
* as the full-build cached value.
*
* Also returns the filtered edge count used for computing the medians so the
* caller can pass it directly to `writeMedianCache` without a second query.
*/
function computeGlobalMediansFromEdges(db: BetterSqlite3Database): {
fanIn: number;
fanOut: number;
edgeCount: number;
} {
const excludedKinds = `('file', 'directory', 'parameter', 'property')`;
const fanInRows = db
.prepare(
`SELECT COUNT(*) AS cnt FROM edges e
JOIN nodes t ON e.target_id = t.id
WHERE e.kind IN ('calls', 'imports-type')
AND t.kind NOT IN ${excludedKinds}
GROUP BY e.target_id`,
)
.all() as { cnt: number }[];
const fanOutRows = db
.prepare(
`SELECT COUNT(*) AS cnt FROM edges e
JOIN nodes s ON e.source_id = s.id
WHERE e.kind = 'calls'
AND s.kind NOT IN ${excludedKinds}
GROUP BY e.source_id`,
)
.all() as { cnt: number }[];
const fanInDist = fanInRows.map((r) => r.cnt).sort((a, b) => a - b);
const fanOutDist = fanOutRows.map((r) => r.cnt).sort((a, b) => a - b);
// Sum of fanInRows[*].cnt equals the total edge count for the relevant
// edge subset — no extra COUNT query needed.
const edgeCount = fanInRows.reduce((acc, r) => acc + r.cnt, 0);
return { fanIn: median(fanInDist), fanOut: median(fanOutDist), edgeCount };
}
/**
* Read cached role medians from build_meta. Returns null when absent or stale
* (edge count moved beyond MEDIAN_INVALIDATION_DELTA from the cached value).
*
* The staleness check uses the same edge subset (calls + imports-type) that
* the medians are derived from, so only changes to the edges that actually
* influence fan-in/fan-out can evict the cache.
*/
function readCachedMedians(db: BetterSqlite3Database): { fanIn: number; fanOut: number } | null {
const raw = getBuildMeta(db, ROLES_MEDIANS_KEY);
if (!raw) return null;
try {
const cached = JSON.parse(raw) as { fanIn: number; fanOut: number; edgeCount: number };
// Count only the edge kinds that drive median computation — same subset
// used by computeGlobalMediansFromEdges and classifyNodeRolesFull.
const currentCount = (
db
.prepare(`SELECT COUNT(*) AS cnt FROM edges WHERE kind IN ('calls', 'imports-type')`)
.get() as { cnt: number }
).cnt;
if (
Math.abs(currentCount - cached.edgeCount) >
Math.max(MEDIAN_INVALIDATION_DELTA, cached.edgeCount * 0.1)
)
return null;
return { fanIn: cached.fanIn, fanOut: cached.fanOut };
} catch (e) {
debug(`readCachedMedians: failed to parse cached medians — ${e}`);
return null;
}
}
/**
* Persist global role medians + current edge count to build_meta.
*
* @param edgeCount - pre-computed calls+imports-type edge count. When provided,
* the function skips the COUNT query entirely. Pass when the count is already
* known at the call site (e.g. from `computeGlobalMediansFromEdges`).
*/
function writeMedianCache(
db: BetterSqlite3Database,
medians: { fanIn: number; fanOut: number },
edgeCount?: number,
): void {
const cnt =
edgeCount ??
(
db
.prepare(`SELECT COUNT(*) AS cnt FROM edges WHERE kind IN ('calls', 'imports-type')`)
.get() as { cnt: number }
).cnt;
setBuildMeta(db, { [ROLES_MEDIANS_KEY]: JSON.stringify({ ...medians, edgeCount: cnt }) });
}
function classifyNodeRolesFull(db: BetterSqlite3Database, emptySummary: RoleSummary): RoleSummary {
// Property kind (class/struct fields) can never have callers/callees.
// Classify them directly as dead-leaf without the expensive fan-in/fan-out JOINs.
//
// `parameter` is deliberately NOT included here (#1723): a parameter's liveness
// is a local dataflow question (is it referenced within its own function body),
// not a call-graph reachability question, so "no incoming call edges" carries
// zero dead-code signal for it. Parameters are also excluded from the main
// query below, so they never receive a role at all — the same treatment as
// `file`/`directory` nodes.
const leafRows = db
.prepare(
`SELECT n.id
FROM nodes n
WHERE n.kind = 'property'`,
)
.all() as { id: number }[];
// Only compute fan-in/fan-out for callable/classifiable nodes
const rows = db
.prepare(
`SELECT n.id, n.name, n.kind, n.file,
COALESCE(fi.cnt, 0) AS fan_in,
COALESCE(fo.cnt, 0) AS fan_out
FROM nodes n
LEFT JOIN (
SELECT target_id, COUNT(*) AS cnt FROM edges WHERE kind IN ('calls', 'imports-type') GROUP BY target_id
) fi ON n.id = fi.target_id
LEFT JOIN (
SELECT source_id, COUNT(*) AS cnt FROM edges WHERE kind = 'calls' GROUP BY source_id
) fo ON n.id = fo.source_id
WHERE n.kind NOT IN ('file', 'directory', 'parameter', 'property')`,
)
.all() as CallableNodeRow[];
if (rows.length === 0 && leafRows.length === 0) return emptySummary;
const exportedIds = new Set(
(
db
.prepare(
`SELECT DISTINCT e.target_id
FROM edges e
JOIN nodes caller ON e.source_id = caller.id
JOIN nodes target ON e.target_id = target.id
WHERE e.kind IN ('calls', 'imports-type') AND caller.file != target.file`,
)
.all() as { target_id: number }[]
).map((r) => r.target_id),
);
// Mark symbols as exported when their files are targets of reexports edges
// from production-reachable barrels (traces through multi-level chains) (#837)
//
// `method` is excluded (#1780): a `reexports` edge only ever concerns
// top-level module bindings (functions, classes, types, constants, ...) — a
// class/interface method can never be an independently re-exportable
// binding on its own, so inheriting "exported" status from a co-located
// top-level re-export is a category error. Without this exclusion, e.g. an
// abstract base class's zero-fan-in method declarations were promoted to
// `entry` merely because some other symbol in the same file was re-exported
// through a barrel.
const reexportExported = db
.prepare(
`WITH RECURSIVE prod_reachable(file_id) AS (
SELECT DISTINCT e.target_id
FROM edges e
JOIN nodes src ON e.source_id = src.id
WHERE e.kind IN ('imports', 'dynamic-imports', 'imports-type')
AND src.kind = 'file'
${testFilterSQL('src.file')}
UNION
SELECT e.target_id
FROM edges e
JOIN prod_reachable pr ON e.source_id = pr.file_id
WHERE e.kind = 'reexports'
)
SELECT DISTINCT n.id
FROM nodes n
JOIN nodes f ON f.file = n.file AND f.kind = 'file'
WHERE f.id IN (
SELECT e.target_id FROM edges e
WHERE e.kind = 'reexports'
AND e.source_id IN (SELECT file_id FROM prod_reachable)
)
AND n.kind NOT IN ('file', 'directory', 'parameter', 'property', 'method')`,
)
.all() as { id: number }[];
for (const r of reexportExported) exportedIds.add(r.id);
// Mark symbols with exported=1 as exported — the extractor sets this flag when the
// author writes `export interface Foo { }` / `export type Bar = ...` / `export function`.
// Cross-file edge inference misses these when the symbol is only used as a type annotation
// within the same file (no calls/imports-type edge is produced for same-file type usage).
// This fixes false dead-unresolved classification for exported interfaces with no external callers (#1583).
const explicitlyExported = db
.prepare(
`SELECT id FROM nodes
WHERE exported = 1
AND kind NOT IN ('file', 'directory', 'parameter', 'property')`,
)
.all() as { id: number }[];
for (const r of explicitlyExported) exportedIds.add(r.id);
// Compute production fan-in (excluding callers in test files)
const prodFanInMap = new Map<number, number>();
const prodRows = db
.prepare(
`SELECT e.target_id, COUNT(*) AS cnt
FROM edges e
JOIN nodes caller ON e.source_id = caller.id
WHERE e.kind IN ('calls', 'imports-type')
${testFilterSQL('caller.file')}
GROUP BY e.target_id`,
)
.all() as { target_id: number; cnt: number }[];
for (const r of prodRows) {
prodFanInMap.set(r.target_id, r.cnt);
}
// Delegate classification to the pure-logic classifier.
// Compute medians from the already-loaded rows (no extra DB round-trip),
// pass them as overrides to avoid recomputing inside classifyRoles,
// and cache them for subsequent incremental builds.
const { activeFiles, calledActiveFiles } = buildActiveFilesSet(rows);
const classifierInput = buildClassifierInput(
rows,
exportedIds,
prodFanInMap,
activeFiles,
calledActiveFiles,
);
const nonZeroFanIn = classifierInput
.filter((n) => n.fanIn > 0)
.map((n) => n.fanIn)
.sort((a, b) => a - b);
const nonZeroFanOut = classifierInput
.filter((n) => n.fanOut > 0)
.map((n) => n.fanOut)
.sort((a, b) => a - b);
const globalMedians = { fanIn: median(nonZeroFanIn), fanOut: median(nonZeroFanOut) };
const roleMap = classifyRoles(classifierInput, globalMedians);
// Derive the edge count from already-loaded in-memory rows: summing fan_in
// across all nodes equals COUNT(*) FROM edges WHERE kind IN ('calls','imports-type'),
// since the full-build query left-joins every matching edge exactly once per target.
// Passing this avoids an extra COUNT query on the full-build path.
const inMemoryEdgeCount = rows.reduce((acc, r) => acc + r.fan_in, 0);
writeMedianCache(db, globalMedians, inMemoryEdgeCount);
const { summary, idsByRole } = buildRoleSummary(rows, leafRows, roleMap, emptySummary);
batchUpdateRoles(db, idsByRole, () => {
db.prepare('UPDATE nodes SET role = NULL').run();
});
return summary;
}
/**
* Direct barrels: files that directly re-export (one hop) into any of the
* given target files. Used by `classifyNodeRolesIncremental`'s scoped
* alternative to the full `prod_reachable` recursive CTE — see
* `isBarrelProdReachable`. Mirrors Rust `find_direct_reexport_barrels`.
*/
function findDirectReexportBarrels(
db: BetterSqlite3Database,
allAffectedFiles: string[],
): string[] {
const placeholders = allAffectedFiles.map(() => '?').join(',');
const rows = db
.prepare(
`SELECT DISTINCT n1.file AS file FROM edges e
JOIN nodes n1 ON e.source_id = n1.id
JOIN nodes n2 ON e.target_id = n2.id
WHERE e.kind = 'reexports' AND n2.file IN (${placeholders})`,
)
.all(...allAffectedFiles) as { file: string }[];
return rows.map((r) => r.file);
}
/**
* True when `barrelFile` is production-reachable — i.e. a member of the same
* `prod_reachable` set `classifyNodeRolesFull`'s recursive CTE computes
* globally (a non-test file directly imports it, or reaches it transitively
* through a chain of `reexports` edges) — but answered for one specific file
* instead of materializing the whole graph's closure. Mirrors Rust
* `is_barrel_prod_reachable` — see that function's doc comment for the
* measured cost difference (#1855) and the reachability argument.
*/
function isBarrelProdReachable(db: BetterSqlite3Database, barrelFile: string): boolean {
// Fast path: barrelFile itself is directly imported by a non-test file
// (the base case of the original `prod_reachable` definition).
const direct = cachedStmt(
_barrelDirectStmt,
db,
`SELECT EXISTS(
SELECT 1 FROM edges e
JOIN nodes src ON e.source_id = src.id
JOIN nodes tgt ON e.target_id = tgt.id
WHERE e.kind IN ('imports', 'dynamic-imports', 'imports-type')
AND src.kind = 'file' AND tgt.kind = 'file' AND tgt.file = ?
${testFilterSQL('src.file')}
) AS reachable`,
).get(barrelFile) as { reachable: number };
if (direct.reachable) return true;
// Slow path: walk `reexports` edges backward from barrelFile (who
// re-exports INTO barrelFile, transitively) looking for an ancestor
// that's directly imported by production. `UNION` (not `UNION ALL`)
// dedupes on `file`, which both bounds the search to barrelFile's own
// chain and guarantees termination if the chain contains a cycle.
const backward = cachedStmt(
_barrelBackwardStmt,
db,
`WITH RECURSIVE ancestors(file) AS (
SELECT ? AS file
UNION
SELECT DISTINCT n1.file FROM edges e
JOIN nodes n1 ON e.source_id = n1.id
JOIN nodes n2 ON e.target_id = n2.id
JOIN ancestors a ON n2.file = a.file
WHERE e.kind = 'reexports'