-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtypes.ts
More file actions
2432 lines (2171 loc) · 72.2 KB
/
types.ts
File metadata and controls
2432 lines (2171 loc) · 72.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
/**
* Core type definitions for codegraph.
*
* These interfaces serve as the migration contract — each module is migrated
* to satisfy its interface. They capture every abstraction in the codebase:
* symbol/edge kinds, database shapes, repository contracts, extractors,
* parsers, builders, visitors, features, config, and the graph model.
*/
// ════════════════════════════════════════════════════════════════════════
// §1 Symbol & Edge Kind Enumerations
// ════════════════════════════════════════════════════════════════════════
/** The original 10 symbol kinds — default query scope. */
export type CoreSymbolKind =
| 'function'
| 'method'
| 'class'
| 'interface'
| 'type'
| 'struct'
| 'enum'
| 'trait'
| 'record'
| 'module'
| 'namespace';
/** Sub-declaration kinds (Phase 1). Includes 'method' for class child nodes. */
export type ExtendedSymbolKind = 'parameter' | 'property' | 'constant' | 'variable' | 'method';
/** All queryable symbol kinds. */
export type SymbolKind = CoreSymbolKind | ExtendedSymbolKind;
/** Special kind used for file-level nodes in the graph. */
export type FileNodeKind = 'file';
/** Union of every kind that can appear in a node row. */
export type AnyNodeKind = SymbolKind | FileNodeKind;
/** Coupling and dependency edge kinds. */
export type CoreEdgeKind =
| 'imports'
| 'imports-type'
| 'dynamic-imports'
| 'reexports'
| 'calls'
| 'extends'
| 'implements'
| 'contains';
/** Parent/child and type relationship edges. */
export type StructuralEdgeKind = 'parameter_of' | 'receiver';
/** Dataflow-specific edge kinds. */
export type DataflowEdgeKind = 'flows_to' | 'returns' | 'mutates';
/** All edge kinds that can appear in the graph. */
export type EdgeKind = CoreEdgeKind | StructuralEdgeKind;
/** Extended edge kinds including dataflow. */
export type AnyEdgeKind = EdgeKind | DataflowEdgeKind;
/** AST node kinds extracted during analysis. */
export type ASTNodeKind = 'new' | 'string' | 'regex' | 'throw' | 'await';
/** Coarse role classifications for symbols based on connectivity. */
export type CoreRole = 'entry' | 'core' | 'utility' | 'adapter' | 'dead' | 'test-only' | 'leaf';
/** Dead sub-roles — refine the coarse "dead" bucket. */
export type DeadSubRole = 'dead-leaf' | 'dead-entry' | 'dead-ffi' | 'dead-unresolved';
/** Every valid role. */
export type Role = CoreRole | DeadSubRole;
/** Supported language identifiers (from LANGUAGE_REGISTRY). */
export type LanguageId =
| 'javascript'
| 'typescript'
| 'tsx'
| 'python'
| 'go'
| 'rust'
| 'java'
| 'csharp'
| 'ruby'
| 'php'
| 'hcl'
| 'c'
| 'cpp'
| 'kotlin'
| 'swift'
| 'scala'
| 'bash'
| 'elixir'
| 'lua'
| 'dart'
| 'zig'
| 'haskell'
| 'ocaml'
| 'ocaml-interface'
| 'fsharp'
| 'gleam'
| 'clojure'
| 'julia'
| 'r'
| 'erlang'
| 'solidity'
| 'objc'
| 'cuda'
| 'groovy'
| 'verilog';
/** Engine mode selector. */
export type EngineMode = 'native' | 'wasm' | 'auto';
/** Graph export formats. */
export type ExportFormat = 'dot' | 'mermaid' | 'json' | 'graphml' | 'graphson' | 'neo4j-csv';
// ════════════════════════════════════════════════════════════════════════
// §2 Database Row Shapes
// ════════════════════════════════════════════════════════════════════════
/** A node row as stored in (and returned from) SQLite. */
export interface NodeRow {
id: number;
name: string;
kind: AnyNodeKind;
file: string;
line: number;
end_line: number | null;
parent_id: number | null;
exported: 0 | 1 | null;
qualified_name: string | null;
scope: string | null;
visibility: 'public' | 'private' | 'protected' | null;
role: Role | null;
}
/** A node row augmented with fan-in count (from findNodesWithFanIn). */
export interface NodeRowWithFanIn extends NodeRow {
fan_in: number;
}
/** A node row augmented with triage signals (from findNodesForTriage). */
export interface TriageNodeRow extends NodeRow {
fan_in: number;
cognitive: number;
mi: number;
cyclomatic: number;
max_nesting: number;
churn: number;
}
/** Compact node ID row (from bulkNodeIdsByFile). */
export interface NodeIdRow {
id: number;
name: string;
kind: string;
line: number;
}
/** A child node row (from findNodeChildren). */
export interface ChildNodeRow {
name: string;
kind: SymbolKind;
line: number;
end_line: number | null;
qualified_name: string | null;
scope: string | null;
visibility: 'public' | 'private' | 'protected' | null;
file?: string;
}
/** An edge row as stored in SQLite. */
export interface EdgeRow {
id: number;
source_id: number;
target_id: number;
kind: EdgeKind;
confidence: number | null;
dynamic: 0 | 1;
}
/** Callee/caller node shape (from findCallees / findCallers). */
export interface RelatedNodeRow {
id: number;
name: string;
kind: string;
file: string;
line: number;
end_line?: number | null;
}
/** An incoming/outgoing edge with the related node info. */
export interface AdjacentEdgeRow {
name: string;
kind: string;
file: string;
line: number;
edge_kind: EdgeKind;
}
/** Import target/source row. */
export interface ImportEdgeRow {
file: string;
edge_kind: EdgeKind;
}
/** Intra-file call edge (from findIntraFileCallEdges). */
export interface IntraFileCallEdge {
caller_name: string;
callee_name: string;
}
/** Callable node row (for graph-read queries). */
export interface CallableNodeRow {
id: number;
name: string;
kind: string;
file: string;
}
/** Call edge row (for graph-read queries). */
export interface CallEdgeRow {
source_id: number;
target_id: number;
confidence: number | null;
}
/** File node row (for graph-read queries). */
export interface FileNodeRow {
id: number;
name: string;
file: string;
}
/** Import edge row (for graph-read queries). */
export interface ImportGraphEdgeRow {
source_id: number;
target_id: number;
}
/** Complexity metrics (from getComplexityForNode). */
export interface ComplexityMetrics {
cognitive: number;
cyclomatic: number;
max_nesting: number;
maintainability_index: number | null;
halstead_volume: number | null;
}
// ════════════════════════════════════════════════════════════════════════
// §3 Repository Interface
// ════════════════════════════════════════════════════════════════════════
/** Query options common across many repository methods. */
export interface QueryOpts {
kind?: SymbolKind;
kinds?: SymbolKind[];
file?: string;
noTests?: boolean;
}
/** Options for listFunctionNodes / iterateFunctionNodes. */
export interface ListFunctionOpts {
file?: string;
pattern?: string;
noTests?: boolean;
}
/** Options for findNodesForTriage. */
export interface TriageQueryOpts {
kind?: string;
role?: Role;
noTests?: boolean;
file?: string;
}
/**
* Abstract Repository contract — defines all graph data access methods.
* Concrete implementations: SqliteRepository, InMemoryRepository.
*/
export interface Repository {
// ── Node lookups ──────────────────────────────────────────────────
findNodeById(id: number): NodeRow | undefined;
findNodesByFile(file: string): NodeRow[];
findFileNodes(fileLike: string): NodeRow[];
findNodesWithFanIn(namePattern: string, opts?: QueryOpts): NodeRowWithFanIn[];
countNodes(): number;
countEdges(): number;
countFiles(): number;
getNodeId(name: string, kind: string, file: string, line: number): number | undefined;
getFunctionNodeId(name: string, file: string, line: number): number | undefined;
bulkNodeIdsByFile(file: string): NodeIdRow[];
findNodeChildren(parentId: number): ChildNodeRow[];
findNodesByScope(scopeName: string, opts?: QueryOpts): NodeRow[];
findNodeByQualifiedName(qualifiedName: string, opts?: { file?: string }): NodeRow[];
listFunctionNodes(opts?: ListFunctionOpts): NodeRow[];
iterateFunctionNodes(opts?: ListFunctionOpts): IterableIterator<NodeRow>;
findNodesForTriage(opts?: TriageQueryOpts): TriageNodeRow[];
// ── Edge queries ──────────────────────────────────────────────────
findCallees(nodeId: number): RelatedNodeRow[];
findCallers(nodeId: number): RelatedNodeRow[];
findDistinctCallers(nodeId: number): RelatedNodeRow[];
findAllOutgoingEdges(nodeId: number): AdjacentEdgeRow[];
findAllIncomingEdges(nodeId: number): AdjacentEdgeRow[];
findCalleeNames(nodeId: number): string[];
findCallerNames(nodeId: number): string[];
findImportTargets(nodeId: number): ImportEdgeRow[];
findImportSources(nodeId: number): ImportEdgeRow[];
findImportDependents(nodeId: number): NodeRow[];
findCrossFileCallTargets(file: string): Set<number>;
countCrossFileCallers(nodeId: number, file: string): number;
getClassHierarchy(classNodeId: number): Set<number>;
findImplementors(nodeId: number): RelatedNodeRow[];
findInterfaces(nodeId: number): RelatedNodeRow[];
findIntraFileCallEdges(file: string): IntraFileCallEdge[];
// ── Graph-read queries ────────────────────────────────────────────
getCallableNodes(): CallableNodeRow[];
getCallEdges(): CallEdgeRow[];
getFileNodesAll(): FileNodeRow[];
getImportEdges(): ImportGraphEdgeRow[];
// ── Optional table checks ─────────────────────────────────────────
hasCfgTables(): boolean;
hasEmbeddings(): boolean;
hasDataflowTable(): boolean;
getComplexityForNode(nodeId: number): ComplexityMetrics | undefined;
}
/**
* In-memory repository — mutable, used for testing and incremental builds.
* Extends Repository with mutation methods.
*/
export interface MutableRepository extends Repository {
addNode(attrs: {
name: string;
kind: AnyNodeKind;
file: string;
line: number;
end_line?: number;
parent_id?: number;
exported?: 0 | 1;
qualified_name?: string;
scope?: string;
visibility?: 'public' | 'private' | 'protected';
role?: Role;
}): number;
addEdge(attrs: {
source_id: number;
target_id: number;
kind: AnyEdgeKind;
confidence?: number;
dynamic?: 0 | 1;
}): number;
addComplexity(
nodeId: number,
metrics: {
cognitive: number;
cyclomatic: number;
max_nesting: number;
maintainability_index?: number;
halstead_volume?: number;
},
): void;
}
// ════════════════════════════════════════════════════════════════════════
// §4 Extractor Types
// ════════════════════════════════════════════════════════════════════════
/** A symbol definition produced by any extractor. */
export interface Definition {
name: string;
kind: SymbolKind;
line: number;
endLine?: number;
children?: SubDeclaration[];
visibility?: 'public' | 'private' | 'protected';
decorators?: string[];
/** Populated post-analysis by the complexity visitor. */
complexity?: DefinitionComplexity;
/** Populated post-analysis by the CFG visitor. */
cfg?: { blocks: CfgBlock[]; edges: CfgEdge[] } | null;
}
/** Sub-declaration (child) within a definition. */
export interface SubDeclaration {
name: string;
kind: 'parameter' | 'property' | 'constant' | 'method';
line: number;
endLine?: number;
visibility?: 'public' | 'private' | 'protected';
decorators?: string[];
}
/** Complexity metrics attached to a definition post-analysis. */
export interface DefinitionComplexity {
cognitive: number;
cyclomatic: number;
maxNesting: number;
halstead?: HalsteadMetrics;
loc?: LOCMetrics;
maintainabilityIndex?: number;
}
/** Halstead software science metrics. */
export interface HalsteadMetrics {
volume: number;
difficulty: number;
effort: number;
bugs: number;
}
/** Halstead derived metrics including raw counts. */
export interface HalsteadDerivedMetrics extends HalsteadMetrics {
n1: number;
n2: number;
bigN1: number;
bigN2: number;
vocabulary: number;
length: number;
}
/** Lines-of-code metrics. */
export interface LOCMetrics {
loc: number;
sloc: number;
commentLines: number;
}
/** A function/method call detected by an extractor. */
export interface Call {
name: string;
line: number;
receiver?: string;
dynamic?: boolean;
}
/** An import statement detected by an extractor. */
export interface Import {
source: string;
names: string[];
line: number;
// Standard flags
typeOnly?: boolean;
reexport?: boolean;
wildcardReexport?: boolean;
dynamicImport?: boolean;
// Language-specific flags (mutually exclusive at runtime)
pythonImport?: boolean;
goImport?: boolean;
rustUse?: boolean;
javaImport?: boolean;
csharpUsing?: boolean;
rubyRequire?: boolean;
phpUse?: boolean;
cInclude?: boolean;
kotlinImport?: boolean;
swiftImport?: boolean;
scalaImport?: boolean;
bashSource?: boolean;
}
/** A class/struct/trait relationship (extends or implements). */
export interface ClassRelation {
name: string;
extends?: string;
implements?: string;
line: number;
}
/** A named export from a module. */
export interface Export {
name: string;
kind: SymbolKind;
line: number;
}
/** A type-map entry for call resolution confidence scoring. */
export interface TypeMapEntry {
type: string;
confidence: number;
}
/** The normalized output shape returned by every language extractor. */
export interface ExtractorOutput {
definitions: Definition[];
calls: Call[];
imports: Import[];
classes: ClassRelation[];
exports: Export[];
typeMap: Map<string, TypeMapEntry>;
/** WASM tree retained for downstream analysis (complexity, CFG, dataflow). */
_tree?: TreeSitterTree;
/** Language identifier. */
_langId?: LanguageId;
/** Line count for metrics. */
_lineCount?: number;
/** Dataflow results, populated post-analysis. */
dataflow?: DataflowResult;
/** AST node rows, populated post-analysis. */
astNodes?: ASTNodeRow[];
/** Set when typeMap was backfilled from WASM for a native parse result. */
_typeMapBackfilled?: boolean;
}
/** Extractor function signature. */
export type ExtractorFn = (
tree: TreeSitterTree,
filePath: string,
query?: TreeSitterQuery,
) => ExtractorOutput;
// ════════════════════════════════════════════════════════════════════════
// §5 Parser & Language Registry
// ════════════════════════════════════════════════════════════════════════
/** A single entry in the LANGUAGE_REGISTRY. */
export interface LanguageRegistryEntry {
id: LanguageId;
extensions: string[];
grammarFile: string;
extractor: ExtractorFn;
required: boolean;
}
/** tree-sitter opaque types (thin wrappers — real impl is WASM). */
export interface TreeSitterNode {
id: number;
type: string;
text: string;
startPosition: { row: number; column: number };
endPosition: { row: number; column: number };
childCount: number;
namedChildCount: number;
child(index: number): TreeSitterNode | null;
namedChild(index: number): TreeSitterNode | null;
childForFieldName(name: string): TreeSitterNode | null;
parent: TreeSitterNode | null;
previousSibling: TreeSitterNode | null;
nextSibling: TreeSitterNode | null;
children: TreeSitterNode[];
namedChildren: TreeSitterNode[];
}
export interface TreeSitterTree {
rootNode: TreeSitterNode;
}
export interface TreeSitterQuery {
matches(node: TreeSitterNode): TreeSitterQueryMatch[];
captures(node: TreeSitterNode): TreeSitterQueryCapture[];
}
export interface TreeSitterQueryMatch {
pattern: number;
captures: TreeSitterQueryCapture[];
}
export interface TreeSitterQueryCapture {
name: string;
node: TreeSitterNode;
}
// ════════════════════════════════════════════════════════════════════════
// §6 Import Resolution
// ════════════════════════════════════════════════════════════════════════
/** A single import to resolve. */
export interface ImportBatchItem {
fromFile: string;
importSource: string;
}
/** Batch of imports to resolve. */
export type ImportBatch = ImportBatchItem[];
/** Result of resolveImportsBatch: Map<"fromFile|importSource", resolvedPath>. */
export type BatchResolvedMap = Map<string, string>;
/** Path aliases from tsconfig/jsconfig. */
export interface PathAliases {
baseUrl: string | null;
paths: Record<string, string[]>;
}
/** Parsed bare specifier. */
export interface BareSpecifier {
packageName: string;
subpath: string;
}
// ════════════════════════════════════════════════════════════════════════
// §7 AST Visitor System
// ════════════════════════════════════════════════════════════════════════
/** Shared context mutated during the DFS walk. */
export interface VisitorContext {
nestingLevel: number;
currentFunction: TreeSitterNode | null;
langId: string;
scopeStack: ScopeEntry[];
}
/** An entry on the scope stack. */
export interface ScopeEntry {
funcName: string | null;
funcNode: TreeSitterNode;
params: Map<string, unknown>;
locals: Map<string, unknown>;
}
/** Return value from enterNode — request skip of descendants. */
export interface EnterNodeResult {
skipChildren?: boolean;
}
/** A pluggable analysis visitor for the unified DFS walker. */
export interface Visitor {
name: string;
init?(langId: string): void;
enterNode?(node: TreeSitterNode, context: VisitorContext): EnterNodeResult | undefined;
exitNode?(node: TreeSitterNode, context: VisitorContext): void;
enterFunction?(funcNode: TreeSitterNode, funcName: string | null, context: VisitorContext): void;
exitFunction?(funcNode: TreeSitterNode, funcName: string | null, context: VisitorContext): void;
finish?(): unknown;
functionNodeTypes?: Set<string>;
}
/** Options for walkWithVisitors. */
export interface WalkOptions {
functionNodeTypes?: Set<string>;
nestingNodeTypes?: Set<string>;
getFunctionName?: (node: TreeSitterNode) => string | null;
}
/** Result of walkWithVisitors: Map of visitor.name → finish() result. */
export type WalkResults = Record<string, unknown>;
// ════════════════════════════════════════════════════════════════════════
// §8 AST Analysis Engine
// ════════════════════════════════════════════════════════════════════════
/** Toggles for runAnalyses. */
export interface AnalysisOpts {
ast?: boolean;
complexity?: boolean;
cfg?: boolean;
dataflow?: boolean;
}
/** Timing output from runAnalyses. */
export interface AnalysisTiming {
astMs: number;
complexityMs: number;
cfgMs: number;
dataflowMs: number;
_unifiedWalkMs?: number;
}
/** An AST node row stored in the database. */
export interface ASTNodeRow {
node_id: number;
kind: ASTNodeKind;
line: number;
text: string;
}
/** AST type mapping: tree-sitter node type → analysis kind. */
export type ASTTypeMap = Map<string, ASTNodeKind>;
/** Complexity rules for a language. */
export interface ComplexityRules {
branchNodes: Set<string>;
caseNodes: Set<string>;
logicalOperators: Set<string>;
logicalNodeType: string | null;
optionalChainType: string | null;
nestingNodes: Set<string>;
functionNodes: Set<string>;
ifNodeType: string | null;
elseNodeType: string | null;
elifNodeType: string | null;
elseViaAlternative: boolean;
switchLikeNodes: Set<string>;
}
/** Halstead rules for a language. */
export interface HalsteadRules {
operatorLeafTypes: Set<string>;
operandLeafTypes: Set<string>;
compoundOperators: Set<string>;
skipTypes: Set<string>;
}
/** CFG rules for a language (merged result of CFG_DEFAULTS + overrides). */
export interface CfgRulesConfig {
ifNode: string | null;
ifNodes: Set<string> | null;
elifNode: string | null;
elseClause: string | null;
elseViaAlternative: boolean;
ifConsequentField: string | null;
forNodes: Set<string>;
whileNode: string | null;
whileNodes: Set<string> | null;
doNode: string | null;
infiniteLoopNode: string | null;
unlessNode: string | null;
untilNode: string | null;
switchNode: string | null;
switchNodes: Set<string> | null;
caseNode: string | null;
caseNodes: Set<string> | null;
defaultNode: string | null;
tryNode: string | null;
catchNode: string | null;
finallyNode: string | null;
returnNode: string | null;
throwNode: string | null;
breakNode: string | null;
continueNode: string | null;
blockNode: string | null;
blockNodes: Set<string> | null;
labeledNode: string | null;
functionNodes: Set<string>;
}
/** Dataflow rules for a language (merged result of DATAFLOW_DEFAULTS + overrides). */
export interface DataflowRulesConfig {
functionNodes: Set<string>;
nameField: string;
varAssignedFnParent: string | null;
assignmentFnParent: string | null;
pairFnParent: string | null;
paramListField: string;
paramIdentifier: string;
paramWrapperTypes: Set<string>;
defaultParamType: string | null;
restParamType: string | null;
objectDestructType: string | null;
arrayDestructType: string | null;
shorthandPropPattern: string | null;
pairPatternType: string | null;
extractParamName: ((node: TreeSitterNode) => string[] | null) | null;
returnNode: string | null;
varDeclaratorNode: string | null;
varDeclaratorNodes: Set<string> | null;
varNameField: string;
varValueField: string;
assignmentNode: string | null;
assignLeftField: string;
assignRightField: string;
callNode: string | null;
callNodes: Set<string> | null;
callFunctionField: string;
callArgsField: string;
spreadType: string | null;
memberNode: string | null;
memberObjectField: string;
memberPropertyField: string;
optionalChainNode: string | null;
awaitNode: string | null;
mutatingMethods: Set<string>;
expressionStmtNode: string;
callObjectField: string | null;
expressionListType: string | null;
equalsClauseType: string | null;
argumentWrapperType: string | null;
extraIdentifierTypes: Set<string> | null;
}
/** Language rule module: exports from each language rule file. */
export interface LanguageRuleModule {
complexity: ComplexityRules;
halstead: HalsteadRules;
cfg: CfgRulesConfig;
dataflow: DataflowRulesConfig;
astTypes: Record<string, string> | null;
}
/** A basic block in a control flow graph. */
export interface CfgBlock {
id: number;
label: string;
startLine: number;
endLine: number;
}
/** An edge in a control flow graph. */
export interface CfgEdge {
from: number;
to: number;
label?: string;
}
/** Dataflow extraction result. */
export interface DataflowResult {
parameters: DataflowParam[];
returns: DataflowReturn[];
assignments: DataflowAssignment[];
argFlows: DataflowArgFlow[];
mutations: DataflowMutation[];
}
export interface DataflowParam {
name: string;
funcName: string;
line: number;
typeHint?: string;
}
export interface DataflowReturn {
funcName: string;
line: number;
expression: string;
}
export interface DataflowAssignment {
name: string;
line: number;
expression: string;
}
export interface DataflowArgFlow {
callerFunc: string;
callee: string;
argIndex: number;
binding: { name: string; type: 'param' | 'local' | 'unknown' };
line: number;
}
export interface DataflowMutation {
binding: { name: string; type: 'param' | 'local' | 'unknown' };
mutatingExpr: string;
line: number;
}
// ════════════════════════════════════════════════════════════════════════
// §9 Graph Model (CodeGraph)
// ════════════════════════════════════════════════════════════════════════
/** Node attributes stored in the in-memory graph. */
export interface GraphNodeAttrs {
label?: string;
kind?: string;
file?: string;
name?: string;
line?: number;
dbId?: number;
[key: string]: unknown;
}
/** Edge attributes stored in the in-memory graph. */
export interface GraphEdgeAttrs {
kind?: string;
confidence?: number;
weight?: number;
[key: string]: unknown;
}
/** The unified in-memory graph model. */
export interface CodeGraph {
readonly directed: boolean;
readonly nodeCount: number;
readonly edgeCount: number;
// Node operations
addNode(id: string, attrs?: GraphNodeAttrs): CodeGraph;
hasNode(id: string): boolean;
getNodeAttrs(id: string): GraphNodeAttrs | undefined;
nodes(): IterableIterator<[string, GraphNodeAttrs]>;
nodeIds(): string[];
// Edge operations
addEdge(source: string, target: string, attrs?: GraphEdgeAttrs): CodeGraph;
hasEdge(source: string, target: string): boolean;
getEdgeAttrs(source: string, target: string): GraphEdgeAttrs | undefined;
edges(): Generator<[string, string, GraphEdgeAttrs]>;
// Adjacency
successors(id: string): string[];
predecessors(id: string): string[];
neighbors(id: string): string[];
outDegree(id: string): number;
inDegree(id: string): number;
// Filtering
subgraph(predicate: (id: string, attrs: GraphNodeAttrs) => boolean): CodeGraph;
filterEdges(predicate: (src: string, tgt: string, attrs: GraphEdgeAttrs) => boolean): CodeGraph;
// Conversion
toEdgeArray(): Array<{ source: string; target: string }>;
toGraphology(opts?: { type?: string }): unknown;
// Utilities
clone(): CodeGraph;
merge(other: CodeGraph): CodeGraph;
}
// ════════════════════════════════════════════════════════════════════════
// §10 Build Pipeline
// ════════════════════════════════════════════════════════════════════════
/** Engine options for the build pipeline. */
export interface EngineOpts {
engine: EngineMode;
dataflow: boolean;
ast: boolean;
/** Persistent NativeDatabase connection for build writes (Phase 6.15). */
nativeDb?: NativeDatabase;
/**
* Suspend the JS (better-sqlite3) connection before a native write to avoid
* dual-connection WAL corruption. Call `resumeJsDb()` after the write completes.
* Only set during pipeline builds where both connections coexist.
*/
suspendJsDb?: () => void;
resumeJsDb?: () => void;
}
/** A file change detected during incremental builds. */
export interface ParseChange {
file: string;
relPath?: string;
content?: string;
hash?: string;
stat?: { mtime: number; size: number };
_reverseDepOnly?: boolean;
}
/** Metadata-only self-heal update. */
export interface MetadataUpdate {
relPath: string;
hash: string;
stat: { mtime: number; size: number };
}
/** A file queued for parsing. */
export interface FileToParse {
file: string;
relPath?: string;
}
/** Shared mutable state threaded through all build stages. */
export interface PipelineContext {
// Inputs (set during setup)
rootDir: string;
db: unknown; // better-sqlite3.Database
dbPath: string;
config: CodegraphConfig;
opts: BuildGraphOpts;
engineOpts: EngineOpts;
engineName: 'native' | 'wasm';
engineVersion: string | null;
aliases: PathAliases;
incremental: boolean;
forceFullRebuild: boolean;
schemaVersion: number;
// File collection
allFiles: string[];
discoveredDirs: Set<string>;
// Change detection
isFullBuild: boolean;
parseChanges: ParseChange[];
metadataUpdates: MetadataUpdate[];
removed: string[];
earlyExit: boolean;
// Parsing
allSymbols: Map<string, ExtractorOutput>;
fileSymbols: Map<string, ExtractorOutput>;
filesToParse: FileToParse[];
// Import resolution
batchResolved: BatchResolvedMap | null;
reexportMap: Map<string, unknown[]>;
barrelOnlyFiles: Set<string>;
// Node lookup
nodesByName: Map<string, NodeRow[]>;
nodesByNameAndFile: Map<string, NodeRow[]>;
// Misc state
hasEmbeddings: boolean;
lineCountMap: Map<string, number>;
// Phase timing
timing: Record<string, number>;
buildStart: number;
}
/** Options for buildGraph. */
export interface BuildGraphOpts {