-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnalyzer.java
More file actions
1375 lines (1227 loc) · 59.9 KB
/
Copy pathAnalyzer.java
File metadata and controls
1375 lines (1227 loc) · 59.9 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
package io.github.randomcodespace.iq.analyzer;
import io.github.randomcodespace.iq.analyzer.linker.Linker;
import io.github.randomcodespace.iq.cache.AnalysisCache;
import io.github.randomcodespace.iq.cache.FileHasher;
import io.github.randomcodespace.iq.cli.VersionCommand;
import io.github.randomcodespace.iq.config.CodeIqConfig;
import io.github.randomcodespace.iq.config.ProjectConfig;
import io.github.randomcodespace.iq.config.ProjectConfigLoader;
import io.github.randomcodespace.iq.detector.Detector;
import io.github.randomcodespace.iq.detector.DetectorContext;
import io.github.randomcodespace.iq.detector.DetectorRegistry;
import io.github.randomcodespace.iq.detector.DetectorResult;
import io.github.randomcodespace.iq.detector.DetectorUtils;
import io.github.randomcodespace.iq.grammar.AntlrParserFactory;
import io.github.randomcodespace.iq.intelligence.FileClassification;
import io.github.randomcodespace.iq.intelligence.FileEntry;
import io.github.randomcodespace.iq.intelligence.FileInventory;
import io.github.randomcodespace.iq.intelligence.RepositoryIdentity;
import io.github.randomcodespace.iq.model.CodeEdge;
import io.github.randomcodespace.iq.model.CodeNode;
import io.github.randomcodespace.iq.model.NodeKind;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Consumer;
/**
* Main analysis pipeline orchestrator.
* <p>
* Steps:
* <ol>
* <li>Discover files (FileDiscovery)</li>
* <li>For each file (virtual threads): read, parse, run detectors</li>
* <li>Build graph (batched via GraphBuilder)</li>
* <li>Run cross-file linkers</li>
* <li>Classify layers</li>
* <li>Return AnalysisResult</li>
* </ol>
* <p>
* Determinism: files are sorted before processing and results are
* collected in indexed slots to avoid ordering non-determinism from
* parallel execution.
*/
@Service
public class Analyzer {
private static final String PROP_FRAMEWORK = "framework";
private static final String PROP_ROOT = "root";
private static final String PROP_SERVICE = "service";
private static final Logger log = LoggerFactory.getLogger(Analyzer.class);
/** Languages whose content should be fed through the structured parser. */
private static final Set<String> STRUCTURED_LANGUAGES = Set.of(
"yaml", "json", "xml", "toml", "ini", "properties"
);
/** Module boundary file names — presence signals a new module root. */
static final Set<String> MODULE_BOUNDARY_MARKERS = Set.of(
"pom.xml", "build.gradle", "build.gradle.kts",
"package.json", "go.mod", "__init__.py",
"Cargo.toml", "setup.py", "pyproject.toml"
);
private final DetectorRegistry registry;
private final StructuredParser parser;
private final FileDiscovery fileDiscovery;
private final LayerClassifier layerClassifier;
private final List<Linker> linkers;
private final CodeIqConfig config;
private final ConfigScanner configScanner;
private final ArchitectureKeywordFilter keywordFilter;
/** Primary constructor — used by Spring Boot dependency injection. */
@Autowired
public Analyzer(
DetectorRegistry registry,
StructuredParser parser,
FileDiscovery fileDiscovery,
LayerClassifier layerClassifier,
List<Linker> linkers,
CodeIqConfig config,
ConfigScanner configScanner,
ArchitectureKeywordFilter keywordFilter
) {
this.registry = registry;
this.parser = parser;
this.fileDiscovery = fileDiscovery;
this.layerClassifier = layerClassifier;
this.linkers = linkers;
this.config = config;
this.configScanner = configScanner;
this.keywordFilter = keywordFilter;
}
/** Backward-compatible constructor for tests that don't need smart indexing. */
public Analyzer(
DetectorRegistry registry,
StructuredParser parser,
FileDiscovery fileDiscovery,
LayerClassifier layerClassifier,
List<Linker> linkers,
CodeIqConfig config
) {
this(registry, parser, fileDiscovery, layerClassifier, linkers, config,
new ConfigScanner(), new ArchitectureKeywordFilter());
}
/**
* Execute the analysis pipeline on the given repository path.
*
* @param repoPath root of the repository to analyze
* @param onProgress optional callback for progress reporting (may be null)
* @return the analysis result containing graph data and statistics
*/
public AnalysisResult run(Path repoPath, Consumer<String> onProgress) {
return run(repoPath, null, onProgress);
}
/**
* Execute the analysis pipeline with optional parallelism control.
*
* @param repoPath root of the repository to analyze
* @param parallelism max parallel threads, or null for adaptive (virtual threads)
* @param onProgress optional callback for progress reporting (may be null)
* @return the analysis result containing graph data and statistics
*/
public AnalysisResult run(Path repoPath, Integer parallelism, Consumer<String> onProgress) {
return run(repoPath, parallelism, true, onProgress);
}
/**
* Execute the analysis pipeline with incremental analysis support.
*
* @param repoPath root of the repository to analyze
* @param parallelism max parallel threads, or null for adaptive (virtual threads)
* @param incremental if true, use file content hashing to skip unchanged files
* @param onProgress optional callback for progress reporting (may be null)
* @return the analysis result containing graph data and statistics
*/
public AnalysisResult run(Path repoPath, Integer parallelism, boolean incremental,
Consumer<String> onProgress) {
Instant start = Instant.now();
Consumer<String> report = onProgress != null ? onProgress : msg -> {};
final Path root = repoPath.toAbsolutePath().normalize();
// Open incremental cache if enabled
AnalysisCache cache = null;
if (incremental) {
try {
Path cachePath = root.resolve(config.getCacheDir()).resolve("analysis-cache.db");
cache = new AnalysisCache(cachePath);
report.accept("Incremental analysis enabled");
} catch (Exception e) {
log.debug("Could not open incremental cache, running full analysis", e);
}
}
try {
return runWithCache(root, parallelism, cache, report, start);
} finally {
if (cache != null) {
cache.close();
}
}
}
private AnalysisResult runWithCache(Path root, Integer parallelism, AnalysisCache cache,
Consumer<String> report, Instant start) {
// 0. Load project config for pipeline filtering
ProjectConfig projectConfig = ProjectConfigLoader.loadProjectConfig(root);
DetectorRegistry effectiveRegistry = registry;
// Apply detector category filter from project config
if (projectConfig.hasDetectorCategoryFilter()) {
effectiveRegistry = effectiveRegistry.filterByCategories(
projectConfig.getDetectorCategories());
report.accept("Detector categories: " + projectConfig.getDetectorCategories());
}
// Apply detector include filter from project config
if (projectConfig.hasDetectorIncludeFilter()) {
effectiveRegistry = effectiveRegistry.filterByNames(
projectConfig.getDetectorInclude());
report.accept("Detector include: " + projectConfig.getDetectorInclude());
}
// Apply parallelism override from project config
if (parallelism == null && projectConfig.getPipelineParallelism() != null) {
parallelism = projectConfig.getPipelineParallelism();
report.accept("Pipeline parallelism: " + parallelism + " (from config)");
}
// 1. Discover files
report.accept("Discovering files...");
List<DiscoveredFile> files = fileDiscovery.discover(root);
// Apply language filter from project config
if (projectConfig.hasLanguageFilter()) {
Set<String> allowedLanguages = new HashSet<>(projectConfig.getLanguages());
files = files.stream()
.filter(f -> allowedLanguages.contains(f.language()))
.toList();
report.accept("Language filter active: " + projectConfig.getLanguages());
}
// Apply exclude patterns from project config
if (projectConfig.hasExcludePatterns()) {
List<String> excludes = projectConfig.getExclude();
List<java.util.regex.Pattern> compiledExcludes = compileExcludePatterns(excludes);
files = files.stream()
.filter(f -> !matchesAnyCompiledExclude(f.path().toString(), compiledExcludes))
.toList();
report.accept("Exclude patterns: " + excludes);
}
int totalFiles = files.size();
report.accept("Found " + totalFiles + " files");
// 1b. Resolve repository identity and build file inventory
RepositoryIdentity repoIdentity = RepositoryIdentity.resolve(root);
FileInventory fileInventory = buildFileInventory(files, cache);
// Compute language breakdown
Map<String, Integer> languageBreakdown = new HashMap<>();
for (DiscoveredFile f : files) {
languageBreakdown.merge(f.language(), 1, Integer::sum);
}
// 2. Analyze files in parallel with virtual threads
report.accept("Analyzing " + totalFiles + " files...");
DetectorResult[] resultSlots = new DetectorResult[files.size()];
var cacheHitsCounter = new java.util.concurrent.atomic.AtomicInteger(0);
final DetectorRegistry detectorRegistry = effectiveRegistry;
var executorService = parallelism != null && parallelism > 0
? Executors.newFixedThreadPool(parallelism)
: Executors.newVirtualThreadPerTaskExecutor();
try (var executor = executorService) {
List<Future<?>> futures = new ArrayList<>(files.size());
for (int i = 0; i < files.size(); i++) {
final int idx = i;
final DiscoveredFile file = files.get(idx);
final AnalysisCache cacheRef = cache;
futures.add(executor.submit(() -> {
// Check cache first
if (cacheRef != null) {
try {
Path absPath = root.resolve(file.path());
String hash = FileHasher.hash(absPath);
if (cacheRef.isCached(hash)) {
var cached = cacheRef.loadCachedResults(hash);
if (cached != null) {
resultSlots[idx] = DetectorResult.of(cached.nodes(), cached.edges());
cacheHitsCounter.incrementAndGet();
return null;
}
}
// Run detectors and cache result
DetectorResult result = analyzeFile(file, root, detectorRegistry);
resultSlots[idx] = result;
if (result != null && (!result.nodes().isEmpty() || !result.edges().isEmpty())) {
cacheRef.storeResults(hash, file.path().toString(), file.language(),
result.nodes(), result.edges());
}
} catch (IOException e) {
log.debug("Could not hash file {}", file.path(), e);
resultSlots[idx] = analyzeFile(file, root, detectorRegistry);
}
} else {
resultSlots[idx] = analyzeFile(file, root, detectorRegistry);
}
return null;
}));
}
// Collect in order -- deterministic regardless of thread completion order
for (int i = 0; i < futures.size(); i++) {
try {
futures.get(i).get();
} catch (ExecutionException e) {
log.warn("Analysis failed for {}", files.get(i).path(), e.getCause());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Analysis interrupted for {}", files.get(i).path());
}
}
}
if (cache != null && cacheHitsCounter.get() > 0) {
report.accept("Cache hits: " + cacheHitsCounter.get() + " / " + totalFiles + " files");
}
// 3. Build graph (batched)
report.accept("Building graph...");
var builder = new GraphBuilder(repoIdentity, VersionCommand.VERSION);
int filesAnalyzed = 0;
for (int i = 0; i < resultSlots.length; i++) {
DetectorResult result = resultSlots[i];
if (result != null && (!result.nodes().isEmpty() || !result.edges().isEmpty())) {
builder.addResult(result);
filesAnalyzed++;
}
}
// 4. Run cross-file linkers
report.accept("Linking cross-file relationships...");
builder.runLinkers(linkers);
// Flush and collect deferred edges
GraphBuilder.FlushResult flushed = builder.flush();
List<io.github.randomcodespace.iq.model.CodeEdge> recoveredEdges = builder.flushDeferred();
// 5. Classify layers
report.accept("Classifying layers...");
List<CodeNode> allNodes = builder.getNodes();
layerClassifier.classify(allNodes);
// 5b. Detect service boundaries and create SERVICE nodes
report.accept("Detecting service boundaries...");
var serviceDetector = new ServiceDetector();
String projectDirName = root.getFileName() != null ? root.getFileName().toString() : PROP_ROOT;
var serviceResult = serviceDetector.detect(allNodes, builder.getEdges(), projectDirName, root);
if (!serviceResult.serviceNodes().isEmpty()) {
serviceResult.serviceNodes().forEach(n -> n.setProvenance(builder.getProvenance()));
builder.addNodes(serviceResult.serviceNodes());
builder.addEdges(serviceResult.serviceEdges());
allNodes = builder.getNodes(); // refresh reference after adding service nodes
}
// 5c. Tag nodes with service name if configured (multi-repo mode) -- overrides auto-detected
String serviceName = config.getServiceName();
if (serviceName != null && !serviceName.isBlank()) {
for (CodeNode node : allNodes) {
node.getProperties().put(PROP_SERVICE, serviceName);
}
}
// 6. Attach edges to their source nodes for downstream consumers
Map<String, CodeNode> nodeById = new HashMap<>(allNodes.size());
for (CodeNode node : allNodes) {
nodeById.put(node.getId(), node);
}
for (var edge : builder.getEdges()) {
CodeNode source = nodeById.get(edge.getSourceId());
if (source != null) {
source.getEdges().add(edge);
}
}
// 7. Compute node breakdown
Map<String, Integer> nodeBreakdown = new HashMap<>();
for (CodeNode node : allNodes) {
String kindValue = node.getKind().getValue();
nodeBreakdown.merge(kindValue, 1, Integer::sum);
}
// 8. Compute edge breakdown
Map<String, Integer> edgeBreakdown = new HashMap<>();
for (var edge : builder.getEdges()) {
String kindValue = edge.getKind().getValue();
edgeBreakdown.merge(kindValue, 1, Integer::sum);
}
// 7b. Compute framework breakdown from node properties
Map<String, Integer> frameworkBreakdown = new HashMap<>();
for (CodeNode node : allNodes) {
Object fw = node.getProperties().get(PROP_FRAMEWORK);
if (fw != null && !fw.toString().isEmpty()) {
frameworkBreakdown.merge(fw.toString(), 1, Integer::sum);
}
Object authType = node.getProperties().get("auth_type");
if (authType != null && !authType.toString().isEmpty()) {
frameworkBreakdown.merge("auth:" + authType, 1, Integer::sum);
}
}
// 8. Record analysis run in cache
if (cache != null) {
String commitSha = getGitHead(root);
cache.recordRun(commitSha, filesAnalyzed);
}
Duration elapsed = Duration.between(start, Instant.now());
int nodeCount = builder.getNodeCount();
int edgeCount = builder.getEdgeCount();
report.accept("Analysis complete - " + nodeCount + " nodes, " + edgeCount + " edges");
log.debug("Analysis complete: {} nodes, {} edges in {}ms",
nodeCount, edgeCount, elapsed.toMillis());
return new AnalysisResult(
totalFiles,
filesAnalyzed,
nodeCount,
edgeCount,
languageBreakdown,
nodeBreakdown,
edgeBreakdown,
frameworkBreakdown,
elapsed,
allNodes
);
}
/**
* Execute the indexing pipeline with batched streaming to H2.
* <p>
* Unlike {@link #run}, this method does NOT hold all nodes/edges in memory.
* It processes files in batches and flushes each batch to H2, then releases
* the batch memory. No linkers, layer classification, or Neo4j are used.
*
* @param repoPath root of the repository to analyze
* @param parallelism max parallel threads, or null for adaptive (virtual threads)
* @param batchSize number of files per H2 flush batch
* @param incremental if true, use file content hashing to skip unchanged files
* @param onProgress optional callback for progress reporting (may be null)
* @return the analysis result containing graph data and statistics
*/
public AnalysisResult runBatchedIndex(Path repoPath, Integer parallelism, int batchSize,
boolean incremental, Consumer<String> onProgress) {
Instant start = Instant.now();
Consumer<String> report = onProgress != null ? onProgress : msg -> {};
final Path root = repoPath.toAbsolutePath().normalize();
// Always use H2 cache as the primary store during indexing
Path cachePath = root.resolve(config.getCacheDir()).resolve("analysis-cache.db");
AnalysisCache cache;
try {
cache = new AnalysisCache(cachePath);
} catch (Exception e) {
log.error("Failed to open H2 store at {}", cachePath, e);
return new AnalysisResult(0, 0, 0, 0,
Map.of(), Map.of(), Map.of(), Map.of(), Duration.ZERO);
}
try {
return runBatchedWithCache(root, parallelism, batchSize, incremental, cache, report, start);
} finally {
cache.close();
}
}
private AnalysisResult runBatchedWithCache(Path root, Integer parallelism, int batchSize,
boolean incremental, AnalysisCache cache,
Consumer<String> report, Instant start) {
// 0. Load project config for pipeline filtering
ProjectConfig projectConfig = ProjectConfigLoader.loadProjectConfig(root);
DetectorRegistry effectiveRegistry = registry;
if (projectConfig.hasDetectorCategoryFilter()) {
effectiveRegistry = effectiveRegistry.filterByCategories(
projectConfig.getDetectorCategories());
report.accept("Detector categories: " + projectConfig.getDetectorCategories());
}
if (projectConfig.hasDetectorIncludeFilter()) {
effectiveRegistry = effectiveRegistry.filterByNames(
projectConfig.getDetectorInclude());
report.accept("Detector include: " + projectConfig.getDetectorInclude());
}
if (parallelism == null && projectConfig.getPipelineParallelism() != null) {
parallelism = projectConfig.getPipelineParallelism();
report.accept("Pipeline parallelism: " + parallelism + " (from config)");
}
// 1. Discover files
report.accept("Discovering files...");
List<DiscoveredFile> files = fileDiscovery.discover(root);
if (projectConfig.hasLanguageFilter()) {
Set<String> allowedLanguages = new HashSet<>(projectConfig.getLanguages());
files = files.stream()
.filter(f -> allowedLanguages.contains(f.language()))
.toList();
report.accept("Language filter active: " + projectConfig.getLanguages());
}
if (projectConfig.hasExcludePatterns()) {
List<String> excludes = projectConfig.getExclude();
List<java.util.regex.Pattern> compiledExcludes = compileExcludePatterns(excludes);
files = files.stream()
.filter(f -> !matchesAnyCompiledExclude(f.path().toString(), compiledExcludes))
.toList();
report.accept("Exclude patterns: " + excludes);
}
int totalFiles = files.size();
report.accept("Found " + totalFiles + " files");
// Compute language breakdown
Map<String, Integer> languageBreakdown = new HashMap<>();
for (DiscoveredFile f : files) {
languageBreakdown.merge(f.language(), 1, Integer::sum);
}
// 2. Process files in batches
report.accept("Indexing " + totalFiles + " files in batches of " + batchSize + "...");
final DetectorRegistry detectorRegistry = effectiveRegistry;
int totalNodesWritten = 0;
int totalEdgesWritten = 0;
int filesAnalyzed = 0;
int cacheHits = 0;
int batchNumber = 0;
Map<String, Integer> nodeBreakdown = new HashMap<>();
Map<String, Integer> edgeBreakdown = new HashMap<>();
Map<String, Integer> frameworkBreakdown = new HashMap<>();
// Clear previous index data if not incremental
if (!incremental) {
cache.clear();
}
var batchExecutorService = parallelism != null && parallelism > 0
? Executors.newFixedThreadPool(parallelism)
: Executors.newVirtualThreadPerTaskExecutor();
try (batchExecutorService) {
List<DiscoveredFile> batch = new ArrayList<>(batchSize);
for (int fileIdx = 0; fileIdx < files.size(); fileIdx++) {
batch.add(files.get(fileIdx));
if (batch.size() >= batchSize || fileIdx == files.size() - 1) {
batchNumber++;
report.accept("Processing batch " + batchNumber + " (" + batch.size() + " files)...");
// Analyze batch in parallel
DetectorResult[] resultSlots = new DetectorResult[batch.size()];
var batchCacheHits = new java.util.concurrent.atomic.AtomicInteger(0);
{
List<Future<?>> futures = new ArrayList<>(batch.size());
for (int i = 0; i < batch.size(); i++) {
final int idx = i;
final DiscoveredFile file = batch.get(idx);
futures.add(batchExecutorService.submit(() -> {
if (incremental) {
try {
Path absPath = root.resolve(file.path());
String hash = FileHasher.hash(absPath);
if (cache.isCached(hash)) {
var cached = cache.loadCachedResults(hash);
if (cached != null) {
resultSlots[idx] = DetectorResult.of(cached.nodes(), cached.edges());
batchCacheHits.incrementAndGet();
return null;
}
}
DetectorResult result = analyzeFile(file, root, detectorRegistry);
resultSlots[idx] = result;
if (result != null && (!result.nodes().isEmpty() || !result.edges().isEmpty())) {
cache.storeResults(hash, file.path().toString(), file.language(),
result.nodes(), result.edges());
}
} catch (IOException e) {
log.debug("Could not hash file {}", file.path(), e);
resultSlots[idx] = analyzeFile(file, root, detectorRegistry);
}
} else {
resultSlots[idx] = analyzeFile(file, root, detectorRegistry);
}
return null;
}));
}
// Collect in order
for (int i = 0; i < futures.size(); i++) {
try {
futures.get(i).get();
} catch (ExecutionException e) {
log.warn("Analysis failed for {}", batch.get(i).path(), e.getCause());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Analysis interrupted for {}", batch.get(i).path());
}
}
}
cacheHits += batchCacheHits.get();
// Collect batch results and flush non-cached to H2
List<CodeNode> batchNodes = new ArrayList<>();
List<CodeEdge> batchEdges = new ArrayList<>();
int batchFilesAnalyzed = 0;
for (int i = 0; i < resultSlots.length; i++) {
DetectorResult result = resultSlots[i];
if (result != null && (!result.nodes().isEmpty() || !result.edges().isEmpty())) {
batchFilesAnalyzed++;
// Only store non-incremental results (incremental already stored above)
if (!incremental) {
batchNodes.addAll(result.nodes());
batchEdges.addAll(result.edges());
}
// Tag nodes with service name if configured (multi-repo mode)
String svcName = config.getServiceName();
if (svcName != null && !svcName.isBlank()) {
for (CodeNode node : result.nodes()) {
node.getProperties().put(PROP_SERVICE, svcName);
}
}
// Track breakdowns
for (CodeNode node : result.nodes()) {
nodeBreakdown.merge(node.getKind().getValue(), 1, Integer::sum);
Object fw = node.getProperties().get(PROP_FRAMEWORK);
if (fw != null && !fw.toString().isEmpty()) {
frameworkBreakdown.merge(fw.toString(), 1, Integer::sum);
}
}
for (var edge : result.edges()) {
edgeBreakdown.merge(edge.getKind().getValue(), 1, Integer::sum);
}
totalNodesWritten += result.nodes().size();
totalEdgesWritten += result.edges().size();
}
}
filesAnalyzed += batchFilesAnalyzed;
// For non-incremental mode, batch-flush to H2
if (!incremental && (!batchNodes.isEmpty() || !batchEdges.isEmpty())) {
String batchId = "batch:" + batchNumber + ":" + System.nanoTime();
cache.storeBatchResults(batchId, "batch-" + batchNumber,
"mixed", batchNodes, batchEdges);
}
// Release batch memory
batch.clear();
}
}
} // close batchExecutorService
if (cacheHits > 0) {
report.accept("Cache hits: " + cacheHits + " / " + totalFiles + " files");
}
// Record run
String commitSha = getGitHead(root);
cache.recordRun(commitSha, filesAnalyzed);
Duration elapsed = Duration.between(start, Instant.now());
report.accept("Index complete - " + totalNodesWritten + " nodes, "
+ totalEdgesWritten + " edges written to H2");
return new AnalysisResult(
totalFiles,
filesAnalyzed,
totalNodesWritten,
totalEdgesWritten,
languageBreakdown,
nodeBreakdown,
edgeBreakdown,
frameworkBreakdown,
elapsed
);
}
// =========================================================================
// Smart Index Pipeline (config-first, module-partitioned)
// =========================================================================
/**
* Config-first, module-partitioned indexing pipeline.
* <p>
* Phase 1 scans config files to build an {@link InfrastructureRegistry}.
* Phase 2 discovers source files, partitions them by module, pre-filters
* each module with {@link ArchitectureKeywordFilter}, then runs detectors
* in parallel and flushes results to H2 per batch.
* <p>
* This method is additive — existing {@link #runBatchedIndex} is unchanged.
*
* @param repoPath root of the repository to analyze
* @param parallelism max parallel threads, or null for virtual threads
* @param batchSize files per H2 flush batch
* @param incremental if true, use file content hashing to skip unchanged files
* @param onProgress optional progress callback
* @return analysis result with phase timing in the report
*/
public AnalysisResult runSmartIndex(Path repoPath, Integer parallelism, int batchSize,
boolean incremental, Consumer<String> onProgress) {
Instant start = Instant.now();
Consumer<String> report = onProgress != null ? onProgress : msg -> {};
final Path root = repoPath.toAbsolutePath().normalize();
Path cachePath = root.resolve(config.getCacheDir()).resolve("analysis-cache.db");
AnalysisCache cache;
try {
cache = new AnalysisCache(cachePath);
} catch (Exception e) {
log.error("Failed to open H2 store at {}", cachePath, e);
return new AnalysisResult(0, 0, 0, 0,
Map.of(), Map.of(), Map.of(), Map.of(), Duration.ZERO);
}
try {
return runSmartWithCache(root, parallelism, batchSize, incremental, cache, report, start);
} finally {
cache.close();
}
}
private AnalysisResult runSmartWithCache(Path root, Integer parallelism, int batchSize,
boolean incremental, AnalysisCache cache,
Consumer<String> report, Instant start) {
// ── Phase 1: Config scanning ──────────────────────────────────────────
Instant phase1Start = Instant.now();
report.accept("Phase 1: Scanning config files...");
InfrastructureRegistry infraRegistry = configScanner.scan(root);
long phase1Ms = Duration.between(phase1Start, Instant.now()).toMillis();
report.accept("Phase 1 complete - " + infraRegistry.size()
+ " infrastructure endpoint(s) in " + phase1Ms + "ms");
if (infraRegistry.getServiceName() != null) {
report.accept("Service: " + infraRegistry.getServiceName());
// Propagate to config if not already set
if (config.getServiceName() == null || config.getServiceName().isBlank()) {
config.setServiceName(infraRegistry.getServiceName());
}
}
// ── Phase 2: File discovery + project config ───────────────────────────
Instant phase2Start = Instant.now();
report.accept("Phase 2: Discovering files...");
ProjectConfig projectConfig = ProjectConfigLoader.loadProjectConfig(root);
DetectorRegistry effectiveRegistry = registry;
if (projectConfig.hasDetectorCategoryFilter()) {
effectiveRegistry = effectiveRegistry.filterByCategories(
projectConfig.getDetectorCategories());
}
if (projectConfig.hasDetectorIncludeFilter()) {
effectiveRegistry = effectiveRegistry.filterByNames(
projectConfig.getDetectorInclude());
}
if (parallelism == null && projectConfig.getPipelineParallelism() != null) {
parallelism = projectConfig.getPipelineParallelism();
}
List<DiscoveredFile> allFiles = fileDiscovery.discover(root);
if (projectConfig.hasLanguageFilter()) {
Set<String> allowed = new HashSet<>(projectConfig.getLanguages());
allFiles = allFiles.stream().filter(f -> allowed.contains(f.language())).toList();
}
if (projectConfig.hasExcludePatterns()) {
List<java.util.regex.Pattern> compiledExcludes =
compileExcludePatterns(projectConfig.getExclude());
allFiles = allFiles.stream()
.filter(f -> !matchesAnyCompiledExclude(f.path().toString(), compiledExcludes))
.toList();
}
int totalFiles = allFiles.size();
// Compute language breakdown
Map<String, Integer> languageBreakdown = new HashMap<>();
for (DiscoveredFile f : allFiles) {
languageBreakdown.merge(f.language(), 1, Integer::sum);
}
// ── Phase 3: Module partitioning ──────────────────────────────────────
Map<String, List<DiscoveredFile>> modules = detectModules(root, allFiles);
report.accept("Phase 2 complete - " + totalFiles + " files in "
+ modules.size() + " module(s) in "
+ Duration.between(phase2Start, Instant.now()).toMillis() + "ms");
// ── Phase 4: Per-module analysis with keyword pre-filter ──────────────
if (!incremental) {
cache.clear();
}
final DetectorRegistry detectorRegistry = effectiveRegistry;
int totalNodesWritten = 0;
int totalEdgesWritten = 0;
int filesAnalyzed = 0;
int filesSkipped = 0;
int cacheHits = 0;
int batchNumber = 0;
Map<String, Integer> nodeBreakdown = new HashMap<>();
Map<String, Integer> edgeBreakdown = new HashMap<>();
Map<String, Integer> frameworkBreakdown = new HashMap<>();
var executorService = parallelism != null && parallelism > 0
? Executors.newFixedThreadPool(parallelism)
: Executors.newVirtualThreadPerTaskExecutor();
// Process modules in sorted order for determinism
List<String> sortedModuleKeys = new ArrayList<>(modules.keySet());
sortedModuleKeys.sort(String::compareTo);
try (var executor = executorService) {
List<DiscoveredFile> pendingBatch = new ArrayList<>(batchSize);
int moduleIndex = 0;
for (String moduleKey : sortedModuleKeys) {
List<DiscoveredFile> moduleFiles = modules.get(moduleKey);
moduleIndex++;
report.accept("Processing module " + moduleIndex + "/" + sortedModuleKeys.size()
+ ": " + moduleKey + " (" + moduleFiles.size() + " files)");
// Pre-filter source files with keyword filter; always pass structured files
List<DiscoveredFile> filtered = new ArrayList<>(moduleFiles.size());
for (DiscoveredFile file : moduleFiles) {
if (STRUCTURED_LANGUAGES.contains(file.language())) {
// Always include config/structured files
filtered.add(file);
} else {
// Read and check for architecture keywords
try {
Path absPath = root.resolve(file.path());
byte[] raw = Files.readAllBytes(absPath);
if (keywordFilter.shouldAnalyze(raw, file.language())) {
filtered.add(file);
} else {
filesSkipped++;
}
} catch (IOException e) {
log.debug("Could not read for keyword filter {}", file.path(), e);
filtered.add(file); // include on error
}
}
}
// Add filtered files to pending batch
for (DiscoveredFile file : filtered) {
pendingBatch.add(file);
if (pendingBatch.size() >= batchSize) {
batchNumber++;
var batchResult = processSmartBatch(pendingBatch, root, executor,
detectorRegistry, infraRegistry, incremental, cache,
nodeBreakdown, edgeBreakdown, frameworkBreakdown,
batchNumber, report);
totalNodesWritten += batchResult[0];
totalEdgesWritten += batchResult[1];
filesAnalyzed += batchResult[2];
cacheHits += batchResult[3];
pendingBatch.clear();
}
}
}
// Flush remaining files
if (!pendingBatch.isEmpty()) {
batchNumber++;
var batchResult = processSmartBatch(pendingBatch, root, executor,
detectorRegistry, infraRegistry, incremental, cache,
nodeBreakdown, edgeBreakdown, frameworkBreakdown,
batchNumber, report);
totalNodesWritten += batchResult[0];
totalEdgesWritten += batchResult[1];
filesAnalyzed += batchResult[2];
cacheHits += batchResult[3];
pendingBatch.clear();
}
}
if (filesSkipped > 0) {
report.accept("Keyword filter: skipped " + filesSkipped + " / " + totalFiles
+ " files (" + (filesSkipped * 100 / Math.max(1, totalFiles)) + "%)");
}
if (cacheHits > 0) {
report.accept("Cache hits: " + cacheHits + " / " + totalFiles + " files");
}
String commitSha = getGitHead(root);
cache.recordRun(commitSha, filesAnalyzed);
Duration elapsed = Duration.between(start, Instant.now());
report.accept("Smart index complete - " + totalNodesWritten + " nodes, "
+ totalEdgesWritten + " edges written to H2");
return new AnalysisResult(
totalFiles,
filesAnalyzed,
totalNodesWritten,
totalEdgesWritten,
languageBreakdown,
nodeBreakdown,
edgeBreakdown,
frameworkBreakdown,
elapsed
);
}
/** Analyze one batch, flush to H2, return [nodes, edges, filesAnalyzed, cacheHits]. */
private int[] processSmartBatch(
List<DiscoveredFile> batch, Path root,
java.util.concurrent.ExecutorService executor,
DetectorRegistry detectorRegistry, InfrastructureRegistry infraRegistry,
boolean incremental, AnalysisCache cache,
Map<String, Integer> nodeBreakdown, Map<String, Integer> edgeBreakdown,
Map<String, Integer> frameworkBreakdown,
int batchNumber, Consumer<String> report) {
report.accept("Processing batch " + batchNumber + " (" + batch.size() + " files)...");
DetectorResult[] slots = new DetectorResult[batch.size()];
var batchCacheHits = new java.util.concurrent.atomic.AtomicInteger(0);
List<Future<?>> futures = new ArrayList<>(batch.size());
for (int i = 0; i < batch.size(); i++) {
final int idx = i;
final DiscoveredFile file = batch.get(idx);
futures.add(executor.submit(() -> {
if (incremental) {
try {
Path absPath = root.resolve(file.path());
String hash = FileHasher.hash(absPath);
if (cache.isCached(hash)) {
var cached = cache.loadCachedResults(hash);
if (cached != null) {
slots[idx] = DetectorResult.of(cached.nodes(), cached.edges());
batchCacheHits.incrementAndGet();
return null;
}
}
DetectorResult result = analyzeFileWithRegistry(file, root, detectorRegistry, infraRegistry);
slots[idx] = result;
if (result != null && (!result.nodes().isEmpty() || !result.edges().isEmpty())) {
cache.storeResults(hash, file.path().toString(), file.language(),
result.nodes(), result.edges());
}
} catch (IOException e) {
log.debug("Could not hash {}", file.path(), e);
slots[idx] = analyzeFileWithRegistry(file, root, detectorRegistry, infraRegistry);
}
} else {
slots[idx] = analyzeFileWithRegistry(file, root, detectorRegistry, infraRegistry);
}
return null;
}));
}
for (int i = 0; i < futures.size(); i++) {
try {
futures.get(i).get();
} catch (ExecutionException e) {
log.warn("Analysis failed for {}", batch.get(i).path(), e.getCause());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
log.warn("Analysis interrupted for {}", batch.get(i).path());
}
}
int nodes = 0, edges = 0, analyzed = 0;
List<CodeNode> batchNodes = new ArrayList<>();
List<CodeEdge> batchEdges = new ArrayList<>();
for (DetectorResult result : slots) {
if (result != null && (!result.nodes().isEmpty() || !result.edges().isEmpty())) {
analyzed++;
if (!incremental) {
batchNodes.addAll(result.nodes());
batchEdges.addAll(result.edges());
}
String svcName = config.getServiceName();
if (svcName != null && !svcName.isBlank()) {
for (CodeNode node : result.nodes()) {
node.getProperties().put(PROP_SERVICE, svcName);
}
}
for (CodeNode node : result.nodes()) {
nodeBreakdown.merge(node.getKind().getValue(), 1, Integer::sum);
Object fw = node.getProperties().get(PROP_FRAMEWORK);
if (fw != null && !fw.toString().isEmpty()) {
frameworkBreakdown.merge(fw.toString(), 1, Integer::sum);
}
}
for (var edge : result.edges()) {
edgeBreakdown.merge(edge.getKind().getValue(), 1, Integer::sum);
}
nodes += result.nodes().size();
edges += result.edges().size();
}
}
if (!incremental && (!batchNodes.isEmpty() || !batchEdges.isEmpty())) {
String batchId = "batch:" + batchNumber + ":" + System.nanoTime();
cache.storeBatchResults(batchId, "batch-" + batchNumber, "mixed", batchNodes, batchEdges);
}