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,219 @@
1
+ """Pipeline & Containers: Multi-CI workflows, container assets, base images, and security hygiene."""
2
+ from __future__ import annotations
3
+
4
+ import streamlit as st
5
+
6
+ from ui.components.common import badge, df, page_header, require_result
7
+
8
+ SEV_ORDER = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"]
9
+ ICON = {"CRITICAL": "CRITICAL", "HIGH": "HIGH", "MEDIUM": "MEDIUM", "LOW": "LOW", "INFO": "INFO"}
10
+ PLATFORM_BADGES = {
11
+ "github_actions": "GitHub Actions",
12
+ "gitlab_ci": "GitLab CI/CD",
13
+ "jenkins": "Jenkins",
14
+ "circleci": "CircleCI",
15
+ "azure_pipelines": "Azure Pipelines",
16
+ "generic_ci": "Generic CI",
17
+ }
18
+
19
+
20
+ def render() -> None:
21
+ page_header(
22
+ "Pipeline & Containers",
23
+ "Static multi-CI platform analysis (GitHub Actions, GitLab CI, Jenkins, CircleCI, Azure Pipelines) and container security.",
24
+ )
25
+ r = require_result()
26
+ if not r:
27
+ return
28
+ p = r.get("pipeline") or {}
29
+ sm = p.get("summary") or {}
30
+ if not p or not (p.get("files") or p.get("findings")):
31
+ st.info("No Dockerfile, docker-compose file or CI/CD workflow was found in this repository.")
32
+ return
33
+
34
+ c = st.columns(5)
35
+ c[0].metric("Files Analysed", sm.get("files_analysed", 0))
36
+ c[1].metric("Security Findings", sm.get("findings", 0))
37
+ c[2].metric("Critical / High", sum(sm.get("by_severity", {}).get(k, 0) for k in ("CRITICAL", "HIGH")))
38
+ c[3].metric("Container Assets", len(p.get("container_assets") or p.get("images") or []))
39
+ c[4].metric("Actions / Tasks", len(p.get("actions") or []))
40
+
41
+ risks = {a["finding_id"]: a for a in r.get("risk_assessments", [])}
42
+ t_find, t_ci, t_containers, t_act, t_files = st.tabs([
43
+ "Findings",
44
+ "Multi-CI Platforms",
45
+ "Container Assets",
46
+ "CI Actions & Tasks",
47
+ "Coverage",
48
+ ])
49
+
50
+ with t_find:
51
+ f1, f2, f3 = st.columns([1, 1, 2])
52
+ sev = f1.multiselect("Severity", SEV_ORDER, default=[s for s in SEV_ORDER if s in ("CRITICAL", "HIGH", "MEDIUM")])
53
+ all_ecos = sorted({f.get("ecosystem", "CI") for f in p.get("findings", [])})
54
+ ecos = f2.multiselect("Ecosystem", all_ecos)
55
+ text = f3.text_input("Search rule, file or text", placeholder="e.g. GHA001, GL001, JNK001, Dockerfile ...")
56
+
57
+ rows = [
58
+ f for f in p.get("findings", [])
59
+ if (not sev or f.get("severity") in sev)
60
+ and (not ecos or f.get("ecosystem") in ecos)
61
+ and (not text or text.lower() in (f.get("rule_id", "") + f.get("file", "") + f.get("title", "") + f.get("snippet", "")).lower())
62
+ ]
63
+ st.caption(f"Showing {len(rows)} of {len(p.get('findings', []))} findings")
64
+ df(
65
+ [
66
+ {
67
+ "ID": f["finding_id"],
68
+ "Severity": f"{ICON.get(f.get('severity', ''), '')} {f.get('severity', '')}",
69
+ "Platform": f.get("ecosystem", "CI"),
70
+ "Rule": f.get("rule_id", ""),
71
+ "Finding": f.get("title", ""),
72
+ "Where": f"{f.get('file', '')}:{f.get('line', '')}" if f.get("line") else f.get("file", ""),
73
+ "Risk": (risks.get(f["finding_id"]) or {}).get("label", ""),
74
+ }
75
+ for f in rows
76
+ ],
77
+ height=360,
78
+ )
79
+ if rows:
80
+ pick = st.selectbox(
81
+ "Details",
82
+ [f["finding_id"] for f in rows],
83
+ format_func=lambda i: next(f"{i} - {f['title']}" for f in rows if f["finding_id"] == i),
84
+ )
85
+ f = next(x for x in rows if x["finding_id"] == pick)
86
+ a = risks.get(pick)
87
+ st.markdown(
88
+ f"**{f['title']}** \n`{f['file']}"
89
+ + (f":{f['line']}" if f.get("line") else "")
90
+ + "`"
91
+ + (f" · risk {badge(a['label'])} (score {a['score']})" if a else "")
92
+ )
93
+ if f.get("snippet"):
94
+ st.code(f["snippet"], language="dockerfile" if f.get("category") == "container" else "yaml")
95
+ st.markdown(f"**Why it matters:** {f.get('why', '')}")
96
+ st.markdown(f"**How to fix:** {f.get('remediation', '')}")
97
+ if f.get("references"):
98
+ st.caption("References: " + " · ".join(f["references"]))
99
+ st.caption(f"Evidence `{f.get('evidence_id')}` · {'directly visible in the file' if f.get('evidence_strength') == 'high' else 'pattern-based (heuristic)'}")
100
+
101
+ with t_ci:
102
+ st.markdown("#### Discovered CI/CD Pipelines")
103
+ ci_files = [fi for fi in p.get("files", []) if "pipeline" in fi.get("type", "").lower() or "workflow" in fi.get("type", "").lower() or fi.get("type") == "CI"]
104
+ if not ci_files:
105
+ st.info("No CI/CD pipeline definitions discovered.")
106
+ else:
107
+ col_left, col_right = st.columns([1, 2])
108
+ selected_ci = col_left.radio(
109
+ "Select Pipeline File",
110
+ [fi["file"] for fi in ci_files],
111
+ format_func=lambda path: f"{path} ({next(fi.get('type') for fi in ci_files if fi['file'] == path)})",
112
+ )
113
+ with col_right:
114
+ ci_item = next((fi for fi in ci_files if fi["file"] == selected_ci), None)
115
+ if ci_item:
116
+ st.markdown(f"### `{selected_ci}`")
117
+ st.markdown(f"**Platform Type:** `{ci_item.get('type')}` · **Status:** `{ci_item.get('status')}`")
118
+
119
+ # Show associated findings
120
+ file_findings = [f for f in p.get("findings", []) if f.get("file") == selected_ci]
121
+ st.markdown(f"**Security Findings:** {len(file_findings)}")
122
+ for ff in file_findings:
123
+ st.markdown(f"- {ICON.get(ff.get('severity', ''), '')} **{ff.get('rule_id')}**: {ff.get('title')}")
124
+
125
+ # Show discovered container build directives
126
+ dbuilds = [b for b in p.get("docker_builds", []) if b.get("ci_file") == selected_ci]
127
+ if dbuilds:
128
+ st.markdown("#### Extracted Container Build Directives")
129
+ df(
130
+ [
131
+ {
132
+ "Dockerfile": b.get("dockerfile_path"),
133
+ "Target Tag": b.get("image_tag") or "(not tagged)",
134
+ "Context": b.get("context_path", "."),
135
+ "Builder Tool": b.get("builder_tool", "docker"),
136
+ "Job": b.get("ci_job", ""),
137
+ }
138
+ for b in dbuilds
139
+ ],
140
+ height=180,
141
+ )
142
+
143
+ with t_containers:
144
+ st.markdown("#### Discovered Container Assets")
145
+ c_assets = p.get("container_assets") or []
146
+ if not c_assets:
147
+ # Fall back to base images if container_assets not yet present
148
+ imgs = p.get("images") or []
149
+ df(
150
+ [
151
+ {
152
+ "Image": i["ref"],
153
+ "Registry class": i["kind"],
154
+ "Tag": i.get("tag") or "(none)",
155
+ "Digest-pinned": "yes" if i.get("digest") else "no",
156
+ "Where": f"{i['file']}:{i['line']}",
157
+ }
158
+ for i in imgs
159
+ ],
160
+ height=300,
161
+ )
162
+ else:
163
+ df(
164
+ [
165
+ {
166
+ "Source File": a.get("source_file"),
167
+ "Source Type": a.get("source_type"),
168
+ "Target Tag": a.get("image_tag") or "(none)",
169
+ "Base Image": f"{a.get('base_image', '')}:{a.get('base_image_tag', '')}" if a.get("base_image") else "(none)",
170
+ "Stages": ", ".join(a.get("stage_names", [])) or "single",
171
+ "Linked CI Jobs": ", ".join(a.get("associated_ci_jobs", [])) or "none",
172
+ "Scan Status": a.get("scan_status", "pending"),
173
+ }
174
+ for a in c_assets
175
+ ],
176
+ height=320,
177
+ )
178
+
179
+ # Show container vulnerabilities if scanned
180
+ cont_findings = p.get("container_findings") or [v for v in r.get("vulnerabilities", []) if v.get("asset_type") == "container_image"]
181
+ if cont_findings:
182
+ st.markdown("#### Container Image Vulnerabilities (Trivy)")
183
+ df(
184
+ [
185
+ {
186
+ "ID": cf.get("primary_id"),
187
+ "Package": cf.get("package_name"),
188
+ "Installed": cf.get("installed_version"),
189
+ "Severity": cf.get("severity"),
190
+ "CVSS": cf.get("cvss_score") or "n/a",
191
+ "Class": (cf.get("container_details") or {}).get("package_type", "os_pkg"),
192
+ "Image": (cf.get("container_details") or {}).get("image_name", ""),
193
+ "Fixed in": ", ".join(cf.get("fixed_versions", [])[:2]) or "none",
194
+ }
195
+ for cf in cont_findings
196
+ ],
197
+ height=260,
198
+ )
199
+
200
+ with t_act:
201
+ st.markdown("#### CI Actions, Orbs, and External Tasks")
202
+ acts = p.get("actions") or []
203
+ df(
204
+ [
205
+ {
206
+ "Type": a.get("kind", "action"),
207
+ "Reference": a.get("name", "") + (a.get("path") or "") or a.get("task", "") or a.get("ref", ""),
208
+ "Pinned": "yes" if a.get("pinned") else "no",
209
+ "Job": a.get("job", ""),
210
+ "File": f"{a.get('file', '')}:{a.get('line', '')}" if a.get("line") else a.get("file", ""),
211
+ }
212
+ for a in acts
213
+ ],
214
+ height=300,
215
+ )
216
+
217
+ with t_files:
218
+ st.markdown("#### File Coverage")
219
+ df(p.get("files") or [], height=300)
@@ -0,0 +1,409 @@
1
+ """Remediation (legacy dashboard): ranked proposals, evidence, clone-only validation previews and the audit trail.
2
+
3
+ This page is read-only for the user's repository. Review decisions, application to the working tree, branches and pull
4
+ requests go through the shared remediation lifecycle (``remediation.lifecycle``): ``stackparity fix -i``, ``stackparity fix
5
+ --apply``, ``stackparity pr`` or the localhost dashboard. The former Accept & Apply, Accept & Create PR, Commit & Create PR
6
+ Branch, Undo and approval-form actions were removed because they bypassed that lifecycle's binding of each approval to the
7
+ scan, repository revision and exact patch.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import streamlit as st
12
+
13
+ from config.settings import get_settings
14
+ from remediation.apply_local import applied_record
15
+ from remediation.local_trial import discard_trial, latest_trial, run_trial, tests_possible
16
+ from remediation.export import patch_text, pr_markdown
17
+ from reporting.counts import remediation_totals
18
+ from remediation.pr_template_engine import find_pr_template, render_pull_request
19
+ from storage.database import Database
20
+ from storage.memory import Memory
21
+ from ui.components.common import df, page_header, require_result
22
+
23
+ ICON = {"upgrade": "upgrade", "pin": "pin", "remove": "remove", "replace": "replace", "mitigate": "mitigate", "block": "block", "escalate": "escalate"}
24
+ STATE = {"approved": "approved", "rejected": "rejected", "needs_review": "needs review"}
25
+
26
+
27
+ def _mem() -> Memory:
28
+ return Memory(Database(get_settings().db_path))
29
+
30
+
31
+ def _local_state(root: str, i: dict, ap: dict | None) -> str:
32
+ """Where a proposal is in the Resolve -> Accept flow (local-folder scans)."""
33
+ if applied_record(root, i):
34
+ return "Applied"
35
+ if ap and ap["state"] == "rejected":
36
+ return "Ignored"
37
+ t = latest_trial(root, i) if i.get("patch") else None
38
+ if t:
39
+ return "Validated" if t["status"] == "passed" else "Validation failed"
40
+ return "No automatic fix" if not i.get("patch") else "Open"
41
+
42
+
43
+ def _local_progress(items: list[dict], root: str, vulns: list[dict], approvals: dict) -> dict:
44
+ """Live counters: proposals by state and the findings that remain after the applied fixes."""
45
+ states = {i["id"]: _local_state(root, i, approvals.get(i["fingerprint"])) for i in items}
46
+ fixed: set[tuple] = set()
47
+ for i in items:
48
+ rec = applied_record(root, i)
49
+ for f in (rec or {}).get("fixed") or []:
50
+ fixed.add((f.get("package"), f.get("version"), f.get("id")))
51
+ remaining = [v for v in vulns if (v.get("package_name"), v.get("installed_version"), v.get("primary_id")) not in fixed]
52
+ return {"states": states, "fixed": len(fixed), "remaining": remaining}
53
+
54
+
55
+ LIFECYCLE_HINT = ("Decisions and changes go through the shared remediation lifecycle: review the exact diff and approve it with "
56
+ "`stackparity fix -i` (or in the localhost dashboard, `stackparity dashboard`), validate with `stackparity fix --apply`, then "
57
+ "`stackparity fix --apply --to-working-tree` or `stackparity pr`.")
58
+
59
+
60
+ def _lifecycle_panel(i: dict, result: dict) -> None:
61
+ """Authoritative state of this proposal in the shared lifecycle (read-only here)."""
62
+ try:
63
+ from remediation import lifecycle
64
+ db = Database(get_settings().db_path)
65
+ lifecycle.ensure_schema(db)
66
+ row = next((c for c in lifecycle.overview(db, result) if c["id"] == i["id"]), None)
67
+ except Exception as e: # noqa: BLE001
68
+ st.caption(f"Lifecycle state unavailable: {e}")
69
+ row = None
70
+ if row:
71
+ s = row["status"]
72
+ st.info(f"**Lifecycle state: {s['state'].replace('_', ' ')}**" + (f" by {s['actor']} ({s['updated_at']})" if s.get("actor") else "")
73
+ + (f" \n{s['reason']}" if s.get("reason") else ""), icon=":material/verified_user:")
74
+ st.caption(LIFECYCLE_HINT)
75
+
76
+
77
+ def _local_actions(i: dict, repo: dict, mem, ap, root: str, result: dict) -> None:
78
+ """Local-folder flow, read-only: earlier applications, then a Resolve preview on a clone. Applying is done via the lifecycle."""
79
+ rec = applied_record(root, i)
80
+ if rec:
81
+ lock = rec.get("lock") or {}
82
+ st.success(f"**Applied to your project by an earlier StackParity version** at {rec['applied_at']}: " + ", ".join(f"`{f}`" for f in rec["files"]),
83
+ icon=":material/check_circle:")
84
+ if rec.get("backup_dir"):
85
+ st.caption(f"The original files were backed up to `{rec['backup_dir']}`. To revert, use `git restore` on the files listed "
86
+ "(or copy the backups back) after checking nothing else changed in them.")
87
+ if lock.get("note"):
88
+ st.caption(f"Lockfile: {lock['note']}.")
89
+ return
90
+ _lifecycle_panel(i, result)
91
+ if not i.get("patch"):
92
+ st.warning("No automatic file change could be produced for this proposal; follow the rationale for a manual fix.")
93
+ return
94
+
95
+ trial = latest_trial(root, i)
96
+ if trial is None: # preview only: Resolve validates on a clone
97
+ can_test, why_not = tests_possible(root, i)
98
+ st.caption("**Resolve** previews this fix on a clone of your project: it applies it there, rescans, checks declared compatibility and runs the project's tests. Your files are not touched.")
99
+ if can_test:
100
+ st.checkbox("Also run this project's own build/tests in the Docker sandbox", value=True, key=f"tests_ok_{i['id']}",
101
+ help="Isolated container: dependencies are installed with network, tests run without network.")
102
+ else:
103
+ st.caption("Project tests will not run: " + why_not)
104
+ if st.button("Resolve", key=f"resolve_{i['id']}", type="primary", icon=":material/build:"):
105
+ run_tests = bool(st.session_state.get(f"tests_ok_{i['id']}", True)) and can_test
106
+ box = st.status("Validating the fix on a clone of your project ...", expanded=True)
107
+ t = run_trial(root, i, result, get_settings(), with_tests=run_tests, progress=lambda m: box.write(m))
108
+ box.update(label=f"Validation {t['status']}", state="complete" if t["status"] == "passed" else "error", expanded=False)
109
+ st.rerun()
110
+ return
111
+
112
+ ok = trial["status"] == "passed" # step 2: preview results (read-only)
113
+ if ok:
114
+ st.success("**Resolved on a clone: validation passed.**", icon=":material/science:")
115
+ else:
116
+ st.error("**Validation failed.** " + "; ".join(trial.get("reasons") or ["see the steps below"]), icon=":material/error:")
117
+ cmp_ = trial.get("comparison")
118
+ if cmp_:
119
+ m = st.columns(4)
120
+ m[0].metric("Findings before", cmp_["before"])
121
+ m[1].metric("After the fix", cmp_["after"], delta=cmp_["after"] - cmp_["before"], delta_color="inverse")
122
+ m[2].metric("Fixed", len(cmp_["fixed"]))
123
+ m[3].metric("Newly introduced", len(cmp_["new"]))
124
+ with st.expander("Validation steps", expanded=not ok):
125
+ for stp in trial.get("steps", []):
126
+ st.markdown(f":material/{'check_circle' if stp['ok'] else 'cancel'}: **{stp['step']}** - {stp['detail']}")
127
+ comp = trial.get("compat") or {}
128
+ if comp.get("checks"):
129
+ st.markdown("**Declared compatibility** (registry metadata for the new version)")
130
+ icon = {"ok": "PASS", "warn": "WARN", "fail": "FAIL", "unknown": "UNKNOWN"}
131
+ df([{"Status": icon.get(c["status"], ""), "Check": c["name"], "Detail": c["detail"]} for c in comp["checks"]], height="content")
132
+ for run in (trial.get("tests") or {}).get("runs", []):
133
+ with st.expander(f"{run['phase']} - exit code {run['exit_code']} ({run['seconds']}s)"):
134
+ st.code(run["log_tail"] or "(no output)", language="text")
135
+
136
+ warnings = trial.get("warnings") or []
137
+ if ok and warnings:
138
+ st.warning("**Warnings from the preview**\n\n" + "\n".join(f"- {w}" for w in warnings))
139
+
140
+ if st.button("Resolve again", key=f"reresolve_{i['id']}", icon=":material/refresh:", help="Discard this preview and run it again."):
141
+ discard_trial(root, i)
142
+ st.rerun()
143
+ st.caption("This was a preview on a clone; your files were not changed. " + LIFECYCLE_HINT)
144
+
145
+
146
+ def render() -> None:
147
+ page_header(
148
+ "Remediation",
149
+ "Ranked proposals with evidence and clone-only validation previews. Approving and applying happen in the shared lifecycle (CLI or localhost dashboard).",
150
+ )
151
+ r = require_result()
152
+ if not r:
153
+ return
154
+ st.info("This legacy page is read-only for your repository. " + LIFECYCLE_HINT, icon=":material/info:")
155
+ rem = r.get("remediation") or {}
156
+ items = rem.get("items") or []
157
+ if not items:
158
+ st.info("No remediation proposals for this scan (no vulnerability findings, remediation disabled, or this stored scan predates the Remediation Agent).")
159
+ return
160
+ repo = r["repo"]
161
+ try:
162
+ mem = _mem()
163
+ approvals = mem.approvals(repo["url"])
164
+ except Exception as e: # noqa: BLE001
165
+ st.warning(f"Approval storage unavailable: {e}")
166
+ mem, approvals = None, {}
167
+
168
+ vs = rem.get("validation_summary") or {}
169
+ totals = remediation_totals(items, len(r.get("vulnerabilities") or []))
170
+ fixed = totals["fixed_unique"]
171
+ auto_count = sum(1 for i in items if i.get("automation_tier") == "automated" or i.get("priority") in ("P2", "P3"))
172
+ manual_count = len(items) - auto_count
173
+
174
+ is_local_scan = repo.get("source") == "local"
175
+ scan_root = repo.get("local_path") or repo.get("repo_dir") or repo.get("path") or "."
176
+ vulns_all = r.get("vulnerabilities") or []
177
+ prog = _local_progress(items, scan_root, vulns_all, approvals) if is_local_scan else None
178
+ c = st.columns(5)
179
+ if prog:
180
+ st_counts = {k: sum(1 for v in prog["states"].values() if v == k) for k in set(prog["states"].values())}
181
+ open_n = len(items) - st_counts.get("Applied", 0) - st_counts.get("Ignored", 0)
182
+ c[0].metric("Proposals", len(items))
183
+ c[1].metric("Open", open_n, help="Not yet applied or ignored")
184
+ c[2].metric("Applied", st_counts.get("Applied", 0), help="Written to your project; rescan to confirm")
185
+ c[3].metric("Ignored", st_counts.get("Ignored", 0))
186
+ c[4].metric("Findings remaining", len(prog["remaining"]), delta=(-prog["fixed"] if prog["fixed"] else None), delta_color="inverse",
187
+ help="Total findings minus those fixed by the proposals you applied")
188
+ if prog["fixed"]:
189
+ sev = {}
190
+ for v in prog["remaining"]:
191
+ sev[v.get("severity") or "UNKNOWN"] = sev.get(v.get("severity") or "UNKNOWN", 0) + 1
192
+ st.caption("Remaining by severity: " + " · ".join(f"{sev[k]} {k.lower()}" for k in ("CRITICAL", "HIGH", "MEDIUM", "LOW", "UNKNOWN") if sev.get(k)))
193
+ else:
194
+ c[0].metric("Proposals", len(items))
195
+ c[1].metric("Findings Fixed", fixed, help="Unique findings the proposals fix; proposals overlap, so this is not the sum of the table's Fixes column")
196
+ c[2].metric("Auto-PR (Low/Med)", auto_count)
197
+ c[3].metric("Manual Review (High/Crit)", manual_count)
198
+ c[4].metric("Approved", sum(1 for i in items if approvals.get(i["fingerprint"], {}).get("state") == "approved"))
199
+
200
+ covered_ids = {f for i in items for f in i.get("finding_ids", [])}
201
+ uncovered = [v for v in vulns_all if v["finding_id"] not in covered_ids]
202
+ no_fix = sum(1 for v in uncovered if not v.get("fixed_versions"))
203
+ st.caption(f"{totals['covered_unique']} of {totals['total_findings']} findings are covered by a proposal."
204
+ + (f" Not covered: {len(uncovered)} ({no_fix} have no published fix; {len(uncovered) - no_fix} belong to {rem.get('groups_not_planned', 0)} lower-priority group(s) that hit the planning limit"
205
+ f" of {get_settings().remediation_max_groups} proposals / {get_settings().remediation_budget_s}s: raise it in Settings & Health and rescan)." if uncovered else ""))
206
+
207
+ by_id = {v["finding_id"]: v for v in vulns_all}
208
+ owner = {}
209
+ for x in items:
210
+ for fid in x.get("finding_ids", []):
211
+ owner.setdefault(fid, x["id"])
212
+ sev_rank = {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3}
213
+ with st.expander(f"All {len(vulns_all)} vulnerabilities and the proposal that fixes each", expanded=False):
214
+ fixed_keys = set()
215
+ if prog:
216
+ fixed_keys = {(v.get("package_name"), v.get("installed_version"), v.get("primary_id")) for v in vulns_all} - {(v.get("package_name"), v.get("installed_version"), v.get("primary_id")) for v in prog["remaining"]}
217
+ df([{"Severity": v.get("severity") or "UNKNOWN", "Vulnerability": v.get("primary_id"), "Package": f"{v.get('package_name')} {v.get('installed_version')}",
218
+ "Fixed in": ", ".join((v.get("fixed_versions") or [])[:3]) or "no published fix",
219
+ "Proposal": owner.get(v["finding_id"], "none"),
220
+ "Status": "fixed" if (v.get("package_name"), v.get("installed_version"), v.get("primary_id")) in fixed_keys else ("open" if v["finding_id"] in owner else "no automatic fix")}
221
+ for v in sorted(vulns_all, key=lambda v: (sev_rank.get(v.get("severity"), 9), v.get("package_name") or ""))], height="content")
222
+
223
+ # Table filter by automation policy
224
+ col_f1, _ = st.columns([1, 2])
225
+ policy_filter = col_f1.selectbox("Filter by Automation Policy", ["All Proposals", "Automated (Low/Medium)", "Manual Review Required (High/Critical)"])
226
+
227
+ applied_ids = {k for k, v in (prog["states"].items() if prog else []) if v == "Applied"}
228
+ if applied_ids:
229
+ st.caption(f"{len(applied_ids)} fixed proposal(s) are hidden here; see **Fix Report** for the record (and to undo).")
230
+ open_items = [x for x in items if x["id"] not in applied_ids]
231
+ if not open_items:
232
+ st.success("All proposals are fixed. Rescan the folder to confirm; details are in **Fix Report**.")
233
+ return
234
+
235
+ rows = []
236
+ for i in open_items:
237
+ wi = i.get("what_if") or {}
238
+ ap = approvals.get(i["fingerprint"])
239
+ tier = i.get("automation_tier") or ("manual_review" if i.get("priority") in ("P0", "P1") else "automated")
240
+ policy_label = "Manual Review" if tier == "manual_review" else "Auto-PR"
241
+
242
+ if policy_filter == "Automated (Low/Medium)" and tier != "automated":
243
+ continue
244
+ if policy_filter == "Manual Review Required (High/Critical)" and tier != "manual_review":
245
+ continue
246
+
247
+ rows.append({
248
+ "ID": i["id"],
249
+ "Priority": i["priority"],
250
+ "Policy": policy_label,
251
+ "Action": i["action"],
252
+ "Proposal": i["title"],
253
+ "Fixes": len(wi.get("fixed", [])) if wi else "n/a",
254
+ "Remaining": len(wi.get("remaining", [])) if wi else "n/a",
255
+ "New": len(wi.get("newly_introduced", [])) if wi else "n/a",
256
+ "Breaking risk": (i.get("compatibility") or {}).get("breaking_risk", ""),
257
+ "Confidence": i.get("confidence", ""),
258
+ "State" if is_local_scan else "Approval": (prog["states"].get(i["id"], "Open") if prog else (STATE.get(ap["state"], "pending") if ap else "pending")),
259
+ })
260
+ df(rows, height=300)
261
+
262
+ # Proposal inspector
263
+ pick = st.selectbox(
264
+ "Select Proposal to Inspect",
265
+ [i["id"] for i in open_items],
266
+ format_func=lambda x: next(f"{x} · {i['priority']} · {'[Auto]' if i.get('automation_tier') == 'automated' else '[Manual]'} {i['title']}" for i in open_items if i["id"] == x),
267
+ )
268
+ i = next(x for x in open_items if x["id"] == pick)
269
+ wi, val = i.get("what_if") or {}, i.get("validation") or {}
270
+ ap = approvals.get(i["fingerprint"])
271
+ tier = i.get("automation_tier") or ("manual_review" if i.get("priority") in ("P0", "P1") else "automated")
272
+ is_manual = (tier == "manual_review" or i.get("priority") in ("P0", "P1"))
273
+ is_local = repo.get("source") == "local"
274
+ local_root = repo.get("local_path") or repo.get("repo_dir") or repo.get("path") or "."
275
+
276
+ st.markdown(f"### {i['title']}")
277
+ st.markdown(i.get("rationale", ""))
278
+ covered_here = [by_id[f] for f in i.get("finding_ids", []) if f in by_id]
279
+ if covered_here:
280
+ st.markdown(f"**Vulnerabilities this proposal fixes ({len(covered_here)})**")
281
+ df([{"Severity": v.get("severity") or "UNKNOWN", "Vulnerability": v.get("primary_id"), "Package": f"{v.get('package_name')} {v.get('installed_version')}",
282
+ "Fixed in": ", ".join((v.get("fixed_versions") or [])[:3]) or "-"}
283
+ for v in sorted(covered_here, key=lambda v: sev_rank.get(v.get("severity"), 9))], height="content")
284
+
285
+ if is_local:
286
+ _local_actions(i, repo, mem, ap, local_root, r)
287
+ else:
288
+ _lifecycle_panel(i, r)
289
+
290
+
291
+
292
+ if i.get("alternatives"):
293
+ for a in i["alternatives"]:
294
+ st.caption(f"Alternative ({a['action']}): {a['note']}")
295
+
296
+ impact = i.get("reachability_impact") or {}
297
+ if impact:
298
+ with st.expander(f"Code Reachability Impact ({impact.get('reachability_preservation_score', 100)}% preserved · {impact.get('status', 'unknown')})", expanded=True, icon=":material/track_changes:"):
299
+ c_a, c_b = st.columns(2)
300
+ c_a.metric("Preservation Score", f"{impact.get('reachability_preservation_score', 100)}%")
301
+ c_b.metric("App Files Affected", len(impact.get("app_files_affected", [])))
302
+ st.markdown(f"**Impact Summary:** {impact.get('impact_summary', 'N/A')}")
303
+ if impact.get("app_files_affected"):
304
+ st.caption("Files: " + ", ".join(f"`{f}`" for f in impact["app_files_affected"][:8]))
305
+ if impact.get("imported_symbols"):
306
+ st.caption("Symbols: " + ", ".join(f"`{s}`" for s in impact["imported_symbols"][:8]))
307
+ if impact.get("recommendation"):
308
+ st.info(impact["recommendation"], icon=":material/info:")
309
+
310
+ t_eff, t_patch, t_val, t_appr = st.tabs(["Measured effect", "Patch & rollback", "Validation", "Approval & export"])
311
+ with t_eff:
312
+ if not wi:
313
+ st.info("This proposal could not be simulated (no fixed version, or the registry did not resolve a tree).")
314
+ else:
315
+ m = st.columns(4)
316
+ m[0].metric("Fixed", len(wi["fixed"]))
317
+ m[1].metric("Remaining", len(wi["remaining"]))
318
+ m[2].metric("Newly introduced", len(wi["newly_introduced"]))
319
+ m[3].metric("Verdict", wi["verdict"].replace("_", " "))
320
+ st.caption(wi.get("method", ""))
321
+ if wi["fixed"]:
322
+ st.markdown("**Fixed**")
323
+ df(wi["fixed"], height="content")
324
+ if wi["newly_introduced"]:
325
+ st.warning("The proposed versions bring in advisories that are not in the project today:")
326
+ df(wi["newly_introduced"], height="content")
327
+ if wi.get("already_present_elsewhere"):
328
+ st.caption(f"{wi['already_present_elsewhere']} advisory(ies) on the new dependency tree already exist in this project via another path (not counted as introduced).")
329
+ d = wi["sbom_diff"]
330
+ st.markdown("**Before / after SBOM of this dependency sub-tree**")
331
+ a, b_, c3 = st.columns(3)
332
+ a.metric("Version changes", len(d["changed"]))
333
+ b_.metric("Added", len(d["added"]))
334
+ c3.metric("Removed", len(d["removed"]))
335
+ if d["changed"]:
336
+ df([{"Package": x["package"], "Before": x["from"], "After": x["to"]} for x in d["changed"]], height=min(260, 40 + 35 * len(d["changed"])))
337
+ if d["added"] or d["removed"]:
338
+ with st.expander("Added / removed packages"):
339
+ st.write("Added: " + (", ".join(d["added"][:40]) or "none"))
340
+ st.write("Removed: " + (", ".join(d["removed"][:40]) or "none"))
341
+ if wi.get("candidates_tried"):
342
+ with st.expander("Versions tried (parent-upgrade search)"):
343
+ df([{"Version": c_["version"], "Advisories left": c_["remaining"], "New HIGH/CRITICAL": c_["new_high"]} for c_ in wi["candidates_tried"]], height="content")
344
+ with t_patch:
345
+ comp = i.get("compatibility") or {}
346
+ if comp:
347
+ st.markdown(f"**Compatibility:** {comp.get('semver_change')} change, breaking-change risk **{comp.get('breaking_risk')}**. {comp.get('note', '')}")
348
+ if i.get("patch"):
349
+ st.markdown(f"**Proposed change to** `{i['patch']['path']}`")
350
+ st.code(i["patch"]["diff"], language="diff")
351
+ if i.get("lock_note"):
352
+ st.caption(f"Then refresh the lockfile: {i['lock_note']}")
353
+ if patch_text(i):
354
+ st.download_button("Download .patch", patch_text(i), file_name=f"{i['id']}.patch", mime="text/x-diff", key=f"t_patch_dl_{i['id']}", icon=":material/download:")
355
+ else:
356
+ st.info("No automatic patch could be produced for this proposal (manual change or no manifest found); the rationale lists what to do.")
357
+ st.markdown("**Rollback**")
358
+ for n, s in enumerate(i.get("rollback", []), 1):
359
+ st.markdown(f"{n}. {s}")
360
+ with t_val:
361
+ matrix = val.get("matrix") or {}
362
+ if matrix:
363
+ st.markdown("#### Multi-Tier Verification Matrix")
364
+ t_rows = []
365
+ for k, m_item in matrix.items():
366
+ p_val = m_item.get("passed")
367
+ status_icon = "Passed" if p_val is True else "Failed" if p_val is False else "Opt-In / Pending"
368
+ t_rows.append({"Tier": m_item.get("name", k), "Status": status_icon, "Details": m_item.get("details", "")})
369
+ df(t_rows, height=180)
370
+
371
+ st.markdown(f"- Patch applies cleanly (`git apply --check`): **{val.get('patch_applies')}**")
372
+ st.markdown(f"- Static what-if rescan: **{'done' if val.get('what_if_run') else 'not possible'}**")
373
+ bt = val.get("build_tests") or {}
374
+ st.markdown(f"- Build and tests: **{bt.get('status', 'not_run')}** - {bt.get('reason', '') or bt.get('attribution', '')}")
375
+ for run in bt.get("runs", []):
376
+ with st.expander(f"{run['phase']} - exit code {run['exit_code']} ({run['seconds']}s)"):
377
+ st.code(run["log_tail"] or "(no output)", language="text")
378
+ if bt.get("baseline"):
379
+ st.caption(f"Baseline (without the patch): {bt['baseline']['status']}")
380
+ from sandbox.runner import docker_status
381
+ ds = docker_status()
382
+ if not ds["available"]:
383
+ st.caption("Container test runs are unavailable: " + ds["reason"])
384
+ else:
385
+ st.caption("To run this repository's tests in a Docker sandbox against approved changes: `stackparity fix --apply --run-tests`.")
386
+ if i.get("evidence_id"):
387
+ st.caption(f"Evidence `{i['evidence_id']}`")
388
+ with t_appr:
389
+ if ap:
390
+ st.caption(f"Recorded by an earlier StackParity version: {STATE[ap['state']]} by {ap['actor']} on {ap['decided_at']}: {ap['reason']}. "
391
+ "Such records do not authorize any change.")
392
+ _lifecycle_panel(i, r)
393
+ tmpl_found = find_pr_template(repo.get("repo_dir") or repo.get("local_path") or repo.get("path") or ".")
394
+ with st.expander("Preview the pull request description"):
395
+ pr_t, pr_b, used_tmpl = render_pull_request(i, repo, ap or {"state": "pending", "actor": "-", "reason": "not approved"},
396
+ repo_dir=repo.get("repo_dir") or repo.get("local_path") or ".", impact=i.get("reachability_impact"))
397
+ st.caption(f"Template: {tmpl_found[0] if tmpl_found else 'Standard security PR format'}")
398
+ st.code(pr_b, language="markdown")
399
+ e1, e2 = st.columns(2)
400
+ if patch_text(i):
401
+ e1.download_button("Download .patch", patch_text(i), file_name=f"{i['id']}.patch", mime="text/x-diff", use_container_width=True)
402
+ e2.download_button("Download PR description (.md)", pr_markdown(i, repo, ap or {}), file_name=f"{i['id']}-pr.md", mime="text/markdown",
403
+ use_container_width=True)
404
+
405
+ with st.expander("Audit trail"):
406
+ try:
407
+ df([{"When": a["at"], "Who": a["actor"], "Action": a["action"], "Subject": a["subject"], "Detail": a["detail"]} for a in mem.audit_log(repo["url"])] if mem else [], height=260)
408
+ except Exception: # noqa: BLE001
409
+ st.caption("Audit log unavailable.")