euparliamentmonitor 0.8.4
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.
- package/LICENSE +201 -0
- package/README.md +1005 -0
- package/SECURITY.md +151 -0
- package/package.json +131 -0
- package/scripts/constants/committee-indicator-map.d.ts +199 -0
- package/scripts/constants/committee-indicator-map.d.ts.map +1 -0
- package/scripts/constants/committee-indicator-map.js +1224 -0
- package/scripts/constants/committee-indicator-map.js.map +1 -0
- package/scripts/constants/config.d.ts +38 -0
- package/scripts/constants/config.d.ts.map +1 -0
- package/scripts/constants/config.js +66 -0
- package/scripts/constants/config.js.map +1 -0
- package/scripts/constants/language-articles.d.ts +84 -0
- package/scripts/constants/language-articles.d.ts.map +1 -0
- package/scripts/constants/language-articles.js +6771 -0
- package/scripts/constants/language-articles.js.map +1 -0
- package/scripts/constants/language-core.d.ts +38 -0
- package/scripts/constants/language-core.d.ts.map +1 -0
- package/scripts/constants/language-core.js +90 -0
- package/scripts/constants/language-core.js.map +1 -0
- package/scripts/constants/language-ui.d.ts +82 -0
- package/scripts/constants/language-ui.d.ts.map +1 -0
- package/scripts/constants/language-ui.js +889 -0
- package/scripts/constants/language-ui.js.map +1 -0
- package/scripts/constants/languages.d.ts +14 -0
- package/scripts/constants/languages.d.ts.map +1 -0
- package/scripts/constants/languages.js +15 -0
- package/scripts/constants/languages.js.map +1 -0
- package/scripts/generators/analysis-builders.d.ts +266 -0
- package/scripts/generators/analysis-builders.d.ts.map +1 -0
- package/scripts/generators/analysis-builders.js +2903 -0
- package/scripts/generators/analysis-builders.js.map +1 -0
- package/scripts/generators/breaking-content.d.ts +45 -0
- package/scripts/generators/breaking-content.d.ts.map +1 -0
- package/scripts/generators/breaking-content.js +530 -0
- package/scripts/generators/breaking-content.js.map +1 -0
- package/scripts/generators/committee-helpers.d.ts +54 -0
- package/scripts/generators/committee-helpers.d.ts.map +1 -0
- package/scripts/generators/committee-helpers.js +154 -0
- package/scripts/generators/committee-helpers.js.map +1 -0
- package/scripts/generators/dashboard-content.d.ts +95 -0
- package/scripts/generators/dashboard-content.d.ts.map +1 -0
- package/scripts/generators/dashboard-content.js +630 -0
- package/scripts/generators/dashboard-content.js.map +1 -0
- package/scripts/generators/deep-analysis-content.d.ts +23 -0
- package/scripts/generators/deep-analysis-content.d.ts.map +1 -0
- package/scripts/generators/deep-analysis-content.js +831 -0
- package/scripts/generators/deep-analysis-content.js.map +1 -0
- package/scripts/generators/mindmap-content.d.ts +55 -0
- package/scripts/generators/mindmap-content.d.ts.map +1 -0
- package/scripts/generators/mindmap-content.js +512 -0
- package/scripts/generators/mindmap-content.js.map +1 -0
- package/scripts/generators/motions-content.d.ts +50 -0
- package/scripts/generators/motions-content.d.ts.map +1 -0
- package/scripts/generators/motions-content.js +391 -0
- package/scripts/generators/motions-content.js.map +1 -0
- package/scripts/generators/news-enhanced.d.ts +14 -0
- package/scripts/generators/news-enhanced.d.ts.map +1 -0
- package/scripts/generators/news-enhanced.js +169 -0
- package/scripts/generators/news-enhanced.js.map +1 -0
- package/scripts/generators/news-indexes.d.ts +31 -0
- package/scripts/generators/news-indexes.d.ts.map +1 -0
- package/scripts/generators/news-indexes.js +410 -0
- package/scripts/generators/news-indexes.js.map +1 -0
- package/scripts/generators/pipeline/fetch-stage.d.ts +352 -0
- package/scripts/generators/pipeline/fetch-stage.d.ts.map +1 -0
- package/scripts/generators/pipeline/fetch-stage.js +1522 -0
- package/scripts/generators/pipeline/fetch-stage.js.map +1 -0
- package/scripts/generators/pipeline/generate-stage.d.ts +43 -0
- package/scripts/generators/pipeline/generate-stage.d.ts.map +1 -0
- package/scripts/generators/pipeline/generate-stage.js +204 -0
- package/scripts/generators/pipeline/generate-stage.js.map +1 -0
- package/scripts/generators/pipeline/output-stage.d.ts +48 -0
- package/scripts/generators/pipeline/output-stage.d.ts.map +1 -0
- package/scripts/generators/pipeline/output-stage.js +145 -0
- package/scripts/generators/pipeline/output-stage.js.map +1 -0
- package/scripts/generators/pipeline/transform-stage.d.ts +57 -0
- package/scripts/generators/pipeline/transform-stage.d.ts.map +1 -0
- package/scripts/generators/pipeline/transform-stage.js +111 -0
- package/scripts/generators/pipeline/transform-stage.js.map +1 -0
- package/scripts/generators/propositions-content.d.ts +29 -0
- package/scripts/generators/propositions-content.d.ts.map +1 -0
- package/scripts/generators/propositions-content.js +90 -0
- package/scripts/generators/propositions-content.js.map +1 -0
- package/scripts/generators/sankey-content.d.ts +45 -0
- package/scripts/generators/sankey-content.d.ts.map +1 -0
- package/scripts/generators/sankey-content.js +227 -0
- package/scripts/generators/sankey-content.js.map +1 -0
- package/scripts/generators/sitemap.d.ts +66 -0
- package/scripts/generators/sitemap.d.ts.map +1 -0
- package/scripts/generators/sitemap.js +562 -0
- package/scripts/generators/sitemap.js.map +1 -0
- package/scripts/generators/strategies/article-strategy.d.ts +146 -0
- package/scripts/generators/strategies/article-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/article-strategy.js +4 -0
- package/scripts/generators/strategies/article-strategy.js.map +1 -0
- package/scripts/generators/strategies/breaking-news-strategy.d.ts +64 -0
- package/scripts/generators/strategies/breaking-news-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/breaking-news-strategy.js +246 -0
- package/scripts/generators/strategies/breaking-news-strategy.js.map +1 -0
- package/scripts/generators/strategies/committee-reports-strategy.d.ts +93 -0
- package/scripts/generators/strategies/committee-reports-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/committee-reports-strategy.js +447 -0
- package/scripts/generators/strategies/committee-reports-strategy.js.map +1 -0
- package/scripts/generators/strategies/month-ahead-strategy.d.ts +60 -0
- package/scripts/generators/strategies/month-ahead-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/month-ahead-strategy.js +175 -0
- package/scripts/generators/strategies/month-ahead-strategy.js.map +1 -0
- package/scripts/generators/strategies/monthly-review-strategy.d.ts +66 -0
- package/scripts/generators/strategies/monthly-review-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/monthly-review-strategy.js +204 -0
- package/scripts/generators/strategies/monthly-review-strategy.js.map +1 -0
- package/scripts/generators/strategies/motions-strategy.d.ts +61 -0
- package/scripts/generators/strategies/motions-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/motions-strategy.js +215 -0
- package/scripts/generators/strategies/motions-strategy.js.map +1 -0
- package/scripts/generators/strategies/propositions-strategy.d.ts +60 -0
- package/scripts/generators/strategies/propositions-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/propositions-strategy.js +257 -0
- package/scripts/generators/strategies/propositions-strategy.js.map +1 -0
- package/scripts/generators/strategies/week-ahead-strategy.d.ts +57 -0
- package/scripts/generators/strategies/week-ahead-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/week-ahead-strategy.js +178 -0
- package/scripts/generators/strategies/week-ahead-strategy.js.map +1 -0
- package/scripts/generators/strategies/weekly-review-strategy.d.ts +63 -0
- package/scripts/generators/strategies/weekly-review-strategy.d.ts.map +1 -0
- package/scripts/generators/strategies/weekly-review-strategy.js +211 -0
- package/scripts/generators/strategies/weekly-review-strategy.js.map +1 -0
- package/scripts/generators/swot-content.d.ts +42 -0
- package/scripts/generators/swot-content.d.ts.map +1 -0
- package/scripts/generators/swot-content.js +366 -0
- package/scripts/generators/swot-content.js.map +1 -0
- package/scripts/generators/week-ahead-content.d.ts +103 -0
- package/scripts/generators/week-ahead-content.d.ts.map +1 -0
- package/scripts/generators/week-ahead-content.js +610 -0
- package/scripts/generators/week-ahead-content.js.map +1 -0
- package/scripts/index.d.ts +40 -0
- package/scripts/index.d.ts.map +1 -0
- package/scripts/index.js +53 -0
- package/scripts/index.js.map +1 -0
- package/scripts/mcp/ep-mcp-client.d.ts +471 -0
- package/scripts/mcp/ep-mcp-client.d.ts.map +1 -0
- package/scripts/mcp/ep-mcp-client.js +734 -0
- package/scripts/mcp/ep-mcp-client.js.map +1 -0
- package/scripts/mcp/mcp-connection.d.ts +264 -0
- package/scripts/mcp/mcp-connection.d.ts.map +1 -0
- package/scripts/mcp/mcp-connection.js +790 -0
- package/scripts/mcp/mcp-connection.js.map +1 -0
- package/scripts/mcp/mcp-health.d.ts +75 -0
- package/scripts/mcp/mcp-health.d.ts.map +1 -0
- package/scripts/mcp/mcp-health.js +78 -0
- package/scripts/mcp/mcp-health.js.map +1 -0
- package/scripts/mcp/mcp-retry.d.ts +94 -0
- package/scripts/mcp/mcp-retry.d.ts.map +1 -0
- package/scripts/mcp/mcp-retry.js +127 -0
- package/scripts/mcp/mcp-retry.js.map +1 -0
- package/scripts/mcp/wb-mcp-client.d.ts +38 -0
- package/scripts/mcp/wb-mcp-client.d.ts.map +1 -0
- package/scripts/mcp/wb-mcp-client.js +112 -0
- package/scripts/mcp/wb-mcp-client.js.map +1 -0
- package/scripts/templates/article-template.d.ts +9 -0
- package/scripts/templates/article-template.d.ts.map +1 -0
- package/scripts/templates/article-template.js +378 -0
- package/scripts/templates/article-template.js.map +1 -0
- package/scripts/templates/section-builders.d.ts +28 -0
- package/scripts/templates/section-builders.d.ts.map +1 -0
- package/scripts/templates/section-builders.js +142 -0
- package/scripts/templates/section-builders.js.map +1 -0
- package/scripts/types/analysis.d.ts +115 -0
- package/scripts/types/analysis.d.ts.map +1 -0
- package/scripts/types/analysis.js +4 -0
- package/scripts/types/analysis.js.map +1 -0
- package/scripts/types/common.d.ts +584 -0
- package/scripts/types/common.d.ts.map +1 -0
- package/scripts/types/common.js +96 -0
- package/scripts/types/common.js.map +1 -0
- package/scripts/types/generation.d.ts +104 -0
- package/scripts/types/generation.d.ts.map +1 -0
- package/scripts/types/generation.js +4 -0
- package/scripts/types/generation.js.map +1 -0
- package/scripts/types/index.d.ts +24 -0
- package/scripts/types/index.d.ts.map +1 -0
- package/scripts/types/index.js +16 -0
- package/scripts/types/index.js.map +1 -0
- package/scripts/types/intelligence.d.ts +129 -0
- package/scripts/types/intelligence.d.ts.map +1 -0
- package/scripts/types/intelligence.js +4 -0
- package/scripts/types/intelligence.js.map +1 -0
- package/scripts/types/mcp.d.ts +418 -0
- package/scripts/types/mcp.d.ts.map +1 -0
- package/scripts/types/mcp.js +4 -0
- package/scripts/types/mcp.js.map +1 -0
- package/scripts/types/parliament.d.ts +388 -0
- package/scripts/types/parliament.d.ts.map +1 -0
- package/scripts/types/parliament.js +4 -0
- package/scripts/types/parliament.js.map +1 -0
- package/scripts/types/quality.d.ts +114 -0
- package/scripts/types/quality.d.ts.map +1 -0
- package/scripts/types/quality.js +4 -0
- package/scripts/types/quality.js.map +1 -0
- package/scripts/types/stakeholder.d.ts +88 -0
- package/scripts/types/stakeholder.d.ts.map +1 -0
- package/scripts/types/stakeholder.js +16 -0
- package/scripts/types/stakeholder.js.map +1 -0
- package/scripts/types/visualization.d.ts +708 -0
- package/scripts/types/visualization.d.ts.map +1 -0
- package/scripts/types/visualization.js +4 -0
- package/scripts/types/visualization.js.map +1 -0
- package/scripts/types/world-bank.d.ts +85 -0
- package/scripts/types/world-bank.d.ts.map +1 -0
- package/scripts/types/world-bank.js +4 -0
- package/scripts/types/world-bank.js.map +1 -0
- package/scripts/utils/article-category.d.ts +18 -0
- package/scripts/utils/article-category.d.ts.map +1 -0
- package/scripts/utils/article-category.js +49 -0
- package/scripts/utils/article-category.js.map +1 -0
- package/scripts/utils/article-quality-scorer.d.ts +87 -0
- package/scripts/utils/article-quality-scorer.d.ts.map +1 -0
- package/scripts/utils/article-quality-scorer.js +1048 -0
- package/scripts/utils/article-quality-scorer.js.map +1 -0
- package/scripts/utils/content-metadata.d.ts +34 -0
- package/scripts/utils/content-metadata.d.ts.map +1 -0
- package/scripts/utils/content-metadata.js +249 -0
- package/scripts/utils/content-metadata.js.map +1 -0
- package/scripts/utils/content-validator.d.ts +94 -0
- package/scripts/utils/content-validator.d.ts.map +1 -0
- package/scripts/utils/content-validator.js +489 -0
- package/scripts/utils/content-validator.js.map +1 -0
- package/scripts/utils/copy-test-reports.d.ts +9 -0
- package/scripts/utils/copy-test-reports.d.ts.map +1 -0
- package/scripts/utils/copy-test-reports.js +508 -0
- package/scripts/utils/copy-test-reports.js.map +1 -0
- package/scripts/utils/file-utils.d.ts +144 -0
- package/scripts/utils/file-utils.d.ts.map +1 -0
- package/scripts/utils/file-utils.js +374 -0
- package/scripts/utils/file-utils.js.map +1 -0
- package/scripts/utils/fix-articles.d.ts +27 -0
- package/scripts/utils/fix-articles.d.ts.map +1 -0
- package/scripts/utils/fix-articles.js +510 -0
- package/scripts/utils/fix-articles.js.map +1 -0
- package/scripts/utils/generate-docs-index.d.ts +8 -0
- package/scripts/utils/generate-docs-index.d.ts.map +1 -0
- package/scripts/utils/generate-docs-index.js +275 -0
- package/scripts/utils/generate-docs-index.js.map +1 -0
- package/scripts/utils/html-sanitize.d.ts +18 -0
- package/scripts/utils/html-sanitize.d.ts.map +1 -0
- package/scripts/utils/html-sanitize.js +57 -0
- package/scripts/utils/html-sanitize.js.map +1 -0
- package/scripts/utils/intelligence-analysis.d.ts +173 -0
- package/scripts/utils/intelligence-analysis.d.ts.map +1 -0
- package/scripts/utils/intelligence-analysis.js +936 -0
- package/scripts/utils/intelligence-analysis.js.map +1 -0
- package/scripts/utils/intelligence-index.d.ts +126 -0
- package/scripts/utils/intelligence-index.d.ts.map +1 -0
- package/scripts/utils/intelligence-index.js +731 -0
- package/scripts/utils/intelligence-index.js.map +1 -0
- package/scripts/utils/metadata-utils.d.ts +14 -0
- package/scripts/utils/metadata-utils.d.ts.map +1 -0
- package/scripts/utils/metadata-utils.js +18 -0
- package/scripts/utils/metadata-utils.js.map +1 -0
- package/scripts/utils/news-metadata.d.ts +47 -0
- package/scripts/utils/news-metadata.d.ts.map +1 -0
- package/scripts/utils/news-metadata.js +259 -0
- package/scripts/utils/news-metadata.js.map +1 -0
- package/scripts/utils/validate-articles.d.ts +2 -0
- package/scripts/utils/validate-articles.d.ts.map +1 -0
- package/scripts/utils/validate-articles.js +284 -0
- package/scripts/utils/validate-articles.js.map +1 -0
- package/scripts/utils/validate-ep-api.d.ts +51 -0
- package/scripts/utils/validate-ep-api.d.ts.map +1 -0
- package/scripts/utils/validate-ep-api.js +160 -0
- package/scripts/utils/validate-ep-api.js.map +1 -0
- package/scripts/utils/world-bank-data.d.ts +84 -0
- package/scripts/utils/world-bank-data.d.ts.map +1 -0
- package/scripts/utils/world-bank-data.js +311 -0
- package/scripts/utils/world-bank-data.js.map +1 -0
|
@@ -0,0 +1,936 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
/**
|
|
4
|
+
* @module Utils/IntelligenceAnalysis
|
|
5
|
+
* @description Pure intelligence analysis utility functions for structured
|
|
6
|
+
* assessment of European Parliament data. All functions are stateless and
|
|
7
|
+
* safely handle malformed or missing MCP data. No side effects.
|
|
8
|
+
*/
|
|
9
|
+
import { escapeHTML } from './file-utils.js';
|
|
10
|
+
import { ALL_STAKEHOLDER_TYPES } from '../types/index.js';
|
|
11
|
+
// ─── Validation constants ─────────────────────────────────────────────────────
|
|
12
|
+
/** Valid significance levels in descending priority order */
|
|
13
|
+
const SIGNIFICANCE_LEVELS = ['critical', 'high', 'medium', 'low'];
|
|
14
|
+
/** Valid risk levels for coalition and bottleneck assessment */
|
|
15
|
+
const RISK_LEVELS = ['high', 'medium', 'low'];
|
|
16
|
+
/** Valid alignment trend values */
|
|
17
|
+
const ALIGNMENT_TRENDS = ['strengthening', 'weakening', 'stable'];
|
|
18
|
+
/** Priority weights for significance-based ranking */
|
|
19
|
+
const SIGNIFICANCE_WEIGHTS = {
|
|
20
|
+
critical: 4,
|
|
21
|
+
high: 3,
|
|
22
|
+
medium: 2,
|
|
23
|
+
low: 1,
|
|
24
|
+
};
|
|
25
|
+
// ─── Private value-extraction helpers ────────────────────────────────────────
|
|
26
|
+
/**
|
|
27
|
+
* Safely extract a string from an unknown field value
|
|
28
|
+
*
|
|
29
|
+
* @param val - Unknown value to coerce
|
|
30
|
+
* @returns The string value or empty string if not a string
|
|
31
|
+
*/
|
|
32
|
+
function asStr(val) {
|
|
33
|
+
return typeof val === 'string' ? val : '';
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Safely extract a finite number from an unknown field value
|
|
37
|
+
*
|
|
38
|
+
* @param val - Unknown value to coerce
|
|
39
|
+
* @param fallback - Value returned when input is not a finite number
|
|
40
|
+
* @returns Finite number or fallback
|
|
41
|
+
*/
|
|
42
|
+
function asNum(val, fallback = 0) {
|
|
43
|
+
return typeof val === 'number' && Number.isFinite(val) ? val : fallback;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Safely extract an array of strings from an unknown field value
|
|
47
|
+
*
|
|
48
|
+
* @param val - Unknown value to coerce
|
|
49
|
+
* @returns Array of strings (empty array if input is not an array)
|
|
50
|
+
*/
|
|
51
|
+
function asStrArr(val) {
|
|
52
|
+
if (!Array.isArray(val))
|
|
53
|
+
return [];
|
|
54
|
+
return val.filter((v) => typeof v === 'string');
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Coerce an unknown value to a non-null Record or return null
|
|
58
|
+
*
|
|
59
|
+
* @param input - Value to cast
|
|
60
|
+
* @returns Record or null for null/undefined/non-object input
|
|
61
|
+
*/
|
|
62
|
+
function toRecord(input) {
|
|
63
|
+
if (input === null || input === undefined || typeof input !== 'object')
|
|
64
|
+
return null;
|
|
65
|
+
return input;
|
|
66
|
+
}
|
|
67
|
+
// ─── Private parsing validators ───────────────────────────────────────────────
|
|
68
|
+
/**
|
|
69
|
+
* Validate and normalise a raw significance level string
|
|
70
|
+
*
|
|
71
|
+
* @param raw - Raw string from MCP data
|
|
72
|
+
* @returns Validated SignificanceLevel, defaulting to 'low'
|
|
73
|
+
*/
|
|
74
|
+
function parseSignificance(raw) {
|
|
75
|
+
const lower = raw.toLowerCase();
|
|
76
|
+
return SIGNIFICANCE_LEVELS.includes(lower) ? lower : 'low';
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Validate and normalise a raw risk level string
|
|
80
|
+
*
|
|
81
|
+
* @param raw - Raw string from MCP data
|
|
82
|
+
* @returns Validated RiskLevel, defaulting to 'medium'
|
|
83
|
+
*/
|
|
84
|
+
function parseRiskLevel(raw) {
|
|
85
|
+
const lower = raw.toLowerCase();
|
|
86
|
+
return RISK_LEVELS.includes(lower) ? lower : 'medium';
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Validate and normalise a raw alignment trend string
|
|
90
|
+
*
|
|
91
|
+
* @param raw - Raw string from MCP data
|
|
92
|
+
* @returns Validated AlignmentTrend, defaulting to 'stable'
|
|
93
|
+
*/
|
|
94
|
+
function parseAlignmentTrend(raw) {
|
|
95
|
+
const lower = raw.toLowerCase();
|
|
96
|
+
return ALIGNMENT_TRENDS.includes(lower) ? lower : 'stable';
|
|
97
|
+
}
|
|
98
|
+
// ─── Exported intelligence functions ─────────────────────────────────────────
|
|
99
|
+
/**
|
|
100
|
+
* Parse and score a voting anomaly from raw MCP data.
|
|
101
|
+
* Returns null for null, undefined, non-object, or inputs missing a valid
|
|
102
|
+
* anomaly identifier.
|
|
103
|
+
*
|
|
104
|
+
* @param rawAnomaly - Raw MCP anomaly data (unknown shape)
|
|
105
|
+
* @returns Structured VotingAnomalyIntelligence or null if input is invalid
|
|
106
|
+
*/
|
|
107
|
+
export function scoreVotingAnomaly(rawAnomaly) {
|
|
108
|
+
const a = toRecord(rawAnomaly);
|
|
109
|
+
if (!a)
|
|
110
|
+
return null;
|
|
111
|
+
const anomalyId = asStr(a['anomalyId']) || asStr(a['id']);
|
|
112
|
+
if (!anomalyId)
|
|
113
|
+
return null;
|
|
114
|
+
return {
|
|
115
|
+
anomalyId,
|
|
116
|
+
significance: parseSignificance(asStr(a['significance'])),
|
|
117
|
+
description: asStr(a['description']),
|
|
118
|
+
affectedGroups: asStrArr(a['affectedGroups']),
|
|
119
|
+
deviationPercentage: asNum(a['deviationPercentage']),
|
|
120
|
+
historicalContext: asStr(a['historicalContext']),
|
|
121
|
+
implication: asStr(a['implication']),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Analyse a coalition's cohesion from raw MCP coalition data.
|
|
126
|
+
* Returns null for null, undefined, non-object, or inputs missing a valid
|
|
127
|
+
* coalition identifier.
|
|
128
|
+
*
|
|
129
|
+
* @param rawCoalition - Raw MCP coalition data (unknown shape)
|
|
130
|
+
* @returns Structured CoalitionIntelligence or null if input is invalid
|
|
131
|
+
*/
|
|
132
|
+
export function analyzeCoalitionCohesion(rawCoalition) {
|
|
133
|
+
const c = toRecord(rawCoalition);
|
|
134
|
+
if (!c)
|
|
135
|
+
return null;
|
|
136
|
+
const coalitionId = asStr(c['coalitionId']) || asStr(c['id']);
|
|
137
|
+
if (!coalitionId)
|
|
138
|
+
return null;
|
|
139
|
+
return {
|
|
140
|
+
coalitionId,
|
|
141
|
+
groups: asStrArr(c['groups']),
|
|
142
|
+
cohesionScore: Math.min(1, Math.max(0, asNum(c['cohesionScore']))),
|
|
143
|
+
alignmentTrend: parseAlignmentTrend(asStr(c['alignmentTrend'])),
|
|
144
|
+
keyVotes: Math.max(0, Math.round(asNum(c['keyVotes']))),
|
|
145
|
+
riskLevel: parseRiskLevel(asStr(c['riskLevel'])),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Extract and score MEP influence from raw MCP influence data.
|
|
150
|
+
* Returns null for null, undefined, non-object, or inputs missing both a
|
|
151
|
+
* valid MEP identifier and display name.
|
|
152
|
+
*
|
|
153
|
+
* @param rawInfluence - Raw MCP MEP influence data (unknown shape)
|
|
154
|
+
* @returns Structured MEPInfluenceScore or null if input is invalid
|
|
155
|
+
*/
|
|
156
|
+
export function scoreMEPInfluence(rawInfluence) {
|
|
157
|
+
const m = toRecord(rawInfluence);
|
|
158
|
+
if (!m)
|
|
159
|
+
return null;
|
|
160
|
+
const mepId = asStr(m['mepId']) || asStr(m['id']);
|
|
161
|
+
const mepName = asStr(m['mepName']) || asStr(m['name']);
|
|
162
|
+
if (!mepId || !mepName)
|
|
163
|
+
return null;
|
|
164
|
+
return {
|
|
165
|
+
mepId,
|
|
166
|
+
mepName,
|
|
167
|
+
overallScore: Math.min(100, Math.max(0, asNum(m['overallScore']))),
|
|
168
|
+
votingActivity: Math.min(100, Math.max(0, asNum(m['votingActivity']))),
|
|
169
|
+
legislativeOutput: Math.min(100, Math.max(0, asNum(m['legislativeOutput']))),
|
|
170
|
+
committeeEngagement: Math.min(100, Math.max(0, asNum(m['committeeEngagement']))),
|
|
171
|
+
rank: asStr(m['rank']),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Calculate legislative velocity from raw MCP procedure data.
|
|
176
|
+
* Returns null for null, undefined, non-object, or inputs missing a valid
|
|
177
|
+
* procedure identifier or title.
|
|
178
|
+
*
|
|
179
|
+
* @param rawProcedure - Raw MCP procedure data (unknown shape)
|
|
180
|
+
* @returns Structured LegislativeVelocity or null if input is invalid
|
|
181
|
+
*/
|
|
182
|
+
export function calculateLegislativeVelocity(rawProcedure) {
|
|
183
|
+
const p = toRecord(rawProcedure);
|
|
184
|
+
if (!p)
|
|
185
|
+
return null;
|
|
186
|
+
const procedureId = asStr(p['procedureId']) || asStr(p['id']);
|
|
187
|
+
const title = asStr(p['title']);
|
|
188
|
+
if (!procedureId || !title)
|
|
189
|
+
return null;
|
|
190
|
+
return {
|
|
191
|
+
procedureId,
|
|
192
|
+
title,
|
|
193
|
+
stage: asStr(p['stage']) || 'Unknown',
|
|
194
|
+
daysInCurrentStage: Math.max(0, Math.round(asNum(p['daysInCurrentStage']))),
|
|
195
|
+
velocityScore: Math.min(1, Math.max(0, asNum(p['velocityScore']))),
|
|
196
|
+
bottleneckRisk: parseRiskLevel(asStr(p['bottleneckRisk'])),
|
|
197
|
+
predictedCompletion: asStr(p['predictedCompletion']),
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Sort items by significance level descending, with numeric score as
|
|
202
|
+
* tie-breaker. Items with higher significance or scores appear first.
|
|
203
|
+
* The original array is not mutated.
|
|
204
|
+
*
|
|
205
|
+
* @param items - Array of items with optional significance and score fields
|
|
206
|
+
* @returns New sorted array ordered by significance then score
|
|
207
|
+
*/
|
|
208
|
+
export function rankBySignificance(items) {
|
|
209
|
+
return [...items].sort((a, b) => {
|
|
210
|
+
const sigA = SIGNIFICANCE_WEIGHTS[a.significance ?? ''] ?? 0;
|
|
211
|
+
const sigB = SIGNIFICANCE_WEIGHTS[b.significance ?? ''] ?? 0;
|
|
212
|
+
if (sigA !== sigB)
|
|
213
|
+
return sigB - sigA;
|
|
214
|
+
const scoreA = a.overallScore ?? a.cohesionScore ?? 0;
|
|
215
|
+
const scoreB = b.overallScore ?? b.cohesionScore ?? 0;
|
|
216
|
+
return scoreB - scoreA;
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Build an HTML section element for displaying intelligence items as a list.
|
|
221
|
+
* All title, className, and item strings are HTML-escaped to prevent XSS.
|
|
222
|
+
* Returns an empty string when the items array is empty.
|
|
223
|
+
*
|
|
224
|
+
* @param title - Section heading text (will be HTML-escaped)
|
|
225
|
+
* @param items - Array of text items to display as list entries (will be HTML-escaped)
|
|
226
|
+
* @param className - CSS class name for the section element (will be HTML-escaped)
|
|
227
|
+
* @returns HTML string for the intelligence section, or empty string if no items
|
|
228
|
+
*/
|
|
229
|
+
export function buildIntelligenceSection(title, items, className) {
|
|
230
|
+
if (items.length === 0)
|
|
231
|
+
return '';
|
|
232
|
+
const safeClass = escapeHTML(className);
|
|
233
|
+
const safeTitle = escapeHTML(title);
|
|
234
|
+
const itemsHtml = items.map((item) => `<li>${escapeHTML(item)}</li>`).join('\n ');
|
|
235
|
+
return `<section class="${safeClass}">
|
|
236
|
+
<h2>${safeTitle}</h2>
|
|
237
|
+
<ul>
|
|
238
|
+
${itemsHtml}
|
|
239
|
+
</ul>
|
|
240
|
+
</section>`;
|
|
241
|
+
}
|
|
242
|
+
// ─── Stakeholder scoring functions ───────────────────────────────────────────
|
|
243
|
+
/**
|
|
244
|
+
* Derive a severity level from a numeric 0-1 importance score.
|
|
245
|
+
*
|
|
246
|
+
* @param score - Normalised importance score (0 = least important, 1 = most)
|
|
247
|
+
* @returns Severity level
|
|
248
|
+
*/
|
|
249
|
+
function severityFromScore(score) {
|
|
250
|
+
if (score >= 0.7)
|
|
251
|
+
return 'high';
|
|
252
|
+
if (score >= 0.4)
|
|
253
|
+
return 'medium';
|
|
254
|
+
return 'low';
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Build a default set of stakeholder perspectives for a parliamentary action.
|
|
258
|
+
* Each perspective is seeded with a reasoning string and evidence items derived
|
|
259
|
+
* from the provided topic and impact scores. All six stakeholder groups receive
|
|
260
|
+
* a perspective entry.
|
|
261
|
+
*
|
|
262
|
+
* @param topic - Short description of the parliamentary action (e.g. vote title)
|
|
263
|
+
* @param scores - Optional per-stakeholder importance scores (0-1); defaults to 0.5
|
|
264
|
+
* @returns Array of six StakeholderPerspective objects, one per stakeholder group
|
|
265
|
+
*/
|
|
266
|
+
export function buildDefaultStakeholderPerspectives(topic, scores) {
|
|
267
|
+
return ALL_STAKEHOLDER_TYPES.map((stakeholder) => {
|
|
268
|
+
const score = scores?.[stakeholder] ?? 0.5;
|
|
269
|
+
const severity = severityFromScore(score);
|
|
270
|
+
return {
|
|
271
|
+
stakeholder,
|
|
272
|
+
impact: score >= 0.6
|
|
273
|
+
? 'positive'
|
|
274
|
+
: score <= 0.3
|
|
275
|
+
? 'negative'
|
|
276
|
+
: 'neutral',
|
|
277
|
+
severity,
|
|
278
|
+
reasoning: `Impact on this stakeholder group: ${severity} significance based on "${topic}".`,
|
|
279
|
+
evidence: [topic],
|
|
280
|
+
};
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Score stakeholder influence from raw MCP data.
|
|
285
|
+
* Returns null for null, undefined, non-object, or missing stakeholder type.
|
|
286
|
+
*
|
|
287
|
+
* @param rawData - Raw stakeholder influence data (unknown shape)
|
|
288
|
+
* @returns Structured StakeholderPerspective or null if input is invalid
|
|
289
|
+
*/
|
|
290
|
+
export function scoreStakeholderInfluence(rawData) {
|
|
291
|
+
const d = toRecord(rawData);
|
|
292
|
+
if (!d)
|
|
293
|
+
return null;
|
|
294
|
+
const stakeholderRaw = asStr(d['stakeholder']);
|
|
295
|
+
if (!ALL_STAKEHOLDER_TYPES.includes(stakeholderRaw))
|
|
296
|
+
return null;
|
|
297
|
+
const stakeholder = stakeholderRaw;
|
|
298
|
+
const impactRaw = asStr(d['impact']).toLowerCase();
|
|
299
|
+
const validImpacts = ['positive', 'negative', 'neutral', 'mixed'];
|
|
300
|
+
const impact = validImpacts.includes(impactRaw)
|
|
301
|
+
? impactRaw
|
|
302
|
+
: 'neutral';
|
|
303
|
+
const severityRaw = asStr(d['severity']).toLowerCase();
|
|
304
|
+
const validSeverities = ['high', 'medium', 'low'];
|
|
305
|
+
const severity = validSeverities.includes(severityRaw)
|
|
306
|
+
? severityRaw
|
|
307
|
+
: 'medium';
|
|
308
|
+
return {
|
|
309
|
+
stakeholder,
|
|
310
|
+
impact,
|
|
311
|
+
severity,
|
|
312
|
+
reasoning: asStr(d['reasoning']),
|
|
313
|
+
evidence: asStrArr(d['evidence']),
|
|
314
|
+
};
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Build a StakeholderOutcomeMatrix row for a single parliamentary action.
|
|
318
|
+
* Derives outcomes from per-stakeholder scores: score > 0.6 → winner,
|
|
319
|
+
* score < 0.4 → loser, otherwise neutral.
|
|
320
|
+
*
|
|
321
|
+
* @param action - The parliamentary action being assessed
|
|
322
|
+
* @param scores - Per-stakeholder importance scores (0-1); defaults to 0.5
|
|
323
|
+
* @param confidence - Confidence level for the outcome assessments
|
|
324
|
+
* @returns A StakeholderOutcomeMatrix row
|
|
325
|
+
*/
|
|
326
|
+
export function buildStakeholderOutcomeMatrix(action, scores = {}, confidence = 'medium') {
|
|
327
|
+
const outcomes = Object.fromEntries(ALL_STAKEHOLDER_TYPES.map((stakeholder) => {
|
|
328
|
+
const score = scores[stakeholder] ?? 0.5;
|
|
329
|
+
const outcome = score > 0.6 ? 'winner' : score < 0.4 ? 'loser' : 'neutral';
|
|
330
|
+
return [stakeholder, outcome];
|
|
331
|
+
}));
|
|
332
|
+
return { action, outcomes, confidence };
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* Map an array of StakeholderPerspective objects to a simple influence ranking.
|
|
336
|
+
* Returns stakeholder types sorted by severity (high → medium → low), then by
|
|
337
|
+
* impact direction (negative before positive, as negative impacts require more
|
|
338
|
+
* political attention).
|
|
339
|
+
*
|
|
340
|
+
* @param perspectives - Array of stakeholder perspectives to rank
|
|
341
|
+
* @returns Stakeholder types sorted by influence priority
|
|
342
|
+
*/
|
|
343
|
+
export function rankStakeholdersByInfluence(perspectives) {
|
|
344
|
+
const severityWeight = {
|
|
345
|
+
high: 3,
|
|
346
|
+
medium: 2,
|
|
347
|
+
low: 1,
|
|
348
|
+
};
|
|
349
|
+
const impactWeight = {
|
|
350
|
+
negative: 3,
|
|
351
|
+
mixed: 2,
|
|
352
|
+
positive: 1,
|
|
353
|
+
neutral: 0,
|
|
354
|
+
};
|
|
355
|
+
return [...perspectives]
|
|
356
|
+
.sort((a, b) => {
|
|
357
|
+
const sw = severityWeight[b.severity] - severityWeight[a.severity];
|
|
358
|
+
if (sw !== 0)
|
|
359
|
+
return sw;
|
|
360
|
+
const iw = impactWeight[b.impact] - impactWeight[a.impact];
|
|
361
|
+
if (iw !== 0)
|
|
362
|
+
return iw;
|
|
363
|
+
// Deterministic tie-breaker: canonical ALL_STAKEHOLDER_TYPES order
|
|
364
|
+
return (ALL_STAKEHOLDER_TYPES.indexOf(a.stakeholder) - ALL_STAKEHOLDER_TYPES.indexOf(b.stakeholder));
|
|
365
|
+
})
|
|
366
|
+
.map((p) => p.stakeholder);
|
|
367
|
+
}
|
|
368
|
+
// ─── Advanced political intelligence functions ──────────────────────────────
|
|
369
|
+
/**
|
|
370
|
+
* Compute voting intensity metrics from a set of voting records.
|
|
371
|
+
* Analyses the distribution of for/against/abstain votes to determine
|
|
372
|
+
* unanimity, polarization, and margin characteristics.
|
|
373
|
+
*
|
|
374
|
+
* @param records - Voting records to analyse
|
|
375
|
+
* @returns VotingIntensity metrics, or null if the records array is empty or contains no
|
|
376
|
+
* valid vote counts (for example, when all records have a total vote count of 0)
|
|
377
|
+
*/
|
|
378
|
+
export function computeVotingIntensity(records) {
|
|
379
|
+
if (records.length === 0)
|
|
380
|
+
return null;
|
|
381
|
+
let totalUnanimity = 0;
|
|
382
|
+
let totalPolarization = 0;
|
|
383
|
+
let totalMargin = 0;
|
|
384
|
+
let closeVoteCount = 0;
|
|
385
|
+
let decisiveVoteCount = 0;
|
|
386
|
+
let validCount = 0;
|
|
387
|
+
let polarizationCount = 0;
|
|
388
|
+
for (const record of records) {
|
|
389
|
+
const total = record.votes.for + record.votes.against + record.votes.abstain;
|
|
390
|
+
if (total === 0)
|
|
391
|
+
continue;
|
|
392
|
+
validCount++;
|
|
393
|
+
const forPct = record.votes.for / total;
|
|
394
|
+
const againstPct = record.votes.against / total;
|
|
395
|
+
const abstainPct = record.votes.abstain / total;
|
|
396
|
+
const margin = Math.abs(forPct - againstPct);
|
|
397
|
+
// Largest-position share: max share among for/against/abstain
|
|
398
|
+
const maxPct = Math.max(forPct, againstPct, abstainPct);
|
|
399
|
+
totalUnanimity += maxPct;
|
|
400
|
+
// Margin, close/decisive, and polarization only meaningful when for+against > 0
|
|
401
|
+
const forAgainstTotal = record.votes.for + record.votes.against;
|
|
402
|
+
if (forAgainstTotal > 0) {
|
|
403
|
+
polarizationCount++;
|
|
404
|
+
const balance = Math.min(record.votes.for, record.votes.against) / forAgainstTotal;
|
|
405
|
+
totalPolarization += balance * 2; // normalise: 0 = one-sided, 1 = perfectly split
|
|
406
|
+
totalMargin += margin;
|
|
407
|
+
if (margin < 0.1)
|
|
408
|
+
closeVoteCount++;
|
|
409
|
+
if (margin > 0.6)
|
|
410
|
+
decisiveVoteCount++;
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
if (validCount === 0)
|
|
414
|
+
return null;
|
|
415
|
+
return {
|
|
416
|
+
unanimity: Math.round((totalUnanimity / validCount) * 100) / 100,
|
|
417
|
+
polarization: polarizationCount > 0 ? Math.round((totalPolarization / polarizationCount) * 100) / 100 : 0,
|
|
418
|
+
averageMargin: polarizationCount > 0 ? Math.round((totalMargin / polarizationCount) * 100) / 100 : 0,
|
|
419
|
+
closeVoteCount,
|
|
420
|
+
decisiveVoteCount,
|
|
421
|
+
};
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Detect coalition shifts by comparing current cohesion patterns against
|
|
425
|
+
* a baseline. Stability threshold is ±5%; severity tiers are >5% (medium),
|
|
426
|
+
* >10% (high), and >20% (critical).
|
|
427
|
+
*
|
|
428
|
+
* @param currentPatterns - Current period voting patterns
|
|
429
|
+
* @param baselinePatterns - Previous period patterns (or estimated baseline)
|
|
430
|
+
* @returns Array of detected coalition shifts, sorted by significance
|
|
431
|
+
*/
|
|
432
|
+
export function detectCoalitionShifts(currentPatterns, baselinePatterns) {
|
|
433
|
+
const baselineMap = new Map();
|
|
434
|
+
for (const bp of baselinePatterns) {
|
|
435
|
+
baselineMap.set(bp.group, bp.cohesion);
|
|
436
|
+
}
|
|
437
|
+
const shifts = [];
|
|
438
|
+
for (const current of currentPatterns) {
|
|
439
|
+
const previous = baselineMap.get(current.group) ?? current.cohesion;
|
|
440
|
+
const delta = current.cohesion - previous;
|
|
441
|
+
const absDelta = Math.abs(delta);
|
|
442
|
+
let direction;
|
|
443
|
+
if (delta > 0.05)
|
|
444
|
+
direction = 'strengthening';
|
|
445
|
+
else if (delta < -0.05)
|
|
446
|
+
direction = 'weakening';
|
|
447
|
+
else
|
|
448
|
+
direction = 'stable';
|
|
449
|
+
let significance;
|
|
450
|
+
if (absDelta > 0.2)
|
|
451
|
+
significance = 'critical';
|
|
452
|
+
else if (absDelta > 0.1)
|
|
453
|
+
significance = 'high';
|
|
454
|
+
else if (absDelta > 0.05)
|
|
455
|
+
significance = 'medium';
|
|
456
|
+
else
|
|
457
|
+
significance = 'low';
|
|
458
|
+
shifts.push({
|
|
459
|
+
group: current.group,
|
|
460
|
+
previousCohesion: Math.round(previous * 100) / 100,
|
|
461
|
+
currentCohesion: Math.round(current.cohesion * 100) / 100,
|
|
462
|
+
cohesionDelta: Math.round(delta * 100) / 100,
|
|
463
|
+
direction,
|
|
464
|
+
significance,
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
// Sort by significance (critical first), then by absolute delta descending
|
|
468
|
+
const sigOrder = { critical: 4, high: 3, medium: 2, low: 1 };
|
|
469
|
+
return shifts.sort((a, b) => {
|
|
470
|
+
const sigDiff = (sigOrder[b.significance] ?? 0) - (sigOrder[a.significance] ?? 0);
|
|
471
|
+
if (sigDiff !== 0)
|
|
472
|
+
return sigDiff;
|
|
473
|
+
return Math.abs(b.cohesionDelta) - Math.abs(a.cohesionDelta);
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
/**
|
|
477
|
+
* Classify cohesion groups into high-cohesion and fragmented categories.
|
|
478
|
+
*
|
|
479
|
+
* @param patterns - Voting patterns
|
|
480
|
+
* @returns Tuple of [highCohesionGroups, fragmentedGroups]
|
|
481
|
+
*/
|
|
482
|
+
function classifyCohesionGroups(patterns) {
|
|
483
|
+
const high = [];
|
|
484
|
+
const fragmented = [];
|
|
485
|
+
for (const p of patterns) {
|
|
486
|
+
if (p.cohesion > 0.8)
|
|
487
|
+
high.push(p.group);
|
|
488
|
+
if (p.cohesion < 0.5)
|
|
489
|
+
fragmented.push(p.group);
|
|
490
|
+
}
|
|
491
|
+
return [high, fragmented];
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Compute effective number of voting blocs using Laakso-Taagepera style.
|
|
495
|
+
*
|
|
496
|
+
* @param patterns - Voting patterns
|
|
497
|
+
* @returns Effective number of blocs
|
|
498
|
+
*/
|
|
499
|
+
function computeEffectiveBlocs(patterns) {
|
|
500
|
+
let totalParticipation = 0;
|
|
501
|
+
for (const p of patterns)
|
|
502
|
+
totalParticipation += p.participation;
|
|
503
|
+
if (totalParticipation <= 0)
|
|
504
|
+
return patterns.length;
|
|
505
|
+
let sumSquares = 0;
|
|
506
|
+
for (const p of patterns) {
|
|
507
|
+
const share = p.participation / totalParticipation;
|
|
508
|
+
sumSquares += share * share;
|
|
509
|
+
}
|
|
510
|
+
return sumSquares > 0 ? 1 / sumSquares : patterns.length;
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Map an overall index to a polarization assessment label.
|
|
514
|
+
*
|
|
515
|
+
* @param index - Polarization index (0-1)
|
|
516
|
+
* @returns Assessment label
|
|
517
|
+
*/
|
|
518
|
+
function assessPolarization(index) {
|
|
519
|
+
if (index >= 0.75)
|
|
520
|
+
return 'highly-polarized';
|
|
521
|
+
if (index >= 0.5)
|
|
522
|
+
return 'polarized';
|
|
523
|
+
if (index >= 0.25)
|
|
524
|
+
return 'moderate';
|
|
525
|
+
return 'consensus';
|
|
526
|
+
}
|
|
527
|
+
/**
|
|
528
|
+
* Compute a polarization index for a parliamentary period based on
|
|
529
|
+
* voting pattern cohesion data. Uses a Laakso-Taagepera–inspired
|
|
530
|
+
* "effective number of blocs" calculation alongside cohesion analysis.
|
|
531
|
+
*
|
|
532
|
+
* @param patterns - Voting patterns for the period
|
|
533
|
+
* @returns PolarizationIndex assessment, or null if patterns are empty
|
|
534
|
+
*/
|
|
535
|
+
export function computePolarizationIndex(patterns) {
|
|
536
|
+
if (patterns.length === 0)
|
|
537
|
+
return null;
|
|
538
|
+
const [highCohesionGroups, fragmentedGroups] = classifyCohesionGroups(patterns);
|
|
539
|
+
const effectiveBlocs = computeEffectiveBlocs(patterns);
|
|
540
|
+
const extremeCount = highCohesionGroups.length + fragmentedGroups.length;
|
|
541
|
+
const overallIndex = Math.round((extremeCount / patterns.length) * 100) / 100;
|
|
542
|
+
return {
|
|
543
|
+
overallIndex,
|
|
544
|
+
effectiveBlocs: Math.round(effectiveBlocs * 100) / 100,
|
|
545
|
+
highCohesionGroups,
|
|
546
|
+
fragmentedGroups,
|
|
547
|
+
assessment: assessPolarization(overallIndex),
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
// ─── Cross-session analysis functions ─────────────────────────────────────────
|
|
551
|
+
/**
|
|
552
|
+
* Compute average of a numeric array.
|
|
553
|
+
*
|
|
554
|
+
* @param values - Array of numbers
|
|
555
|
+
* @returns Arithmetic mean, or 0 for empty arrays
|
|
556
|
+
*/
|
|
557
|
+
function avg(values) {
|
|
558
|
+
return values.length > 0 ? values.reduce((s, v) => s + v, 0) / values.length : 0;
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Extract valid vote margins and result tallies from voting records.
|
|
562
|
+
* Skips records with missing/malformed vote data, non-finite or negative
|
|
563
|
+
* vote counts, or where for + against is zero (abstain-only votes) to avoid
|
|
564
|
+
* skewing margin and polarization calculations. Only records where
|
|
565
|
+
* `votes.for` and `votes.against` are finite, non-negative numbers are used;
|
|
566
|
+
* numeric-string encodings and other non-numeric values are ignored.
|
|
567
|
+
*
|
|
568
|
+
* @param records - Voting records to process
|
|
569
|
+
* @returns Object containing margins array and per-record result classifications
|
|
570
|
+
*/
|
|
571
|
+
function extractMarginData(records) {
|
|
572
|
+
const margins = [];
|
|
573
|
+
const results = [];
|
|
574
|
+
for (const r of records) {
|
|
575
|
+
const votes = r.votes;
|
|
576
|
+
if (!votes || typeof votes !== 'object')
|
|
577
|
+
continue;
|
|
578
|
+
// Require actual finite numbers — asNum() would silently map non-numbers to 0,
|
|
579
|
+
// which would include malformed records and skew margins/polarization metrics.
|
|
580
|
+
const forCount = votes.for;
|
|
581
|
+
const againstCount = votes.against;
|
|
582
|
+
if (typeof forCount !== 'number' || !Number.isFinite(forCount) || forCount < 0)
|
|
583
|
+
continue;
|
|
584
|
+
if (typeof againstCount !== 'number' || !Number.isFinite(againstCount) || againstCount < 0)
|
|
585
|
+
continue;
|
|
586
|
+
const forAgainstTotal = forCount + againstCount;
|
|
587
|
+
if (forAgainstTotal <= 0)
|
|
588
|
+
continue;
|
|
589
|
+
margins.push(Math.abs(forCount - againstCount) / forAgainstTotal);
|
|
590
|
+
const result = asStr(r.result).toLowerCase();
|
|
591
|
+
if (result === 'adopted' || result === 'approved') {
|
|
592
|
+
results.push('adopted');
|
|
593
|
+
}
|
|
594
|
+
else if (result === 'rejected') {
|
|
595
|
+
results.push('rejected');
|
|
596
|
+
}
|
|
597
|
+
else {
|
|
598
|
+
results.push('other');
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
return { margins, results };
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* Compute adoption rate from a results slice.
|
|
605
|
+
*
|
|
606
|
+
* @param results - Array of result classifications
|
|
607
|
+
* @returns Adoption rate (0-1), or 0 if no decided records
|
|
608
|
+
*/
|
|
609
|
+
function computeAdoptionRate(results) {
|
|
610
|
+
const adopted = results.filter((r) => r === 'adopted').length;
|
|
611
|
+
const decided = results.filter((r) => r === 'adopted' || r === 'rejected').length;
|
|
612
|
+
return decided > 0 ? adopted / decided : 0;
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* Derive adoption-rate direction by comparing first-half and second-half rates.
|
|
616
|
+
*
|
|
617
|
+
* @param firstRate - Adoption rate of the first chronological half
|
|
618
|
+
* @param secondRate - Adoption rate of the second chronological half
|
|
619
|
+
* @returns Direction label based on delta between halves
|
|
620
|
+
*/
|
|
621
|
+
function adoptionDirection(firstRate, secondRate) {
|
|
622
|
+
const delta = secondRate - firstRate;
|
|
623
|
+
if (delta > 0.05)
|
|
624
|
+
return 'increasing';
|
|
625
|
+
if (delta < -0.05)
|
|
626
|
+
return 'decreasing';
|
|
627
|
+
return 'stable';
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Build a margin-shift trend if the delta exceeds 5%.
|
|
631
|
+
*
|
|
632
|
+
* @param firstHalf - Margins from the first half of records
|
|
633
|
+
* @param secondHalf - Margins from the second half of records
|
|
634
|
+
* @param total - Total number of valid records
|
|
635
|
+
* @returns VotingTrend or null if delta is within threshold
|
|
636
|
+
*/
|
|
637
|
+
function buildMarginTrend(firstHalf, secondHalf, total) {
|
|
638
|
+
const marginDelta = avg(secondHalf) - avg(firstHalf);
|
|
639
|
+
if (Math.abs(marginDelta) <= 0.05)
|
|
640
|
+
return null;
|
|
641
|
+
const isIncreasing = marginDelta > 0;
|
|
642
|
+
return {
|
|
643
|
+
trendId: isIncreasing ? 'increasing-margins' : 'decreasing-margins',
|
|
644
|
+
description: isIncreasing
|
|
645
|
+
? 'Voting margins are widening — greater decisiveness'
|
|
646
|
+
: 'Voting margins are narrowing — increasing contention',
|
|
647
|
+
direction: isIncreasing ? 'increasing' : 'decreasing',
|
|
648
|
+
confidence: Math.min(1, Math.round(Math.abs(marginDelta) * 5 * 100) / 100),
|
|
649
|
+
recordCount: total,
|
|
650
|
+
metricValue: Math.round(marginDelta * 100) / 100,
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Build a polarization trend if the close-vote frequency delta exceeds 10%.
|
|
655
|
+
*
|
|
656
|
+
* @param firstHalf - Margins from the first half of records
|
|
657
|
+
* @param secondHalf - Margins from the second half of records
|
|
658
|
+
* @param total - Total number of valid records
|
|
659
|
+
* @returns VotingTrend or null if delta is within threshold
|
|
660
|
+
*/
|
|
661
|
+
function buildPolarizationTrend(firstHalf, secondHalf, total) {
|
|
662
|
+
const closeFirst = firstHalf.filter((m) => m < 0.1).length / firstHalf.length;
|
|
663
|
+
const closeSecond = secondHalf.filter((m) => m < 0.1).length / secondHalf.length;
|
|
664
|
+
const closeDelta = closeSecond - closeFirst;
|
|
665
|
+
if (Math.abs(closeDelta) <= 0.1)
|
|
666
|
+
return null;
|
|
667
|
+
const isIncreasing = closeDelta > 0;
|
|
668
|
+
return {
|
|
669
|
+
trendId: isIncreasing ? 'increasing-polarization' : 'decreasing-polarization',
|
|
670
|
+
description: isIncreasing
|
|
671
|
+
? 'More close votes detected — increasing polarization'
|
|
672
|
+
: 'Fewer close votes — declining polarization',
|
|
673
|
+
direction: isIncreasing ? 'increasing' : 'decreasing',
|
|
674
|
+
confidence: Math.min(1, Math.round(Math.abs(closeDelta) * 3 * 100) / 100),
|
|
675
|
+
recordCount: total,
|
|
676
|
+
metricValue: Math.round(closeDelta * 100) / 100,
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
/**
|
|
680
|
+
* Detect voting trends across multiple voting records by analysing
|
|
681
|
+
* margin distribution, polarization patterns, and result consistency.
|
|
682
|
+
* Records are sorted by date (ascending) before analysis to ensure
|
|
683
|
+
* chronological trend detection. Returns an array of detected trends
|
|
684
|
+
* sorted by confidence.
|
|
685
|
+
*
|
|
686
|
+
* @param records - Voting records to analyse across sessions
|
|
687
|
+
* @returns Array of detected VotingTrend objects (empty if fewer than 2 valid records)
|
|
688
|
+
*/
|
|
689
|
+
export function detectVotingTrends(records) {
|
|
690
|
+
if (records.length < 2)
|
|
691
|
+
return [];
|
|
692
|
+
const toTimestamp = (d) => {
|
|
693
|
+
const t = Date.parse(d ?? '');
|
|
694
|
+
return Number.isFinite(t) ? t : Infinity;
|
|
695
|
+
};
|
|
696
|
+
const sorted = [...records].sort((a, b) => {
|
|
697
|
+
const ta = toTimestamp(a.date);
|
|
698
|
+
const tb = toTimestamp(b.date);
|
|
699
|
+
if (ta === tb)
|
|
700
|
+
return 0;
|
|
701
|
+
return ta < tb ? -1 : 1;
|
|
702
|
+
});
|
|
703
|
+
const { margins, results } = extractMarginData(sorted);
|
|
704
|
+
if (margins.length < 2)
|
|
705
|
+
return [];
|
|
706
|
+
const mid = Math.floor(margins.length / 2);
|
|
707
|
+
const firstHalf = margins.slice(0, mid);
|
|
708
|
+
const secondHalf = margins.slice(mid);
|
|
709
|
+
const trends = [];
|
|
710
|
+
const marginTrend = buildMarginTrend(firstHalf, secondHalf, margins.length);
|
|
711
|
+
if (marginTrend)
|
|
712
|
+
trends.push(marginTrend);
|
|
713
|
+
const polTrend = buildPolarizationTrend(firstHalf, secondHalf, margins.length);
|
|
714
|
+
if (polTrend)
|
|
715
|
+
trends.push(polTrend);
|
|
716
|
+
const firstResults = results.slice(0, mid);
|
|
717
|
+
const secondResults = results.slice(mid);
|
|
718
|
+
const totalDecided = results.filter((r) => r === 'adopted' || r === 'rejected').length;
|
|
719
|
+
if (totalDecided > 0) {
|
|
720
|
+
const overallRate = computeAdoptionRate(results);
|
|
721
|
+
const firstRate = computeAdoptionRate(firstResults);
|
|
722
|
+
const secondRate = computeAdoptionRate(secondResults);
|
|
723
|
+
trends.push({
|
|
724
|
+
trendId: 'adoption-rate',
|
|
725
|
+
description: `Adoption rate is ${Math.round(overallRate * 100)}% across ${totalDecided} decided votes`,
|
|
726
|
+
direction: adoptionDirection(firstRate, secondRate),
|
|
727
|
+
confidence: Math.min(1, Math.round((totalDecided / margins.length) * 100) / 100),
|
|
728
|
+
recordCount: totalDecided,
|
|
729
|
+
metricValue: Math.round(overallRate * 100) / 100,
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
return trends.sort((a, b) => b.confidence - a.confidence);
|
|
733
|
+
}
|
|
734
|
+
/**
|
|
735
|
+
* Compute cross-session coalition stability by analysing average cohesion
|
|
736
|
+
* across a set of voting patterns. Groups with high cohesion are reported
|
|
737
|
+
* as stable; those with low cohesion are flagged.
|
|
738
|
+
*
|
|
739
|
+
* @param patterns - Voting patterns from multiple sessions
|
|
740
|
+
* @returns CoalitionStabilityReport (empty report if no patterns)
|
|
741
|
+
*/
|
|
742
|
+
export function computeCrossSessionCoalitionStability(patterns) {
|
|
743
|
+
if (patterns.length === 0) {
|
|
744
|
+
return {
|
|
745
|
+
overallStability: 0,
|
|
746
|
+
patternCount: 0,
|
|
747
|
+
stableGroups: [],
|
|
748
|
+
decliningGroups: [],
|
|
749
|
+
forecast: 'volatile',
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
// Aggregate cohesion per group, coercing and clamping to [0, 1]
|
|
753
|
+
const groupCohesions = new Map();
|
|
754
|
+
let includedPatterns = 0;
|
|
755
|
+
for (const p of patterns) {
|
|
756
|
+
const groupKey = asStr(p.group).trim();
|
|
757
|
+
if (groupKey.length === 0)
|
|
758
|
+
continue;
|
|
759
|
+
includedPatterns++;
|
|
760
|
+
const raw = asNum(p.cohesion);
|
|
761
|
+
const clamped = Math.max(0, Math.min(1, raw));
|
|
762
|
+
const existing = groupCohesions.get(groupKey);
|
|
763
|
+
if (existing) {
|
|
764
|
+
existing.push(clamped);
|
|
765
|
+
}
|
|
766
|
+
else {
|
|
767
|
+
groupCohesions.set(groupKey, [clamped]);
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
const stableGroups = [];
|
|
771
|
+
const decliningGroups = [];
|
|
772
|
+
let totalAvgCohesion = 0;
|
|
773
|
+
let groupCount = 0;
|
|
774
|
+
for (const [group, cohesions] of groupCohesions) {
|
|
775
|
+
const avgCohesion = cohesions.reduce((s, v) => s + v, 0) / cohesions.length;
|
|
776
|
+
totalAvgCohesion += avgCohesion;
|
|
777
|
+
groupCount++;
|
|
778
|
+
if (avgCohesion >= 0.7) {
|
|
779
|
+
stableGroups.push(group);
|
|
780
|
+
}
|
|
781
|
+
else if (avgCohesion < 0.5) {
|
|
782
|
+
decliningGroups.push(group);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
const overallStability = groupCount > 0 ? Math.round((totalAvgCohesion / groupCount) * 100) / 100 : 0;
|
|
786
|
+
let forecast;
|
|
787
|
+
if (overallStability >= 0.7)
|
|
788
|
+
forecast = 'stable';
|
|
789
|
+
else if (overallStability >= 0.5)
|
|
790
|
+
forecast = 'at-risk';
|
|
791
|
+
else
|
|
792
|
+
forecast = 'volatile';
|
|
793
|
+
return {
|
|
794
|
+
overallStability,
|
|
795
|
+
patternCount: includedPatterns,
|
|
796
|
+
stableGroups,
|
|
797
|
+
decliningGroups,
|
|
798
|
+
forecast,
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
/**
|
|
802
|
+
* Rank MEP influence scores filtered by topic relevance.
|
|
803
|
+
* Matches scores whose mepName, mepId, or rank contains the topic substring
|
|
804
|
+
* (case-insensitive). Returns the filtered list sorted by overallScore
|
|
805
|
+
* descending. If topic is empty or no matches found, returns all scores
|
|
806
|
+
* sorted by overallScore.
|
|
807
|
+
*
|
|
808
|
+
* @param scores - MEP influence scores to rank
|
|
809
|
+
* @param topic - Topic keyword to filter by; if null/undefined/empty, all
|
|
810
|
+
* scores are returned sorted by overallScore
|
|
811
|
+
* @returns Sorted array of matching MEPInfluenceScore entries
|
|
812
|
+
*/
|
|
813
|
+
export function rankMEPInfluenceByTopic(scores, topic) {
|
|
814
|
+
if (scores.length === 0)
|
|
815
|
+
return [];
|
|
816
|
+
const lowerTopic = String(topic ?? '')
|
|
817
|
+
.toLowerCase()
|
|
818
|
+
.trim();
|
|
819
|
+
const getSafeScore = (entry) => {
|
|
820
|
+
const raw = asNum(entry.overallScore);
|
|
821
|
+
return Number.isFinite(raw) ? raw : 0;
|
|
822
|
+
};
|
|
823
|
+
// If topic is empty, return all sorted by score
|
|
824
|
+
if (lowerTopic.length === 0) {
|
|
825
|
+
return [...scores].sort((a, b) => getSafeScore(b) - getSafeScore(a));
|
|
826
|
+
}
|
|
827
|
+
const matched = scores.filter((s) => {
|
|
828
|
+
const safeName = typeof s.mepName === 'string' ? s.mepName.toLowerCase() : '';
|
|
829
|
+
const safeRank = typeof s.rank === 'string' ? s.rank.toLowerCase() : '';
|
|
830
|
+
const safeId = typeof s.mepId === 'string' ? s.mepId.toLowerCase() : '';
|
|
831
|
+
return (safeName.includes(lowerTopic) || safeRank.includes(lowerTopic) || safeId.includes(lowerTopic));
|
|
832
|
+
});
|
|
833
|
+
// If no matches, return all sorted
|
|
834
|
+
const pool = matched.length > 0 ? matched : [...scores];
|
|
835
|
+
return pool.sort((a, b) => getSafeScore(b) - getSafeScore(a));
|
|
836
|
+
}
|
|
837
|
+
/**
|
|
838
|
+
* Count stages whose document count exceeds 1.5× the average (bottlenecks).
|
|
839
|
+
*
|
|
840
|
+
* @param stageValues - Array of per-stage document counts
|
|
841
|
+
* @returns Number of bottleneck stages
|
|
842
|
+
*/
|
|
843
|
+
function countBottleneckStages(stageValues) {
|
|
844
|
+
if (stageValues.length === 0)
|
|
845
|
+
return 0;
|
|
846
|
+
const avgPerStage = stageValues.reduce((s, v) => s + v, 0) / stageValues.length;
|
|
847
|
+
let count = 0;
|
|
848
|
+
for (const val of stageValues) {
|
|
849
|
+
if (val > avgPerStage * 1.5 && val > 1)
|
|
850
|
+
count++;
|
|
851
|
+
}
|
|
852
|
+
return count;
|
|
853
|
+
}
|
|
854
|
+
/**
|
|
855
|
+
* Compute average days per stage from a set of valid timestamps and the
|
|
856
|
+
* number of stages. Returns 0 when fewer than 2 dates are available.
|
|
857
|
+
*
|
|
858
|
+
* @param dates - Array of valid timestamp numbers (ms since epoch)
|
|
859
|
+
* @param stageCount - Number of distinct stages
|
|
860
|
+
* @returns Estimated average days per stage (rounded)
|
|
861
|
+
*/
|
|
862
|
+
function computeDaysPerStage(dates, stageCount) {
|
|
863
|
+
if (dates.length < 2 || stageCount <= 0)
|
|
864
|
+
return 0;
|
|
865
|
+
let minDate = dates[0];
|
|
866
|
+
let maxDate = dates[0];
|
|
867
|
+
for (let i = 1; i < dates.length; i++) {
|
|
868
|
+
const current = dates[i];
|
|
869
|
+
if (current < minDate)
|
|
870
|
+
minDate = current;
|
|
871
|
+
if (current > maxDate)
|
|
872
|
+
maxDate = current;
|
|
873
|
+
}
|
|
874
|
+
const spanDays = (maxDate - minDate) / (1000 * 60 * 60 * 24);
|
|
875
|
+
return Math.round(spanDays / stageCount);
|
|
876
|
+
}
|
|
877
|
+
/**
|
|
878
|
+
* Determine throughput assessment label based on date availability and
|
|
879
|
+
* average days per stage.
|
|
880
|
+
*
|
|
881
|
+
* @param hasDateData - Whether sufficient date data was available
|
|
882
|
+
* @param avgDays - Average days per stage
|
|
883
|
+
* @returns Throughput label: 'fast', 'normal', or 'slow'
|
|
884
|
+
*/
|
|
885
|
+
function assessThroughput(hasDateData, avgDays) {
|
|
886
|
+
if (!hasDateData)
|
|
887
|
+
return 'normal';
|
|
888
|
+
if (avgDays <= 30)
|
|
889
|
+
return 'fast';
|
|
890
|
+
if (avgDays <= 90)
|
|
891
|
+
return 'normal';
|
|
892
|
+
return 'slow';
|
|
893
|
+
}
|
|
894
|
+
/**
|
|
895
|
+
* Build a legislative velocity report with stage-by-stage breakdown from
|
|
896
|
+
* a set of legislative documents. Analyses document status distribution
|
|
897
|
+
* and identifies potential bottlenecks.
|
|
898
|
+
*
|
|
899
|
+
* @param docs - Legislative documents to analyse
|
|
900
|
+
* @returns LegislativeVelocityReport summary
|
|
901
|
+
*/
|
|
902
|
+
export function buildLegislativeVelocityReport(docs) {
|
|
903
|
+
if (docs.length === 0) {
|
|
904
|
+
return {
|
|
905
|
+
documentCount: 0,
|
|
906
|
+
stageBreakdown: Object.create(null),
|
|
907
|
+
averageDaysPerStage: 0,
|
|
908
|
+
bottleneckCount: 0,
|
|
909
|
+
throughputAssessment: assessThroughput(false, 0),
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
const stageBreakdown = Object.create(null);
|
|
913
|
+
for (const doc of docs) {
|
|
914
|
+
const status = typeof doc.status === 'string' ? doc.status.trim() : '';
|
|
915
|
+
const type = typeof doc.type === 'string' ? doc.type.trim() : '';
|
|
916
|
+
const rawStage = status || type || 'Unknown';
|
|
917
|
+
const stage = rawStage === '__proto__' || rawStage === 'constructor' || rawStage === 'prototype'
|
|
918
|
+
? 'Unknown'
|
|
919
|
+
: rawStage;
|
|
920
|
+
stageBreakdown[stage] = (stageBreakdown[stage] ?? 0) + 1;
|
|
921
|
+
}
|
|
922
|
+
const bottleneckCount = countBottleneckStages(Object.values(stageBreakdown));
|
|
923
|
+
const dates = docs
|
|
924
|
+
.map((d) => (d.date ? new Date(d.date).getTime() : NaN))
|
|
925
|
+
.filter((t) => !Number.isNaN(t));
|
|
926
|
+
const hasDateData = dates.length >= 2;
|
|
927
|
+
const averageDaysPerStage = computeDaysPerStage(dates, Object.keys(stageBreakdown).length);
|
|
928
|
+
return {
|
|
929
|
+
documentCount: docs.length,
|
|
930
|
+
stageBreakdown,
|
|
931
|
+
averageDaysPerStage,
|
|
932
|
+
bottleneckCount,
|
|
933
|
+
throughputAssessment: assessThroughput(hasDateData, averageDaysPerStage),
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
//# sourceMappingURL=intelligence-analysis.js.map
|