All files / src/generators/pipeline analysis-classification.ts

97.33% Statements 73/75
67.5% Branches 27/40
93.33% Functions 14/15
97.22% Lines 70/72

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                                                                                  7x   7x   7x   7x     7x 7x 7x 7x 7x 7x   7x 7x 7x     7x 7x 7x 7x 7x     7x                               9x 9x 9x 9x 9x 9x 9x           9x             9x   9x                                                                                                                       6x 6x 6x   6x                                                                                                 5x 5x 5x     5x       7x         7x 5x   7x       5x 3x     5x                                         3x                                   5x 5x 5x   5x       25x   5x 5x 5x 5x 5x   5x                                                                                               4x 4x 4x   4x   4x   4x 4x                                                                               4x 2x     2x 4x 2x   2x                                 7x              
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/Pipeline/AnalysisClassification
 * @description Classification analysis method builders for the analysis pipeline.
 *
 * Contains markdown builders for the **Classification** analysis method group:
 * - `significance-classification` — political significance scoring
 * - `impact-matrix` — multi-dimensional impact assessment
 * - `actor-mapping` — political actor classification
 * - `forces-analysis` — political forces balance analysis
 * - `significance-scoring` — 5-dimension EP event significance scoring
 */
 
import {
  assessPoliticalSignificance,
  buildImpactMatrix,
  classifyPoliticalActors,
  analyzePoliticalForces,
} from '../../utils/political-classification.js';
import {
  scoreSignificance,
  scoreBatch,
  formatBatchMarkdown,
} from '../../utils/significance-scoring.js';
import {
  sanitizeCell,
  safeArr,
  toClassificationInput,
  buildMarkdownHeader,
  impactToNum,
  impactIndicator,
  highestImpactDimension,
} from './analysis-helpers.js';
import type { MarkdownBuilder } from './analysis-helpers.js';
import type { AnalysisMethod } from './analysis-stage.js';
 
// ─── Heuristic scoring thresholds for EP event data ───────────────────────────
 
/** Event-count threshold above which parliamentary significance is elevated */
const EVENT_VOLUME_HIGH_THRESHOLD = 5;
/** Event-count threshold above which institutional relevance is elevated */
const EVENT_VOLUME_VERY_HIGH_THRESHOLD = 10;
/** Procedure-count threshold above which policy impact is elevated */
const PROCEDURE_VOLUME_THRESHOLD = 3;
/** Adopted-text-count threshold above which public interest is elevated */
const ADOPTED_TEXT_VOLUME_THRESHOLD = 2;
 
/** Base scores for EP event dimensions when data volume is high / low */
const EVENT_PARLIAMENTARY_HIGH = 6;
const EVENT_PARLIAMENTARY_LOW = 4;
const EVENT_POLICY_HIGH = 6;
const EVENT_POLICY_LOW = 3;
const EVENT_PUBLIC_HIGH = 5;
const EVENT_PUBLIC_LOW = 3;
/** Default temporal urgency for events (mid-range, adjusted at AI scoring) */
const EVENT_DEFAULT_URGENCY = 5;
const EVENT_INSTITUTIONAL_HIGH = 7;
const EVENT_INSTITUTIONAL_LOW = 4;
 
/** Default dimension scores for adopted texts (plenary-approved) */
const ADOPTED_PARLIAMENTARY = 7;
const ADOPTED_POLICY = 6;
const ADOPTED_PUBLIC = 5;
const ADOPTED_URGENCY = 4;
const ADOPTED_INSTITUTIONAL = 6;
 
/** Analysis method identifier for significance scoring */
export const METHOD_SIGNIFICANCE_SCORING_ID = 'significance-scoring' as const;
 
// ─── Per-method markdown builders ────────────────────────────────────────────
 
/**
 * Build markdown for the significance classification method.
 * Scores and ranks legislative items by political significance.
 *
 * @param fetchedData - Raw fetched EP data
 * @param date - Analysis date
 * @returns Markdown content string
 */
export function buildSignificanceClassificationMarkdown(
  fetchedData: Record<string, unknown>,
  date: string
): string {
  const input = toClassificationInput(fetchedData);
  const significance = assessPoliticalSignificance(input);
  const events = safeArr(fetchedData, 'events');
  const docs = safeArr(fetchedData, 'documents');
  const procedures = safeArr(fetchedData, 'procedures');
  const adoptedTexts = safeArr(fetchedData, 'adoptedTexts');
  const header = buildMarkdownHeader(
    'significance-classification',
    date,
    significance === 'routine' ? 'medium' : 'high'
  );
 
  const sigMap: Record<string, number> = {
    historic: 0.95,
    critical: 0.8,
    significant: 0.65,
    notable: 0.45,
    routine: 0.25,
  };
  const sigScore = sigMap[significance] ?? 0.25;
 
  return (
    header +
    `# Political Significance Classification
 
## Overall Significance: **${significance.toUpperCase()}**
 
\`\`\`mermaid
quadrantChart
    title Political Significance Assessment — ${date}
    x-axis Low Volume --> High Volume
    y-axis Low Impact --> High Impact
    quadrant-1 Critical Watch
    quadrant-2 Strategic Priority
    quadrant-3 Monitor
    quadrant-4 Routine Track
    Current Assessment: [${sigScore.toFixed(2)}, ${sigScore.toFixed(2)}]
    Events Signal: [${Math.min(events.length / 20, 0.95).toFixed(2)}, 0.60]
    Documents Signal: [${Math.min(docs.length / 20, 0.95).toFixed(2)}, 0.55]
    Procedures Signal: [${Math.min(procedures.length / 10, 0.95).toFixed(2)}, 0.75]
    Adopted Texts: [${Math.min(adoptedTexts.length / 10, 0.95).toFixed(2)}, 0.85]
\`\`\`
 
## 5-Signal Model Scores
 
| Signal | Raw Data | Score |
|--------|----------|-------|
| Volume | ${events.length} events, ${docs.length} documents | ${Math.min((events.length + docs.length) / 10, 5).toFixed(1)}/5 |
| Pipeline | ${procedures.length} procedures | ${Math.min(procedures.length / 5, 5).toFixed(1)}/5 |
| Output | ${adoptedTexts.length} adopted texts | ${Math.min(adoptedTexts.length / 5, 5).toFixed(1)}/5 |
| Anomalies | Pattern deviation detection | — |
| Coalition | Group alignment analysis | — |
 
## Data Summary
 
| Metric | Value |
|--------|-------|
| Computed significance | ${significance.toUpperCase()} |
| Total data points | ${events.length + docs.length + procedures.length + adoptedTexts.length} |
| Events | ${events.length} |
| Documents | ${docs.length} |
| Procedures | ${procedures.length} |
| Adopted texts | ${adoptedTexts.length} |
| Date | ${date} |
 
## Date: ${date}
`
  );
}
 
/**
 * Build markdown for the impact matrix method.
 *
 * @param fetchedData - Raw fetched EP data
 * @param date - Analysis date
 * @returns Markdown content string
 */
export function buildImpactMatrixMarkdown(
  fetchedData: Record<string, unknown>,
  date: string
): string {
  const input = toClassificationInput(fetchedData);
  const matrix = buildImpactMatrix(input);
  const header = buildMarkdownHeader('impact-matrix', date, 'medium');
 
  return (
    header +
    `# Political Impact Matrix
 
## Overall Significance: **${matrix.overallSignificance.toUpperCase()}**
 
\`\`\`mermaid
pie title Impact Distribution by Dimension — ${date}
    "Legislative" : ${impactToNum(matrix.legislativeImpact)}
    "Coalition" : ${impactToNum(matrix.coalitionImpact)}
    "Public Opinion" : ${impactToNum(matrix.publicOpinionImpact)}
    "Institutional" : ${impactToNum(matrix.institutionalImpact)}
    "Economic" : ${impactToNum(matrix.economicImpact)}
\`\`\`
 
## Impact Dimensions
 
| Dimension | Level | Indicator | Numeric |
|-----------|-------|-----------|---------|
| Legislative | ${matrix.legislativeImpact} | ${impactIndicator(matrix.legislativeImpact)} | ${impactToNum(matrix.legislativeImpact)} |
| Coalition | ${matrix.coalitionImpact} | ${impactIndicator(matrix.coalitionImpact)} | ${impactToNum(matrix.coalitionImpact)} |
| Public Opinion | ${matrix.publicOpinionImpact} | ${impactIndicator(matrix.publicOpinionImpact)} | ${impactToNum(matrix.publicOpinionImpact)} |
| Institutional | ${matrix.institutionalImpact} | ${impactIndicator(matrix.institutionalImpact)} | ${impactToNum(matrix.institutionalImpact)} |
| Economic | ${matrix.economicImpact} | ${impactIndicator(matrix.economicImpact)} | ${impactToNum(matrix.economicImpact)} |
 
## Summary
 
| Metric | Value |
|--------|-------|
| Overall significance | ${matrix.overallSignificance.toUpperCase()} |
| Highest impact | ${highestImpactDimension(matrix)} |
| Date | ${date} |
 
## Date: ${date}
`
  );
}
 
/**
 * Build markdown for the actor mapping method.
 *
 * @param fetchedData - Raw fetched EP data
 * @param date - Analysis date
 * @returns Markdown content string
 */
export function buildActorMappingMarkdown(
  fetchedData: Record<string, unknown>,
  date: string
): string {
  const input = toClassificationInput(fetchedData);
  const actors = classifyPoliticalActors(input);
  const header = buildMarkdownHeader('actor-mapping', date, actors.length > 0 ? 'medium' : 'low');
 
  const actorRows =
    actors.length > 0
      ? actors
          .map(
            (a) =>
              `| ${sanitizeCell(a.name)} | ${sanitizeCell(a.actorType)} | ${sanitizeCell(String(a.influence))} | ${sanitizeCell(a.position)} | ${sanitizeCell(a.role)} |`
          )
          .join('\n')
      : '| — | — | — | — | — |';
 
  const actorTypes = actors.length > 0 ? [...new Set(actors.map((a) => a.actorType))] : [];
  const typeCounts = actorTypes.map((t) => ({
    type: t,
    count: actors.filter((a) => a.actorType === t).length,
  }));
 
  const mermaidPie =
    typeCounts.length > 0
      ? typeCounts.map((tc) => `    "${tc.type}" : ${tc.count}`).join('\n')
      : '    "No actors classified" : 1';
 
  return (
    header +
    `# Political Actor Mapping
 
## Actors Identified: ${actors.length}
 
\`\`\`mermaid
pie title Actor Type Distribution — ${date}
${mermaidPie}
\`\`\`
 
## Actor Classification
 
| Actor | Type | Influence | Position | Role |
|-------|------|-----------|----------|------|
${actorRows}
 
## Type Counts
 
| Type | Count |
|------|-------|
${typeCounts.length > 0 ? typeCounts.map((tc) => `| ${tc.type} | ${tc.count} |`).join('\n') : '| — | 0 |'}
 
## Date: ${date}
`
  );
}
 
/**
 * Build markdown for the political forces analysis method.
 *
 * @param fetchedData - Raw fetched EP data
 * @param date - Analysis date
 * @returns Markdown content string
 */
export function buildForcesAnalysisMarkdown(
  fetchedData: Record<string, unknown>,
  date: string
): string {
  const input = toClassificationInput(fetchedData);
  const forces = analyzePoliticalForces(input);
  const header = buildMarkdownHeader('forces-analysis', date, 'medium');
 
  const forceRow = (
    name: string,
    f: { strength: number; trend: string; keyActors: readonly string[]; confidence: string }
  ) =>
    `| ${sanitizeCell(name)} | ${sanitizeCell(f.trend)} | ${(f.strength * 100).toFixed(0)}% | ${f.keyActors.length > 0 ? sanitizeCell(f.keyActors.join(', ')) : '—'} | ${sanitizeCell(f.confidence)} |`;
 
  const cp = Math.max(1, Math.min(99, Math.round(forces.coalitionPower.strength * 100)));
  const op = Math.max(1, Math.min(99, Math.round(forces.oppositionPower.strength * 100)));
  const ib = Math.max(1, Math.min(99, Math.round(forces.institutionalBarriers.strength * 100)));
  const pp = Math.max(1, Math.min(99, Math.round(forces.publicPressure.strength * 100)));
  const ei = Math.max(1, Math.min(99, Math.round(forces.externalInfluences.strength * 100)));
 
  return (
    header +
    `# Political Forces Analysis
 
\`\`\`mermaid
pie title Political Force Distribution — ${date}
    "Coalition Power" : ${cp}
    "Opposition Power" : ${op}
    "Institutional Barriers" : ${ib}
    "Public Pressure" : ${pp}
    "External Influences" : ${ei}
\`\`\`
 
## Forces Data
 
| Force | Trend | Strength | Key Actors | Confidence |
|-------|-------|----------|------------|------------|
${forceRow('Coalition Power', forces.coalitionPower)}
${forceRow('Opposition Power', forces.oppositionPower)}
${forceRow('Institutional Barriers', forces.institutionalBarriers)}
${forceRow('Public Pressure', forces.publicPressure)}
${forceRow('External Influences', forces.externalInfluences)}
 
## Balance
 
| Metric | Value |
|--------|-------|
| Coalition vs Opposition | ${cp}% vs ${op}% |
| Dominant force | ${cp > op ? 'Coalition' : op > cp ? 'Opposition' : 'Balanced'} |
| Date | ${date} |
 
## Date: ${date}
`
  );
}
 
/**
 * Build markdown for the significance-scoring method.
 * Uses the 5-dimension scoring engine to score all EP events.
 *
 * @param fetchedData - Raw fetched EP data
 * @param date - Analysis date
 * @returns Markdown content string
 */
export function buildSignificanceScoringMarkdown(
  fetchedData: Record<string, unknown>,
  date: string
): string {
  const events = safeArr(fetchedData, 'events');
  const adoptedTexts = safeArr(fetchedData, 'adoptedTexts');
  const procedures = safeArr(fetchedData, 'procedures');
 
  const header = buildMarkdownHeader(METHOD_SIGNIFICANCE_SCORING_ID, date, 'medium');
 
  const inputs = [
    ...events.map((e) => {
      const ev = e as Record<string, unknown>;
      return {
        title: String(ev['title'] ?? ev['label'] ?? 'Unknown Event'),
        reference: String(ev['id'] ?? ''),
        parliamentarySignificance: Math.min(
          10,
          events.length > EVENT_VOLUME_HIGH_THRESHOLD
            ? EVENT_PARLIAMENTARY_HIGH
            : EVENT_PARLIAMENTARY_LOW
        ),
        policyImpact: Math.min(
          10,
          procedures.length > PROCEDURE_VOLUME_THRESHOLD ? EVENT_POLICY_HIGH : EVENT_POLICY_LOW
        ),
        publicInterest: Math.min(
          10,
          adoptedTexts.length > ADOPTED_TEXT_VOLUME_THRESHOLD ? EVENT_PUBLIC_HIGH : EVENT_PUBLIC_LOW
        ),
        temporalUrgency: EVENT_DEFAULT_URGENCY,
        institutionalRelevance: Math.min(
          10,
          events.length > EVENT_VOLUME_VERY_HIGH_THRESHOLD
            ? EVENT_INSTITUTIONAL_HIGH
            : EVENT_INSTITUTIONAL_LOW
        ),
      };
    }),
    ...adoptedTexts.map((t) => {
      const at = t as Record<string, unknown>;
      return {
        title: String(at['title'] ?? at['label'] ?? 'Adopted Text'),
        reference: String(at['id'] ?? ''),
        parliamentarySignificance: ADOPTED_PARLIAMENTARY,
        policyImpact: ADOPTED_POLICY,
        publicInterest: ADOPTED_PUBLIC,
        temporalUrgency: ADOPTED_URGENCY,
        institutionalRelevance: ADOPTED_INSTITUTIONAL,
      };
    }),
  ];
 
  if (inputs.length === 0) {
    return `${header}# 📈 Significance Scoring — ${date}\n\nNo events or adopted texts available for scoring.\n`;
  }
 
  const batch = scoreBatch(inputs);
  const alignedScores = inputs.map((input) => scoreSignificance(input));
  const batchTable = formatBatchMarkdown(inputs, alignedScores);
 
  return `${header}# 📈 Significance Scoring — ${date}
 
## Summary
 
| Decision | Count |
|----------|:-----:|
| 📰 Publish | ${batch.summary.publish} |
| 📋 Hold | ${batch.summary.hold} |
| 🗄️ Skip | ${batch.summary.skip} |
 
## Batch Scoring
 
${batchTable}
`;
}
 
/** All classification method builders keyed by their AnalysisMethod identifier */
export const CLASSIFICATION_BUILDERS: Readonly<Partial<Record<AnalysisMethod, MarkdownBuilder>>> = {
  'significance-classification': buildSignificanceClassificationMarkdown,
  'impact-matrix': buildImpactMatrixMarkdown,
  'actor-mapping': buildActorMappingMarkdown,
  'forces-analysis': buildForcesAnalysisMarkdown,
  [METHOD_SIGNIFICANCE_SCORING_ID]: buildSignificanceScoringMarkdown,
};