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,248 @@
1
+ """Remediation Agent (plans the smallest safe change) and Validator Agent (proves it: what-if rescan, before/after SBOM, patch check).
2
+
3
+ Both are deterministic and evidence-based; every proposal is *only a proposal*: it needs human approval (UI) before the patch/PR text can be exported,
4
+ and nothing is ever applied, pushed or merged by the Guardian.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import subprocess
9
+ import tempfile
10
+ import time
11
+ from pathlib import Path
12
+
13
+ import networkx as nx
14
+
15
+ from agents.runtime import Runtime
16
+ from agents.specialists import ScanState, source_package_view
17
+ from core import git_manager as gm
18
+ from remediation import whatif
19
+ from remediation.delivery import get_remediation_severity_tier
20
+ from remediation.planner import PlanContext, plan_group, split_label
21
+ from remediation.reachability_impact import evaluate_reachability_impact
22
+ from vulnerability.osv_client import OsvClient
23
+
24
+ PRIO = {"P0": 0, "P1": 1, "P2": 2, "P3": 3}
25
+
26
+
27
+ def fingerprint(rem: dict) -> str:
28
+ t = rem.get("target") or {}
29
+ return "|".join(["rem", rem.get("ecosystem") or "", rem.get("service") or ".", rem.get("source_package") or "", rem.get("action") or "", f"{t.get('from')}->{t.get('to')}"])
30
+
31
+
32
+ class RemediationAgent:
33
+ name = "Remediation Agent"
34
+
35
+ def run(self, st: ScanState, rt: Runtime) -> None:
36
+ o, s = st.options, st.ctx.s
37
+ if not getattr(o, "remediate", True):
38
+ rt.skip("remediate", "disabled in the scan options")
39
+ return
40
+ if not st.vulns:
41
+ rt.skip("remediate", "no vulnerability findings to remediate")
42
+ return
43
+ with rt.step("remediate", "Planning the smallest safe change per source package (parent-upgrade search, pins, mitigations)") as b:
44
+ risks = {a["finding_id"]: a for a in st.risk["assessments"]}
45
+ groups = source_package_view(st.vulns, risks)
46
+
47
+ def group_urgency(g: dict) -> tuple[int, int, int]:
48
+ prio = min((risks.get(i, {}).get("priority", "P3") for i in g["finding_ids"]), default="P3")
49
+ has_heavy = any(risks.get(i, {}).get("influence_tier") == "heavy" or risks.get(i, {}).get("app_files", 0) >= 5 for i in g["finding_ids"])
50
+ is_dev = all(bool(next((f.get("dev_dependency") for f in st.vulns if f["finding_id"] == i), False)) for i in g["finding_ids"])
51
+ p_val = PRIO.get(prio, 3)
52
+ if prio == "P0":
53
+ rank = 0
54
+ elif has_heavy and not is_dev:
55
+ rank = 1
56
+ elif prio == "P1":
57
+ rank = 2
58
+ elif prio == "P2" and not is_dev:
59
+ rank = 3
60
+ else:
61
+ rank = 4
62
+ return (rank, p_val, -len(g["finding_ids"]))
63
+
64
+ groups.sort(key=group_urgency)
65
+ osv = OsvClient(st.ctx.http, st.ctx.cache, s.osv_batch_size, s.osv_workers)
66
+ ctx = PlanContext(repo_dir=st.repo_dir, http=st.ctx.http, cache=st.ctx.cache, osv=osv, vulns=st.vulns, manifests_index=st.insp.manifests, components=st.components)
67
+ items, sims, skipped = [], {}, 0
68
+ t0 = time.time()
69
+ container_ids = {f["finding_id"] for f in st.vulns if f.get("asset_type") == "container_image"}
70
+ for g in groups:
71
+ if container_ids and set(g["finding_ids"]) <= container_ids:
72
+ continue # OS/image packages are planned below from the distro's own fix data, not through language registries
73
+ if len(items) >= s.remediation_max_groups or time.time() - t0 > s.remediation_budget_s:
74
+ skipped += 1
75
+ continue
76
+ try:
77
+ rem = plan_group(ctx, g, risks, len(items) + 1)
78
+ except Exception as e: # noqa: BLE001 - one group failing must not lose the others
79
+ rt.warn("remediate", f"Could not plan {g['source_package']}: {type(e).__name__}: {str(e)[:100]}")
80
+ skipped += 1
81
+ continue
82
+ sims[rem["id"]] = rem.pop("sim", None)
83
+ rem["fingerprint"] = fingerprint(rem)
84
+ t_info = rem.get("target") or {}
85
+ src_pkg = rem.get("source_package") or rem.get("package") or ""
86
+ impact = evaluate_reachability_impact(
87
+ st.source_index,
88
+ rem.get("ecosystem", "npm"),
89
+ src_pkg,
90
+ t_info.get("from") or "current",
91
+ t_info.get("to") or "recommended",
92
+ semver_delta=(rem.get("compatibility") or {}).get("semver_change"),
93
+ )
94
+ rem["reachability_impact"] = impact.to_dict()
95
+ items.append(rem)
96
+ rt.progress("remediate", f"{rem['id']} {rem['action']}: {rem['title']}", id=rem["id"])
97
+ if container_ids:
98
+ from remediation.container_plan import plan_container_groups
99
+ from remediation.planner import best_risk
100
+ try:
101
+ for rem in plan_container_groups(ctx, st.vulns, risks, len(items) + 1, best_risk):
102
+ rem.pop("sim", None)
103
+ rem["fingerprint"] = fingerprint(rem)
104
+ rem["reachability_impact"] = {}
105
+ items.append(rem)
106
+ rt.progress("remediate", f"{rem['id']} {rem['action']}: {rem['title']}", id=rem["id"])
107
+ except Exception as e: # noqa: BLE001
108
+ rt.warn("remediate", f"Could not plan container findings: {type(e).__name__}: {str(e)[:100]}")
109
+ # Scanning records proposals. Only an explicit delivery command may publish.
110
+ for rem in items:
111
+ tier, label = get_remediation_severity_tier(rem, st.vulns)
112
+ rem["automation_tier"] = tier
113
+ rem["severity_tier"] = label
114
+ rem["requires_human_intervention"] = True
115
+
116
+ low_med = [r for r in items if r.get("automation_tier") == "automated"]
117
+ high_crit = [r for r in items if r.get("automation_tier") == "manual_review"]
118
+
119
+ st.rem_sims = sims
120
+ st.remediation = {"items": items, "manifests": {p: t[:200000] for p, t in ctx.originals.items()}, "groups_total": len(groups), "groups_not_planned": skipped,
121
+ "budget_seconds": s.remediation_budget_s, "automated_low_med": len(low_med), "manual_high_crit": len(high_crit)}
122
+ acts: dict[str, int] = {}
123
+ for r in items:
124
+ acts[r["action"]] = acts.get(r["action"], 0) + 1
125
+ rt.observe("remediate", f"{len(items)} remediation(s) planned: " + ", ".join(f"{v} {k}" for k, v in sorted(acts.items())) + (f"; {len(low_med)} Low/Medium proposal(s)" if low_med else ""))
126
+ if high_crit:
127
+ rt.decide("remediate", f"Require human approval for {len(high_crit)} High/Critical severity proposal(s)", reason="High and Critical severity changes require manual verification (Accept or Ignore in Streamlit).", agent="Supervisor")
128
+ b["message"] = f"{len(items)} remediation(s) ({len(low_med)} low/medium, {len(high_crit)} manual)"
129
+
130
+
131
+ class ValidatorAgent:
132
+ name = "Validator Agent"
133
+
134
+ def run(self, st: ScanState, rt: Runtime) -> None:
135
+ items = (st.remediation or {}).get("items") or []
136
+ if not items:
137
+ rt.skip("validate_fix", "no remediation proposals to validate")
138
+ return
139
+ with rt.step("validate_fix", "Validating proposals: what-if rescan, before/after SBOM, patch applicability") as b:
140
+ counts = {"reduces_risk": 0, "partial": 0, "no_effect": 0, "introduces_risk": 0, "not_simulated": 0}
141
+ for rem in items:
142
+ sim = st.rem_sims.get(rem["id"])
143
+ before = [f for f in st.vulns if f["finding_id"] in set(rem["finding_ids"])]
144
+ if sim is None:
145
+ rem["what_if"] = None
146
+ counts["not_simulated"] += 1
147
+ else:
148
+ b_nodes = self._before_nodes(st, rem, before, sim)
149
+ a_nodes = {(n, v) for _, n, v in sim["nodes"]}
150
+ wi = whatif.evaluate(before, sim["after"], b_nodes, a_nodes, known_all=st.vulns)
151
+ wi.update(method="registry-resolved dependency tree (deps.dev) + OSV re-match with local range validation", candidates_tried=sim.get("search", []))
152
+ rem["what_if"] = wi
153
+ counts[wi["verdict"]] += 1
154
+ rem["evidence_id"] = st.evidence.add("what-if", "what-if-simulator", rem["id"], f"{rem['title']}: fixes {len(wi['fixed'])}, remaining {len(wi['remaining'])}, new {len(wi['newly_introduced'])}",
155
+ {"verdict": wi["verdict"], "fixed": len(wi["fixed"]), "new": len(wi["newly_introduced"])})
156
+ if wi["newly_introduced"]:
157
+ rt.warn("validate_fix", f"{rem['id']} would introduce {len(wi['newly_introduced'])} new finding(s): " + ", ".join(f"{f['id']} ({f['package']})" for f in wi["newly_introduced"][:3]))
158
+ if not rem.get("rationale"):
159
+ rem["rationale"] = self._rationale(rem, before)
160
+ applies = self._check_patch(st, rem)
161
+
162
+ wi_obj = rem.get("what_if")
163
+ wi_passed = bool(wi_obj and wi_obj.get("verdict") in ("reduces_risk", "partial"))
164
+ new_cves = len(wi_obj.get("newly_introduced", [])) if wi_obj else 0
165
+ lock_note = rem.get("lock_note", "")
166
+
167
+ matrix = {
168
+ "tier_1_patch": {"name": "Tier 1: Patch Applicability", "passed": bool(applies),
169
+ "details": "Patch applies cleanly without conflicts" if applies else "Patch cannot be applied cleanly"},
170
+ "tier_2_lockfile": {"name": "Tier 2: Lockfile Coherence", "passed": None,
171
+ "details": f"Refresh command: {lock_note}" if lock_note else "Standard manifest update"},
172
+ "tier_3_whatif": {"name": "Tier 3: OSV What-If Rescan", "passed": wi_passed,
173
+ "details": f"Verdict: {wi_obj.get('verdict', 'not_simulated')} (Fixed {len(wi_obj.get('fixed', []))}, Remaining {len(wi_obj.get('remaining', []))})" if wi_obj else "Not simulated"},
174
+ "tier_4_sandbox": {"name": "Tier 4: Sandbox Build & Tests", "status": "not_run", "passed": None,
175
+ "details": "Opt-in: execute in isolated Docker container upon user request"},
176
+ "tier_5_security_gate": {"name": "Tier 5: Security Regression Gate", "passed": (new_cves == 0 if wi_obj else None),
177
+ "details": "No comparison available" if not wi_obj else "No new advisories found in comparison" if new_cves == 0 else f"{new_cves} new advisory(ies) introduced"},
178
+ }
179
+
180
+ rem["validation"] = {"patch_applies": applies, "what_if_run": sim is not None,
181
+ "matrix": matrix,
182
+ "build_tests": {"status": "not_run", "reason": "Static what-if only: the repository's build and tests are not executed (optional sandbox validation can be enabled)."}}
183
+ st.remediation["validation_summary"] = counts
184
+ rt.observe("validate_fix", "What-if results: " + ", ".join(f"{v} {k.replace('_', ' ')}" for k, v in counts.items() if v))
185
+ bad = [r["id"] for r in items if (r.get("validation") or {}).get("patch_applies") is False]
186
+ if bad:
187
+ rt.warn("validate_fix", "Patch does not apply cleanly for: " + ", ".join(bad))
188
+ b["message"] = ", ".join(f"{v} {k.replace('_', ' ')}" for k, v in counts.items() if v)
189
+
190
+ @staticmethod
191
+ def _rationale(rem: dict, before: list[dict]) -> str:
192
+ wi = rem.get("what_if") or {}
193
+ verdicts: dict[str, int] = {}
194
+ for f in before:
195
+ verdicts[(f.get("verdict") or "not investigated").replace("_", " ")] = verdicts.get((f.get("verdict") or "not investigated").replace("_", " "), 0) + 1
196
+ sev = ", ".join(f"{n} {k.title()}" for k, n in (wi.get("before", {}).get("by_severity") or {}).items())
197
+ t = rem.get("target") or {}
198
+ parts = []
199
+ if rem["action"] == "upgrade":
200
+ tried = len(wi.get("candidates_tried") or [])
201
+ parts.append(f"{rem['source_package']} introduces {len(before)} finding(s) ({sev or 'severity n/a'}). Upgrading to {t.get('to')} is the smallest version found "
202
+ f"(searched {tried} candidate version(s), same major first) whose registry-resolved dependency tree no longer contains any of these advisories.")
203
+ else:
204
+ parts.append(f"No newer release of {rem['source_package']} clears the findings, so the vulnerable transitive package(s) are pinned to the smallest fixed version(s): "
205
+ + ", ".join(f"{c['package']} {c.get('from')} -> {c['to']}" for c in rem.get("changes", [])[:4]) + ". The pinned versions were re-checked against OSV.")
206
+ if wi:
207
+ parts.append(f"Measured effect: fixes {len(wi.get('fixed', []))}, {len(wi.get('remaining', []))} remain in this group, {len(wi.get('newly_introduced', []))} newly introduced"
208
+ + (f" (worst: {max((x['severity'] or 'UNKNOWN' for x in wi['newly_introduced']), key=lambda s: ['UNKNOWN', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'].index(s))})" if wi.get("newly_introduced") else "")
209
+ + (f"; {wi['already_present_elsewhere']} advisory(ies) on the new tree are already present in the project through another path" if wi.get("already_present_elsewhere") else "") + ".")
210
+ parts.append("Investigation verdicts in this group: " + ", ".join(f"{n} {k}" for k, n in sorted(verdicts.items(), key=lambda kv: -kv[1])) + ".")
211
+ if rem.get("evidence_id"):
212
+ parts.append(f"[{rem['evidence_id']}]")
213
+ return " ".join(parts)
214
+
215
+ @staticmethod
216
+ def _before_nodes(st: ScanState, rem: dict, before: list[dict], sim: dict) -> set[tuple[str, str]]:
217
+ if sim.get("mode") == "pin":
218
+ return {(f["package_name"], f["installed_version"]) for f in before}
219
+ name, ver = split_label(rem["source_package"])
220
+ nodes = {(name, ver)}
221
+ g = st.graph
222
+ ref = next((n for n, a in g.nodes(data=True) if a.get("label") == rem["source_package"]), None)
223
+ if ref is not None:
224
+ for d in nx.descendants(g, ref):
225
+ a = g.nodes[d]
226
+ if a.get("kind") == "component" and a.get("version"):
227
+ nodes.add((a.get("name"), a.get("version")))
228
+ return nodes
229
+
230
+ @staticmethod
231
+ def _check_patch(st: ScanState, rem: dict) -> bool | None:
232
+ """``git apply --check`` against the original manifest in a throw-away directory. None = no patch to check."""
233
+ p = rem.get("patch")
234
+ if not p:
235
+ return None
236
+ original = st.remediation["manifests"].get(p["path"])
237
+ if original is None:
238
+ return None
239
+ with tempfile.TemporaryDirectory() as td:
240
+ f = Path(td) / p["path"]
241
+ f.parent.mkdir(parents=True, exist_ok=True)
242
+ f.write_text(original, encoding="utf-8", newline="")
243
+ (Path(td) / "fix.patch").write_text(p["diff"], encoding="utf-8", newline="")
244
+ try:
245
+ r = gm.run_git(["apply", "--check", "fix.patch"], cwd=Path(td), check=False, timeout=30)
246
+ except gm.GitError:
247
+ return None
248
+ return r.returncode == 0
@@ -0,0 +1,177 @@
1
+ """Agent runtime: shared scan state, a step catalogue with weighted progress, and an append-only decision trace.
2
+
3
+ Every agent reports through ``Runtime`` so the UI can show a live progress bar, per-agent activity and every
4
+ decision (what was observed, what was decided and why). The trace is stored with the scan result.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import threading
9
+ import time
10
+ import traceback
11
+ from contextlib import contextmanager
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Callable, Optional
14
+
15
+ # (step id, owning agent, label) - the full pipeline. Progress = finished steps / total.
16
+ STEPS: list[tuple[str, str, str]] = [
17
+ ("validate", "Supervisor", "Validate the repository URL"),
18
+ ("clone", "Recon Agent", "Clone the repository into an isolated workspace"),
19
+ ("discover", "Recon Agent", "Find manifest, lock and configuration files"),
20
+ ("classify", "Recon Agent", "Detect languages, frameworks and services"),
21
+ ("plan", "Supervisor", "Plan the analysis strategy"),
22
+ ("lockfiles", "SBOM Agent", "Parse lockfiles (independent inventory)"),
23
+ ("sbom_generate", "SBOM Agent", "Generate the CycloneDX SBOM (Syft, Trivy or built-in rule engine)"),
24
+ ("sbom_validate", "SBOM Agent", "Validate the SBOM"),
25
+ ("pipeline", "Pipeline Agent", "Analyse Dockerfiles, compose files and CI/CD workflows"),
26
+ ("quality", "SBOM Agent", "Assess SBOM quality and completeness"),
27
+ ("metadata", "SBOM Agent", "Fuse metadata (lockfile + scanner + registries) and verify integrity"),
28
+ ("graph", "Graph Agent", "Build the dependency graph"),
29
+ ("osv", "Vulnerability Agent", "Query OSV and validate affected version ranges"),
30
+ ("enrich", "Vulnerability Agent", "Enrich with NVD (CVSS) and CISA KEV"),
31
+ ("trace", "Vulnerability Agent", "Trace each vulnerable component to its source package"),
32
+ ("verify", "Verification Agent", "Cross-check findings against OSV by PURL (ground truth)"),
33
+ ("investigate", "Investigator Agent", "Investigate findings: reachability, EPSS exploitability, evidence-backed verdict"),
34
+ ("typosquat", "Threat Agent", "Typosquatting analysis"),
35
+ ("package_risk", "Threat Agent", "Package risk: integrity, install scripts, provenance, dependency confusion"),
36
+ ("lockfile_history", "Threat Agent", "Compare lockfiles against Git history"),
37
+ ("suspicious_changes", "Threat Agent", "Forensic non-CVE suspicious change & AI investigation"),
38
+ ("risk", "Risk Agent", "Deterministic risk scoring and correlation"),
39
+ ("explain", "Risk Agent", "Evidence-grounded explanations"),
40
+ ("remediate", "Remediation Agent", "Plan the smallest safe change per source package"),
41
+ ("validate_fix", "Validator Agent", "Validate proposals: what-if rescan, before/after SBOM, patch check"),
42
+ ("memory", "Memory Agent", "Compare with previous scans and record finding history"),
43
+ ("summary", "Analyst Agent", "Executive summary and prioritised actions"),
44
+ ("export", "Analyst Agent", "Write reports and save to SQLite"),
45
+ ("cleanup", "Supervisor", "Clean up the temporary workspace"),
46
+ ]
47
+ STEP_INDEX = {s[0]: i for i, s in enumerate(STEPS)}
48
+ AGENTS = list(dict.fromkeys(s[1] for s in STEPS))
49
+
50
+ AGENT_ROLES = {
51
+ "Supervisor": "Plans the run, observes every agent's result, and adapts (fallbacks, retries, triage) - owns the decision trace.",
52
+ "Recon Agent": "Acquires the repository safely and discovers what it contains (config files, ecosystems, frameworks, services).",
53
+ "SBOM Agent": "Builds the software inventory: lockfile parsing, CycloneDX generation (Syft / Trivy / built-in rule engine), validation and quality assessment.",
54
+ "Investigator Agent": "Investigates each finding with read-only tools (import/reachability evidence, EPSS, dependency path) and issues a verdict with confidence and cited evidence; optional LLM reasoning behind a grounding gate.",
55
+ "Pipeline Agent": "Analyses Dockerfiles, docker-compose and CI/CD definitions (GitHub Actions, GitLab, Jenkins, ...) for unsafe or unpinned components; images and actions join the SBOM.",
56
+ "Graph Agent": "Builds the directed dependency graph and checks its integrity.",
57
+ "Vulnerability Agent": "Correlates components with OSV, validates ranges, enriches with NVD/KEV, traces findings to source packages.",
58
+ "Verification Agent": "Independently re-checks findings against the ground-truth database via a second query route.",
59
+ "Threat Agent": "Detects suspicious dependency changes: typosquatting and modified lockfiles in Git history.",
60
+ "Risk Agent": "Scores risk with transparent rules, correlates detections and writes evidence-grounded explanations.",
61
+ "Remediation Agent": "Chooses upgrade / pin / remove / mitigate / block / escalate per source package, searches parent versions via registry resolution, and drafts a reviewable patch with rationale and rollback.",
62
+ "Validator Agent": "Proves a proposal without running repository code: re-resolves the dependency tree, re-matches advisories (fixed, remaining, newly introduced), diffs the SBOM and checks the patch applies.",
63
+ "Memory Agent": "Remembers every scan: tells new findings from persisting and fixed ones, keeps analyst decisions with reasons and expiry.",
64
+ "Analyst Agent": "Summarises results, prioritises actions, and produces reports.",
65
+ }
66
+
67
+
68
+ @dataclass
69
+ class Event:
70
+ ts: float
71
+ agent: str
72
+ step: str
73
+ kind: str # start | progress | done | skip | decision | observation | warning | error
74
+ message: str
75
+ progress: float # overall 0..1 after this event
76
+ detail: dict = field(default_factory=dict)
77
+
78
+ def to_dict(self) -> dict:
79
+ return {"t": round(self.ts, 2), "agent": self.agent, "step": self.step, "kind": self.kind, "message": self.message,
80
+ "progress": round(self.progress, 3), "detail": self.detail}
81
+
82
+
83
+ class Runtime:
84
+ """Collects events, computes overall progress, isolates step failures."""
85
+
86
+ def __init__(self, on_event: Optional[Callable[[dict], None]] = None):
87
+ self.t0 = time.time()
88
+ self.on_event = on_event
89
+ self.events: list[Event] = []
90
+ self.status: dict[str, str] = {s[0]: "pending" for s in STEPS} # pending|running|done|skipped|error
91
+ self.timings: dict[str, float] = {}
92
+ self.errors: list[dict] = []
93
+ self._started: dict[str, float] = {}
94
+ self._lock = threading.RLock() # agents on parallel graph branches share this runtime
95
+ self.callback_errors = 0
96
+
97
+ # ---------------------------------------------------------------- progress
98
+ def overall(self) -> float:
99
+ done = sum(1 for v in self.status.values() if v in ("done", "skipped", "error"))
100
+ running = sum(1 for v in self.status.values() if v == "running")
101
+ return min((done + 0.5 * running) / len(STEPS), 1.0)
102
+
103
+ def _emit(self, step: str, kind: str, message: str, detail: Optional[dict] = None, agent: Optional[str] = None) -> None:
104
+ agent = agent or (STEPS[STEP_INDEX[step]][1] if step in STEP_INDEX else "Supervisor")
105
+ with self._lock:
106
+ ev = Event(time.time() - self.t0, agent, step, kind, message, self.overall(), detail or {})
107
+ self.events.append(ev)
108
+ payload = {**ev.to_dict(), "label": STEPS[STEP_INDEX[step]][2] if step in STEP_INDEX else step, "status": dict(self.status)}
109
+ if self.on_event:
110
+ try:
111
+ self.on_event(payload)
112
+ except Exception:
113
+ self.callback_errors += 1 # UI callback problems must never break a scan (counted, surfaced in the result)
114
+
115
+ # ---------------------------------------------------------------- step lifecycle
116
+ def begin(self, step: str, message: str = "") -> None:
117
+ with self._lock:
118
+ if self.status[step] == "running":
119
+ self._emit(step, "progress", message)
120
+ return
121
+ self.status[step] = "running"
122
+ self._started[step] = time.time()
123
+ self._emit(step, "start", message or STEPS[STEP_INDEX[step]][2])
124
+
125
+ def progress(self, step: str, message: str, **detail: Any) -> None:
126
+ self._emit(step, "progress", message, detail)
127
+
128
+ def done(self, step: str, message: str = "", **detail: Any) -> None:
129
+ with self._lock:
130
+ if self.status[step] == "pending":
131
+ self._started[step] = time.time()
132
+ self.status[step] = "done"
133
+ self.timings[step] = round(time.time() - self._started.get(step, time.time()), 2)
134
+ self._emit(step, "done", message or "done", detail)
135
+
136
+ def skip(self, step: str, reason: str) -> None:
137
+ with self._lock:
138
+ self.status[step] = "skipped"
139
+ self._emit(step, "skip", reason)
140
+
141
+ def fail(self, step: str, err: str) -> None:
142
+ with self._lock:
143
+ self.status[step] = "error"
144
+ self.errors.append({"stage": step, "error": err})
145
+ self._emit(step, "error", err)
146
+
147
+ def finish_open(self, step: str, message: str = "done") -> None:
148
+ if self.status[step] == "running":
149
+ self.done(step, message)
150
+
151
+ # ---------------------------------------------------------------- agent reasoning
152
+ def observe(self, step: str, message: str, agent: Optional[str] = None, **detail: Any) -> None:
153
+ self._emit(step, "observation", message, detail, agent)
154
+
155
+ def decide(self, step: str, message: str, reason: str = "", agent: Optional[str] = None, **detail: Any) -> None:
156
+ self._emit(step, "decision", message, {"reason": reason, **detail}, agent)
157
+
158
+ def warn(self, step: str, message: str, agent: Optional[str] = None, **detail: Any) -> None:
159
+ self._emit(step, "warning", message, detail, agent)
160
+
161
+ @contextmanager
162
+ def step(self, step: str, message: str = ""):
163
+ """Run a step; an exception is recorded as a step error and swallowed so independent steps continue."""
164
+ self.begin(step, message)
165
+ box: dict[str, Any] = {"ok": True}
166
+ try:
167
+ yield box
168
+ except Exception as e:
169
+ box["ok"] = False
170
+ self.fail(step, f"{type(e).__name__}: {str(e)[:300]}")
171
+ self.errors[-1]["trace"] = traceback.format_exc()[-500:]
172
+ else:
173
+ if self.status[step] == "running":
174
+ self.done(step, box.get("message", "done"), **box.get("detail", {}))
175
+
176
+ def trace(self) -> list[dict]:
177
+ return [e.to_dict() for e in self.events]