blastradius-skill 1.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.
@@ -0,0 +1,3 @@
1
+ """BlastRadius: Call-graph and blast-radius analysis for coding agents."""
2
+
3
+ __version__ = "1.0.1"
@@ -0,0 +1,537 @@
1
+ """Architecture views derived from the BlastRadius dependency graph (v0.3)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import defaultdict
7
+ from collections.abc import Callable
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ import networkx as nx
12
+
13
+ from blastradius.blast import DEFAULT_CAP, normalize_scope
14
+ from blastradius.graph import CONFIDENCE_ORDER, BlastGraph, is_test_file
15
+
16
+ VALID_VIEWS = (
17
+ "summary",
18
+ "entry_points",
19
+ "core_modules",
20
+ "shared_utilities",
21
+ "critical_paths",
22
+ "module_boundaries",
23
+ "circular_dependencies",
24
+ "layers",
25
+ "calibration",
26
+ )
27
+
28
+ _ENTRY_DECORATOR_RE = re.compile(
29
+ r"(?:^|\.)(?:route|get|post|put|patch|delete|api_view|endpoint|command|group|tool)$"
30
+ )
31
+
32
+ _SYMBOL_EDGE_TYPES = {"call", "type_ref", "inheritance"}
33
+
34
+
35
+ def _module_to_file(graph: BlastGraph) -> dict[str, str]:
36
+ """Map module qualified name to its POSIX relative file path."""
37
+ mapping: dict[str, str] = {}
38
+ for node, attrs in graph._graph.nodes(data=True):
39
+ if attrs.get("kind") == "module":
40
+ file_path = attrs.get("file", "")
41
+ if file_path:
42
+ mapping[node] = file_path
43
+ return mapping
44
+
45
+
46
+ def _non_test_modules(graph: BlastGraph) -> dict[str, str]:
47
+ """Return {module_qname: posix_file} for non-test modules."""
48
+ return {
49
+ mod: path
50
+ for mod, path in _module_to_file(graph).items()
51
+ if not is_test_file(path)
52
+ }
53
+
54
+
55
+ def _boundary_for_file(posix_file: str) -> str:
56
+ """Return top-level package/directory boundary for a POSIX relative path."""
57
+ parts = posix_file.split("/")
58
+ if len(parts) <= 1:
59
+ return "(root)"
60
+ if parts[0] in ("src", "lib", "app", "packages") and len(parts) >= 3:
61
+ return f"{parts[0]}/{parts[1]}"
62
+ return parts[0]
63
+
64
+
65
+ def _has_entry_decorator(decorators: list[str]) -> bool:
66
+ """Return True if any decorator matches a route, HTTP verb, CLI, or MCP tool pattern."""
67
+ for dec in decorators:
68
+ name = dec.strip().lstrip("@").split("(", 1)[0].strip().lower()
69
+ if _ENTRY_DECORATOR_RE.search(name):
70
+ return True
71
+ return False
72
+
73
+
74
+ def _matches_scope(posix_file: str, scope: str) -> bool:
75
+ if scope == "repo":
76
+ return True
77
+ return posix_file == scope or posix_file.startswith(f"{scope}/")
78
+
79
+
80
+ def _build_module_import_graph(graph: BlastGraph, scope: str = "repo") -> nx.DiGraph:
81
+ """Build directed graph of non-test module -> module dependencies."""
82
+ mod_files = _non_test_modules(graph)
83
+ file_to_mod = {path: mod for mod, path in mod_files.items()}
84
+ mod_graph = nx.DiGraph()
85
+
86
+ for mod, path in sorted(mod_files.items()):
87
+ if _matches_scope(path, scope):
88
+ mod_graph.add_node(mod, file=path)
89
+
90
+ for src, dst, attrs in graph._graph.edges(data=True):
91
+ src_file = attrs.get("source_file") or graph._graph.nodes.get(src, {}).get("file", "")
92
+ dst_file = attrs.get("target_file") or graph._graph.nodes.get(dst, {}).get("file", "")
93
+ if not src_file or not dst_file or src_file == dst_file:
94
+ continue
95
+ src_mod = file_to_mod.get(src_file)
96
+ dst_mod = file_to_mod.get(dst_file)
97
+ if not src_mod or not dst_mod:
98
+ continue
99
+ if src_mod not in mod_graph or dst_mod not in mod_graph:
100
+ continue
101
+ conf = attrs.get("confidence", "name-match-only")
102
+ if mod_graph.has_edge(src_mod, dst_mod):
103
+ existing = mod_graph[src_mod][dst_mod]["confidence"]
104
+ if CONFIDENCE_ORDER.get(conf, 99) < CONFIDENCE_ORDER.get(existing, 99):
105
+ mod_graph[src_mod][dst_mod]["confidence"] = conf
106
+ mod_graph[src_mod][dst_mod]["edge_count"] += 1
107
+ else:
108
+ mod_graph.add_edge(src_mod, dst_mod, confidence=conf, edge_count=1)
109
+
110
+ return mod_graph
111
+
112
+
113
+ def _count_non_test_callers(
114
+ graph: BlastGraph,
115
+ node: str,
116
+ ) -> tuple[int, set[str]]:
117
+ """Return (non-test inbound symbol edge count, calling non-test files) excluding self-edges."""
118
+ caller_files: set[str] = set()
119
+ caller_count = 0
120
+ for pred in graph._graph.predecessors(node):
121
+ if pred == node:
122
+ continue
123
+ pred_node_file = graph._graph.nodes.get(pred, {}).get("file", "")
124
+ edge_dict = graph._graph.get_edge_data(pred, node) or {}
125
+ for attrs in edge_dict.values():
126
+ if attrs.get("edge_type") not in _SYMBOL_EDGE_TYPES:
127
+ continue
128
+ src_file = attrs.get("source_file") or pred_node_file
129
+ if src_file and is_test_file(src_file):
130
+ continue
131
+ caller_count += 1
132
+ if src_file:
133
+ caller_files.add(src_file)
134
+ return caller_count, caller_files
135
+
136
+
137
+ def _compute_entry_points(graph: BlastGraph, scope: str = "repo") -> list[dict[str, Any]]:
138
+ """Find non-test definitions with zero non-test inbound calls or entry decorators."""
139
+ results: list[dict[str, Any]] = []
140
+ for node, attrs in graph._graph.nodes(data=True):
141
+ kind = attrs.get("kind", "")
142
+ file_path = attrs.get("file", "")
143
+ if kind == "module" or not file_path or is_test_file(file_path):
144
+ continue
145
+ if not _matches_scope(file_path, scope):
146
+ continue
147
+
148
+ inbound_non_test, _ = _count_non_test_callers(graph, node)
149
+ decorators = list(attrs.get("decorators") or [])
150
+ has_dec = _has_entry_decorator(decorators)
151
+ if inbound_non_test == 0 or has_dec:
152
+ reason = "decorator" if has_dec else "no_inbound_calls"
153
+ if has_dec and inbound_non_test == 0:
154
+ reason = "decorator_and_no_inbound_calls"
155
+ results.append({
156
+ "decorators": decorators,
157
+ "file": file_path,
158
+ "inbound_calls": inbound_non_test,
159
+ "kind": kind,
160
+ "line": attrs.get("line_start", 1),
161
+ "name": node,
162
+ "reason": reason,
163
+ })
164
+
165
+ results.sort(
166
+ key=lambda r: (0 if "decorator" in r["reason"] else 1, r["file"], r["line"], r["name"])
167
+ )
168
+ return results
169
+
170
+
171
+ def _compute_core_modules(graph: BlastGraph, scope: str = "repo") -> list[dict[str, Any]]:
172
+ """Rank non-test modules by inbound dependent module count."""
173
+ mod_graph = _build_module_import_graph(graph, scope=scope)
174
+ results: list[dict[str, Any]] = []
175
+ for mod, attrs in mod_graph.nodes(data=True):
176
+ in_deg = mod_graph.in_degree(mod)
177
+ out_deg = mod_graph.out_degree(mod)
178
+ dependents = sorted(mod_graph.nodes[p]["file"] for p in mod_graph.predecessors(mod))
179
+ results.append({
180
+ "dependents": dependents,
181
+ "file": attrs["file"],
182
+ "inbound_modules": in_deg,
183
+ "module": mod,
184
+ "outbound_modules": out_deg,
185
+ })
186
+ results.sort(key=lambda r: (-r["inbound_modules"], -r["outbound_modules"], r["file"]))
187
+ return results
188
+
189
+
190
+ def _compute_shared_utilities(graph: BlastGraph, scope: str = "repo") -> list[dict[str, Any]]:
191
+ """Rank non-test symbols by inbound non-test caller fan-in."""
192
+ results: list[dict[str, Any]] = []
193
+ for node, attrs in graph._graph.nodes(data=True):
194
+ kind = attrs.get("kind", "")
195
+ file_path = attrs.get("file", "")
196
+ if kind == "module" or not file_path or is_test_file(file_path):
197
+ continue
198
+ if not _matches_scope(file_path, scope):
199
+ continue
200
+
201
+ caller_count, caller_files = _count_non_test_callers(graph, node)
202
+ if caller_count > 0:
203
+ results.append({
204
+ "caller_count": caller_count,
205
+ "calling_files": sorted(caller_files),
206
+ "file": file_path,
207
+ "kind": kind,
208
+ "line": attrs.get("line_start", 1),
209
+ "name": node,
210
+ })
211
+
212
+ results.sort(
213
+ key=lambda r: (
214
+ -r["caller_count"],
215
+ -len(r["calling_files"]),
216
+ r["file"],
217
+ r["line"],
218
+ r["name"],
219
+ )
220
+ )
221
+ return results
222
+
223
+
224
+ def _compute_critical_paths(
225
+ graph: BlastGraph,
226
+ scope: str = "repo",
227
+ max_paths: int = DEFAULT_CAP,
228
+ ) -> list[dict[str, Any]]:
229
+ """Find shortest dependency paths from entry points to high fan-in symbols."""
230
+ sym_graph = nx.DiGraph()
231
+ for node, attrs in graph._graph.nodes(data=True):
232
+ kind = attrs.get("kind", "")
233
+ file_path = attrs.get("file", "")
234
+ if kind == "module" or not file_path or is_test_file(file_path):
235
+ continue
236
+ if _matches_scope(file_path, scope):
237
+ sym_graph.add_node(node, file=file_path, line=attrs.get("line_start", 1))
238
+
239
+ for src, dst, attrs in graph._graph.edges(data=True):
240
+ if attrs.get("edge_type") in _SYMBOL_EDGE_TYPES and src in sym_graph and dst in sym_graph:
241
+ sym_graph.add_edge(src, dst)
242
+
243
+ entries = [
244
+ e["name"]
245
+ for e in _compute_entry_points(graph, scope=scope)
246
+ if e["name"] in sym_graph
247
+ ]
248
+ shared = _compute_shared_utilities(graph, scope=scope)
249
+ sinks = [u["name"] for u in shared if u["name"] in sym_graph and u["caller_count"] >= 2]
250
+ if not sinks:
251
+ sinks = [u["name"] for u in shared[:10] if u["name"] in sym_graph]
252
+
253
+ paths: list[dict[str, Any]] = []
254
+ seen: set[tuple[str, str]] = set()
255
+ for entry in entries[:25]:
256
+ for sink in sinks[:25]:
257
+ if entry == sink or (entry, sink) in seen:
258
+ continue
259
+ try:
260
+ path = nx.shortest_path(sym_graph, source=entry, target=sink)
261
+ except (nx.NetworkXNoPath, nx.NodeNotFound):
262
+ continue
263
+ if len(path) < 2:
264
+ continue
265
+ seen.add((entry, sink))
266
+ paths.append({
267
+ "entry": entry,
268
+ "hops": len(path) - 1,
269
+ "path": path,
270
+ "target": sink,
271
+ })
272
+ if len(paths) >= max_paths * 2:
273
+ break
274
+ if len(paths) >= max_paths * 2:
275
+ break
276
+
277
+ paths.sort(key=lambda p: (-p["hops"], p["entry"], p["target"]))
278
+ return paths
279
+
280
+
281
+ def _compute_module_boundaries(graph: BlastGraph, scope: str = "repo") -> list[dict[str, Any]]:
282
+ """Aggregate cross-boundary module dependency edges."""
283
+ mod_graph = _build_module_import_graph(graph, scope=scope)
284
+ grouped: dict[tuple[str, str], dict[str, Any]] = {}
285
+
286
+ for src_mod, dst_mod, attrs in mod_graph.edges(data=True):
287
+ src_file = mod_graph.nodes[src_mod]["file"]
288
+ dst_file = mod_graph.nodes[dst_mod]["file"]
289
+ src_b = _boundary_for_file(src_file)
290
+ dst_b = _boundary_for_file(dst_file)
291
+ if src_b == dst_b:
292
+ continue
293
+ key = (src_b, dst_b)
294
+ entry = grouped.setdefault(
295
+ key,
296
+ {
297
+ "confidence": attrs.get("confidence", "name-match-only"),
298
+ "edge_count": 0,
299
+ "sample_edges": [],
300
+ "source_boundary": src_b,
301
+ "target_boundary": dst_b,
302
+ },
303
+ )
304
+ entry["edge_count"] += attrs.get("edge_count", 1)
305
+ conf = attrs.get("confidence", "name-match-only")
306
+ if CONFIDENCE_ORDER.get(conf, 99) < CONFIDENCE_ORDER.get(entry["confidence"], 99):
307
+ entry["confidence"] = conf
308
+ entry["sample_edges"].append({"from": src_file, "to": dst_file})
309
+
310
+ results = list(grouped.values())
311
+ for item in results:
312
+ item["sample_edges"] = sorted(
313
+ item["sample_edges"], key=lambda e: (e["from"], e["to"])
314
+ )[:5]
315
+ results.sort(key=lambda r: (-r["edge_count"], r["source_boundary"], r["target_boundary"]))
316
+ return results
317
+
318
+
319
+ def _compute_circular_dependencies(graph: BlastGraph, scope: str = "repo") -> list[dict[str, Any]]:
320
+ """Detect strongly connected components of size > 1 in the module import graph."""
321
+ mod_graph = _build_module_import_graph(graph, scope=scope)
322
+ cycles: list[dict[str, Any]] = []
323
+ for scc in nx.strongly_connected_components(mod_graph):
324
+ if len(scc) <= 1:
325
+ continue
326
+ files = sorted(mod_graph.nodes[m]["file"] for m in scc)
327
+ modules = sorted(scc)
328
+ cycles.append({
329
+ "files": files,
330
+ "modules": modules,
331
+ "size": len(files),
332
+ })
333
+ cycles.sort(key=lambda c: (-c["size"], c["files"]))
334
+ return cycles
335
+
336
+
337
+ def _compute_layers(
338
+ graph: BlastGraph,
339
+ scope: str = "repo",
340
+ layer_rules: dict[str, Any] | None = None,
341
+ ) -> dict[str, Any]:
342
+ """Infer architectural layers from import direction or evaluate configured layer_rules."""
343
+ mod_graph = _build_module_import_graph(graph, scope=scope)
344
+ condensation = nx.condensation(mod_graph)
345
+
346
+ # Layer 0 = leaf/foundation modules (no outbound imports); higher layers depend on lower ones.
347
+ depth_map: dict[int, int] = {}
348
+ for scc_id in reversed(list(nx.topological_sort(condensation))):
349
+ succs = list(condensation.successors(scc_id))
350
+ depth_map[scc_id] = 0 if not succs else 1 + max(depth_map[s] for s in succs)
351
+
352
+ inferred_layers: dict[int, list[str]] = defaultdict(list)
353
+ for mod, attrs in mod_graph.nodes(data=True):
354
+ scc_id = condensation.graph["mapping"][mod]
355
+ lvl = depth_map.get(scc_id, 0)
356
+ inferred_layers[lvl].append(attrs["file"])
357
+
358
+ layers_list = [
359
+ {"files": sorted(files), "layer": lvl}
360
+ for lvl, files in sorted(inferred_layers.items(), reverse=True)
361
+ ]
362
+
363
+ violations: list[dict[str, Any]] = []
364
+ configured = False
365
+ if layer_rules is not None:
366
+ order_raw = layer_rules.get("order")
367
+ if order_raw is not None:
368
+ if not isinstance(order_raw, list):
369
+ raise ValueError("layer_rules['order'] must be a list of layer names")
370
+ configured = True
371
+ rank = {str(name): idx for idx, name in enumerate(order_raw)}
372
+ for src_mod, dst_mod in mod_graph.edges():
373
+ src_file = mod_graph.nodes[src_mod]["file"]
374
+ dst_file = mod_graph.nodes[dst_mod]["file"]
375
+ src_b = _boundary_for_file(src_file)
376
+ dst_b = _boundary_for_file(dst_file)
377
+ if src_b in rank and dst_b in rank and rank[src_b] > rank[dst_b]:
378
+ violations.append({
379
+ "from": src_file,
380
+ "from_layer": src_b,
381
+ "to": dst_file,
382
+ "to_layer": dst_b,
383
+ })
384
+ violations.sort(key=lambda v: (v["from"], v["to"]))
385
+
386
+ return {
387
+ "configured": configured,
388
+ "layers": layers_list,
389
+ "violations": violations,
390
+ }
391
+
392
+
393
+ def _truncate_list(items: list[Any], cap: int) -> tuple[list[Any], bool]:
394
+ if len(items) > cap:
395
+ return items[:cap], True
396
+ return items, False
397
+
398
+
399
+ _LIST_VIEW_COMPUTERS: dict[str, Callable[[BlastGraph, str], list[dict[str, Any]]]] = {
400
+ "entry_points": _compute_entry_points,
401
+ "core_modules": _compute_core_modules,
402
+ "shared_utilities": _compute_shared_utilities,
403
+ "module_boundaries": _compute_module_boundaries,
404
+ "circular_dependencies": _compute_circular_dependencies,
405
+ }
406
+
407
+
408
+ def get_architecture_view_result(
409
+ graph: BlastGraph,
410
+ view: str = "summary",
411
+ scope: str = "repo",
412
+ repo_root: Path | None = None,
413
+ cap: int = DEFAULT_CAP,
414
+ layer_rules: dict[str, Any] | None = None,
415
+ ) -> dict[str, Any]:
416
+ """Compute a deterministic, read-only architecture view from BlastGraph."""
417
+ clean_view = (view or "summary").strip().lower()
418
+ if clean_view not in VALID_VIEWS:
419
+ raise ValueError(
420
+ f"Unsupported architecture view {view!r}. Valid views: {', '.join(VALID_VIEWS)}"
421
+ )
422
+ if cap < 1:
423
+ raise ValueError(f"cap must be >= 1, got {cap}")
424
+ if layer_rules is not None and not isinstance(layer_rules, dict):
425
+ raise ValueError("layer_rules must be a mapping when provided")
426
+
427
+ norm_scope = normalize_scope(scope, repo_root=repo_root)
428
+
429
+ if clean_view == "calibration":
430
+ if repo_root is None:
431
+ from blastradius.cache import DEFAULT_FACTOR_MAX_POINTS, MIN_CALIBRATION_RUNS
432
+
433
+ return {
434
+ "active": False,
435
+ "calibrated_weights": dict(DEFAULT_FACTOR_MAX_POINTS),
436
+ "confidence_stats": {},
437
+ "default_weights": dict(DEFAULT_FACTOR_MAX_POINTS),
438
+ "factor_stats": {},
439
+ "min_runs_required": MIN_CALIBRATION_RUNS,
440
+ "runs_count": 0,
441
+ "scope": norm_scope,
442
+ "truncated": False,
443
+ "view": "calibration",
444
+ "warnings": ["cannot load calibration without repo_root"],
445
+ }
446
+ from blastradius.verify import get_calibration_status_result
447
+
448
+ cal = get_calibration_status_result(repo_root)
449
+ cal["scope"] = norm_scope
450
+ cal["view"] = "calibration"
451
+ return cal
452
+
453
+ if clean_view in _LIST_VIEW_COMPUTERS:
454
+ raw = _LIST_VIEW_COMPUTERS[clean_view](graph, norm_scope)
455
+ items, truncated = _truncate_list(raw, cap)
456
+ return {
457
+ "items": items,
458
+ "scope": norm_scope,
459
+ "total": len(raw),
460
+ "truncated": truncated,
461
+ "view": clean_view,
462
+ }
463
+
464
+ if clean_view == "critical_paths":
465
+ raw = _compute_critical_paths(graph, scope=norm_scope, max_paths=cap)
466
+ items, truncated = _truncate_list(raw, cap)
467
+ return {
468
+ "items": items,
469
+ "scope": norm_scope,
470
+ "total": len(raw),
471
+ "truncated": truncated,
472
+ "view": clean_view,
473
+ }
474
+
475
+ if clean_view == "layers":
476
+ layer_data = _compute_layers(graph, scope=norm_scope, layer_rules=layer_rules)
477
+ layers_capped, trunc_layers = _truncate_list(layer_data["layers"], cap)
478
+ viol_capped, trunc_viol = _truncate_list(layer_data["violations"], cap)
479
+ return {
480
+ "configured": layer_data["configured"],
481
+ "layers": layers_capped,
482
+ "scope": norm_scope,
483
+ "total_layers": len(layer_data["layers"]),
484
+ "total_violations": len(layer_data["violations"]),
485
+ "truncated": trunc_layers or trunc_viol,
486
+ "view": clean_view,
487
+ "violations": viol_capped,
488
+ }
489
+
490
+ summary_cap = min(cap, 10)
491
+ entries = _compute_entry_points(graph, scope=norm_scope)
492
+ core = _compute_core_modules(graph, scope=norm_scope)
493
+ shared = _compute_shared_utilities(graph, scope=norm_scope)
494
+ paths = _compute_critical_paths(graph, scope=norm_scope, max_paths=summary_cap)
495
+ boundaries = _compute_module_boundaries(graph, scope=norm_scope)
496
+ cycles = _compute_circular_dependencies(graph, scope=norm_scope)
497
+ layers_data = _compute_layers(graph, scope=norm_scope, layer_rules=layer_rules)
498
+
499
+ sections = {
500
+ "circular_dependencies": cycles[:summary_cap],
501
+ "core_modules": core[:summary_cap],
502
+ "critical_paths": paths[:summary_cap],
503
+ "entry_points": entries[:summary_cap],
504
+ "layers": layers_data["layers"][:summary_cap],
505
+ "layer_violations": layers_data["violations"][:summary_cap],
506
+ "module_boundaries": boundaries[:summary_cap],
507
+ "shared_utilities": shared[:summary_cap],
508
+ }
509
+ truncated = any(
510
+ len(full) > summary_cap
511
+ for full in (
512
+ entries,
513
+ core,
514
+ shared,
515
+ paths,
516
+ boundaries,
517
+ cycles,
518
+ layers_data["layers"],
519
+ layers_data["violations"],
520
+ )
521
+ )
522
+ return {
523
+ "counts": {
524
+ "circular_dependencies": len(cycles),
525
+ "core_modules": len(core),
526
+ "critical_paths": len(paths),
527
+ "entry_points": len(entries),
528
+ "layer_violations": len(layers_data["violations"]),
529
+ "layers": len(layers_data["layers"]),
530
+ "module_boundaries": len(boundaries),
531
+ "shared_utilities": len(shared),
532
+ },
533
+ "scope": norm_scope,
534
+ "sections": sections,
535
+ "truncated": truncated,
536
+ "view": "summary",
537
+ }