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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 | 36x 36x 36x 36x 36x 36x 77x 77x 7x 7x 212x 36x 36x 253x 253x 184x 3318x 3318x 184x 184x 3134x 128x 783x 142x 2535x 24x 24x 24x 24x 24x 22x 22x 22x 21x 23x 23x 23x 23x 18x 10x 2x 8x 8x 8x 8x 8x 8x 25x 25x 25x 19x 19x 19x 19x 24x 24x 24x 7x 17x 17x 17x 17x 6x 11x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 1x 22x 22x 22x 22x 22x 24x 24x 24x 24x 23x 14x 14x 23x 23x 8x 8x 25x 25x 5x 20x 19x 24x 24x 17x 17x 17x 17x 23x 23x 23x 23x 23x 23x 22x 22x 22x 142x 142x 142x 142x 142x 142x 24x 24x 11x 24x 11x 24x 11x 11x 11x 24x 25x 25x 24x 24x 23x 23x 23x 46x 142x 142x 142x 55x 55x 55x 55x 55x 142x 142x 142x 142x 24x 1x 24x 1x 24x 24x 23x 11x 23x 23x 23x 25x 25x 25x 24x 24x 24x 23x 23x 23x 23x 23x 23x 142x 142x 142x 142x 24x 10x 24x 24x 24x 10x 24x 24x 23x 10x 23x 23x 25x 25x 25x 24x 24x 24x 23x 23x 23x 23x 23x 23x 142x 142x 142x 142x 142x 142x 142x 118x 63x 184x 184x 184x 171x 154x 151x 135x 142x 24x 24x 24x 23x 23x 23x 25x 25x 25x 24x 24x 24x 23x 23x 23x 23x 23x 23x 142x 142x 142x 142x 36x 23x 23x 138x 23x 138x 23x 23x 138x 208x 23x 23x 23x 23x 4x | /**
* @module analysis-framework/political-risk-assessment
* @description Political risk scoring engine implementing Likelihood × Impact
* risk assessment for parliamentary documents.
*
* Inspired by ISMS Risk_Assessment_Methodology.md (Quantitative risk scoring),
* adapted for political intelligence analysis of Swedish parliamentary context.
*
* ## Risk Categories
* - Coalition Stability — Government collapse or realignment risk
* - Policy Implementation — Policy failure or stalling risk
* - Democratic Process — Threat to democratic norms and institutions
* - Economic Policy — Fiscal/monetary policy decision risk
* - Social Cohesion — Societal division or unrest risk
* - International Standing — Sweden's international position risk
*
* ## Scoring Formula
* Risk Score = likelihood_probability × impact_weight × 10
* With current scales (almost-certain=0.90, transformative=10), the
* practical maximum is 90. Values are clamped to [0, 100] for safety.
*
* The engine is **pure** — deterministic for the same input, no side effects.
*
* @author Hack23 AB
* @license Apache-2.0
*/
import type { RawDocument, CIAContext } from '../data-transformers/types.js';
import type {
PoliticalRiskAssessment,
PoliticalRiskProfile,
PoliticalRiskCategory,
LikelihoodLevel,
RiskImpactLevel,
} from './methodology-types.js';
import {
LIKELIHOOD_PROBABILITY,
IMPACT_WEIGHT,
} from './methodology-types.js';
// ---------------------------------------------------------------------------
// Keyword banks per risk category
// ---------------------------------------------------------------------------
/** Keywords signalling coalition stability risk */
const COALITION_RISK_KEYWORDS: readonly string[] = [
'tidöavtal', 'samarbetspartier', 'sd-stöd', 'partiledare',
'oenighet', 'spricka', 'misstroendevotum', 'misstroende',
'koalitionskris', 'budgetomröstning', 'budgetkompromiss',
'coalition', 'confidence vote', 'no-confidence', 'government crisis',
];
/** Keywords signalling policy implementation risk */
const POLICY_RISK_KEYWORDS: readonly string[] = [
'remissrunda', 'parlamentarisk beredning', 'utredning', 'betänkande',
'genomförande', 'implementering', 'lagstiftningsprocess',
'opposition blockerar', 'riksdagen avslår', 'avslag',
'implementation', 'legislative process', 'parliamentary approval', 'blocked',
];
/** Keywords signalling democratic process risk */
const DEMOCRATIC_RISK_KEYWORDS: readonly string[] = [
'grundlag', 'konstitutionsutskott', 'KU-granskning', 'demokrati',
'offentlighetsprincipen', 'transparens', 'yttrandefrihet', 'pressfrihet',
'vallag', 'rösträtt', 'minoritetsskydd',
'constitutional', 'democratic', 'transparency', 'freedom of press',
'voting rights', 'minority rights', 'rule of law', 'rättsstat',
];
/** Keywords signalling economic policy risk */
const ECONOMIC_RISK_KEYWORDS: readonly string[] = [
'statsbudget', 'budgetproposition', 'skatt', 'inflation', 'ränta',
'konjunktur', 'BNP', 'statsskuld', 'underskott', 'surplus',
'miljoner', 'miljarder', 'penningpolitik', 'riksbanken',
'fiscal', 'monetary', 'GDP', 'debt', 'deficit', 'tax', 'interest rate',
];
/** Keywords signalling social cohesion risk */
const SOCIAL_RISK_KEYWORDS: readonly string[] = [
'segregation', 'diskriminering', 'jämlikhet', 'ojämlikhet',
'välfärd', 'socialbidrag', 'fattigdom', 'integration',
'invandring', 'flyktingar', 'social oro', 'strejk',
'discrimination', 'equality', 'welfare', 'poverty', 'social unrest',
'migration', 'integration', 'vulnerable groups',
];
/** Keywords signalling international standing risk */
const INTERNATIONAL_RISK_KEYWORDS: readonly string[] = [
'NATO', 'FN', 'nordiskt samarbete', 'utrikespolitik',
'handelsavtal', 'sanktioner', 'diplomatisk', 'ambassad',
'internationella åtaganden', 'EU-direktiv', 'EU-förordning',
'treaty', 'international obligations', 'foreign policy', 'sanctions',
'diplomacy', 'Nordic cooperation', 'European Union',
];
// ---------------------------------------------------------------------------
// Likelihood assessment helpers
// ---------------------------------------------------------------------------
/**
* Normalize defection probability to 0–1 range.
* Accepts both fractional (0.35) and percent-style (35) values.
* Defensively handles non-finite and negative inputs.
*/
function normalizeDefectionProbability(raw: number): number {
Iif (!Number.isFinite(raw) || raw <= 0) return 0;
if (raw <= 1) return raw;
const percent = raw / 100;
return percent > 1 ? 1 : percent;
}
/**
* Derive normalized document type from RawDocument.
* Falls back from `doktyp` to `documentType`, lowercased and trimmed.
*/
function getDocType(doc: RawDocument): string {
return String(doc.doktyp ?? doc.documentType ?? '').toLowerCase().trim();
}
/** Committees with elevated social cohesion risk relevance */
const SOCIAL_COHESION_COMMITTEES = new Set(['SoU', 'SfU', 'AU']);
/** Committees with elevated social impact relevance */
const SOCIAL_IMPACT_COMMITTEES = new Set(['SoU', 'SfU']);
function getDocText(doc: RawDocument): string {
const fullContentText = doc.fullContent
? doc.fullContent.replace(/<[^>]+>/g, ' ')
: undefined;
return [
doc.titel, doc.rubrik, doc.undertitel, doc.title,
doc.summary, doc.notis, doc.fullText, fullContentText,
].filter(Boolean).join(' ');
}
function escapeRegExp(input: string): string {
return input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function keywordMatches(textLower: string, keyword: string): boolean {
// Use word-boundary matching for short/uppercase abbreviations to avoid
// false positives (e.g. 'EU' matching inside unrelated words).
const isShortAbbreviation = /^[A-ZÅÄÖ]{2,4}$/.test(keyword);
if (isShortAbbreviation) {
const pattern = new RegExp(`\\b${escapeRegExp(keyword.toLowerCase())}\\b`, 'i');
return pattern.test(textLower);
}
return textLower.includes(keyword.toLowerCase());
}
function containsAny(text: string, keywords: readonly string[]): boolean {
const lower = text.toLowerCase();
return keywords.some(kw => keywordMatches(lower, kw));
}
function countMatches(text: string, keywords: readonly string[]): number {
const lower = text.toLowerCase();
return keywords.filter(kw => keywordMatches(lower, kw)).length;
}
/**
* Assess coalition stability likelihood based on CIA data and document signals.
*/
function assessCoalitionLikelihood(doc: RawDocument, cia: CIAContext | undefined): LikelihoodLevel {
const text = getDocText(doc);
const keywordMatches = countMatches(text, COALITION_RISK_KEYWORDS);
const stability = cia?.coalitionStability?.stabilityScore;
const margin = cia?.coalitionStability?.majorityMargin;
// Very unstable coalition + crisis keywords → almost certain
if (stability !== undefined && stability < 30 && keywordMatches >= 2) return 'almost-certain';
// Unstable coalition with some signals → likely
Iif (stability !== undefined && stability < 50 && keywordMatches >= 1) return 'likely';
// Thin majority + any signal → possible
Iif (margin !== undefined && margin <= 2 && keywordMatches >= 1) return 'possible';
// Document mentions coalition dynamics → unlikely
if (keywordMatches >= 1) return 'unlikely';
return 'rare';
}
/**
* Assess policy implementation likelihood based on document type and content.
*/
function assessPolicyImplementationLikelihood(doc: RawDocument, cia: CIAContext | undefined): LikelihoodLevel {
const text = getDocText(doc);
const keywordMatches = countMatches(text, POLICY_RISK_KEYWORDS);
const docType = getDocType(doc);
// Committee reports are high-signal implementation inputs by default
if (docType === 'bet') return keywordMatches >= 1 ? 'almost-certain' : 'likely';
// Government propositions — assess implementation risk based on obstruction level
if (docType === 'prop') {
// When CIA context is absent, fall back to keyword-based assessment
// instead of hard-coding a default denial rate that could bias scores.
if (cia?.overallMotionDenialRate === undefined) {
return keywordMatches >= 1 ? 'possible' : 'unlikely';
}
const motionDenialRate = cia.overallMotionDenialRate;
// High denial rate means opposition is being blocked → government faces less obstruction
// → lower risk of policy failure. Low denial rate means opposition motions succeed
// more often → higher risk that government policies stall.
Eif (motionDenialRate > 90) return 'rare';
if (motionDenialRate < 50) return 'likely';
// Denial rate in [50, 90] — moderate obstruction level → possible risk
return 'possible';
}
// Interpellations signal policy criticism
Iif (docType === 'ip' && keywordMatches >= 1) return 'possible';
Iif (keywordMatches >= 2) return 'possible';
Iif (keywordMatches >= 1) return 'unlikely';
return 'rare';
}
/**
* Assess democratic process risk likelihood.
*/
function assessDemocraticProcessLikelihood(doc: RawDocument): LikelihoodLevel {
const text = getDocText(doc);
const keywordMatches = countMatches(text, DEMOCRATIC_RISK_KEYWORDS);
if (doc.organ === 'KU') return 'almost-certain'; // KU documents always involve democratic oversight
Iif (keywordMatches >= 3) return 'likely';
Iif (keywordMatches >= 2) return 'possible';
Iif (keywordMatches >= 1) return 'unlikely';
return 'rare';
}
/**
* Assess economic policy risk likelihood.
*/
function assessEconomicPolicyLikelihood(doc: RawDocument, cia: CIAContext | undefined): LikelihoodLevel {
const text = getDocText(doc);
const keywordMatches = countMatches(text, ECONOMIC_RISK_KEYWORDS);
if (doc.organ === 'FiU') {
Eif (keywordMatches >= 2) return 'almost-certain';
return 'likely';
}
Iif (keywordMatches >= 3) return 'likely';
Iif (keywordMatches >= 2) return 'possible';
Iif (keywordMatches >= 1) return 'unlikely';
// High instability makes economic risk more likely even without direct signals
if (cia?.coalitionStability?.stabilityScore !== undefined && cia.coalitionStability.stabilityScore < 40) {
return 'unlikely';
}
return 'rare';
}
/**
* Assess social cohesion risk likelihood.
*/
function assessSocialCohesionLikelihood(doc: RawDocument): LikelihoodLevel {
const text = getDocText(doc);
const keywordMatches = countMatches(text, SOCIAL_RISK_KEYWORDS);
const committee = doc.organ ?? '';
Iif (SOCIAL_COHESION_COMMITTEES.has(committee) && keywordMatches >= 2) return 'likely';
Iif (keywordMatches >= 3) return 'likely';
Iif (keywordMatches >= 2) return 'possible';
Iif (keywordMatches >= 1) return 'unlikely';
return 'rare';
}
/**
* Assess international standing risk likelihood.
*/
function assessInternationalLikelihood(doc: RawDocument): LikelihoodLevel {
const text = getDocText(doc);
const keywordMatches = countMatches(text, INTERNATIONAL_RISK_KEYWORDS);
if (doc.organ === 'UU') {
Eif (keywordMatches >= 2) return 'almost-certain';
return 'likely';
}
Iif (doc.organ === 'FöU' && keywordMatches >= 1) return 'likely';
Iif (keywordMatches >= 3) return 'likely';
Iif (keywordMatches >= 2) return 'possible';
Iif (keywordMatches >= 1) return 'unlikely';
return 'rare';
}
// ---------------------------------------------------------------------------
// Impact assessment helpers
// ---------------------------------------------------------------------------
function assessCoalitionImpact(doc: RawDocument, cia: CIAContext | undefined): RiskImpactLevel {
const stability = cia?.coalitionStability?.stabilityScore;
const text = getDocText(doc);
const hasExplosiveContent = containsAny(text, ['misstroendevotum', 'misstroende', 'no-confidence']);
if (hasExplosiveContent) return 'transformative';
if (stability !== undefined && stability < 30) return 'critical';
Iif (stability !== undefined && stability < 50) return 'high';
return 'moderate';
}
function assessPolicyImpact(doc: RawDocument): RiskImpactLevel {
const docType = getDocType(doc);
if (docType === 'prop' || docType === 'bet') return 'high';
Iif (docType === 'sou' || docType === 'skr') return 'moderate';
return 'low';
}
function assessDemocraticImpact(doc: RawDocument): RiskImpactLevel {
const text = getDocText(doc);
if (containsAny(text, ['grundlag', 'konstitution', 'constitutional', 'fundamental law'])) {
return 'transformative';
}
if (doc.organ === 'KU') return 'critical';
return 'high';
}
function assessEconomicImpact(doc: RawDocument): RiskImpactLevel {
const docType = getDocType(doc);
if (doc.organ === 'FiU' && (docType === 'bet' || docType === 'prop')) return 'transformative';
const text = getDocText(doc);
Iif (containsAny(text, ['statsbudget', 'budgetproposition', 'BNP', 'GDP'])) return 'critical';
Iif (containsAny(text, ECONOMIC_RISK_KEYWORDS)) return 'high';
return 'moderate';
}
function assessSocialImpact(doc: RawDocument): RiskImpactLevel {
const committee = doc.organ ?? '';
Iif (SOCIAL_IMPACT_COMMITTEES.has(committee) && getDocType(doc) === 'prop') return 'high';
const text = getDocText(doc);
Iif (containsAny(text, ['segregation', 'diskriminering', 'discrimination', 'poverty', 'fattigdom'])) return 'high';
return 'moderate';
}
function assessInternationalImpact(doc: RawDocument): RiskImpactLevel {
if (doc.organ === 'UU' || doc.organ === 'FöU') return 'high';
const text = getDocText(doc);
Iif (containsAny(text, ['NATO', 'EU-direktiv', 'internationella åtaganden', 'treaty obligations'])) return 'high';
return 'moderate';
}
// ---------------------------------------------------------------------------
// Evidence extraction
// ---------------------------------------------------------------------------
function extractEvidence(doc: RawDocument, category: PoliticalRiskCategory, cia: CIAContext | undefined): string[] {
const evidence: string[] = [];
const docId = doc.dok_id;
Eif (docId) {
evidence.push(`Document: ${docId} (${getDocType(doc) || 'unknown'} in ${doc.organ ?? 'unknown'})`);
}
Iif (doc.speeches && doc.speeches.length > 0) {
const relevantSpeeches = doc.speeches
.filter(s => s.text && s.text.length > 0)
.slice(0, 2);
for (const speech of relevantSpeeches) {
if (speech.talare) {
evidence.push(`Speech by ${speech.talare} (${speech.parti ?? 'unknown party'})`);
}
}
}
// Category-specific evidence signals
switch (category) {
case 'coalition-stability':
Eif (doc.parti) evidence.push(`Party affiliation: ${doc.parti}`);
if (cia?.coalitionStability?.stabilityScore !== undefined) {
evidence.push(`CIA coalition stability score: ${cia.coalitionStability.stabilityScore}`);
}
if (cia?.coalitionStability?.majorityMargin !== undefined) {
evidence.push(`CIA majority margin: ${cia.coalitionStability.majorityMargin}`);
}
if (cia?.coalitionStability?.defectionProbability !== undefined) {
const rawDP = cia.coalitionStability.defectionProbability;
const normDP = normalizeDefectionProbability(rawDP);
evidence.push(`CIA defection probability: ${normDP} (raw=${rawDP})`);
}
break;
case 'democratic-process':
if (doc.organ === 'KU') evidence.push('Constitutional Committee (KU) involvement');
break;
case 'economic-policy':
if (doc.organ === 'FiU') evidence.push('Finance Committee (FiU) involvement');
break;
case 'international-standing':
if (doc.organ === 'UU') evidence.push('Foreign Affairs Committee (UU) involvement');
Iif (doc.organ === 'FöU') evidence.push('Defence Committee (FöU) involvement');
break;
default:
break;
}
const coalitionStability = cia?.coalitionStability;
const hasCoalitionContext =
coalitionStability !== undefined &&
(
coalitionStability.stabilityScore !== undefined ||
coalitionStability.majorityMargin !== undefined ||
coalitionStability.defectionProbability !== undefined
);
if (category !== 'coalition-stability' && hasCoalitionContext) {
const rawDP = coalitionStability.defectionProbability;
const normDP = rawDP !== undefined ? normalizeDefectionProbability(rawDP) : undefined;
const stabilityDisplay = coalitionStability.stabilityScore ?? 'N/A';
const majorityMarginDisplay = coalitionStability.majorityMargin ?? 'N/A';
evidence.push(`CIA coalition context: stability=${stabilityDisplay}, majorityMargin=${majorityMarginDisplay}, defectionProbability=${normDP ?? 'N/A'}`);
}
return evidence;
}
// ---------------------------------------------------------------------------
// Mitigating / escalating factors
// ---------------------------------------------------------------------------
function getMitigatingFactors(category: PoliticalRiskCategory, cia: CIAContext | undefined): string[] {
const factors: string[] = [];
const stability = cia?.coalitionStability?.stabilityScore;
switch (category) {
case 'coalition-stability':
if (stability !== undefined && stability >= 70) {
factors.push('Coalition stability score is high — low defection risk');
}
if (cia?.coalitionStability?.majorityMargin !== undefined && cia.coalitionStability.majorityMargin > 5) {
factors.push('Comfortable parliamentary majority reduces collapse risk');
}
// Always include a baseline mitigating factor
factors.push('Swedish constitutional norms require democratic transitions through electoral process');
break;
case 'policy-implementation':
if (cia?.overallMotionDenialRate !== undefined && cia.overallMotionDenialRate > 95) {
factors.push('Government controls parliament — high policy implementation success rate');
}
factors.push('Riksdag committee scrutiny provides quality assurance for legislation');
factors.push('Lagrådet (Council on Legislation) reviews government proposals for legal compliance');
break;
case 'democratic-process':
factors.push('Swedish constitutional review process (Lagrådet) provides safeguard');
factors.push('Riksdag committee scrutiny provides democratic oversight');
break;
case 'economic-policy':
factors.push('Riksbank independent mandate provides monetary policy buffer');
factors.push('EU fiscal frameworks constrain extreme fiscal departures');
break;
case 'social-cohesion':
factors.push('Swedish welfare state provides social safety net baseline');
factors.push('Strong civil society organisations monitor social policy impacts');
break;
case 'international-standing':
factors.push('NATO membership provides defence collective security guarantee');
factors.push('EU membership binds Sweden to multilateral obligations and norms');
break;
}
return factors;
}
function getEscalatingFactors(category: PoliticalRiskCategory, cia: CIAContext | undefined): string[] {
const factors: string[] = [];
const stability = cia?.coalitionStability?.stabilityScore;
switch (category) {
case 'coalition-stability':
if (stability !== undefined && stability < 40) {
factors.push('Coalition stability score is low — elevated defection and collapse risk');
}
{
const rawDefectionProbability = cia?.coalitionStability?.defectionProbability;
const normalizedDefectionProbability =
rawDefectionProbability !== undefined
? normalizeDefectionProbability(rawDefectionProbability)
: undefined;
if (normalizedDefectionProbability !== undefined && normalizedDefectionProbability > 0.2) {
factors.push('High defection probability detected in CIA coalition data');
}
}
// Always include a baseline escalating factor
factors.push('Parliamentary majority remains structurally vulnerable to individual defections over time');
break;
case 'policy-implementation':
if (stability !== undefined && stability < 50) {
factors.push('Unstable coalition may fail to pass legislation through parliament');
}
factors.push('Opposition coordination can delay or block legislative priorities');
break;
case 'democratic-process':
factors.push('Media narrative framing and public perception can accelerate democratic erosion');
factors.push('Social media amplification of anti-democratic rhetoric poses systemic risk');
break;
case 'economic-policy':
factors.push('Global economic uncertainty amplifies domestic policy risk');
factors.push('Coalition budget disagreements may block timely fiscal adjustments');
break;
case 'social-cohesion':
factors.push('Polarising political rhetoric elevates social division risk');
factors.push('Unequal distribution of policy costs can accelerate social fragmentation');
break;
case 'international-standing':
factors.push('Domestic political instability signals unpredictability to international partners');
factors.push('Divergence from EU/NATO positions increases geopolitical exposure');
break;
}
return factors;
}
// ---------------------------------------------------------------------------
// Confidence assessment
// ---------------------------------------------------------------------------
function assessConfidence(doc: RawDocument, cia: CIAContext | undefined): 'high' | 'medium' | 'low' {
let signals = 0;
if (doc.fullText || doc.fullContent) signals += 2;
if (doc.summary || doc.notis) signals += 1;
Iif (doc.speeches && doc.speeches.length > 0) signals += 1;
if (cia !== undefined) signals += 2;
if (signals >= 4) return 'high';
if (signals >= 2) return 'medium';
return 'low';
}
// ---------------------------------------------------------------------------
// Risk score computation
// ---------------------------------------------------------------------------
/**
* Compute a risk score from likelihood and impact.
*
* Formula: likelihood_probability × impact_weight × 10
* With current scales (almost-certain=0.90, transformative=10), the
* practical maximum is 90. Values are clamped to [0, 100] for safety.
*/
export function computeRiskScore(
likelihood: LikelihoodLevel,
impact: RiskImpactLevel,
): number {
const probability = LIKELIHOOD_PROBABILITY[likelihood];
const weight = IMPACT_WEIGHT[impact];
return Math.min(100, Math.max(0, Math.round(probability * weight * 10)));
}
/**
* Derive priority tier from risk score.
*/
export function deriveRiskPriority(score: number): 'critical' | 'high' | 'medium' | 'low' {
if (score >= 70) return 'critical';
if (score >= 50) return 'high';
if (score >= 30) return 'medium';
return 'low';
}
// ---------------------------------------------------------------------------
// Per-category assessment
// ---------------------------------------------------------------------------
function assessSingleCategory(
doc: RawDocument,
cia: CIAContext | undefined,
category: PoliticalRiskCategory,
): PoliticalRiskAssessment {
let likelihood: LikelihoodLevel;
let impact: RiskImpactLevel;
switch (category) {
case 'coalition-stability':
likelihood = assessCoalitionLikelihood(doc, cia);
impact = assessCoalitionImpact(doc, cia);
break;
case 'policy-implementation':
likelihood = assessPolicyImplementationLikelihood(doc, cia);
impact = assessPolicyImpact(doc);
break;
case 'democratic-process':
likelihood = assessDemocraticProcessLikelihood(doc);
impact = assessDemocraticImpact(doc);
break;
case 'economic-policy':
likelihood = assessEconomicPolicyLikelihood(doc, cia);
impact = assessEconomicImpact(doc);
break;
case 'social-cohesion':
likelihood = assessSocialCohesionLikelihood(doc);
impact = assessSocialImpact(doc);
break;
case 'international-standing':
likelihood = assessInternationalLikelihood(doc);
impact = assessInternationalImpact(doc);
break;
}
const riskScore = computeRiskScore(likelihood, impact);
const priority = deriveRiskPriority(riskScore);
const confidence = assessConfidence(doc, cia);
return {
riskCategory: category,
likelihood,
impact,
riskScore,
priority,
evidence: extractEvidence(doc, category, cia),
confidence,
mitigatingFactors: getMitigatingFactors(category, cia),
escalatingFactors: getEscalatingFactors(category, cia),
};
}
// ---------------------------------------------------------------------------
// All categories
// ---------------------------------------------------------------------------
const ALL_RISK_CATEGORIES: readonly PoliticalRiskCategory[] = [
'coalition-stability',
'policy-implementation',
'democratic-process',
'economic-policy',
'social-cohesion',
'international-standing',
];
// ---------------------------------------------------------------------------
// Composite risk score
// ---------------------------------------------------------------------------
/**
* Compute a composite risk score across all six categories.
* Weighted by priority tier: critical×1.0, high×0.7, medium×0.5, low×0.3.
*/
function computeCompositeRiskScore(assessments: PoliticalRiskAssessment[]): number {
Iif (assessments.length === 0) return 0;
const priorityWeights: Readonly<Record<string, number>> = {
critical: 1.0, high: 0.7, medium: 0.5, low: 0.3,
};
const totalWeight = assessments.reduce((sum, a) => sum + (priorityWeights[a.priority] ?? 0.3), 0);
const weightedSum = assessments.reduce(
(sum, a) => sum + a.riskScore * (priorityWeights[a.priority] ?? 0.3),
0,
);
return Math.min(100, Math.max(0, Math.round(weightedSum / totalWeight)));
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
* Assess political risk for a parliamentary document across all 6 risk categories.
*
* Applies the ISMS-inspired Likelihood × Impact methodology to each category
* and returns a complete risk profile with composite scoring and priority ranking.
*
* The function is **pure** — deterministic for the same input, no side effects.
*
* @param doc - The parliamentary document to assess
* @param cia - Optional CIA context (coalition stability data improves accuracy)
* @returns Complete political risk profile with per-category assessments
*
* @example
* ```typescript
* const profile = assessPoliticalRisk(doc, ciaContext);
* console.log(profile.overallRiskLevel); // 'critical' | 'high' | 'medium' | 'low'
* console.log(profile.compositeRiskScore); // 0–100
* console.log(profile.dominantRisk); // highest-priority category
* ```
*/
export function assessPoliticalRisk(
doc: RawDocument,
cia?: CIAContext,
): PoliticalRiskProfile {
const riskAssessments = ALL_RISK_CATEGORIES.map(category =>
assessSingleCategory(doc, cia, category)
);
// Sort by risk score descending to identify dominant risk
const sorted = [...riskAssessments].sort((a, b) => b.riskScore - a.riskScore);
const dominantRisk = sorted[0]?.riskCategory ?? 'policy-implementation';
const compositeRiskScore = computeCompositeRiskScore(riskAssessments);
const overallRiskLevel = deriveRiskPriority(compositeRiskScore);
return {
riskAssessments,
dominantRisk,
compositeRiskScore,
overallRiskLevel,
};
}
/**
* Assess political risk for a specific category only.
*
* Use when you need a targeted assessment for a single risk dimension
* rather than the full 6-category profile.
*
* @param doc - The parliamentary document to assess
* @param category - The specific risk category to assess
* @param cia - Optional CIA context
* @returns Risk assessment for the specified category
*/
export function assessSingleRiskCategory(
doc: RawDocument,
category: PoliticalRiskCategory,
cia?: CIAContext,
): PoliticalRiskAssessment {
return assessSingleCategory(doc, cia, category);
}
|