forked from vitali87/code-graph-rag
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtypes_defs.py
More file actions
661 lines (507 loc) · 16.8 KB
/
Copy pathtypes_defs.py
File metadata and controls
661 lines (507 loc) · 16.8 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
from __future__ import annotations
from collections import defaultdict
from collections.abc import Awaitable, Callable, ItemsView, KeysView, Sequence
from dataclasses import dataclass
from enum import StrEnum
from pathlib import Path
from typing import TYPE_CHECKING, NamedTuple, Protocol, TypedDict
from prompt_toolkit.styles import Style
from .constants import NodeLabel, RelationshipType, SupportedLanguage
if TYPE_CHECKING:
from tree_sitter import Language, Node, Parser, Query
from .models import LanguageSpec
type LanguageLoader = Callable[[], Language] | None
PropertyValue = str | int | float | bool | list[str] | None
PropertyDict = dict[str, PropertyValue]
type ResultScalar = str | int | float | bool | None
type ResultValue = ResultScalar | list[ResultScalar] | dict[str, ResultScalar]
type ResultRow = dict[str, ResultValue]
class FunctionMatch(TypedDict):
node: Node
simple_name: str
qualified_name: str
parent_class: str | None
line_number: int
class NodeBatchRow(TypedDict):
id: PropertyValue
props: PropertyDict
class RelBatchRow(TypedDict):
from_val: PropertyValue
to_val: PropertyValue
props: PropertyDict
BatchParams = NodeBatchRow | RelBatchRow | PropertyDict
class BatchWrapper(TypedDict):
batch: Sequence[BatchParams]
type SimpleName = str
type QualifiedName = str
type SimpleNameLookup = defaultdict[SimpleName, set[QualifiedName]]
NodeIdentifier = tuple[NodeLabel | str, str, str | None]
type ASTNode = Node
class NodeType(StrEnum):
FUNCTION = "Function"
METHOD = "Method"
ANONYMOUS_FUNCTION = "AnonymousFunction"
CLASS = "Class"
MODULE = "Module"
INTERFACE = "Interface"
PACKAGE = "Package"
ENUM = "Enum"
TYPE = "Type"
UNION = "Union"
type TrieNode = dict[str, TrieNode | QualifiedName | NodeType]
type FunctionRegistry = dict[QualifiedName, NodeType]
class FunctionRegistryTrieProtocol(Protocol):
def __contains__(self, qualified_name: QualifiedName) -> bool: ...
def __getitem__(self, qualified_name: QualifiedName) -> NodeType: ...
def __setitem__(
self, qualified_name: QualifiedName, func_type: NodeType
) -> None: ...
def get(
self, qualified_name: QualifiedName, default: NodeType | None = None
) -> NodeType | None: ...
def keys(self) -> KeysView[QualifiedName]: ...
def items(self) -> ItemsView[QualifiedName, NodeType]: ...
def find_with_prefix(self, prefix: str) -> list[tuple[QualifiedName, NodeType]]: ...
def find_ending_with(self, suffix: str) -> list[QualifiedName]: ...
def register_external(
self, qualified_name: QualifiedName, func_type: NodeType
) -> None: ...
class ASTCacheProtocol(Protocol):
def __setitem__(self, key: Path, value: tuple[Node, SupportedLanguage]) -> None: ...
def __getitem__(self, key: Path) -> tuple[Node, SupportedLanguage]: ...
def __delitem__(self, key: Path) -> None: ...
def __contains__(self, key: Path) -> bool: ...
def items(self) -> ItemsView[Path, tuple[Node, SupportedLanguage]]: ...
class ColumnDescriptor(Protocol):
@property
def name(self) -> str: ...
class LoadableProtocol(Protocol):
def _ensure_loaded(self) -> None: ...
class CursorProtocol(Protocol):
def execute(
self,
query: str,
params: dict[str, PropertyValue]
| Sequence[BatchParams]
| BatchWrapper
| None = None,
) -> None: ...
def close(self) -> None: ...
@property
def description(self) -> Sequence[ColumnDescriptor] | None: ...
def fetchall(self) -> list[tuple[PropertyValue, ...]]: ...
class PathValidatorProtocol(Protocol):
@property
def project_root(self) -> Path: ...
class TreeSitterNodeProtocol(Protocol):
@property
def type(self) -> str: ...
@property
def children(self) -> list[TreeSitterNodeProtocol]: ...
@property
def text(self) -> bytes: ...
class ModuleResolverProtocol(Protocol):
"""Protocol for language-specific module resolution.
Resolves import specifiers to filesystem paths, which are then converted
to qualified names (QNs) using the language's FQNSpec.file_to_module_parts().
This ensures QNs match between import resolution and function indexing.
"""
def resolve(self, import_specifier: str, from_file: Path) -> Path | None:
"""Resolve an import specifier to a filesystem path.
Args:
import_specifier: The import string from source code
(e.g., '@web-platform/shared-acorn-redux/src/selectors')
from_file: Absolute path to the file containing the import
Returns:
Absolute filesystem path of the resolved module, or None if:
- Import is external (node_modules, system package)
- Import cannot be resolved
"""
...
def is_external(self, import_specifier: str) -> bool:
"""Check if an import refers to an external dependency.
Args:
import_specifier: The import string from source code
Returns:
True if this is an external package (npm, PyPI, crates.io, etc.)
False if internal to the repository
"""
...
def initialize(self) -> None:
"""Initialize the resolver with repository configuration.
One-time setup that reads configuration files:
- TypeScript: tsconfig.json, package.json, pnpm-workspace.yaml
- Python: pyproject.toml, setup.py, __init__.py
- Rust: Cargo.toml, Cargo.lock
Note:
Called once after __init__().
Uses repo_path from __init__() to locate configuration files.
Should cache parsed configuration for fast resolution.
"""
...
def cleanup(self) -> None:
"""Cleanup resources held by the resolver.
Called when the resolver is no longer needed. For example:
- Terminate long-running subprocesses (e.g., Node.js)
- Close file handles or database connections
- Clear large caches if memory is constrained
Note:
Should be idempotent and safe to call multiple times.
"""
...
class TypeResolverProtocol(Protocol):
def resolve_function_types(
self, file_path: Path
) -> dict[str, dict[str, dict[str, str]]]: ...
def initialize(self) -> None: ...
def cleanup(self) -> None: ...
@property
def is_available(self) -> bool: ...
class ModelConfigKwargs(TypedDict, total=False):
api_key: str | None
endpoint: str | None
project_id: str | None
region: str | None
provider_type: str | None
thinking_budget: int | None
service_account_file: str | None
custom_headers: dict[str, str] | None
class GraphMetadata(TypedDict):
total_nodes: int
total_relationships: int
exported_at: str
class NodeData(TypedDict):
node_id: int
labels: list[str]
properties: dict[str, PropertyValue]
class RelationshipData(TypedDict):
from_id: int
to_id: int
type: str
properties: dict[str, PropertyValue]
class GraphData(TypedDict):
nodes: list[NodeData] | list[ResultRow]
relationships: list[RelationshipData] | list[ResultRow]
metadata: GraphMetadata
class GraphSummary(TypedDict):
total_nodes: int
total_relationships: int
node_labels: dict[str, int]
relationship_types: dict[str, int]
metadata: GraphMetadata
class EmbeddingQueryResult(TypedDict):
node_id: int
qualified_name: str
start_line: int | None
end_line: int | None
path: str | None
class SemanticSearchResult(TypedDict):
node_id: int
qualified_name: str
name: str
type: str
score: float
class JavaClassInfo(TypedDict):
name: str | None
type: str
superclass: str | None
interfaces: list[str]
modifiers: list[str]
type_parameters: list[str]
class JavaMethodInfo(TypedDict):
name: str | None
type: str
return_type: str | None
parameters: list[str]
modifiers: list[str]
type_parameters: list[str]
annotations: list[str]
class JavaFieldInfo(TypedDict):
name: str | None
type: str | None
modifiers: list[str]
annotations: list[str]
class JavaAnnotationInfo(TypedDict):
name: str | None
arguments: list[str]
class JavaMethodCallInfo(TypedDict):
name: str | None
object: str | None
arguments: int
class CancelledResult(NamedTuple):
cancelled: bool
class CgrignorePatterns(NamedTuple):
exclude: frozenset[str]
unignore: frozenset[str]
class AgentLoopUI(NamedTuple):
status_message: str
cancelled_log: str
approval_prompt: str
denial_default: str
panel_title: str
ORANGE_STYLE = Style.from_dict({"": "#ff8c00"})
OPTIMIZATION_LOOP_UI = AgentLoopUI(
status_message="[bold green]Agent is analyzing codebase... (Press Ctrl+C to cancel)[/bold green]",
cancelled_log="ASSISTANT: [Analysis was cancelled]",
approval_prompt="Do you approve this optimization?",
denial_default="User rejected this optimization without feedback",
panel_title="[bold green]Optimization Agent[/bold green]",
)
CHAT_LOOP_UI = AgentLoopUI(
status_message="[bold green]Thinking... (Press Ctrl+C to cancel)[/bold green]",
cancelled_log="ASSISTANT: [Thinking was cancelled]",
approval_prompt="Do you approve this change?",
denial_default="User rejected this change without feedback",
panel_title="[bold green]Assistant[/bold green]",
)
class LanguageImport(NamedTuple):
lang_key: SupportedLanguage
module_path: str
attr_name: str
submodule_name: SupportedLanguage
class ToolNames(NamedTuple):
query_graph: str
read_file: str
analyze_document: str
semantic_search: str
create_file: str
edit_file: str
shell_command: str
class ConfirmationToolNames(NamedTuple):
replace_code: str
create_file: str
shell_command: str
class ReplaceCodeArgs(TypedDict, total=False):
file_path: str
target_code: str
replacement_code: str
class CreateFileArgs(TypedDict, total=False):
file_path: str
content: str
class ShellCommandArgs(TypedDict, total=False):
command: str
@dataclass
class RawToolArgs:
file_path: str = ""
target_code: str = ""
replacement_code: str = ""
content: str = ""
command: str = ""
ToolArgs = ReplaceCodeArgs | CreateFileArgs | ShellCommandArgs
class LanguageQueries(TypedDict):
functions: Query | None
classes: Query | None
calls: Query | None
imports: Query | None
locals: Query | None
config: LanguageSpec
language: Language
parser: Parser
class FunctionNodeProps(TypedDict, total=False):
qualified_name: str
name: str | None
start_line: int
end_line: int
docstring: str | None
MCPToolArguments = dict[str, str | int | None]
class MCPInputSchemaProperty(TypedDict, total=False):
type: str
description: str
default: str
MCPInputSchemaProperties = dict[str, MCPInputSchemaProperty]
class MCPInputSchema(TypedDict):
type: str
properties: MCPInputSchemaProperties
required: list[str]
class MCPToolSchema(NamedTuple):
name: str
description: str
inputSchema: MCPInputSchema
class QueryResultDict(TypedDict, total=False):
query_used: str
results: list[ResultRow]
summary: str
error: str
class CodeSnippetResultDict(TypedDict, total=False):
qualified_name: str
source_code: str
file_path: str
line_start: int
line_end: int
docstring: str | None
found: bool
error_message: str | None
error: str
class ListProjectsSuccessResult(TypedDict):
projects: list[str]
count: int
class ListProjectsErrorResult(TypedDict):
projects: list[str]
count: int
error: str
ListProjectsResult = ListProjectsSuccessResult | ListProjectsErrorResult
class DeleteProjectSuccessResult(TypedDict):
success: bool
project: str
message: str
class DeleteProjectErrorResult(TypedDict):
success: bool
error: str
DeleteProjectResult = DeleteProjectSuccessResult | DeleteProjectErrorResult
MCPResultType = (
str
| QueryResultDict
| CodeSnippetResultDict
| ListProjectsResult
| DeleteProjectResult
)
MCPHandlerType = Callable[..., Awaitable[MCPResultType]]
class NodeSchema(NamedTuple):
label: NodeLabel
properties: str
class RelationshipSchema(NamedTuple):
sources: tuple[NodeLabel, ...]
rel_type: RelationshipType
targets: tuple[NodeLabel, ...]
NODE_SCHEMAS: tuple[NodeSchema, ...] = (
NodeSchema(NodeLabel.PROJECT, "{name: string}"),
NodeSchema(
NodeLabel.PACKAGE, "{qualified_name: string, name: string, path: string}"
),
NodeSchema(NodeLabel.FOLDER, "{path: string, name: string}"),
NodeSchema(NodeLabel.FILE, "{path: string, name: string, extension: string}"),
NodeSchema(
NodeLabel.MODULE, "{qualified_name: string, name: string, path: string}"
),
NodeSchema(
NodeLabel.CLASS,
"{qualified_name: string, name: string, decorators: list[string]}",
),
NodeSchema(
NodeLabel.FUNCTION,
"{qualified_name: string, name: string, decorators: list[string]}",
),
NodeSchema(
NodeLabel.METHOD,
"{qualified_name: string, name: string, decorators: list[string]}",
),
NodeSchema(
NodeLabel.ANONYMOUS_FUNCTION,
"{qualified_name: string, name: string, start_line: integer, end_line: integer}",
),
NodeSchema(NodeLabel.INTERFACE, "{qualified_name: string, name: string}"),
NodeSchema(NodeLabel.ENUM, "{qualified_name: string, name: string}"),
NodeSchema(NodeLabel.TYPE, "{qualified_name: string, name: string}"),
NodeSchema(NodeLabel.UNION, "{qualified_name: string, name: string}"),
NodeSchema(
NodeLabel.MODULE_INTERFACE,
"{qualified_name: string, name: string, path: string}",
),
NodeSchema(
NodeLabel.MODULE_IMPLEMENTATION,
"{qualified_name: string, name: string, path: string, implements_module: string}",
),
NodeSchema(NodeLabel.EXTERNAL_PACKAGE, "{name: string, version_spec: string}"),
)
RELATIONSHIP_SCHEMAS: tuple[RelationshipSchema, ...] = (
RelationshipSchema(
(NodeLabel.PROJECT, NodeLabel.PACKAGE, NodeLabel.FOLDER),
RelationshipType.CONTAINS_PACKAGE,
(NodeLabel.PACKAGE,),
),
RelationshipSchema(
(NodeLabel.PROJECT, NodeLabel.PACKAGE, NodeLabel.FOLDER),
RelationshipType.CONTAINS_FOLDER,
(NodeLabel.FOLDER,),
),
RelationshipSchema(
(NodeLabel.PROJECT, NodeLabel.PACKAGE, NodeLabel.FOLDER),
RelationshipType.CONTAINS_FILE,
(NodeLabel.FILE,),
),
RelationshipSchema(
(NodeLabel.PROJECT, NodeLabel.PACKAGE, NodeLabel.FOLDER),
RelationshipType.CONTAINS_MODULE,
(NodeLabel.MODULE,),
),
RelationshipSchema(
(NodeLabel.MODULE,),
RelationshipType.DEFINES,
(NodeLabel.CLASS, NodeLabel.FUNCTION, NodeLabel.ANONYMOUS_FUNCTION),
),
RelationshipSchema(
(NodeLabel.CLASS,),
RelationshipType.DEFINES_METHOD,
(NodeLabel.METHOD,),
),
RelationshipSchema(
(NodeLabel.FUNCTION, NodeLabel.METHOD),
RelationshipType.DEFINES,
(NodeLabel.ANONYMOUS_FUNCTION,),
),
RelationshipSchema(
(NodeLabel.MODULE,),
RelationshipType.IMPORTS,
(NodeLabel.MODULE,),
),
RelationshipSchema(
(NodeLabel.MODULE,),
RelationshipType.EXPORTS,
(NodeLabel.CLASS, NodeLabel.FUNCTION),
),
RelationshipSchema(
(NodeLabel.MODULE,),
RelationshipType.EXPORTS_MODULE,
(NodeLabel.MODULE_INTERFACE,),
),
RelationshipSchema(
(NodeLabel.MODULE,),
RelationshipType.IMPLEMENTS_MODULE,
(NodeLabel.MODULE_IMPLEMENTATION,),
),
RelationshipSchema(
(NodeLabel.CLASS,),
RelationshipType.INHERITS,
(NodeLabel.CLASS,),
),
RelationshipSchema(
(NodeLabel.CLASS,),
RelationshipType.IMPLEMENTS,
(NodeLabel.INTERFACE,),
),
RelationshipSchema(
(NodeLabel.METHOD,),
RelationshipType.OVERRIDES,
(NodeLabel.METHOD,),
),
RelationshipSchema(
(NodeLabel.MODULE_IMPLEMENTATION,),
RelationshipType.IMPLEMENTS,
(NodeLabel.MODULE_INTERFACE,),
),
RelationshipSchema(
(NodeLabel.PROJECT,),
RelationshipType.DEPENDS_ON_EXTERNAL,
(NodeLabel.EXTERNAL_PACKAGE,),
),
RelationshipSchema(
(NodeLabel.FUNCTION, NodeLabel.METHOD, NodeLabel.MODULE),
RelationshipType.CALLS,
(NodeLabel.FUNCTION, NodeLabel.METHOD),
),
RelationshipSchema(
(NodeLabel.MODULE,),
RelationshipType.DEFINES,
(NodeLabel.ANONYMOUS_FUNCTION,),
),
RelationshipSchema(
(NodeLabel.FUNCTION, NodeLabel.METHOD),
RelationshipType.DEFINES,
(NodeLabel.ANONYMOUS_FUNCTION,),
),
RelationshipSchema(
(NodeLabel.ANONYMOUS_FUNCTION,),
RelationshipType.CALLS,
(NodeLabel.FUNCTION, NodeLabel.METHOD),
),
)