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,17 @@
1
+ """StackParity — CLI-first, local-first software supply-chain security platform."""
2
+ from __future__ import annotations
3
+
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ __version__ = "1.0.0" # single source of truth: pyproject.toml reads it ([tool.hatch.version])
8
+ __app_name__ = "StackParity"
9
+
10
+ # Installed wheels ship the engine packages under stackparity/_engine (so they cannot shadow the host environment's modules);
11
+ # a source checkout keeps them next to this package under src/.
12
+ _ENGINE = Path(__file__).resolve().parent / "_engine"
13
+ _SRC = Path(__file__).resolve().parent.parent
14
+ for _path in (_ENGINE, _SRC):
15
+ if (_path / "core").is_dir() and str(_path) not in sys.path:
16
+ sys.path.insert(0, str(_path))
17
+ break
@@ -0,0 +1,294 @@
1
+ """Investigator Agent: turns a raw CVE match into an evidence-backed judgement of whether it matters for *this* application.
2
+
3
+ For every confirmed finding it runs a short, bounded tool loop (advisory facts -> dependency path -> import evidence -> EPSS) and derives a
4
+ verdict with a confidence score and the list of evidence ids it relied on.
5
+
6
+ * Deterministic planner (default, always runs): fixed rule table, reproducible, no network beyond the EPSS batch.
7
+ * LLM planner (optional, only when ``LLM_API_KEY`` is configured and "LLM" is ticked): for the highest-risk findings the model may call
8
+ the same read-only tools (<= N steps) and propose a verdict plus a rationale. The proposal passes a *grounding gate* and is accepted only if
9
+ it cites real evidence ids, mentions only facts present in the evidence, and does not contradict hard evidence (e.g. "not reachable" while an
10
+ import was found). Otherwise the deterministic verdict stays and the rejection reason is recorded. The LLM can therefore never lower
11
+ a finding below what the evidence supports, and every AI-assisted conclusion is labelled as such.
12
+
13
+ Verdicts never claim safety: ``no_import_evidence`` means "no static import found", not "not exploitable".
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import re
19
+ from typing import Any, Optional
20
+
21
+ from agents.runtime import Runtime
22
+ from agents.specialists import ScanState
23
+ from intel.epss import EpssClient
24
+ from llm.client import LLMError, extract_json, from_settings
25
+ from tools import builtin # noqa: F401 (registers the tools)
26
+ from tools.registry import ToolContext, call, catalogue
27
+
28
+ VERDICTS = ("exploitable_likely", "reachable", "possibly_reachable", "test_only", "no_import_evidence", "needs_review")
29
+ LLM_TOOLS = ("advisory_facts", "dependency_path", "find_imports", "package_meta", "epss", "read_snippet")
30
+ SEV_RANK = {"CRITICAL": 4, "HIGH": 3, "MEDIUM": 2, "LOW": 1, None: 0}
31
+ VERDICT_TEXT = {
32
+ "exploitable_likely": "likely exploitable: the application imports the package and exploitation signals are strong",
33
+ "reachable": "reachable: the application's own code imports the vulnerable package",
34
+ "possibly_reachable": "possibly reachable: a direct dependency that pulls it in is imported by the application (exact use of the vulnerable code is unknown)",
35
+ "test_only": "used only by tests in the analysed source",
36
+ "no_import_evidence": "no import found in the analysed source (the package may still be used through configuration, plugins or a CLI)",
37
+ "needs_review": "insufficient evidence to judge automatically",
38
+ }
39
+
40
+
41
+ def _name_of(label: str) -> str:
42
+ return label.rsplit("@", 1)[0] if "@" in label[1:] else label
43
+
44
+
45
+ def confidence(f: dict, reach: dict, epss: Optional[dict]) -> dict:
46
+ basis, score = [], 0
47
+ for ok, pts, txt in ((f["affected_status"] == "confirmed_affected", 30, "affected range confirmed by local version matching"),
48
+ (bool(f.get("cross_verified")), 20, "independently reproduced by a second OSV query route"),
49
+ (f.get("cvss_score") is not None, 10, "CVSS score available"),
50
+ (reach.get("status") not in (None, "unknown"), 20, "static import evidence available"),
51
+ (reach.get("confidence") == "high", 5, "import matching is exact for this ecosystem"),
52
+ (bool(f.get("fixed_versions")), 5, "fixed version known"),
53
+ (epss is not None, 10, "EPSS score available")):
54
+ if ok:
55
+ score += pts
56
+ basis.append(txt)
57
+ return {"score": score, "label": "High" if score >= 75 else "Medium" if score >= 45 else "Low", "basis": basis}
58
+
59
+
60
+ def decide(f: dict, reach: dict, epss: Optional[dict]) -> str:
61
+ e = (epss or {}).get("epss") or 0.0
62
+ hard = bool(f.get("kev")) or e >= 0.5
63
+ severe = (f.get("cvss_score") or 0) >= 7 or f.get("severity") in ("CRITICAL", "HIGH")
64
+ st = reach.get("status")
65
+ if f["affected_status"] != "confirmed_affected":
66
+ return "needs_review"
67
+ if st == "used_by_app":
68
+ return "exploitable_likely" if (hard or (severe and e >= 0.1)) else "reachable"
69
+ if st == "reachable_via_dependency":
70
+ return "possibly_reachable"
71
+ if st == "used_in_tests_only":
72
+ return "test_only"
73
+ if st == "not_imported":
74
+ return "no_import_evidence"
75
+ return "needs_review"
76
+
77
+
78
+ def rationale(f: dict, reach: dict, epss: Optional[dict], verdict: str, ev: dict) -> str:
79
+ parts = [f"{f['package_name']}@{f['installed_version']} ({f['primary_id']}): {VERDICT_TEXT[verdict]}."]
80
+ if reach.get("locations"):
81
+ loc = reach["locations"][0]
82
+ via = f" (via {reach['via'][0]})" if reach.get("via") else ""
83
+ parts.append(f"Import evidence: {loc['path']}:{loc['line']}{via} [{ev.get('reach')}].")
84
+ elif reach.get("status") not in (None, "unknown"):
85
+ parts.append(f"No import evidence in {reach.get('files_analysed', 0)} analysed source file(s) [{ev.get('reach')}].")
86
+ parts.append(f"Dependency: {f['dependency_type']}" + (f" via {', '.join(f['source_packages'][:2])}" if f["source_packages"] else "") + f" [{ev.get('path')}].")
87
+ sev = f"{f['severity']} (CVSS {f['cvss_score']})" if f.get("cvss_score") is not None else (f["severity"] or "severity unavailable")
88
+ parts.append(f"{sev}; " + ("listed in CISA KEV; " if f.get("kev") else "not in CISA KEV; ") + (f"EPSS {epss['epss']:.1%} [{ev.get('epss')}]." if epss else "EPSS unavailable."))
89
+ return " ".join(p for p in parts if p)
90
+
91
+
92
+ class InvestigatorAgent:
93
+ name = "Investigator Agent"
94
+
95
+ # ------------------------------------------------------------------ entry
96
+ def run(self, st: ScanState, rt: Runtime) -> None:
97
+ o, s = st.options, st.ctx.s
98
+ if not getattr(o, "investigate", True):
99
+ rt.skip("investigate", "disabled in the scan options")
100
+ return
101
+ if not st.vulns:
102
+ rt.skip("investigate", "no vulnerability findings to investigate")
103
+ return
104
+ with rt.step("investigate", f"Investigating {len(st.vulns)} finding(s) with read-only tools (import evidence, EPSS, dependency path)") as b:
105
+ ctx = ToolContext(repo_dir=st.repo_dir, evidence=st.evidence, http=st.ctx.http, cache=st.ctx.cache, state=st)
106
+ epss_client = EpssClient(st.ctx.http, st.ctx.cache)
107
+ cves = sorted({c for f in st.vulns for c in f["cve_ids"]})
108
+ st.epss = epss_client.get_many(cves)
109
+ st.result["epss_status"] = epss_client.status
110
+ rt.observe("investigate", f"EPSS: {len(st.epss)}/{len(cves)} CVEs scored ({epss_client.status['state']})")
111
+ if epss_client.status["state"] in ("unavailable", "partial"):
112
+ st.result["limitations"].append("EPSS exploitation probabilities were not fully available; exploitability scoring used KEV/CVSS only for the missing CVEs.")
113
+ results: dict[str, dict] = {}
114
+ for i, f in enumerate(st.vulns, 1):
115
+ results[f["finding_id"]] = self._investigate(ctx, f)
116
+ if i % 40 == 0:
117
+ rt.progress("investigate", f"{i}/{len(st.vulns)} findings investigated")
118
+ st.investigations = results
119
+ idx = st.source_index
120
+ if idx is not None:
121
+ rt.observe("investigate", f"Source index: {sum(idx.files_by_lang.values())} source file(s) analysed ({', '.join(idx.languages) or 'none'})" + ("; truncated at the file limit" if idx.truncated else ""))
122
+ counts: dict[str, int] = {}
123
+ for r in results.values():
124
+ counts[r["verdict"]] = counts.get(r["verdict"], 0) + 1
125
+ rt.observe("investigate", "Verdicts: " + ", ".join(f"{k} {v}" for k, v in sorted(counts.items(), key=lambda kv: VERDICTS.index(kv[0]))))
126
+ client = from_settings(s) if o.use_llm else None
127
+ if o.use_llm and not client:
128
+ rt.warn("investigate", "LLM reasoning requested but LLM_API_KEY is not set - deterministic investigation only")
129
+ if client:
130
+ self._llm_pass(st, rt, ctx, client)
131
+ st.result["investigations"] = results
132
+ b["message"] = ", ".join(f"{v} {k}" for k, v in sorted(counts.items(), key=lambda kv: VERDICTS.index(kv[0]))[:4])
133
+
134
+ # ------------------------------------------------------------------ deterministic planner
135
+ def _investigate(self, ctx: ToolContext, f: dict) -> dict:
136
+ fid = f["finding_id"]
137
+ steps: list[dict] = []
138
+
139
+ def use(tool: str, **args) -> dict:
140
+ r = call(ctx, tool, args)
141
+ steps.append({"tool": tool, "args": args, "evidence_id": r.get("evidence_id"), "error": r.get("error")})
142
+ return r
143
+
144
+ facts = use("advisory_facts", finding_id=fid)
145
+ path = use("dependency_path", finding_id=fid)
146
+ eco = f["ecosystem"]
147
+ if f["dependency_type"] in ("direct", "direct_inferred"):
148
+ r = use("find_imports", package=f["package_name"], ecosystem=eco)
149
+ reach = {**r, "package": f["package_name"], "via": []}
150
+ reach_ev = r.get("evidence_id")
151
+ else:
152
+ srcs = [_name_of(x) for x in f["source_packages"][:3]] or []
153
+ rs = [use("find_imports", package=n, ecosystem=eco) for n in srcs]
154
+ used = [(n, r) for n, r in zip(srcs, rs) if r.get("status") == "used_by_app"]
155
+ tests = [(n, r) for n, r in zip(srcs, rs) if r.get("status") == "used_in_tests_only"]
156
+ if used:
157
+ n, r = used[0]
158
+ reach = {**r, "status": "reachable_via_dependency", "package": n, "via": [x[0] for x in used]}
159
+ elif tests:
160
+ n, r = tests[0]
161
+ reach = {**r, "status": "used_in_tests_only", "package": n, "via": [x[0] for x in tests]}
162
+ elif rs and all(r.get("status") == "not_imported" for r in rs):
163
+ reach = {**rs[0], "status": "not_imported", "package": srcs[0], "via": []}
164
+ else:
165
+ reach = {"status": "unknown", "reason": "source packages could not be traced to application imports", "locations": [], "via": [], "confidence": "none"}
166
+ reach_ev = (rs[0].get("evidence_id") if rs else None)
167
+ epss = None
168
+ for c in f["cve_ids"]:
169
+ e = use("epss", cve=c)
170
+ if e.get("available") and (epss is None or e["epss"] > epss["epss"]):
171
+ epss = {k: e[k] for k in ("epss", "percentile", "date")}
172
+ epss["evidence_id"] = e.get("evidence_id")
173
+ ev = {"reach": reach_ev, "path": path.get("evidence_id"), "osv": facts.get("evidence_id"), "epss": (epss or {}).get("evidence_id")}
174
+ verdict = decide(f, reach, epss)
175
+ conf = confidence(f, reach, epss)
176
+ f["reachability"] = {k: reach.get(k) for k in ("status", "package", "via", "locations", "app_files", "test_files", "confidence", "reason", "files_analysed", "import_density", "import_ratio", "influence_tier")}
177
+ f["epss"], f["epss_percentile"] = (epss or {}).get("epss"), (epss or {}).get("percentile")
178
+ f["verdict"], f["verdict_confidence"] = verdict, conf
179
+ app_cnt = reach.get("app_files", 0)
180
+ dens = reach.get("import_density") or reach.get("influence_tier") or "unknown"
181
+ sev = f.get("severity")
182
+ if sev in ("CRITICAL", "HIGH") and reach.get("status") in ("not_imported", "used_in_tests_only") and not f.get("kev"):
183
+ prio_shift = {"shift": "deprioritized", "reason": f"Deprioritized: no production imports detected despite {sev} advisory severity", "influence_tier": dens}
184
+ elif sev in ("MEDIUM", "LOW") and (dens == "heavy" or app_cnt >= 5):
185
+ prio_shift = {"shift": "elevated", "reason": f"Elevated: heavy application imports across {app_cnt} files in production codebase", "influence_tier": "heavy"}
186
+ else:
187
+ prio_shift = {"shift": "standard", "reason": "Consistent with advisory severity and codebase reachability", "influence_tier": dens}
188
+ f["prioritization"] = prio_shift
189
+ return {"finding_id": fid, "verdict": verdict, "confidence": conf, "reachability": f["reachability"], "epss": epss, "steps": steps, "evidence_ids": [v for v in ev.values() if v],
190
+ "rationale": rationale(f, reach, epss, verdict, ev), "prioritization": prio_shift, "ai_assisted": False, "planner": "deterministic"}
191
+
192
+ # ------------------------------------------------------------------ optional LLM planner
193
+ def _llm_pass(self, st: ScanState, rt: Runtime, ctx: ToolContext, client) -> None:
194
+ s = st.ctx.s
195
+ ranked = sorted(st.vulns, key=lambda f: (-(f.get("kev") or 0), -SEV_RANK.get(f["severity"], 0), -(f.get("epss") or 0)))
196
+ pick = [f for f in ranked if f["affected_status"] == "confirmed_affected"][:s.investigator_llm_max]
197
+ if not pick:
198
+ return
199
+ rt.decide("investigate", f"Let {client.label} investigate the {len(pick)} highest-risk finding(s)", reason="Bounded by max steps and a grounding gate; the model may only call read-only tools and cannot "
200
+ "lower a verdict below what the evidence supports. Only package names, advisory facts and <=11-line import snippets are sent (secrets redacted).", agent="Supervisor")
201
+ accepted = rejected = errors = 0
202
+ for f in pick:
203
+ inv = st.investigations[f["finding_id"]]
204
+ try:
205
+ prop = self._llm_loop(ctx, client, f, inv, s.investigator_max_steps)
206
+ except LLMError as e:
207
+ errors += 1
208
+ inv["llm"] = {"status": "error", "error": str(e)[:160]}
209
+ if errors >= 2:
210
+ rt.warn("investigate", f"LLM unavailable ({str(e)[:100]}); continuing deterministically")
211
+ break
212
+ continue
213
+ except Exception as e: # noqa: BLE001
214
+ inv["llm"] = {"status": "error", "error": f"{type(e).__name__}: {str(e)[:120]}"}
215
+ continue
216
+ problems = self.guard(prop, f, inv, ctx)
217
+ if problems:
218
+ rejected += 1
219
+ inv["llm"] = {"status": "rejected", "problems": problems[:4], "proposal": {"verdict": prop.get("verdict")}}
220
+ continue
221
+ accepted += 1
222
+ inv["llm"] = {"status": "accepted", "model": client.label}
223
+ inv.update(verdict=prop["verdict"], rationale=prop["rationale"], ai_assisted=True, planner=f"llm:{client.label}", steps=inv["steps"] + prop["steps"],
224
+ evidence_ids=sorted(set(inv["evidence_ids"]) | set(prop["cites"])))
225
+ f["verdict"] = prop["verdict"]
226
+ rt.observe("investigate", f"LLM investigations: {accepted} accepted, {rejected} rejected by the grounding gate, {errors} error(s)")
227
+
228
+ def _llm_loop(self, ctx: ToolContext, client, f: dict, inv: dict, max_steps: int) -> dict:
229
+ system = ("You are a supply-chain security investigator. Decide whether a vulnerability in a dependency matters for THIS application. "
230
+ "Reply with exactly ONE JSON object per turn, either {\"tool\": <name>, \"args\": {...}} to gather evidence, or "
231
+ "{\"final\": {\"verdict\": <one of " + json.dumps(list(VERDICTS)) + ">, \"rationale\": <=500 characters of plain text that cites evidence ids in square brackets, \"cites\": [evidence ids]}}. "
232
+ "Rules: use only facts present in tool results; never invent versions, CVE ids, file names, numbers or evidence ids; imports are package-level evidence, not proof of exploitability; "
233
+ "if the evidence is insufficient answer needs_review. Tools: " + json.dumps([t for t in catalogue() if t["name"] in LLM_TOOLS]))
234
+ have = ctx.evidence.many(inv["evidence_ids"])
235
+ transcript: list[dict] = []
236
+ steps: list[dict] = []
237
+ brief = {"finding_id": f["finding_id"], "package": f"{f['package_name']}@{f['installed_version']}", "ecosystem": f["ecosystem"], "advisory": f["primary_id"], "severity": f["severity"], "cvss": f["cvss_score"],
238
+ "dependency": f["dependency_type"], "source_packages": f["source_packages"][:3], "kev": f["kev"], "epss": f.get("epss"), "baseline_verdict": inv["verdict"]}
239
+ for _ in range(max_steps):
240
+ user = json.dumps({"finding": brief, "evidence": [{"id": e.id, "summary": e.summary} for e in have], "transcript": transcript}, default=str)
241
+ msg = extract_json(client.complete(system, user, max_tokens=700, json_mode=True))
242
+ if "final" in msg:
243
+ fin = msg["final"]
244
+ return {"verdict": str(fin.get("verdict", "")), "rationale": str(fin.get("rationale", "")).strip(), "cites": [str(c) for c in fin.get("cites", []) if isinstance(c, str)], "steps": steps}
245
+ name, args = msg.get("tool"), msg.get("args") or {}
246
+ if name not in LLM_TOOLS:
247
+ transcript.append({"tool": name, "error": "tool not allowed"})
248
+ continue
249
+ res = call(ctx, name, args)
250
+ steps.append({"tool": name, "args": args, "evidence_id": res.get("evidence_id"), "error": res.get("error"), "by": "llm"})
251
+ if res.get("evidence_id"):
252
+ e = ctx.evidence.get(res["evidence_id"])
253
+ if e and all(x.id != e.id for x in have):
254
+ have.append(e)
255
+ transcript.append({"tool": name, "args": args, "result": {k: v for k, v in res.items() if k != "snippet"} | ({"snippet": res["snippet"]} if "snippet" in res else {})})
256
+ raise LLMError("no final answer within the step limit")
257
+
258
+ @staticmethod
259
+ def guard(prop: dict, f: dict, inv: dict, ctx: ToolContext) -> list[str]:
260
+ """Grounding gate for an LLM proposal. Returns the list of problems (empty = accepted)."""
261
+ problems: list[str] = []
262
+ if prop.get("verdict") not in VERDICTS:
263
+ problems.append(f"verdict '{prop.get('verdict')}' is not an allowed verdict")
264
+ return problems
265
+ text = prop.get("rationale", "")
266
+ if not text or len(text) > 700:
267
+ problems.append("rationale is empty or longer than 700 characters")
268
+ known = set(ctx.evidence._items)
269
+ cites = set(prop.get("cites", []))
270
+ bad = [c for c in cites if c not in known]
271
+ if bad:
272
+ problems.append(f"cites unknown evidence id(s): {', '.join(bad[:3])}")
273
+ if not cites:
274
+ problems.append("no evidence ids cited")
275
+ mentioned = set(re.findall(r"\[([a-z\-]+:[^\]\s]+#[0-9a-f]{6})\]", text))
276
+ if any(m not in known for m in mentioned):
277
+ problems.append("the text references an evidence id that does not exist")
278
+ allowed_ids = set(f["vulnerability_ids"]) | set(f["cve_ids"])
279
+ for cid in set(re.findall(r"\b(?:CVE-\d{4}-\d{4,}|GHSA-[0-9a-z\-]{14,}|PYSEC-\d{4}-\d+)\b", text)):
280
+ if cid not in allowed_ids:
281
+ problems.append(f"mentions advisory id {cid} that is not part of this finding")
282
+ st = inv["reachability"].get("status")
283
+ v = prop["verdict"]
284
+ epss = (inv.get("epss") or {}).get("epss") or 0.0
285
+ hard = bool(f.get("kev")) or epss >= 0.5 or ((f.get("cvss_score") or 0) >= 7 and epss >= 0.1)
286
+ if v in ("no_import_evidence", "test_only") and st in ("used_by_app", "reachable_via_dependency"):
287
+ problems.append("contradicts import evidence (the application imports the package or its parent)")
288
+ if v in ("reachable", "exploitable_likely") and st in ("not_imported", "used_in_tests_only", "unknown"):
289
+ problems.append("claims reachability without import evidence")
290
+ if v == "exploitable_likely" and not hard:
291
+ problems.append("claims likely exploitation without KEV/EPSS/CVSS support")
292
+ if f["affected_status"] != "confirmed_affected" and v != "needs_review":
293
+ problems.append("the affected range is not confirmed; only needs_review is allowed")
294
+ return problems
@@ -0,0 +1,37 @@
1
+ """Memory Agent: compares this scan with the repository's history and records it (deterministic, SQLite-backed)."""
2
+ from __future__ import annotations
3
+
4
+ from agents.runtime import Runtime
5
+ from agents.specialists import ScanState
6
+ from storage.memory import Memory, fingerprint, title
7
+
8
+
9
+ class MemoryAgent:
10
+ name = "Memory Agent"
11
+
12
+ def run(self, st: ScanState, rt: Runtime) -> None:
13
+ with rt.step("memory", "Comparing with previous scans of this repository and recording finding history") as b:
14
+ mem = Memory(st.ctx.db)
15
+ labels = {a["finding_id"]: a["label"] for a in st.risk["assessments"]}
16
+ typos = [f.model_dump() for f in st.typo["findings"]]
17
+ locks = [c for c in st.lres["findings"] if c["classification"] != "insufficient_baseline"]
18
+ items = ([("vulnerability", f, labels.get(f["finding_id"])) for f in st.vulns] + [("typosquatting", f, labels.get(f["finding_id"])) for f in typos]
19
+ + [("pipeline", f, labels.get(f["finding_id"])) for f in st.pipe["findings"]]
20
+ + [("package_risk", f, labels.get(f["finding_id"])) for f in st.pkgrisk["findings"]]
21
+ + [("lockfile_change", f, labels.get(f["finding_id"])) for f in locks])
22
+ diff = mem.record_scan(st.info.url, st.info.scan_id, st.info.scan_timestamp, items)
23
+ fps = {f["finding_id"]: fingerprint(k, f) for k, f, _ in items}
24
+ titles = {f["finding_id"]: title(k, f) for k, f, _ in items}
25
+ seen = mem.record_packages(st.info.url, {(c.ecosystem or "", c.name) for c in st.components if not c.is_self and c.type != "file" and c.ecosystem})
26
+ typo_seen = {f["package_name"]: seen[(f["ecosystem"], f["package_name"])] for f in typos if (f["ecosystem"], f["package_name"]) in seen}
27
+ st.result["memory"] = {"diff": diff, "fingerprints": fps, "titles": titles, "packages_seen_in_other_repos": len(seen), "typosquat_candidates_seen_elsewhere": typo_seen}
28
+ c = diff["counts"]
29
+ if diff["baseline"]:
30
+ rt.observe("memory", "First scan of this repository: no history to compare; this scan becomes the baseline.")
31
+ else:
32
+ rt.observe("memory", f"Compared with the previous state: {c['new']} new, {c['persisting']} persisting, {c['fixed']} fixed, {c['regressed']} reappeared.")
33
+ if c["regressed"]:
34
+ rt.decide("memory", f"Flag {c['regressed']} finding(s) that were fixed before and are back", reason="A previously fixed finding reappeared - likely a reverted upgrade.", agent="Supervisor")
35
+ if typo_seen:
36
+ rt.observe("memory", f"{len(typo_seen)} suspicious package name(s) were also seen in other scanned repositories: " + ", ".join(sorted(typo_seen)[:5]))
37
+ b["message"] = ("baseline recorded" if diff["baseline"] else f"{c['new']} new / {c['fixed']} fixed / {c['persisting']} persisting")
@@ -0,0 +1,152 @@
1
+ """Pipeline Agent: analyses container and CI/CD definitions and adds the images/actions the repository depends on to the SBOM."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+
6
+ from agents.runtime import Runtime
7
+ from agents.specialists import ScanState
8
+ from containers.discovery import discover_container_assets
9
+ from containers.trivy_image_scanner import scan_container_image
10
+ from core.models import Component
11
+ from pipeline_analysis.analyzer import analyze_repository
12
+
13
+ ICON_EVIDENCE = {"container": "dockerfile", "ci": "workflow"}
14
+
15
+
16
+ def _docker_purl(img: dict) -> str:
17
+ name = img["name"].replace("docker.io/", "").replace("index.docker.io/", "")
18
+ if name.startswith("library/"):
19
+ name = name[len("library/"):]
20
+ ver = img.get("digest") or img.get("tag")
21
+ return f"pkg:docker/{name}" + (f"@{ver}" if ver else "")
22
+
23
+
24
+ def _action_purl(a: dict) -> str:
25
+ return f"pkg:github/{a['name']}" + (f"@{a['ref']}" if a.get("ref") else "")
26
+
27
+
28
+ class PipelineAgent:
29
+ name = "Pipeline Agent"
30
+
31
+ def run(self, st: ScanState, rt: Runtime) -> None:
32
+ insp = st.insp
33
+ if not (insp.dockerfiles or insp.container_files or insp.ci_files):
34
+ rt.skip("pipeline", "no Dockerfile, compose file or CI/CD definition found")
35
+ st.pipe = {"findings": [], "images": [], "actions": [], "files": [], "summary": {"files_analysed": 0, "findings": 0, "by_severity": {}, "images": 0, "actions": 0, "actions_unpinned": 0, "images_unpinned": 0}}
36
+ return
37
+ with rt.step("pipeline", f"Analysing {len(insp.dockerfiles)} Dockerfile(s), {len(insp.container_files)} compose/container file(s), {len(insp.ci_files)} CI/CD file(s) (parsed, never executed)") as b:
38
+ res = analyze_repository(st.repo_dir, insp.dockerfiles, insp.container_files, insp.ci_files, st.info.scan_timestamp)
39
+ st.pipe = res
40
+ for f in res["findings"]: # every finding is backed by an evidence record the explanations and policies can cite
41
+ kind = ICON_EVIDENCE.get(f["category"], "pipeline")
42
+ f["evidence_id"] = st.evidence.add(kind, "pipeline-analyzer", f["finding_id"], f"{f['rule_id']}: {f['title']}", {"rule": f["rule_id"], "snippet": f["snippet"], "severity": f["severity"]},
43
+ source=f"{f['file']}:{f['line']}")
44
+ for fi in res["files"]:
45
+ rt.progress("pipeline", f"{fi['type']} {fi['file']}: " + (f"{fi.get('findings', 0)} finding(s)" if fi["status"] == "analysed" else fi["status"]), file=fi["file"])
46
+ sm = res["summary"]
47
+ sev = ", ".join(f"{n} {k}" for k, n in sorted(sm["by_severity"].items(), key=lambda kv: ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"].index(kv[0]))) or "none"
48
+ rt.observe("pipeline", f"{sm['findings']} finding(s) ({sev}); {sm['images']} base image(s) ({sm['images_unpinned']} not digest-pinned); {sm['actions']} CI action(s) ({sm['actions_unpinned']} not pinned to a SHA)")
49
+ # Correlate Dockerfiles, Compose, and CI builds into container assets
50
+ assets = discover_container_assets(st.repo_dir, insp.dockerfiles, insp.container_files, res.get("docker_builds", []))
51
+ res["container_assets"] = [a.__dict__ for a in assets]
52
+
53
+ # Opt-in Trivy container image scanning
54
+ container_vulns: list[dict] = []
55
+ s = getattr(st.ctx, "s", None)
56
+ if s and getattr(s, "container_scan_enabled", False):
57
+ rt.progress("pipeline", f"Opt-in container scanning active: evaluating up to {s.container_scan_max_images} image(s)...")
58
+ for asset in assets[:s.container_scan_max_images]:
59
+ target_ref = asset.image_tag or (f"{asset.base_image}:{asset.base_image_tag}" if asset.base_image and asset.base_image_tag else asset.base_image)
60
+ if not target_ref:
61
+ continue
62
+ findings, meta = scan_container_image(target_ref, asset, s)
63
+ for cf in findings:
64
+ cv = {
65
+ "finding_id": f"VULN-CONT-{len(container_vulns) + 1:03d}",
66
+ "component_ref": f"pkg:docker/{cf.package_name}@{cf.installed_version}",
67
+ "component_refs": [],
68
+ "package_name": cf.package_name,
69
+ "ecosystem": cf.os_distribution or "Container",
70
+ "installed_version": cf.installed_version,
71
+ "purl": f"pkg:docker/{cf.package_name}@{cf.installed_version}",
72
+ "vulnerability_ids": [cf.vuln_id],
73
+ "cve_ids": [cf.vuln_id] if cf.vuln_id.startswith("CVE-") else [],
74
+ "primary_id": cf.vuln_id,
75
+ "summary": cf.title or (cf.description[:200] if cf.description else None),
76
+ "severity": cf.severity,
77
+ "severity_source": "Trivy",
78
+ "cvss_score": cf.cvss_score,
79
+ "affected_status": "confirmed_affected",
80
+ "affected_status_reason": f"Detected in container image {cf.image_tag}",
81
+ "fixed_versions": [cf.fixed_version] if cf.fixed_version else [],
82
+ "recommended_fix": cf.fixed_version,
83
+ "references": [{"url": r, "type": "ADVISORY"} for r in cf.references],
84
+ "advisory_urls": cf.references,
85
+ "dependency_type": "container_package",
86
+ "sources": ["Trivy"],
87
+ "scan_timestamp": st.info.scan_timestamp,
88
+ "asset_type": "container_image",
89
+ "container_details": {
90
+ "image_name": cf.image_tag,
91
+ "source_file": cf.source_file,
92
+ "package_type": cf.package_type,
93
+ "os_distribution": cf.os_distribution,
94
+ "layer_diff_id": cf.layer_diff_id,
95
+ "target": cf.target,
96
+ },
97
+ }
98
+ # complete the record with the model's defaults so every later stage (risk, explain, remediate, export) can rely on the same fields
99
+ from vulnerability.vulnerability_models import VulnerabilityFinding
100
+ cv["service_dir"] = (cf.source_file.rsplit("/", 1)[0] if "/" in (cf.source_file or "") else ".") or "."
101
+ cv["source_packages"] = [cf.image_tag or "image"]
102
+ cv["root_component"] = cf.image_tag or "image"
103
+ cv = VulnerabilityFinding(**cv).model_dump()
104
+ container_vulns.append(cv)
105
+ st.evidence.add("container", "trivy-scanner", cv["finding_id"], f"{cf.vuln_id}: {cf.package_name} ({cf.severity})", cv, source=f"{cf.source_file}:{cf.image_tag}")
106
+
107
+ if container_vulns:
108
+ rt.observe("pipeline", f"Container scanner identified {len(container_vulns)} container vulnerability finding(s)")
109
+ res["container_findings"] = container_vulns
110
+
111
+ crit = [f for f in res["findings"] if f["severity"] == "CRITICAL"]
112
+ if crit:
113
+ rt.decide("pipeline", f"Escalate {len(crit)} critical pipeline finding(s) to risk scoring", reason="; ".join(sorted({f['title'] for f in crit}))[:200], agent="Supervisor")
114
+ self._add_components(st, rt, res)
115
+ b["message"] = f"{sm['findings']} findings, {sm['images']} images, {sm['actions']} actions, {len(assets)} container assets"
116
+
117
+ @staticmethod
118
+ def _add_components(st: ScanState, rt: Runtime, res: dict) -> None:
119
+ """Images and CI actions are part of the supply chain: record them in the inventory and in the SBOM document."""
120
+ have = {c.purl for c in st.components if c.purl}
121
+ entries = st.sbom_doc.setdefault("components", []) if st.sbom_doc else None
122
+ added = 0
123
+ for img in res["images"]:
124
+ purl = _docker_purl(img)
125
+ if purl in have:
126
+ continue
127
+ have.add(purl)
128
+ c = Component(bom_ref=purl, name=img["name"], version=img.get("digest") or img.get("tag") or "latest", type="container", purl=purl, ecosystem=None, purl_type="docker",
129
+ locations=[img["file"]], service_dir=".", found_by="pipeline-analyzer", sources=["pipeline"], source_type="registry",
130
+ provenance={"image_kind": {"source": "inferred:heuristic", "confidence": "medium", "evidence": img["kind"], "conflicts": []}})
131
+ st.components.append(c)
132
+ added += 1
133
+ if entries is not None:
134
+ entries.append({"bom-ref": purl, "type": "container", "name": img["name"], "version": c.version, "purl": purl,
135
+ "properties": [{"name": "sc-guardian:image-kind", "value": img["kind"]}, {"name": "sc-guardian:pinned-by-digest", "value": str(bool(img.get("digest"))).lower()},
136
+ {"name": "sc-guardian:location:0:path", "value": img["file"]}]})
137
+ for a in res["actions"]:
138
+ if a.get("kind") != "action" or not a.get("ref"):
139
+ continue
140
+ purl = _action_purl(a)
141
+ if purl in have:
142
+ continue
143
+ have.add(purl)
144
+ c = Component(bom_ref=purl, name=a["name"], version=a["ref"], type="library", purl=purl, ecosystem=None, purl_type="github", locations=[a["file"]], service_dir=".",
145
+ found_by="pipeline-analyzer", sources=["pipeline"], source_type="git")
146
+ st.components.append(c)
147
+ added += 1
148
+ if entries is not None:
149
+ entries.append({"bom-ref": purl, "type": "library", "name": a["name"], "version": a["ref"], "purl": purl,
150
+ "properties": [{"name": "sc-guardian:pinned-by-sha", "value": str(bool(a.get("pinned"))).lower()}, {"name": "sc-guardian:location:0:path", "value": a["file"]}]})
151
+ if added:
152
+ rt.observe("pipeline", f"{added} container image/CI action component(s) added to the SBOM (type container / pkg:github)")