Repository navigation
Expand file tree
/
Copy pathcode_retrieval.py
More file actions
186 lines (166 loc) · 7.13 KB
/
Copy pathcode_retrieval.py
File metadata and controls
186 lines (166 loc) · 7.13 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
from __future__ import annotations
import asyncio
from pathlib import Path
from loguru import logger
from pydantic_ai import Tool
from .. import logs as ls
from .. import tool_errors as te
from ..constants import ENCODING_UTF8
from ..cypher_queries import CYPHER_FIND_BY_QUALIFIED_NAME, CYPHER_LIST_PROJECTS
from ..schemas import CodeSnippet
from ..services import QueryProtocol
from ..taint import ReadContentRecord
from ..utils.path_utils import (
absolute_path_within_project_root,
project_root_for_qualified_name,
project_roots_from_rows,
)
from . import tool_descriptions as td
class CodeRetriever:
__slots__ = ("project_root", "ingestor", "_project_roots")
def __init__(self, project_root: str, ingestor: QueryProtocol):
self.project_root = Path(project_root).resolve()
self.ingestor = ingestor
# ponytail: session-lifetime cache; a project indexed after the first
# lookup is treated as unknown (permissive) until a new retriever.
self._project_roots: dict[str, str | None] | None = None
logger.info(ls.CODE_RETRIEVER_INIT.format(root=self.project_root))
async def _get_project_roots(self) -> dict[str, str | None]:
"""Return the indexed projects' roots, caching after the first query."""
if self._project_roots is None:
self._project_roots = project_roots_from_rows(
await asyncio.to_thread(self.ingestor.fetch_all, CYPHER_LIST_PROJECTS)
)
return self._project_roots
async def find_code_snippet(self, qualified_name: str) -> CodeSnippet:
"""Look up a qualified name in the graph and read back its source."""
logger.info(ls.CODE_RETRIEVER_SEARCH.format(name=qualified_name))
params = {"qn": qualified_name}
try:
results = await asyncio.to_thread(
self.ingestor.fetch_all, CYPHER_FIND_BY_QUALIFIED_NAME, params
)
if not results:
return CodeSnippet(
qualified_name=qualified_name,
source_code="",
file_path="",
line_start=0,
line_end=0,
found=False,
error_message=te.CODE_ENTITY_NOT_FOUND,
)
res = results[0]
file_path_str = res.get("path")
start_line = res.get("start")
end_line = res.get("end")
if not isinstance(file_path_str, str):
file_path_str = ""
if (
not file_path_str.strip()
or type(start_line) is not int
or type(end_line) is not int
or start_line < 1
or end_line < start_line
):
return CodeSnippet(
qualified_name=qualified_name,
source_code="",
file_path=file_path_str,
line_start=0,
line_end=0,
found=False,
error_message=te.CODE_MISSING_LOCATION,
)
# The recorded absolute_path is authoritative: a same-named file
# in the active repo must not shadow a cross-project node. The
# relative join covers stale node paths and old graphs without
# the property (issue #425), but must stay inside the node's
# known project root too: a missing foreign source is not local.
project_roots = await self._get_project_roots()
absolute_path_str = res.get("absolute_path")
if absolute_path_str and not absolute_path_within_project_root(
qualified_name, absolute_path_str, project_roots
):
absolute_path_str = None
if absolute_path_str and Path(absolute_path_str).is_file():
full_path = Path(absolute_path_str)
else:
fallback_root = (
project_root_for_qualified_name(qualified_name, project_roots)
or self.project_root
)
full_path = (fallback_root / file_path_str).resolve()
if not full_path.is_relative_to(fallback_root):
return CodeSnippet(
qualified_name=qualified_name,
source_code="",
file_path=file_path_str,
line_start=0,
line_end=0,
found=False,
error_message=te.CODE_MISSING_LOCATION,
)
if not full_path.is_file():
return CodeSnippet(
qualified_name=qualified_name,
source_code="",
file_path=file_path_str,
line_start=0,
line_end=0,
found=False,
error_message=te.CODE_SOURCE_FILE_MISSING.format(
path=file_path_str
),
)
with full_path.open("r", encoding=ENCODING_UTF8) as f:
all_lines = f.readlines()
if end_line > len(all_lines):
return CodeSnippet(
qualified_name=qualified_name,
source_code="",
file_path=file_path_str,
line_start=0,
line_end=0,
found=False,
error_message=te.CODE_MISSING_LOCATION,
)
snippet_lines = all_lines[start_line - 1 : end_line]
source_code = "".join(snippet_lines)
return CodeSnippet(
qualified_name=qualified_name,
source_code=source_code,
file_path=file_path_str,
line_start=start_line,
line_end=end_line,
docstring=res.get("docstring"),
)
except Exception as e:
logger.exception(ls.CODE_RETRIEVER_ERROR.format(error=e))
return CodeSnippet(
qualified_name=qualified_name,
source_code="",
file_path="",
line_start=0,
line_end=0,
found=False,
error_message=str(e),
)
def create_code_retrieval_tool(
code_retriever: CodeRetriever, read_record: ReadContentRecord | None = None
) -> Tool:
"""Build the `get_code_snippet` tool, recording returned source in
`read_record` so it feeds the egress taint gate (issue #1128)."""
async def get_code_snippet(qualified_name: str) -> CodeSnippet:
"""Fetch the source for a qualified name, recording what it returns."""
logger.info(ls.CODE_TOOL_RETRIEVE.format(name=qualified_name))
snippet = await code_retriever.find_code_snippet(qualified_name)
if read_record is not None and snippet.found:
# Feed the egress taint gate (issue #1128).
read_record.record(snippet.source_code)
return snippet
return Tool(
function=get_code_snippet,
name=td.AgenticToolName.GET_CODE_SNIPPET,
description=td.CODE_RETRIEVAL,
)