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,214 @@
1
+ """Generate a narrative digest comparing current metrics to the last snapshot."""
2
+
3
+ from datetime import datetime, timezone
4
+
5
+ import click
6
+
7
+ from roam.commands.metrics_history import collect_metrics, get_snapshots
8
+ from roam.commands.resolve import ensure_index
9
+ from roam.db.connection import open_db
10
+ from roam.output.formatter import json_envelope, to_json
11
+
12
+ _METRICS = [
13
+ ("health_score", "Health score"),
14
+ ("files", "Files"),
15
+ ("symbols", "Symbols"),
16
+ ("cycles", "Cycles"),
17
+ ("god_components", "God components"),
18
+ ("bottlenecks", "Bottlenecks"),
19
+ ("dead_exports", "Dead exports"),
20
+ ("layer_violations", "Violations"),
21
+ ]
22
+
23
+ # Metrics where a decrease is good (lower = healthier)
24
+ _LOWER_IS_BETTER = frozenset(
25
+ {
26
+ "cycles",
27
+ "god_components",
28
+ "bottlenecks",
29
+ "dead_exports",
30
+ "layer_violations",
31
+ }
32
+ )
33
+
34
+
35
+ def _arrow(key, delta):
36
+ """Return ▲ for improvement, ▼ for regression, empty for no change."""
37
+ if delta == 0:
38
+ return ""
39
+ if key in _LOWER_IS_BETTER:
40
+ return "\u25b2" if delta < 0 else "\u25bc"
41
+ # Higher is better (health_score, files, symbols, edges)
42
+ return "\u25b2" if delta > 0 else "\u25bc"
43
+
44
+
45
+ def _delta_str(delta):
46
+ """Format a delta value with sign."""
47
+ if delta == 0:
48
+ return "="
49
+ sign = "+" if delta > 0 else ""
50
+ return f"{sign}{delta}"
51
+
52
+
53
+ def _build_recommendations(current, previous, deltas):
54
+ """Generate actionable recommendations based on metric changes."""
55
+ recs = []
56
+
57
+ new_dead = deltas.get("dead_exports", 0)
58
+ if new_dead > 0:
59
+ recs.append(f"Run `roam dead --summary` to review {new_dead} new dead export{'s' if new_dead != 1 else ''}")
60
+
61
+ new_cycles = deltas.get("cycles", 0)
62
+ if new_cycles > 0:
63
+ recs.append(f"Run `roam health` to inspect {new_cycles} new cycle{'s' if new_cycles != 1 else ''}")
64
+
65
+ new_gods = deltas.get("god_components", 0)
66
+ if new_gods > 0:
67
+ recs.append(
68
+ f"Run `roam health --no-framework` to review {new_gods} new god component{'s' if new_gods != 1 else ''}"
69
+ )
70
+
71
+ new_violations = deltas.get("layer_violations", 0)
72
+ if new_violations > 0:
73
+ recs.append(
74
+ f"Run `roam layers` to review {new_violations} new layer violation{'s' if new_violations != 1 else ''}"
75
+ )
76
+
77
+ score_drop = deltas.get("health_score", 0)
78
+ if score_drop < -5:
79
+ recs.append(f"Health dropped by {abs(score_drop)} points — run `roam health` for details")
80
+
81
+ if not recs:
82
+ if deltas.get("health_score", 0) > 0:
83
+ recs.append("Health is improving — keep it up!")
84
+ else:
85
+ recs.append("No significant changes detected")
86
+
87
+ return recs
88
+
89
+
90
+ @click.command("digest")
91
+ @click.option("--root", default=".", help="Project root")
92
+ @click.option("--since", default=None, help="Compare against snapshot tag")
93
+ @click.option("--brief", is_flag=True, help="One-line summary")
94
+ @click.pass_context
95
+ def digest(ctx, root, since, brief):
96
+ """Compare current metrics against the most recent snapshot.
97
+
98
+ Shows deltas with directional arrows and recommendations.
99
+ Use --since to compare against a specific tagged snapshot.
100
+ """
101
+ json_mode = ctx.obj.get("json") if ctx.obj else False
102
+ ensure_index()
103
+
104
+ with open_db(readonly=True) as conn:
105
+ current = collect_metrics(conn)
106
+
107
+ # Find the comparison snapshot
108
+ snaps = get_snapshots(conn, limit=50)
109
+ if not snaps:
110
+ if json_mode:
111
+ click.echo(
112
+ to_json(
113
+ json_envelope(
114
+ "digest",
115
+ summary={"error": "No snapshots found"},
116
+ current=current,
117
+ previous=None,
118
+ deltas=None,
119
+ )
120
+ )
121
+ )
122
+ else:
123
+ click.echo("No snapshots found. Run `roam snapshot` first to create a baseline.")
124
+ return
125
+
126
+ # Pick the right snapshot for comparison
127
+ previous = None
128
+ if since:
129
+ for s in snaps:
130
+ if s["tag"] == since:
131
+ previous = dict(s)
132
+ break
133
+ if previous is None:
134
+ tags = [s["tag"] for s in snaps if s["tag"]]
135
+ tag_list = ", ".join(tags[:10]) if tags else "(none)"
136
+ if json_mode:
137
+ click.echo(
138
+ to_json(
139
+ json_envelope(
140
+ "digest",
141
+ summary={"error": f"Tag '{since}' not found"},
142
+ available_tags=tags[:20],
143
+ )
144
+ )
145
+ )
146
+ else:
147
+ click.echo(f"Tag '{since}' not found. Available tags: {tag_list}")
148
+ return
149
+ else:
150
+ previous = dict(snaps[0])
151
+
152
+ # Compute deltas
153
+ deltas = {}
154
+ for key, _label in _METRICS:
155
+ cur_val = current.get(key, 0) or 0
156
+ prev_val = previous.get(key, 0) or 0
157
+ deltas[key] = cur_val - prev_val
158
+
159
+ recommendations = _build_recommendations(current, previous, deltas)
160
+
161
+ # Format snapshot date
162
+ snap_ts = previous.get("timestamp", 0)
163
+ snap_date = datetime.fromtimestamp(snap_ts, tz=timezone.utc).strftime("%Y-%m-%d")
164
+ snap_tag = previous.get("tag")
165
+ snap_label = f"{snap_date}"
166
+ if snap_tag:
167
+ snap_label += f" [{snap_tag}]"
168
+
169
+ if json_mode:
170
+ click.echo(
171
+ to_json(
172
+ json_envelope(
173
+ "digest",
174
+ summary={
175
+ "health_score": current.get("health_score"),
176
+ "previous_health_score": previous.get("health_score"),
177
+ "health_delta": deltas.get("health_score", 0),
178
+ "snapshot_date": snap_date,
179
+ "snapshot_tag": snap_tag,
180
+ },
181
+ current=current,
182
+ previous={k: previous.get(k) for k, _ in _METRICS},
183
+ deltas=deltas,
184
+ recommendations=recommendations,
185
+ )
186
+ )
187
+ )
188
+ return
189
+
190
+ # Brief mode: single line
191
+ if brief:
192
+ score = current.get("health_score", 0)
193
+ prev_score = previous.get("health_score", 0)
194
+ d = score - prev_score
195
+ arrow = _arrow("health_score", d)
196
+ click.echo(f"Health: {prev_score} \u2192 {score} ({_delta_str(d)}) {arrow} (vs {snap_label})")
197
+ return
198
+
199
+ # Full text output
200
+ click.echo(f"Digest (vs {snap_label} snapshot):\n")
201
+
202
+ max_label = max(len(label) for _, label in _METRICS)
203
+ for key, label in _METRICS:
204
+ cur_val = current.get(key, 0) or 0
205
+ prev_val = previous.get(key, 0) or 0
206
+ d = deltas[key]
207
+ arrow = _arrow(key, d)
208
+ padded = label.ljust(max_label)
209
+ click.echo(f" {padded} {prev_val} \u2192 {cur_val} ({_delta_str(d)}) {arrow}")
210
+
211
+ if recommendations:
212
+ click.echo("\nRecommendations:")
213
+ for rec in recommendations:
214
+ click.echo(f" \u2022 {rec}")
@@ -0,0 +1,334 @@
1
+ """Detect stale docstrings whose code body has drifted since the docs were written."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import subprocess
7
+ from collections import defaultdict
8
+ from datetime import datetime, timezone
9
+
10
+ import click
11
+
12
+ from roam.commands.resolve import ensure_index
13
+ from roam.db.connection import find_project_root, open_db
14
+ from roam.output.formatter import (
15
+ abbrev_kind,
16
+ json_envelope,
17
+ loc,
18
+ to_json,
19
+ )
20
+
21
+ # ---------------------------------------------------------------------------
22
+ # Git blame parsing
23
+ # ---------------------------------------------------------------------------
24
+
25
+
26
+ def _run_git_blame(file_path, project_root):
27
+ """Run ``git blame -t <file>`` and return raw stdout, or None on error.
28
+
29
+ The ``-t`` flag gives us raw Unix timestamps instead of human dates,
30
+ which makes downstream comparison straightforward.
31
+ """
32
+ try:
33
+ result = subprocess.run(
34
+ ["git", "blame", "-t", "--", file_path],
35
+ capture_output=True,
36
+ text=True,
37
+ timeout=30,
38
+ cwd=str(project_root),
39
+ )
40
+ if result.returncode != 0:
41
+ return None
42
+ return result.stdout
43
+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):
44
+ return None
45
+
46
+
47
+ _BLAME_LINE_RE = re.compile(
48
+ r"""
49
+ ^[0-9a-f^]+ # commit hash (possibly prefixed with ^)
50
+ \s+
51
+ \(
52
+ (.+?) # 1: author (may contain spaces)
53
+ \s+
54
+ (\d+) # 2: unix timestamp
55
+ \s+
56
+ [+-]\d{4} # timezone offset
57
+ \s+
58
+ (\d+) # 3: line number
59
+ \)
60
+ """,
61
+ re.VERBOSE,
62
+ )
63
+
64
+
65
+ def _parse_blame(blame_output):
66
+ """Parse ``git blame -t`` output into a dict mapping line_number -> (timestamp, author).
67
+
68
+ Returns {int: (int, str)} — line numbers are 1-based.
69
+ """
70
+ result = {}
71
+ for raw_line in blame_output.splitlines():
72
+ m = _BLAME_LINE_RE.match(raw_line)
73
+ if m:
74
+ author = m.group(1).strip()
75
+ timestamp = int(m.group(2))
76
+ lineno = int(m.group(3))
77
+ result[lineno] = (timestamp, author)
78
+ return result
79
+
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # Docstring line-range heuristic
83
+ # ---------------------------------------------------------------------------
84
+
85
+
86
+ def _estimate_docstring_lines(line_start, line_end, docstring_text):
87
+ """Estimate the line range of the docstring within a symbol.
88
+
89
+ Heuristic:
90
+ - The docstring typically starts at ``line_start + 1`` (the line right
91
+ after the ``def`` / ``class`` statement).
92
+ - Its length in lines is derived from the stored docstring text.
93
+ - We clamp to ``line_end`` so we never exceed the symbol body.
94
+
95
+ Returns (doc_start, doc_end, body_start, body_end) — all 1-based inclusive.
96
+ """
97
+ if not docstring_text:
98
+ return None
99
+
100
+ doc_line_count = max(1, docstring_text.count("\n") + 1)
101
+ # +1 for the opening/closing triple-quotes if single-line, +2 for multi-line
102
+ # A rough estimate: count lines in the docstring text and add 2 for delimiters
103
+ # when the docstring is multi-line, or keep the line count for single-line ones.
104
+ if doc_line_count == 1:
105
+ # Single-line docstring: """text""" — occupies 1 line
106
+ overhead = 1
107
+ else:
108
+ # Multi-line docstring: opening """ on its own line + content + closing """
109
+ overhead = doc_line_count + 2
110
+
111
+ doc_start = line_start + 1 # line after def/class
112
+ doc_end = min(doc_start + overhead - 1, line_end)
113
+
114
+ body_start = doc_end + 1
115
+ body_end = line_end
116
+
117
+ if body_start > body_end:
118
+ # Symbol is too short (entire body is the docstring) — nothing to compare
119
+ return None
120
+
121
+ return doc_start, doc_end, body_start, body_end
122
+
123
+
124
+ # ---------------------------------------------------------------------------
125
+ # Core staleness analysis
126
+ # ---------------------------------------------------------------------------
127
+
128
+
129
+ def _analyze_staleness(symbols_by_file, project_root, threshold_days):
130
+ """Analyze docstring staleness for all symbols grouped by file.
131
+
132
+ Parameters
133
+ ----------
134
+ symbols_by_file : dict[str, list[dict]]
135
+ Mapping of file_path -> list of symbol dicts, each with keys:
136
+ name, kind, file_path, line_start, line_end, docstring.
137
+ project_root : Path
138
+ Absolute path to the project root (for running git commands).
139
+ threshold_days : int
140
+ Minimum drift in days to consider a docstring stale.
141
+
142
+ Returns
143
+ -------
144
+ list[dict]
145
+ Stale symbol records sorted by drift descending.
146
+ """
147
+ threshold_seconds = threshold_days * 86400
148
+ stale = []
149
+
150
+ for file_path, symbols in symbols_by_file.items():
151
+ blame_output = _run_git_blame(file_path, project_root)
152
+ if not blame_output:
153
+ continue
154
+
155
+ blame_map = _parse_blame(blame_output)
156
+ if not blame_map:
157
+ continue
158
+
159
+ for sym in symbols:
160
+ ranges = _estimate_docstring_lines(
161
+ sym["line_start"],
162
+ sym["line_end"],
163
+ sym["docstring"],
164
+ )
165
+ if ranges is None:
166
+ continue
167
+
168
+ doc_start, doc_end, body_start, body_end = ranges
169
+
170
+ # Gather timestamps for docstring lines and body lines
171
+ doc_timestamps = []
172
+ doc_authors = {}
173
+ for ln in range(doc_start, doc_end + 1):
174
+ entry = blame_map.get(ln)
175
+ if entry:
176
+ ts, author = entry
177
+ doc_timestamps.append(ts)
178
+ doc_authors[ts] = author
179
+
180
+ body_timestamps = []
181
+ body_authors = {}
182
+ for ln in range(body_start, body_end + 1):
183
+ entry = blame_map.get(ln)
184
+ if entry:
185
+ ts, author = entry
186
+ body_timestamps.append(ts)
187
+ body_authors[ts] = author
188
+
189
+ if not doc_timestamps or not body_timestamps:
190
+ continue
191
+
192
+ doc_latest = max(doc_timestamps)
193
+ body_latest = max(body_timestamps)
194
+
195
+ drift_seconds = body_latest - doc_latest
196
+ if drift_seconds >= threshold_seconds:
197
+ drift_days = drift_seconds // 86400
198
+
199
+ doc_date = datetime.fromtimestamp(doc_latest, tz=timezone.utc)
200
+ body_date = datetime.fromtimestamp(body_latest, tz=timezone.utc)
201
+
202
+ stale.append(
203
+ {
204
+ "name": sym["name"],
205
+ "kind": sym["kind"],
206
+ "file": sym["file_path"],
207
+ "line": sym["line_start"],
208
+ "doc_date": doc_date.strftime("%Y-%m-%d"),
209
+ "doc_author": doc_authors.get(doc_latest, "?"),
210
+ "body_date": body_date.strftime("%Y-%m-%d"),
211
+ "body_author": body_authors.get(body_latest, "?"),
212
+ "drift_days": drift_days,
213
+ }
214
+ )
215
+
216
+ # Sort by drift descending (most stale first)
217
+ stale.sort(key=lambda s: -s["drift_days"])
218
+ return stale
219
+
220
+
221
+ # ---------------------------------------------------------------------------
222
+ # SQL query
223
+ # ---------------------------------------------------------------------------
224
+
225
+ _DOCUMENTED_SYMBOLS_SQL = """
226
+ SELECT s.name, s.kind, f.path AS file_path,
227
+ s.line_start, s.line_end, s.docstring
228
+ FROM symbols s
229
+ JOIN files f ON s.file_id = f.id
230
+ WHERE s.docstring IS NOT NULL
231
+ AND s.docstring != ''
232
+ AND s.line_start IS NOT NULL
233
+ AND s.line_end IS NOT NULL
234
+ AND s.line_end > s.line_start
235
+ ORDER BY f.path, s.line_start
236
+ """
237
+
238
+
239
+ # ---------------------------------------------------------------------------
240
+ # Click command
241
+ # ---------------------------------------------------------------------------
242
+
243
+
244
+ @click.command("doc-staleness")
245
+ @click.option("--limit", default=20, show_default=True, help="Maximum number of stale symbols to display.")
246
+ @click.option(
247
+ "--days",
248
+ default=90,
249
+ show_default=True,
250
+ help="Staleness threshold in days (body changed N+ days after docstring).",
251
+ )
252
+ @click.pass_context
253
+ def doc_staleness(ctx, limit, days):
254
+ """Detect stale docstrings where the code body changed long after the docs."""
255
+ json_mode = ctx.obj.get("json") if ctx.obj else False
256
+ ensure_index()
257
+
258
+ project_root = find_project_root()
259
+
260
+ with open_db(readonly=True) as conn:
261
+ rows = conn.execute(_DOCUMENTED_SYMBOLS_SQL).fetchall()
262
+
263
+ if not rows:
264
+ if json_mode:
265
+ click.echo(
266
+ to_json(
267
+ json_envelope(
268
+ "doc-staleness",
269
+ summary={"stale_count": 0, "threshold_days": days},
270
+ stale=[],
271
+ )
272
+ )
273
+ )
274
+ else:
275
+ click.echo("No documented symbols found in index.")
276
+ return
277
+
278
+ # Group by file path for efficient blame (one git blame per file)
279
+ symbols_by_file = defaultdict(list)
280
+ for r in rows:
281
+ symbols_by_file[r["file_path"]].append(
282
+ {
283
+ "name": r["name"],
284
+ "kind": r["kind"],
285
+ "file_path": r["file_path"],
286
+ "line_start": r["line_start"],
287
+ "line_end": r["line_end"],
288
+ "docstring": r["docstring"],
289
+ }
290
+ )
291
+
292
+ stale = _analyze_staleness(symbols_by_file, project_root, days)
293
+
294
+ # Apply limit
295
+ displayed = stale[:limit]
296
+
297
+ if json_mode:
298
+ click.echo(
299
+ to_json(
300
+ json_envelope(
301
+ "doc-staleness",
302
+ summary={
303
+ "stale_count": len(stale),
304
+ "displayed": len(displayed),
305
+ "threshold_days": days,
306
+ "files_scanned": len(symbols_by_file),
307
+ "symbols_scanned": len(rows),
308
+ },
309
+ stale=displayed,
310
+ )
311
+ )
312
+ )
313
+ return
314
+
315
+ # --- Text output ---
316
+ if not stale:
317
+ click.echo(f"No stale docstrings found (threshold: {days} days).")
318
+ click.echo(f" Scanned {len(rows)} documented symbols across {len(symbols_by_file)} files.")
319
+ return
320
+
321
+ click.echo(f"Stale documentation (body changed >{days} days after docstring):\n")
322
+
323
+ for item in displayed:
324
+ click.echo(f" {item['name']:<25s} {abbrev_kind(item['kind']):<5s} {loc(item['file'], item['line'])}")
325
+ click.echo(f" Docstring: last updated {item['doc_date']} (by {item['doc_author']})")
326
+ click.echo(f" Body: last updated {item['body_date']} (by {item['body_author']})")
327
+ click.echo(f" Drift: {item['drift_days']} days")
328
+ click.echo()
329
+
330
+ if len(stale) > limit:
331
+ click.echo(f" (+{len(stale) - limit} more stale docstrings, use --limit to see all)")
332
+ click.echo(
333
+ f" Total: {len(stale)} stale docstring(s) across {len(symbols_by_file)} files ({len(rows)} symbols scanned)"
334
+ )