-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathphase2_context_provider.py
More file actions
396 lines (159 loc) · 8.72 KB
/
Copy pathphase2_context_provider.py
File metadata and controls
396 lines (159 loc) · 8.72 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
"""
phase2_context_provider.py
===========================
Provides rich architectural context for a given Java file using
Phase 2's graph + document builder components — NO LLM required.
This is purely deterministic: it reads Phase 1 JSON output and builds
structured module documents the same way Phase 2's RAG engine does.
Used by Phase 3 Case 2b to inject semantic context into translation prompts.
What it provides per file:
- The module's own architectural summary (role, entry point, cycles, procedures, fields)
- All direct + transitive (depth-2) dependency summaries
- Project-level overview (language distribution, entry points, cycles)
This closes the key gap: the LLM currently only sees raw Java + Python stubs,
but has NO idea of architectural patterns, cycles, or what the project IS.
"""
from pathlib import Path
from typing import Optional
from phase2.loaders.ir_loader import IRLoader
from phase2.loaders.dependency_loader import DependencyLoader
from phase2.loaders.metadata_loader import MetadataLoader
from phase2.graph.graph_index import GraphIndex
from phase2.builders.module_document_builder import ModuleDocumentBuilder
from phase2.builders.system_document_builder import SystemDocumentBuilder
class Phase2ContextProvider:
"""
Lightweight Phase 2 integration for Phase 3 Case 2b.
Initialise once per run, then call get_context_for_file() per Java file.
No vector index. No LLM. Pure graph traversal + document building.
"""
# How many chars to budget for semantic context in the prompt.
# ModuleDocumentBuilder produces ~600–900 chars per module.
# 3000 chars covers ~4 modules comfortably within the LLM's context window.
MAX_CONTEXT_CHARS = 3_000
def __init__(self, phase1_output_dir: str | Path):
phase1_dir = Path(phase1_output_dir)
ir_path = phase1_dir / "ir_registry.json"
dep_path = phase1_dir / "dependency_graph.json"
meta_path = phase1_dir / "project_metadata.json"
for p in (ir_path, dep_path, meta_path):
if not p.exists():
raise FileNotFoundError(
f"Phase 1 output not found: {p}\n"
f"Run Phase 1 first: python run_phase1.py --repo <path>"
)
self._ir = IRLoader(str(ir_path))
self._deps = DependencyLoader(str(dep_path))
self._meta = MetadataLoader(str(meta_path))
self.graph = GraphIndex(self._ir, self._deps, self._meta)
self._mod_builder = ModuleDocumentBuilder(self.graph)
self._sys_builder = SystemDocumentBuilder(self.graph)
# Build file_path → module_id index (Phase 1 stores relative paths)
self._path_to_module_id: dict[str, str] = {
m["file_path"]: m["module_id"]
for m in self._ir.get_all_modules()
}
# Cache project overview (same for all files)
self._project_overview: str = self._sys_builder.build_project_overview()
stats = self._ir.stats()
print(
f"[Phase2ContextProvider] Ready — "
f"{stats['total_modules']} modules, "
f"{stats['total_procedures']} procedures, "
f"languages: {stats['languages']}"
)
# ──────────────────────────────────────────────────────────────────
# Public API
# ──────────────────────────────────────────────────────────────────
def get_context_for_file(
self,
node_id: str,
dep_node_ids: list[str],
depth: int = 2,
) -> str:
"""
Build a structured architectural context string for the given Java file.
Parameters
----------
node_id : relative file path used as DAG node, e.g. "src/.../Foo.java"
dep_node_ids : direct dependency node_ids from the DAG
depth : how many hops of graph neighbours to include (default 2)
Returns
-------
A formatted string ready to be injected into the LLM prompt, capped at
MAX_CONTEXT_CHARS to stay within token budget.
"""
sections: list[str] = []
# ── 1. Project overview (always included, short) ──────────────
sections.append("### PROJECT ARCHITECTURE OVERVIEW\n" + self._project_overview)
# ── 2. The current module's own architectural summary ─────────
current_doc = self._build_doc_for_node(node_id)
if current_doc:
sections.append("### CURRENT MODULE\n" + current_doc)
# ── 3. Direct dependency summaries ────────────────────────────
dep_docs: list[str] = []
seen: set[str] = {node_id}
for dep_id in dep_node_ids:
if dep_id in seen:
continue
seen.add(dep_id)
doc = self._build_doc_for_node(dep_id)
if doc:
dep_docs.append(doc)
if dep_docs:
sections.append(
"### DIRECT DEPENDENCY ARCHITECTURE\n" + "\n\n".join(dep_docs)
)
# ── 4. Graph-expanded neighbours (depth hops) ─────────────────
mid = self._path_to_module_id.get(node_id)
if mid and depth > 1:
neighbour_docs: list[str] = []
reachable = self.graph.bfs_reachable(mid, max_depth=depth)
for neighbour_mid, hop in sorted(reachable.items(), key=lambda x: x[1]):
if hop == 0:
continue # that's the module itself
neighbour_node = self._module_id_to_node(neighbour_mid)
if neighbour_node and neighbour_node not in seen:
seen.add(neighbour_node)
doc = self._build_doc_for_module_id(neighbour_mid)
if doc:
neighbour_docs.append(f"[depth {hop}] " + doc)
if neighbour_docs:
sections.append(
"### TRANSITIVE DEPENDENCIES (structural context)\n"
+ "\n\n".join(neighbour_docs)
)
# ── 5. Cycle warning ──────────────────────────────────────────
if mid and self.graph.is_in_cycle(mid):
cluster = self.graph.get_cycle_cluster(mid)
names = [self.graph.get_module_name(m) or m for m in cluster]
sections.append(
"### ⚠ CIRCULAR DEPENDENCY WARNING\n"
f"This module is part of a circular dependency cluster: "
f"{' ↔ '.join(names)}\n"
"Use TYPE_CHECKING guards (from __future__ import annotations) "
"for cross-imports between these classes."
)
# ── Join + cap ────────────────────────────────────────────────
separator = "\n" + ("─" * 50) + "\n"
full = separator.join(sections)
if len(full) > self.MAX_CONTEXT_CHARS:
full = full[: self.MAX_CONTEXT_CHARS] + "\n# [context truncated to fit token budget]"
return full
def has_module(self, node_id: str) -> bool:
"""True if Phase 1 has IR data for this file path."""
return node_id in self._path_to_module_id
# ──────────────────────────────────────────────────────────────────
# Internal helpers
# ──────────────────────────────────────────────────────────────────
def _build_doc_for_node(self, node_id: str) -> str:
mid = self._path_to_module_id.get(node_id)
if not mid:
return ""
return self._mod_builder.build_document(mid)
def _build_doc_for_module_id(self, module_id: str) -> str:
return self._mod_builder.build_document(module_id)
def _module_id_to_node(self, module_id: str) -> Optional[str]:
"""Reverse lookup: module_id → file_path (node_id)."""
module = self._ir.get_module_by_id(module_id)
return module["file_path"] if module else None