forked from colbymchenry/codegraph
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.ts
More file actions
841 lines (676 loc) · 17.6 KB
/
types.ts
File metadata and controls
841 lines (676 loc) · 17.6 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
/**
* CodeGraph Type Definitions
*
* Core types for the semantic knowledge graph system.
*/
// =============================================================================
// Union Types
// =============================================================================
/**
* Types of nodes in the knowledge graph.
*
* Defined as a runtime-iterable `as const` array so the same source
* of truth backs both the TS type and any runtime validation
* (e.g. the search query parser).
*/
export const NODE_KINDS = [
'file',
'module',
'class',
'struct',
'interface',
'trait',
'protocol',
'function',
'method',
'property',
'field',
'variable',
'constant',
'enum',
'enum_member',
'type_alias',
'namespace',
'parameter',
'import',
'export',
'route',
'component',
] as const;
export type NodeKind = (typeof NODE_KINDS)[number];
/**
* Types of edges (relationships) between nodes
*/
export type EdgeKind =
| 'contains' // Parent contains child (file→class, class→method)
| 'calls' // Function/method calls another
| 'imports' // File imports from another
| 'exports' // File exports a symbol
| 'extends' // Class/interface extends another
| 'implements' // Class implements interface
| 'references' // Generic reference to another symbol
| 'type_of' // Variable/parameter has type
| 'returns' // Function returns type
| 'instantiates' // Creates instance of class
| 'overrides' // Method overrides parent method
| 'decorates'; // Decorator applied to symbol
/**
* Supported programming languages. See NODE_KINDS for why this is a
* runtime-iterable const array.
*/
export const LANGUAGES = [
'typescript',
'javascript',
'tsx',
'jsx',
'python',
'go',
'rust',
'java',
'c',
'cpp',
'csharp',
'php',
'ruby',
'swift',
'kotlin',
'dart',
'svelte',
'vue',
'liquid',
'pascal',
'scala',
'unknown',
] as const;
export type Language = (typeof LANGUAGES)[number];
// =============================================================================
// Core Graph Types
// =============================================================================
/**
* A node in the knowledge graph representing a code symbol
*/
export interface Node {
/** Unique identifier (hash of file path + qualified name) */
id: string;
/** Type of code element */
kind: NodeKind;
/** Simple name (e.g., "calculateTotal") */
name: string;
/** Fully qualified name (e.g., "src/utils.ts::MathHelper.calculateTotal") */
qualifiedName: string;
/** File path relative to project root */
filePath: string;
/** Programming language */
language: Language;
/** Starting line number (1-indexed) */
startLine: number;
/** Ending line number (1-indexed) */
endLine: number;
/** Starting column (0-indexed) */
startColumn: number;
/** Ending column (0-indexed) */
endColumn: number;
/** Documentation string if present */
docstring?: string;
/** Function/method signature */
signature?: string;
/** Visibility modifier */
visibility?: 'public' | 'private' | 'protected' | 'internal';
/** Whether symbol is exported */
isExported?: boolean;
/** Whether symbol is async */
isAsync?: boolean;
/** Whether symbol is static */
isStatic?: boolean;
/** Whether symbol is abstract */
isAbstract?: boolean;
/** Decorators/annotations applied */
decorators?: string[];
/** Generic type parameters */
typeParameters?: string[];
/** When the node was last updated */
updatedAt: number;
}
/**
* An edge representing a relationship between two nodes
*/
export interface Edge {
/** Source node ID */
source: string;
/** Target node ID */
target: string;
/** Type of relationship */
kind: EdgeKind;
/** Additional context about the relationship */
metadata?: Record<string, unknown>;
/** Line number where relationship occurs (e.g., call site) */
line?: number;
/** Column number where relationship occurs */
column?: number;
/** How this edge was created */
provenance?: 'tree-sitter' | 'scip' | 'heuristic';
}
/**
* Metadata about a tracked file
*/
export interface FileRecord {
/** File path relative to project root */
path: string;
/** Content hash for change detection */
contentHash: string;
/** Detected language */
language: Language;
/** File size in bytes */
size: number;
/** Last modification timestamp */
modifiedAt: number;
/** When last indexed */
indexedAt: number;
/** Number of nodes extracted */
nodeCount: number;
/** Any extraction errors */
errors?: ExtractionError[];
}
// =============================================================================
// Extraction Types
// =============================================================================
/**
* Result from parsing a source file
*/
export interface ExtractionResult {
/** Extracted nodes */
nodes: Node[];
/** Extracted edges */
edges: Edge[];
/** References that couldn't be resolved yet */
unresolvedReferences: UnresolvedReference[];
/** Any errors during extraction */
errors: ExtractionError[];
/** Extraction duration in milliseconds */
durationMs: number;
}
/**
* Error during code extraction
*/
export interface ExtractionError {
/** Error message */
message: string;
/** File path where the error occurred */
filePath?: string;
/** Line number if available */
line?: number;
/** Column number if available */
column?: number;
/** Error severity */
severity: 'error' | 'warning';
/** Error code for categorization */
code?: string;
}
/**
* A reference that couldn't be resolved during extraction
*/
export interface UnresolvedReference {
/** ID of the node containing the reference */
fromNodeId: string;
/** Name being referenced */
referenceName: string;
/** Type of reference (call, type, import, etc.) */
referenceKind: EdgeKind;
/** Location of the reference */
line: number;
column: number;
/** File path where reference occurs (denormalized for performance) */
filePath?: string;
/** Language of the source file (denormalized for performance) */
language?: Language;
/** Possible qualified names it might resolve to */
candidates?: string[];
}
// =============================================================================
// Query Types
// =============================================================================
/**
* A subgraph containing a subset of the knowledge graph
*/
export interface Subgraph {
/** Nodes in this subgraph */
nodes: Map<string, Node>;
/** Edges in this subgraph */
edges: Edge[];
/** Root node IDs (entry points) */
roots: string[];
}
/**
* Options for graph traversal
*/
export interface TraversalOptions {
/** Maximum depth to traverse (default: Infinity) */
maxDepth?: number;
/** Edge types to follow (default: all) */
edgeKinds?: EdgeKind[];
/** Node types to include (default: all) */
nodeKinds?: NodeKind[];
/** Direction of traversal */
direction?: 'outgoing' | 'incoming' | 'both';
/** Maximum nodes to return */
limit?: number;
/** Whether to include the starting node */
includeStart?: boolean;
}
/**
* Options for searching the graph
*/
export interface SearchOptions {
/** Node types to search */
kinds?: NodeKind[];
/** Languages to include */
languages?: Language[];
/** File path patterns to include */
includePatterns?: string[];
/** File path patterns to exclude */
excludePatterns?: string[];
/** Maximum results to return */
limit?: number;
/** Offset for pagination */
offset?: number;
/** Whether search is case-sensitive */
caseSensitive?: boolean;
}
/**
* A search result with relevance scoring
*/
export interface SearchResult {
/** Matching node */
node: Node;
/** Relevance score (0-1) */
score: number;
/** Matched text snippets for highlighting */
highlights?: string[];
}
// =============================================================================
// Context Types
// =============================================================================
/**
* Context information for code understanding
*/
export interface Context {
/** Primary node being examined */
focal: Node;
/** Nodes containing the focal node (file, class, etc.) */
ancestors: Node[];
/** Nodes directly contained by focal node */
children: Node[];
/** Incoming references (who calls/uses this) */
incomingRefs: Array<{ node: Node; edge: Edge }>;
/** Outgoing references (what this calls/uses) */
outgoingRefs: Array<{ node: Node; edge: Edge }>;
/** Related type information */
types: Node[];
/** Relevant imports */
imports: Node[];
}
/**
* A block of code with context
*/
export interface CodeBlock {
/** The code content */
content: string;
/** File path */
filePath: string;
/** Starting line */
startLine: number;
/** Ending line */
endLine: number;
/** Language for syntax highlighting */
language: Language;
/** Associated node if extracted */
node?: Node;
}
// =============================================================================
// Configuration Types
// =============================================================================
/**
* Framework-specific hints for better extraction
*/
export interface FrameworkHint {
/** Framework name (react, express, django, etc.) */
name: string;
/** Version constraint if relevant */
version?: string;
/** Custom patterns for this framework */
patterns?: {
/** Component detection patterns */
components?: string[];
/** Route detection patterns */
routes?: string[];
/** Model detection patterns */
models?: string[];
};
}
/**
* Configuration for a CodeGraph project
*/
export interface CodeGraphConfig {
/** Schema version for migrations */
version: number;
/** Root directory of the project */
rootDir: string;
/** Glob patterns for files to include */
include: string[];
/** Glob patterns for files to exclude */
exclude: string[];
/** Languages to process (auto-detected if empty) */
languages: Language[];
/** Framework hints for better extraction */
frameworks: FrameworkHint[];
/** Maximum file size to process (in bytes) */
maxFileSize: number;
/** Whether to extract docstrings */
extractDocstrings: boolean;
/** Whether to track call sites */
trackCallSites: boolean;
/** Custom symbol patterns to extract */
customPatterns?: {
/** Name for this pattern group */
name: string;
/** Regex pattern to match */
pattern: string;
/** Node kind to assign */
kind: NodeKind;
}[];
}
/**
* Default configuration values
*/
export const DEFAULT_CONFIG: CodeGraphConfig = {
version: 1,
rootDir: '.',
include: [
// TypeScript/JavaScript
'**/*.ts',
'**/*.tsx',
'**/*.js',
'**/*.jsx',
// Python
'**/*.py',
// Go
'**/*.go',
// Rust
'**/*.rs',
// Java
'**/*.java',
// C/C++
'**/*.c',
'**/*.h',
'**/*.cpp',
'**/*.hpp',
'**/*.cc',
'**/*.cxx',
// C#
'**/*.cs',
// PHP
'**/*.php',
// Ruby
'**/*.rb',
// Swift
'**/*.swift',
// Kotlin
'**/*.kt',
'**/*.kts',
// Dart
'**/*.dart',
// Svelte
'**/*.svelte',
// Vue
'**/*.vue',
// Liquid (Shopify themes)
'**/*.liquid',
// Pascal / Delphi
'**/*.pas',
'**/*.dpr',
'**/*.dpk',
'**/*.lpr',
'**/*.dfm',
'**/*.fmx',
// Scala
'**/*.scala',
'**/*.sc',
],
exclude: [
// Version control
'**/.git/**',
// Dependencies
'**/node_modules/**',
'**/vendor/**',
'**/Pods/**',
// Generic build outputs
'**/dist/**',
'**/build/**',
'**/out/**',
'**/bin/**',
'**/obj/**',
'**/target/**',
// JavaScript/TypeScript
'**/*.min.js',
'**/*.bundle.js',
'**/.next/**',
'**/.nuxt/**',
'**/.svelte-kit/**',
'**/.output/**',
'**/.turbo/**',
'**/.cache/**',
'**/.parcel-cache/**',
'**/.vite/**',
'**/.astro/**',
'**/.docusaurus/**',
'**/.gatsby/**',
'**/.webpack/**',
'**/.nx/**',
'**/.yarn/cache/**',
'**/.pnpm-store/**',
'**/storybook-static/**',
// React Native / Expo
'**/.expo/**',
'**/web-build/**',
'**/ios/Pods/**',
'**/ios/build/**',
'**/android/build/**',
'**/android/.gradle/**',
// Python
'**/__pycache__/**',
'**/.venv/**',
'**/venv/**',
'**/site-packages/**',
'**/dist-packages/**',
'**/.pytest_cache/**',
'**/.mypy_cache/**',
'**/.ruff_cache/**',
'**/.tox/**',
'**/.nox/**',
'**/*.egg-info/**',
'**/.eggs/**',
// Go
'**/go/pkg/mod/**',
// Rust
'**/target/debug/**',
'**/target/release/**',
// Java/Kotlin/Gradle
'**/.gradle/**',
'**/.m2/**',
'**/generated-sources/**',
'**/.kotlin/**',
// Dart/Flutter
'**/.dart_tool/**',
// C#/.NET
'**/.vs/**',
'**/.nuget/**',
'**/artifacts/**',
'**/publish/**',
// C/C++
'**/cmake-build-*/**',
'**/CMakeFiles/**',
'**/bazel-*/**',
'**/vcpkg_installed/**',
'**/.conan/**',
'**/Debug/**',
'**/Release/**',
'**/x64/**',
'**/.pio/**', // Platform.io (IoT/embedded build artifacts and library deps)
// Electron
'**/release/**',
'**/*.app/**',
'**/*.asar',
// Swift/iOS/Xcode
'**/DerivedData/**',
'**/.build/**',
'**/.swiftpm/**',
'**/xcuserdata/**',
'**/Carthage/Build/**',
'**/SourcePackages/**',
// Delphi/Pascal
'**/__history/**',
'**/__recovery/**',
'**/*.dcu',
// PHP
'**/.composer/**',
'**/storage/framework/**',
'**/bootstrap/cache/**',
// Ruby
'**/.bundle/**',
'**/tmp/cache/**',
'**/public/assets/**',
'**/public/packs/**',
'**/.yardoc/**',
// Testing/Coverage
'**/coverage/**',
'**/htmlcov/**',
'**/.nyc_output/**',
'**/test-results/**',
'**/.coverage/**',
// IDE/Editor
'**/.idea/**',
// Logs and temp
'**/logs/**',
'**/tmp/**',
'**/temp/**',
// Documentation build output
'**/_build/**',
'**/docs/_build/**',
'**/site/**',
],
languages: [],
frameworks: [],
maxFileSize: 1024 * 1024, // 1MB
extractDocstrings: true,
trackCallSites: true,
};
// =============================================================================
// Database Types
// =============================================================================
/**
* Database schema version info
*/
export interface SchemaVersion {
/** Current schema version */
version: number;
/** When schema was created/updated */
appliedAt: number;
/** Description of this version */
description?: string;
}
/**
* Statistics about the knowledge graph
*/
export interface GraphStats {
/** Total number of nodes */
nodeCount: number;
/** Total number of edges */
edgeCount: number;
/** Number of tracked files */
fileCount: number;
/** Node counts by kind */
nodesByKind: Record<NodeKind, number>;
/** Edge counts by kind */
edgesByKind: Record<EdgeKind, number>;
/** File counts by language */
filesByLanguage: Record<Language, number>;
/** Database size in bytes */
dbSizeBytes: number;
/** Last update timestamp */
lastUpdated: number;
}
// =============================================================================
// Task Context Types (for buildContext)
// =============================================================================
/**
* Input for building task context
*/
export type TaskInput = string | { title: string; description?: string };
/**
* Options for building task context
*/
export interface BuildContextOptions {
/** Maximum number of nodes to include (default: 50) */
maxNodes?: number;
/** Maximum number of code blocks to include (default: 10) */
maxCodeBlocks?: number;
/** Maximum characters per code block (default: 2000) */
maxCodeBlockSize?: number;
/** Whether to include code blocks (default: true) */
includeCode?: boolean;
/** Output format (default: 'markdown') */
format?: 'markdown' | 'json';
/** Number of semantic search results (default: 5) */
searchLimit?: number;
/** Graph traversal depth from entry points (default: 2) */
traversalDepth?: number;
/** Minimum semantic similarity score (default: 0.3) */
minScore?: number;
}
/**
* Full context for a task, ready for Claude
*/
export interface TaskContext {
/** The original query/task */
query: string;
/** Subgraph of relevant nodes and edges */
subgraph: Subgraph;
/** Entry point nodes (from semantic search) */
entryPoints: Node[];
/** Code blocks extracted from key nodes */
codeBlocks: CodeBlock[];
/** Files involved in this context */
relatedFiles: string[];
/** Brief summary of the context */
summary: string;
/** Statistics about the context */
stats: {
/** Number of nodes included */
nodeCount: number;
/** Number of edges included */
edgeCount: number;
/** Number of files touched */
fileCount: number;
/** Number of code blocks included */
codeBlockCount: number;
/** Total characters in code blocks */
totalCodeSize: number;
};
}
/**
* Options for finding relevant context
*/
export interface FindRelevantContextOptions {
/** Number of semantic search results (default: 5) */
searchLimit?: number;
/** Graph traversal depth (default: 2) */
traversalDepth?: number;
/** Maximum nodes in result (default: 50) */
maxNodes?: number;
/** Minimum semantic similarity score (default: 0.3) */
minScore?: number;
/** Edge types to follow in traversal */
edgeKinds?: EdgeKind[];
/** Node types to include */
nodeKinds?: NodeKind[];
}