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 | 25x 25x 25x 25x 25x 25x 25x 25x 425x 3600x 25x 25x 25x 25x 125x 125x 355x 355x 2x 353x 118782x 66778x 432x 21x 21x 273x | /**
* @module WorldBank/Context
* @description Economic context provider for news generation and political intelligence.
* Maps World Bank indicators to Swedish political policy areas, enabling enriched
* analysis that connects parliamentary decisions to economic outcomes.
*
* **SINGLE SOURCE OF TRUTH**: Indicator data is loaded from
* `analysis/worldbank/indicators-inventory.json` — the canonical machine-readable
* inventory. Both AI agents (`view` tool) and this TypeScript module consume the
* same JSON, ensuring consistency. To add or modify indicators, edit the JSON file
* only — no TypeScript changes are required, and updates are picked up on the next run.
*
* Used by agentic workflows and article quality enhancement to add economic depth
* to political reporting.
*
* @author Hack23 AB
* @license Apache-2.0
*/
import { readFileSync } from 'fs';
import { dirname, resolve } from 'path';
import { fileURLToPath } from 'url';
import type { Language } from './types/language.js';
import { COUNTRY_CODES } from './world-bank-client.js';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/** An economic indicator mapped to a policy area */
export interface EconomicIndicatorContext {
/** World Bank indicator ID */
readonly indicatorId: string;
/** Human-readable name */
readonly name: string;
/** Concise description for article context */
readonly description: string;
/** Swedish policy areas this indicator relates to */
readonly policyAreas: readonly string[];
/** Relevant Riksdag committees */
readonly committees: readonly string[];
/** Unit of measurement */
readonly unit: string;
}
/** Nordic country comparison set */
export interface NordicComparisonSet {
readonly countries: readonly string[];
readonly countryNames: Readonly<Record<string, string>>;
}
/** Localized economic section heading */
export interface EconomicSectionHeadings {
readonly economicContext: string;
readonly nordicComparison: string;
readonly policyImplications: string;
readonly country: string;
readonly unit: string;
}
// ---------------------------------------------------------------------------
// JSON inventory types (mirrors analysis/worldbank/indicators-inventory.json)
// ---------------------------------------------------------------------------
interface InventoryIndicator {
id: string;
key: string;
name: string;
unit: string;
description?: string;
policyAreas?: string[];
committees?: string[];
mcpTool?: string;
mcpParam?: string;
source?: number;
}
interface InventoryDomain {
label: string;
committees: string[];
indicatorCount: number;
indicators: InventoryIndicator[];
}
interface IndicatorInventory {
version: string;
totalIndicators: number;
domains: Record<string, InventoryDomain>;
}
// ---------------------------------------------------------------------------
// Load indicators from JSON inventory (single source of truth)
// ---------------------------------------------------------------------------
/**
* Resolve the path to the indicators inventory JSON.
* Works both when running from the repo root (`npx tsx scripts/...`) and
* from within the scripts directory.
*/
function resolveInventoryPath(): string {
try {
const thisDir = dirname(fileURLToPath(import.meta.url));
return resolve(thisDir, '..', 'analysis', 'worldbank', 'indicators-inventory.json');
} catch {
// Fallback for environments where import.meta.url is unavailable
return resolve(process.cwd(), 'analysis', 'worldbank', 'indicators-inventory.json');
}
}
/**
* Load and transform indicators from the JSON inventory file.
* Each indicator in the JSON is mapped to an EconomicIndicatorContext
* with description, policyAreas, and committees.
*/
function loadIndicatorsFromInventory(): readonly EconomicIndicatorContext[] {
try {
const raw = readFileSync(resolveInventoryPath(), 'utf-8');
const inventory: IndicatorInventory = JSON.parse(raw);
const indicators: EconomicIndicatorContext[] = [];
for (const domain of Object.values(inventory.domains)) {
for (const ind of domain.indicators) {
indicators.push({
indicatorId: ind.id,
name: ind.name,
description: ind.description ?? `${ind.name} — ${domain.label} indicator for Sweden.`,
policyAreas: ind.policyAreas ?? [domain.label.toLowerCase()],
committees: ind.committees ?? domain.committees,
unit: ind.unit,
});
}
}
return indicators;
} catch (err: unknown) {
const error =
err instanceof Error
? err
: new Error(`[world-bank-context] Failed to load indicators inventory: ${String(err)}`);
// Tests may intentionally mock or omit the inventory file.
// Preserve the existing fallback there, but fail fast elsewhere so
// builds cannot silently generate incomplete economic content.
if (process.env.NODE_ENV === 'test') {
return [];
}
console.error(`[world-bank-context] Failed to load indicators inventory: ${error.message}`);
throw error;
}
}
// ---------------------------------------------------------------------------
// Economic indicator mappings (loaded from JSON)
// ---------------------------------------------------------------------------
/**
* All World Bank indicators mapped to Swedish political policy areas.
* Loaded from `analysis/worldbank/indicators-inventory.json` — the single source of truth.
*
* To add indicators: edit the JSON file, NOT this module.
* Full inventory: analysis/worldbank/indicators-inventory.json
* Committee mapping: analysis/worldbank/indicator-policy-mapping.md
*/
export const ECONOMIC_INDICATORS: readonly EconomicIndicatorContext[] = loadIndicatorsFromInventory();
// ---------------------------------------------------------------------------
// Nordic comparison configuration
// ---------------------------------------------------------------------------
/** Standard Nordic + Germany comparison set for benchmarking Sweden */
export const NORDIC_COMPARISON: NordicComparisonSet = {
countries: [
COUNTRY_CODES.sweden,
COUNTRY_CODES.denmark,
COUNTRY_CODES.norway,
COUNTRY_CODES.finland,
COUNTRY_CODES.germany,
],
countryNames: {
[COUNTRY_CODES.sweden]: 'Sweden',
[COUNTRY_CODES.denmark]: 'Denmark',
[COUNTRY_CODES.norway]: 'Norway',
[COUNTRY_CODES.finland]: 'Finland',
[COUNTRY_CODES.germany]: 'Germany',
},
} as const;
// ---------------------------------------------------------------------------
// Localized headings for economic context sections
// ---------------------------------------------------------------------------
/**
* Localized section headings for economic context in articles.
* Follows the same pattern as EDITORIAL_PILLAR_HEADINGS.
*/
export const ECONOMIC_SECTION_HEADINGS: Readonly<Record<Language, EconomicSectionHeadings>> = {
en: {
economicContext: 'Economic Context',
nordicComparison: 'Nordic Comparison',
policyImplications: 'Policy Implications',
country: 'Country',
unit: 'Unit',
},
sv: {
economicContext: 'Ekonomisk kontext',
nordicComparison: 'Nordisk jämförelse',
policyImplications: 'Policyimplikationer',
country: 'Land',
unit: 'Enhet',
},
da: {
economicContext: 'Økonomisk kontekst',
nordicComparison: 'Nordisk sammenligning',
policyImplications: 'Politiske implikationer',
country: 'Land',
unit: 'Enhed',
},
no: {
economicContext: 'Økonomisk kontekst',
nordicComparison: 'Nordisk sammenligning',
policyImplications: 'Politiske implikasjoner',
country: 'Land',
unit: 'Enhet',
},
fi: {
economicContext: 'Taloudellinen konteksti',
nordicComparison: 'Pohjoismainen vertailu',
policyImplications: 'Poliittiset vaikutukset',
country: 'Maa',
unit: 'Yksikkö',
},
de: {
economicContext: 'Wirtschaftlicher Kontext',
nordicComparison: 'Nordischer Vergleich',
policyImplications: 'Politische Auswirkungen',
country: 'Land',
unit: 'Einheit',
},
fr: {
economicContext: 'Contexte économique',
nordicComparison: 'Comparaison nordique',
policyImplications: 'Implications politiques',
country: 'Pays',
unit: 'Unité',
},
es: {
economicContext: 'Contexto económico',
nordicComparison: 'Comparación nórdica',
policyImplications: 'Implicaciones políticas',
country: 'País',
unit: 'Unidad',
},
nl: {
economicContext: 'Economische context',
nordicComparison: 'Noordse vergelijking',
policyImplications: 'Beleidsimplicaties',
country: 'Land',
unit: 'Eenheid',
},
ar: {
economicContext: 'السياق الاقتصادي',
nordicComparison: 'المقارنة الاسكندنافية',
policyImplications: 'تداعيات السياسات',
country: 'الدولة',
unit: 'الوحدة',
},
he: {
economicContext: 'הקשר כלכלי',
nordicComparison: 'השוואה סקנדינבית',
policyImplications: 'השלכות מדיניות',
country: 'מדינה',
unit: 'יחידה',
},
ja: {
economicContext: '経済的背景',
nordicComparison: '北欧比較',
policyImplications: '政策的含意',
country: '国',
unit: '単位',
},
ko: {
economicContext: '경제적 맥락',
nordicComparison: '북유럽 비교',
policyImplications: '정책적 시사점',
country: '국가',
unit: '단위',
},
zh: {
economicContext: '经济背景',
nordicComparison: '北欧比较',
policyImplications: '政策影响',
country: '国家',
unit: '单位',
},
} as const;
// ---------------------------------------------------------------------------
// Utility functions
// ---------------------------------------------------------------------------
/**
* Get the localized economic section heading.
*
* @param lang - Language code
* @param section - Section key
* @returns Localized heading string
*/
export function getEconomicHeading(
lang: Language | string,
section: keyof EconomicSectionHeadings,
): string {
const headings = ECONOMIC_SECTION_HEADINGS[lang as Language] ?? ECONOMIC_SECTION_HEADINGS.en;
return headings[section];
}
/**
* Find relevant economic indicators for a given policy area or committee.
*
* @param query - Policy area or committee abbreviation to search for
* @returns Matching economic indicators
*/
export function findRelevantIndicators(query: string): readonly EconomicIndicatorContext[] {
const q = query.trim().toLowerCase();
if (q.length === 0) {
return [];
}
return ECONOMIC_INDICATORS.filter(
(indicator) =>
indicator.policyAreas.some((area) => area.toLowerCase().includes(q)) ||
indicator.committees.some((c) => c.toLowerCase() === q),
);
}
/**
* Get the World Bank API query parameters for Swedish economic indicators.
* Used by agentic workflows to know which indicators to fetch.
*
* @returns Array of { countryCode, indicatorId, name } for all configured indicators
*/
export function getSwedishIndicatorQueries(): readonly { countryCode: string; indicatorId: string; name: string }[] {
return ECONOMIC_INDICATORS.map((indicator) => ({
countryCode: COUNTRY_CODES.sweden,
indicatorId: indicator.indicatorId,
name: indicator.name,
}));
}
/**
* Detect economic context references in article content.
* Used by article quality enhancer to score economic depth.
*
* @param content - HTML or text content to analyze
* @returns True if economic context is present
*/
export function hasEconomicContext(content: string): boolean {
const text = content.toLowerCase();
const patterns: readonly RegExp[] = [
/\bgdp\b/i,
/\bunemployment\b/i,
/\binflation\b/i,
/\beconomic\s+(growth|context|impact)\b/i,
/\bworld\s+bank\b/i,
/\bbnp\b/i, // Swedish: bruttonationalprodukt
/\barbetslöshet/i, // Swedish: unemployment (arbetslöshet, arbetslösheten, etc.)
/\bekonomi/i, // Swedish: economy
/\bhandelsbalans/i, // Swedish: trade balance (handelsbalans, handelsbalansen, etc.)
/\bstatsskuld/i, // Swedish: national debt (statsskuld, statsskulden, etc.)
/\bförsvarsutgift/i, // Swedish: defense expenditure (försvarsutgift, försvarsutgifter, etc.)
/\bforskningsutgift/i, // Swedish: R&D expenditure (forskningsutgift, forskningsutgifter, etc.)
/\bmilitärut/i, // Swedish: military expenditure (militärutgift, etc.)
/\bskattein/i, // Swedish: tax revenue (skatteintäkt, skatteintäkter, etc.)
/\bgini/i, // GINI index
/\bco2\b/i, // CO2 emissions
/\bnato\s*2\s*%/i, // NATO 2% target
/\bförny(?:else)?bart?\s+energi/i, // Swedish: renewable energy (förnybar/förnyelsebar energi)
/\bbirth\s*rate\b/i,
/\bfertility\s*rate\b/i,
/\blife\s*expectancy\b/i,
/\bNY\.GDP/i, // World Bank indicator IDs
/\bSL\.UEM/i,
/\bFP\.CPI/i,
/\bMS\.MIL/i,
/\bGC\.TAX/i,
/\bSI\.POV\.GINI/i,
/\bEN\.ATM/i,
/\bSH\.XPD/i,
/\bSE\.XPD/i,
];
return patterns.some((pattern) => pattern.test(text));
}
|