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,623 @@
1
+ """Authoritative remediation lifecycle shared by the CLI and the dashboard.
2
+
3
+ One place decides what a remediation candidate is, what its exact change is, and which review state it is in:
4
+
5
+ * ``candidates`` turns a persisted scan into reviewable candidates: dependency upgrades/pins from the planner and line-level
6
+ source/configuration fixes for non-CVE findings, each with evidence, the exact diff and the alternatives available. Diffs are
7
+ recomputed against the files as they are now, so a reviewer always sees the change that would really be made.
8
+ * ``decide`` and ``transition`` persist states against the scan ID, remediation ID, repository revision and patch content.
9
+ * ``status`` re-checks that binding: if the files or the patch changed after a decision, the approval is invalidated and the
10
+ candidate returns to review.
11
+ * ``materialize`` builds the combined file contents for a set of approved candidates. It never writes to disk.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import time
18
+ from dataclasses import asdict, dataclass, field
19
+ from datetime import datetime, timezone
20
+ from pathlib import Path
21
+ from typing import Any, Optional
22
+
23
+ from remediation import code_fixes, patchers
24
+
25
+ STATES = ("proposed", "pending_review", "approved", "rejected", "skipped", "applied_in_isolation",
26
+ "validation_passed", "validation_failed", "ready_for_pr", "pr_created", "applied")
27
+ DECISIONS = ("approved", "rejected", "skipped", "pending_review")
28
+ # states whose meaning depends on the exact patch and files: invalidated when either changes
29
+ BOUND = ("approved", "applied_in_isolation", "validation_passed", "validation_failed", "ready_for_pr")
30
+ APPLICABLE = ("approved", "applied_in_isolation", "validation_passed", "ready_for_pr")
31
+ TERMINAL = ("pr_created", "applied")
32
+ # The only way into "approved", "rejected" or "skipped" is decide(); the execution states below can only follow an approval.
33
+ _TRANSITIONS = {
34
+ "applied_in_isolation": APPLICABLE,
35
+ "validation_passed": ("applied_in_isolation",),
36
+ "validation_failed": ("applied_in_isolation",),
37
+ "ready_for_pr": ("applied_in_isolation", "validation_passed"),
38
+ "pr_created": ("ready_for_pr",),
39
+ "applied": ("ready_for_pr", "validation_passed"),
40
+ "pending_review": tuple(s for s in STATES if s not in TERMINAL),
41
+ }
42
+ LOCK_SECONDS = 900
43
+
44
+
45
+ def approval_ttl_seconds() -> int:
46
+ """How long an approval stays valid (STACKPARITY_APPROVAL_TTL_HOURS, default 168 = 7 days)."""
47
+ import os
48
+ try:
49
+ hours = float(os.environ.get("STACKPARITY_APPROVAL_TTL_HOURS", "168"))
50
+ except ValueError:
51
+ hours = 168.0
52
+ return int(max(hours, 0.0) * 3600)
53
+ _SEV_RANK = {"CRITICAL": 4, "HIGH": 3, "MEDIUM": 2, "LOW": 1}
54
+
55
+ SCHEMA = """
56
+ CREATE TABLE IF NOT EXISTS remediation_state (
57
+ scan_id TEXT NOT NULL,
58
+ item_id TEXT NOT NULL,
59
+ repo_url TEXT NOT NULL,
60
+ state TEXT NOT NULL,
61
+ choice TEXT,
62
+ patch_sha TEXT,
63
+ revision TEXT,
64
+ actor TEXT,
65
+ reason TEXT,
66
+ updated_at TEXT NOT NULL,
67
+ detail TEXT,
68
+ busy_until REAL,
69
+ PRIMARY KEY (scan_id, item_id)
70
+ );
71
+ """
72
+
73
+
74
+ class LifecycleError(RuntimeError):
75
+ pass
76
+
77
+
78
+ @dataclass
79
+ class Candidate:
80
+ id: str
81
+ kind: str # dependency | code
82
+ title: str
83
+ severity: str
84
+ confidence: str
85
+ finding_ids: list[str]
86
+ evidence: list[dict]
87
+ targets: list[dict] # [{path, line}]
88
+ rationale: str
89
+ compatibility: str
90
+ recommendation: str = ""
91
+ alternatives: list[dict] = field(default_factory=list) # [{key, title, risk, patch: bool}]
92
+ choice: Optional[str] = None
93
+ diff: str = ""
94
+ manual: bool = False # True: no safe automatic change; recommendation only
95
+ stale_reason: str = "" # why the stored patch could not be recomputed
96
+ lock_note: str = ""
97
+ ecosystem: str = ""
98
+ changes: list[dict] = field(default_factory=list)
99
+ patch_path: str = ""
100
+ line_text: str = ""
101
+ applicability: str = "" # conditions verified before the change was proposed
102
+ validation_requirements: str = "" # what must be checked after applying it
103
+
104
+ @property
105
+ def patch_sha(self) -> str:
106
+ return hashlib.sha256(self.diff.encode("utf-8")).hexdigest() if self.diff else ""
107
+
108
+ def to_dict(self) -> dict:
109
+ return {**asdict(self), "patch_sha": self.patch_sha}
110
+
111
+
112
+ # ---------------------------------------------------------------------------------------------------------------- file access
113
+ def read_file(root: Path, rel: str, max_bytes: int = 2_000_000) -> Optional[str]:
114
+ """Read ``rel`` confined to ``root`` with line endings preserved; None for symlinks, escapes, binary or oversize files."""
115
+ try:
116
+ root_r = root.resolve()
117
+ p = root / rel
118
+ if p.is_symlink():
119
+ return None
120
+ p = p.resolve()
121
+ p.relative_to(root_r)
122
+ if not p.is_file() or p.stat().st_size > max_bytes:
123
+ return None
124
+ return p.read_bytes().decode("utf-8")
125
+ except (OSError, ValueError, UnicodeDecodeError):
126
+ return None
127
+
128
+
129
+ def safe_target(root: Path, rel: str) -> Path:
130
+ """Resolve a repository-relative path for writing; refuses absolute paths, traversal and symlinks."""
131
+ if not rel or Path(rel).is_absolute() or ".." in Path(rel).parts or rel.startswith(("/", "\\")):
132
+ raise LifecycleError(f"Refusing unsafe path: {rel!r}")
133
+ p = root / rel
134
+ if p.is_symlink():
135
+ raise LifecycleError(f"Refusing to write through a symlink: {rel}")
136
+ resolved = p.resolve()
137
+ try:
138
+ resolved.relative_to(root.resolve())
139
+ except ValueError as exc:
140
+ raise LifecycleError(f"Path escapes the repository: {rel}") from exc
141
+ return resolved
142
+
143
+
144
+ def git_head(root: Optional[Path]) -> str:
145
+ if not root:
146
+ return "unavailable"
147
+ from core.git_manager import run_git
148
+ try:
149
+ p = run_git(["rev-parse", "HEAD"], cwd=root, timeout=15, check=False)
150
+ return p.stdout.strip() if p.returncode == 0 else "unversioned"
151
+ except Exception:
152
+ return "unversioned"
153
+
154
+
155
+ def revision(root: Optional[Path], paths: list[str]) -> str:
156
+ """Digest of HEAD plus the current bytes of every file a change touches."""
157
+ parts = {"head": git_head(root)}
158
+ for rel in sorted(set(paths)):
159
+ text = read_file(root, rel) if root else None
160
+ parts[rel] = hashlib.sha256(text.encode("utf-8")).hexdigest() if text is not None else "missing"
161
+ return hashlib.sha256(json.dumps(parts, sort_keys=True).encode()).hexdigest()
162
+
163
+
164
+ def repo_root_of(scan: dict) -> Optional[Path]:
165
+ repo = scan.get("repo") or {}
166
+ if repo.get("source") not in (None, "local"):
167
+ return None
168
+ for cand in (repo.get("local_path"), repo.get("repo_dir"), repo.get("path")):
169
+ if cand and Path(cand).is_dir():
170
+ return Path(cand).resolve()
171
+ return None
172
+
173
+
174
+ def _lock_hint(root: Optional[Path], manifest: str) -> str:
175
+ if not root:
176
+ return ""
177
+ d = (root / manifest).parent
178
+ return " ".join(n for n in ("yarn.lock", "pnpm-lock.yaml", "package-lock.json") if (d / n).exists())
179
+
180
+
181
+ # ---------------------------------------------------------------------------------------------------------------- candidates
182
+ def _severity(values: list[str]) -> str:
183
+ best = max((_SEV_RANK.get(str(v).upper(), 0) for v in values), default=0)
184
+ return next((k for k, r in _SEV_RANK.items() if r == best), "UNKNOWN")
185
+
186
+
187
+ def _dependency_candidate(scan: dict, item: dict, root: Optional[Path]) -> Candidate:
188
+ vulns = {v.get("finding_id"): v for v in scan.get("vulnerabilities") or []}
189
+ findings = [vulns[f] for f in item.get("finding_ids") or [] if f in vulns]
190
+ evidence = [{"id": v.get("primary_id"), "aliases": [a for a in v.get("aliases") or [] if a != v.get("primary_id")][:4],
191
+ "package": v.get("package_name"), "installed": v.get("installed_version"),
192
+ "fixed": (v.get("fixed_versions") or [None])[0], "severity": v.get("severity"),
193
+ "summary": (v.get("summary") or "")[:240], "kev": bool(v.get("kev")),
194
+ "reachability": (v.get("reachability") or {}).get("status"), "path": v.get("dependency_path") or v.get("path"),
195
+ "url": (v.get("references") or [None])[0] if isinstance(v.get("references"), list) else None}
196
+ for v in findings]
197
+ compat = item.get("compatibility") or {}
198
+ cand = Candidate(
199
+ id=str(item.get("id")), kind="dependency", title=item.get("title") or f"Remediate {item.get('source_package')}",
200
+ severity=_severity([v.get("severity") for v in findings]), confidence=str(item.get("confidence") or "unknown"),
201
+ finding_ids=list(item.get("finding_ids") or []), evidence=evidence, targets=[], rationale=item.get("rationale") or "",
202
+ compatibility=(f"{compat.get('semver_change')} version change, breaking-change risk {compat.get('breaking_risk')}. {compat.get('note', '')}".strip()
203
+ if compat else "No compatibility assessment recorded."),
204
+ recommendation="", lock_note=item.get("lock_note") or "", ecosystem=item.get("ecosystem") or "",
205
+ changes=list(item.get("changes") or []),
206
+ alternatives=[{"key": f"alt-{i}", "title": f"{a.get('action')}: {a.get('note')}", "risk": "", "patch": False}
207
+ for i, a in enumerate(item.get("alternatives") or [])],
208
+ )
209
+ patch = item.get("patch") or {}
210
+ if not patch or not cand.changes:
211
+ cand.manual = True
212
+ cand.recommendation = item.get("rationale") or "No safe automatic change was found."
213
+ return cand
214
+ cand.patch_path = patch.get("path") or ""
215
+ cand.targets = [{"path": cand.patch_path, "line": None}]
216
+ cand.applicability = (f"{cand.patch_path} still declares the scanned version(s); the ecosystem patcher rewrites only those "
217
+ "declarations and refuses anything it cannot parse.")
218
+ cand.validation_requirements = ("Regenerate and verify the lockfile (--lockfiles), run the test suite (--run-tests), and confirm the "
219
+ "rescan no longer reports the advisories.")
220
+ if root is None: # remote scan: the stored diff can be shown, never applied
221
+ cand.diff = patch.get("diff") or ""
222
+ cand.stale_reason = "The scanned repository is not available locally, so the change cannot be applied from here."
223
+ return cand
224
+ files = _apply_dependency({}, root, cand)
225
+ if files is None:
226
+ cand.manual = True
227
+ cand.stale_reason = f"{cand.patch_path} no longer contains the dependency as scanned; rescan the repository."
228
+ cand.recommendation = item.get("rationale") or ""
229
+ return cand
230
+ original = read_file(root, cand.patch_path) or ""
231
+ cand.diff = patchers.unified_diff(cand.patch_path, original, files[cand.patch_path])
232
+ return cand
233
+
234
+
235
+ def _apply_dependency(texts: dict, root: Path, cand: Candidate) -> Optional[dict]:
236
+ path = cand.patch_path
237
+ cur = texts.get(path)
238
+ if cur is None:
239
+ cur = read_file(root, path)
240
+ if cur is None:
241
+ return None
242
+ hint = _lock_hint(root, path)
243
+ for ch in cand.changes:
244
+ res = patchers.patch_for(cand.ecosystem, path, cur, ch["package"], ch["to"], ch.get("kind") or "bump", hint)
245
+ if not res:
246
+ return None
247
+ cur = res["new_text"]
248
+ return {**texts, path: cur}
249
+
250
+
251
+ def _code_candidates(scan: dict, root: Optional[Path], choices: dict[str, str]) -> list[Candidate]:
252
+ from reporting.view import non_cve_findings
253
+ out = []
254
+ for f in non_cve_findings(scan):
255
+ path, line = f.get("file"), f.get("line")
256
+ cid = "FIX-" + hashlib.sha1(f"{f['uid']}|{path}|{line}".encode()).hexdigest()[:8].upper()
257
+ evidence = [{"id": f.get("rule_id") or f["finding_id"], "engine": f.get("engine"), "file": path, "line": line,
258
+ "snippet": f.get("snippet"), "classification": f.get("classification"), "description": f.get("description")}]
259
+ cand = Candidate(id=cid, kind="code", title=f.get("title") or "Non-CVE finding", severity=f.get("severity") or "UNKNOWN",
260
+ confidence=str(f.get("confidence") or "unknown"), finding_ids=[f["finding_id"]], evidence=evidence,
261
+ targets=[{"path": path, "line": line}] if path else [], rationale=f.get("description") or f.get("title") or "",
262
+ compatibility="", recommendation=f.get("recommendation") or "Review the finding manually.", manual=True)
263
+ text = read_file(root, path) if root and path else None
264
+ if text is not None and not (isinstance(line, int) and line > 0):
265
+ line = code_fixes.locate(path, text, f.get("title") or "")
266
+ if line:
267
+ cand.targets = [{"path": path, "line": line}]
268
+ evidence[0]["line"] = line
269
+ fixes = code_fixes.propose(path, text, line) if text is not None and line else []
270
+ if fixes:
271
+ cand.line_text = text.splitlines(keepends=True)[line - 1]
272
+ evidence[0]["snippet"] = evidence[0].get("snippet") or cand.line_text.strip()
273
+ cand.alternatives = [{"key": r.key, "title": r.title, "risk": r.risk, "patch": True} for r, _ in fixes]
274
+ chosen = next(((r, t) for r, t in fixes if r.key == choices.get(cid)), fixes[0])
275
+ rule, new_text = chosen
276
+ cand.manual = False
277
+ cand.choice = rule.key
278
+ cand.title = f"{rule.title} ({path}:{line})"
279
+ cand.rationale = f"{rule.rationale} Finding: {f.get('title')}."
280
+ cand.compatibility = rule.risk
281
+ cand.confidence = rule.confidence
282
+ cand.applicability = rule.applicability
283
+ cand.validation_requirements = rule.validation
284
+ cand.diff = patchers.unified_diff(path, text, new_text)
285
+ out.append(cand)
286
+ return out
287
+
288
+
289
+ def candidates(scan: dict, choices: Optional[dict[str, str]] = None, include_manual: bool = True) -> list[Candidate]:
290
+ root = repo_root_of(scan)
291
+ items = (scan.get("remediation") or {}).get("items") or []
292
+ cands = [_dependency_candidate(scan, item, root) for item in items]
293
+ cands += _code_candidates(scan, root, choices or {})
294
+ if not include_manual:
295
+ cands = [c for c in cands if not c.manual]
296
+ cands.sort(key=lambda c: (c.manual, -_SEV_RANK.get(c.severity, 0), c.id))
297
+ return cands
298
+
299
+
300
+ # ---------------------------------------------------------------------------------------------------------------- persistence
301
+ def _now() -> str:
302
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
303
+
304
+
305
+ def ensure_schema(db) -> None:
306
+ with db.connect() as c:
307
+ c.executescript(SCHEMA)
308
+
309
+
310
+ def records(db, scan_id: str) -> dict[str, dict]:
311
+ ensure_schema(db)
312
+ with db.connect() as c:
313
+ rows = c.execute("SELECT * FROM remediation_state WHERE scan_id=?", (scan_id,)).fetchall()
314
+ return {r["item_id"]: {**dict(r), "detail": json.loads(r["detail"] or "{}")} for r in rows}
315
+
316
+
317
+ def choices_of(db, scan_id: str) -> dict[str, str]:
318
+ return {k: v["choice"] for k, v in records(db, scan_id).items() if v.get("choice")}
319
+
320
+
321
+ def _write(db, scan: dict, cand: Candidate, state: str, actor: str, reason: str, detail: Optional[dict] = None, binding: bool = True,
322
+ expected: Optional[dict] = None) -> bool:
323
+ root = repo_root_of(scan)
324
+ rev = revision(root, [t["path"] for t in cand.targets if t.get("path")]) if binding else None
325
+ repo_url = (scan.get("repo") or {}).get("url") or ""
326
+ with db.connect() as c:
327
+ if expected is not None:
328
+ # A dashboard read must not invalidate a decision that changed while it inspected the files.
329
+ c.execute("BEGIN IMMEDIATE")
330
+ prev = c.execute("SELECT * FROM remediation_state WHERE scan_id=? AND item_id=?", (scan["repo"]["scan_id"], cand.id)).fetchone()
331
+ previous_detail = json.loads(prev["detail"] or "{}") if prev else {}
332
+ if expected is not None and (prev is None or {**dict(prev), "detail": previous_detail} != expected):
333
+ return False
334
+ merged = {**previous_detail, **(detail or {})}
335
+ history = merged.get("history") or []
336
+ history.append({"at": _now(), "state": state, "actor": actor, "reason": reason})
337
+ merged["history"] = history[-50:]
338
+ c.execute("INSERT INTO remediation_state(scan_id,item_id,repo_url,state,choice,patch_sha,revision,actor,reason,updated_at,detail,busy_until)"
339
+ " VALUES (?,?,?,?,?,?,?,?,?,?,?,NULL) ON CONFLICT(scan_id,item_id) DO UPDATE SET state=excluded.state, choice=excluded.choice,"
340
+ " patch_sha=COALESCE(excluded.patch_sha, remediation_state.patch_sha), revision=COALESCE(excluded.revision, remediation_state.revision),"
341
+ " actor=excluded.actor, reason=excluded.reason, updated_at=excluded.updated_at, detail=excluded.detail",
342
+ (scan["repo"]["scan_id"], cand.id, repo_url, state, cand.choice, cand.patch_sha if binding else None, rev, actor, reason, _now(),
343
+ json.dumps(merged, default=str)))
344
+ from storage.memory import Memory
345
+ Memory(db).audit(repo_url, actor, f"remediation_{state}", f"{cand.id}: {cand.title}"[:300], reason[:1000])
346
+ return True
347
+
348
+
349
+ def _record_status(rec: Optional[dict]) -> dict:
350
+ rec = rec or {}
351
+ return {"state": rec.get("state", "proposed"), "stale": False, "reason": rec.get("reason") or "", "actor": rec.get("actor"),
352
+ "updated_at": rec.get("updated_at"), "detail": rec.get("detail") or {}}
353
+
354
+
355
+ def status(db, scan: dict, cand: Candidate, rec: Optional[dict] = None) -> dict:
356
+ """Current state of ``cand``; invalidates (and persists the invalidation of) approvals whose patch or files changed."""
357
+ if rec is None:
358
+ rec = records(db, scan["repo"]["scan_id"]).get(cand.id)
359
+ out = _record_status(rec)
360
+ if rec and rec["state"] in BOUND:
361
+ why = ""
362
+ approved_at = (rec.get("detail") or {}).get("approved_at")
363
+ if not cand.diff or cand.manual:
364
+ why = "the change can no longer be generated from the current files"
365
+ elif rec.get("patch_sha") != cand.patch_sha:
366
+ why = "the proposed patch changed after the decision"
367
+ elif rec.get("revision") != revision(repo_root_of(scan), [t["path"] for t in cand.targets if t.get("path")]):
368
+ why = "the repository revision or an affected file changed after the decision"
369
+ elif not approved_at:
370
+ why = "no approval time was recorded for it"
371
+ elif time.time() - _epoch(approved_at) > approval_ttl_seconds():
372
+ why = f"it expired (approvals are valid for {approval_ttl_seconds() // 3600} hours)"
373
+ if why:
374
+ reason = f"Approval invalidated: {why}. Review it again."
375
+ if not _write(db, scan, cand, "pending_review", "stackparity", reason, binding=False, expected=rec):
376
+ latest = _record_status(records(db, scan["repo"]["scan_id"]).get(cand.id))
377
+ if latest["state"] in BOUND:
378
+ latest.update(state="pending_review", stale=True, reason="Remediation state changed during review. Refresh and try again.")
379
+ return latest
380
+ out.update(state="pending_review", stale=True, reason=reason)
381
+ return out
382
+
383
+
384
+ def decide(db, scan: dict, cand: Candidate, decision: str, actor: str, reason: str = "", choice: Optional[str] = None) -> dict:
385
+ if decision not in DECISIONS:
386
+ raise LifecycleError(f"Decision must be one of: {', '.join(DECISIONS)}")
387
+ current = status(db, scan, cand)
388
+ if current["state"] == "pr_created":
389
+ raise LifecycleError(f"{cand.id} already has a pull request; it cannot be decided again.")
390
+ if current["state"] == "applied":
391
+ raise LifecycleError(f"{cand.id} was already applied to the working tree; rescan to review the repository as it is now.")
392
+ if choice and choice != cand.choice:
393
+ if not any(a["key"] == choice and a.get("patch") for a in cand.alternatives):
394
+ raise LifecycleError(f"{cand.id} has no alternative named {choice!r}")
395
+ cand = _rechoose(scan, cand, choice)
396
+ if decision == "approved":
397
+ if cand.manual or not cand.diff:
398
+ raise LifecycleError(f"{cand.id} has no automatic change to approve; it is a manual recommendation.")
399
+ if cand.stale_reason:
400
+ raise LifecycleError(cand.stale_reason)
401
+ detail = {"approved_at": _now(), "approved_patch_sha": cand.patch_sha} if decision == "approved" else {"approved_at": None}
402
+ _write(db, scan, cand, decision, actor, reason or f"{decision.replace('_', ' ')} after reviewing the diff", detail)
403
+ return status(db, scan, cand)
404
+
405
+
406
+ def _rechoose(scan: dict, cand: Candidate, choice: str) -> Candidate:
407
+ fresh = next(c for c in _code_candidates(scan, repo_root_of(scan), {cand.id: choice}) if c.id == cand.id)
408
+ return fresh
409
+
410
+
411
+ def transition(db, scan: dict, cand: Candidate, state: str, actor: str, reason: str, detail: Optional[dict] = None) -> None:
412
+ """Move ``cand`` along the execution states. Review decisions (approve, reject, skip) are only possible through decide()."""
413
+ if state not in STATES:
414
+ raise LifecycleError(f"Unknown state {state}")
415
+ allowed = _TRANSITIONS.get(state)
416
+ if allowed is None:
417
+ raise LifecycleError(f"{state} is a review decision; record it with decide() after the diff was reviewed.")
418
+ current = status(db, scan, cand)["state"]
419
+ if current not in allowed:
420
+ raise LifecycleError(f"{cand.id} is {current.replace('_', ' ')}; it cannot move to {state.replace('_', ' ')}.")
421
+ _write(db, scan, cand, state, actor, reason, detail)
422
+
423
+
424
+ def _epoch(stamp: str) -> float:
425
+ try:
426
+ return datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).timestamp()
427
+ except (TypeError, ValueError):
428
+ return 0.0
429
+
430
+
431
+ def acquire(db, scan_id: str, ids: list[str]) -> bool:
432
+ """Mark ``ids`` busy so a concurrent CLI or dashboard run cannot execute or publish them twice."""
433
+ now = time.time()
434
+ with db.connect() as c:
435
+ busy = c.execute(f"SELECT COUNT(*) FROM remediation_state WHERE scan_id=? AND item_id IN ({','.join('?' * len(ids))}) AND busy_until > ?",
436
+ (scan_id, *ids, now)).fetchone()[0]
437
+ if busy:
438
+ return False
439
+ c.execute(f"UPDATE remediation_state SET busy_until=? WHERE scan_id=? AND item_id IN ({','.join('?' * len(ids))})", (now + LOCK_SECONDS, scan_id, *ids))
440
+ return True
441
+
442
+
443
+ def release(db, scan_id: str, ids: list[str]) -> None:
444
+ with db.connect() as c:
445
+ c.execute(f"UPDATE remediation_state SET busy_until=NULL WHERE scan_id=? AND item_id IN ({','.join('?' * len(ids))})", (scan_id, *ids))
446
+
447
+
448
+ def overview(db, scan: dict) -> list[dict]:
449
+ """Candidates with their evaluated state, for the dashboard and JSON output."""
450
+ recs = records(db, scan["repo"]["scan_id"])
451
+ out = []
452
+ for cand in candidates(scan, {k: v["choice"] for k, v in recs.items() if v.get("choice")}):
453
+ out.append({**cand.to_dict(), "status": status(db, scan, cand, recs.get(cand.id))})
454
+ return out
455
+
456
+
457
+ def approved(db, scan: dict) -> list[Candidate]:
458
+ recs = records(db, scan["repo"]["scan_id"])
459
+ out = []
460
+ for cand in candidates(scan, {k: v["choice"] for k, v in recs.items() if v.get("choice")}, include_manual=False):
461
+ if status(db, scan, cand, recs.get(cand.id))["state"] in APPLICABLE:
462
+ out.append(cand)
463
+ return out
464
+
465
+
466
+ # ---------------------------------------------------------------------------------------------------------------- materialize
467
+ def materialize(root: Path, cands: list[Candidate]) -> tuple[dict[str, str], dict[str, str]]:
468
+ """Combined new contents for ``cands`` applied in order. Returns (files, originals). Raises when two changes conflict."""
469
+ texts: dict[str, str] = {}
470
+ originals: dict[str, str] = {}
471
+ for cand in cands:
472
+ for t in cand.targets:
473
+ p = t.get("path")
474
+ if p and p not in originals:
475
+ text = read_file(root, p)
476
+ if text is None:
477
+ raise LifecycleError(f"{p} cannot be read safely")
478
+ originals[p] = text
479
+ if cand.kind == "dependency":
480
+ res = _apply_dependency(texts, root, cand)
481
+ if res is None:
482
+ raise LifecycleError(f"{cand.id} cannot be applied on top of the other approved changes")
483
+ texts = res
484
+ else:
485
+ path, line = cand.targets[0]["path"], cand.targets[0]["line"]
486
+ cur = texts.get(path, originals[path])
487
+ lines = cur.splitlines(keepends=True)
488
+ # an earlier fix in the same file may have inserted an import: locate the reported line by its content
489
+ near = [i for i, l in enumerate(lines) if l == cand.line_text]
490
+ if not near:
491
+ raise LifecycleError(f"{cand.id}: {path}:{line} changed; review it again")
492
+ idx = min(near, key=lambda i: abs(i - (line - 1)))
493
+ fixes = code_fixes.propose(path, cur, idx + 1, only=cand.choice)
494
+ if not fixes:
495
+ raise LifecycleError(f"{cand.id} cannot be applied on top of the other approved changes")
496
+ texts[path] = fixes[0][1]
497
+ return texts, originals
498
+
499
+
500
+ def combined_diff(files: dict[str, str], originals: dict[str, str]) -> str:
501
+ return "".join(patchers.unified_diff(p, originals[p], files[p]) for p in sorted(files) if files[p] != originals.get(p))
502
+
503
+
504
+ # ---------------------------------------------------------------------------------------------------------------- execution
505
+ def validate_approved(db, scan: dict, actor: str, *, run_tests: bool = False, lockfiles: bool = False, publish=None,
506
+ base: Optional[str] = None, policy=None, allow_build_code: bool = False
507
+ ) -> tuple[Any, Optional[tuple[dict, dict]], Optional[str]]:
508
+ """Validate (and optionally publish) the approved changes in an isolated worktree; record every state transition.
509
+
510
+ ``policy`` defaults to the execution policy the scan ran under (an offline scan is validated offline); pass
511
+ ``netpolicy.for_scan(scan).authorize([...], actor)`` only after the user explicitly allowed network access for this step.
512
+ Returns (IsolatedRun or None, (files, originals) or None, error message or None). Shared by the CLI and the dashboard.
513
+ """
514
+ from core import netpolicy
515
+ from remediation.worktree_pr import run_isolated
516
+ policy = policy or netpolicy.for_scan(scan)
517
+ root = repo_root_of(scan)
518
+ chosen = approved(db, scan)
519
+ if not chosen:
520
+ return None, None, "No approved changes. Review and approve candidates first."
521
+ if root is None:
522
+ return None, None, "The scanned repository is not available locally; changes cannot be validated from here."
523
+ ids = [c.id for c in chosen]
524
+ if not acquire(db, scan["repo"]["scan_id"], ids):
525
+ return None, None, "Another StackParity session is already applying or publishing these changes."
526
+ try:
527
+ try:
528
+ files, originals = materialize(root, chosen)
529
+ except LifecycleError as exc:
530
+ return None, None, str(exc)
531
+ run = run_isolated(root, scan, chosen, files, run_tests=run_tests, regenerate_locks=lockfiles, publish=publish, base_branch=base,
532
+ policy=policy, allow_build_code=allow_build_code)
533
+ validation = {"status": run.validation_status, "tests": run.tests_status, "tests_detail": run.tests_detail, "rescan": run.rescan,
534
+ "lockfiles": run.lockfiles, "lock_consistent": run.lock_consistent, "policy": run.policy, "error": run.error,
535
+ "branch": run.branch, "pr_url": run.pr_url, "patch_sha": hashlib.sha256(run.diff.encode()).hexdigest() if run.diff else None,
536
+ "at": _now()}
537
+ for cand in chosen:
538
+ if not run.patch_applied:
539
+ continue
540
+ transition(db, scan, cand, "applied_in_isolation", actor, "Applied in an isolated worktree", {"validation": validation})
541
+ if run.validation_status == "failed":
542
+ transition(db, scan, cand, "validation_failed", actor, run.error or "Validation failed", {"validation": validation})
543
+ continue
544
+ if run.validation_status == "validated":
545
+ transition(db, scan, cand, "validation_passed", actor, "Tests passed and the rescan confirmed the fix", {"validation": validation})
546
+ transition(db, scan, cand, "ready_for_pr", actor, f"Validation {run.validation_status}", {"validation": validation})
547
+ if run.published and run.pr_url:
548
+ transition(db, scan, cand, "pr_created", actor, f"Pull request {run.pr_url}", {"pr_url": run.pr_url, "branch": run.branch})
549
+ db.save_remediation_run(scan["repo"]["scan_id"], ",".join(ids), {"status": run.validation_status, "tests": run.tests_status,
550
+ "error": run.error, "pr_url": run.pr_url, "items": ids,
551
+ "lock_consistent": run.lock_consistent, "policy": run.policy})
552
+ return run, (files, originals), None
553
+ finally:
554
+ release(db, scan["repo"]["scan_id"], ids)
555
+
556
+
557
+ def apply_to_working_tree(db, scan: dict, run, files: dict[str, str], originals: dict[str, str], actor: str, *,
558
+ include_generated: bool = False, allow_inconsistent_lockfile: bool = False) -> list[str]:
559
+ """Write a validated run into the user's checkout. The only function that changes a user's repository files.
560
+
561
+ Refuses unless every candidate of ``run`` is still approved and validated in this lifecycle (not rejected, skipped,
562
+ expired, stale or failed), validation did not fail, and every affected file is byte-for-byte what was reviewed.
563
+ Regenerated lockfiles are written only with ``include_generated`` (the caller showed them and the user agreed). A run that
564
+ left a lockfile out of step with its manifest is refused unless ``allow_inconsistent_lockfile`` (the user was told which
565
+ command to run). Writes are atomic per file and rolled back on error. Returns the paths written.
566
+ """
567
+ import os
568
+ root = repo_root_of(scan)
569
+ if root is None:
570
+ raise LifecycleError("The scanned repository is not available locally.")
571
+ if run is None or not run.patch_applied:
572
+ raise LifecycleError("Nothing was validated; run the isolated validation first.")
573
+ if run.validation_status == "failed":
574
+ raise LifecycleError("Validation failed; nothing was written.")
575
+ recs = records(db, scan["repo"]["scan_id"])
576
+ current = {c.id: c for c in candidates(scan, {k: v["choice"] for k, v in recs.items() if v.get("choice")}, include_manual=False)}
577
+ for item in run.item_ids:
578
+ cand = current.get(item)
579
+ st = status(db, scan, cand, recs.get(item))["state"] if cand else "missing"
580
+ if st not in ("ready_for_pr", "validation_passed"):
581
+ raise LifecycleError(f"{item} is {st.replace('_', ' ')}, not an approved and validated change; nothing was written.")
582
+ approved_now = {c.id for c in approved(db, scan)}
583
+ if approved_now != set(run.item_ids):
584
+ raise LifecycleError("The set of approved changes differs from the validated set; validate again before applying.")
585
+ try:
586
+ expected, _ = materialize(root, [current[i] for i in run.item_ids])
587
+ except LifecycleError as exc:
588
+ raise LifecycleError(f"The approved changes no longer apply to the current files: {exc}") from exc
589
+ if expected != files:
590
+ raise LifecycleError("The validated contents differ from the approved changes; validate again before applying.")
591
+ plan = dict(files)
592
+ before = dict(originals)
593
+ if run.generated and not include_generated:
594
+ raise LifecycleError("Validation regenerated lockfile(s) " + ", ".join(sorted(run.generated)) + " that were not part of the reviewed diff; "
595
+ "review them and include them explicitly.")
596
+ if not run.lock_consistent and not allow_inconsistent_lockfile:
597
+ stale = [e["lockfile"] for e in run.lockfiles if not (e["status"] == "regenerated" and e["consistent"])]
598
+ raise LifecycleError(f"{', '.join(stale)} was not regenerated and verified; applying only the manifest would leave them inconsistent.")
599
+ if include_generated:
600
+ plan.update(run.generated)
601
+ before.update(run.generated_originals)
602
+ for rel, text in before.items():
603
+ if read_file(root, rel) != text and not (rel in run.generated_originals and read_file(root, rel) is None and text == ""):
604
+ raise LifecycleError(f"{rel} changed since the review; nothing was written. Rescan and review again.")
605
+ written: list[str] = []
606
+ try:
607
+ for rel, text in plan.items():
608
+ target = safe_target(root, rel)
609
+ tmp = target.with_name(f".{target.name}.stackparity-{os.getpid()}.tmp")
610
+ tmp.write_bytes(text.encode("utf-8"))
611
+ os.replace(tmp, target)
612
+ written.append(rel)
613
+ except (OSError, LifecycleError) as exc:
614
+ for rel in written:
615
+ try:
616
+ safe_target(root, rel).write_bytes(before.get(rel, "").encode("utf-8"))
617
+ except (OSError, LifecycleError):
618
+ pass
619
+ raise LifecycleError(f"Writing failed and the {len(written)} file(s) already written were restored: {exc}") from exc
620
+ for item in run.item_ids: # states were verified above; the files now differ, so do not re-derive the binding
621
+ _write(db, scan, current[item], "applied", actor, "Applied to the working tree after isolated validation",
622
+ {"applied_files": sorted(plan), "applied_at": _now()}, binding=False)
623
+ return sorted(plan)