mulle-roam-code 0.0.1__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 (257) hide show
  1. mulle_roam_code-0.0.1.dist-info/METADATA +1590 -0
  2. mulle_roam_code-0.0.1.dist-info/RECORD +257 -0
  3. mulle_roam_code-0.0.1.dist-info/WHEEL +5 -0
  4. mulle_roam_code-0.0.1.dist-info/entry_points.txt +3 -0
  5. mulle_roam_code-0.0.1.dist-info/licenses/LICENSE +21 -0
  6. mulle_roam_code-0.0.1.dist-info/top_level.txt +1 -0
  7. roam/__init__.py +8 -0
  8. roam/__main__.py +5 -0
  9. roam/analysis/__init__.py +1 -0
  10. roam/analysis/effects.py +639 -0
  11. roam/analysis/taint.py +689 -0
  12. roam/api.py +238 -0
  13. roam/bridges/__init__.py +3 -0
  14. roam/bridges/base.py +49 -0
  15. roam/bridges/bridge_config.py +218 -0
  16. roam/bridges/bridge_protobuf.py +352 -0
  17. roam/bridges/bridge_rest_api.py +242 -0
  18. roam/bridges/bridge_salesforce.py +198 -0
  19. roam/bridges/bridge_template.py +247 -0
  20. roam/bridges/registry.py +51 -0
  21. roam/catalog/__init__.py +0 -0
  22. roam/catalog/detectors.py +2242 -0
  23. roam/catalog/fixes.py +86 -0
  24. roam/catalog/smells.py +599 -0
  25. roam/catalog/tasks.py +1260 -0
  26. roam/cli.py +548 -0
  27. roam/commands/__init__.py +0 -0
  28. roam/commands/changed_files.py +139 -0
  29. roam/commands/cmd_adversarial.py +699 -0
  30. roam/commands/cmd_affected.py +432 -0
  31. roam/commands/cmd_affected_tests.py +375 -0
  32. roam/commands/cmd_agent_context.py +168 -0
  33. roam/commands/cmd_agent_export.py +890 -0
  34. roam/commands/cmd_agent_plan.py +315 -0
  35. roam/commands/cmd_ai_ratio.py +765 -0
  36. roam/commands/cmd_ai_readiness.py +775 -0
  37. roam/commands/cmd_alerts.py +409 -0
  38. roam/commands/cmd_annotate.py +210 -0
  39. roam/commands/cmd_api_changes.py +796 -0
  40. roam/commands/cmd_api_drift.py +781 -0
  41. roam/commands/cmd_attest.py +913 -0
  42. roam/commands/cmd_auth_gaps.py +799 -0
  43. roam/commands/cmd_bisect.py +216 -0
  44. roam/commands/cmd_breaking.py +464 -0
  45. roam/commands/cmd_budget.py +413 -0
  46. roam/commands/cmd_bus_factor.py +403 -0
  47. roam/commands/cmd_capsule.py +275 -0
  48. roam/commands/cmd_check_rules.py +574 -0
  49. roam/commands/cmd_clean.py +147 -0
  50. roam/commands/cmd_closure.py +294 -0
  51. roam/commands/cmd_clusters.py +457 -0
  52. roam/commands/cmd_codeowners.py +600 -0
  53. roam/commands/cmd_complexity.py +364 -0
  54. roam/commands/cmd_config.py +310 -0
  55. roam/commands/cmd_context.py +1151 -0
  56. roam/commands/cmd_conventions.py +697 -0
  57. roam/commands/cmd_coupling.py +462 -0
  58. roam/commands/cmd_coverage_gaps.py +638 -0
  59. roam/commands/cmd_cut.py +235 -0
  60. roam/commands/cmd_dark_matter.py +127 -0
  61. roam/commands/cmd_dashboard.py +365 -0
  62. roam/commands/cmd_dead.py +1585 -0
  63. roam/commands/cmd_debt.py +731 -0
  64. roam/commands/cmd_deps.py +121 -0
  65. roam/commands/cmd_describe.py +959 -0
  66. roam/commands/cmd_dev_profile.py +580 -0
  67. roam/commands/cmd_diagnose.py +377 -0
  68. roam/commands/cmd_diff.py +633 -0
  69. roam/commands/cmd_digest.py +214 -0
  70. roam/commands/cmd_doc_staleness.py +334 -0
  71. roam/commands/cmd_docs_coverage.py +193 -0
  72. roam/commands/cmd_doctor.py +319 -0
  73. roam/commands/cmd_drift.py +377 -0
  74. roam/commands/cmd_duplicates.py +559 -0
  75. roam/commands/cmd_effects.py +362 -0
  76. roam/commands/cmd_endpoints.py +768 -0
  77. roam/commands/cmd_entry_points.py +358 -0
  78. roam/commands/cmd_fan.py +311 -0
  79. roam/commands/cmd_file.py +334 -0
  80. roam/commands/cmd_fingerprint.py +172 -0
  81. roam/commands/cmd_fitness.py +723 -0
  82. roam/commands/cmd_fn_coupling.py +295 -0
  83. roam/commands/cmd_forecast.py +366 -0
  84. roam/commands/cmd_grep.py +282 -0
  85. roam/commands/cmd_guard.py +434 -0
  86. roam/commands/cmd_health.py +922 -0
  87. roam/commands/cmd_hooks.py +458 -0
  88. roam/commands/cmd_hotspots.py +606 -0
  89. roam/commands/cmd_impact.py +228 -0
  90. roam/commands/cmd_index.py +102 -0
  91. roam/commands/cmd_ingest_trace.py +143 -0
  92. roam/commands/cmd_init.py +166 -0
  93. roam/commands/cmd_intent.py +459 -0
  94. roam/commands/cmd_invariants.py +301 -0
  95. roam/commands/cmd_layers.py +387 -0
  96. roam/commands/cmd_map.py +275 -0
  97. roam/commands/cmd_math.py +213 -0
  98. roam/commands/cmd_mcp_setup.py +135 -0
  99. roam/commands/cmd_metrics.py +663 -0
  100. roam/commands/cmd_migration_safety.py +712 -0
  101. roam/commands/cmd_minimap.py +519 -0
  102. roam/commands/cmd_missing_index.py +885 -0
  103. roam/commands/cmd_module.py +204 -0
  104. roam/commands/cmd_mutate.py +400 -0
  105. roam/commands/cmd_n1.py +967 -0
  106. roam/commands/cmd_onboard.py +740 -0
  107. roam/commands/cmd_orchestrate.py +180 -0
  108. roam/commands/cmd_orphan_routes.py +754 -0
  109. roam/commands/cmd_over_fetch.py +633 -0
  110. roam/commands/cmd_owner.py +299 -0
  111. roam/commands/cmd_partition.py +714 -0
  112. roam/commands/cmd_path_coverage.py +564 -0
  113. roam/commands/cmd_patterns.py +689 -0
  114. roam/commands/cmd_plan.py +616 -0
  115. roam/commands/cmd_plan_refactor.py +432 -0
  116. roam/commands/cmd_pr_diff.py +292 -0
  117. roam/commands/cmd_pr_risk.py +677 -0
  118. roam/commands/cmd_preflight.py +706 -0
  119. roam/commands/cmd_relate.py +405 -0
  120. roam/commands/cmd_report.py +304 -0
  121. roam/commands/cmd_reset.py +117 -0
  122. roam/commands/cmd_risk.py +533 -0
  123. roam/commands/cmd_rules.py +319 -0
  124. roam/commands/cmd_safe_delete.py +224 -0
  125. roam/commands/cmd_safe_zones.py +295 -0
  126. roam/commands/cmd_schema.py +166 -0
  127. roam/commands/cmd_search.py +295 -0
  128. roam/commands/cmd_search_semantic.py +101 -0
  129. roam/commands/cmd_secrets.py +636 -0
  130. roam/commands/cmd_semantic_diff.py +538 -0
  131. roam/commands/cmd_simulate.py +296 -0
  132. roam/commands/cmd_simulate_departure.py +632 -0
  133. roam/commands/cmd_sketch.py +160 -0
  134. roam/commands/cmd_smells.py +179 -0
  135. roam/commands/cmd_snapshot.py +50 -0
  136. roam/commands/cmd_spectral.py +183 -0
  137. roam/commands/cmd_split.py +432 -0
  138. roam/commands/cmd_suggest_refactoring.py +486 -0
  139. roam/commands/cmd_suggest_reviewers.py +491 -0
  140. roam/commands/cmd_supply_chain.py +831 -0
  141. roam/commands/cmd_symbol.py +135 -0
  142. roam/commands/cmd_syntax_check.py +301 -0
  143. roam/commands/cmd_test_gaps.py +574 -0
  144. roam/commands/cmd_testmap.py +308 -0
  145. roam/commands/cmd_tour.py +377 -0
  146. roam/commands/cmd_trace.py +304 -0
  147. roam/commands/cmd_trend.py +461 -0
  148. roam/commands/cmd_trends.py +929 -0
  149. roam/commands/cmd_understand.py +763 -0
  150. roam/commands/cmd_uses.py +170 -0
  151. roam/commands/cmd_verify.py +812 -0
  152. roam/commands/cmd_verify_imports.py +435 -0
  153. roam/commands/cmd_vibe_check.py +932 -0
  154. roam/commands/cmd_visualize.py +361 -0
  155. roam/commands/cmd_vuln_map.py +139 -0
  156. roam/commands/cmd_vuln_reach.py +289 -0
  157. roam/commands/cmd_vulns.py +414 -0
  158. roam/commands/cmd_watch.py +759 -0
  159. roam/commands/cmd_weather.py +118 -0
  160. roam/commands/cmd_why.py +325 -0
  161. roam/commands/cmd_ws.py +755 -0
  162. roam/commands/cmd_xlang.py +170 -0
  163. roam/commands/context_helpers.py +1137 -0
  164. roam/commands/gate_presets.py +222 -0
  165. roam/commands/graph_helpers.py +93 -0
  166. roam/commands/metrics_history.py +298 -0
  167. roam/commands/next_steps.py +107 -0
  168. roam/commands/resolve.py +302 -0
  169. roam/competitor_site_data.py +2229 -0
  170. roam/coverage_reports.py +462 -0
  171. roam/db/__init__.py +0 -0
  172. roam/db/connection.py +359 -0
  173. roam/db/queries.py +151 -0
  174. roam/db/schema.py +335 -0
  175. roam/exit_codes.py +100 -0
  176. roam/graph/__init__.py +43 -0
  177. roam/graph/anomaly.py +493 -0
  178. roam/graph/builder.py +61 -0
  179. roam/graph/clusters.py +286 -0
  180. roam/graph/cycles.py +210 -0
  181. roam/graph/dark_matter.py +207 -0
  182. roam/graph/diff.py +467 -0
  183. roam/graph/fingerprint.py +297 -0
  184. roam/graph/layers.py +134 -0
  185. roam/graph/pagerank.py +171 -0
  186. roam/graph/partition.py +437 -0
  187. roam/graph/pathfinding.py +119 -0
  188. roam/graph/propagation.py +208 -0
  189. roam/graph/simulate.py +286 -0
  190. roam/graph/spectral.py +260 -0
  191. roam/index/__init__.py +5 -0
  192. roam/index/complexity.py +1108 -0
  193. roam/index/discovery.py +338 -0
  194. roam/index/file_roles.py +586 -0
  195. roam/index/git_stats.py +577 -0
  196. roam/index/incremental.py +75 -0
  197. roam/index/indexer.py +1191 -0
  198. roam/index/parser.py +461 -0
  199. roam/index/relations.py +537 -0
  200. roam/index/symbols.py +71 -0
  201. roam/index/test_conventions.py +508 -0
  202. roam/languages/__init__.py +21 -0
  203. roam/languages/apex_lang.py +241 -0
  204. roam/languages/aura_lang.py +228 -0
  205. roam/languages/base.py +111 -0
  206. roam/languages/c_lang.py +458 -0
  207. roam/languages/csharp_lang.py +1215 -0
  208. roam/languages/foxpro_lang.py +1554 -0
  209. roam/languages/generic_lang.py +702 -0
  210. roam/languages/go_lang.py +392 -0
  211. roam/languages/hcl_lang.py +398 -0
  212. roam/languages/java_lang.py +418 -0
  213. roam/languages/javascript_lang.py +799 -0
  214. roam/languages/kotlin_lang.py +147 -0
  215. roam/languages/objc_lang.py +401 -0
  216. roam/languages/php_lang.py +696 -0
  217. roam/languages/python_lang.py +850 -0
  218. roam/languages/registry.py +283 -0
  219. roam/languages/ruby_lang.py +429 -0
  220. roam/languages/rust_lang.py +545 -0
  221. roam/languages/sfxml_lang.py +276 -0
  222. roam/languages/swift_lang.py +173 -0
  223. roam/languages/typescript_lang.py +323 -0
  224. roam/languages/visualforce_lang.py +151 -0
  225. roam/languages/yaml_lang.py +566 -0
  226. roam/mcp_server.py +4794 -0
  227. roam/output/__init__.py +0 -0
  228. roam/output/formatter.py +557 -0
  229. roam/output/mermaid.py +62 -0
  230. roam/output/sarif.py +897 -0
  231. roam/output/schema_registry.py +57 -0
  232. roam/plugins.py +208 -0
  233. roam/refactor/__init__.py +0 -0
  234. roam/refactor/codegen.py +106 -0
  235. roam/refactor/transforms.py +711 -0
  236. roam/rules/__init__.py +0 -0
  237. roam/rules/ast_match.py +238 -0
  238. roam/rules/builtin.py +617 -0
  239. roam/rules/dataflow.py +515 -0
  240. roam/rules/engine.py +943 -0
  241. roam/runtime/__init__.py +3 -0
  242. roam/runtime/hotspots.py +138 -0
  243. roam/runtime/trace_ingest.py +535 -0
  244. roam/search/__init__.py +1 -0
  245. roam/search/framework_packs.py +673 -0
  246. roam/search/index_embeddings.py +732 -0
  247. roam/search/onnx_embeddings.py +233 -0
  248. roam/search/tfidf.py +355 -0
  249. roam/security/__init__.py +1 -0
  250. roam/security/vuln_reach.py +246 -0
  251. roam/security/vuln_store.py +334 -0
  252. roam/surface_counts.py +158 -0
  253. roam/workspace/__init__.py +3 -0
  254. roam/workspace/aggregator.py +426 -0
  255. roam/workspace/api_scanner.py +538 -0
  256. roam/workspace/config.py +95 -0
  257. roam/workspace/db.py +136 -0
@@ -0,0 +1,754 @@
1
+ """Find backend API routes that have no consumers in the codebase (dead endpoints)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import subprocess
8
+ from collections import defaultdict
9
+ from pathlib import Path
10
+
11
+ import click
12
+
13
+ from roam.commands.resolve import ensure_index
14
+ from roam.db.connection import find_project_root, open_db
15
+ from roam.output.formatter import format_table, json_envelope, loc, to_json
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # Skip patterns — routes that are intentionally internal / infrastructure
19
+ # ---------------------------------------------------------------------------
20
+
21
+ _SKIP_PATH_PATTERNS = re.compile(
22
+ r"telescope|horizon|pulse|sanctum|broadcasting|"
23
+ r"health|healthcheck|health-check|"
24
+ r"webhook|webhooks|stripe/|paypal/|"
25
+ r"_debugbar|_ignition|nova-api",
26
+ re.IGNORECASE,
27
+ )
28
+
29
+ _SKIP_NAMES = re.compile(
30
+ r"^(login|logout|register|password|verify|email|two-factor|"
31
+ r"sanctum|csrf|broadcasting|health)$",
32
+ re.IGNORECASE,
33
+ )
34
+
35
+ # Frontend file extensions to search
36
+ _FRONTEND_EXTENSIONS = {
37
+ ".vue",
38
+ ".ts",
39
+ ".tsx",
40
+ ".js",
41
+ ".jsx",
42
+ ".mts",
43
+ ".mjs",
44
+ ".cts",
45
+ ".cjs",
46
+ }
47
+
48
+ # Backend-only file patterns (tests, seeders, etc.)
49
+ _BACKEND_EXTENSIONS = {".php"}
50
+
51
+ _BACKEND_TEST_PATTERNS = re.compile(
52
+ r"[/\\](tests?|spec|feature|unit)[/\\]|Test\.php$|Spec\.php$",
53
+ re.IGNORECASE,
54
+ )
55
+
56
+ _SEEDER_FACTORY_PATTERN = re.compile(
57
+ r"[/\\](database|seeders?|factories)[/\\]",
58
+ re.IGNORECASE,
59
+ )
60
+
61
+
62
+ # ---------------------------------------------------------------------------
63
+ # Route extraction from PHP route files
64
+ # ---------------------------------------------------------------------------
65
+
66
+ # Standard single-action routes:
67
+ # Route::get('/path', [Controller::class, 'method'])
68
+ # Route::post('/path', 'Controller@method')
69
+ # Route::get('/path', fn => ...) (closure — no controller)
70
+ _SINGLE_ROUTE_RE = re.compile(
71
+ r"Route\s*::\s*(get|post|put|patch|delete|options|head|any)\s*\("
72
+ r"\s*['\"]([^'\"]+)['\"]"
73
+ r"(?:\s*,\s*"
74
+ r"(?:"
75
+ r"\[\s*([A-Za-z_\\]+)::class\s*,\s*['\"]([A-Za-z_]+)['\"]\s*\]"
76
+ r"|['\"]([A-Za-z_\\]+)@([A-Za-z_]+)['\"]"
77
+ r"))?"
78
+ r"\s*\)",
79
+ re.IGNORECASE,
80
+ )
81
+
82
+ # Resource / apiResource routes (these expand to multiple methods):
83
+ # Route::resource('name', Controller::class)
84
+ # Route::apiResource('name', Controller::class)
85
+ _RESOURCE_ROUTE_RE = re.compile(
86
+ r"Route\s*::\s*(apiResource|resource)\s*\("
87
+ r"\s*['\"]([^'\"]+)['\"]"
88
+ r"\s*,\s*([A-Za-z_\\]+)::class",
89
+ re.IGNORECASE,
90
+ )
91
+
92
+ # Route groups with prefix:
93
+ # Route::prefix('prefix')->group(...)
94
+ _PREFIX_RE = re.compile(
95
+ r"Route\s*::\s*(?:[^;]*?->)?\s*prefix\s*\(\s*['\"]([^'\"]+)['\"]",
96
+ re.IGNORECASE,
97
+ )
98
+
99
+ # Standard REST methods for apiResource (create/edit excluded)
100
+ _APIRESOURCE_METHODS = {
101
+ "index": "GET",
102
+ "store": "POST",
103
+ "show": "GET",
104
+ "update": "PUT",
105
+ "destroy": "DELETE",
106
+ }
107
+
108
+ # Full resource adds create/edit
109
+ _RESOURCE_METHODS = {
110
+ **_APIRESOURCE_METHODS,
111
+ "create": "GET",
112
+ "edit": "GET",
113
+ }
114
+
115
+ _HTTP_METHOD_MAP = {
116
+ "get": "GET",
117
+ "post": "POST",
118
+ "put": "PUT",
119
+ "patch": "PATCH",
120
+ "delete": "DELETE",
121
+ "options": "OPTIONS",
122
+ "head": "HEAD",
123
+ "any": "ANY",
124
+ }
125
+
126
+
127
+ def _extract_routes_from_file(file_path: Path) -> list[dict]:
128
+ """Parse a PHP route file and extract route definitions.
129
+
130
+ Returns a list of dicts:
131
+ {method, path, controller, action, file, line}
132
+ """
133
+ try:
134
+ source = file_path.read_text(encoding="utf-8", errors="replace")
135
+ except OSError:
136
+ return []
137
+
138
+ routes = []
139
+
140
+ def _line_of(match):
141
+ """Return 1-based line number for a regex match in 'source'."""
142
+ return source[: match.start()].count("\n") + 1
143
+
144
+ # --- Single-action routes ---
145
+ for m in _SINGLE_ROUTE_RE.finditer(source):
146
+ http_verb = _HTTP_METHOD_MAP.get(m.group(1).lower(), m.group(1).upper())
147
+ raw_path = m.group(2)
148
+
149
+ # Normalise path — make it start with /
150
+ if not raw_path.startswith("/"):
151
+ raw_path = "/" + raw_path
152
+
153
+ # Controller and action
154
+ if m.group(3): # [Controller::class, 'method'] form
155
+ controller = m.group(3).split("\\")[-1] # short name
156
+ action = m.group(4)
157
+ elif m.group(5): # 'Controller@method' form
158
+ controller = m.group(5).split("\\")[-1]
159
+ action = m.group(6)
160
+ else:
161
+ controller = None # closure-based route
162
+ action = None
163
+
164
+ routes.append(
165
+ {
166
+ "method": http_verb,
167
+ "path": raw_path,
168
+ "controller": controller,
169
+ "action": action,
170
+ "file": str(file_path),
171
+ "line": _line_of(m),
172
+ }
173
+ )
174
+
175
+ # --- Resource / apiResource routes ---
176
+ for m in _RESOURCE_ROUTE_RE.finditer(source):
177
+ is_api = m.group(1).lower() == "apiresource"
178
+ resource_name = m.group(2).strip("/")
179
+ controller = m.group(3).split("\\")[-1]
180
+ method_map = _APIRESOURCE_METHODS if is_api else _RESOURCE_METHODS
181
+ line = _line_of(m)
182
+
183
+ for action, http_verb in method_map.items():
184
+ if action == "index":
185
+ path = f"/{resource_name}"
186
+ elif action == "store":
187
+ path = f"/{resource_name}"
188
+ elif action == "create":
189
+ path = f"/{resource_name}/create"
190
+ elif action == "show":
191
+ path = f"/{resource_name}/{{id}}"
192
+ elif action == "edit":
193
+ path = f"/{resource_name}/{{id}}/edit"
194
+ elif action in ("update", "destroy"):
195
+ path = f"/{resource_name}/{{id}}"
196
+ else:
197
+ path = f"/{resource_name}"
198
+
199
+ routes.append(
200
+ {
201
+ "method": http_verb,
202
+ "path": path,
203
+ "controller": controller,
204
+ "action": action,
205
+ "file": str(file_path),
206
+ "line": line,
207
+ }
208
+ )
209
+
210
+ return routes
211
+
212
+
213
+ def _find_route_files(project_root: Path) -> list[Path]:
214
+ """Locate PHP route files in the project."""
215
+ candidates = []
216
+ routes_dir = project_root / "routes"
217
+ if routes_dir.is_dir():
218
+ for php_file in routes_dir.glob("*.php"):
219
+ candidates.append(php_file)
220
+
221
+ # Also check common alternate locations
222
+ for alt in ["app/routes", "src/routes"]:
223
+ alt_dir = project_root / alt
224
+ if alt_dir.is_dir():
225
+ for php_file in alt_dir.glob("*.php"):
226
+ candidates.append(php_file)
227
+
228
+ return candidates
229
+
230
+
231
+ def _should_skip_route(route: dict) -> bool:
232
+ """Return True if this route should be excluded from orphan analysis."""
233
+ path = route["path"]
234
+ # Skip infra / telescope / horizon etc.
235
+ if _SKIP_PATH_PATTERNS.search(path):
236
+ return True
237
+ # Skip pure auth routes by first segment
238
+ segments = [s for s in path.split("/") if s and not s.startswith("{")]
239
+ first = segments[0] if segments else ""
240
+ if _SKIP_NAMES.match(first):
241
+ return True
242
+ return False
243
+
244
+
245
+ # ---------------------------------------------------------------------------
246
+ # Path segment extraction
247
+ # ---------------------------------------------------------------------------
248
+
249
+
250
+ def _path_segments(route_path: str) -> list[str]:
251
+ """Extract meaningful segments from a route path for searching.
252
+
253
+ '/api/orders/{id}/items' → ['orders', 'items']
254
+ Drops the 'api' prefix (too generic) and parameter placeholders.
255
+ """
256
+ parts = route_path.strip("/").split("/")
257
+ segments = []
258
+ for p in parts:
259
+ if p.startswith("{") or p in ("api", "v1", "v2", "v3", ""):
260
+ continue
261
+ segments.append(p)
262
+ return segments
263
+
264
+
265
+ # ---------------------------------------------------------------------------
266
+ # Codebase searching
267
+ # ---------------------------------------------------------------------------
268
+
269
+
270
+ def _search_with_git_grep(pattern: str, project_root: Path, extra_args: list[str] | None = None) -> list[str]:
271
+ """Run git grep and return matching file paths (unique)."""
272
+ cmd = ["git", "grep", "-l", "-I", "--no-color", "-F", pattern]
273
+ if extra_args:
274
+ cmd.extend(extra_args)
275
+ try:
276
+ result = subprocess.run(
277
+ cmd,
278
+ cwd=str(project_root),
279
+ capture_output=True,
280
+ text=True,
281
+ timeout=15,
282
+ encoding="utf-8",
283
+ errors="replace",
284
+ )
285
+ if result.returncode <= 1:
286
+ return [line.strip() for line in result.stdout.splitlines() if line.strip()]
287
+ except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
288
+ pass
289
+ return []
290
+
291
+
292
+ def _search_with_git_grep_regex(pattern: str, project_root: Path) -> list[str]:
293
+ """Run git grep with regex and return matching file paths (unique)."""
294
+ cmd = ["git", "grep", "-l", "-I", "--no-color", "-E", pattern]
295
+ try:
296
+ result = subprocess.run(
297
+ cmd,
298
+ cwd=str(project_root),
299
+ capture_output=True,
300
+ text=True,
301
+ timeout=15,
302
+ encoding="utf-8",
303
+ errors="replace",
304
+ )
305
+ if result.returncode <= 1:
306
+ return [line.strip() for line in result.stdout.splitlines() if line.strip()]
307
+ except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
308
+ pass
309
+ return []
310
+
311
+
312
+ def _search_in_files(segment: str, project_root: Path, file_paths: list[str]) -> list[str]:
313
+ """Fallback: search for segment in a list of files by reading them."""
314
+ matches = []
315
+ pattern = re.compile(re.escape(segment), re.IGNORECASE)
316
+ for rel_path in file_paths:
317
+ full = project_root / rel_path
318
+ try:
319
+ text = full.read_text(encoding="utf-8", errors="replace")
320
+ if pattern.search(text):
321
+ matches.append(rel_path)
322
+ except OSError:
323
+ continue
324
+ return matches
325
+
326
+
327
+ def _classify_match_files(matching_files: list[str]) -> dict:
328
+ """Classify a list of matching file paths.
329
+
330
+ Returns:
331
+ {
332
+ 'frontend': [...], # .vue, .ts, .js etc.
333
+ 'backend_test': [...], # PHP test/spec files
334
+ 'backend_other': [...], # seeders, factories, other PHP
335
+ 'docs': [...], # .md etc.
336
+ }
337
+ """
338
+ result: dict[str, list] = {
339
+ "frontend": [],
340
+ "backend_test": [],
341
+ "backend_other": [],
342
+ "docs": [],
343
+ }
344
+ for f in matching_files:
345
+ norm = f.replace("\\", "/")
346
+ ext = os.path.splitext(f)[1].lower()
347
+ if ext in _FRONTEND_EXTENSIONS:
348
+ result["frontend"].append(f)
349
+ elif ext in _BACKEND_EXTENSIONS:
350
+ if _BACKEND_TEST_PATTERNS.search(norm):
351
+ result["backend_test"].append(f)
352
+ else:
353
+ result["backend_other"].append(f)
354
+ elif ext in {".md", ".rst", ".txt"}:
355
+ result["docs"].append(f)
356
+ # else: ignore binary, lock files, etc.
357
+ return result
358
+
359
+
360
+ def _determine_confidence(classified: dict) -> str:
361
+ """Compute orphan confidence from classified match files.
362
+
363
+ high: no references at all (outside route files + controller)
364
+ medium: referenced in backend-only files (tests/seeders) but not frontend
365
+ low: referenced in docs/comments only
366
+ """
367
+ if classified["frontend"]:
368
+ return "used" # has a consumer — not orphan
369
+
370
+ if not any(classified.values()):
371
+ return "high"
372
+
373
+ if classified["backend_test"] or classified["backend_other"]:
374
+ return "medium"
375
+
376
+ if classified["docs"]:
377
+ return "low"
378
+
379
+ return "high"
380
+
381
+
382
+ # ---------------------------------------------------------------------------
383
+ # Controller method analysis
384
+ # ---------------------------------------------------------------------------
385
+
386
+ _RE_PUBLIC_METHOD = re.compile(
387
+ r"public\s+function\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(",
388
+ re.IGNORECASE,
389
+ )
390
+
391
+
392
+ def _extract_controller_public_methods(project_root: Path, controller_name: str) -> list[str]:
393
+ """Find public methods in a controller PHP file.
394
+
395
+ Returns a list of method names.
396
+ """
397
+ if not controller_name:
398
+ return []
399
+
400
+ # Search for the controller file
401
+ matches = _search_with_git_grep(
402
+ f"class {controller_name}",
403
+ project_root,
404
+ ["--", "*.php"],
405
+ )
406
+
407
+ for rel_path in matches:
408
+ full = project_root / rel_path
409
+ try:
410
+ source = full.read_text(encoding="utf-8", errors="replace")
411
+ except OSError:
412
+ continue
413
+
414
+ methods = _RE_PUBLIC_METHOD.findall(source)
415
+ # Filter out magic methods
416
+ return [m for m in methods if not m.startswith("__")]
417
+
418
+ return []
419
+
420
+
421
+ def _find_routed_actions(routes: list[dict]) -> dict[str, set]:
422
+ """Build a map of controller → set of routed action names."""
423
+ routed: dict[str, set] = defaultdict(set)
424
+ for r in routes:
425
+ if r["controller"] and r["action"]:
426
+ routed[r["controller"]].add(r["action"])
427
+ return routed
428
+
429
+
430
+ # ---------------------------------------------------------------------------
431
+ # Main analysis
432
+ # ---------------------------------------------------------------------------
433
+
434
+
435
+ def _analyse_orphan_routes(project_root: Path, conn, limit: int) -> dict:
436
+ """Run the full orphan routes analysis.
437
+
438
+ Returns a dict with:
439
+ routes_total, routes_with_consumers, orphans (list), unrouted_methods (list)
440
+ """
441
+ # Step 1: Locate and parse route files
442
+ route_files = _find_route_files(project_root)
443
+ all_routes: list[dict] = []
444
+ for rf in route_files:
445
+ all_routes.extend(_extract_routes_from_file(rf))
446
+
447
+ # Filter skippable routes
448
+ all_routes = [r for r in all_routes if not _should_skip_route(r)]
449
+
450
+ # Also get the set of all indexed file paths from the DB (for fallback search)
451
+ indexed_files = [row["path"] for row in conn.execute("SELECT path FROM files").fetchall()]
452
+
453
+ # Determine which route files and controller files to exclude from consumer search
454
+ route_file_prefixes = set()
455
+ for rf in route_files:
456
+ try:
457
+ rel = str(rf.relative_to(project_root)).replace("\\", "/")
458
+ except ValueError:
459
+ rel = str(rf)
460
+ route_file_prefixes.add(rel)
461
+
462
+ orphans: list[dict] = []
463
+ routes_with_consumers = 0
464
+
465
+ for route in all_routes:
466
+ segments = _path_segments(route["path"])
467
+ if not segments:
468
+ # Path has no meaningful segments (e.g. '/' or '/api')
469
+ routes_with_consumers += 1
470
+ continue
471
+
472
+ # Collect all files that reference any segment of this route
473
+ all_matching: list[str] = []
474
+
475
+ for segment in segments:
476
+ if len(segment) < 3:
477
+ # Too short (e.g. 'id') — too noisy to search
478
+ continue
479
+
480
+ # Primary: git grep (fastest)
481
+ found = _search_with_git_grep(segment, project_root)
482
+ if not found:
483
+ # Fallback: manual search in indexed files
484
+ found = _search_in_files(segment, project_root, indexed_files)
485
+
486
+ all_matching.extend(found)
487
+
488
+ # Deduplicate
489
+ all_matching = list(set(all_matching))
490
+
491
+ # Remove the route files themselves and the controller file from matches
492
+ controller_name = route.get("controller") or ""
493
+
494
+ def _is_self_reference(file_path: str) -> bool:
495
+ norm = file_path.replace("\\", "/")
496
+ # Exclude the route definition files
497
+ if norm in route_file_prefixes:
498
+ return True
499
+ # Exclude the controller file itself
500
+ if controller_name and controller_name.lower() in norm.lower():
501
+ # Check it actually looks like a controller path
502
+ if "controller" in norm.lower() or "http" in norm.lower():
503
+ return True
504
+ return False
505
+
506
+ consumer_files = [f for f in all_matching if not _is_self_reference(f)]
507
+
508
+ classified = _classify_match_files(consumer_files)
509
+ confidence = _determine_confidence(classified)
510
+
511
+ if confidence == "used":
512
+ routes_with_consumers += 1
513
+ continue
514
+
515
+ # It's an orphan candidate
516
+ orphan = {
517
+ "confidence": confidence,
518
+ "method": route["method"],
519
+ "path": route["path"],
520
+ "controller": route["controller"],
521
+ "action": route["action"],
522
+ "file": route["file"],
523
+ "line": route["line"],
524
+ "found_in": {
525
+ "backend_test": classified["backend_test"][:3],
526
+ "backend_other": classified["backend_other"][:3],
527
+ "docs": classified["docs"][:3],
528
+ },
529
+ }
530
+ orphans.append(orphan)
531
+
532
+ # Sort: high → medium → low
533
+ _confidence_order = {"high": 0, "medium": 1, "low": 2}
534
+ orphans.sort(key=lambda o: _confidence_order.get(o["confidence"], 9))
535
+
536
+ if limit:
537
+ orphans = orphans[:limit]
538
+
539
+ # Step 2: Find controller methods that aren't mapped to any route
540
+ routed_actions = _find_routed_actions(all_routes)
541
+ unrouted_methods: list[dict] = []
542
+
543
+ seen_controllers: set[str] = set()
544
+ for route in all_routes:
545
+ ctrl = route.get("controller")
546
+ if not ctrl or ctrl in seen_controllers:
547
+ continue
548
+ seen_controllers.add(ctrl)
549
+
550
+ all_methods = _extract_controller_public_methods(project_root, ctrl)
551
+ mapped = routed_actions.get(ctrl, set())
552
+ for method in all_methods:
553
+ if method not in mapped:
554
+ # Also skip common Laravel lifecycle / base methods
555
+ if method in {
556
+ "callAction",
557
+ "middleware",
558
+ "getMiddleware",
559
+ "authorize",
560
+ "authorizeResource",
561
+ "authorizeForUser",
562
+ "dispatch",
563
+ "dispatchNow",
564
+ "validate",
565
+ "validateWithBag",
566
+ }:
567
+ continue
568
+ unrouted_methods.append(
569
+ {
570
+ "controller": ctrl,
571
+ "method": method,
572
+ }
573
+ )
574
+
575
+ return {
576
+ "routes_total": len(all_routes),
577
+ "routes_with_consumers": routes_with_consumers,
578
+ "orphans": orphans,
579
+ "unrouted_methods": unrouted_methods,
580
+ }
581
+
582
+
583
+ # ---------------------------------------------------------------------------
584
+ # CLI command
585
+ # ---------------------------------------------------------------------------
586
+
587
+
588
+ @click.command("orphan-routes")
589
+ @click.option("--limit", "-n", default=50, show_default=True, help="Maximum number of orphan findings to show")
590
+ @click.option(
591
+ "--confidence",
592
+ "confidence_filter",
593
+ default=None,
594
+ type=click.Choice(["high", "medium", "low"], case_sensitive=False),
595
+ help="Only show orphans of a specific confidence level",
596
+ )
597
+ @click.option(
598
+ "--no-unrouted",
599
+ "skip_unrouted",
600
+ is_flag=True,
601
+ default=False,
602
+ help="Skip controller method analysis (faster)",
603
+ )
604
+ @click.pass_context
605
+ def orphan_routes_cmd(ctx, limit, confidence_filter, skip_unrouted):
606
+ """Find backend API routes that have no frontend consumers (dead endpoints).
607
+
608
+ Parses routes/api.php and routes/web.php, extracts route definitions,
609
+ then searches the codebase for references to each route's path segments.
610
+
611
+ Confidence levels:
612
+
613
+ \b
614
+ high: path segment not found in any file outside route files / controller
615
+ medium: path found only in backend files (tests, seeders) — not frontend
616
+ low: path found only in docs or comments
617
+
618
+ Skips infrastructure routes (telescope, horizon, health checks, webhooks).
619
+ Also reports public controller methods that are not mapped to any route.
620
+ """
621
+ json_mode = ctx.obj.get("json") if ctx.obj else False
622
+ ensure_index()
623
+
624
+ project_root = find_project_root()
625
+
626
+ with open_db(readonly=True) as conn:
627
+ result = _analyse_orphan_routes(project_root, conn, limit)
628
+
629
+ orphans = result["orphans"]
630
+ unrouted = result["unrouted_methods"]
631
+ routes_total = result["routes_total"]
632
+ routes_with_consumers = result["routes_with_consumers"]
633
+
634
+ # Apply confidence filter if requested
635
+ if confidence_filter:
636
+ orphans = [o for o in orphans if o["confidence"] == confidence_filter.lower()]
637
+
638
+ n_high = sum(1 for o in orphans if o["confidence"] == "high")
639
+ n_medium = sum(1 for o in orphans if o["confidence"] == "medium")
640
+ n_low = sum(1 for o in orphans if o["confidence"] == "low")
641
+
642
+ if routes_total == 0:
643
+ msg = "No routes found. Ensure routes/api.php or routes/web.php exist and the roam index is up to date."
644
+ if json_mode:
645
+ click.echo(
646
+ to_json(
647
+ json_envelope(
648
+ "orphan-routes",
649
+ summary={"verdict": "no routes found", "error": msg},
650
+ )
651
+ )
652
+ )
653
+ else:
654
+ click.echo(msg)
655
+ return
656
+
657
+ # --- JSON output ---
658
+ if json_mode:
659
+ clean_orphans = []
660
+ for o in orphans:
661
+ entry = {
662
+ "confidence": o["confidence"],
663
+ "method": o["method"],
664
+ "path": o["path"],
665
+ "location": loc(o["file"], o["line"]),
666
+ }
667
+ if o["controller"]:
668
+ entry["controller"] = o["controller"]
669
+ entry["action"] = o["action"]
670
+ refs = {k: v for k, v in o["found_in"].items() if v}
671
+ if refs:
672
+ entry["referenced_in"] = refs
673
+ clean_orphans.append(entry)
674
+
675
+ clean_unrouted = (
676
+ [] if skip_unrouted else [{"controller": u["controller"], "method": u["method"]} for u in unrouted]
677
+ )
678
+
679
+ click.echo(
680
+ to_json(
681
+ json_envelope(
682
+ "orphan-routes",
683
+ summary={
684
+ "verdict": f"{len(orphans)} orphan routes found "
685
+ f"({n_high} high, {n_medium} medium, {n_low} low)",
686
+ "routes_total": routes_total,
687
+ "routes_with_consumers": routes_with_consumers,
688
+ "orphans_found": len(orphans),
689
+ "high": n_high,
690
+ "medium": n_medium,
691
+ "low": n_low,
692
+ "unrouted_controller_methods": len(clean_unrouted),
693
+ },
694
+ orphans=clean_orphans,
695
+ unrouted_methods=clean_unrouted,
696
+ )
697
+ )
698
+ )
699
+ return
700
+
701
+ # --- Text output ---
702
+ click.echo("=== Orphan Routes ===\n")
703
+ click.echo(f"VERDICT: {len(orphans)} orphan routes found ({n_high} high, {n_medium} medium, {n_low} low)")
704
+ click.echo()
705
+ click.echo(f" Routes defined: {routes_total}")
706
+ click.echo(f" Routes with consumers: {routes_with_consumers}")
707
+ click.echo(f" Potentially orphaned: {len(orphans)}")
708
+ click.echo()
709
+
710
+ if not orphans:
711
+ click.echo(" All routes appear to have consumers — no orphans detected.")
712
+ else:
713
+ for o in orphans:
714
+ conf_label = f"[{o['confidence']}]"
715
+ controller_str = ""
716
+ if o["controller"] and o["action"]:
717
+ controller_str = f"\n Controller: {o['controller']}::{o['action']}"
718
+ elif o["controller"]:
719
+ controller_str = f"\n Controller: {o['controller']}"
720
+
721
+ location_str = loc(o["file"], o["line"])
722
+
723
+ refs = {k: v for k, v in o["found_in"].items() if v}
724
+ if refs:
725
+ ref_parts = []
726
+ for kind, files in refs.items():
727
+ label = {
728
+ "backend_test": "tests",
729
+ "backend_other": "backend",
730
+ "docs": "docs",
731
+ }.get(kind, kind)
732
+ ref_parts.append(f"{label}: {', '.join(files[:2])}")
733
+ ref_str = f"\n Only referenced in: {'; '.join(ref_parts)}"
734
+ else:
735
+ ref_str = "\n No references found in codebase"
736
+
737
+ click.echo(f" {conf_label:<10} {o['method']} {o['path']} {location_str}{controller_str}{ref_str}")
738
+ click.echo()
739
+
740
+ if not skip_unrouted and unrouted:
741
+ click.echo(f"-- Controller methods with no route mapping ({len(unrouted)}) --\n")
742
+ rows = []
743
+ for u in unrouted[:30]:
744
+ rows.append([u["controller"], u["method"]])
745
+ click.echo(
746
+ format_table(
747
+ ["Controller", "Method"],
748
+ rows,
749
+ budget=30,
750
+ )
751
+ )
752
+ if len(unrouted) > 30:
753
+ click.echo(f" (+{len(unrouted) - 30} more)")
754
+ click.echo()