stackparity 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. stackparity/__init__.py +17 -0
  2. stackparity/_engine/agents/investigator.py +294 -0
  3. stackparity/_engine/agents/memory_agent.py +37 -0
  4. stackparity/_engine/agents/pipeline_agent.py +152 -0
  5. stackparity/_engine/agents/remediation_agent.py +248 -0
  6. stackparity/_engine/agents/runtime.py +177 -0
  7. stackparity/_engine/agents/specialists.py +709 -0
  8. stackparity/_engine/agents/suspicious_change_agent.py +1275 -0
  9. stackparity/_engine/cli/__init__.py +2 -0
  10. stackparity/_engine/cli/main.py +1252 -0
  11. stackparity/_engine/cli/remediate.py +461 -0
  12. stackparity/_engine/cli/term.py +44 -0
  13. stackparity/_engine/config/__init__.py +0 -0
  14. stackparity/_engine/config/constants.py +88 -0
  15. stackparity/_engine/config/loader.py +155 -0
  16. stackparity/_engine/config/settings.py +108 -0
  17. stackparity/_engine/containers/__init__.py +12 -0
  18. stackparity/_engine/containers/discovery.py +143 -0
  19. stackparity/_engine/containers/models.py +72 -0
  20. stackparity/_engine/containers/trivy_image_scanner.py +165 -0
  21. stackparity/_engine/core/__init__.py +0 -0
  22. stackparity/_engine/core/capabilities.py +107 -0
  23. stackparity/_engine/core/finding_schema.py +305 -0
  24. stackparity/_engine/core/git_manager.py +206 -0
  25. stackparity/_engine/core/http.py +64 -0
  26. stackparity/_engine/core/models.py +109 -0
  27. stackparity/_engine/core/netpolicy.py +242 -0
  28. stackparity/_engine/core/plugins.py +43 -0
  29. stackparity/_engine/core/repository_inspector.py +243 -0
  30. stackparity/_engine/core/safe_env.py +48 -0
  31. stackparity/_engine/core/scan_orchestrator.py +289 -0
  32. stackparity/_engine/core/scan_state.py +58 -0
  33. stackparity/_engine/core/url_validator.py +135 -0
  34. stackparity/_engine/ecosystems/__init__.py +1 -0
  35. stackparity/_engine/ecosystems/registry.py +138 -0
  36. stackparity/_engine/evidence/__init__.py +1 -0
  37. stackparity/_engine/evidence/store.py +65 -0
  38. stackparity/_engine/explainability/__init__.py +0 -0
  39. stackparity/_engine/explainability/evidence_formatter.py +30 -0
  40. stackparity/_engine/explainability/explanation_engine.py +132 -0
  41. stackparity/_engine/explainability/explanation_validator.py +54 -0
  42. stackparity/_engine/explainability/prompt_templates.py +18 -0
  43. stackparity/_engine/graph/__init__.py +0 -0
  44. stackparity/_engine/graph/dependency_tracer.py +86 -0
  45. stackparity/_engine/graph/graph_builder.py +165 -0
  46. stackparity/_engine/graph/graph_diff.py +57 -0
  47. stackparity/_engine/graph/graph_exporter.py +194 -0
  48. stackparity/_engine/graph/graph_validator.py +46 -0
  49. stackparity/_engine/graph/impact_analyzer.py +23 -0
  50. stackparity/_engine/graph/tree_view.py +185 -0
  51. stackparity/_engine/intel/__init__.py +0 -0
  52. stackparity/_engine/intel/epss.py +53 -0
  53. stackparity/_engine/llm/__init__.py +1 -0
  54. stackparity/_engine/llm/client.py +138 -0
  55. stackparity/_engine/monitor/__init__.py +0 -0
  56. stackparity/_engine/monitor/watch.py +171 -0
  57. stackparity/_engine/non_cve/__init__.py +7 -0
  58. stackparity/_engine/non_cve/base.py +62 -0
  59. stackparity/_engine/non_cve/iac.py +144 -0
  60. stackparity/_engine/non_cve/sast.py +272 -0
  61. stackparity/_engine/non_cve/supply_chain.py +147 -0
  62. stackparity/_engine/orchestration/__init__.py +1 -0
  63. stackparity/_engine/orchestration/pipeline.py +279 -0
  64. stackparity/_engine/orchestration/supervisor.py +167 -0
  65. stackparity/_engine/pipeline_analysis/__init__.py +0 -0
  66. stackparity/_engine/pipeline_analysis/analyzer.py +90 -0
  67. stackparity/_engine/pipeline_analysis/ci.py +189 -0
  68. stackparity/_engine/pipeline_analysis/ci_adapters/__init__.py +24 -0
  69. stackparity/_engine/pipeline_analysis/ci_adapters/azure_pipelines.py +221 -0
  70. stackparity/_engine/pipeline_analysis/ci_adapters/base.py +239 -0
  71. stackparity/_engine/pipeline_analysis/ci_adapters/circleci.py +176 -0
  72. stackparity/_engine/pipeline_analysis/ci_adapters/github_actions.py +356 -0
  73. stackparity/_engine/pipeline_analysis/ci_adapters/gitlab_ci.py +268 -0
  74. stackparity/_engine/pipeline_analysis/ci_adapters/jenkins.py +180 -0
  75. stackparity/_engine/pipeline_analysis/ci_adapters/registry.py +80 -0
  76. stackparity/_engine/pipeline_analysis/ci_models.py +72 -0
  77. stackparity/_engine/pipeline_analysis/dockerfile.py +235 -0
  78. stackparity/_engine/pipeline_analysis/eol.py +62 -0
  79. stackparity/_engine/pipeline_analysis/models.py +37 -0
  80. stackparity/_engine/policy/__init__.py +0 -0
  81. stackparity/_engine/policy/engine.py +216 -0
  82. stackparity/_engine/policy/resources/default.yaml +56 -0
  83. stackparity/_engine/policy/resources/strict.yaml +35 -0
  84. stackparity/_engine/reachability/__init__.py +0 -0
  85. stackparity/_engine/reachability/app_reachability.py +186 -0
  86. stackparity/_engine/reachability/scanners.py +215 -0
  87. stackparity/_engine/remediation/__init__.py +0 -0
  88. stackparity/_engine/remediation/adapters.py +198 -0
  89. stackparity/_engine/remediation/apply_local.py +309 -0
  90. stackparity/_engine/remediation/code_fixes.py +383 -0
  91. stackparity/_engine/remediation/compat.py +156 -0
  92. stackparity/_engine/remediation/container_plan.py +127 -0
  93. stackparity/_engine/remediation/delivery.py +31 -0
  94. stackparity/_engine/remediation/export.py +44 -0
  95. stackparity/_engine/remediation/lifecycle.py +623 -0
  96. stackparity/_engine/remediation/local_trial.py +358 -0
  97. stackparity/_engine/remediation/patchers.py +215 -0
  98. stackparity/_engine/remediation/planner.py +285 -0
  99. stackparity/_engine/remediation/pr_template_engine.py +234 -0
  100. stackparity/_engine/remediation/reachability_impact.py +147 -0
  101. stackparity/_engine/remediation/versions.py +92 -0
  102. stackparity/_engine/remediation/whatif.py +64 -0
  103. stackparity/_engine/remediation/worktree_pr.py +434 -0
  104. stackparity/_engine/reporting/__init__.py +0 -0
  105. stackparity/_engine/reporting/counts.py +63 -0
  106. stackparity/_engine/reporting/fix_pdf.py +343 -0
  107. stackparity/_engine/reporting/fix_report.py +135 -0
  108. stackparity/_engine/reporting/json_exporter.py +61 -0
  109. stackparity/_engine/reporting/report_generator.py +200 -0
  110. stackparity/_engine/reporting/sarif.py +71 -0
  111. stackparity/_engine/reporting/vex.py +57 -0
  112. stackparity/_engine/reporting/view.py +166 -0
  113. stackparity/_engine/risk_analysis/__init__.py +0 -0
  114. stackparity/_engine/risk_analysis/contextual_scorer.py +253 -0
  115. stackparity/_engine/risk_analysis/evidence_collector.py +62 -0
  116. stackparity/_engine/risk_analysis/evidence_normalizer.py +37 -0
  117. stackparity/_engine/risk_analysis/finding_correlator.py +90 -0
  118. stackparity/_engine/risk_analysis/function_impact.py +184 -0
  119. stackparity/_engine/risk_analysis/production_context.py +252 -0
  120. stackparity/_engine/risk_analysis/risk_rules.py +81 -0
  121. stackparity/_engine/risk_analysis/risk_scorer.py +390 -0
  122. stackparity/_engine/sandbox/__init__.py +0 -0
  123. stackparity/_engine/sandbox/runner.py +142 -0
  124. stackparity/_engine/sbom/__init__.py +0 -0
  125. stackparity/_engine/sbom/adapters/__init__.py +19 -0
  126. stackparity/_engine/sbom/adapters/builtin.py +29 -0
  127. stackparity/_engine/sbom/adapters/syft.py +26 -0
  128. stackparity/_engine/sbom/adapters/trivy.py +76 -0
  129. stackparity/_engine/sbom/builtin_generator.py +227 -0
  130. stackparity/_engine/sbom/cyclonedx_validator.py +166 -0
  131. stackparity/_engine/sbom/exporters.py +153 -0
  132. stackparity/_engine/sbom/fusion/__init__.py +5 -0
  133. stackparity/_engine/sbom/fusion/engine.py +315 -0
  134. stackparity/_engine/sbom/fusion/hashes.py +47 -0
  135. stackparity/_engine/sbom/fusion/ledger.py +96 -0
  136. stackparity/_engine/sbom/fusion/registries.py +271 -0
  137. stackparity/_engine/sbom/fusion/resolver.py +143 -0
  138. stackparity/_engine/sbom/fusion/writer.py +114 -0
  139. stackparity/_engine/sbom/lockfile_analyzer.py +114 -0
  140. stackparity/_engine/sbom/merge.py +71 -0
  141. stackparity/_engine/sbom/package_extractors/common.py +104 -0
  142. stackparity/_engine/sbom/package_extractors/manifests.py +101 -0
  143. stackparity/_engine/sbom/package_extractors/npm.py +206 -0
  144. stackparity/_engine/sbom/package_extractors/others.py +267 -0
  145. stackparity/_engine/sbom/package_extractors/python.py +143 -0
  146. stackparity/_engine/sbom/quality_analyzer.py +191 -0
  147. stackparity/_engine/sbom/scanner_engine.py +98 -0
  148. stackparity/_engine/sbom/syft_runner.py +100 -0
  149. stackparity/_engine/sbom/tool_locator.py +69 -0
  150. stackparity/_engine/sbom/trivy_runner.py +82 -0
  151. stackparity/_engine/storage/__init__.py +0 -0
  152. stackparity/_engine/storage/cache.py +56 -0
  153. stackparity/_engine/storage/database.py +295 -0
  154. stackparity/_engine/storage/memory.py +146 -0
  155. stackparity/_engine/suspicious_changes/__init__.py +12 -0
  156. stackparity/_engine/suspicious_changes/analyzer.py +1022 -0
  157. stackparity/_engine/suspicious_changes/change_correlation.py +861 -0
  158. stackparity/_engine/suspicious_changes/lifecycle_script_detector.py +263 -0
  159. stackparity/_engine/suspicious_changes/lockfile_change_detector.py +316 -0
  160. stackparity/_engine/suspicious_changes/manifest_diff_detector.py +251 -0
  161. stackparity/_engine/suspicious_changes/package_risk.py +78 -0
  162. stackparity/_engine/suspicious_changes/popular_packages.py +94 -0
  163. stackparity/_engine/suspicious_changes/registry_detector.py +354 -0
  164. stackparity/_engine/suspicious_changes/suspicious_models.py +57 -0
  165. stackparity/_engine/suspicious_changes/typosquatting_detector.py +298 -0
  166. stackparity/_engine/tools/__init__.py +1 -0
  167. stackparity/_engine/tools/builtin.py +93 -0
  168. stackparity/_engine/tools/registry.py +66 -0
  169. stackparity/_engine/ui/__init__.py +0 -0
  170. stackparity/_engine/ui/components/__init__.py +0 -0
  171. stackparity/_engine/ui/components/common.py +238 -0
  172. stackparity/_engine/ui/components/live_progress.py +157 -0
  173. stackparity/_engine/ui/components/memory_panel.py +82 -0
  174. stackparity/_engine/ui/pages/__init__.py +0 -0
  175. stackparity/_engine/ui/pages/agents_page.py +76 -0
  176. stackparity/_engine/ui/pages/architecture_page.py +44 -0
  177. stackparity/_engine/ui/pages/fixes_page.py +98 -0
  178. stackparity/_engine/ui/pages/graph_page.py +203 -0
  179. stackparity/_engine/ui/pages/health_page.py +117 -0
  180. stackparity/_engine/ui/pages/monitor_page.py +67 -0
  181. stackparity/_engine/ui/pages/pipeline_page.py +219 -0
  182. stackparity/_engine/ui/pages/remediation_page.py +409 -0
  183. stackparity/_engine/ui/pages/reports_page.py +54 -0
  184. stackparity/_engine/ui/pages/sbom_page.py +210 -0
  185. stackparity/_engine/ui/pages/scan_page.py +131 -0
  186. stackparity/_engine/ui/pages/suspicious_page.py +551 -0
  187. stackparity/_engine/ui/pages/vulns_page.py +201 -0
  188. stackparity/_engine/ui/state.py +116 -0
  189. stackparity/_engine/ui/theme.py +201 -0
  190. stackparity/_engine/ui/visualizations/__init__.py +0 -0
  191. stackparity/_engine/ui/visualizations/graphs.py +373 -0
  192. stackparity/_engine/vulnerability/__init__.py +0 -0
  193. stackparity/_engine/vulnerability/cvss.py +58 -0
  194. stackparity/_engine/vulnerability/kev_client.py +47 -0
  195. stackparity/_engine/vulnerability/nvd_client.py +74 -0
  196. stackparity/_engine/vulnerability/osv_client.py +139 -0
  197. stackparity/_engine/vulnerability/remediation_engine.py +50 -0
  198. stackparity/_engine/vulnerability/verification.py +94 -0
  199. stackparity/_engine/vulnerability/version_matcher.py +299 -0
  200. stackparity/_engine/vulnerability/vulnerability_correlator.py +303 -0
  201. stackparity/_engine/vulnerability/vulnerability_models.py +64 -0
  202. stackparity/cli.py +30 -0
  203. stackparity/dashboard_app.py +95 -0
  204. stackparity/web_dist/assets/index-DRJYw2Du.css +1 -0
  205. stackparity/web_dist/assets/index-Q6LLpbEi.js +495 -0
  206. stackparity/web_dist/index.html +13 -0
  207. stackparity/web_server.py +533 -0
  208. stackparity-1.0.0.dist-info/METADATA +204 -0
  209. stackparity-1.0.0.dist-info/RECORD +212 -0
  210. stackparity-1.0.0.dist-info/WHEEL +4 -0
  211. stackparity-1.0.0.dist-info/entry_points.txt +2 -0
  212. stackparity-1.0.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,285 @@
1
+ """Remediation planning: choose the *smallest safe change* per source package and prove it with a static what-if.
2
+
3
+ For each group of findings introduced by one direct dependency (``source_package_view``):
4
+
5
+ 1. Direct package itself vulnerable -> candidate upgrade >= the highest fixed version, same major first.
6
+ 2. Only transitive children vulnerable -> **parent-upgrade search**: walk newer versions of the direct dependency, resolve each one's dependency tree
7
+ (deps.dev) and re-match advisories on every node; take the first version whose tree clears the findings without introducing new HIGH/CRITICAL ones.
8
+ 3. No parent version helps -> pin the vulnerable child (npm overrides, pip constraint, Maven dependencyManagement, ...).
9
+ 4. No fix exists at all -> mitigate / block / escalate (never an invented version).
10
+
11
+ Nothing is applied: the output is a proposal (diff + rationale + rollback + measured effect) that requires human approval.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import re
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path
18
+ from typing import Any, Optional
19
+
20
+ from core.http import HttpClient
21
+ from core.repository_inspector import safe_read_text
22
+ from remediation import patchers
23
+ from remediation.versions import candidates, change_kind, list_versions, drop_deprecated
24
+ from remediation.whatif import SEV_RANK, check_nodes
25
+ from sbom.fusion.registries import DEPSDEV_SYSTEM
26
+ from sbom.fusion.resolver import _fetch
27
+ from sbom.package_extractors.common import normalize_name
28
+ from vulnerability.osv_client import OsvClient
29
+ from vulnerability.remediation_engine import OVERRIDE_HINTS
30
+ from vulnerability.version_matcher import VersionError, compare
31
+
32
+ LOCK_REGEN = {"npm": "npm install --package-lock-only (yarn: `yarn install`, pnpm: `pnpm install --lockfile-only`)", "PyPI": "regenerate the lock: `uv lock` / `poetry lock` / `pip-compile`",
33
+ "Maven": "no lockfile; run `mvn -q dependency:tree` to confirm the resolved versions", "Go": "go mod tidy", "crates.io": "cargo update -p <crate>",
34
+ "Packagist": "composer update <vendor/package>", "NuGet": "dotnet restore --force-evaluate"}
35
+ ACTION_ORDER = {"upgrade": 0, "pin": 1, "remove": 2, "replace": 3, "mitigate": 4, "block": 5, "escalate": 6}
36
+
37
+
38
+ @dataclass
39
+ class PlanContext:
40
+ repo_dir: Path
41
+ http: HttpClient
42
+ cache: Any
43
+ osv: OsvClient
44
+ vulns: list[dict]
45
+ manifests_index: list[Any] # core.models.ManifestFile
46
+ components: list[Any]
47
+ max_candidates: int = 10
48
+ texts: dict[str, Optional[str]] = field(default_factory=dict)
49
+ originals: dict[str, str] = field(default_factory=dict)
50
+
51
+ def text(self, path: str) -> Optional[str]:
52
+ if path not in self.texts:
53
+ self.texts[path] = safe_read_text(self.repo_dir, path, max_bytes=500_000)
54
+ return self.texts[path]
55
+
56
+
57
+ def split_label(label: str) -> tuple[str, str]:
58
+ name, _, ver = label.rpartition("@") if "@" in label[1:] else (label, "", "")
59
+ return (name or label), ver
60
+
61
+
62
+ def manifest_for(ctx: PlanContext, eco: str, service: str, package: str) -> Optional[tuple[str, str]]:
63
+ """Return (manifest path, lock hint) in the service directory that can carry a change for ``package``."""
64
+ svc = service if service not in (None, ".") else ""
65
+ here = [m for m in ctx.manifests_index if (m.service_dir if m.service_dir != "." else "") == svc]
66
+ names = {m.name: m.path for m in here}
67
+ lock_hint = " ".join(m.name for m in here if m.kind == "lockfile")
68
+ if eco == "npm" and "package.json" in names:
69
+ return names["package.json"], lock_hint
70
+ if eco == "PyPI":
71
+ for m in here:
72
+ if m.name.startswith("requirements") and m.name.endswith(".txt"):
73
+ t = ctx.text(m.path) or ""
74
+ if re.search(r"(?im)^\s*" + re.escape(package).replace(r"\-", "[-_.]") + r"\b", t):
75
+ return m.path, lock_hint
76
+ reqs = [m.path for m in here if m.name.startswith("requirements") and m.name.endswith(".txt")]
77
+ if reqs:
78
+ return reqs[0], lock_hint
79
+ if "pyproject.toml" in names:
80
+ return names["pyproject.toml"], lock_hint
81
+ if eco == "Maven" and "pom.xml" in names:
82
+ return names["pom.xml"], lock_hint
83
+ if eco == "Go" and "go.mod" in names:
84
+ return names["go.mod"], lock_hint
85
+ if eco == "crates.io" and "Cargo.toml" in names:
86
+ return names["Cargo.toml"], lock_hint
87
+ if eco == "Packagist" and "composer.json" in names:
88
+ return names["composer.json"], lock_hint
89
+ if eco == "NuGet":
90
+ for m in here:
91
+ if m.name.endswith("proj"):
92
+ return m.path, lock_hint
93
+ return None
94
+
95
+
96
+ def _apply(ctx: PlanContext, eco: str, service: str, changes: list[dict]) -> Optional[dict]:
97
+ """Apply a list of {package, to, kind} to the service's manifest text; returns {path, diff, original} or None if any change cannot be expressed."""
98
+ if not changes:
99
+ return None
100
+ mp = manifest_for(ctx, eco, service, changes[0]["package"])
101
+ if not mp:
102
+ return None
103
+ path, hint = mp
104
+ original = ctx.text(path)
105
+ if original is None:
106
+ return None
107
+ cur = original
108
+ for ch in changes:
109
+ res = patchers.patch_for(eco, path, cur, ch["package"], ch["to"], ch["kind"], hint)
110
+ if not res:
111
+ return None
112
+ cur = res["new_text"]
113
+ if cur == original:
114
+ return None
115
+ ctx.originals[path] = original
116
+ return {"path": path, "diff": patchers.unified_diff(path, original, cur), "new_text": cur}
117
+
118
+
119
+ def _tree_nodes(ctx: PlanContext, eco: str, name: str, ver: str) -> list[tuple[str, str, str]]:
120
+ """(eco, name, version) of every node of the registry-resolved tree of name@ver (falls back to the package itself)."""
121
+ if eco in DEPSDEV_SYSTEM:
122
+ try:
123
+ t = _fetch(ctx.http, ctx.cache, eco, name, ver)
124
+ except Exception:
125
+ t = None
126
+ if t:
127
+ return [(n.get("eco") or eco, n["name"], n["version"]) for n in t["nodes"] if n.get("version")]
128
+ return [(eco, name, ver)]
129
+
130
+
131
+ def _ids(findings: list[dict]) -> set[str]:
132
+ return {i for f in findings for i in (f.get("vulnerability_ids") or [f.get("primary_id")])}
133
+
134
+
135
+ def _min_fix(eco: str, findings: list[dict]) -> Optional[str]:
136
+ fixes = [f["recommended_fix"] for f in findings if f.get("recommended_fix")]
137
+ best: Optional[str] = None
138
+ for v in fixes:
139
+ try:
140
+ if best is None or compare(eco, v, best) > 0:
141
+ best = v
142
+ except VersionError:
143
+ continue
144
+ return best
145
+
146
+
147
+ def search_upgrade(ctx: PlanContext, eco: str, name: str, cur: str, group_findings: list[dict], itself: list[dict]) -> Optional[dict]:
148
+ """Parent-upgrade search. Returns {version, nodes, after, remaining_ids, tried} for the best candidate, or None."""
149
+ target_ids = _ids(group_findings)
150
+ min_version = _min_fix(eco, itself) if itself else None
151
+ vs = list_versions(ctx.http, ctx.cache, eco, name)
152
+ cands = drop_deprecated(ctx.http, ctx.cache, eco, name, candidates(eco, cur, vs, min_version=min_version)[:ctx.max_candidates])
153
+ best = None
154
+ tried = []
155
+ for cand in cands:
156
+ nodes = _tree_nodes(ctx, eco, name, cand)
157
+ try:
158
+ after = check_nodes(ctx.osv, nodes)
159
+ except RuntimeError:
160
+ return best
161
+ remaining = {i for f in after for i in f["ids"] + [f["id"]]} & target_ids
162
+ newhigh = [f for f in after if SEV_RANK.get(f["severity"], 0) >= 3 and not ({*f["ids"], f["id"]} & target_ids)
163
+ and not any(normalize_name(eco, f["package"]) == normalize_name(eco, g["package_name"]) for g in ctx.vulns)]
164
+ tried.append({"version": cand, "remaining": len(remaining), "new_high": len(newhigh)})
165
+ score = (len(remaining), len(newhigh))
166
+ if best is None or score < best["score"]:
167
+ best = {"version": cand, "nodes": nodes, "after": after, "remaining_ids": sorted(remaining), "score": score, "tried": tried}
168
+ if not remaining and not newhigh:
169
+ break
170
+ if best:
171
+ best["tried"] = tried
172
+ return best
173
+
174
+
175
+ def plan_pins(ctx: PlanContext, eco: str, children: list[dict]) -> Optional[dict]:
176
+ """Pin each vulnerable child to the smallest version that clears its advisories (verified against OSV)."""
177
+ by_pkg: dict[str, list[dict]] = {}
178
+ for f in children:
179
+ by_pkg.setdefault(f["package_name"], []).append(f)
180
+ pins, nodes, after_all = [], [], []
181
+ for pkg, fs in by_pkg.items():
182
+ cur = fs[0]["installed_version"]
183
+ mf = _min_fix(eco, fs)
184
+ if not mf:
185
+ return None
186
+ vs = list_versions(ctx.http, ctx.cache, eco, pkg)
187
+ cands = drop_deprecated(ctx.http, ctx.cache, eco, pkg, [mf] + [v for v in candidates(eco, cur, vs, min_version=mf, same_major=4, other_major=2) if v != mf])
188
+ ok = None
189
+ for cand in cands[:5]:
190
+ try:
191
+ after = check_nodes(ctx.osv, [(eco, pkg, cand)])
192
+ except RuntimeError:
193
+ return None
194
+ if not ({i for f in after for i in f["ids"] + [f["id"]]} & _ids(fs)):
195
+ ok = (cand, after)
196
+ break
197
+ if not ok:
198
+ return None
199
+ pins.append({"package": pkg, "from": cur, "to": ok[0], "kind": "pin"})
200
+ nodes.append((eco, pkg, ok[0]))
201
+ after_all += ok[1]
202
+ return {"pins": pins, "nodes": nodes, "after": after_all}
203
+
204
+
205
+ def rollback_text(eco: str, path: str, changes: list[dict]) -> list[str]:
206
+ steps = [f"Revert the change: `git revert <commit>` or `git checkout -- {path}`.", "Restore the previous versions: " + "; ".join(f"{c['package']} {c.get('from', '?')}" for c in changes) + "."]
207
+ if eco in LOCK_REGEN:
208
+ steps.append("Regenerate/refresh the lockfile after reverting: " + LOCK_REGEN[eco] + ".")
209
+ steps.append("Re-run the test suite and the Guardian scan to confirm the previous state.")
210
+ return steps
211
+
212
+
213
+ def best_risk(findings: list[dict], risks: dict[str, dict]) -> tuple[str, str]:
214
+ order = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFORMATIONAL"]
215
+ labs = [(risks.get(f["finding_id"]) or {}).get("label", "INFORMATIONAL") for f in findings]
216
+ lab = min(labs, key=order.index) if labs else "INFORMATIONAL"
217
+ pr = [(risks.get(f["finding_id"]) or {}).get("priority", "P3") for f in findings]
218
+ return lab, min(pr) if pr else "P3"
219
+
220
+
221
+ def plan_group(ctx: PlanContext, g: dict, risks: dict[str, dict], rid: int) -> dict[str, Any]:
222
+ fids = set(g["finding_ids"])
223
+ findings = [f for f in ctx.vulns if f["finding_id"] in fids]
224
+ src_name, src_ver = split_label(g["source_package"])
225
+ eco = findings[0]["ecosystem"]
226
+ service = next((f.get("service_dir") for f in findings if f.get("service_dir")), ".") or "."
227
+ itself = [f for f in findings if normalize_name(eco, f["package_name"]) == normalize_name(eco, src_name)]
228
+ children = [f for f in findings if f not in itself]
229
+ label, priority = best_risk(findings, risks)
230
+ fixable = [f for f in findings if f.get("fixed_versions")]
231
+ rem: dict[str, Any] = {"id": f"REM-{rid:03d}", "source_package": g["source_package"], "root": g["root"], "ecosystem": eco, "service": service, "finding_ids": sorted(fids), "priority": priority, "risk_label": label,
232
+ "packages": g.get("packages", [])[:8], "alternatives": [], "sim": None}
233
+ verdicts = {f.get("verdict") for f in findings}
234
+ kev = any(f.get("kev") for f in findings)
235
+ if not fixable:
236
+ rem.update(action="block" if kev else "mitigate", title=f"No fixed version exists for {len(findings)} finding(s) in {g['source_package']}: " + ("block and escalate" if kev else "mitigate and monitor"),
237
+ target={"package": src_name, "from": src_ver, "to": None}, patch=None, changes=[],
238
+ rationale="The advisories record no fixed release. " + ("At least one finding is actively exploited (CISA KEV), so the component should be blocked until a fix exists. " if kev else "")
239
+ + "Options: replace the library with a maintained alternative, remove the vulnerable code path/feature, or apply the advisory's mitigation; escalate for security review.",
240
+ confidence="medium", rollback=["Nothing is changed by this recommendation."])
241
+ return rem
242
+ changes: list[dict] = []
243
+ sim = None
244
+ if itself or children:
245
+ found = search_upgrade(ctx, eco, src_name, src_ver, findings, itself) if src_ver else None
246
+ if found and not found["remaining_ids"]:
247
+ changes = [{"package": src_name, "from": src_ver, "to": found["version"], "kind": "bump"}]
248
+ sim = {"nodes": found["nodes"], "after": found["after"], "search": found["tried"], "mode": "upgrade"}
249
+ rem["action"] = "upgrade"
250
+ elif children and not itself:
251
+ pins = plan_pins(ctx, eco, children)
252
+ if pins:
253
+ changes = pins["pins"]
254
+ sim = {"nodes": pins["nodes"], "after": pins["after"], "search": found["tried"] if found else [], "mode": "pin"}
255
+ rem["action"] = "pin"
256
+ elif found:
257
+ changes = [{"package": src_name, "from": src_ver, "to": found["version"], "kind": "bump"}]
258
+ sim = {"nodes": found["nodes"], "after": found["after"], "search": found["tried"], "mode": "upgrade"}
259
+ rem["action"] = "upgrade"
260
+ elif found:
261
+ changes = [{"package": src_name, "from": src_ver, "to": found["version"], "kind": "bump"}]
262
+ sim = {"nodes": found["nodes"], "after": found["after"], "search": found["tried"], "mode": "upgrade"}
263
+ rem["action"] = "upgrade"
264
+ if not changes:
265
+ rem.update(action="escalate", title=f"No safe automatic change found for {g['source_package']}", target={"package": src_name, "from": src_ver, "to": None}, patch=None, changes=[],
266
+ rationale="No newer version of the direct dependency clears the findings without leaving some behind, and a verified pin was not possible. Review manually.", confidence="low",
267
+ rollback=["Nothing is changed by this recommendation."])
268
+ return rem
269
+ ch0 = changes[0]
270
+ kind = change_kind(ch0.get("from", ""), ch0["to"])
271
+ patch = _apply(ctx, eco, service, changes)
272
+ first = "pin" if rem["action"] == "pin" else "bump"
273
+ rem.update(title=(f"Upgrade {src_name} {src_ver} -> {ch0['to']}" if rem["action"] == "upgrade" else f"Pin {', '.join(c['package'] + ' to ' + c['to'] for c in changes[:3])}" + (" ..." if len(changes) > 3 else "")),
274
+ target={"package": ch0["package"], "from": ch0.get("from"), "to": ch0["to"], "ecosystem": eco}, changes=changes, sim=sim, patch=patch,
275
+ compatibility={"semver_change": kind, "breaking_risk": "high" if kind == "major" else "medium" if kind == "minor" else "low" if kind == "patch" else "unknown",
276
+ "note": ("Major version change: read the release notes and run the full test suite." if kind == "major" else "Compatibility within the same major line is expected but not verified by this scan.") if first == "bump"
277
+ else "A pin forces a version the parent did not declare compatibility with; run the tests."},
278
+ rollback=rollback_text(eco, patch["path"] if patch else "the manifest", changes),
279
+ lock_note=LOCK_REGEN.get(eco), confidence="high" if patch and sim and not sim["after"] else "medium" if patch else "low")
280
+ reach = {(f.get("reachability") or {}).get("status") for f in findings}
281
+ if reach <= {"not_imported", "used_in_tests_only", None} and verdicts <= {"no_import_evidence", "test_only"}:
282
+ rem["alternatives"].append({"action": "remove", "note": f"No application import of {src_name} (or its children) was found; if it is an unused or dev-only tool, removing it eliminates all {len(findings)} finding(s) with no upgrade risk."})
283
+ if eco in OVERRIDE_HINTS:
284
+ rem["alternatives"].append({"action": "manual", "note": OVERRIDE_HINTS[eco]})
285
+ return rem
@@ -0,0 +1,234 @@
1
+ """Repository Pull Request Template Discovery and Conformance Engine.
2
+
3
+ Finds existing repository PR templates (e.g. .github/pull_request_template.md) and
4
+ conforms strictly to their sections and checklists. If no template exists, renders
5
+ StackParity's standardized enterprise security pull-request format.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from pathlib import Path
11
+ from typing import Any, Optional
12
+
13
+ PR_TEMPLATE_CANDIDATES = [
14
+ ".github/pull_request_template.md",
15
+ ".github/PULL_REQUEST_TEMPLATE.md",
16
+ ".github/pull_request_template.txt",
17
+ "pull_request_template.md",
18
+ "PULL_REQUEST_TEMPLATE.md",
19
+ ".github/PULL_REQUEST_TEMPLATE/default.md",
20
+ ".github/PULL_REQUEST_TEMPLATE/security.md",
21
+ "docs/pull_request_template.md",
22
+ "docs/.github/pull_request_template.md",
23
+ ]
24
+
25
+
26
+ def find_pr_template(repo_dir: Path | str | None) -> Optional[tuple[str, str]]:
27
+ """Scan the repo for an existing PR template. Return (relative_path, text) or None."""
28
+ if not repo_dir:
29
+ return None
30
+ root = Path(repo_dir)
31
+ from core.repository_inspector import safe_read_text
32
+ pr_dir = root / ".github" / "PULL_REQUEST_TEMPLATE"
33
+ candidates = list(PR_TEMPLATE_CANDIDATES)
34
+ if pr_dir.resolve().is_relative_to(root.resolve()) and pr_dir.is_dir():
35
+ candidates.extend(f.relative_to(root).as_posix() for f in sorted(pr_dir.glob("*.md")))
36
+ for rel in candidates:
37
+ text = safe_read_text(root, rel, max_bytes=65536)
38
+ if text and text.strip():
39
+ return rel, text
40
+ return None
41
+
42
+
43
+ def generate_pr_title(rem: dict) -> str:
44
+ """Generate a clean conventional commit title for the pull request."""
45
+ action = rem.get("action", "upgrade")
46
+ src = rem.get("source_package") or rem.get("package") or "dependency"
47
+ target = rem.get("target") or {}
48
+ from_v = target.get("from") or ""
49
+ to_v = target.get("to") or ""
50
+ cves = [f.split()[0] for f in rem.get("finding_ids", []) if "CVE-" in f or "GHSA-" in f]
51
+ cve_tag = f" to resolve {cves[0]}" if cves else ""
52
+
53
+ if action == "upgrade" and from_v and to_v:
54
+ return f"fix(deps): bump {src} from {from_v} to {to_v}{cve_tag}"
55
+ if action == "pin":
56
+ return f"fix(deps): pin transitive dependency {src} to {to_v or 'safe version'}{cve_tag}"
57
+ if action == "remove":
58
+ return f"fix(deps): remove vulnerable dependency {src}{cve_tag}"
59
+ return f"fix(deps): remediate security findings in {src}{cve_tag}"
60
+
61
+
62
+ def _format_reachability_section(impact: dict | None) -> str:
63
+ if not impact:
64
+ return ""
65
+ lines = [
66
+ "### 🎯 Code Reachability & Call Surface Impact",
67
+ f"- **Preservation Score:** {impact.get('reachability_preservation_score', 100)}% preserved",
68
+ f"- **Status:** `{impact.get('status', 'unknown')}` ({impact.get('semver_change', 'n/a')} change)",
69
+ f"- **Files Affected ({len(impact.get('app_files_affected', []))}):** "
70
+ + (", ".join(f"`{f}`" for f in impact.get("app_files_affected", [])[:6]) or "None (isolated/unimported)"),
71
+ ]
72
+ if impact.get("imported_symbols"):
73
+ lines.append(f"- **Imported Symbols:** {', '.join(f'`{s}`' for s in impact['imported_symbols'][:6])}")
74
+ if impact.get("impact_summary"):
75
+ lines.append(f"- **Summary:** {impact['impact_summary']}")
76
+ if impact.get("recommendation"):
77
+ lines.append(f"- **Recommendation:** {impact['recommendation']}")
78
+ return "\n".join(lines)
79
+
80
+
81
+ def _format_verification_section(val: dict, wi: dict) -> str:
82
+ lines = [
83
+ "### 🛡️ Multi-Tier Verification Status",
84
+ f"- **Tier 1 (Patch Applicability):** {'✅ Passed' if val.get('patch_applies') else '❌ Failed'}",
85
+ f"- **Tier 2 (Lockfile Coherence):** {'✅ Verified' if val.get('lockfile_coherence', True) else '⚠️ Requires manual lock refresh'}",
86
+ f"- **Tier 3 (OSV What-If Rescan):** {'✅ ' + str(wi.get('verdict', 'verified')).replace('_', ' ').title() if wi else 'Not simulated'}",
87
+ f"- **Tier 4 (Sandbox Build & Tests):** {(val.get('build_tests') or {}).get('status', 'not_run').replace('_', ' ').title()}",
88
+ f"- **Tier 5 (Security Regression Gate):** {'✅ Passed (No new HIGH/CRITICAL CVEs introduced)' if not wi.get('newly_introduced') else '⚠️ New advisories present'}",
89
+ ]
90
+ return "\n".join(lines)
91
+
92
+
93
+ def _conform_to_repo_template(template: str, rem: dict, repo: dict, approval: Optional[dict], impact: Optional[dict]) -> str:
94
+ """Populate an existing repository pull request template."""
95
+ wi = rem.get("what_if") or {}
96
+ val = rem.get("validation") or {}
97
+ cves = ", ".join(rem.get("finding_ids", [])[:8]) or "security advisory"
98
+
99
+ text = template
100
+
101
+ # Auto-check relevant checkboxes
102
+ def check_boxes(match):
103
+ line = match.group(0)
104
+ lower = line.lower()
105
+ if any(w in lower for w in ("security", "bug fix", "bugfix", "dependency", "dependencies", "deps", "patch")):
106
+ return line.replace("[ ]", "[x]")
107
+ if "tests" in lower and (val.get("patch_applies") or (val.get("build_tests") or {}).get("status") == "passed"):
108
+ return line.replace("[ ]", "[x]")
109
+ return line
110
+
111
+ text = re.sub(r"^[ \t]*- \[[ xX]\] .+$", check_boxes, text, flags=re.M)
112
+
113
+ # Prepare injected evidence summary
114
+ evidence_block = (
115
+ f"\n\n---\n"
116
+ f"### 🛡️ Automated Security Fix Summary (StackParity)\n"
117
+ f"- **Proposal:** {rem['title']} ({rem['action']})\n"
118
+ f"- **Priority:** {rem.get('priority', 'P1')} · **Confidence:** {rem.get('confidence', 'High')}\n"
119
+ f"- **Target Repository:** `{repo.get('url')}` @ `{str(repo.get('commit_sha') or '')[:10]}`\n"
120
+ f"- **Addressed Findings:** {cves}\n\n"
121
+ f"{_format_reachability_section(impact)}\n\n"
122
+ f"{_format_verification_section(val, wi)}\n\n"
123
+ )
124
+ if wi:
125
+ evidence_block += (
126
+ f"**What-If Effect:** Fixed **{len(wi.get('fixed', []))}** finding(s), "
127
+ f"**{len(wi.get('remaining', []))}** remaining, **{len(wi.get('newly_introduced', []))}** introduced.\n\n"
128
+ )
129
+ if rem.get("rollback"):
130
+ evidence_block += "**Rollback Instructions:**\n" + "\n".join(f"{idx}. {step}" for idx, step in enumerate(rem["rollback"], 1)) + "\n\n"
131
+ if approval:
132
+ evidence_block += f"**Approved by:** {approval.get('actor', 'reviewer')} on {approval.get('decided_at', 'n/a')}: {approval.get('reason', '')}\n\n"
133
+
134
+ # Append evidence block to the bottom of the conformed template
135
+ return text.rstrip() + "\n" + evidence_block
136
+
137
+
138
+ def _render_standard_pr(rem: dict, repo: dict, approval: Optional[dict], impact: Optional[dict]) -> str:
139
+ """Render StackParity's standard enterprise security pull-request template."""
140
+ wi = rem.get("what_if") or {}
141
+ val = rem.get("validation") or {}
142
+ target = rem.get("target") or {}
143
+
144
+ lines = [
145
+ f"## {rem['title']}",
146
+ "",
147
+ f"_Proposed by StackParity for `{repo.get('url')}` @ `{(repo.get('commit_sha') or '')[:10]}`; requires human review before merging._",
148
+ "",
149
+ f"**Priority:** `{rem.get('priority', 'P1')}` · **Action:** `{rem['action']}` · **Confidence:** `{rem.get('confidence', 'High')}`",
150
+ "",
151
+ "### 📋 Summary",
152
+ rem.get("rationale") or f"Automated dependency remediation for {rem.get('source_package')}.",
153
+ "",
154
+ f"- **Target Package:** `{rem.get('source_package')}`",
155
+ f"- **Version Delta:** `{target.get('from', 'current')}` ➔ `{target.get('to', 'recommended')}`",
156
+ f"- **Addressed Findings:** {', '.join(rem.get('finding_ids', [])[:10]) or 'None'}",
157
+ "",
158
+ _format_reachability_section(impact),
159
+ "",
160
+ ]
161
+
162
+ if wi:
163
+ lines += [
164
+ "### 📊 Measured Effect (What-If Dependency Simulation)",
165
+ f"- **Fixed Advisories ({len(wi.get('fixed', []))}):** " + (", ".join(f"{f['id']} ({f['package']})" for f in wi.get("fixed", [])[:8]) or "None"),
166
+ f"- **Remaining Advisories:** {len(wi.get('remaining', []))}",
167
+ f"- **Newly Introduced Advisories:** {len(wi.get('newly_introduced', []))}"
168
+ + (" - " + ", ".join(f"{f['id']} ({f['package']}@{f['version']}, {f['severity']})" for f in wi["newly_introduced"][:5]) if wi.get("newly_introduced") else ""),
169
+ f"- **Simulation Verdict:** `{wi.get('verdict', 'unknown').replace('_', ' ').title()}`",
170
+ "",
171
+ ]
172
+ d = wi.get("sbom_diff") or {}
173
+ if d.get("changed") or d.get("added") or d.get("removed"):
174
+ lines += [
175
+ "**SBOM Diff (Affected Sub-Tree)**",
176
+ f"- Changed: {', '.join(c['package'] + ' ' + c['from'] + ' -> ' + c['to'] for c in d.get('changed', [])[:10]) or 'None'}",
177
+ f"- Added: {', '.join(d.get('added', [])[:10]) or 'None'}",
178
+ f"- Removed: {', '.join(d.get('removed', [])[:10]) or 'None'}",
179
+ "",
180
+ ]
181
+
182
+ comp = rem.get("compatibility") or {}
183
+ if comp:
184
+ lines += [
185
+ "### 🔄 Compatibility & Breaking Risk",
186
+ f"- **SemVer Change:** {comp.get('semver_change', 'n/a')}",
187
+ f"- **Breaking Risk:** {comp.get('breaking_risk', 'low')}",
188
+ f"- **Note:** {comp.get('note', '')}",
189
+ "",
190
+ ]
191
+
192
+ lines += [_format_verification_section(val, wi), ""]
193
+
194
+ if rem.get("lock_note"):
195
+ lines += ["### 🔒 Lockfile Refresh Command", f"```bash\n{rem['lock_note']}\n```", ""]
196
+
197
+ if rem.get("rollback"):
198
+ lines += ["### ⏪ Rollback Instructions"]
199
+ lines += [f"{i}. {s}" for i, s in enumerate(rem["rollback"], 1)]
200
+ lines += [""]
201
+
202
+ if approval:
203
+ lines += [
204
+ "### ✅ Approval Audit",
205
+ f"Approved by **{approval.get('actor', 'reviewer')}** at {approval.get('decided_at', '')}: {approval.get('reason', '')}",
206
+ f"- **Decision:** `{approval.get('state', '').replace('_', ' ').title()}`",
207
+ f"- **Reviewer:** **{approval.get('actor', 'reviewer')}**",
208
+ f"- **Timestamp:** {approval.get('decided_at', '')}",
209
+ f"- **Reason:** {approval.get('reason', '')}",
210
+ "",
211
+ ]
212
+
213
+ lines += ["---", f"_No change was applied automatically. Findings: {', '.join(rem.get('finding_ids', [])[:12])}_"]
214
+ return "\n".join(lines)
215
+
216
+
217
+ def render_pull_request(
218
+ rem: dict,
219
+ repo: dict,
220
+ approval: Optional[dict] = None,
221
+ repo_dir: Optional[Path | str] = None,
222
+ impact: Optional[dict] = None,
223
+ ) -> tuple[str, str, bool]:
224
+ """Render PR title and markdown body. Return (title, body, used_repo_template)."""
225
+ title = generate_pr_title(rem)
226
+ found = find_pr_template(repo_dir)
227
+
228
+ if found:
229
+ rel_path, template_text = found
230
+ body = _conform_to_repo_template(template_text, rem, repo, approval, impact)
231
+ return (title, body, True)
232
+
233
+ body = _render_standard_pr(rem, repo, approval, impact)
234
+ return (title, body, False)
@@ -0,0 +1,147 @@
1
+ """Code reachability impact evaluation for remediation library versions.
2
+
3
+ Analyzes how upgrading a dependency from version A to B affects the application's
4
+ active import paths, submodules, and call surface.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import asdict, dataclass, field
9
+ from typing import Any, Optional
10
+
11
+ from reachability.scanners import LANG_ECO, SourceIndex, Usage, _matches
12
+ from remediation.versions import change_kind
13
+
14
+
15
+ @dataclass
16
+ class CodeReachabilityImpact:
17
+ source_package: str
18
+ from_version: str
19
+ to_version: str
20
+ semver_change: str # "patch", "minor", "major", "pin", "none", "unknown"
21
+ status: str # "safe_preserved", "potential_api_shift", "major_breaking_risk", "isolated_unused", "unknown"
22
+ app_files_affected: list[str] = field(default_factory=list)
23
+ test_files_affected: list[str] = field(default_factory=list)
24
+ imported_symbols: list[str] = field(default_factory=list)
25
+ reachability_preservation_score: int = 100 # 0 to 100
26
+ impact_summary: str = ""
27
+ recommendation: str = ""
28
+
29
+ def to_dict(self) -> dict[str, Any]:
30
+ return asdict(self)
31
+
32
+
33
+ def evaluate_reachability_impact(
34
+ idx: Optional[SourceIndex],
35
+ eco: str,
36
+ package_name: str,
37
+ from_version: str,
38
+ to_version: str,
39
+ semver_delta: Optional[str] = None,
40
+ ) -> CodeReachabilityImpact:
41
+ """Evaluate how far upgrading ``package_name`` from ``from_version`` to ``to_version`` affects application imports."""
42
+ semver = semver_delta or change_kind(from_version, to_version)
43
+
44
+ if not idx:
45
+ return CodeReachabilityImpact(
46
+ source_package=package_name,
47
+ from_version=from_version,
48
+ to_version=to_version,
49
+ semver_change=semver,
50
+ status="unknown",
51
+ impact_summary="Source code index was not available; reachability impact could not be evaluated statically.",
52
+ recommendation="Review package release notes before deploying.",
53
+ reachability_preservation_score=80,
54
+ )
55
+
56
+ lang = next((l for l, e in LANG_ECO.items() if e == eco), None)
57
+ if not lang or not idx.files_by_lang.get(lang):
58
+ return CodeReachabilityImpact(
59
+ source_package=package_name,
60
+ from_version=from_version,
61
+ to_version=to_version,
62
+ semver_change=semver,
63
+ status="unknown",
64
+ impact_summary=f"No {eco} source files analyzed in this project.",
65
+ recommendation="Verify import compatibility manually.",
66
+ reachability_preservation_score=85,
67
+ )
68
+
69
+ usages = [u for u in idx.by_lang.get(lang, []) if _matches(eco, package_name, u.module)]
70
+ app_usages = [u for u in usages if not u.test]
71
+ test_usages = [u for u in usages if u.test]
72
+
73
+ app_files = sorted({u.path for u in app_usages})
74
+ test_files = sorted({u.path for u in test_usages})
75
+ symbols = sorted({u.module for u in (app_usages + test_usages)})[:15]
76
+
77
+ app_count = len(app_files)
78
+
79
+ if app_count == 0:
80
+ if len(test_files) > 0:
81
+ status = "isolated_test_only"
82
+ score = 98
83
+ summary = (
84
+ f"{package_name} is only imported in {len(test_files)} test file(s); "
85
+ f"the upgrade from {from_version} to {to_version} ({semver}) has zero production runtime exposure."
86
+ )
87
+ rec = "Run automated test suite after upgrading to ensure test helpers remain compatible."
88
+ else:
89
+ status = "isolated_unused"
90
+ score = 100
91
+ summary = (
92
+ f"No static imports of {package_name} were found in the codebase. "
93
+ f"Upgrading from {from_version} to {to_version} carries zero direct import breakage risk."
94
+ )
95
+ rec = "Clean upgrade or consider removing the dependency if completely unused."
96
+ elif semver in ("patch", "pin", "none"):
97
+ status = "safe_preserved"
98
+ score = 98
99
+ summary = (
100
+ f"All {app_count} application file(s) importing {package_name} use standard module paths. "
101
+ f"Patch upgrade ({from_version} -> {to_version}) preserves API signatures and call surfaces."
102
+ )
103
+ rec = "Safe to apply with standard automated verification."
104
+ elif semver == "minor":
105
+ status = "safe_preserved"
106
+ score = 92
107
+ summary = (
108
+ f"Minor version upgrade ({from_version} -> {to_version}) across {app_count} application file(s). "
109
+ f"Backward compatibility is typically maintained according to SemVer."
110
+ )
111
+ rec = "Apply and review lockfile diff; verify unit test execution."
112
+ elif semver == "major":
113
+ if app_count >= 5:
114
+ status = "major_breaking_risk"
115
+ score = 65
116
+ summary = (
117
+ f"Major version upgrade ({from_version} -> {to_version}) with HEAVY application usage "
118
+ f"across {app_count} files ({', '.join(symbols[:3])}). High probability of breaking API changes or removed methods."
119
+ )
120
+ rec = "Review migration guide and breaking changes before committing; execute sandbox integration tests."
121
+ else:
122
+ status = "potential_api_shift"
123
+ score = 75
124
+ summary = (
125
+ f"Major version upgrade ({from_version} -> {to_version}) affecting {app_count} file(s). "
126
+ f"Imported symbols ({', '.join(symbols[:4])}) may require migration if APIs were deprecated."
127
+ )
128
+ rec = "Inspect imported call sites and run tests before deployment."
129
+ else:
130
+ status = "potential_api_shift"
131
+ score = 80
132
+ summary = f"Version change ({from_version} -> {to_version}) across {app_count} application file(s)."
133
+ rec = "Perform standard verification."
134
+
135
+ return CodeReachabilityImpact(
136
+ source_package=package_name,
137
+ from_version=from_version,
138
+ to_version=to_version,
139
+ semver_change=semver,
140
+ status=status,
141
+ app_files_affected=app_files,
142
+ test_files_affected=test_files,
143
+ imported_symbols=symbols,
144
+ reachability_preservation_score=score,
145
+ impact_summary=summary,
146
+ recommendation=rec,
147
+ )