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,1151 @@
1
+ """Get the minimal context needed to safely modify a symbol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+
7
+ import click
8
+
9
+ from roam.commands.changed_files import is_test_file
10
+ from roam.commands.context_helpers import (
11
+ batch_context as _batch_context,
12
+ )
13
+ from roam.commands.context_helpers import (
14
+ gather_annotations as _gather_annotations,
15
+ )
16
+ from roam.commands.context_helpers import (
17
+ gather_symbol_context as _gather_symbol_context,
18
+ )
19
+ from roam.commands.context_helpers import (
20
+ gather_task_extras as _gather_task_extras,
21
+ )
22
+ from roam.commands.context_helpers import (
23
+ get_coupling as _get_coupling,
24
+ )
25
+ from roam.commands.next_steps import format_next_steps_text, suggest_next_steps
26
+ from roam.commands.resolve import ensure_index, file_not_found_hint, find_symbol, symbol_not_found
27
+ from roam.db.connection import batched_in, open_db
28
+ from roam.db.queries import FILE_BY_PATH
29
+ from roam.output.formatter import abbrev_kind, format_table, json_envelope, loc, to_json
30
+
31
+ _TASK_CHOICES = ["refactor", "debug", "extend", "review", "understand"]
32
+
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Task-mode text output helpers
36
+ # ---------------------------------------------------------------------------
37
+
38
+
39
+ def _render_complexity_text(metrics):
40
+ if not metrics:
41
+ return
42
+ click.echo("Complexity:")
43
+ click.echo(
44
+ f" cognitive={metrics['cognitive_complexity']:.0f} "
45
+ f"nesting={metrics['nesting_depth']} "
46
+ f"params={metrics['param_count']} "
47
+ f"lines={metrics['line_count']} "
48
+ f"returns={metrics['return_count']} "
49
+ f"bool_ops={metrics['bool_op_count']} "
50
+ f"callbacks={metrics['callback_depth']}"
51
+ )
52
+ click.echo()
53
+
54
+
55
+ def _render_graph_centrality_text(metrics):
56
+ if not metrics:
57
+ return
58
+ click.echo("Graph centrality:")
59
+ click.echo(
60
+ f" pagerank={metrics['pagerank']:.6f} "
61
+ f"in_degree={metrics['in_degree']} "
62
+ f"out_degree={metrics['out_degree']} "
63
+ f"betweenness={metrics['betweenness']:.6f}"
64
+ )
65
+ click.echo()
66
+
67
+
68
+ def _render_churn_text(churn):
69
+ if not churn:
70
+ return
71
+ click.echo("Git churn (file):")
72
+ click.echo(
73
+ f" commits={churn['commit_count']} total_churn={churn['total_churn']} authors={churn['distinct_authors']}"
74
+ )
75
+ click.echo()
76
+
77
+
78
+ def _render_coupling_text(coupling):
79
+ if not coupling:
80
+ return
81
+ click.echo(f"Temporal coupling ({len(coupling)} partners):")
82
+ rows = [[c["path"], f"{c['strength']:.0%}", str(c["cochange_count"])] for c in coupling[:10]]
83
+ click.echo(format_table(["file", "strength", "co-changes"], rows))
84
+ click.echo()
85
+
86
+
87
+ def _render_affected_tests_text(tests):
88
+ if not tests:
89
+ click.echo("Affected tests: (none found via BFS)")
90
+ click.echo()
91
+ return
92
+ direct = sum(1 for t in tests if t["kind"] == "DIRECT")
93
+ transitive = sum(1 for t in tests if t["kind"] == "TRANSITIVE")
94
+ click.echo(f"Affected tests ({direct} direct, {transitive} transitive):")
95
+ for t in tests[:15]:
96
+ via_str = f" via {t['via']}" if t.get("via") else ""
97
+ hops = t["hops"]
98
+ click.echo(f" {t['kind']:<12s} {t['file']}::{t['symbol']} ({hops} hop{'s' if hops != 1 else ''}{via_str})")
99
+ if len(tests) > 15:
100
+ click.echo(f" (+{len(tests) - 15} more)")
101
+ click.echo()
102
+
103
+
104
+ def _render_blast_radius_text(blast):
105
+ if not blast:
106
+ return
107
+ click.echo("Blast radius:")
108
+ click.echo(f" {blast['dependent_symbols']} dependent symbols in {blast['dependent_files']} files")
109
+ click.echo()
110
+
111
+
112
+ def _render_cluster_text(cluster):
113
+ if not cluster:
114
+ return
115
+ click.echo(f"Cluster: {cluster['cluster_label']} ({cluster['cluster_size']} symbols)")
116
+ names = ", ".join(m["name"] for m in cluster["top_members"][:6])
117
+ if cluster["cluster_size"] > 6:
118
+ names += f" +{cluster['cluster_size'] - 6} more"
119
+ click.echo(f" members: {names}")
120
+ click.echo()
121
+
122
+
123
+ def _render_similar_symbols_text(similar):
124
+ if not similar:
125
+ return
126
+ click.echo(f"Similar symbols ({len(similar)}):")
127
+ rows = [[abbrev_kind(s["kind"]), s["name"], s["location"]] for s in similar[:10]]
128
+ click.echo(format_table(["kind", "name", "location"], rows))
129
+ click.echo()
130
+
131
+
132
+ def _render_entry_points_text(entries):
133
+ if not entries:
134
+ return
135
+ click.echo(f"Entry points reaching this ({len(entries)}):")
136
+ rows = [[abbrev_kind(e["kind"]), e["name"], e["location"]] for e in entries]
137
+ click.echo(format_table(["kind", "name", "location"], rows))
138
+ click.echo()
139
+
140
+
141
+ def _render_file_context_text(file_context):
142
+ if not file_context:
143
+ return
144
+ click.echo(f"File context ({len(file_context)} other exports):")
145
+ for fc in file_context[:15]:
146
+ doc = " [documented]" if fc["has_docstring"] else ""
147
+ click.echo(f" {abbrev_kind(fc['kind'])} {fc['name']} L{fc['line']}{doc}")
148
+ if len(file_context) > 15:
149
+ click.echo(f" (+{len(file_context) - 15} more)")
150
+ click.echo()
151
+
152
+
153
+ def _render_annotations_text(annotations):
154
+ if not annotations:
155
+ return
156
+ click.echo(f"Annotations ({len(annotations)}):")
157
+ for a in annotations:
158
+ tag_str = f"[{a['tag']}] " if a.get("tag") else ""
159
+ author_str = f" (by {a['author']})" if a.get("author") else ""
160
+ click.echo(f" {tag_str}{a['content']}{author_str}")
161
+ click.echo()
162
+
163
+
164
+ # ---------------------------------------------------------------------------
165
+ # Task-mode output: text
166
+ # ---------------------------------------------------------------------------
167
+
168
+
169
+ def _output_task_single_text(c, task, extras):
170
+ """Render task-mode text output for a single symbol."""
171
+ sym = c["sym"]
172
+ line_start = c["line_start"]
173
+ non_test_callers = c["non_test_callers"]
174
+ callees = c["callees"]
175
+ test_callers = c["test_callers"]
176
+ test_importers = c["test_importers"]
177
+ siblings = c["siblings"]
178
+ files_to_read = c["files_to_read"]
179
+ skipped_callers = c["skipped_callers"]
180
+ skipped_callees = c["skipped_callees"]
181
+
182
+ hide_callees = extras.get("_hide_callees", False)
183
+ limit_callers = extras.get("_limit_callers")
184
+ limit_callees = extras.get("_limit_callees")
185
+
186
+ sig = sym["signature"] or ""
187
+ click.echo(f"=== Context for: {sym['name']} (task={task}) ===")
188
+ click.echo(
189
+ f"{abbrev_kind(sym['kind'])} "
190
+ f"{sym['qualified_name'] or sym['name']}"
191
+ f"{' ' + sig if sig else ''} "
192
+ f"{loc(sym['file_path'], line_start)}"
193
+ )
194
+ click.echo()
195
+
196
+ # Annotations (shown for all task modes)
197
+ _render_annotations_text(extras.get("annotations"))
198
+
199
+ # understand: show docstring first
200
+ if task == "understand" and extras.get("docstring"):
201
+ click.echo("Docstring:")
202
+ for line in extras["docstring"].strip().splitlines()[:10]:
203
+ click.echo(f" {line}")
204
+ click.echo()
205
+
206
+ # Callers
207
+ caller_cap = limit_callers or 20
208
+ if non_test_callers:
209
+ click.echo(f"Callers ({len(non_test_callers)}):")
210
+ rows = []
211
+ for cr in non_test_callers[:caller_cap]:
212
+ rows.append(
213
+ [
214
+ abbrev_kind(cr["kind"]),
215
+ cr["name"],
216
+ loc(cr["file_path"], cr["edge_line"] or cr["line_start"]),
217
+ cr["edge_kind"] or "",
218
+ ]
219
+ )
220
+ click.echo(format_table(["kind", "name", "location", "edge"], rows))
221
+ if len(non_test_callers) > caller_cap:
222
+ click.echo(f" (+{len(non_test_callers) - caller_cap} more)")
223
+ click.echo()
224
+ else:
225
+ click.echo("Callers: (none)")
226
+ click.echo()
227
+
228
+ # Callees (hidden for refactor, limited for understand)
229
+ if not hide_callees:
230
+ callee_cap = limit_callees or 15
231
+ if callees:
232
+ click.echo(f"Callees ({len(callees)}):")
233
+ rows = []
234
+ for ce in callees[:callee_cap]:
235
+ rows.append(
236
+ [
237
+ abbrev_kind(ce["kind"]),
238
+ ce["name"],
239
+ loc(ce["file_path"], ce["line_start"]),
240
+ ce["edge_kind"] or "",
241
+ ]
242
+ )
243
+ click.echo(format_table(["kind", "name", "location", "edge"], rows))
244
+ if len(callees) > callee_cap:
245
+ click.echo(f" (+{len(callees) - callee_cap} more)")
246
+ click.echo()
247
+ else:
248
+ click.echo("Callees: (none)")
249
+ click.echo()
250
+
251
+ # Tests (default for non-review/debug; those use BFS affected_tests)
252
+ if task not in ("review", "debug"):
253
+ if test_callers or test_importers:
254
+ click.echo(f"Tests ({len(test_callers)} direct, {len(test_importers)} file-level):")
255
+ for t in test_callers:
256
+ click.echo(f" {abbrev_kind(t['kind'])} {t['name']} {loc(t['file_path'], t['line_start'])}")
257
+ for ti in test_importers:
258
+ click.echo(f" file {ti['path']}")
259
+ else:
260
+ click.echo("Tests: (none)")
261
+ click.echo()
262
+
263
+ # Siblings (shown for refactor, understand)
264
+ if task in ("refactor", "understand") and siblings:
265
+ click.echo(f"Siblings ({len(siblings)} exports in same file):")
266
+ for s in siblings[:10]:
267
+ click.echo(f" {abbrev_kind(s['kind'])} {s['name']}")
268
+ if len(siblings) > 10:
269
+ click.echo(f" (+{len(siblings) - 10} more)")
270
+ click.echo()
271
+
272
+ # Task-specific extra sections
273
+ if task == "refactor":
274
+ _render_complexity_text(extras.get("complexity"))
275
+ _render_graph_centrality_text(extras.get("graph_centrality"))
276
+ _render_coupling_text(extras.get("coupling"))
277
+
278
+ elif task == "debug":
279
+ _render_complexity_text(extras.get("complexity"))
280
+ _render_affected_tests_text(extras.get("affected_tests", []))
281
+
282
+ elif task == "extend":
283
+ _render_graph_centrality_text(extras.get("graph_centrality"))
284
+ _render_similar_symbols_text(extras.get("similar_symbols", []))
285
+ _render_entry_points_text(extras.get("entry_points_reaching", []))
286
+
287
+ elif task == "review":
288
+ _render_complexity_text(extras.get("complexity"))
289
+ _render_churn_text(extras.get("git_churn"))
290
+ _render_affected_tests_text(extras.get("affected_tests", []))
291
+ _render_coupling_text(extras.get("coupling"))
292
+ _render_blast_radius_text(extras.get("blast_radius"))
293
+ _render_graph_centrality_text(extras.get("graph_centrality"))
294
+
295
+ elif task == "understand":
296
+ _render_cluster_text(extras.get("cluster"))
297
+ _render_graph_centrality_text(extras.get("graph_centrality"))
298
+ _render_file_context_text(extras.get("file_context", []))
299
+
300
+ # Files to read
301
+ skipped_total = skipped_callers + skipped_callees
302
+ extra_label = f", +{skipped_total} more" if skipped_total else ""
303
+ click.echo(f"Files to read ({len(files_to_read)}{extra_label}):")
304
+ for f in files_to_read:
305
+ end_str = f"-{f['end']}" if f["end"] and f["end"] != f["start"] else ""
306
+ lr = f":{f['start']}{end_str}" if f["start"] else ""
307
+ click.echo(f" {f['path']:<50s} {lr:<12s} ({f['reason']})")
308
+
309
+
310
+ # ---------------------------------------------------------------------------
311
+ # Task-mode output: JSON
312
+ # ---------------------------------------------------------------------------
313
+
314
+
315
+ def _output_task_single_json(c, task, extras, budget=0):
316
+ """Build and emit JSON output for task-mode single symbol."""
317
+ sym = c["sym"]
318
+ line_start = c["line_start"]
319
+ line_end = c["line_end"]
320
+ non_test_callers = c["non_test_callers"]
321
+ callees = c["callees"]
322
+ test_callers = c["test_callers"]
323
+ test_importers = c["test_importers"]
324
+ siblings = c["siblings"]
325
+ files_to_read = c["files_to_read"]
326
+
327
+ hide_callees = extras.get("_hide_callees", False)
328
+ limit_callers = extras.get("_limit_callers")
329
+ limit_callees = extras.get("_limit_callees")
330
+
331
+ caller_cap = limit_callers or len(non_test_callers)
332
+ callee_cap = limit_callees or len(callees)
333
+
334
+ payload = {
335
+ "task": task,
336
+ "symbol": sym["qualified_name"] or sym["name"],
337
+ "kind": sym["kind"],
338
+ "signature": sym["signature"] or "",
339
+ "location": loc(sym["file_path"], line_start),
340
+ "definition": {
341
+ "file": sym["file_path"],
342
+ "start": line_start,
343
+ "end": line_end,
344
+ },
345
+ "callers": [
346
+ {
347
+ "name": cr["name"],
348
+ "kind": cr["kind"],
349
+ "location": loc(
350
+ cr["file_path"],
351
+ cr["edge_line"] or cr["line_start"],
352
+ ),
353
+ "edge_kind": cr["edge_kind"] or "",
354
+ }
355
+ for cr in non_test_callers[:caller_cap]
356
+ ],
357
+ }
358
+
359
+ if not hide_callees:
360
+ payload["callees"] = [
361
+ {
362
+ "name": ce["name"],
363
+ "kind": ce["kind"],
364
+ "location": loc(ce["file_path"], ce["line_start"]),
365
+ "edge_kind": ce["edge_kind"] or "",
366
+ }
367
+ for ce in callees[:callee_cap]
368
+ ]
369
+
370
+ if task not in ("review", "debug"):
371
+ payload["tests"] = [
372
+ {
373
+ "name": t["name"],
374
+ "kind": t["kind"],
375
+ "location": loc(t["file_path"], t["line_start"]),
376
+ "edge_kind": t["edge_kind"] or "",
377
+ }
378
+ for t in test_callers
379
+ ]
380
+ payload["test_files"] = [r["path"] for r in test_importers]
381
+
382
+ if task in ("refactor", "understand"):
383
+ payload["siblings"] = [{"name": s["name"], "kind": s["kind"]} for s in siblings[:10]]
384
+
385
+ # Annotations
386
+ anns = extras.get("annotations")
387
+ if anns:
388
+ payload["annotations"] = anns
389
+
390
+ # Task-specific extras
391
+ for key in (
392
+ "docstring",
393
+ "complexity",
394
+ "graph_centrality",
395
+ "git_churn",
396
+ "blast_radius",
397
+ "cluster",
398
+ ):
399
+ val = extras.get(key)
400
+ if val is not None:
401
+ payload[key] = val
402
+
403
+ for key in (
404
+ "coupling",
405
+ "affected_tests",
406
+ "similar_symbols",
407
+ "entry_points_reaching",
408
+ "file_context",
409
+ ):
410
+ val = extras.get(key)
411
+ if val:
412
+ payload[key] = val
413
+
414
+ payload["files_to_read"] = [
415
+ {
416
+ "path": f["path"],
417
+ "start": f["start"],
418
+ "end": f["end"],
419
+ "reason": f["reason"],
420
+ "score": f.get("score"),
421
+ "rank": f.get("rank"),
422
+ }
423
+ for f in files_to_read
424
+ ]
425
+
426
+ # Summary
427
+ summary = {"task": task, "callers": len(non_test_callers)}
428
+ if not hide_callees:
429
+ summary["callees"] = len(callees)
430
+ summary["tests"] = len(test_callers)
431
+ summary["files_to_read"] = len(files_to_read)
432
+
433
+ if extras.get("blast_radius"):
434
+ summary["blast_radius_symbols"] = extras["blast_radius"]["dependent_symbols"]
435
+ summary["blast_radius_files"] = extras["blast_radius"]["dependent_files"]
436
+ if extras.get("affected_tests") is not None:
437
+ summary["affected_tests_total"] = len(extras["affected_tests"])
438
+ if extras.get("coupling"):
439
+ summary["coupling_partners"] = len(extras["coupling"])
440
+
441
+ click.echo(to_json(json_envelope("context", summary=summary, budget=budget, **payload)))
442
+
443
+
444
+ # ---------------------------------------------------------------------------
445
+ # File-level context: --for-file
446
+ # ---------------------------------------------------------------------------
447
+
448
+
449
+ def _resolve_file(conn, path):
450
+ """Resolve a file path to its DB row, or None."""
451
+ path = path.replace("\\", "/")
452
+ frow = conn.execute(FILE_BY_PATH, (path,)).fetchone()
453
+ if frow is None:
454
+ frow = conn.execute(
455
+ "SELECT * FROM files WHERE path LIKE ? LIMIT 1",
456
+ (f"%{path}",),
457
+ ).fetchone()
458
+ return frow
459
+
460
+
461
+ def _gather_file_level_context(conn, frow):
462
+ """Gather comprehensive file-level context.
463
+
464
+ Returns a dict with callers, callees, tests, coupling, and complexity
465
+ aggregated across all symbols in the file.
466
+ """
467
+ file_id = frow["id"]
468
+ file_path = frow["path"]
469
+
470
+ # Get all symbols in the file
471
+ symbols = conn.execute(
472
+ "SELECT s.*, f.path as file_path "
473
+ "FROM symbols s JOIN files f ON s.file_id = f.id "
474
+ "WHERE s.file_id = ? ORDER BY s.line_start",
475
+ (file_id,),
476
+ ).fetchall()
477
+
478
+ sym_ids = [s["id"] for s in symbols]
479
+ if not sym_ids:
480
+ return {
481
+ "file_path": file_path,
482
+ "symbol_count": 0,
483
+ "callers": [],
484
+ "callees": [],
485
+ "tests": [],
486
+ "coupling": [],
487
+ "complexity": None,
488
+ }
489
+
490
+ # --- Callers: symbols in OTHER files that reference symbols in this file ---
491
+ caller_rows = batched_in(
492
+ conn,
493
+ "SELECT e.target_id, s.name as caller_name, s.kind as caller_kind, "
494
+ "f.path as caller_file, s.line_start as caller_line, "
495
+ "ts.name as target_name "
496
+ "FROM edges e "
497
+ "JOIN symbols s ON e.source_id = s.id "
498
+ "JOIN files f ON s.file_id = f.id "
499
+ "JOIN symbols ts ON e.target_id = ts.id "
500
+ "WHERE e.target_id IN ({ph}) AND s.file_id != ?",
501
+ sym_ids,
502
+ post=[file_id],
503
+ )
504
+
505
+ # Group callers by source file
506
+ callers_by_file = defaultdict(list)
507
+ for r in caller_rows:
508
+ if not is_test_file(r["caller_file"]):
509
+ callers_by_file[r["caller_file"]].append(r["target_name"])
510
+
511
+ callers = []
512
+ for cfile, targets in sorted(callers_by_file.items()):
513
+ unique_targets = sorted(set(targets))
514
+ callers.append(
515
+ {
516
+ "file": cfile,
517
+ "symbols": unique_targets,
518
+ "count": len(unique_targets),
519
+ }
520
+ )
521
+
522
+ # --- Callees: symbols in OTHER files that this file's symbols reference ---
523
+ callee_rows = batched_in(
524
+ conn,
525
+ "SELECT e.source_id, s.name as callee_name, s.kind as callee_kind, "
526
+ "f.path as callee_file, s.line_start as callee_line "
527
+ "FROM edges e "
528
+ "JOIN symbols s ON e.target_id = s.id "
529
+ "JOIN files f ON s.file_id = f.id "
530
+ "WHERE e.source_id IN ({ph}) AND s.file_id != ?",
531
+ sym_ids,
532
+ post=[file_id],
533
+ )
534
+
535
+ # Group callees by target file
536
+ callees_by_file = defaultdict(list)
537
+ for r in callee_rows:
538
+ callees_by_file[r["callee_file"]].append(r["callee_name"])
539
+
540
+ callees = []
541
+ for cfile, names in sorted(callees_by_file.items()):
542
+ unique_names = sorted(set(names))
543
+ callees.append(
544
+ {
545
+ "file": cfile,
546
+ "symbols": unique_names,
547
+ "count": len(unique_names),
548
+ }
549
+ )
550
+
551
+ # --- Tests: test files that reference any symbol in this file ---
552
+ test_caller_rows = batched_in(
553
+ conn,
554
+ "SELECT DISTINCT f.path "
555
+ "FROM edges e "
556
+ "JOIN symbols s ON e.source_id = s.id "
557
+ "JOIN files f ON s.file_id = f.id "
558
+ "WHERE e.target_id IN ({ph}) AND s.file_id != ?",
559
+ sym_ids,
560
+ post=[file_id],
561
+ )
562
+
563
+ direct_tests = sorted(set(r["path"] for r in test_caller_rows if is_test_file(r["path"])))
564
+
565
+ # Also check file_edges for file-level test importers
566
+ test_importers = conn.execute(
567
+ "SELECT f.path FROM file_edges fe JOIN files f ON fe.source_file_id = f.id WHERE fe.target_file_id = ?",
568
+ (file_id,),
569
+ ).fetchall()
570
+ file_level_tests = sorted(set(r["path"] for r in test_importers if is_test_file(r["path"])))
571
+
572
+ # Merge direct + file-level, mark kind
573
+ test_set = set()
574
+ tests = []
575
+ for t in direct_tests:
576
+ test_set.add(t)
577
+ tests.append({"file": t, "kind": "direct"})
578
+ for t in file_level_tests:
579
+ if t not in test_set:
580
+ test_set.add(t)
581
+ tests.append({"file": t, "kind": "file-level"})
582
+
583
+ # --- Coupling ---
584
+ coupling = _get_coupling(conn, file_path, limit=10)
585
+
586
+ # --- Complexity summary ---
587
+ metrics_rows = batched_in(
588
+ conn,
589
+ "SELECT sm.* FROM symbol_metrics sm WHERE sm.symbol_id IN ({ph})",
590
+ sym_ids,
591
+ )
592
+
593
+ complexity = None
594
+ if metrics_rows:
595
+ cc_values = [r["cognitive_complexity"] for r in metrics_rows]
596
+ threshold = 15
597
+ complexity = {
598
+ "avg": round(sum(cc_values) / len(cc_values), 1),
599
+ "max": max(cc_values),
600
+ "count_above_threshold": sum(1 for v in cc_values if v > threshold),
601
+ "threshold": threshold,
602
+ "measured_symbols": len(cc_values),
603
+ }
604
+
605
+ return {
606
+ "file_path": file_path,
607
+ "language": frow["language"],
608
+ "line_count": frow["line_count"],
609
+ "symbol_count": len(symbols),
610
+ "callers": callers,
611
+ "callees": callees,
612
+ "tests": tests,
613
+ "coupling": coupling,
614
+ "complexity": complexity,
615
+ }
616
+
617
+
618
+ def _output_file_context_text(data):
619
+ """Render --for-file context as text."""
620
+ click.echo(f"Context for {data['file_path']} ({data['symbol_count']} symbols):")
621
+ click.echo()
622
+
623
+ # Callers
624
+ callers = data["callers"]
625
+ if callers:
626
+ click.echo(f"Callers ({len(callers)} unique files):")
627
+ for c in callers[:20]:
628
+ syms = ", ".join(c["symbols"][:3])
629
+ if len(c["symbols"]) > 3:
630
+ syms += f" +{len(c['symbols']) - 3} more"
631
+ click.echo(f" {c['file']:<50s} \u2192 {syms}")
632
+ if len(callers) > 20:
633
+ click.echo(f" (+{len(callers) - 20} more)")
634
+ click.echo()
635
+ else:
636
+ click.echo("Callers: (none)")
637
+ click.echo()
638
+
639
+ # Callees
640
+ callees = data["callees"]
641
+ if callees:
642
+ click.echo(f"Callees ({len(callees)} unique files):")
643
+ for c in callees[:20]:
644
+ syms = ", ".join(c["symbols"][:3])
645
+ if len(c["symbols"]) > 3:
646
+ syms += f" +{len(c['symbols']) - 3} more"
647
+ click.echo(f" {c['file']:<50s} \u2190 {syms}")
648
+ if len(callees) > 20:
649
+ click.echo(f" (+{len(callees) - 20} more)")
650
+ click.echo()
651
+ else:
652
+ click.echo("Callees: (none)")
653
+ click.echo()
654
+
655
+ # Tests
656
+ tests = data["tests"]
657
+ if tests:
658
+ direct = sum(1 for t in tests if t["kind"] == "direct")
659
+ file_lvl = sum(1 for t in tests if t["kind"] == "file-level")
660
+ click.echo(f"Tests ({direct} direct, {file_lvl} file-level):")
661
+ for t in tests:
662
+ click.echo(f" {t['file']} ({t['kind']})")
663
+ click.echo()
664
+ else:
665
+ click.echo("Tests: (none)")
666
+ click.echo()
667
+
668
+ # Coupling
669
+ coupling = data["coupling"]
670
+ if coupling:
671
+ click.echo(f"Coupling ({len(coupling)} partners):")
672
+ rows = [[c["path"], str(c["cochange_count"]), f"{c['strength']:.0%}"] for c in coupling[:10]]
673
+ click.echo(format_table(["file", "co-changes", "strength"], rows))
674
+ click.echo()
675
+
676
+ # Complexity
677
+ cx = data["complexity"]
678
+ if cx:
679
+ click.echo(
680
+ f"Complexity: avg={cx['avg']}, max={cx['max']}, "
681
+ f"{cx['count_above_threshold']} above threshold "
682
+ f"(>{cx['threshold']})"
683
+ )
684
+ click.echo()
685
+
686
+
687
+ def _output_file_context_json(data, budget=0):
688
+ """Render --for-file context as JSON."""
689
+ summary = {
690
+ "symbol_count": data["symbol_count"],
691
+ "caller_files": len(data["callers"]),
692
+ "callee_files": len(data["callees"]),
693
+ "test_files": len(data["tests"]),
694
+ "coupling_partners": len(data["coupling"]),
695
+ }
696
+ if data["complexity"]:
697
+ summary["complexity_avg"] = data["complexity"]["avg"]
698
+ summary["complexity_max"] = data["complexity"]["max"]
699
+
700
+ click.echo(
701
+ to_json(
702
+ json_envelope(
703
+ "context",
704
+ summary=summary,
705
+ budget=budget,
706
+ mode="file",
707
+ file=data["file_path"],
708
+ language=data.get("language"),
709
+ line_count=data.get("line_count"),
710
+ symbol_count=data["symbol_count"],
711
+ callers=data["callers"],
712
+ callees=data["callees"],
713
+ tests=data["tests"],
714
+ coupling=data["coupling"],
715
+ complexity=data["complexity"],
716
+ )
717
+ )
718
+ )
719
+
720
+
721
+ # ---------------------------------------------------------------------------
722
+ # CLI command
723
+ # ---------------------------------------------------------------------------
724
+
725
+
726
+ @click.command()
727
+ @click.argument("names", nargs=-1)
728
+ @click.option(
729
+ "--task",
730
+ "task",
731
+ type=click.Choice(_TASK_CHOICES, case_sensitive=False),
732
+ default=None,
733
+ help="Tailor context to a specific task intent: refactor, debug, extend, review, understand.",
734
+ )
735
+ @click.option(
736
+ "--for-file",
737
+ "for_file",
738
+ type=str,
739
+ default=None,
740
+ help="Get aggregated context for an entire file instead of a symbol.",
741
+ )
742
+ @click.option(
743
+ "--session-hint",
744
+ "session_hint",
745
+ type=str,
746
+ default="",
747
+ help="Optional conversation hint used to personalize files-to-read ranking.",
748
+ )
749
+ @click.option(
750
+ "--recent-symbol",
751
+ "recent_symbols",
752
+ multiple=True,
753
+ help="Recently discussed symbol(s) to bias context ranking (repeatable).",
754
+ )
755
+ @click.option(
756
+ "--no-propagation",
757
+ "no_propagation",
758
+ is_flag=True,
759
+ default=False,
760
+ help="Disable call-graph propagation ranking (use legacy PageRank-only mode).",
761
+ )
762
+ @click.pass_context
763
+ def context(ctx, names, task, for_file, session_hint, recent_symbols, no_propagation):
764
+ """Get the minimal context needed to safely modify a symbol.
765
+
766
+ Returns definition, callers, callees, tests, and the exact files
767
+ to read -- everything an AI agent needs in one shot.
768
+
769
+ Pass multiple symbol names for batch mode with shared callers analysis.
770
+
771
+ Use --for-file PATH to get file-level context: callers grouped by
772
+ source file, callees grouped by target file, tests, coupling partners,
773
+ and a complexity summary across all symbols in the file.
774
+
775
+ Use --session-hint and --recent-symbol to personalize files-to-read
776
+ ranking for long conversations.
777
+
778
+ Use --task to tailor the context to a specific agent intent:
779
+
780
+ \b
781
+ refactor - callers, siblings, complexity, coupling (safe modification)
782
+ debug - callees, callers, affected tests (execution tracing)
783
+ extend - full graph, similar symbols, conventions (integration)
784
+ review - complexity, churn, blast radius, coupling (risk assessment)
785
+ understand - docstring, cluster, architecture role (comprehension)
786
+ """
787
+ json_mode = ctx.obj.get("json") if ctx.obj else False
788
+ token_budget = ctx.obj.get("budget", 0) if ctx.obj else 0
789
+ ensure_index()
790
+
791
+ # --- File-level context mode ---
792
+ if for_file:
793
+ with open_db(readonly=True) as conn:
794
+ frow = _resolve_file(conn, for_file)
795
+ if frow is None:
796
+ click.echo(file_not_found_hint(for_file))
797
+ raise SystemExit(1)
798
+ data = _gather_file_level_context(conn, frow)
799
+ if json_mode:
800
+ _output_file_context_json(data, budget=token_budget)
801
+ else:
802
+ _output_file_context_text(data)
803
+ return
804
+
805
+ # Require at least one symbol name if --for-file is not used
806
+ if not names:
807
+ click.echo(ctx.get_help())
808
+ return
809
+
810
+ with open_db(readonly=True) as conn:
811
+ # Resolve all symbols
812
+ resolved = []
813
+ for name in names:
814
+ sym = find_symbol(conn, name)
815
+ if sym is None:
816
+ click.echo(symbol_not_found(conn, name, json_mode=json_mode))
817
+ raise SystemExit(1)
818
+ resolved.append(sym)
819
+
820
+ # Gather context for each
821
+ use_propagation = not no_propagation
822
+ contexts = [
823
+ _gather_symbol_context(
824
+ conn,
825
+ sym,
826
+ task=task,
827
+ session_hint=session_hint,
828
+ recent_symbols=recent_symbols,
829
+ use_propagation=use_propagation,
830
+ )
831
+ for sym in resolved
832
+ ]
833
+
834
+ # --- Batch mode (task extras are ignored) ---
835
+ if len(contexts) > 1:
836
+ if task and not json_mode:
837
+ click.echo(
838
+ "Warning: task-specific extra sections are ignored in batch mode "
839
+ "(multiple symbols). Ranking still uses task/session hints.",
840
+ err=True,
841
+ )
842
+ shared_callers, shared_callees, scored_files = _batch_context(
843
+ conn,
844
+ contexts,
845
+ task=task,
846
+ session_hint=session_hint,
847
+ recent_symbols=recent_symbols,
848
+ use_propagation=use_propagation,
849
+ )
850
+
851
+ if json_mode:
852
+ click.echo(
853
+ to_json(
854
+ json_envelope(
855
+ "context",
856
+ budget=token_budget,
857
+ summary={
858
+ "symbols": len(contexts),
859
+ "shared_callers": len(shared_callers),
860
+ "shared_callees": len(shared_callees),
861
+ "files_to_read": len(scored_files),
862
+ },
863
+ mode="batch",
864
+ symbols=[
865
+ {
866
+ "name": c["sym"]["qualified_name"] or c["sym"]["name"],
867
+ "kind": c["sym"]["kind"],
868
+ "location": loc(c["sym"]["file_path"], c["line_start"]),
869
+ "callers": [
870
+ {
871
+ "name": cr["name"],
872
+ "kind": cr["kind"],
873
+ "location": loc(cr["file_path"], cr["edge_line"] or cr["line_start"]),
874
+ }
875
+ for cr in c["non_test_callers"][:20]
876
+ ],
877
+ "callees": [
878
+ {
879
+ "name": ce["name"],
880
+ "kind": ce["kind"],
881
+ "location": loc(ce["file_path"], ce["line_start"]),
882
+ }
883
+ for ce in c["callees"][:15]
884
+ ],
885
+ "tests": len(c["test_callers"]),
886
+ }
887
+ for c in contexts
888
+ ],
889
+ shared_callers=[
890
+ {
891
+ "name": c["name"],
892
+ "kind": c["kind"],
893
+ "location": loc(c["file_path"], c["line_start"]),
894
+ }
895
+ for c in shared_callers
896
+ ],
897
+ shared_callees=[
898
+ {
899
+ "name": c["name"],
900
+ "kind": c["kind"],
901
+ "location": loc(c["file_path"], c["line_start"]),
902
+ }
903
+ for c in shared_callees
904
+ ],
905
+ files_to_read=scored_files,
906
+ )
907
+ )
908
+ )
909
+ return
910
+
911
+ # Text batch output
912
+ click.echo(f"=== Batch Context ({len(contexts)} symbols) ===\n")
913
+
914
+ for c in contexts:
915
+ s = c["sym"]
916
+ sig = s["signature"] or ""
917
+ click.echo(f"--- {s['name']} ---")
918
+ click.echo(
919
+ f" {abbrev_kind(s['kind'])} "
920
+ f"{s['qualified_name'] or s['name']}"
921
+ f"{' ' + sig if sig else ''} "
922
+ f"{loc(s['file_path'], c['line_start'])}"
923
+ )
924
+ click.echo(
925
+ f" Callers: {len(c['non_test_callers'])} "
926
+ f"Callees: {len(c['callees'])} "
927
+ f"Tests: {len(c['test_callers'])}"
928
+ )
929
+ click.echo()
930
+
931
+ if shared_callers:
932
+ click.echo(f"Shared callers ({len(shared_callers)}):")
933
+ rows = [
934
+ [abbrev_kind(c["kind"]), c["name"], loc(c["file_path"], c["line_start"])]
935
+ for c in shared_callers[:15]
936
+ ]
937
+ click.echo(format_table(["kind", "name", "location"], rows))
938
+ click.echo()
939
+
940
+ if shared_callees:
941
+ click.echo(f"Shared callees ({len(shared_callees)}):")
942
+ rows = [
943
+ [abbrev_kind(c["kind"]), c["name"], loc(c["file_path"], c["line_start"])]
944
+ for c in shared_callees[:15]
945
+ ]
946
+ click.echo(format_table(["kind", "name", "location"], rows))
947
+ click.echo()
948
+
949
+ click.echo(f"Files to read ({len(scored_files)}):")
950
+ for f in scored_files[:25]:
951
+ reasons = ", ".join(f["reasons"])
952
+ rel_str = f"{f['relevance']:.0%}" if f["relevance"] > 0 else ""
953
+ click.echo(f" {f['path']:<50s} {rel_str:>5s} ({reasons})")
954
+ if len(scored_files) > 25:
955
+ click.echo(f" (+{len(scored_files) - 25} more)")
956
+ return
957
+
958
+ # --- Single symbol mode ---
959
+ c = contexts[0]
960
+ sym = c["sym"]
961
+
962
+ # Task mode: gather extras and render
963
+ if task:
964
+ extras = _gather_task_extras(conn, sym, c, task)
965
+ if json_mode:
966
+ _output_task_single_json(c, task, extras, budget=token_budget)
967
+ else:
968
+ _output_task_single_text(c, task, extras)
969
+ return
970
+
971
+ # --- Default single symbol mode (original behavior) ---
972
+ # Inject annotations if any
973
+ default_annotations = _gather_annotations(conn, sym=sym)
974
+
975
+ line_start = c["line_start"]
976
+ line_end = c["line_end"]
977
+ non_test_callers = c["non_test_callers"]
978
+ callees = c["callees"]
979
+ test_callers = c["test_callers"]
980
+ test_importers = c["test_importers"]
981
+ siblings = c["siblings"]
982
+ files_to_read = c["files_to_read"]
983
+ skipped_callers = c["skipped_callers"]
984
+ skipped_callees = c["skipped_callees"]
985
+
986
+ if json_mode:
987
+ _sym_name = sym["qualified_name"] or sym["name"]
988
+ _next_steps = suggest_next_steps(
989
+ "context",
990
+ {
991
+ "symbol": _sym_name,
992
+ "callers": len(non_test_callers),
993
+ },
994
+ )
995
+ click.echo(
996
+ to_json(
997
+ json_envelope(
998
+ "context",
999
+ budget=token_budget,
1000
+ summary={
1001
+ "callers": len(non_test_callers),
1002
+ "callees": len(callees),
1003
+ "tests": len(test_callers),
1004
+ "files_to_read": len(files_to_read),
1005
+ },
1006
+ symbol=_sym_name,
1007
+ kind=sym["kind"],
1008
+ signature=sym["signature"] or "",
1009
+ location=loc(sym["file_path"], line_start),
1010
+ definition={
1011
+ "file": sym["file_path"],
1012
+ "start": line_start,
1013
+ "end": line_end,
1014
+ },
1015
+ callers=[
1016
+ {
1017
+ "name": cr["name"],
1018
+ "kind": cr["kind"],
1019
+ "location": loc(cr["file_path"], cr["edge_line"] or cr["line_start"]),
1020
+ "edge_kind": cr["edge_kind"] or "",
1021
+ }
1022
+ for cr in non_test_callers
1023
+ ],
1024
+ callees=[
1025
+ {
1026
+ "name": ce["name"],
1027
+ "kind": ce["kind"],
1028
+ "location": loc(ce["file_path"], ce["line_start"]),
1029
+ "edge_kind": ce["edge_kind"] or "",
1030
+ }
1031
+ for ce in callees
1032
+ ],
1033
+ tests=[
1034
+ {
1035
+ "name": t["name"],
1036
+ "kind": t["kind"],
1037
+ "location": loc(t["file_path"], t["line_start"]),
1038
+ "edge_kind": t["edge_kind"] or "",
1039
+ }
1040
+ for t in test_callers
1041
+ ],
1042
+ test_files=[r["path"] for r in test_importers],
1043
+ siblings=[{"name": s["name"], "kind": s["kind"]} for s in siblings[:10]],
1044
+ annotations=default_annotations if default_annotations else [],
1045
+ files_to_read=[
1046
+ {
1047
+ "path": f["path"],
1048
+ "start": f["start"],
1049
+ "end": f["end"],
1050
+ "reason": f["reason"],
1051
+ "score": f.get("score"),
1052
+ "rank": f.get("rank"),
1053
+ }
1054
+ for f in files_to_read
1055
+ ],
1056
+ next_steps=_next_steps,
1057
+ )
1058
+ )
1059
+ )
1060
+ return
1061
+
1062
+ # --- Text output ---
1063
+ sig = sym["signature"] or ""
1064
+ click.echo(f"=== Context for: {sym['name']} ===")
1065
+ click.echo(
1066
+ f"{abbrev_kind(sym['kind'])} "
1067
+ f"{sym['qualified_name'] or sym['name']}"
1068
+ f"{' ' + sig if sig else ''} "
1069
+ f"{loc(sym['file_path'], line_start)}"
1070
+ )
1071
+ click.echo()
1072
+
1073
+ _render_annotations_text(default_annotations)
1074
+
1075
+ if non_test_callers:
1076
+ click.echo(f"Callers ({len(non_test_callers)}):")
1077
+ rows = []
1078
+ for cr in non_test_callers[:20]:
1079
+ rows.append(
1080
+ [
1081
+ abbrev_kind(cr["kind"]),
1082
+ cr["name"],
1083
+ loc(cr["file_path"], cr["edge_line"] or cr["line_start"]),
1084
+ cr["edge_kind"] or "",
1085
+ ]
1086
+ )
1087
+ click.echo(format_table(["kind", "name", "location", "edge"], rows))
1088
+ if len(non_test_callers) > 20:
1089
+ click.echo(f" (+{len(non_test_callers) - 20} more)")
1090
+ click.echo()
1091
+ else:
1092
+ click.echo("Callers: (none)")
1093
+ click.echo()
1094
+
1095
+ if callees:
1096
+ click.echo(f"Callees ({len(callees)}):")
1097
+ rows = []
1098
+ for ce in callees[:15]:
1099
+ rows.append(
1100
+ [
1101
+ abbrev_kind(ce["kind"]),
1102
+ ce["name"],
1103
+ loc(ce["file_path"], ce["line_start"]),
1104
+ ce["edge_kind"] or "",
1105
+ ]
1106
+ )
1107
+ click.echo(format_table(["kind", "name", "location", "edge"], rows))
1108
+ if len(callees) > 15:
1109
+ click.echo(f" (+{len(callees) - 15} more)")
1110
+ click.echo()
1111
+ else:
1112
+ click.echo("Callees: (none)")
1113
+ click.echo()
1114
+
1115
+ if test_callers or test_importers:
1116
+ click.echo(f"Tests ({len(test_callers)} direct, {len(test_importers)} file-level):")
1117
+ for t in test_callers:
1118
+ click.echo(f" {abbrev_kind(t['kind'])} {t['name']} {loc(t['file_path'], t['line_start'])}")
1119
+ for ti in test_importers:
1120
+ click.echo(f" file {ti['path']}")
1121
+ else:
1122
+ click.echo("Tests: (none)")
1123
+ click.echo()
1124
+
1125
+ if siblings:
1126
+ click.echo(f"Siblings ({len(siblings)} exports in same file):")
1127
+ for s in siblings[:10]:
1128
+ click.echo(f" {abbrev_kind(s['kind'])} {s['name']}")
1129
+ if len(siblings) > 10:
1130
+ click.echo(f" (+{len(siblings) - 10} more)")
1131
+ click.echo()
1132
+
1133
+ skipped_total = skipped_callers + skipped_callees
1134
+ extra = f", +{skipped_total} more" if skipped_total else ""
1135
+ click.echo(f"Files to read ({len(files_to_read)}{extra}):")
1136
+ for f in files_to_read:
1137
+ end_str = f"-{f['end']}" if f["end"] and f["end"] != f["start"] else ""
1138
+ lr = f":{f['start']}{end_str}" if f["start"] else ""
1139
+ click.echo(f" {f['path']:<50s} {lr:<12s} ({f['reason']})")
1140
+
1141
+ _sym_name = sym["qualified_name"] or sym["name"]
1142
+ _next_steps = suggest_next_steps(
1143
+ "context",
1144
+ {
1145
+ "symbol": _sym_name,
1146
+ "callers": len(non_test_callers),
1147
+ },
1148
+ )
1149
+ _ns_text = format_next_steps_text(_next_steps)
1150
+ if _ns_text:
1151
+ click.echo(_ns_text)