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,709 @@
1
+ """Specialist agents. Each agent owns a set of pipeline steps, uses tools (Git, Syft, OSV, NetworkX, ...), reports every
2
+ observation/decision through the Runtime and leaves its outputs on the shared ScanState.
3
+
4
+ Reasoning is rule-based and deterministic. An LLM is used only where free text is produced (Risk Agent explanations),
5
+ and only when an API key is configured; its output is validated against the collected evidence.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import time
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Any, Optional
14
+
15
+ import networkx as nx
16
+
17
+ from agents.runtime import Runtime
18
+ from core import git_manager as gm
19
+ from core.models import Component, InspectionResult, LockDependency, RepoInfo
20
+ from core.repository_inspector import headline_languages, inspect_repository, own_package_identities
21
+ from explainability.explanation_engine import explain
22
+ from llm.client import from_settings as llm_from_settings, CALL_LOG
23
+ from evidence.store import EvidenceStore
24
+ from graph.dependency_tracer import classify_all
25
+ from graph.graph_builder import build_graph
26
+ from graph.graph_exporter import graph_to_json
27
+ from graph.graph_validator import validate_graph
28
+ from reporting import json_exporter, report_generator
29
+ from risk_analysis.evidence_collector import collect_lockfile_evidence, collect_typosquat_evidence, collect_vulnerability_evidence
30
+ from risk_analysis.evidence_normalizer import normalize_bundle
31
+ from risk_analysis.finding_correlator import correlate_findings, summarize_by_root
32
+ from sbom.cyclonedx_validator import load_sbom, normalize_components, validate_cyclonedx
33
+ from sbom.lockfile_analyzer import analyze_repository, supported_files
34
+ from sbom.package_extractors.common import parse_purl
35
+ from sbom.quality_analyzer import analyze_quality
36
+ from sbom.scanner_engine import SCANNER_LABELS, available_scanners, generate_sbom
37
+ from sbom.syft_runner import run_syft
38
+ from sbom.trivy_runner import run_trivy
39
+ from suspicious_changes.lockfile_change_detector import detect_lockfile_changes
40
+ from suspicious_changes.typosquatting_detector import detect_typosquatting
41
+ from vulnerability.kev_client import KevClient
42
+ from vulnerability.nvd_client import NvdClient
43
+ from vulnerability.osv_client import OsvClient
44
+ from vulnerability.verification import cross_check
45
+ from vulnerability.vulnerability_correlator import correlate
46
+
47
+ LLM_EXPLAIN_TOP_N = 15
48
+
49
+
50
+ from core.scan_state import ScanState # noqa: E402, F401
51
+
52
+
53
+ # ====================================================================================================== Recon
54
+ class ReconAgent:
55
+ name = "Recon Agent"
56
+
57
+ def discover(self, st: ScanState, rt: Runtime) -> None:
58
+ with rt.step("discover", f"Scanning {st.repo_dir.name} for manifests, lockfiles and configuration files (static, nothing is executed)") as b:
59
+ st.insp = inspect_repository(st.repo_dir, st.ctx.s)
60
+ insp = st.insp
61
+ for m in sorted(insp.manifests, key=lambda m: (m.service_dir, m.name)):
62
+ rt.progress("discover", f"Found {m.kind}: {m.path} ({m.ecosystem})", path=m.path, kind=m.kind, ecosystem=m.ecosystem)
63
+ for d in insp.dockerfiles + insp.container_files:
64
+ rt.progress("discover", f"Found container config: {d} (analysed statically)", path=d)
65
+ for c in insp.ci_files:
66
+ rt.progress("discover", f"Found CI/CD config: {c} (analysed statically)", path=c)
67
+ b["message"] = (f"{len(insp.manifests)} manifest/lock files, {len(insp.dockerfiles) + len(insp.container_files)} container files, "
68
+ f"{len(insp.ci_files)} CI files in {insp.total_files} files")
69
+
70
+ def classify(self, st: ScanState, rt: Runtime) -> None:
71
+ with rt.step("classify") as b:
72
+ insp = st.insp
73
+ st.service_dirs = sorted({s["dir"] for s in insp.services} | {"."}) if insp.services else ["."]
74
+ langs = headline_languages(insp)
75
+ rt.observe("classify", "Languages: " + (", ".join(f"{k} ({insp.languages[k]['files']} files)" for k in langs[:6]) or "none detected"))
76
+ rt.observe("classify", "Ecosystems: " + (", ".join(insp.ecosystems) or "none") + " | Frameworks: " + (", ".join(sorted({h.name for h in insp.frameworks})) or "none"))
77
+ rt.observe("classify", f"{len(insp.services)} service root(s): " + ", ".join(s["dir"] for s in insp.services[:8]))
78
+ b["message"] = f"{len(langs)} languages, {len(insp.ecosystems)} ecosystems, {len(insp.services)} services"
79
+
80
+
81
+ # ====================================================================================================== SBOM
82
+ class SBOMAgent:
83
+ name = "SBOM Agent"
84
+
85
+ def lockfiles(self, st: ScanState, rt: Runtime) -> None:
86
+ with rt.step("lockfiles") as b:
87
+ st.lock_deps, st.lock_errors = analyze_repository(st.repo_dir, st.insp)
88
+ by: dict[str, int] = {}
89
+ for d in st.lock_deps:
90
+ by[d.lockfile] = by.get(d.lockfile, 0) + 1
91
+ for f, n in sorted(by.items()):
92
+ rt.progress("lockfiles", f"Parsed {f}: {n} dependency records", file=f, count=n)
93
+ for e in st.lock_errors:
94
+ rt.warn("lockfiles", f"Could not parse {e['file']}: {e['error']}")
95
+ b["message"] = f"{len(st.lock_deps)} dependency records from {len(by)} files"
96
+
97
+ def generate(self, st: ScanState, rt: Runtime) -> None:
98
+ """Rule-based scanner selection: try Syft, then Trivy, then the built-in lockfile rule engine (see sbom/scanner_engine)."""
99
+ s = st.ctx.s
100
+ choice = getattr(st.options, "sbom_scanner", "auto") or "auto"
101
+ avail = available_scanners(s)
102
+ with rt.step("sbom_generate", f"Selecting SBOM scanner (requested: {SCANNER_LABELS.get(choice, choice)})") as b:
103
+ rt.observe("sbom_generate", "Scanners available: " + ", ".join(f"{k} ({'found' if v else 'not installed'})" for k, v in avail.items()))
104
+ out = generate_sbom(st.repo_dir, st.lock_deps, s.artifacts_dir / "sbom", st.prefix, choice, s, st.info.name, st.info.commit_sha)
105
+ for a in out.attempts:
106
+ if a["ok"]:
107
+ rt.observe("sbom_generate", f"{a['scanner']} produced a CycloneDX SBOM" + (f" (v{a['version']}, {a['duration_s']}s)" if a["version"] else ""), command=a["command"])
108
+ else:
109
+ rt.warn("sbom_generate", f"{a['scanner']} unavailable or failed: {a['error']}")
110
+ if out.scanner is None:
111
+ st.inventory_source = "none"
112
+ st.sbom_tool = {"requested": choice, "used": None, "attempts": out.attempts}
113
+ st.result["limitations"].append("No SBOM could be generated.")
114
+ b["message"] = "no SBOM generated"
115
+ return
116
+ failed_first = [a["scanner"] for a in out.attempts if not a["ok"]]
117
+ if failed_first:
118
+ rt.decide("sbom_generate", f"Fall back to {out.scanner}", reason=f"{', '.join(failed_first)} did not produce an SBOM; the next scanner in the chain was used.", agent="Supervisor")
119
+ if out.scanner == "builtin":
120
+ rt.decide("sbom_generate", "Use the built-in rule engine", reason="Generates CycloneDX from the parsed lockfiles/manifests with documented rules R1-R6; "
121
+ "the lockfile-vs-SBOM comparison is therefore not independent.", agent="Supervisor")
122
+ st.result["limitations"].append("The SBOM was produced by the built-in rule engine from lockfiles/manifests: "
123
+ "packages that are not declared in a parsed lockfile (binaries, OS packages, vendored code) are not inventoried.")
124
+ if out.engine_stats.get("skipped_unpinned"):
125
+ n = out.engine_stats["skipped_unpinned"]
126
+ rt.warn("sbom_generate", f"Rule R1: {n} declared dependency record(s) have no pinned version (manifest ranges without a lockfile) and are not inventoried.")
127
+ st.result["limitations"].append(f"{n} dependency declaration(s) without a pinned version were not inventoried by the rule engine; add a lockfile or install Syft/Trivy for better coverage.")
128
+ st.syft = out.run
129
+ st.sbom_doc, st.sbom_path, st.inventory_source = out.doc, out.raw_path, out.scanner
130
+ st.sbom_tool = {"requested": choice, "used": out.scanner, "attempts": out.attempts, "engine_stats": out.engine_stats,
131
+ "version": out.run.version if out.run else None, "run": out.run.to_dict() if out.run else None, "available": {k: bool(v) for k, v in avail.items()}}
132
+ b["message"] = f"{out.scanner}: CycloneDX {out.doc.get('specVersion')} ({len(out.doc.get('components', []))} components)"
133
+
134
+ def validate(self, st: ScanState, rt: Runtime) -> None:
135
+ if not st.sbom_doc:
136
+ rt.skip("sbom_validate", "no SBOM to validate")
137
+ st.result["sbom"] = {"path": None, "validation": {"valid": False, "errors": ["SBOM not generated"], "warnings": [], "stats": {}}}
138
+ return
139
+ with rt.step("sbom_validate") as b:
140
+ v = validate_cyclonedx(st.sbom_doc)
141
+ st.components = normalize_components(st.sbom_doc, st.repo_dir, st.service_dirs, tool=st.inventory_source)
142
+ own = own_package_identities(st.repo_dir, st.insp)
143
+ for c in st.components:
144
+ ids = own.get(c.service_dir or ".", set())
145
+ if any(c.name == n and (v is None or c.version in (None, v)) for n, v in ids):
146
+ c.is_self = True
147
+ selfs = [c for c in st.components if c.is_self]
148
+ if selfs:
149
+ rt.observe("sbom_validate", "Application's own package(s) recognised and excluded from dependency matching: " + ", ".join(f"{c.name}@{c.version}" for c in selfs))
150
+ st.result["sbom"] = {"path": st.sbom_path, "validation": v, "serial_number": st.sbom_doc.get("serialNumber"), "spec_version": st.sbom_doc.get("specVersion")}
151
+ for e in v["errors"]:
152
+ rt.warn("sbom_validate", f"Validation error: {e}")
153
+ if not v["valid"]:
154
+ rt.fail("sbom_validate", "SBOM failed validation: " + "; ".join(v["errors"][:3]))
155
+ return
156
+ rt.observe("sbom_validate", f"Valid CycloneDX {v['stats']['spec_version']}: {v['stats']['components']} components, {v['stats']['dependencies']} dependency records, {len(v['warnings'])} warnings")
157
+ b["message"] = "valid"
158
+
159
+ @staticmethod
160
+ def wants_second_pass(st: ScanState) -> bool:
161
+ """Routing predicate for the graph's conditional edge (auto mode, external primary scanner, SBOM misses lockfile packages)."""
162
+ return ((getattr(st.options, "sbom_scanner", "auto") or "auto") == "auto" and st.inventory_source in ("syft", "trivy")
163
+ and st.quality.get("inventory_status") == "incomplete")
164
+
165
+ def second_pass(self, st: ScanState, rt: Runtime) -> bool:
166
+ """Adaptive step: if the primary SBOM misses lockfile packages and another installed scanner has not run, run it and merge."""
167
+ s = st.ctx.s
168
+ if not self.wants_second_pass(st):
169
+ return False
170
+ q = st.quality
171
+ other = "trivy" if st.inventory_source == "syft" else "syft"
172
+ avail = available_scanners(s)
173
+ if not avail.get(other):
174
+ rt.observe("quality", f"{q['lockfile_missing_from_sbom_count']} lockfile package(s) are missing from the {st.inventory_source} SBOM; {other} is not installed, so no second opinion is possible", agent="Supervisor")
175
+ return False
176
+ rt.decide("quality", f"Run {other} as a second inventory and merge", reason=f"{q['lockfile_missing_from_sbom_count']} lockfile package(s) are missing from the {st.inventory_source} SBOM.", agent="Supervisor")
177
+ out_dir = s.artifacts_dir / "sbom"
178
+ res = (run_syft if other == "syft" else run_trivy)(st.repo_dir, out_dir / f"{st.prefix}.{other}.cdx.json", s)
179
+ st.sbom_tool.setdefault("attempts", []).append({"scanner": other, "ok": res.ok, "version": res.version, "duration_s": res.duration_s, "error": res.error,
180
+ "command": " ".join(res.command) if res.command else None, "role": "second-pass"})
181
+ if not res.ok:
182
+ rt.warn("quality", f"Second-pass {other} failed: {res.error}")
183
+ return False
184
+ from sbom.adapters import get_adapter
185
+ from sbom.merge import merge_inventories
186
+ sec_doc = get_adapter(other).canonicalize(load_sbom(res.sbom_path))
187
+ sec = normalize_components(sec_doc, st.repo_dir, st.service_dirs, tool=other)
188
+ st.sbom_doc, st.components, stats = merge_inventories(st.sbom_doc, st.components, sec_doc, sec)
189
+ merged_path = out_dir / f"{st.prefix}.merged.cdx.json"
190
+ merged_path.write_text(json.dumps(st.sbom_doc, indent=2), encoding="utf-8")
191
+ st.sbom_files = [{"label": f"{st.inventory_source} (primary, raw)", "path": st.sbom_path}, {"label": f"{other} (second pass, raw)", "path": res.sbom_path},
192
+ {"label": "merged canonical (used for analysis)", "path": str(merged_path)}]
193
+ st.inventory_source = f"{st.inventory_source}+{other}"
194
+ st.sbom_tool.update(merged=stats, used=st.inventory_source)
195
+ rt.observe("quality", f"Merged inventories: {stats['matched']} components confirmed by both, {stats['added_from_secondary']} added by {other}; analysis now uses {stats['total']} components")
196
+ st.quality = analyze_quality(st.components, st.sbom_doc, st.lock_deps, st.insp, syft_ok=True, lock_errors=st.lock_errors)
197
+ rt.observe("quality", f"Re-assessed inventory: {st.quality['inventory_status']}")
198
+ return True
199
+
200
+ def fuse_metadata(self, st: ScanState, rt: Runtime) -> None:
201
+ """Fill every metadata field from the most trustworthy source, record provenance, verify digests, write the fused CycloneDX file."""
202
+ s, o = st.ctx.s, st.options
203
+ if not st.sbom_doc:
204
+ rt.skip("metadata", "no SBOM to enrich")
205
+ return
206
+ with rt.step("metadata", "Fusing lockfile, scanner and registry metadata (field-level provenance)") as b:
207
+ from sbom.fusion.engine import fuse
208
+ from sbom.fusion.resolver import resolve
209
+ from sbom.fusion.writer import write_fused
210
+ if o.metadata_registry:
211
+ res_ = resolve(st.lock_deps, st.ctx.http, st.ctx.cache, budget_s=min(90.0, s.metadata_budget_s))
212
+ rs = res_["stats"]
213
+ st.result["registry_resolution"] = rs
214
+ if rs["candidates"]:
215
+ rt.decide("metadata", f"Resolve transitive dependencies of {rs['candidates']} pinned direct dependenc(ies) via deps.dev", reason="These services have no lockfile for that ecosystem, so the transitive closure "
216
+ "is otherwise unknown; resolution is done by the registry, nothing from the repository is executed.", agent="Supervisor")
217
+ rt.observe("metadata", f"Registry resolution: {rs['resolved']} resolved, {rs['not_found']} not found, {rs['unavailable']} unavailable -> {rs['derived_packages']} additional transitive package(s)")
218
+ if res_["derived"]:
219
+ from sbom.builtin_generator import generate_cyclonedx
220
+ from sbom.merge import merge_inventories
221
+ ddoc, _ = generate_cyclonedx(res_["derived"], st.info.name, st.info.commit_sha)
222
+ dcomps = normalize_components(ddoc, st.repo_dir, st.service_dirs, tool="builtin")
223
+ for c_ in dcomps:
224
+ c_.sources, c_.resolution = ["registry-resolver"], "registry-resolved"
225
+ st.lock_deps.extend(res_["derived"])
226
+ st.sbom_doc, st.components, mstats = merge_inventories(st.sbom_doc, st.components, ddoc, dcomps)
227
+ st.result["limitations"].append(f"{rs['derived_packages']} transitive package(s) were resolved by the deps.dev registry for manifest-only services (no lockfile): each direct dependency was "
228
+ "resolved on its own, so the project's real version mediation may differ. They are labelled 'registry-resolved'.")
229
+ rep = fuse(st.components, st.lock_deps, st.ctx.http if o.metadata_registry else None, st.ctx.cache, registry=bool(o.metadata_registry),
230
+ budget_s=s.metadata_budget_s, on_progress=lambda m: rt.progress("metadata", m))
231
+ st.fusion = rep
232
+ cov = rep["coverage"]
233
+ rt.observe("metadata", "Coverage (scanner -> after fusion): " + ", ".join(f"{f} {c['before']}->{c['after']}" for f, c in cov.items()) + f" of {rep['components']} components")
234
+ reg = rep.get("registry_phase", {})
235
+ if reg.get("skipped"):
236
+ rt.decide("metadata", "Skip registry look-ups", reason="Disabled in the scan options; only lockfile-recorded metadata was used.", agent="Supervisor")
237
+ else:
238
+ rt.observe("metadata", f"Registries: {reg.get('fetched', 0)} fetched, {reg.get('from_cache', 0)} from cache, {reg.get('not_found', 0)} not found, {reg.get('unavailable', 0)} unavailable"
239
+ + (f", {reg['skipped_budget']} skipped (time budget)" if reg.get("skipped_budget") else ""))
240
+ if reg.get("hosts_tripped"):
241
+ rt.warn("metadata", "Registry host(s) unreachable, skipped after repeated failures: " + ", ".join(reg["hosts_tripped"]))
242
+ st.result["limitations"].append("Some registries were unreachable; metadata for those packages may be incomplete (see Metadata tab for per-field reasons).")
243
+ if reg.get("unsupported_ecosystems"):
244
+ rt.observe("metadata", "No registry client for: " + ", ".join(reg["unsupported_ecosystems"]) + " (only lockfile/scanner metadata available)")
245
+ integ = rep["integrity"]
246
+ rt.observe("metadata", "Integrity: " + ", ".join(f"{k} {v}" for k, v in sorted(integ.items())))
247
+ if rep["integrity_mismatches"]:
248
+ rt.warn("metadata", f"{len(rep['integrity_mismatches'])} lockfile digest(s) differ from the registry's digest for the same version - possible tampered lockfile or republished package")
249
+ rt.decide("metadata", "Surface integrity mismatches prominently", reason="A pinned digest that does not match the registry is a strong supply-chain signal.", agent="Supervisor")
250
+ if rep["install_script_packages"]:
251
+ rt.observe("metadata", f"{len(rep['install_script_packages'])} package(s) run install-time scripts")
252
+ out_dir = s.artifacts_dir / "sbom"
253
+ fused = write_fused(st.sbom_doc, st.components, rep, st.inventory_source)
254
+ path = out_dir / f"{st.prefix}.fused.cdx.json"
255
+ path.write_text(json.dumps(fused, indent=2), encoding="utf-8")
256
+ v = validate_cyclonedx(fused)
257
+ for e in v["errors"]:
258
+ rt.warn("metadata", f"Fused document validation error: {e}")
259
+ raw = st.sbom_files or [{"label": f"{st.inventory_source} (raw scanner output)", "path": st.sbom_path}]
260
+ st.sbom_files = [{"label": "FUSED CycloneDX (scanner + lockfile + registries, with provenance)", "path": str(path)}] + raw
261
+ st.fused_path, st.sbom_doc, st.sbom_path = str(path), fused, str(path) # the fused file is the primary SBOM; raw files stay in sbom_files
262
+ st.result["sbom"] = {**st.result.get("sbom", {}), "fused_validation": v, "fused_path": str(path)}
263
+ st.quality = analyze_quality(st.components, st.sbom_doc, st.lock_deps, st.insp, syft_ok=True, lock_errors=st.lock_errors)
264
+ b["message"] = f"avg completeness {rep['average_completeness']:.0%}; integrity: " + ", ".join(f"{k} {v}" for k, v in sorted(integ.items()))
265
+
266
+ def quality(self, st: ScanState, rt: Runtime) -> None:
267
+ with rt.step("quality") as b:
268
+ st.quality = analyze_quality(st.components, st.sbom_doc, st.lock_deps, st.insp, syft_ok=bool(st.sbom_doc), lock_errors=st.lock_errors)
269
+ q = st.quality
270
+ if st.inventory_source == "builtin":
271
+ q.setdefault("limitations", []).append("SBOM and lockfile inventory come from the same parsers, so the lockfile-vs-SBOM comparison cannot reveal missed packages.")
272
+ rt.observe("quality", f"Inventory: {q['inventory_status']}; relationships: {q['dependency_relationships']}; metadata: {q['metadata_status']}; "
273
+ f"{q['lockfile_missing_from_sbom_count']} lockfile packages missing from SBOM; {q['unresolved_components']} unresolved components")
274
+ if q["lockfile_missing_from_sbom_count"]:
275
+ rt.decide("quality", "Flag the SBOM as incomplete", reason="Lockfile packages were not discovered by Syft.", agent="Supervisor")
276
+ b["message"] = q["inventory_status"]
277
+
278
+
279
+ def _components_from_lockfiles(lock_deps: list[LockDependency]) -> list[Component]:
280
+ seen: dict[str, Component] = {}
281
+ for d in lock_deps:
282
+ if not d.version or d.lockfile.endswith("go.sum"):
283
+ continue
284
+ ref = f"lock:{d.ecosystem}:{d.name}@{d.version}:{d.service_dir}"
285
+ if ref in seen:
286
+ continue
287
+ pp = parse_purl(d.purl) if d.purl else None
288
+ seen[ref] = Component(bom_ref=ref, name=pp["osv_name"] if pp else d.name, version=d.version, purl=d.purl, ecosystem=d.ecosystem,
289
+ purl_type=pp["type"] if pp else None, locations=[d.lockfile], service_dir=d.service_dir, found_by="lockfile-parser")
290
+ return list(seen.values())
291
+
292
+
293
+ # ====================================================================================================== Graph
294
+ class GraphAgent:
295
+ name = "Graph Agent"
296
+
297
+ def build(self, st: ScanState, rt: Runtime) -> None:
298
+ with rt.step("graph") as b:
299
+ g, binfo = build_graph(st.sbom_doc, st.components, st.lock_deps, st.service_dirs, st.info.name)
300
+ val = validate_graph(g, binfo)
301
+ st.graph, st.rel = g, classify_all(g)
302
+ st.result["graph"] = {**graph_to_json(g, val), "relationships": st.rel}
303
+ for w in val["warnings"]:
304
+ rt.observe("graph", w)
305
+ direct = sum(1 for per in st.rel.values() if any(v.startswith("direct") for v in per.values()))
306
+ b["message"] = f"{val['components']} packages, {val['edges']} edges, {len(val['roots'])} root(s); {direct} direct, {len(st.rel) - direct} transitive-only"
307
+
308
+
309
+ # ====================================================================================================== Vulnerability
310
+ class VulnerabilityAgent:
311
+ name = "Vulnerability Agent"
312
+ ORDER = ["osv", "enrich", "trace"]
313
+
314
+ def run(self, st: ScanState, rt: Runtime) -> None:
315
+ o, s, ctx = st.options, st.ctx.s, st.ctx
316
+ eligible = [c for c in st.components if c.ecosystem and c.version and c.type != "file"]
317
+ if not eligible:
318
+ for step in self.ORDER:
319
+ rt.skip(step, "no components with a known ecosystem and version")
320
+ st.result.update(vuln_coverage={}, source_status={"OSV": {"source": "OSV", "state": "not_queried"}})
321
+ if st.pipe and st.pipe.get("container_findings"): # a Dockerfile-only project still has image findings
322
+ st.vulns = list(st.pipe["container_findings"])
323
+ return
324
+ st.osv = OsvClient(ctx.http, ctx.cache, s.osv_batch_size, s.osv_workers)
325
+
326
+ def on_step(stage: str, msg: str) -> None:
327
+ idx = self.ORDER.index(stage)
328
+ for earlier in self.ORDER[:idx]:
329
+ rt.finish_open(earlier, "done")
330
+ rt.begin(stage, msg)
331
+
332
+ for attempt in (1, 2):
333
+ osv = st.osv if attempt == 1 else OsvClient(ctx.http, ctx.cache, s.osv_batch_size, s.osv_workers)
334
+ st.osv = osv
335
+ nvd = NvdClient(ctx.http, ctx.cache, s.nvd_api_key) if o.use_nvd else None
336
+ kev = KevClient(ctx.http, ctx.cache) if o.use_kev else None
337
+ cap = s.nvd_max_cves_with_key if s.nvd_api_key else s.nvd_max_cves_no_key
338
+ try:
339
+ st.vres = correlate(st.components, st.graph, st.lock_deps, osv, nvd, kev, cap, st.info.scan_timestamp, s.max_paths_per_target,
340
+ s.max_path_depth, on_step=on_step)
341
+ except Exception as e:
342
+ for step in self.ORDER:
343
+ if rt.status[step] == "running":
344
+ rt.fail(step, f"{type(e).__name__}: {str(e)[:200]}")
345
+ st.vres = None
346
+ break
347
+ state = st.vres["source_status"]["OSV"]["state"]
348
+ if state in ("unavailable", "partial") and attempt == 1:
349
+ rt.decide("osv", "Retry OSV once after a short pause", reason=f"OSV state was '{state}'; packages that already succeeded are cached so only the missing ones are re-queried.", agent="Supervisor")
350
+ time.sleep(3)
351
+ continue
352
+ break
353
+ if st.vres is None:
354
+ st.result["limitations"].append("Vulnerability correlation failed; absence of findings here does NOT mean no vulnerabilities.")
355
+ st.result.update(vuln_coverage={}, source_status={"OSV": {"source": "OSV", "state": "failed"}})
356
+ return
357
+ st.vulns = [f.model_dump() for f in st.vres["findings"]]
358
+ if st.pipe and st.pipe.get("container_findings"):
359
+ st.vulns.extend(st.pipe["container_findings"])
360
+ st.result.update(vuln_coverage=st.vres["coverage"], source_status=st.vres["source_status"])
361
+ cov = st.vres["coverage"]
362
+ rt.observe("osv", f"{cov['queried_unique_packages']} unique packages queried; {cov['advisories_returned']} advisories returned; "
363
+ f"{cov['confirmed']} confirmed, {cov['not_affected']} not affected after local range validation, {cov['unknown']} unconfirmed; "
364
+ f"{cov['unscanned_components']} components not queryable")
365
+ nvd_s = st.vres["source_status"]["NVD"]
366
+ if nvd_s.get("skipped_over_cap"):
367
+ rt.decide("enrich", f"Limit NVD lookups to {nvd_s['requested'] + nvd_s['from_cache']} CVEs", reason="No NVD_API_KEY: the public rate limit allows only a few requests; "
368
+ f"CVEs without any CVSS score were prioritised; {nvd_s['skipped_over_cap']} skipped.", agent="Supervisor")
369
+ if not (o.use_nvd or o.use_kev):
370
+ rt.progress("enrich", "NVD and KEV disabled by options")
371
+ for step in self.ORDER:
372
+ rt.finish_open(step, "done")
373
+ tr = [f for f in st.vulns if f["dependency_type"] == "transitive"]
374
+ rt.observe("trace", f"{len(tr)} findings are transitive; {len({p for f in tr for p in f['source_packages']})} direct dependencies introduce them")
375
+ st.result["osv_name_route"] = st.vres["osv_name_route"]
376
+
377
+
378
+ class VerificationAgent:
379
+ name = "Verification Agent"
380
+
381
+ def run(self, st: ScanState, rt: Runtime) -> None:
382
+ if st.vres is None or st.osv is None or not st.vres.get("osv_name_route"):
383
+ rt.skip("verify", "no OSV results to verify")
384
+ return
385
+ if st.vres["source_status"]["OSV"]["state"] in ("unavailable", "failed"):
386
+ rt.skip("verify", "OSV unreachable")
387
+ return
388
+ with rt.step("verify", "Re-querying every PURL through OSV's PURL route and comparing with the name/version route") as b:
389
+ res = cross_check(st.osv, st.vres["osv_name_route"], st.vres["findings"])
390
+ st.vulns = [f.model_dump() for f in st.vres["findings"]]
391
+ if st.pipe and st.pipe.get("container_findings"):
392
+ st.vulns.extend(st.pipe["container_findings"])
393
+ st.result["verification"] = res
394
+ rt.observe("verify", f"{res['routes_agree']}/{res['components_checked']} components returned identical advisory sets by both routes; "
395
+ f"{res['findings_cross_verified']}/{res['findings_checked']} findings independently reproduced")
396
+ if res["disagreement_count"]:
397
+ rt.warn("verify", f"{res['disagreement_count']} component(s) differ between the two routes (listed in the Ground Truth view)")
398
+ b["message"] = f"{res['findings_cross_verified']}/{res['findings_checked']} findings cross-verified"
399
+
400
+ # ====================================================================================================== Threat
401
+ class ThreatAgent:
402
+ name = "Threat Agent"
403
+
404
+ def typosquat(self, st: ScanState, rt: Runtime) -> None:
405
+ o = st.options
406
+ with rt.step("typosquat") as b:
407
+ dep = {r: {"type": _overall(v), "roots": [st.graph.nodes[k].get("label", k) for k in v]} for r, v in st.rel.items()}
408
+ st.typo = detect_typosquatting(st.components, st.ctx.http if o.registry_checks else None, st.ctx.cache, dep, st.info.scan_timestamp)
409
+ stt = st.typo["stats"]
410
+ rt.observe("typosquat", f"{stt.get('unique_packages_checked', 0)} package names compared; {stt.get('candidates', 0)} similarity candidates; "
411
+ f"{stt.get('registry_checks', 0)} verified against the registry; {stt.get('suppressed_established', 0)} suppressed as established packages")
412
+ if stt.get("candidates") and not o.registry_checks:
413
+ rt.decide("typosquat", "Cap uncorroborated name matches at 'low' evidence", reason="Registry checks are disabled.", agent="Supervisor")
414
+ b["message"] = f"{len(st.typo['findings'])} suspicious package name(s)"
415
+
416
+ def package_risk(self, st: ScanState, rt: Runtime) -> None:
417
+ from suspicious_changes.package_risk import assess
418
+ with rt.step("package_risk", "Checking fused package metadata for integrity, install-script, recency, deprecation and dependency-confusion signals") as b:
419
+ st.pkgrisk = assess(st.components, st.info.scan_timestamp)
420
+ fs = st.pkgrisk["findings"]
421
+ for f in fs:
422
+ f["evidence_id"] = st.evidence.add("registry", "package-risk", f["finding_id"], f"{f['rule_id']}: {f['title']}", {"rule": f["rule_id"], "package": f["subject"]})
423
+ pv = st.pkgrisk["provenance"]
424
+ rt.observe("package_risk", f"{len(fs)} signal(s); build provenance published for {pv['attested']} of {pv['with_registry_data']} packages with registry data (presence only, not cryptographically verified)")
425
+ if any(f["rule_id"] == "PKG-INT" for f in fs):
426
+ rt.decide("package_risk", "Escalate lockfile digest mismatches", reason="A pinned digest that does not match the registry is a strong supply-chain signal.", agent="Supervisor")
427
+ b["message"] = f"{len(fs)} package risk signal(s)"
428
+
429
+ def lockfile_history(self, st: ScanState, rt: Runtime) -> None:
430
+ o = st.options
431
+ if not st.git_history:
432
+ rt.skip("lockfile_history", "not the top level of a Git repository")
433
+ st.lres["limitations"] = ["The scanned path is not the top level of a Git repository, so no Git history comparison was possible (nothing inferred)."]
434
+ return
435
+ with rt.step("lockfile_history", f"Comparing the {o.lockfile_commits} most recent commit(s) with their parent{' / explicit baseline' if o.baseline else ''}") as b:
436
+ st.lres = detect_lockfile_changes(st.repo_dir, "HEAD", o.baseline, o.lockfile_commits, st.info.scan_timestamp)
437
+ sm = st.lres.get("summary") or {}
438
+ for c in st.lres.get("comparisons", []):
439
+ rt.progress("lockfile_history", f"{c['commit'][:8]} vs {(c['baseline'] or 'none')[:8]}: {c['status']}; lockfiles changed: {', '.join(c.get('lockfiles_changed', [])) or 'none'}")
440
+ for lim in st.lres.get("limitations", []):
441
+ rt.warn("lockfile_history", lim)
442
+ if sm.get("potentially_suspicious"):
443
+ rt.decide("lockfile_history", f"Escalate {sm['potentially_suspicious']} potentially suspicious change(s) to risk scoring",
444
+ reason="Integrity/source anomalies were found in Git history.", agent="Supervisor")
445
+ b["message"] = f"{sm.get('total_changes', 0)} changes: {sm.get('potentially_suspicious', 0)} suspicious, {sm.get('unexplained_change', 0)} unexplained"
446
+
447
+ def suspicious_changes(self, st: ScanState, rt: Runtime) -> None:
448
+ from suspicious_changes.analyzer import ChangeAnalyzer
449
+ with rt.step("suspicious_changes", "Running integrated non-CVE forensic change analysis and SuspiciousChangeAgent") as b:
450
+ base = st.options.baseline or f"HEAD~{max(1, int(getattr(st.options, 'lockfile_commits', 1) or 1))}"
451
+ analyzer = ChangeAnalyzer(
452
+ repo_dir=st.repo_dir,
453
+ base_commit=base,
454
+ head_commit="HEAD",
455
+ enable_ai=bool(getattr(st.options, "use_llm", False)),
456
+ )
457
+ res = analyzer.run_investigation()
458
+ st.suspicious_changes = res
459
+ findings = res.get("findings") or []
460
+ scenarios = res.get("correlated_scenarios") or []
461
+ for f in findings:
462
+ fid = str(f.get("id") or f.get("finding_id") or "")
463
+ if fid:
464
+ f["evidence_id"] = st.evidence.add(
465
+ "suspicious_change",
466
+ "change-analyzer",
467
+ fid,
468
+ f"{f.get('category', 'Supply Chain')}: {f.get('title', '')}",
469
+ {"severity": f.get("severity"), "confidence": f.get("confidence"), "evidence_type": f.get("evidence_type")},
470
+ source=f"{f.get('affected_file', '')}:{f.get('line_number', 1)}",
471
+ )
472
+ rt.observe("suspicious_changes", f"{len(findings)} non-CVE forensic finding(s); {len(scenarios)} correlated scenario(s); {len(res.get('ai_investigations') or [])} investigation(s)")
473
+
474
+ # Run modular Non-CVE scanner registry (supply-chain anomaly, SAST/taint, IaC)
475
+ from non_cve import ScanContext, run_all_scanners
476
+ nc_res = run_all_scanners(ScanContext(
477
+ repo_dir=st.repo_dir,
478
+ components=st.components,
479
+ lock_deps=st.lock_deps,
480
+ inspection=st.insp,
481
+ scan_timestamp=st.info.scan_timestamp,
482
+ http_client=getattr(st.ctx, "http", None),
483
+ registry_checks=bool(getattr(st.options, "registry_checks", True)),
484
+ ))
485
+ by_cat = nc_res.get("by_category") or {}
486
+ st.result["scanner_status"] = nc_res.get("meta") or {}
487
+ for scanner_name, meta in st.result["scanner_status"].items():
488
+ if meta.get("status") == "error":
489
+ rt.warn("suspicious_changes", f"Scanner '{scanner_name}' failed: {meta.get('error')}")
490
+ st.result["plugin_findings"] = [{**f, "category": cat} for cat, found in by_cat.items()
491
+ if cat not in ("supply_chain", "sast", "iac") for f in found]
492
+ st.supply_chain_anomalies = by_cat.get("supply_chain", [])
493
+ st.sast_findings = by_cat.get("sast", [])
494
+ st.iac_findings = by_cat.get("iac", [])
495
+ st.result.setdefault("limitations", []).extend(nc_res.get("limitations") or [])
496
+ total_nc = len(st.supply_chain_anomalies) + len(st.sast_findings) + len(st.iac_findings)
497
+ rt.observe("suspicious_changes", f"Modular Non-CVE scanners: {len(st.supply_chain_anomalies)} supply-chain, {len(st.sast_findings)} SAST/taint, {len(st.iac_findings)} IaC finding(s)")
498
+ b["message"] = f"{len(findings)} forensic + {total_nc} modular Non-CVE finding(s), {len(scenarios)} scenario(s)"
499
+
500
+
501
+ def _overall(r: dict) -> str:
502
+ vals = set(r.values())
503
+ return "direct" if "direct" in vals else "direct_inferred" if "direct_inferred" in vals else "transitive" if "transitive" in vals else "unknown"
504
+
505
+
506
+ # ====================================================================================================== Risk
507
+ class RiskAgent:
508
+ name = "Risk Agent"
509
+
510
+ def score(self, st: ScanState, rt: Runtime) -> None:
511
+ with rt.step("risk") as b:
512
+ st.risk = correlate_findings(
513
+ st.vulns,
514
+ [f.model_dump() for f in st.typo["findings"]],
515
+ st.lres["findings"],
516
+ st.rules,
517
+ st.pipe["findings"] + st.pkgrisk["findings"],
518
+ source_index=st.source_index,
519
+ repo_dir=getattr(st, "repo_dir", None),
520
+ )
521
+ res = st.result
522
+ res["risk_assessments"], res["correlations"] = st.risk["assessments"], st.risk["correlations"]
523
+ res["risk_by_root"] = summarize_by_root(st.vulns, st.risk["assessments"])
524
+ counts: dict[str, int] = {}
525
+ for a in st.risk["assessments"]:
526
+ counts[a["label"]] = counts.get(a["label"], 0) + 1
527
+ rt.observe("risk", "Risk labels: " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items(), key=lambda kv: ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFORMATIONAL"].index(kv[0]))))
528
+ for c in st.risk["correlations"]:
529
+ rt.decide("risk", c["note"], reason="Independent detectors agree on the same package.", agent="Supervisor")
530
+ b["message"] = f"{len(st.risk['assessments'])} findings scored"
531
+
532
+ def explain(self, st: ScanState, rt: Runtime) -> None:
533
+ s, o = st.ctx.s, st.options
534
+ with rt.step("explain") as b:
535
+ llm = None
536
+ client = llm_from_settings(s) if o.use_llm else None
537
+ if client:
538
+ llm = lambda sys_, usr: client.complete(sys_, usr, max_tokens=1500) # noqa: E731
539
+ elif o.use_llm:
540
+ rt.warn("explain", "LLM explanations requested but LLM_API_KEY is not set - using deterministic templates")
541
+ risks = {a["finding_id"]: a for a in st.risk["assessments"]}
542
+ top = {a["finding_id"] for a in sorted(st.risk["assessments"], key=lambda a: -a["score"])[:LLM_EXPLAIN_TOP_N]}
543
+ if llm:
544
+ rt.decide("explain", f"Use the LLM only for the {LLM_EXPLAIN_TOP_N} highest-risk findings", reason="Bounds cost; every LLM section is validated against evidence and falls back to templates.", agent="Supervisor")
545
+ typos = [f.model_dump() for f in st.typo["findings"]]
546
+ sbom_id = st.sbom_doc.get("serialNumber")
547
+ lock_index = {(d.service_dir, d.ecosystem, d.name, d.version): d.model_dump() for d in st.lock_deps}
548
+ repo_d = st.result["repo"]
549
+ out, evidence = {}, {}
550
+ for items, collect in ((st.vulns, lambda f: collect_vulnerability_evidence(f, repo_d, sbom_id, lock_index)),
551
+ (typos, lambda f: collect_typosquat_evidence(f, repo_d, sbom_id)),
552
+ (st.lres["findings"], lambda f: collect_lockfile_evidence(f, repo_d, sbom_id))):
553
+ for f in items:
554
+ bundle = normalize_bundle(collect(f))
555
+ evidence[f["finding_id"]] = {k: v for k, v in bundle.items() if k != "corpus"}
556
+ out[f["finding_id"]] = explain(bundle, risks[f["finding_id"]], f, llm if f["finding_id"] in top else None)
557
+ for f in st.pipe["findings"] + st.pkgrisk["findings"]:
558
+ a = risks.get(f["finding_id"])
559
+ if not a:
560
+ continue
561
+ out[f["finding_id"]] = {"headline": f"{a['label']} risk - {f['title']}", "source": "template", "validation": {"grounded": True, "removed_sections": [], "checked": "template"},
562
+ "evidence_ids": [f["evidence_id"]] if f.get("evidence_id") else [],
563
+ "sections": {"impact": f["why"], "how_entered": f"{f['file']}" + (f":{f['line']}" if f["line"] else "") + (f" - `{f['snippet']}`" if f["snippet"] else ""),
564
+ "direct_transitive": (f"package signal {f['rule_id']} for {f['subject']}" if f.get("kind") == "package_risk" else f"{f['ecosystem']} configuration ({f['rule_id']}), not a package dependency"), "remediation": f["remediation"]}}
565
+ evidence[f["finding_id"]] = {"kind": f.get("kind", "pipeline"), "rule": f["rule_id"], "file": f["file"], "line": f["line"], "evidence_id": f.get("evidence_id")}
566
+ st.result["explanations"], st.result["evidence"] = out, evidence
567
+ replaced = sum(len(e["validation"].get("removed_sections", [])) for e in out.values())
568
+ if replaced:
569
+ rt.observe("explain", f"{replaced} LLM-written section(s) failed grounding checks and were replaced by templates")
570
+ b["message"] = f"{len(out)} explanations ({sum(1 for e in out.values() if e['source'] != 'template')} LLM-assisted)"
571
+ st.result["typosquatting"] = typos
572
+
573
+
574
+ # ====================================================================================================== Analyst
575
+ def llm_log() -> list:
576
+ """Outgoing LLM calls recorded by the client (size + hash only), for the disclosure section."""
577
+ return [dict(c) for c in CALL_LOG]
578
+
579
+
580
+ SEV = {"CRITICAL": 4, "HIGH": 3, "MEDIUM": 2, "LOW": 1, None: 0}
581
+
582
+
583
+ class AnalystAgent:
584
+ name = "Analyst Agent"
585
+
586
+ def summarize(self, st: ScanState, rt: Runtime) -> None:
587
+ with rt.step("summary") as b:
588
+ res = st.result
589
+ res["source_package_view"] = source_package_view(st.vulns, {a["finding_id"]: a for a in st.risk["assessments"]})
590
+ v = st.vulns
591
+ sm = res["summary"] = _summary(st, res)
592
+ crit = sum(1 for f in v if f["severity"] == "CRITICAL")
593
+ trans = [f for f in v if f["dependency_type"] == "transitive"]
594
+ lines = [f"{sm['components']} components analysed; {sm['vulnerabilities_confirmed']} confirmed vulnerability findings "
595
+ f"({crit} CRITICAL by CVSS), {sm['vuln_direct']} in direct and {sm['vuln_transitive']} in transitive dependencies."]
596
+ if trans:
597
+ lines.append(f"{len(trans)} transitive findings are introduced by {len({p for f in trans for p in f['source_packages']})} direct dependencies - "
598
+ "fixing a handful of those usually removes most of them.")
599
+ if st.pipe["findings"]:
600
+ ph = sm["pipeline_critical_high"]
601
+ lines.append(f"{len(st.pipe['findings'])} container/CI-CD hygiene finding(s)" + (f", {ph} of them critical or high" if ph else "") + " (Dockerfile, compose and workflow analysis).")
602
+ if st.typo["findings"]:
603
+ lines.append(f"{len(st.typo['findings'])} package name(s) resemble popular packages (signal only, not proof).")
604
+ ls = [c for c in st.lres["findings"] if c["classification"] != "insufficient_baseline"]
605
+ if ls:
606
+ lines.append(f"{len(ls)} lockfile change(s) in Git history need review.")
607
+ lim = st.result["limitations"]
608
+ lines.append("Not assessed: function-level reachability (reachability evidence is package-level). " + (f"{len(lim)} coverage limitation(s) are listed." if lim else ""))
609
+ state = ((res.get("source_status") or {}).get("OSV") or {}).get("state")
610
+ if state not in ("ok", "partial", "stale_cache"):
611
+ lines[0] = (f"{sm['components']} components inventoried; known vulnerabilities were NOT assessed "
612
+ f"(advisory source: {state or 'not queried'}). This is not a clean result.")
613
+ prios = []
614
+ for g in res["source_package_view"][:5]:
615
+ fix = g["top_fix"]
616
+ prios.append(f"Update **{g['source_package']}** in {g['root']}: it brings in {g['vulnerable_packages']} vulnerable package(s) (worst: {g['worst_severity'] or 'n/a'})"
617
+ + (f"; e.g. upgrade {fix}" if fix else ""))
618
+ res["analyst"] = {"headline": lines[0], "paragraphs": lines[1:], "priorities": prios}
619
+ for p in prios[:3]:
620
+ rt.decide("summary", p.replace("**", ""), reason="Highest-impact source package by worst risk and number of vulnerable packages.", agent="Analyst Agent")
621
+ b["message"] = f"{len(prios)} prioritised actions"
622
+
623
+ @staticmethod
624
+ def _policy_gate(st: ScanState, rt: Runtime) -> None:
625
+ """Evaluate the default policy so the report and UI always show a gate result (analyst waivers from memory apply)."""
626
+ from policy.engine import PolicyError, evaluate, load_policy
627
+ from storage.memory import Memory
628
+ try:
629
+ waivers = Memory(st.ctx.db).decisions(st.info.url)
630
+ pr = evaluate(load_policy(st.options.policy), st.result, waivers)
631
+ st.result["policy_result"] = pr
632
+ rt.observe("export", f"Policy gate '{pr['policy']}': {'PASS' if pr['passed'] else 'FAIL'} - {pr['blocking']} blocking, {pr['warnings']} warning(s), {pr['waived']} waived")
633
+ except (PolicyError, Exception) as e: # noqa: BLE001 - a policy problem must not lose the scan
634
+ rt.warn("export", f"Policy evaluation skipped: {type(e).__name__}: {str(e)[:120]}")
635
+
636
+ def export(self, st: ScanState, rt: Runtime) -> None:
637
+ s = st.ctx.s
638
+ res = st.result
639
+ with rt.step("export") as b:
640
+ self._policy_gate(st, rt)
641
+ res["llm_calls"] = list(llm_log())
642
+ paths = res.setdefault("artifacts", {})
643
+ from reporting.sarif import to_sarif
644
+ from reporting.vex import to_vex
645
+ (s.artifacts_dir / "reports").mkdir(parents=True, exist_ok=True)
646
+ (s.artifacts_dir / "reports" / f"{st.prefix}.sarif").write_text(json_exporter.dumps(to_sarif(res)), encoding="utf-8")
647
+ (s.artifacts_dir / "reports" / f"{st.prefix}.vex.json").write_text(json_exporter.dumps(to_vex(res)), encoding="utf-8")
648
+ paths["sarif"] = str(s.artifacts_dir / "reports" / f"{st.prefix}.sarif")
649
+ paths["vex"] = str(s.artifacts_dir / "reports" / f"{st.prefix}.vex.json")
650
+ (s.artifacts_dir / "graphs" / f"{st.prefix}.json").write_text(json_exporter.dumps(json_exporter.graph_export(res)), encoding="utf-8")
651
+ md = report_generator.generate_markdown(res)
652
+ (s.artifacts_dir / "reports" / f"{st.prefix}-report.md").write_text(md, encoding="utf-8")
653
+ (s.artifacts_dir / "reports" / f"{st.prefix}-report.html").write_text(report_generator.markdown_to_html(md), encoding="utf-8")
654
+ paths["report_md"] = str(s.artifacts_dir / "reports" / f"{st.prefix}-report.md")
655
+ paths["report_html"] = str(s.artifacts_dir / "reports" / f"{st.prefix}-report.html")
656
+ b["message"] = f"{len(paths)} reports written (JSON exports and SQLite record follow)"
657
+
658
+
659
+ def source_package_view(vulns: list[dict], risks: dict[str, dict]) -> list[dict]:
660
+ """Group findings by the direct ('source') dependency that introduces them, per root."""
661
+ groups: dict[tuple, dict] = {}
662
+ for f in vulns:
663
+ for e in f["exposures"]:
664
+ for p in e["paths"][:5]:
665
+ if len(p) < 2:
666
+ continue
667
+ key = (e["root"], p[1])
668
+ g = groups.setdefault(key, {"root": e["root"], "source_package": p[1], "findings": set(), "packages": set(), "direct_self": False,
669
+ "worst_severity": None, "worst_risk": "INFORMATIONAL", "fixes": []})
670
+ g["findings"].add(f["finding_id"])
671
+ g["packages"].add(f"{f['package_name']}@{f['installed_version']}")
672
+ if len(p) == 2:
673
+ g["direct_self"] = True
674
+ if SEV[f["severity"]] > SEV[g["worst_severity"]]:
675
+ g["worst_severity"] = f["severity"]
676
+ lab = risks.get(f["finding_id"], {}).get("label", "INFORMATIONAL")
677
+ order = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFORMATIONAL"]
678
+ if order.index(lab) < order.index(g["worst_risk"]):
679
+ g["worst_risk"] = lab
680
+ if f["recommended_fix"]:
681
+ g["fixes"].append(f"{f['package_name']} to {f['recommended_fix']}")
682
+ out = []
683
+ for g in groups.values():
684
+ out.append({"root": g["root"], "source_package": g["source_package"], "vulnerable_packages": len(g["packages"]), "findings": len(g["findings"]),
685
+ "finding_ids": sorted(g["findings"]), "is_itself_vulnerable": g["direct_self"], "worst_severity": g["worst_severity"],
686
+ "worst_risk": g["worst_risk"], "top_fix": g["fixes"][0] if g["fixes"] else None, "packages": sorted(g["packages"])[:12]})
687
+ order = ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFORMATIONAL"]
688
+ out.sort(key=lambda g: (order.index(g["worst_risk"]), -g["vulnerable_packages"]))
689
+ return out
690
+
691
+
692
+ def _summary(st: ScanState, result: dict) -> dict:
693
+ v = st.vulns
694
+ by_sev: dict[str, int] = {}
695
+ for f in v:
696
+ by_sev[f["severity"] or "UNKNOWN"] = by_sev.get(f["severity"] or "UNKNOWN", 0) + 1
697
+ from reporting.counts import risk_breakdown
698
+ by_risk, by_priority, by_risk_other = risk_breakdown(st.risk["assessments"], v)
699
+ confirmed = [f for f in v if f["affected_status"] == "confirmed_affected"]
700
+ return {
701
+ "components": len([c for c in st.components if c.type not in ("file", "container") and c.purl_type not in ("docker", "github") and not c.is_self]), "by_ecosystem": st.quality.get("components_by_ecosystem", {}),
702
+ "vulnerabilities_confirmed": len(confirmed), "vulnerabilities_unknown": len(v) - len(confirmed), "by_cvss_severity": by_sev,
703
+ "vuln_direct": sum(f["dependency_type"].startswith("direct") for f in v), "vuln_transitive": sum(f["dependency_type"] == "transitive" for f in v),
704
+ "kev": sum(f["kev"] for f in v), "with_fix": sum(bool(f["fixed_versions"]) for f in v),
705
+ "typosquatting": len(st.typo["findings"]),
706
+ "pipeline_findings": len(st.pipe["findings"]), "pipeline_critical_high": sum(1 for f in st.pipe["findings"] if f["severity"] in ("CRITICAL", "HIGH")),
707
+ "lockfile_findings": len([c for c in st.lres["findings"] if c["classification"] != "insufficient_baseline"]),
708
+ "by_risk": by_risk, "by_priority": by_priority, "by_risk_other": by_risk_other, "services": len(st.insp.services), "cross_verified": (result.get("verification") or {}).get("findings_cross_verified"),
709
+ }