codegraph-engine 2.2.1__py3-none-any.whl → 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. codegraph/__init__.py +1 -1
  2. codegraph/agent_brain.py +172 -2
  3. codegraph/agent_capabilities.py +564 -6
  4. codegraph/agent_rules.py +1 -1
  5. codegraph/api_drift.py +455 -0
  6. codegraph/async_queue/__init__.py +50 -0
  7. codegraph/async_queue/detectors/__init__.py +48 -0
  8. codegraph/async_queue/detectors/celery.py +160 -0
  9. codegraph/async_queue/detectors/kafka.py +168 -0
  10. codegraph/async_queue/detectors/rabbitmq.py +116 -0
  11. codegraph/async_queue/detectors/redis.py +130 -0
  12. codegraph/async_queue/detectors/sqs.py +135 -0
  13. codegraph/async_queue/models.py +161 -0
  14. codegraph/async_queue/otel_models.py +74 -0
  15. codegraph/async_queue/otel_parser.py +337 -0
  16. codegraph/async_queue/reconciler.py +427 -0
  17. codegraph/async_queue/scanner.py +291 -0
  18. codegraph/async_queue/traversal.py +447 -0
  19. codegraph/branch_comparison.py +197 -0
  20. codegraph/change_impact.py +547 -0
  21. codegraph/cli.py +992 -3
  22. codegraph/cli_output.py +17 -2
  23. codegraph/context.py +38 -11
  24. codegraph/context_freshness.py +351 -0
  25. codegraph/database/__init__.py +14 -0
  26. codegraph/database/extractor.py +712 -17
  27. codegraph/database/interrogation.py +388 -2
  28. codegraph/database/schema_drift.py +862 -0
  29. codegraph/epistemic.py +7 -0
  30. codegraph/evidence_contract.py +21 -0
  31. codegraph/frameworks.py +171 -6
  32. codegraph/frameworks_nestjs.py +502 -0
  33. codegraph/frameworks_nextjs.py +337 -0
  34. codegraph/frameworks_react.py +457 -0
  35. codegraph/freshness.py +2 -0
  36. codegraph/frontend_html.py +109 -0
  37. codegraph/git.py +2 -0
  38. codegraph/git_state.py +545 -0
  39. codegraph/indexing/__init__.py +7 -1
  40. codegraph/indexing/indexer.py +291 -38
  41. codegraph/indexing/models.py +6 -0
  42. codegraph/indexing/parser.py +239 -0
  43. codegraph/indexing/pool.py +136 -0
  44. codegraph/indexing/scanner.py +6 -0
  45. codegraph/indexing/templates.py +418 -0
  46. codegraph/interrogation.py +128 -20
  47. codegraph/mcp/server.py +258 -27
  48. codegraph/models.py +7 -0
  49. codegraph/monorepo.py +3 -0
  50. codegraph/optimizer.py +42 -5
  51. codegraph/process_lifecycle.py +31 -13
  52. codegraph/refactor/__init__.py +36 -0
  53. codegraph/refactor/models.py +114 -0
  54. codegraph/refactor/renamer.py +844 -0
  55. codegraph/refactor/transactions.py +403 -0
  56. codegraph/resolver.py +1202 -159
  57. codegraph/retrieval_policy.py +6 -0
  58. codegraph/route_topology.py +172 -0
  59. codegraph/runtime/__init__.py +19 -0
  60. codegraph/runtime/collector.py +155 -0
  61. codegraph/runtime/db_watcher.py +191 -0
  62. codegraph/runtime/ingestor.py +30 -10
  63. codegraph/runtime/port_inspector.py +304 -0
  64. codegraph/runtime/runner.py +155 -6
  65. codegraph/runtime/trace_linker.py +175 -0
  66. codegraph/search/hybrid.py +26 -0
  67. codegraph/semantic_conflicts.py +270 -0
  68. codegraph/semantic_decorators.py +34 -3
  69. codegraph/structural_diff.py +542 -0
  70. codegraph/styles.py +144 -0
  71. codegraph/symbol_history.py +277 -0
  72. codegraph/tsconfig.py +236 -0
  73. codegraph/ui/__init__.py +6 -0
  74. codegraph/ui/server.py +715 -0
  75. codegraph/watcher.py +323 -0
  76. {codegraph_engine-2.2.1.dist-info → codegraph_engine-3.0.0.dist-info}/METADATA +257 -39
  77. codegraph_engine-3.0.0.dist-info/RECORD +129 -0
  78. codegraph_engine-2.2.1.dist-info/RECORD +0 -87
  79. {codegraph_engine-2.2.1.dist-info → codegraph_engine-3.0.0.dist-info}/WHEEL +0 -0
  80. {codegraph_engine-2.2.1.dist-info → codegraph_engine-3.0.0.dist-info}/entry_points.txt +0 -0
  81. {codegraph_engine-2.2.1.dist-info → codegraph_engine-3.0.0.dist-info}/licenses/LICENSE +0 -0
  82. {codegraph_engine-2.2.1.dist-info → codegraph_engine-3.0.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,418 @@
1
+ """Deterministic HTML, Jinja2, and Web Template Parser.
2
+
3
+ Extracts:
4
+ 1. DOM elements with IDs or semantic anchors into Symbol records.
5
+ 2. Inline JavaScript event handlers (onclick="fn()", @click="fn") into CallRef and Symbol records.
6
+ 3. Form submission actions (<form action="/api/..." method="POST">) into BindingRef records.
7
+ 4. Script tag imports (<script src="...">) and stylesheet links into ImportRef records.
8
+ 5. Embedded <script> JavaScript blocks parsed with exact file line offsets.
9
+ 6. Jinja/Django/EJS template directives ({% block %}, {% extends %}, {% include %}).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import re
15
+ from html.parser import HTMLParser
16
+
17
+ from codegraph.indexing.models import (
18
+ BindingRef,
19
+ CallRef,
20
+ ImportRef,
21
+ InheritanceRef,
22
+ Symbol,
23
+ normalize_module,
24
+ )
25
+ from codegraph.indexing.parser import PARSER_VERSION, ParseResult, _parse_js_ts
26
+
27
+ # Regex for extracting JS function calls in inline handlers like:
28
+ # onclick="quickToggleStock(123)", onsubmit="return handleForm(this, event)"
29
+ _JS_CALL_PATTERN = re.compile(r"\b([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(")
30
+
31
+ # Regex for Jinja2 / Django / EJS template directives
32
+ _JINJA_EXTENDS = re.compile(r"""\{%\s*extends\s+['"]([^'"]+)['"]\s*%\}""")
33
+ _JINJA_INCLUDE = re.compile(r"""\{%\s*include\s+['"]([^'"]+)['"]\s*%\}""")
34
+ _JINJA_BLOCK = re.compile(r"""\{%\s*block\s+([a-zA-Z0-9_]+)\s*%\}""")
35
+ _JINJA_URL_FOR = re.compile(r"""\{\{\s*url_for\s*\(\s*['"]([^'"]+)['"]""")
36
+ _DJANGO_URL = re.compile(r"""\{%\s*url\s+['"]([^'"]+)['"]""")
37
+
38
+ # HTMX HTTP request attribute mappings
39
+ _HTMX_VERBS = {
40
+ "hx-get": "GET",
41
+ "hx-post": "POST",
42
+ "hx-put": "PUT",
43
+ "hx-delete": "DELETE",
44
+ "hx-patch": "PATCH",
45
+ "data-hx-get": "GET",
46
+ "data-hx-post": "POST",
47
+ "data-hx-put": "PUT",
48
+ "data-hx-delete": "DELETE",
49
+ "data-hx-patch": "PATCH",
50
+ }
51
+
52
+
53
+ class _TemplateHTMLParser(HTMLParser):
54
+ def __init__(self, file_path: str, module_name: str) -> None:
55
+ super().__init__()
56
+ self.file_path = file_path
57
+ self.module_name = module_name
58
+ self.symbols: list[Symbol] = []
59
+ self.calls: list[CallRef] = []
60
+ self.imports: list[ImportRef] = []
61
+ self.bindings: list[BindingRef] = []
62
+ self.script_blocks: list[tuple[int, str]] = [] # (start_line, content)
63
+ self._in_script = False
64
+ self._script_start_line = 1
65
+ self._script_buf: list[str] = []
66
+
67
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
68
+ line_num, _ = self.getpos()
69
+ attr_dict: dict[str, str] = {k.lower(): (v or "") for k, v in attrs if k}
70
+
71
+ if tag.lower() == "script":
72
+ src = attr_dict.get("src")
73
+ if src:
74
+ self.imports.append(
75
+ ImportRef(
76
+ source_file=self.file_path,
77
+ module=src,
78
+ line=line_num,
79
+ import_type="script_src",
80
+ )
81
+ )
82
+ else:
83
+ self._in_script = True
84
+ self._script_start_line = line_num
85
+ self._script_buf = []
86
+
87
+ if tag.lower() == "link" and attr_dict.get("rel") == "stylesheet":
88
+ href = attr_dict.get("href")
89
+ if href:
90
+ self.imports.append(
91
+ ImportRef(
92
+ source_file=self.file_path,
93
+ module=href,
94
+ line=line_num,
95
+ import_type="stylesheet",
96
+ )
97
+ )
98
+
99
+ # 1. DOM Elements with ID
100
+ elem_id = attr_dict.get("id")
101
+ if elem_id:
102
+ sym_name = elem_id.strip()
103
+ self.symbols.append(
104
+ Symbol(
105
+ name=sym_name,
106
+ qualified_name=f"{tag}#{sym_name}",
107
+ kind="html_element",
108
+ language="html",
109
+ file_path=self.file_path,
110
+ start_line=line_num,
111
+ end_line=line_num,
112
+ scope=tag,
113
+ )
114
+ )
115
+
116
+ # 2. Inline JavaScript / Alpine.js Event Handlers (onclick, onsubmit, @click, x-on:click, x-init, etc.)
117
+ for attr_k, attr_v in attr_dict.items():
118
+ is_handler = (
119
+ attr_k.startswith("on")
120
+ or attr_k.startswith("@")
121
+ or attr_k.startswith("v-on:")
122
+ or attr_k.startswith("x-on:")
123
+ or attr_k in ("x-init", "x-effect")
124
+ or (attr_k.startswith("(") and attr_k.endswith(")"))
125
+ )
126
+ if not is_handler or not attr_v:
127
+ continue
128
+
129
+ if attr_k.startswith(("@", "x-on:", "x-data", "x-init", "x-show")):
130
+ caller_label = f"{tag}#{elem_id}" if elem_id else tag
131
+ self.bindings.append(
132
+ BindingRef(
133
+ target_name=attr_k,
134
+ file_path=self.file_path,
135
+ line=line_num,
136
+ expr_kind="ALPINE_EVENT",
137
+ source_expr=attr_v,
138
+ base_expr=caller_label,
139
+ )
140
+ )
141
+
142
+ matches = _JS_CALL_PATTERN.findall(attr_v)
143
+ found_fns: list[str] = list(matches)
144
+
145
+ # If attribute value is a bare identifier / method reference (e.g. @click="handleClick" or onclick="handleClick")
146
+ val_clean = attr_v.strip()
147
+ if not found_fns and re.match(r"^[a-zA-Z_$][a-zA-Z0-9_$]*(?:\.[a-zA-Z_$][a-zA-Z0-9_$]*)?$", val_clean):
148
+ found_fns.append(val_clean.split(".")[-1])
149
+
150
+ for fn_name in found_fns:
151
+ if fn_name in ("return", "if", "for", "while", "this"):
152
+ continue
153
+
154
+ caller_label = f"{tag}#{elem_id}" if elem_id else tag
155
+ self.calls.append(
156
+ CallRef(
157
+ callee=fn_name,
158
+ source_file=self.file_path,
159
+ line=line_num,
160
+ end_line=line_num,
161
+ caller_symbol=caller_label,
162
+ caller_canonical_id=f"{self.module_name}.{caller_label}",
163
+ confidence="HIGH",
164
+ )
165
+ )
166
+
167
+ self.symbols.append(
168
+ Symbol(
169
+ name=fn_name,
170
+ qualified_name=f"{caller_label}[{attr_k}]->{fn_name}",
171
+ kind="event_handler",
172
+ language="html",
173
+ file_path=self.file_path,
174
+ start_line=line_num,
175
+ end_line=line_num,
176
+ scope=caller_label,
177
+ )
178
+ )
179
+
180
+ # 3. Form submissions (<form action="..." method="...">)
181
+ if tag.lower() == "form":
182
+ action = attr_dict.get("action", "").strip()
183
+ method = attr_dict.get("method", "GET").strip().upper()
184
+ if action:
185
+ self.bindings.append(
186
+ BindingRef(
187
+ target_name=action,
188
+ file_path=self.file_path,
189
+ line=line_num,
190
+ expr_kind="HTML_FORM_ACTION",
191
+ base_expr=method,
192
+ )
193
+ )
194
+
195
+ # 4. Modern Python Stack: HTMX attributes (hx-get, hx-post, hx-delete, hx-put, hx-patch, etc.)
196
+ for hx_attr, http_method in _HTMX_VERBS.items():
197
+ if hx_attr in attr_dict and attr_dict[hx_attr]:
198
+ raw_endpoint = attr_dict[hx_attr].strip()
199
+ caller_label = f"{tag}#{elem_id}" if elem_id else tag
200
+ target_sel = attr_dict.get("hx-target") or attr_dict.get("data-hx-target") or ""
201
+ trigger = attr_dict.get("hx-trigger") or attr_dict.get("data-hx-trigger") or ""
202
+ swap = attr_dict.get("hx-swap") or attr_dict.get("data-hx-swap") or ""
203
+
204
+ resolved_endpoint = raw_endpoint
205
+ m_django = _DJANGO_URL.search(raw_endpoint)
206
+ if m_django:
207
+ resolved_endpoint = m_django.group(1)
208
+ else:
209
+ m_jinja = _JINJA_URL_FOR.search(raw_endpoint)
210
+ if m_jinja:
211
+ resolved_endpoint = m_jinja.group(1)
212
+
213
+ meta_entries = (
214
+ ("target", target_sel),
215
+ ("trigger", trigger),
216
+ ("swap", swap),
217
+ ("element", tag),
218
+ ("element_id", elem_id or ""),
219
+ ("raw_url", raw_endpoint),
220
+ )
221
+
222
+ self.bindings.append(
223
+ BindingRef(
224
+ target_name=resolved_endpoint,
225
+ file_path=self.file_path,
226
+ line=line_num,
227
+ expr_kind="HTMX_REQUEST",
228
+ base_expr=http_method,
229
+ source_expr=target_sel,
230
+ attr_name=trigger,
231
+ dict_entries=meta_entries,
232
+ )
233
+ )
234
+
235
+ self.calls.append(
236
+ CallRef(
237
+ callee=resolved_endpoint,
238
+ qualified_callee=f"{http_method} {resolved_endpoint}",
239
+ source_file=self.file_path,
240
+ line=line_num,
241
+ end_line=line_num,
242
+ caller_symbol=caller_label,
243
+ caller_canonical_id=f"{self.module_name}.{caller_label}",
244
+ confidence="HIGH",
245
+ )
246
+ )
247
+
248
+ self.symbols.append(
249
+ Symbol(
250
+ name=resolved_endpoint,
251
+ qualified_name=f"{caller_label}[{hx_attr}]->{http_method} {resolved_endpoint}",
252
+ kind="htmx_action",
253
+ language="html",
254
+ file_path=self.file_path,
255
+ start_line=line_num,
256
+ end_line=line_num,
257
+ scope=caller_label,
258
+ )
259
+ )
260
+
261
+ def handle_endtag(self, tag: str) -> None:
262
+ if tag.lower() == "script" and self._in_script:
263
+ self._in_script = False
264
+ content = "".join(self._script_buf)
265
+ if content.strip():
266
+ self.script_blocks.append((self._script_start_line, content))
267
+ self._script_buf = []
268
+
269
+ def handle_data(self, data: str) -> None:
270
+ if self._in_script:
271
+ self._script_buf.append(data)
272
+
273
+
274
+ def parse_html_template(content: str, file_path: str) -> ParseResult:
275
+ """Parse an HTML or web template file in a single deterministic pass."""
276
+ source_hash = hashlib.sha256(content.encode("utf-8", errors="replace")).hexdigest()
277
+ module_name = normalize_module(file_path, "html")
278
+
279
+ parser = _TemplateHTMLParser(file_path=file_path, module_name=module_name)
280
+ try:
281
+ parser.feed(content)
282
+ except Exception as e:
283
+ return ParseResult(
284
+ path=file_path,
285
+ language="html",
286
+ parser_version=PARSER_VERSION,
287
+ source_hash=source_hash,
288
+ parse_failed=True,
289
+ parse_error=f"HTML parse error: {e}",
290
+ )
291
+
292
+ symbols = list(parser.symbols)
293
+ calls = list(parser.calls)
294
+ imports = list(parser.imports)
295
+ inheritance: list[InheritanceRef] = []
296
+ bindings = list(parser.bindings)
297
+
298
+ # 4. Parse Jinja / Django directives line-by-line
299
+ lines = content.splitlines()
300
+ for idx, line in enumerate(lines, 1):
301
+ # {% extends "base.html" %}
302
+ ext_match = _JINJA_EXTENDS.search(line)
303
+ if ext_match:
304
+ inheritance.append(
305
+ InheritanceRef(
306
+ source_symbol=module_name,
307
+ base_name=ext_match.group(1),
308
+ relationship="EXTENDS",
309
+ source_file=file_path,
310
+ line=idx,
311
+ )
312
+ )
313
+
314
+ # {% include "nav.html" %}
315
+ inc_match = _JINJA_INCLUDE.search(line)
316
+ if inc_match:
317
+ imports.append(
318
+ ImportRef(
319
+ source_file=file_path,
320
+ module=inc_match.group(1),
321
+ line=idx,
322
+ import_type="template_include",
323
+ )
324
+ )
325
+
326
+ # {% block content %}
327
+ blk_match = _JINJA_BLOCK.search(line)
328
+ if blk_match:
329
+ blk_name = blk_match.group(1)
330
+ symbols.append(
331
+ Symbol(
332
+ name=blk_name,
333
+ qualified_name=f"block#{blk_name}",
334
+ kind="template_block",
335
+ language="html",
336
+ file_path=file_path,
337
+ start_line=idx,
338
+ end_line=idx,
339
+ scope=module_name,
340
+ )
341
+ )
342
+
343
+ # {{ url_for('user_bp.checkout') }}
344
+ url_match = _JINJA_URL_FOR.search(line)
345
+ if url_match:
346
+ target_endpoint = url_match.group(1)
347
+ calls.append(
348
+ CallRef(
349
+ callee=target_endpoint,
350
+ source_file=file_path,
351
+ line=idx,
352
+ end_line=idx,
353
+ caller_symbol=module_name,
354
+ caller_canonical_id=module_name,
355
+ confidence="HIGH",
356
+ )
357
+ )
358
+
359
+ # 5. Parse embedded <script> tags with JS parser
360
+ for start_line, script_code in parser.script_blocks:
361
+ try:
362
+ js_res = _parse_js_ts(script_code, "javascript", file_path)
363
+ # Offset line numbers by start_line - 1
364
+ line_offset = max(0, start_line - 1)
365
+ for s in js_res.symbols:
366
+ adj_start = s.start_line + line_offset
367
+ adj_end = s.end_line + line_offset
368
+ symbols.append(
369
+ Symbol(
370
+ name=s.name,
371
+ qualified_name=s.qualified_name,
372
+ kind=s.kind,
373
+ language="javascript",
374
+ file_path=file_path,
375
+ start_line=adj_start,
376
+ end_line=adj_end,
377
+ signature=s.signature,
378
+ scope=s.scope,
379
+ )
380
+ )
381
+ for c in js_res.calls:
382
+ calls.append(
383
+ CallRef(
384
+ callee=c.callee,
385
+ source_file=file_path,
386
+ line=c.line + line_offset,
387
+ end_line=c.end_line + line_offset,
388
+ caller_symbol=c.caller_symbol,
389
+ caller_canonical_id=c.caller_canonical_id,
390
+ confidence=c.confidence,
391
+ )
392
+ )
393
+ for imp in js_res.imports:
394
+ imports.append(
395
+ ImportRef(
396
+ source_file=file_path,
397
+ module=imp.module,
398
+ name=imp.name,
399
+ line=imp.line + line_offset,
400
+ import_type=imp.import_type,
401
+ )
402
+ )
403
+ except Exception:
404
+ # Tolerant fallback if inline script cannot be parsed
405
+ pass
406
+
407
+ return ParseResult(
408
+ path=file_path,
409
+ language="html",
410
+ parser_version=PARSER_VERSION,
411
+ source_hash=source_hash,
412
+ symbols=tuple(symbols),
413
+ imports=tuple(imports),
414
+ calls=tuple(calls),
415
+ inheritance=tuple(inheritance),
416
+ bindings=tuple(bindings),
417
+ parse_failed=False,
418
+ )
@@ -1564,7 +1564,10 @@ def trace_path(
1564
1564
  "FROM graph_edges "
1565
1565
  "WHERE source=? AND relationship IN ("
1566
1566
  "'CALLS', 'DEFINES', 'CONTAINS', 'IMPORTS', 'HANDLED_BY', 'ROUTES_TO', "
1567
- "'PROVIDES', 'INJECTS', 'RESOLVES_DEPENDENCY', 'DISPATCHES_TO', 'REGISTERS'"
1567
+ "'PROVIDES', 'INJECTS', 'RESOLVES_DEPENDENCY', 'DISPATCHES_TO', 'REGISTERS', "
1568
+ "'PRODUCES_TO_QUEUE', 'CONSUMES_FROM_QUEUE', 'STATIC_QUEUE_LINKED', 'OTEL_DISTRIBUTED_VERIFIED', "
1569
+ "'DISPATCHES_TASK', 'TRIGGERS_SIGNAL', 'HANDLES_SIGNAL', 'RENDERS_TEMPLATE', "
1570
+ "'DISPATCHES_FORWARD', 'TOOL_HANDLER', 'PIPELINE_STEP'"
1568
1571
  ") AND confidence IN ('HIGH', 'MEDIUM') "
1569
1572
  "ORDER BY relationship ASC, target ASC",
1570
1573
  (curr_sym,),
@@ -2010,25 +2013,130 @@ def list_routes(
2010
2013
  except sqlite3.OperationalError:
2011
2014
  rows = []
2012
2015
 
2013
- routes = [
2014
- {
2015
- "method": r["http_method"],
2016
- "path": r["route_path"],
2017
- "handler": r["handler_canonical_id"] or r["handler_name"],
2018
- "file": r["file_path"],
2019
- "start_line": r["line"],
2020
- "end_line": r["line"],
2021
- "framework": r["framework"],
2022
- "evidence": make_evidence(
2023
- file=r["file_path"],
2024
- start_line=r["line"],
2025
- end_line=r["line"],
2026
- evidence_type="route",
2027
- canonical_id=r["handler_canonical_id"],
2028
- ),
2029
- }
2030
- for r in rows
2031
- ]
2016
+ # Fetch HTMX requests and template rendering edges if available
2017
+ htmx_rows: list[sqlite3.Row] = []
2018
+ try:
2019
+ htmx_rows = con.execute(
2020
+ "SELECT target_name, file_path, line, base_expr, dict_entries_json "
2021
+ "FROM local_bindings WHERE expr_kind='HTMX_REQUEST'"
2022
+ ).fetchall()
2023
+ except sqlite3.OperationalError:
2024
+ pass
2025
+
2026
+ template_edges: dict[str, list[dict[str, Any]]] = {}
2027
+ try:
2028
+ t_rows = con.execute(
2029
+ "SELECT source, target, file, start_line FROM graph_edges WHERE relationship='RENDERS_TEMPLATE'"
2030
+ ).fetchall()
2031
+ for tr in t_rows:
2032
+ template_edges.setdefault(tr["source"], []).append(
2033
+ {
2034
+ "template": tr["target"],
2035
+ "file": tr["file"],
2036
+ "line": tr["start_line"],
2037
+ }
2038
+ )
2039
+ except sqlite3.OperationalError:
2040
+ pass
2041
+
2042
+ def _route_matches_url(route_path: str, url: str, handler_name: str = "", handler_canon: str = "") -> bool:
2043
+ if not route_path or not url:
2044
+ return False
2045
+ if handler_name and (url == handler_name or url.endswith(f".{handler_name}")):
2046
+ return True
2047
+ if handler_canon and url in handler_canon:
2048
+ return True
2049
+ rp = route_path.rstrip("/") or "/"
2050
+ u = url.rstrip("/") or "/"
2051
+ if rp == u:
2052
+ return True
2053
+ u_clean = u.split("?")[0]
2054
+ if rp == u_clean:
2055
+ return True
2056
+ import re
2057
+ pattern = re.sub(r"<[^>]+>", r"[^/]+", rp)
2058
+ pattern = re.sub(r"\{[^}]+\}", r"[^/]+", pattern)
2059
+ pattern = re.sub(r":[\w]+", r"[^/]+", pattern)
2060
+ pattern = f"^{pattern}$"
2061
+ try:
2062
+ return bool(re.match(pattern, u_clean))
2063
+ except Exception:
2064
+ return False
2065
+
2066
+ routes = []
2067
+ for r in rows:
2068
+ r_path = r["route_path"]
2069
+ r_method = (r["http_method"] or "").upper()
2070
+ h_canon = r["handler_canonical_id"] or ""
2071
+ h_name = r["handler_name"] or ""
2072
+
2073
+ # Match HTMX callers
2074
+ htmx_callers: list[dict[str, Any]] = []
2075
+ for hb in htmx_rows:
2076
+ url = hb["target_name"]
2077
+ hb_method = (hb["base_expr"] or "").upper()
2078
+ if (not hb_method or hb_method == r_method or r_method in ("ALL", "ANY")) and _route_matches_url(
2079
+ r_path, url, h_name, h_canon
2080
+ ):
2081
+ import json
2082
+ meta_dict: dict[str, Any] = {}
2083
+ try:
2084
+ raw_entries = json.loads(hb["dict_entries_json"] or "[]")
2085
+ if isinstance(raw_entries, list):
2086
+ meta_dict = dict(raw_entries)
2087
+ elif isinstance(raw_entries, dict):
2088
+ meta_dict = raw_entries
2089
+ except Exception:
2090
+ pass
2091
+ htmx_callers.append(
2092
+ {
2093
+ "url": url,
2094
+ "method": hb_method,
2095
+ "file": hb["file_path"],
2096
+ "line": hb["line"],
2097
+ "target": meta_dict.get("target"),
2098
+ "trigger": meta_dict.get("trigger"),
2099
+ "swap": meta_dict.get("swap"),
2100
+ "element": meta_dict.get("element"),
2101
+ }
2102
+ )
2103
+
2104
+ rendered = template_edges.get(h_canon, []) or template_edges.get(h_name, [])
2105
+
2106
+ lineage: dict[str, Any] = {}
2107
+ try:
2108
+ from codegraph.database.interrogation import get_route_db_lineage
2109
+
2110
+ lineage = get_route_db_lineage(
2111
+ con,
2112
+ route_or_handler=h_canon or h_name or r_path,
2113
+ method=r_method,
2114
+ )
2115
+ except Exception:
2116
+ lineage = {}
2117
+
2118
+ routes.append(
2119
+ {
2120
+ "method": r["http_method"],
2121
+ "path": r["route_path"],
2122
+ "handler": r["handler_canonical_id"] or r["handler_name"],
2123
+ "file": r["file_path"],
2124
+ "start_line": r["line"],
2125
+ "end_line": r["line"],
2126
+ "framework": r["framework"],
2127
+ "htmx_callers": htmx_callers,
2128
+ "templates_rendered": rendered,
2129
+ "db_reads": lineage.get("db_reads", []),
2130
+ "db_writes": lineage.get("db_writes", []),
2131
+ "evidence": make_evidence(
2132
+ file=r["file_path"],
2133
+ start_line=r["line"],
2134
+ end_line=r["line"],
2135
+ evidence_type="route",
2136
+ canonical_id=r["handler_canonical_id"],
2137
+ ),
2138
+ }
2139
+ )
2032
2140
 
2033
2141
  total_count = len(routes)
2034
2142
  if limit is not None: