All files / utils intelligence-analysis.ts

99.02% Statements 102/103
97% Branches 97/100
100% Functions 25/25
98.79% Lines 82/83

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419                                                              10x     10x     10x     10x                               199x                     74x                   32x 46x                   67x 52x                       10x 10x                   20x 20x                   13x 13x                           16x 16x 11x 16x 10x                                       16x 16x 14x 16x 13x                                     10x 10x 8x 10x 10x 6x                                       11x 11x 9x 11x 11x 7x                                                   7x 14x 14x 14x 6x 14x 14x                                     7x 6x 6x 8x 6x                                 876x 489x 75x                                 146x 876x 876x 876x                                             14x 14x 10x 10x 9x 9x 9x 9x     14x 14x 14x     14x                                               146x   876x   876x 876x     146x                             4x         4x           4x   6x 6x 1x 1x           7x    
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Utils/IntelligenceAnalysis
 * @description Pure intelligence analysis utility functions for structured
 * assessment of European Parliament data. All functions are stateless and
 * safely handle malformed or missing MCP data. No side effects.
 */
 
import { escapeHTML } from './file-utils.js';
import type {
  VotingAnomalyIntelligence,
  CoalitionIntelligence,
  MEPInfluenceScore,
  LegislativeVelocity,
  StakeholderPerspective,
  StakeholderOutcomeMatrix,
  AnalysisStakeholderType,
} from '../types/index.js';
import { ALL_STAKEHOLDER_TYPES } from '../types/index.js';
 
// ─── Internal type aliases ────────────────────────────────────────────────────
 
type SignificanceLevel = VotingAnomalyIntelligence['significance'];
type RiskLevel = CoalitionIntelligence['riskLevel'];
type AlignmentTrend = CoalitionIntelligence['alignmentTrend'];
 
// ─── Validation constants ─────────────────────────────────────────────────────
 
/** Valid significance levels in descending priority order */
const SIGNIFICANCE_LEVELS: readonly string[] = ['critical', 'high', 'medium', 'low'];
 
/** Valid risk levels for coalition and bottleneck assessment */
const RISK_LEVELS: readonly string[] = ['high', 'medium', 'low'];
 
/** Valid alignment trend values */
const ALIGNMENT_TRENDS: readonly string[] = ['strengthening', 'weakening', 'stable'];
 
/** Priority weights for significance-based ranking */
const SIGNIFICANCE_WEIGHTS: Readonly<Record<string, number>> = {
  critical: 4,
  high: 3,
  medium: 2,
  low: 1,
};
 
// ─── Private value-extraction helpers ────────────────────────────────────────
 
/**
 * Safely extract a string from an unknown field value
 *
 * @param val - Unknown value to coerce
 * @returns The string value or empty string if not a string
 */
function asStr(val: unknown): string {
  return typeof val === 'string' ? val : '';
}
 
/**
 * Safely extract a finite number from an unknown field value
 *
 * @param val - Unknown value to coerce
 * @param fallback - Value returned when input is not a finite number
 * @returns Finite number or fallback
 */
function asNum(val: unknown, fallback = 0): number {
  return typeof val === 'number' && Number.isFinite(val) ? val : fallback;
}
 
/**
 * Safely extract an array of strings from an unknown field value
 *
 * @param val - Unknown value to coerce
 * @returns Array of strings (empty array if input is not an array)
 */
function asStrArr(val: unknown): string[] {
  if (!Array.isArray(val)) return [];
  return (val as unknown[]).filter((v): v is string => typeof v === 'string');
}
 
/**
 * Coerce an unknown value to a non-null Record or return null
 *
 * @param input - Value to cast
 * @returns Record or null for null/undefined/non-object input
 */
function toRecord(input: unknown): Record<string, unknown> | null {
  if (input === null || input === undefined || typeof input !== 'object') return null;
  return input as Record<string, unknown>;
}
 
// ─── Private parsing validators ───────────────────────────────────────────────
 
/**
 * Validate and normalise a raw significance level string
 *
 * @param raw - Raw string from MCP data
 * @returns Validated SignificanceLevel, defaulting to 'low'
 */
function parseSignificance(raw: string): SignificanceLevel {
  const lower = raw.toLowerCase();
  return SIGNIFICANCE_LEVELS.includes(lower) ? (lower as SignificanceLevel) : 'low';
}
 
/**
 * Validate and normalise a raw risk level string
 *
 * @param raw - Raw string from MCP data
 * @returns Validated RiskLevel, defaulting to 'medium'
 */
function parseRiskLevel(raw: string): RiskLevel {
  const lower = raw.toLowerCase();
  return RISK_LEVELS.includes(lower) ? (lower as RiskLevel) : 'medium';
}
 
/**
 * Validate and normalise a raw alignment trend string
 *
 * @param raw - Raw string from MCP data
 * @returns Validated AlignmentTrend, defaulting to 'stable'
 */
function parseAlignmentTrend(raw: string): AlignmentTrend {
  const lower = raw.toLowerCase();
  return ALIGNMENT_TRENDS.includes(lower) ? (lower as AlignmentTrend) : 'stable';
}
 
// ─── Exported intelligence functions ─────────────────────────────────────────
 
/**
 * Parse and score a voting anomaly from raw MCP data.
 * Returns null for null, undefined, non-object, or inputs missing a valid
 * anomaly identifier.
 *
 * @param rawAnomaly - Raw MCP anomaly data (unknown shape)
 * @returns Structured VotingAnomalyIntelligence or null if input is invalid
 */
export function scoreVotingAnomaly(rawAnomaly: unknown): VotingAnomalyIntelligence | null {
  const a = toRecord(rawAnomaly);
  if (!a) return null;
  const anomalyId = asStr(a['anomalyId']) || asStr(a['id']);
  if (!anomalyId) return null;
  return {
    anomalyId,
    significance: parseSignificance(asStr(a['significance'])),
    description: asStr(a['description']),
    affectedGroups: asStrArr(a['affectedGroups']),
    deviationPercentage: asNum(a['deviationPercentage']),
    historicalContext: asStr(a['historicalContext']),
    implication: asStr(a['implication']),
  };
}
 
/**
 * Analyse a coalition's cohesion from raw MCP coalition data.
 * Returns null for null, undefined, non-object, or inputs missing a valid
 * coalition identifier.
 *
 * @param rawCoalition - Raw MCP coalition data (unknown shape)
 * @returns Structured CoalitionIntelligence or null if input is invalid
 */
export function analyzeCoalitionCohesion(rawCoalition: unknown): CoalitionIntelligence | null {
  const c = toRecord(rawCoalition);
  if (!c) return null;
  const coalitionId = asStr(c['coalitionId']) || asStr(c['id']);
  if (!coalitionId) return null;
  return {
    coalitionId,
    groups: asStrArr(c['groups']),
    cohesionScore: Math.min(1, Math.max(0, asNum(c['cohesionScore']))),
    alignmentTrend: parseAlignmentTrend(asStr(c['alignmentTrend'])),
    keyVotes: Math.max(0, Math.round(asNum(c['keyVotes']))),
    riskLevel: parseRiskLevel(asStr(c['riskLevel'])),
  };
}
 
/**
 * Extract and score MEP influence from raw MCP influence data.
 * Returns null for null, undefined, non-object, or inputs missing both a
 * valid MEP identifier and display name.
 *
 * @param rawInfluence - Raw MCP MEP influence data (unknown shape)
 * @returns Structured MEPInfluenceScore or null if input is invalid
 */
export function scoreMEPInfluence(rawInfluence: unknown): MEPInfluenceScore | null {
  const m = toRecord(rawInfluence);
  if (!m) return null;
  const mepId = asStr(m['mepId']) || asStr(m['id']);
  const mepName = asStr(m['mepName']) || asStr(m['name']);
  if (!mepId || !mepName) return null;
  return {
    mepId,
    mepName,
    overallScore: Math.min(100, Math.max(0, asNum(m['overallScore']))),
    votingActivity: Math.min(100, Math.max(0, asNum(m['votingActivity']))),
    legislativeOutput: Math.min(100, Math.max(0, asNum(m['legislativeOutput']))),
    committeeEngagement: Math.min(100, Math.max(0, asNum(m['committeeEngagement']))),
    rank: asStr(m['rank']),
  };
}
 
/**
 * Calculate legislative velocity from raw MCP procedure data.
 * Returns null for null, undefined, non-object, or inputs missing a valid
 * procedure identifier or title.
 *
 * @param rawProcedure - Raw MCP procedure data (unknown shape)
 * @returns Structured LegislativeVelocity or null if input is invalid
 */
export function calculateLegislativeVelocity(rawProcedure: unknown): LegislativeVelocity | null {
  const p = toRecord(rawProcedure);
  if (!p) return null;
  const procedureId = asStr(p['procedureId']) || asStr(p['id']);
  const title = asStr(p['title']);
  if (!procedureId || !title) return null;
  return {
    procedureId,
    title,
    stage: asStr(p['stage']) || 'Unknown',
    daysInCurrentStage: Math.max(0, Math.round(asNum(p['daysInCurrentStage']))),
    velocityScore: Math.min(1, Math.max(0, asNum(p['velocityScore']))),
    bottleneckRisk: parseRiskLevel(asStr(p['bottleneckRisk'])),
    predictedCompletion: asStr(p['predictedCompletion']),
  };
}
 
/**
 * Sort items by significance level descending, with numeric score as
 * tie-breaker. Items with higher significance or scores appear first.
 * The original array is not mutated.
 *
 * @param items - Array of items with optional significance and score fields
 * @returns New sorted array ordered by significance then score
 */
export function rankBySignificance<
  T extends {
    significance?: string | undefined;
    overallScore?: number | undefined;
    cohesionScore?: number | undefined;
  },
>(items: T[]): T[] {
  return [...items].sort((a, b) => {
    const sigA = SIGNIFICANCE_WEIGHTS[a.significance ?? ''] ?? 0;
    const sigB = SIGNIFICANCE_WEIGHTS[b.significance ?? ''] ?? 0;
    if (sigA !== sigB) return sigB - sigA;
    const scoreA = a.overallScore ?? a.cohesionScore ?? 0;
    const scoreB = b.overallScore ?? b.cohesionScore ?? 0;
    return scoreB - scoreA;
  });
}
 
/**
 * Build an HTML section element for displaying intelligence items as a list.
 * All title, className, and item strings are HTML-escaped to prevent XSS.
 * Returns an empty string when the items array is empty.
 *
 * @param title - Section heading text (will be HTML-escaped)
 * @param items - Array of text items to display as list entries (will be HTML-escaped)
 * @param className - CSS class name for the section element (will be HTML-escaped)
 * @returns HTML string for the intelligence section, or empty string if no items
 */
export function buildIntelligenceSection(
  title: string,
  items: string[],
  className: string
): string {
  if (items.length === 0) return '';
  const safeClass = escapeHTML(className);
  const safeTitle = escapeHTML(title);
  const itemsHtml = items.map((item) => `<li>${escapeHTML(item)}</li>`).join('\n          ');
  return `<section class="${safeClass}">
        <h2>${safeTitle}</h2>
        <ul>
          ${itemsHtml}
        </ul>
      </section>`;
}
 
// ─── Stakeholder scoring functions ───────────────────────────────────────────
 
/**
 * Derive a severity level from a numeric 0-1 importance score.
 *
 * @param score - Normalised importance score (0 = least important, 1 = most)
 * @returns Severity level
 */
function severityFromScore(score: number): StakeholderPerspective['severity'] {
  if (score >= 0.7) return 'high';
  if (score >= 0.4) return 'medium';
  return 'low';
}
 
/**
 * Build a default set of stakeholder perspectives for a parliamentary action.
 * Each perspective is seeded with a reasoning string and evidence items derived
 * from the provided topic and impact scores. All six stakeholder groups receive
 * a perspective entry.
 *
 * @param topic - Short description of the parliamentary action (e.g. vote title)
 * @param scores - Optional per-stakeholder importance scores (0-1); defaults to 0.5
 * @returns Array of six StakeholderPerspective objects, one per stakeholder group
 */
export function buildDefaultStakeholderPerspectives(
  topic: string,
  scores?: Partial<Record<AnalysisStakeholderType, number>>
): StakeholderPerspective[] {
  return ALL_STAKEHOLDER_TYPES.map((stakeholder) => {
    const score = scores?.[stakeholder] ?? 0.5;
    const severity = severityFromScore(score);
    return {
      stakeholder,
      impact:
        score >= 0.6
          ? ('positive' as const)
          : score <= 0.3
            ? ('negative' as const)
            : ('neutral' as const),
      severity,
      reasoning: `Impact on this stakeholder group: ${severity} significance based on "${topic}".`,
      evidence: [topic],
    };
  });
}
 
/**
 * Score stakeholder influence from raw MCP data.
 * Returns null for null, undefined, non-object, or missing stakeholder type.
 *
 * @param rawData - Raw stakeholder influence data (unknown shape)
 * @returns Structured StakeholderPerspective or null if input is invalid
 */
export function scoreStakeholderInfluence(rawData: unknown): StakeholderPerspective | null {
  const d = toRecord(rawData);
  if (!d) return null;
  const stakeholderRaw = asStr(d['stakeholder']);
  if (!(ALL_STAKEHOLDER_TYPES as readonly string[]).includes(stakeholderRaw)) return null;
  const stakeholder = stakeholderRaw as AnalysisStakeholderType;
  const impactRaw = asStr(d['impact']).toLowerCase();
  const validImpacts = ['positive', 'negative', 'neutral', 'mixed'] as const;
  const impact = (validImpacts as readonly string[]).includes(impactRaw)
    ? (impactRaw as StakeholderPerspective['impact'])
    : 'neutral';
  const severityRaw = asStr(d['severity']).toLowerCase();
  const validSeverities = ['high', 'medium', 'low'] as const;
  const severity = (validSeverities as readonly string[]).includes(severityRaw)
    ? (severityRaw as StakeholderPerspective['severity'])
    : 'medium';
  return {
    stakeholder,
    impact,
    severity,
    reasoning: asStr(d['reasoning']),
    evidence: asStrArr(d['evidence']),
  };
}
 
/**
 * Build a StakeholderOutcomeMatrix row for a single parliamentary action.
 * Derives outcomes from per-stakeholder scores: score > 0.6 → winner,
 * score < 0.4 → loser, otherwise neutral.
 *
 * @param action - The parliamentary action being assessed
 * @param scores - Per-stakeholder importance scores (0-1); defaults to 0.5
 * @param confidence - Confidence level for the outcome assessments
 * @returns A StakeholderOutcomeMatrix row
 */
export function buildStakeholderOutcomeMatrix(
  action: string,
  scores: Partial<Record<AnalysisStakeholderType, number>> = {},
  confidence: StakeholderOutcomeMatrix['confidence'] = 'medium'
): StakeholderOutcomeMatrix {
  const outcomes = Object.fromEntries(
    ALL_STAKEHOLDER_TYPES.map((stakeholder) => {
      const score = scores[stakeholder] ?? 0.5;
      const outcome: 'winner' | 'loser' | 'neutral' =
        score > 0.6 ? 'winner' : score < 0.4 ? 'loser' : 'neutral';
      return [stakeholder, outcome];
    })
  ) as Record<AnalysisStakeholderType, 'winner' | 'loser' | 'neutral'>;
  return { action, outcomes, confidence };
}
 
/**
 * Map an array of StakeholderPerspective objects to a simple influence ranking.
 * Returns stakeholder types sorted by severity (high → medium → low), then by
 * impact direction (negative before positive, as negative impacts require more
 * political attention).
 *
 * @param perspectives - Array of stakeholder perspectives to rank
 * @returns Stakeholder types sorted by influence priority
 */
export function rankStakeholdersByInfluence(
  perspectives: readonly StakeholderPerspective[]
): AnalysisStakeholderType[] {
  const severityWeight: Record<StakeholderPerspective['severity'], number> = {
    high: 3,
    medium: 2,
    low: 1,
  };
  const impactWeight: Record<StakeholderPerspective['impact'], number> = {
    negative: 3,
    mixed: 2,
    positive: 1,
    neutral: 0,
  };
  return [...perspectives]
    .sort((a, b) => {
      const sw = severityWeight[b.severity] - severityWeight[a.severity];
      if (sw !== 0) return sw;
      const iw = impactWeight[b.impact] - impactWeight[a.impact];
      Eif (iw !== 0) return iw;
      // Deterministic tie-breaker: canonical ALL_STAKEHOLDER_TYPES order
      return (
        ALL_STAKEHOLDER_TYPES.indexOf(a.stakeholder) - ALL_STAKEHOLDER_TYPES.indexOf(b.stakeholder)
      );
    })
    .map((p) => p.stakeholder);
}