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,92 @@
1
+ """Candidate version selection for upgrades (deps.dev version lists, ecosystem-aware ordering)."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from typing import Optional
6
+ from urllib.parse import quote
7
+
8
+ from core.http import HttpClient, NotFound, SourceUnavailable
9
+ from sbom.fusion.registries import DEPSDEV_SYSTEM
10
+ from storage.cache import Cache
11
+ from vulnerability.version_matcher import VersionError, compare
12
+
13
+ TTL = 24 * 3600
14
+ _PRE = re.compile(r"(alpha|beta|rc|dev|snapshot|preview|nightly|canary|next|experimental|\.a\d|\.b\d|-\d+$)", re.I)
15
+
16
+
17
+ def list_versions(http: HttpClient, cache: Optional[Cache], eco: str, name: str) -> list[str]:
18
+ key = f"{eco}:{name}"
19
+ hit = cache.get("depsdev_versions", key, ttl=TTL) if cache else None
20
+ if hit is not None:
21
+ return hit
22
+ system = DEPSDEV_SYSTEM.get(eco)
23
+ if not system:
24
+ return []
25
+ try:
26
+ d = http.get_json(f"https://api.deps.dev/v3/systems/{system}/packages/{quote(name, safe='')}")
27
+ except (NotFound, SourceUnavailable):
28
+ return []
29
+ vs = [v["versionKey"]["version"] for v in d.get("versions", []) if v.get("versionKey")]
30
+ if cache:
31
+ cache.set("depsdev_versions", key, vs)
32
+ return vs
33
+
34
+
35
+ def deprecated_message(http: HttpClient, cache: Optional[Cache], eco: str, name: str, ver: str) -> Optional[str]:
36
+ """The npm registry's deprecation notice for name@ver (e.g. a withdrawn 'bad release'), or None. Other ecosystems: None."""
37
+ if eco != "npm":
38
+ return None
39
+ key = f"{name}@{ver}"
40
+ hit = cache.get("npm_deprecated", key, ttl=TTL) if cache else None
41
+ if hit is not None:
42
+ return hit or None
43
+ try:
44
+ d = http.get_json(f"https://registry.npmjs.org/{quote(name, safe='')}/{quote(ver, safe='')}")
45
+ except (NotFound, SourceUnavailable):
46
+ return None
47
+ msg = str(d.get("deprecated") or "")
48
+ if cache:
49
+ cache.set("npm_deprecated", key, msg)
50
+ return msg or None
51
+
52
+
53
+ def drop_deprecated(http: HttpClient, cache: Optional[Cache], eco: str, name: str, versions: list[str]) -> list[str]:
54
+ """Prefer versions that are not deprecated; if every candidate is deprecated keep them all (validation will then warn)."""
55
+ clean = [v for v in versions if not deprecated_message(http, cache, eco, name, v)]
56
+ return clean or versions
57
+
58
+
59
+ def major_of(v: str) -> Optional[int]:
60
+ m = re.match(r"^[vV]?(\d+)", v or "")
61
+ return int(m.group(1)) if m else None
62
+
63
+
64
+ def change_kind(cur: str, new: str) -> str:
65
+ a, b = re.findall(r"\d+", cur or "")[:3], re.findall(r"\d+", new or "")[:3]
66
+ if not a or not b:
67
+ return "unknown"
68
+ a += ["0"] * (3 - len(a))
69
+ b += ["0"] * (3 - len(b))
70
+ return "major" if a[0] != b[0] else "minor" if a[1] != b[1] else "patch"
71
+
72
+
73
+ def candidates(eco: str, current: str, versions: list[str], min_version: Optional[str] = None, same_major: int = 8, other_major: int = 4) -> list[str]:
74
+ """Stable versions newer than ``current`` (and >= ``min_version``), same major first (ascending), then later majors (ascending)."""
75
+ ok: list[str] = []
76
+ for v in versions:
77
+ if _PRE.search(v) and not _PRE.search(current):
78
+ continue
79
+ try:
80
+ if compare(eco, v, current) <= 0:
81
+ continue
82
+ if min_version and compare(eco, v, min_version) < 0:
83
+ continue
84
+ except VersionError:
85
+ continue
86
+ ok.append(v)
87
+ import functools
88
+ ok.sort(key=functools.cmp_to_key(lambda a, b: compare(eco, a, b)))
89
+ cm = major_of(current)
90
+ same = [v for v in ok if major_of(v) == cm]
91
+ other = [v for v in ok if major_of(v) != cm]
92
+ return same[:same_major] + other[:other_major]
@@ -0,0 +1,64 @@
1
+ """Static what-if simulation: apply a proposed change to the inventory *in memory* and re-match advisories.
2
+
3
+ No repository code is built or run. For a parent upgrade the registry-resolved tree of the candidate version (deps.dev) replaces the
4
+ current sub-tree; every node of the new tree is re-checked against OSV with the same local range validation the scan uses. The result
5
+ says exactly what is fixed, what remains, and what would be *newly introduced*.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import Any, Iterable, Optional
10
+
11
+ from core.models import Component
12
+ from sbom.package_extractors.common import make_purl, normalize_name
13
+ from vulnerability.osv_client import OsvClient
14
+ from vulnerability.vulnerability_correlator import correlate
15
+
16
+ SEV_RANK = {"CRITICAL": 4, "HIGH": 3, "MEDIUM": 2, "LOW": 1, None: 0}
17
+
18
+
19
+ def check_nodes(osv: OsvClient, nodes: Iterable[tuple[str, str, str]]) -> list[dict]:
20
+ """Confirmed findings for (ecosystem, name, version) nodes, using the production matching code."""
21
+ comps = [Component(bom_ref=f"{e}:{n}@{v}", name=n, version=v, ecosystem=e, purl=make_purl(e, n, v), service_dir=".") for e, n, v in sorted(set(nodes))]
22
+ if not comps:
23
+ return []
24
+ out = correlate(comps, None, [], osv)
25
+ if out["source_status"]["OSV"]["state"] == "unavailable":
26
+ raise RuntimeError("OSV unavailable")
27
+ return [{"id": f.primary_id, "ids": f.vulnerability_ids, "package": f.package_name, "version": f.installed_version, "severity": f.severity, "ecosystem": f.ecosystem}
28
+ for f in out["findings"] if f.affected_status == "confirmed_affected"]
29
+
30
+
31
+ def sbom_diff(before: set[tuple[str, str]], after: set[tuple[str, str]]) -> dict:
32
+ """before/after are {(name, version)}; changed = same name with a different version."""
33
+ bn, an = {}, {}
34
+ for n, v in before:
35
+ bn.setdefault(n, set()).add(v)
36
+ for n, v in after:
37
+ an.setdefault(n, set()).add(v)
38
+ added = sorted(f"{n}@{v}" for n in an.keys() - bn.keys() for v in an[n])
39
+ removed = sorted(f"{n}@{v}" for n in bn.keys() - an.keys() for v in bn[n])
40
+ changed = sorted([{"package": n, "from": ", ".join(sorted(bn[n])), "to": ", ".join(sorted(an[n]))} for n in bn.keys() & an.keys() if bn[n] != an[n]], key=lambda x: x["package"])
41
+ return {"added": added, "removed": removed, "changed": changed, "unchanged": len({n for n in bn.keys() & an.keys() if bn[n] == an[n]})}
42
+
43
+
44
+ def evaluate(before_findings: list[dict], after_findings: list[dict], before_nodes: set[tuple[str, str]], after_nodes: set[tuple[str, str]], known_all: Optional[list[dict]] = None) -> dict[str, Any]:
45
+ """Compare the finding sets (matched by advisory ids + package) and summarise the effect."""
46
+ def key(f): return (normalize_name(f["ecosystem"], f["package_name"] if "package_name" in f else f["package"]), frozenset(f.get("vulnerability_ids") or f.get("ids") or [f.get("primary_id") or f.get("id")]))
47
+ bset = {key(f): f for f in before_findings}
48
+ remaining, new = [], []
49
+ for f in after_findings:
50
+ k = key(f)
51
+ match = next((b for bk, b in bset.items() if bk[0] == k[0] and (bk[1] & k[1])), None)
52
+ (remaining if match else new).append(f)
53
+ known_keys = [key(f) for f in (known_all or [])]
54
+ elsewhere = [f for f in new if any(key(f)[0] == k[0] and (key(f)[1] & k[1]) for k in known_keys)]
55
+ new = [f for f in new if f not in elsewhere] # already present in the project through another path: not *introduced* by this change
56
+ after_keys = [key(f) for f in after_findings]
57
+ fixed = [f for k, f in bset.items() if not any(k[0] == ak[0] and (k[1] & ak[1]) for ak in after_keys)]
58
+ sev = lambda lst: {s: sum(1 for x in lst if (x.get("severity") or "UNKNOWN") == s) for s in ("CRITICAL", "HIGH", "MEDIUM", "LOW", "UNKNOWN") if any((x.get("severity") or "UNKNOWN") == s for x in lst)} # noqa: E731
59
+ verdict = ("introduces_risk" if any(SEV_RANK.get(x.get("severity"), 0) >= 3 for x in new) else "reduces_risk" if fixed and not remaining and not new else "partial" if fixed else "no_effect")
60
+ return {"before": {"findings": len(before_findings), "by_severity": sev(before_findings)}, "after": {"findings_remaining": len(remaining), "by_severity": sev(remaining)},
61
+ "fixed": [{"id": f.get("primary_id") or f.get("id"), "package": f.get("package_name") or f.get("package"), "version": f.get("installed_version") or f.get("version"), "severity": f.get("severity")} for f in fixed],
62
+ "remaining": [{"id": f.get("id") or f.get("primary_id"), "package": f.get("package") or f.get("package_name"), "version": f.get("version") or f.get("installed_version"), "severity": f.get("severity")} for f in remaining],
63
+ "newly_introduced": [{"id": f["id"], "package": f["package"], "version": f["version"], "severity": f["severity"]} for f in new],
64
+ "already_present_elsewhere": len(elsewhere), "sbom_diff": sbom_diff(before_nodes, after_nodes), "verdict": verdict}
@@ -0,0 +1,434 @@
1
+ """Isolated Git worktree remediation, validation, rescanning, and GitHub PR workflow.
2
+
3
+ Guarantees:
4
+ 1. Never modifies the user's active working directory (uses ``git worktree add``).
5
+ 2. Runs compatibility checks, lockfile regeneration through the ecosystem adapters, restricted tests (when available and
6
+ authorized) and a full rescan, all under the scan's execution policy (``core.netpolicy``).
7
+ 3. Never claims a fix is validated if tests were skipped, unavailable or failed, or a lockfile could not be made consistent.
8
+ 4. Never pushes branches or opens PRs without explicit authorization, never force-pushes, and reuses the branch or PR of an
9
+ earlier attempt for the same changes instead of duplicating it.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import re
17
+ import shutil
18
+ import subprocess
19
+ import tempfile
20
+ import uuid
21
+ from dataclasses import dataclass, field
22
+ from pathlib import Path
23
+ from typing import Optional
24
+
25
+ from core.git_manager import GitError, SAFE_CONFIG, run_git
26
+ from core.safe_env import scrubbed_env
27
+
28
+
29
+ def _branch_name(cands: list) -> str:
30
+ """Deterministic for one set of approved changes, so a retry finds the branch (and PR) of an earlier attempt."""
31
+ digest = hashlib.sha256("\n".join(sorted(f"{c.id}:{c.patch_sha}" for c in cands)).encode()).hexdigest()[:8]
32
+ single = cands[0] if len(cands) == 1 and getattr(cands[0], "changes", None) else None
33
+ pkg, ver = (single.changes[0]["package"], single.changes[0]["to"]) if single else ("security", f"{len(cands)}-changes")
34
+ clean = lambda s: re.sub(r"[^a-zA-Z0-9._-]", "-", str(s)).strip("-.")[:40] or "x" # noqa: E731
35
+ return f"stackparity/fix-{clean(pkg)}-{clean(ver)}-{digest}"
36
+
37
+
38
+ def _remote_git(args: list[str], cwd: Path, timeout: int = 120) -> subprocess.CompletedProcess:
39
+ """git against the user's own remote with their credential helper / SSH agent; hooks and prompts disabled."""
40
+ hooks = "core.hooksPath=NUL" if os.name == "nt" else "core.hooksPath=/dev/null"
41
+ try:
42
+ return subprocess.run(["git", "-c", hooks, *args], cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace",
43
+ timeout=timeout, env={**os.environ, "GIT_TERMINAL_PROMPT": "0"}, shell=False)
44
+ except subprocess.TimeoutExpired as exc:
45
+ raise GitError(f"git {args[0]} timed out after {timeout}s") from exc
46
+
47
+
48
+ def _push_branch(worktree: Path, branch: str) -> None:
49
+ """Push the authorized branch (never forced)."""
50
+ proc = _remote_git(["push", "-u", "origin", f"refs/heads/{branch}:refs/heads/{branch}"], worktree)
51
+ if proc.returncode != 0:
52
+ raise GitError(f"git push failed: {proc.stderr.strip()[:500]}")
53
+
54
+
55
+ def _gh(args: list[str], cwd: Path, timeout: int = 90) -> subprocess.CompletedProcess:
56
+ return subprocess.run([gh_executable() or "gh", *args], cwd=cwd, capture_output=True, text=True, encoding="utf-8", errors="replace",
57
+ timeout=timeout, shell=False)
58
+
59
+
60
+ def remote_state(worktree: Path, branch: str) -> dict:
61
+ """What already exists on the remote for ``branch``: {branch_sha, tree, pr_url, pr_state}. Read-only."""
62
+ out: dict = {"branch_sha": None, "tree": None, "pr_url": None, "pr_state": None}
63
+ ls = _remote_git(["ls-remote", "--heads", "origin", f"refs/heads/{branch}"], worktree, timeout=60)
64
+ if ls.returncode != 0:
65
+ raise GitError(f"git ls-remote failed: {ls.stderr.strip()[:300]}")
66
+ if ls.stdout.strip():
67
+ out["branch_sha"] = ls.stdout.split()[0]
68
+ fetched = _remote_git(["fetch", "--no-tags", "--depth=1", "origin", f"refs/heads/{branch}"], worktree, timeout=120)
69
+ if fetched.returncode == 0:
70
+ out["tree"] = run_git(["rev-parse", "FETCH_HEAD^{tree}"], cwd=worktree, check=False).stdout.strip() or None
71
+ try:
72
+ p = _gh(["pr", "list", "--head", branch, "--state", "all", "--json", "url,state", "--limit", "5"], worktree, timeout=60)
73
+ prs = json.loads(p.stdout or "[]") if p.returncode == 0 else []
74
+ except (OSError, ValueError, subprocess.TimeoutExpired):
75
+ prs = []
76
+ if prs:
77
+ best = next((x for x in prs if x.get("state") == "OPEN"), prs[0])
78
+ out["pr_url"], out["pr_state"] = best.get("url"), best.get("state")
79
+ return out
80
+
81
+
82
+ @dataclass
83
+ class IsolatedRun:
84
+ item_ids: list[str]
85
+ branch: str = ""
86
+ files_changed: list[str] = field(default_factory=list)
87
+ diff: str = ""
88
+ patch_applied: bool = False
89
+ compat_warnings: list[str] = field(default_factory=list)
90
+ lockfiles: list[dict] = field(default_factory=list) # adapters.regenerate entries, plus the candidate id
91
+ generated: dict = field(default_factory=dict) # rel path -> regenerated lockfile text (not part of the reviewed diff)
92
+ generated_originals: dict = field(default_factory=dict) # rel path -> the user's current text of those lockfiles
93
+ lock_consistent: bool = True # False: a lockfile next to a changed manifest was not regenerated and verified
94
+ policy: dict = field(default_factory=dict) # execution policy the run used
95
+ tests_status: str = "not_run"
96
+ tests_detail: str = ""
97
+ rescan: dict = field(default_factory=dict)
98
+ validation_status: str = "unvalidated"
99
+ commit_sha: Optional[str] = None
100
+ commit_message: str = ""
101
+ pr_title: str = ""
102
+ pr_body: str = ""
103
+ pr_url: Optional[str] = None
104
+ published: bool = False
105
+ reused_pr: bool = False
106
+ pushed: bool = False
107
+ error: Optional[str] = None
108
+
109
+
110
+ def gh_executable() -> Optional[str]:
111
+ """GitHub CLI to use: STACKPARITY_GH_BIN when set (absolute path), else 'gh' on PATH."""
112
+ configured = os.environ.get("STACKPARITY_GH_BIN")
113
+ return configured if configured and Path(configured).is_file() else shutil.which("gh")
114
+
115
+
116
+ def _head_text(repo_root: Path, rel: str) -> Optional[str]:
117
+ proc = subprocess.run(["git", *SAFE_CONFIG, "show", f"HEAD:{rel}"], cwd=repo_root, capture_output=True, env=scrubbed_env(), timeout=30, shell=False)
118
+ if proc.returncode != 0:
119
+ return None
120
+ try:
121
+ return proc.stdout.decode("utf-8")
122
+ except UnicodeDecodeError:
123
+ return None
124
+
125
+
126
+ def _working_text(repo_root: Path, rel: str) -> Optional[str]:
127
+ p = Path(repo_root, rel)
128
+ try:
129
+ return p.read_bytes().decode("utf-8") if p.is_file() and not p.is_symlink() else None
130
+ except (OSError, UnicodeDecodeError):
131
+ return None
132
+
133
+
134
+ def _regenerate_lockfiles(wt_path: Path, cands: list, enabled: bool, allow_build_code: bool = False) -> list[dict]:
135
+ """Regenerate and verify the lockfiles next to every changed manifest through the ecosystem adapters."""
136
+ from remediation import adapters
137
+ out: list[dict] = []
138
+ seen: set[str] = set()
139
+ for cand in cands:
140
+ if cand.kind != "dependency" or not cand.patch_path:
141
+ continue
142
+ change = (cand.changes or [{}])[0]
143
+ for e in adapters.regenerate(wt_path, cand.patch_path, cand.ecosystem, change, enabled=enabled, allow_build_code=allow_build_code):
144
+ if e["lockfile"] in seen:
145
+ continue
146
+ seen.add(e["lockfile"])
147
+ out.append({**e, "item": cand.id})
148
+ return out
149
+
150
+
151
+ def _isolated_rescan(wt_path: Path, baseline: dict, s) -> dict:
152
+ from dataclasses import replace
153
+ from core.scan_orchestrator import ScanOptions, scan_local_directory
154
+ from storage.database import Database
155
+ sources = baseline.get("source_status") or {}
156
+ # mirror the baseline: if it did not consult OSV, neither does the comparison scan
157
+ offline = (sources.get("OSV") or {}).get("state") != "ok"
158
+ with tempfile.TemporaryDirectory(dir=s.workspace_dir, ignore_cleanup_errors=True) as scratch:
159
+ trial = replace(s, data_dir=Path(scratch) / "data", artifacts_dir=Path(scratch) / "artifacts")
160
+ for sub_dir in ("sbom", "scans", "reports", "graphs"):
161
+ (trial.artifacts_dir / sub_dir).mkdir(parents=True, exist_ok=True)
162
+ trial.data_dir.mkdir(parents=True, exist_ok=True)
163
+ return scan_local_directory(wt_path, options=ScanOptions(
164
+ url=str(wt_path), offline=offline, use_nvd=(sources.get("NVD") or {}).get("state") not in (None, "disabled"),
165
+ use_kev=(sources.get("CISA KEV") or {}).get("state") not in (None, "disabled"), registry_checks=False,
166
+ metadata_registry=bool(baseline.get("registry_resolution")), investigate=False, remediate=False, sbom_scanner="auto"),
167
+ settings=trial, db=Database(trial.db_path))
168
+
169
+
170
+ def _compare(baseline: dict, after: dict, cands: list) -> dict:
171
+ from reporting.view import non_cve_findings
172
+
173
+ def vid(f):
174
+ return (f.get("ecosystem"), f.get("service_dir"), f.get("package_name"), f.get("primary_id"))
175
+
176
+ def nid(f):
177
+ return (f.get("rule_id"), f.get("file"), (f.get("snippet") or "").strip())
178
+
179
+ targets = {i for c in cands for i in c.finding_ids}
180
+ before_v = baseline.get("vulnerabilities") or []
181
+ after_v = after.get("vulnerabilities") or []
182
+ # advisories can only be compared when both scans consulted them
183
+ osv_ok = all((s.get("source_status") or {}).get("OSV", {}).get("state") == "ok" for s in (baseline, after))
184
+ t_v = {vid(f) for f in before_v if f.get("finding_id") in targets}
185
+ before_n = non_cve_findings(baseline)
186
+ t_n = {nid(f) for f in before_n if f["finding_id"] in targets}
187
+ after_n = {nid(f) for f in non_cve_findings(after)}
188
+ remaining_v = t_v & {vid(f) for f in after_v}
189
+ new_high = {vid(f) for f in after_v if f.get("severity") in ("HIGH", "CRITICAL")} - {vid(f) for f in before_v}
190
+ new_n = after_n - {nid(f) for f in before_n}
191
+ return {"status": after.get("status"), "advisories_checked": osv_ok,
192
+ "targeted_cve": len(t_v), "fixed_cve": len(t_v - remaining_v) if osv_ok else None,
193
+ "remaining_cve": sorted(str(k[3]) for k in remaining_v) if osv_ok else None,
194
+ "new_high_critical": len(new_high) if osv_ok else None,
195
+ "targeted_non_cve": len(t_n), "fixed_non_cve": len(t_n - after_n), "new_non_cve": len(new_n),
196
+ "new_non_cve_titles": sorted(str(k[0]) + " " + str(k[1]) for k in new_n)[:10],
197
+ "complete": after.get("status") == "completed" and (osv_ok or not t_v)}
198
+
199
+
200
+ def run_isolated(repo_root: Path, scan: dict, cands: list, files: dict[str, str], *, run_tests: bool = False, regenerate_locks: bool = False,
201
+ rescan: bool = True, publish=None, base_branch: Optional[str] = None, policy=None, allow_build_code: bool = False) -> IsolatedRun:
202
+ """Apply exactly ``files`` (the materialized approved changes) in a temporary worktree, validate, and optionally publish.
203
+
204
+ ``policy`` is the execution policy (default: the one the scan ran under). ``publish`` is a callable receiving the finished
205
+ IsolatedRun (diff, commit message, PR text) and returning True only when the user authorized pushing the branch and
206
+ opening the pull request. The user's checkout is never modified here, and no StackParity branch is left behind locally.
207
+ """
208
+ from core import netpolicy
209
+ pol = policy or netpolicy.for_scan(scan)
210
+ with netpolicy.use(pol):
211
+ return _run_isolated(repo_root, scan, cands, files, run_tests=run_tests, regenerate_locks=regenerate_locks, rescan=rescan,
212
+ publish=publish, base_branch=base_branch, pol=pol, allow_build_code=allow_build_code)
213
+
214
+
215
+ def _run_isolated(repo_root: Path, scan: dict, cands: list, files: dict[str, str], *, run_tests: bool, regenerate_locks: bool,
216
+ rescan: bool, publish, base_branch: Optional[str], pol, allow_build_code: bool) -> IsolatedRun:
217
+ from config.settings import get_settings
218
+ from remediation.compat import static_compat
219
+ from remediation.lifecycle import read_file, safe_target
220
+ s = get_settings()
221
+ run = IsolatedRun(item_ids=[c.id for c in cands], policy=pol.to_dict())
222
+ repo = scan.get("repo") or {}
223
+ head = run_git(["rev-parse", "HEAD"], cwd=repo_root, check=False).stdout.strip()
224
+ if not head:
225
+ run.error = "The repository has no commit; an isolated worktree needs at least one commit."
226
+ return run
227
+ if repo.get("commit_sha") not in (None, "unversioned") and head != repo["commit_sha"]:
228
+ run.error = "Repository HEAD differs from the scanned commit; rescan the current revision first."
229
+ return run
230
+ for rel in files:
231
+ # git compares through its own line-ending normalization, so a CRLF checkout of an unchanged file is not "modified"
232
+ if run_git(["status", "--porcelain", "--", rel], cwd=repo_root, check=False).stdout.strip():
233
+ run.error = f"{rel} has uncommitted changes. Commit or stash them so the remediation branch contains only approved changes."
234
+ return run
235
+ run.branch = _branch_name(cands)
236
+ if run_git(["rev-parse", "--verify", "--quiet", f"refs/heads/{run.branch}"], cwd=repo_root, check=False).returncode == 0:
237
+ run.error = (f"A local branch named {run.branch} already exists. StackParity does not reuse or delete branches it did not create in this run; "
238
+ f"remove or rename it (git branch -m {run.branch} <new-name>) and retry.")
239
+ return run
240
+ wt_path = (Path(s.workspace_dir) / f"wt_{uuid.uuid4().hex[:10]}").resolve()
241
+ created = False
242
+ try:
243
+ wt_path.parent.mkdir(parents=True, exist_ok=True)
244
+ run_git(["worktree", "add", "-b", run.branch, str(wt_path)], cwd=repo_root, timeout=60)
245
+ created = True
246
+ for rel, text in files.items():
247
+ safe_target(wt_path, rel).write_bytes(text.encode("utf-8"))
248
+ run_git(["add", "--", *files.keys()], cwd=wt_path)
249
+ run.patch_applied = True
250
+ run.files_changed = sorted(files)
251
+
252
+ items = {i.get("id"): i for i in (scan.get("remediation") or {}).get("items") or []}
253
+ compat_failed = False
254
+ for cand in cands:
255
+ if cand.kind == "dependency" and cand.id in items:
256
+ try:
257
+ c_res = static_compat(items[cand.id], wt_path)
258
+ compat_failed |= c_res["status"] == "fail"
259
+ run.compat_warnings += [f"{cand.id}: {c['detail']}" for c in c_res["checks"] if c["status"] != "ok"]
260
+ except Exception as exc:
261
+ run.compat_warnings.append(f"{cand.id}: compatibility check unavailable ({type(exc).__name__})")
262
+ elif cand.kind == "code" and cand.compatibility:
263
+ run.compat_warnings.append(f"{cand.id}: {cand.compatibility}")
264
+
265
+ run.lockfiles = _regenerate_lockfiles(wt_path, cands, regenerate_locks, allow_build_code)
266
+ run.lock_consistent = all(e["status"] == "regenerated" and e["consistent"] for e in run.lockfiles)
267
+ regenerated = [e["lockfile"] for e in run.lockfiles if e["status"] == "regenerated" and (wt_path / e["lockfile"]).exists()]
268
+ for rel in regenerated:
269
+ text = read_file(wt_path, rel)
270
+ if text is not None and text != read_file(repo_root, rel):
271
+ run.generated[rel] = text
272
+ run.generated_originals[rel] = read_file(repo_root, rel) or ""
273
+ if run.generated:
274
+ run_git(["add", "--", *run.generated.keys()], cwd=wt_path)
275
+ run.files_changed = sorted(set(run.files_changed) | set(run.generated))
276
+
277
+ if not run_tests:
278
+ run.tests_status, run.tests_detail = "skipped", "Test execution was not authorized (pass --run-tests)."
279
+ elif not pol.allows("package_manager"):
280
+ run.tests_status, run.tests_detail = "unavailable", f"Installing the project's dependencies in a container needs network access; the execution policy is offline ({pol.origin})."
281
+ else:
282
+ try:
283
+ from sandbox.runner import INSTALL_TIMEOUT, TEST_TIMEOUT, _run, detect_recipe, docker_status
284
+ docker = docker_status()
285
+ dep = next((c for c in cands if c.kind == "dependency"), None)
286
+ recipe = detect_recipe(wt_path, dep.ecosystem if dep else "PyPI", Path(dep.patch_path).parent.as_posix() if dep else ".")
287
+ if docker["available"] and recipe:
288
+ with tempfile.TemporaryDirectory(dir=s.workspace_dir) as temp:
289
+ isolated = Path(temp) / "source"
290
+ shutil.copytree(wt_path, isolated, symlinks=True, ignore=shutil.ignore_patterns(".git", ".env", ".env.*"))
291
+ check = _run(docker["exe"], isolated, recipe, "install", INSTALL_TIMEOUT)
292
+ if check["exit_code"] == 0:
293
+ check = _run(docker["exe"], isolated, recipe, "test", TEST_TIMEOUT)
294
+ run.tests_status = "passed" if check["exit_code"] == 0 else "failed"
295
+ run.tests_detail = f"{check['phase']} exit {check['exit_code']} (container)"
296
+ else:
297
+ run.tests_status, run.tests_detail = "unavailable", docker.get("reason") or "No supported test recipe for this repository."
298
+ except Exception as exc:
299
+ run.tests_status, run.tests_detail = "unavailable", f"Test runner unavailable: {type(exc).__name__}"
300
+
301
+ if rescan:
302
+ try:
303
+ run.rescan = _compare(scan, _isolated_rescan(wt_path, scan, s), cands)
304
+ except Exception as exc:
305
+ run.rescan = {"complete": False, "error": f"{type(exc).__name__}: {str(exc)[:200]}"}
306
+ r = run.rescan
307
+ if compat_failed or run.tests_status == "failed" or (r.get("new_high_critical") or 0) > 0 or r.get("new_non_cve") \
308
+ or any(e["status"] == "failed" or (e["status"] == "regenerated" and not e["consistent"]) for e in run.lockfiles):
309
+ run.validation_status = "failed"
310
+ elif run.tests_status == "passed" and r.get("complete") and not r.get("remaining_cve") and r.get("fixed_non_cve", 0) == r.get("targeted_non_cve", 0) \
311
+ and run.lock_consistent:
312
+ run.validation_status = "validated"
313
+ else:
314
+ run.validation_status = "partially_validated_no_tests" if run.tests_status != "passed" else "unvalidated"
315
+
316
+ run.diff = run_git(["diff", "--cached", "--no-color"], cwd=wt_path).stdout
317
+ run.commit_message, run.pr_title, run.pr_body = _pr_text(scan, cands, run)
318
+
319
+ if publish is not None:
320
+ if run.validation_status == "failed":
321
+ run.error = "Validation failed; nothing was published."
322
+ return run
323
+ run_git(["commit", "-m", run.commit_message], cwd=wt_path, timeout=30)
324
+ run.commit_sha = run_git(["rev-parse", "HEAD"], cwd=wt_path).stdout.strip()
325
+ if not publish(run):
326
+ return run
327
+ # the user authorized publication; the execution policy must allow it too (an offline scan needs --online)
328
+ pol.require("git_remote", "push the remediation branch")
329
+ pol.require("pr_publish", "open the pull request")
330
+ _publish(run, wt_path, base_branch)
331
+ return run
332
+ except GitError as exc:
333
+ run.error = str(exc)
334
+ return run
335
+ except PermissionError as exc: # netpolicy.NetworkDenied
336
+ run.error = str(exc)
337
+ return run
338
+ finally:
339
+ if created:
340
+ run_git(["worktree", "remove", "--force", str(wt_path)], cwd=repo_root, timeout=30, check=False)
341
+ shutil.rmtree(wt_path, ignore_errors=True)
342
+ # Retention policy: the branch was created by this run and holds only its commit. Once pushed it lives on the remote
343
+ # (deleted there only by the user or GitHub after merge); locally it is always removed, so nothing accumulates.
344
+ run_git(["branch", "-D", run.branch], cwd=repo_root, timeout=30, check=False)
345
+
346
+
347
+ def _publish(run: IsolatedRun, wt_path: Path, base_branch: Optional[str]) -> None:
348
+ """Push and open the PR, reusing what an earlier attempt for the same changes already created. Never force-pushes."""
349
+ existing = remote_state(wt_path, run.branch)
350
+ if existing["pr_url"] and existing["pr_state"] == "OPEN":
351
+ run.pr_url, run.published, run.reused_pr = existing["pr_url"], True, True
352
+ return
353
+ if existing["pr_url"]:
354
+ run.error = (f"A pull request for exactly these changes already exists ({str(existing['pr_state']).lower()}): {existing['pr_url']}. "
355
+ "Nothing was pushed; reopen it or change the approved set.")
356
+ return
357
+ if existing["branch_sha"]:
358
+ mine = run_git(["rev-parse", "HEAD^{tree}"], cwd=wt_path).stdout.strip()
359
+ if existing["tree"] != mine:
360
+ run.error = (f"origin already has a branch {run.branch} with different content. StackParity never force-pushes; "
361
+ "delete that remote branch or approve a different set of changes.")
362
+ return
363
+ run.pushed = False # identical content from an earlier attempt whose PR creation failed: reuse it
364
+ else:
365
+ _push_branch(wt_path, run.branch)
366
+ run.pushed = True
367
+ body_file = wt_path.parent / f"{wt_path.name}-pr-body.md"
368
+ body_file.write_text(run.pr_body, encoding="utf-8")
369
+ cmd = ["pr", "create", "--title", run.pr_title, "--body-file", str(body_file), "--head", run.branch] + (["--base", base_branch] if base_branch else [])
370
+ try:
371
+ proc = _gh(cmd, wt_path)
372
+ finally:
373
+ body_file.unlink(missing_ok=True)
374
+ if proc.returncode != 0:
375
+ run.error = (f"The branch {run.branch} is on origin, but gh pr create failed: {(proc.stderr or proc.stdout).strip()[:300]}. "
376
+ "Run the same command again: the pushed branch is reused, nothing is duplicated.")
377
+ return
378
+ urls = re.findall(r"https://\S+/pull/\d+", proc.stdout)
379
+ run.pr_url = urls[-1] if urls else None
380
+ run.published = bool(run.pr_url)
381
+ if not run.pr_url:
382
+ run.error = "gh pr create returned no pull request URL: " + proc.stdout.strip()[:200]
383
+
384
+
385
+ def _pr_text(scan: dict, cands: list, run: IsolatedRun) -> tuple[str, str, str]:
386
+ repo = scan.get("repo") or {}
387
+ cves = sorted({e.get("id") for c in cands if c.kind == "dependency" for e in c.evidence if e.get("id")})
388
+ title = (cands[0].title if len(cands) == 1 else
389
+ f"Remediate {len(cands)} approved security findings" + (f" ({len(cves)} advisories)" if cves else ""))[:120]
390
+ r = run.rescan or {}
391
+ lines = ["## Summary", "", f"This pull request applies {len(cands)} remediation(s) reviewed and approved in StackParity.",
392
+ "It is not merged automatically; review it like any other change.", "", "## Changes", ""]
393
+ for c in cands:
394
+ lines.append(f"### {c.id}: {c.title}")
395
+ lines.append(f"- Severity: {c.severity} | Confidence: {c.confidence} | Type: {'dependency' if c.kind == 'dependency' else 'source/configuration'}")
396
+ if c.kind == "dependency":
397
+ ids = [e["id"] for e in c.evidence if e.get("id")]
398
+ lines.append(f"- Advisories addressed: {', '.join(ids[:20]) or 'none recorded'}" + (" ..." if len(ids) > 20 else ""))
399
+ for ch in c.changes[:10]:
400
+ lines.append(f"- `{ch['package']}` {ch.get('from') or '?'} -> {ch['to']} ({ch.get('kind', 'bump')}) in `{c.patch_path}`")
401
+ else:
402
+ ev = c.evidence[0]
403
+ lines.append(f"- Non-CVE evidence: `{ev.get('id')}` from {ev.get('engine')} at `{ev.get('file')}:{ev.get('line')}`: `{(ev.get('snippet') or '').strip()[:160]}`")
404
+ lines.append(f"- Rationale: {c.rationale}")
405
+ lines.append(f"- Compatibility: {c.compatibility or 'not assessed'}")
406
+ lines.append("")
407
+ lines += ["## Modified files", ""] + [f"- `{p}`" for p in run.files_changed]
408
+ for e in run.lockfiles:
409
+ lines.append(f"- Lockfile `{e['lockfile']}` ({e['adapter']}): {e['status']}"
410
+ + (", verified consistent with the manifest" if e.get("consistent") else
411
+ f", **not consistent with the manifest**: run `{e['command']}`") + f". {e['detail']}".rstrip())
412
+ if run.policy.get("mode") == "offline":
413
+ lines.append(f"- Validation ran under an offline execution policy ({run.policy.get('origin')}); network-dependent checks are reported as unverified.")
414
+ fixed_cve = "not measured" if r.get("fixed_cve") is None else f"{r.get('fixed_cve')} of {r.get('targeted_cve')}"
415
+ new_hc = "not measured" if r.get("new_high_critical") is None else r.get("new_high_critical")
416
+ lines += ["", "## Validation (actual results)", "",
417
+ f"- Validation status: `{run.validation_status}`",
418
+ f"- Tests: `{run.tests_status}` ({run.tests_detail})",
419
+ f"- Rescan of the changed tree: advisories fixed {fixed_cve}; new high/critical advisories: {new_hc}; "
420
+ f"non-CVE findings fixed {r.get('fixed_non_cve', 'n/a')} of {r.get('targeted_non_cve', 0)}; new non-CVE findings: {r.get('new_non_cve', 'n/a')}"]
421
+ if r.get("error"):
422
+ lines.append(f"- Rescan error: {r['error']}")
423
+ lines.append("- Compatibility notes: " + ("; ".join(run.compat_warnings[:10]) or "none"))
424
+ remaining = r.get("remaining_cve") or []
425
+ lines += ["", "## Remaining risks", "",
426
+ f"- Advisories still present after this change: {', '.join(remaining[:20])}" if remaining else
427
+ ("- No targeted advisory remained in the rescan." if r.get("advisories_checked") else "- Advisories were not re-checked (offline or unavailable)."),
428
+ "- Findings that were not approved, or that have only manual recommendations, are not addressed here.",
429
+ "", "## References", "", f"- StackParity scan `{repo.get('scan_id')}` of commit `{(repo.get('commit_sha') or '')[:12]}`",
430
+ f"- Remediation IDs: {', '.join(c.id for c in cands)}"]
431
+ message = f"fix(security): {title[:1].lower() + title[1:]}\n\nApproved StackParity remediations: {', '.join(c.id for c in cands)}\nScan: {repo.get('scan_id')}"
432
+ if cves:
433
+ message += "\nAdvisories: " + ", ".join(cves[:30])
434
+ return message, title, "\n".join(lines)
File without changes