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,373 @@
1
+ """Interactive graphs: Sigma.js/Graphology WebGL dependency explorer (uncapped) and vis-network agent-workflow graph.
2
+
3
+ Data is JSON-embedded with script-closing sequences escaped. Offline, a clear message replaces the canvas.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import json
8
+
9
+ import streamlit as st
10
+
11
+ VIS_URL = "https://cdnjs.cloudflare.com/ajax/libs/vis-network/9.1.9/standalone/umd/vis-network.min.js"
12
+ GRAPHOLOGY_URL = "https://cdn.jsdelivr.net/npm/graphology@0.25.4/dist/graphology.umd.min.js"
13
+ SIGMA_URL = "https://cdn.jsdelivr.net/npm/sigma@2.4.0/build/sigma.min.js"
14
+
15
+ _CSS = """
16
+ <style>
17
+ *{box-sizing:border-box} body{margin:0;background:#0b1020;color:#cbd5e1;font:12px system-ui,Segoe UI,sans-serif}
18
+ #bar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:8px 10px;border-bottom:1px solid #1e293b;background:#0f172a}
19
+ #bar input[type=text],#bar select{background:#0b1020;color:#e2e8f0;border:1px solid #334155;border-radius:5px;padding:4px 7px;font-size:12px}
20
+ button{background:#0b1020;color:#e2e8f0;border:1px solid #334155;border-radius:5px;padding:4px 9px;font-size:12px;cursor:pointer}
21
+ button.on{background:#2563eb;border-color:#2563eb;color:#fff} button:hover{border-color:#64748b}
22
+ #wrap{position:relative} #net{height:__H__px;width:100%;background:#0b1020} #side{position:absolute;top:8px;right:8px;width:290px;max-height:__H__px;overflow:auto;
23
+ background:#111a2ee6;border:1px solid #334155;border-radius:8px;padding:10px;font-size:12px;line-height:1.45;display:none;z-index:10}
24
+ #foot{display:flex;gap:14px;align-items:center;flex-wrap:wrap;padding:7px 10px;border-top:1px solid #1e293b;background:#0f172a;font-size:11px}
25
+ .dot{display:inline-block;width:10px;height:10px;border-radius:50%;margin-right:4px;vertical-align:-1px}
26
+ .tag{font-size:11px;padding:1px 6px;border-radius:9px;border:1px solid #334155} code{color:#93c5fd}
27
+ .btn-sm{margin-top:6px;padding:3px 8px;font-size:11px;background:#1e293b;border-color:#475569}
28
+ </style>"""
29
+
30
+ _FALLBACK = "if(typeof vis==='undefined'){document.getElementById('net').innerHTML='<p style=\"padding:1rem\">vis-network could not be loaded (offline?). Use the other tabs.</p>';throw new Error('no vis');}"
31
+ _SIGMA_FALLBACK = "if(typeof graphology==='undefined'||typeof Sigma==='undefined'){document.getElementById('net').innerHTML='<p style=\"padding:1rem\">Sigma.js / Graphology WebGL could not be loaded (offline?). Use the Dependency Tree or Download Complete Graph.</p>';throw new Error('no sigma');}"
32
+
33
+ DEP_HTML = _CSS + """
34
+ <div id="bar">
35
+ <input id="q" type="text" placeholder="Global search across ALL packages..." size="26">
36
+ <span>View:</span><span id="filters"></span>
37
+ <span>Budget:</span><input id="lim" type="range" min="1" max="1" value="1" style="width:110px"><b id="limv" style="color:#60a5fa">1</b><span id="limt"></span>
38
+ <span>Layout:</span><select id="lay"><option value="radial">Layered Radial (0ms)</option><option value="tree">Hierarchical Depth</option><option value="force">Force Relaxation</option></select>
39
+ <span style="flex:1"></span><span id="webgl-badge" class="tag" style="color:#34d399;border-color:#059669">WebGL Ready</span><button id="expand-all">Show All Nodes</button><button id="reset">Reset</button>
40
+ </div>
41
+ <div id="wrap"><div id="net"></div><div id="side"></div></div>
42
+ <div id="foot"><span><i class="dot" style="background:#2563eb"></i>Application Root</span><span><i class="dot" style="background:#059669"></i>Production Runtime</span>
43
+ <span><i class="dot" style="background:#d97706"></i>Development Tool</span><span><i class="dot" style="background:#ef4444"></i>Impact / Selected</span>
44
+ <span><i class="dot" style="background:#dc2626"></i>Vulnerable</span><b id="count"></b><span style="color:#64748b">Click: impact &amp; expand · Double-click: lazy-expand children · Scroll: zoom</span></div>
45
+ <script src="__GRAPHOLOGY_URL__"></script>
46
+ <script src="__SIGMA_URL__"></script>
47
+ <script>
48
+ __SIGMA_FALLBACK__
49
+ const D = __DATA__;
50
+ const SEV = {CRITICAL:'#dc2626',HIGH:'#f97316',MEDIUM:'#eab308',LOW:'#38bdf8',UNKNOWN:'#a78bfa'};
51
+ const COL = {root:'#2563eb',prod:'#059669',dev:'#d97706'};
52
+
53
+ // Build complete, uncapped Graphology graph in memory
54
+ const fullGraph = new graphology.DirectedGraph();
55
+ const byId = {};
56
+ const out = {}, inn = {};
57
+ D.nodes.forEach(n => {
58
+ byId[n.id] = n;
59
+ out[n.id] = [];
60
+ inn[n.id] = [];
61
+ const baseSize = n.kind === 'root' ? 11 : Math.min(3 + Math.log2(2 + (n.desc || 0)) * 1.1 + (n.vuln ? 2.5 : 0), 10);
62
+ fullGraph.addNode(n.id, {
63
+ label: n.label + (n.version ? '@' + n.version : ''),
64
+ x: n.x || 0,
65
+ y: n.y || 0,
66
+ origX: n.x || 0,
67
+ origY: n.y || 0,
68
+ size: baseSize,
69
+ color: n.vuln ? SEV[n.vuln] : COL[n.kind],
70
+ hidden: true,
71
+ });
72
+ });
73
+ D.edges.forEach(([u, v]) => {
74
+ if (fullGraph.hasNode(u) && fullGraph.hasNode(v) && !fullGraph.hasEdge(u, v)) {
75
+ fullGraph.addEdge(u, v, { size: (byId[u] && byId[u].kind === 'root') ? 1.4 : 0.7, color: '#334155', hidden: true });
76
+ out[u].push(v);
77
+ inn[v].push(u);
78
+ }
79
+ });
80
+
81
+ const roots = D.nodes.filter(n => n.kind === 'root').map(n => n.id);
82
+ const pkgs = D.nodes.filter(n => n.kind !== 'root');
83
+ const rank = n => (n.vuln ? 1000 + ({CRITICAL:4,HIGH:3,MEDIUM:2,LOW:1}[n.vuln]||0)*100 : 0) + (n.desc||0) + (n.parents||0)*2 + (n.direct ? 5 : 0);
84
+ const ranked = pkgs.slice().sort((a, b) => rank(b) - rank(a));
85
+ const nDirect = pkgs.filter(n => n.direct).length;
86
+ const nVuln = pkgs.filter(n => n.vuln).length;
87
+
88
+ let filter = 'priority';
89
+ let budget = Math.min(Math.max((D.initial_visible || []).length, 1), Math.max(pkgs.length, 1));
90
+ let selected = null;
91
+ let expanded = new Set(D.initial_visible || roots);
92
+ let query = '';
93
+ let layout = 'radial';
94
+ let selSet = new Set(), selEdges = new Set();
95
+
96
+ const FILTERS = [
97
+ ['priority', 'Priority (' + (D.initial_visible || []).length + ')'],
98
+ ['direct', 'Direct (' + nDirect + ')'],
99
+ ['vuln', 'Vulnerable (' + nVuln + ')'],
100
+ ['prod', 'Production'],
101
+ ['all', 'All (' + pkgs.length + ')'],
102
+ ];
103
+ const fb = document.getElementById('filters');
104
+ FILTERS.forEach(([k, t]) => {
105
+ const b = document.createElement('button');
106
+ b.textContent = t;
107
+ b.dataset.k = k;
108
+ b.onclick = () => {
109
+ filter = k;
110
+ if (k === 'all') budget = pkgs.length;
111
+ document.getElementById('lim').value = budget;
112
+ applyVisibility();
113
+ };
114
+ fb.appendChild(b);
115
+ });
116
+
117
+ const lim = document.getElementById('lim');
118
+ lim.max = Math.max(pkgs.length, 1);
119
+ lim.value = budget;
120
+
121
+ function chainToRoot(id, set) {
122
+ let cur = id, guard = 0;
123
+ while (cur && !set.has(cur) && guard++ < 80) {
124
+ set.add(cur);
125
+ const ps = inn[cur];
126
+ if (!ps || !ps.length) break;
127
+ cur = ps.slice().sort((a, b) => (byId[a] ? byId[a].depth : 999) - (byId[b] ? byId[b].depth : 999))[0];
128
+ }
129
+ if (cur) set.add(cur);
130
+ }
131
+
132
+ function computeVisible() {
133
+ const vis = new Set(roots);
134
+ if (query) {
135
+ // Global search across ALL nodes in fullGraph (even if outside current budget)
136
+ ranked.forEach(n => {
137
+ const fullLabel = (n.label + '@' + n.version).toLowerCase();
138
+ if (fullLabel.includes(query)) {
139
+ chainToRoot(n.id, vis);
140
+ (out[n.id] || []).slice(0, 15).forEach(c => vis.add(c));
141
+ }
142
+ });
143
+ return vis;
144
+ }
145
+ if (filter === 'priority') {
146
+ expanded.forEach(id => { if (byId[id]) vis.add(id); });
147
+ return vis;
148
+ }
149
+ let pool = ranked;
150
+ if (filter === 'direct') pool = ranked.filter(n => n.direct);
151
+ else if (filter === 'vuln') pool = ranked.filter(n => n.vuln);
152
+ else if (filter === 'prod') pool = ranked.filter(n => n.kind === 'prod');
153
+ pool.slice(0, budget).forEach(n => chainToRoot(n.id, vis));
154
+ return vis;
155
+ }
156
+
157
+ function applyLayout(mode) {
158
+ layout = mode;
159
+ if (mode === 'radial') {
160
+ fullGraph.forEachNode((id, attr) => {
161
+ fullGraph.setNodeAttribute(id, 'x', attr.origX);
162
+ fullGraph.setNodeAttribute(id, 'y', attr.origY);
163
+ });
164
+ } else if (mode === 'tree') {
165
+ const byD = {};
166
+ D.nodes.forEach(n => { (byD[n.depth || 0] = byD[n.depth || 0] || []).push(n.id); });
167
+ Object.keys(byD).forEach(d => {
168
+ const arr = byD[d];
169
+ const y = -Number(d) * 180;
170
+ arr.forEach((id, i) => {
171
+ const x = (i - (arr.length - 1) / 2) * 90;
172
+ fullGraph.setNodeAttribute(id, 'x', x);
173
+ fullGraph.setNodeAttribute(id, 'y', y);
174
+ });
175
+ });
176
+ } else if (mode === 'force') {
177
+ // Lightweight deterministic spring-repulsion pass over visible nodes (non-blocking)
178
+ const visNodes = fullGraph.nodes().filter(id => !fullGraph.getNodeAttribute(id, 'hidden'));
179
+ const limitPass = visNodes.slice(0, 1200);
180
+ for (let iter = 0; iter < 15; iter++) {
181
+ limitPass.forEach(u => {
182
+ let fx = 0, fy = 0;
183
+ const ux = fullGraph.getNodeAttribute(u, 'x'), uy = fullGraph.getNodeAttribute(u, 'y');
184
+ (out[u] || []).forEach(v => {
185
+ const vx = fullGraph.getNodeAttribute(v, 'x'), vy = fullGraph.getNodeAttribute(v, 'y');
186
+ fx += (vx - ux) * 0.05; fy += (vy - uy) * 0.05;
187
+ });
188
+ (inn[u] || []).forEach(p => {
189
+ const px = fullGraph.getNodeAttribute(p, 'x'), py = fullGraph.getNodeAttribute(p, 'y');
190
+ fx += (px - ux) * 0.05; fy += (py - uy) * 0.05;
191
+ });
192
+ if (byId[u] && byId[u].kind !== 'root') {
193
+ fullGraph.setNodeAttribute(u, 'x', ux + fx);
194
+ fullGraph.setNodeAttribute(u, 'y', uy + fy);
195
+ }
196
+ });
197
+ }
198
+ }
199
+ }
200
+
201
+ const container = document.getElementById('net');
202
+ const renderer = new Sigma(fullGraph, container, {
203
+ renderEdgeLabels: false,
204
+ labelRenderedSizeThreshold: 6,
205
+ labelColor: { color: '#e2e8f0' },
206
+ defaultEdgeType: 'arrow',
207
+ minCameraRatio: 0.02,
208
+ maxCameraRatio: 12,
209
+ });
210
+
211
+ function applyVisibility() {
212
+ const vis = computeVisible();
213
+ fullGraph.forEachNode((id) => {
214
+ const show = vis.has(id);
215
+ fullGraph.setNodeAttribute(id, 'hidden', !show);
216
+ const n = byId[id];
217
+ const isSel = selected && (id === selected || selSet.has(id));
218
+ fullGraph.setNodeAttribute(id, 'color', isSel ? '#ef4444' : (n.vuln ? SEV[n.vuln] : COL[n.kind]));
219
+ });
220
+ fullGraph.forEachEdge((eid, attr, u, v) => {
221
+ const show = vis.has(u) && vis.has(v);
222
+ fullGraph.setEdgeAttribute(eid, 'hidden', !show);
223
+ const hot = selEdges.has(u + '>' + v);
224
+ fullGraph.setEdgeAttribute(eid, 'color', hot ? '#ef4444' : ((byId[u] && byId[u].kind === 'root') ? '#b91c1c' : '#334155'));
225
+ fullGraph.setEdgeAttribute(eid, 'size', hot ? 2.2 : ((byId[u] && byId[u].kind === 'root') ? 1.2 : 0.6));
226
+ });
227
+ const shownPkgs = [...vis].filter(id => byId[id] && byId[id].kind !== 'root').length;
228
+ const shownDir = [...vis].filter(id => byId[id] && byId[id].direct).length;
229
+ document.getElementById('count').textContent =
230
+ 'Showing ' + shownPkgs + ' of ' + D.total + ' packages (' + shownDir + ' direct, ' + (shownPkgs - shownDir) + ' transitive) • 0 truncated';
231
+ document.getElementById('limv').textContent = budget;
232
+ document.getElementById('limt').textContent = '/ ' + pkgs.length;
233
+ [...fb.children].forEach(b => b.className = b.dataset.k === filter ? 'on' : '');
234
+ renderer.refresh();
235
+ }
236
+
237
+ function ancestors(id) {
238
+ const seen = new Set([id]), es = new Set(), st = [id];
239
+ while (st.length) {
240
+ const c = st.pop();
241
+ (inn[c] || []).forEach(p => { es.add(p + '>' + c); if (!seen.has(p)) { seen.add(p); st.push(p); } });
242
+ }
243
+ return [seen, es];
244
+ }
245
+
246
+ function shortestPath(id) {
247
+ let best = null;
248
+ roots.forEach(r => {
249
+ const prev = { [r]: null }, q = [r];
250
+ let head = 0;
251
+ while (head < q.length) {
252
+ const c = q[head++];
253
+ if (c === id) break;
254
+ for (const x of (out[c] || [])) {
255
+ if (!(x in prev)) { prev[x] = c; q.push(x); }
256
+ }
257
+ }
258
+ if (id in prev) {
259
+ const p = [];
260
+ for (let c = id; c; c = prev[c]) p.unshift(byId[c].label);
261
+ if (!best || p.length < best.length) best = p;
262
+ }
263
+ });
264
+ return best || [];
265
+ }
266
+
267
+ function expandNeighbors(id) {
268
+ expanded.add(id);
269
+ (out[id] || []).forEach(c => expanded.add(c));
270
+ (inn[id] || []).forEach(p => expanded.add(p));
271
+ filter = 'priority';
272
+ applyVisibility();
273
+ }
274
+
275
+ function selectNode(id) {
276
+ selected = id;
277
+ const [s, e] = ancestors(id);
278
+ selSet = s; selEdges = e;
279
+ applyVisibility();
280
+ const n = byId[id], side = document.getElementById('side');
281
+ side.style.display = 'block';
282
+ const intro = [...s].filter(x => byId[x] && byId[x].direct && x !== id).map(x => byId[x].label).slice(0, 6);
283
+ const childCount = (out[id] || []).length;
284
+ side.innerHTML = '<b style="font-size:13px">Impact Analysis</b><br><b>' + n.label + '</b>' + (n.version ? '@' + n.version : '') +
285
+ ' <span class="tag">' + (n.kind === 'root' ? 'root' : n.direct ? 'direct' : 'transitive') + '</span> ' +
286
+ '<span class="tag">' + (n.kind === 'dev' ? 'dev' : n.kind === 'prod' ? 'prod' : 'root') + '</span><br>' +
287
+ (n.vuln ? '<span class="tag" style="color:' + SEV[n.vuln] + ';border-color:' + SEV[n.vuln] + '">' + n.vuln + '</span> ' + n.ids.map(i => '<code>' + i + '</code>').join(' ') + (n.fix ? '<br>Fixed in: <b>' + n.fix + '</b>' : '') + '<br>' : '') +
288
+ 'Reached from <b>' + Math.max(s.size - 1, 0) + '</b> ancestor(s)' + (intro.length && !n.direct ? '<br>Introduced via: ' + intro.join(', ') : '') +
289
+ '<br>Blast radius: <b>' + (n.desc || 0) + '</b> package(s) below<br>' +
290
+ 'Direct children: <b>' + childCount + '</b><br>' +
291
+ (childCount > 0 ? '<button class="btn-sm" id="exp-btn">+ Expand ' + childCount + ' Children</button><br>' : '') +
292
+ '<br>Shortest path:<br><code>' + shortestPath(id).join(' → ') + '</code>';
293
+ const eb = document.getElementById('exp-btn');
294
+ if (eb) eb.onclick = () => expandNeighbors(id);
295
+ }
296
+
297
+ renderer.on('clickNode', ({ node }) => selectNode(node));
298
+ renderer.on('doubleClickNode', ({ node }) => { expandNeighbors(node); selectNode(node); });
299
+
300
+ document.getElementById('expand-all').onclick = () => {
301
+ filter = 'all';
302
+ budget = pkgs.length;
303
+ lim.value = budget;
304
+ applyVisibility();
305
+ };
306
+ document.getElementById('reset').onclick = () => {
307
+ selected = null; selSet = new Set(); selEdges = new Set();
308
+ query = ''; document.getElementById('q').value = '';
309
+ document.getElementById('side').style.display = 'none';
310
+ applyVisibility();
311
+ renderer.getCamera().animatedReset();
312
+ };
313
+ document.getElementById('lay').onchange = e => { applyLayout(e.target.value); applyVisibility(); renderer.getCamera().animatedReset(); };
314
+ lim.oninput = e => { budget = +e.target.value; if (filter === 'priority') filter = 'all'; applyVisibility(); };
315
+ document.getElementById('q').oninput = e => {
316
+ query = e.target.value.trim().toLowerCase();
317
+ applyVisibility();
318
+ if (query.length > 1) {
319
+ const m = ranked.find(n => (n.label + '@' + n.version).toLowerCase().includes(query));
320
+ if (m && fullGraph.hasNode(m.id)) {
321
+ const pos = renderer.getNodeDisplayData(m.id);
322
+ if (pos) renderer.getCamera().animate({ x: pos.x, y: pos.y, ratio: 0.3 }, { duration: 300 });
323
+ }
324
+ }
325
+ };
326
+
327
+ applyVisibility();
328
+ </script>"""
329
+
330
+ FLOW_HTML = _CSS + """
331
+ <div id="wrap"><div id="net"></div><div id="side" style="display:block"><b>Click an agent</b><br>to see its role, tools and outputs.</div></div>
332
+ <div id="foot">__LEGEND__<span style="color:#64748b">Arrows show data flow between agents · Detect branches run in parallel and join at Risk · SBOM may run a second pass when quality is low</span></div>
333
+ <script src="__URL__"></script>
334
+ <script>
335
+ __FALLBACK__
336
+ const D = __DATA__;
337
+ const nodes = new vis.DataSet(D.nodes.map(n => ({id:n.id, label:n.label, shape:'box', margin:9, color:{background:D.colors[n.phase], border:'#0b1020'}, font:{color:'#fff', size:13, bold:true}, widthConstraint:{minimum:100}})));
338
+ const edges = new vis.DataSet(D.edges.map(e => ({from:e[0], to:e[1], dashes:!!e[2], arrows:'to', color:{color:'#64748b'}})));
339
+ const net = new vis.Network(document.getElementById('net'), {nodes, edges}, {layout:{hierarchical:{enabled:true, direction:'LR', sortMethod:'directed', levelSeparation:130, nodeSpacing:40}}, physics:false, interaction:{dragNodes:false, hover:true}});
340
+ net.on('click', p => {if (!p.nodes.length) return; const n = D.nodes.find(x => x.id === p.nodes[0]);
341
+ document.getElementById('side').innerHTML = '<b style="font-size:13px">' + n.label + '</b> <span class="tag" style="border-color:' + D.colors[n.phase] + '">' + n.phase + '</span><br>' + n.role +
342
+ (n.steps.length ? '<br><br><b>Steps</b><br>' + n.steps.map(s => '• ' + s).join('<br>') : '') + (n.ai ? '<br><br><span class="tag">can use optional LLM (grounded)</span>' : '') + (n.approval ? '<br><span class="tag">human approval point</span>' : '');});
343
+ net.once('afterDrawing', () => net.fit());
344
+ </script>"""
345
+
346
+
347
+ def _embed(html: str, height: int, alt: str) -> None:
348
+ html = (
349
+ html.replace("__H__", str(height))
350
+ .replace("__URL__", VIS_URL)
351
+ .replace("__GRAPHOLOGY_URL__", GRAPHOLOGY_URL)
352
+ .replace("__SIGMA_URL__", SIGMA_URL)
353
+ .replace("__FALLBACK__", _FALLBACK)
354
+ .replace("__SIGMA_FALLBACK__", _SIGMA_FALLBACK)
355
+ )
356
+ if hasattr(st, "iframe"):
357
+ st.iframe(html, height=height + 90, alt=alt)
358
+ else:
359
+ import streamlit.components.v1 as components
360
+ components.html(html, height=height + 90, scrolling=False)
361
+
362
+
363
+ def _json(obj: dict) -> str:
364
+ return json.dumps(obj).replace("</", "<\\/")
365
+
366
+
367
+ def render_dependency_graph(payload: dict, height: int = 620) -> None:
368
+ _embed(DEP_HTML.replace("__DATA__", _json(payload)), height, "Interactive WebGL dependency graph")
369
+
370
+
371
+ def render_workflow_graph(payload: dict, height: int = 460) -> None:
372
+ legend = "".join(f"<span><i class='dot' style='background:{c}'></i>{p}</span>" for p, c in payload["colors"].items())
373
+ _embed(FLOW_HTML.replace("__LEGEND__", legend).replace("__DATA__", _json(payload)), height, "Agent workflow graph")
File without changes
@@ -0,0 +1,58 @@
1
+ """CVSS v3.x base-score calculation from a vector string (no invented values: returns None when unparseable)."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ from typing import Optional
6
+
7
+ _W = {
8
+ "AV": {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.2},
9
+ "AC": {"L": 0.77, "H": 0.44},
10
+ "UI": {"N": 0.85, "R": 0.62},
11
+ "CIA": {"H": 0.56, "L": 0.22, "N": 0.0},
12
+ }
13
+
14
+
15
+ def _roundup(x: float) -> float:
16
+ i = int(round(x * 100000))
17
+ return i / 100000.0 if i % 10000 == 0 else (math.floor(i / 10000) + 1) / 10.0
18
+
19
+
20
+ def cvss3_base(vector: str) -> Optional[float]:
21
+ try:
22
+ parts = vector.split("/")
23
+ if not parts[0].startswith("CVSS:3"):
24
+ return None
25
+ m = dict(p.split(":") for p in parts[1:])
26
+ scope_changed = m["S"] == "C"
27
+ pr_w = {"N": 0.85, "L": 0.68 if scope_changed else 0.62, "H": 0.5 if scope_changed else 0.27}[m["PR"]]
28
+ iss = 1 - (1 - _W["CIA"][m["C"]]) * (1 - _W["CIA"][m["I"]]) * (1 - _W["CIA"][m["A"]])
29
+ impact = 7.52 * (iss - 0.029) - 3.25 * (iss - 0.02) ** 15 if scope_changed else 6.42 * iss
30
+ expl = 8.22 * _W["AV"][m["AV"]] * _W["AC"][m["AC"]] * pr_w * _W["UI"][m["UI"]]
31
+ if impact <= 0:
32
+ return 0.0
33
+ base = min(1.08 * (impact + expl), 10) if scope_changed else min(impact + expl, 10)
34
+ return _roundup(base)
35
+ except (KeyError, ValueError, IndexError):
36
+ return None
37
+
38
+
39
+ def severity_from_score(score: Optional[float]) -> Optional[str]:
40
+ if score is None:
41
+ return None
42
+ if score >= 9.0:
43
+ return "CRITICAL"
44
+ if score >= 7.0:
45
+ return "HIGH"
46
+ if score >= 4.0:
47
+ return "MEDIUM"
48
+ if score > 0:
49
+ return "LOW"
50
+ return None # CVSS "NONE" -> no severity label
51
+
52
+
53
+ def normalize_label(label: Optional[str]) -> Optional[str]:
54
+ """Map advisory-database severity words to CRITICAL/HIGH/MEDIUM/LOW; unknown words -> None."""
55
+ if not label:
56
+ return None
57
+ m = {"CRITICAL": "CRITICAL", "HIGH": "HIGH", "MODERATE": "MEDIUM", "MEDIUM": "MEDIUM", "LOW": "LOW"}
58
+ return m.get(str(label).strip().upper())
@@ -0,0 +1,47 @@
1
+ """CISA Known Exploited Vulnerabilities catalog (exploitation-prioritisation signal only)."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any
5
+
6
+ from core.http import HttpClient, SourceUnavailable
7
+ from storage.cache import Cache
8
+
9
+ URL = "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"
10
+ TTL = 24 * 3600
11
+
12
+
13
+ class KevClient:
14
+ def __init__(self, http: HttpClient, cache: Cache | None = None):
15
+ self.http, self.cache = http, cache
16
+ self.status: dict[str, Any] = {"source": "CISA KEV", "state": "not_queried", "entries": 0, "catalog_version": None}
17
+ self._index: dict[str, dict] | None = None
18
+
19
+ def load(self) -> dict[str, dict]:
20
+ if self._index is not None:
21
+ return self._index
22
+ data = self.cache.get("kev", "catalog", ttl=TTL) if self.cache else None
23
+ if data is None:
24
+ try:
25
+ data = self.http.get_json(URL)
26
+ if self.cache:
27
+ self.cache.set("kev", "catalog", data)
28
+ except SourceUnavailable as e:
29
+ stale = self.cache.get("kev", "catalog", allow_stale=True) if self.cache else None
30
+ if stale is None:
31
+ self.status.update(state="unavailable", error=str(e)[:200])
32
+ self._index = {}
33
+ return self._index
34
+ data = stale
35
+ self.status["state"] = "stale_cache"
36
+ if self.status["state"] == "not_queried":
37
+ self.status["state"] = "ok"
38
+ self._index = {v["cveID"]: {"date_added": v.get("dateAdded"), "due_date": v.get("dueDate"),
39
+ "required_action": v.get("requiredAction"), "ransomware_use": v.get("knownRansomwareCampaignUse"),
40
+ "vendor": v.get("vendorProject"), "product": v.get("product")}
41
+ for v in data.get("vulnerabilities", []) if v.get("cveID")}
42
+ self.status["entries"] = len(self._index)
43
+ self.status["catalog_version"] = data.get("catalogVersion")
44
+ return self._index
45
+
46
+ def lookup(self, cve_id: str) -> dict | None:
47
+ return self.load().get(cve_id)
@@ -0,0 +1,74 @@
1
+ """NVD CVE API 2.0 enrichment (optional API key via NVD_API_KEY). Rate-limit aware, cached, never required."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+ from typing import Any, Optional
6
+
7
+ from core.http import HttpClient, NotFound, SourceUnavailable
8
+ from core.safe_env import LIMITER
9
+ from storage.cache import Cache
10
+
11
+ URL = "https://services.nvd.nist.gov/rest/json/cves/2.0"
12
+ TTL = 7 * 24 * 3600
13
+
14
+
15
+ def parse_cve(item: dict) -> dict[str, Any]:
16
+ cve = item.get("cve", item)
17
+ out: dict[str, Any] = {"cve_id": cve.get("id"), "description": None, "cvss": [], "references": [],
18
+ "published": cve.get("published"), "modified": cve.get("lastModified")}
19
+ for d in cve.get("descriptions", []) or []:
20
+ if d.get("lang") == "en":
21
+ out["description"] = d.get("value")
22
+ break
23
+ metrics = cve.get("metrics", {}) or {}
24
+ for key, ver in (("cvssMetricV40", "4.0"), ("cvssMetricV31", "3.1"), ("cvssMetricV30", "3.0"), ("cvssMetricV2", "2.0")):
25
+ for m in metrics.get(key, []) or []:
26
+ data = m.get("cvssData", {})
27
+ score = data.get("baseScore")
28
+ if score is None:
29
+ continue
30
+ out["cvss"].append({"version": data.get("version", ver), "score": float(score), "vector": data.get("vectorString"),
31
+ "severity": (data.get("baseSeverity") or m.get("baseSeverity") or "").upper() or None,
32
+ "source": m.get("source"), "type": m.get("type")})
33
+ out["references"] = [{"url": r.get("url"), "type": ",".join(r.get("tags", []) or [])} for r in (cve.get("references") or [])[:15] if r.get("url")]
34
+ return out
35
+
36
+
37
+ class NvdClient:
38
+ def __init__(self, http: HttpClient, cache: Cache | None = None, api_key: str | None = None):
39
+ self.http, self.cache, self.api_key = http, cache, api_key
40
+ self.delay = 0.7 if api_key else 6.5 # 50 req/30s with key, 5 req/30s without
41
+ self.status: dict[str, Any] = {"source": "NVD", "state": "not_queried", "requested": 0, "from_cache": 0, "enriched": 0,
42
+ "not_found": 0, "unavailable": 0, "skipped_over_cap": 0, "api_key_configured": bool(api_key)}
43
+
44
+ def get_cve(self, cve_id: str) -> Optional[dict]:
45
+ hit = self.cache.get("nvd_cve", cve_id, ttl=TTL) if self.cache else None
46
+ if hit is not None:
47
+ self.status["from_cache"] += 1
48
+ if self.status["state"] == "not_queried":
49
+ self.status["state"] = "ok"
50
+ return hit or None
51
+ LIMITER.wait("nvd", self.delay) # process-wide: concurrent scans share NVD's rate limit
52
+ self.status["requested"] += 1
53
+ try:
54
+ headers = {"apiKey": self.api_key} if self.api_key else None
55
+ data = self.http.get_json(f"{URL}?cveId={cve_id}", headers=headers)
56
+ except NotFound:
57
+ self.status["not_found"] += 1
58
+ return None
59
+ except SourceUnavailable:
60
+ self.status["unavailable"] += 1
61
+ self.status["state"] = "partial"
62
+ return None
63
+ if self.status["state"] == "not_queried":
64
+ self.status["state"] = "ok"
65
+ vulns = data.get("vulnerabilities") or []
66
+ if not vulns:
67
+ self.status["not_found"] += 1
68
+ if self.cache:
69
+ self.cache.set("nvd_cve", cve_id, {})
70
+ return None
71
+ parsed = parse_cve(vulns[0])
72
+ if self.cache:
73
+ self.cache.set("nvd_cve", cve_id, parsed)
74
+ return parsed