All files / src/generators/strategies breaking-news-strategy.ts

95.14% Statements 98/103
85.5% Branches 59/69
100% Functions 6/6
94.62% Lines 88/93

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                                                                                      8x                                   25x 25x   21x 18x   21x 18x   21x 18x     21x                               18x   15x 15x 15x 15x 15x 15x 15x 15x   15x   13x 18x 18x 12x 12x   1x                   18x   15x       15x 13x 13x 13x 13x 13x 13x 13x                                                     22x   22x                                               6x 6x 3x 3x 3x   2x       2x     2x 2x 2x           2x   1x     4x 1x       4x     4x 3x 3x       1x         1x             1x 1x                                       9x                       9x             9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x                           25x 25x 25x 25x 25x 25x 25x 25x 21x 21x 18x     25x                     8x  
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Generators/Strategies/BreakingNewsStrategy
 * @description Article strategy for the Breaking News article type.
 * Uses a **feed-first** approach: EP feed endpoints (adopted texts, events,
 * procedures, MEPs) provide the primary news content, while analytical tools
 * (voting anomalies, coalition dynamics) supply optional context only.
 *
 * Precomputed statistics from `get_all_generated_stats` are **never** the
 * primary news content and are used solely for historical comparison.
 */
 
import type { EuropeanParliamentMCPClient } from '../../mcp/ep-mcp-client.js';
import { ArticleCategory } from '../../types/index.js';
import type { LanguageCode, BreakingNewsFeedData } from '../../types/index.js';
import { BREAKING_NEWS_TITLES, getLocalizedString } from '../../constants/languages.js';
import {
  fetchBreakingNewsFeedData,
  fetchVotingAnomalies,
  fetchCoalitionDynamics,
  loadFeedDataFromFile,
} from '../pipeline/fetch-stage.js';
import {
  buildBreakingNewsContent,
  scoreBreakingNewsSignificance,
  SIGNIFICANCE_THRESHOLD,
} from '../breaking-content.js';
import { buildDeepAnalysisSection } from '../deep-analysis-content.js';
import {
  buildBreakingAnalysis,
  buildBreakingSwot,
  buildBreakingDashboard,
  buildBreakingMindmap,
} from '../analysis-builders.js';
import { buildSwotSection } from '../swot-content.js';
import { buildDashboardSection } from '../dashboard-content.js';
import { buildIntelligenceMindmapSection } from '../mindmap-content.js';
import type { ArticleStrategy, ArticleData, ArticleMetadata } from './article-strategy.js';
import { pl } from '../../utils/metadata-utils.js';
 
/** Base keywords shared by all Breaking News articles */
const BREAKING_NEWS_BASE_KEYWORDS = [
  'European Parliament',
  'breaking news',
  'adopted texts',
  'legislative updates',
  'parliamentary events',
] as const;
 
/**
 * Extract content-aware keywords from breaking news feed data.
 *
 * Scans adopted text titles, event titles, and procedure titles for
 * topic-relevant terms that enrich SEO keywords beyond the static base set.
 *
 * @param feedData - Breaking news feed data (may be undefined)
 * @returns Deduplicated array of keywords including base + content-derived terms
 */
function buildBreakingKeywords(feedData: BreakingNewsFeedData | undefined): string[] {
  const keywords: string[] = [...BREAKING_NEWS_BASE_KEYWORDS];
  if (!feedData) return keywords;
 
  for (const text of feedData.adoptedTexts.slice(0, 5)) {
    Eif (text.title) keywords.push(text.title.slice(0, 60));
  }
  for (const evt of feedData.events.slice(0, 3)) {
    Eif (evt.title) keywords.push(evt.title.slice(0, 60));
  }
  for (const proc of feedData.procedures.slice(0, 3)) {
    Eif (proc.title) keywords.push(proc.title.slice(0, 60));
  }
 
  return [...new Set(keywords)];
}
 
/**
 * Build a content-aware description from breaking news feed data.
 * Summarises the count of adopted texts, events, procedures, and MEP updates
 * and highlights the first adopted text title when available.
 *
 * @param date - Publication date
 * @param feedData - Breaking news feed data (may be undefined)
 * @returns SEO-friendly description string (≤ 200 chars)
 */
function buildBreakingDescription(
  date: string,
  feedData: BreakingNewsFeedData | undefined
): string {
  if (!feedData) return `European Parliament breaking developments for ${date}.`;
 
  const counts: string[] = [];
  if (feedData.adoptedTexts.length > 0)
    counts.push(pl(feedData.adoptedTexts.length, 'adopted text', 'adopted texts'));
  if (feedData.events.length > 0) counts.push(pl(feedData.events.length, 'event', 'events'));
  if (feedData.procedures.length > 0)
    counts.push(pl(feedData.procedures.length, 'procedure', 'procedures'));
  if (feedData.mepUpdates.length > 0)
    counts.push(pl(feedData.mepUpdates.length, 'MEP update', 'MEP updates'));
 
  if (counts.length === 0) return `European Parliament breaking developments for ${date}.`;
 
  const highlight = feedData.adoptedTexts[0]?.title ?? feedData.events[0]?.title ?? '';
  const base = `EP breaking: ${counts.join(', ')}`;
  if (highlight) {
    const full = `${base}. Highlights: ${highlight}`;
    return full.length > 200 ? full.slice(0, 197) + '...' : full;
  }
  return base.length > 200 ? base.slice(0, 197) + '...' : base;
}
 
/**
 * Build a content-aware title suffix from feed data item counts.
 *
 * @param feedData - Breaking news feed data (may be undefined)
 * @returns Short suffix string for appending to the base title, or empty string
 */
function buildBreakingTitleSuffix(feedData: BreakingNewsFeedData | undefined): string {
  if (!feedData) return '';
  const total =
    feedData.adoptedTexts.length +
    feedData.events.length +
    feedData.procedures.length +
    feedData.mepUpdates.length;
  if (total === 0) return '';
  const parts: string[] = [];
  if (feedData.adoptedTexts.length > 0)
    parts.push(pl(feedData.adoptedTexts.length, 'Text', 'Texts'));
  if (feedData.events.length > 0) parts.push(pl(feedData.events.length, 'Event', 'Events'));
  if (feedData.procedures.length > 0)
    parts.push(pl(feedData.procedures.length, 'Procedure', 'Procedures'));
  return parts.join(', ');
}
 
// ─── Data payload ─────────────────────────────────────────────────────────────
 
/** Data fetched and pre-processed by {@link BreakingNewsStrategy} */
export interface BreakingNewsArticleData extends ArticleData {
  /** Feed data — adopted texts, events, procedures, MEP updates (PRIMARY). Undefined when MCP unavailable. */
  readonly feedData: BreakingNewsFeedData | undefined;
  /** Raw voting anomaly text from MCP (CONTEXT ONLY) */
  readonly anomalyRaw: string;
  /** Raw coalition dynamics text from MCP (CONTEXT ONLY) */
  readonly coalitionRaw: string;
  /** Raw voting statistics report text from MCP (KEPT FOR BACKWARD COMPAT) */
  readonly reportRaw: string;
}
 
// ─── Strategy implementation ──────────────────────────────────────────────────
 
/**
 * Article strategy for {@link ArticleCategory.BREAKING_NEWS}.
 *
 * **Feed-first**: EP feed endpoints are the primary data source.
 * Analytical tools provide supplementary context only.
 * Stats are NEVER the news itself.
 */
export class BreakingNewsStrategy implements ArticleStrategy<BreakingNewsArticleData> {
  readonly type = ArticleCategory.BREAKING_NEWS;
 
  readonly requiredMCPTools = [
    'get_adopted_texts_feed',
    'get_events_feed',
    'get_procedures_feed',
    'get_meps_feed',
    'detect_voting_anomalies',
    'analyze_coalition_dynamics',
  ] as const;
 
  /**
   * Fetch EP feed data (primary) first, then conditionally fetch analytical
   * context (secondary) in a second phase.
   *
   * @param client - MCP client or null
   * @param date - ISO 8601 publication date
   * @returns Populated breaking news data payload
   */
  async fetchData(
    client: EuropeanParliamentMCPClient | null,
    date: string
  ): Promise<BreakingNewsArticleData> {
    // Step 0: Check for pre-fetched feed data file (set by --feed-data CLI arg).
    // This allows agentic workflows to pass MCP data fetched via framework tools
    // into the generator without requiring a direct MCP connection.
    const feedDataFile = process.env['EP_FEED_DATA_FILE'];
    if (feedDataFile) {
      console.log(`  📂 Loading pre-fetched feed data from: ${feedDataFile}`);
      const fileFeedData = loadFeedDataFromFile(feedDataFile, { start: date, end: date });
      if (fileFeedData) {
        const totalItems =
          fileFeedData.adoptedTexts.length +
          fileFeedData.events.length +
          fileFeedData.procedures.length +
          fileFeedData.mepUpdates.length;
        console.log(`  📰 Pre-fetched feed data: ${totalItems} total items`);
 
        // Fetch analytical context from MCP if client available, else skip
        let anomalyRaw = '';
        let coalitionRaw = '';
        Iif (client && totalItems > 0) {
          [anomalyRaw, coalitionRaw] = await Promise.all([
            fetchVotingAnomalies(client),
            fetchCoalitionDynamics(client),
          ]);
        }
        return { date, feedData: fileFeedData, anomalyRaw, coalitionRaw, reportRaw: '' };
      }
      console.log('  ⚠️ Pre-fetched feed data failed to load — falling through to MCP fetch');
    }
 
    if (client) {
      console.log('  📡 Fetching EP feed data (primary) and analytical context...');
    }
 
    // Step 1: Fetch feed data (PRIMARY news content) — 'today' for realtime breaking news
    const feedData = await fetchBreakingNewsFeedData(client, 'today');
 
    // When client is null, feedData is undefined — MCP unavailable
    if (!feedData) {
      console.log('  ⚠️ MCP unavailable — no feed data or analytical context');
      return { date, feedData, anomalyRaw: '', coalitionRaw: '', reportRaw: '' };
    }
 
    const totalFeedItems =
      feedData.adoptedTexts.length +
      feedData.events.length +
      feedData.procedures.length +
      feedData.mepUpdates.length;
 
    Iif (totalFeedItems > 0) {
      console.log(
        `  📰 Feed data: ${feedData.adoptedTexts.length} adopted texts, ` +
          `${feedData.events.length} events, ${feedData.procedures.length} procedures, ` +
          `${feedData.mepUpdates.length} MEP updates`
      );
    } else {
      console.log('  ⚠️ No feed data available — skipping analytical context fetch');
      return { date, feedData, anomalyRaw: '', coalitionRaw: '', reportRaw: '' };
    }
 
    // Step 2: Fetch analytical context only when at least one feed item is available
    const [anomalyRaw, coalitionRaw] = await Promise.all([
      fetchVotingAnomalies(client),
      fetchCoalitionDynamics(client),
    ]);
 
    return { date, feedData, anomalyRaw, coalitionRaw, reportRaw: '' };
  }
 
  /**
   * Build the breaking news HTML body for the specified language.
   *
   * @param data - Breaking news data payload
   * @param lang - Target language code used for editorial strings
   * @returns Article HTML body
   */
  buildContent(data: BreakingNewsArticleData, lang: LanguageCode): string {
    const base = buildBreakingNewsContent(
      data.date,
      data.anomalyRaw,
      data.coalitionRaw,
      data.reportRaw,
      '',
      lang,
      [],
      [],
      [],
      data.feedData
    );
    const analysis = buildBreakingAnalysis(
      data.date,
      data.feedData,
      data.anomalyRaw,
      data.coalitionRaw,
      lang
    );
    const deepSection = buildDeepAnalysisSection(analysis, lang);
    const mindmapData = buildBreakingMindmap(data.feedData, lang);
    const mindmapSection = buildIntelligenceMindmapSection(mindmapData, lang);
    const swotData = buildBreakingSwot(data.feedData, data.anomalyRaw, data.coalitionRaw, lang);
    const swotSection = buildSwotSection(swotData, lang);
    const dashboardData = buildBreakingDashboard(data.feedData, lang);
    const dashboardSection = buildDashboardSection(dashboardData, lang);
    const injection = deepSection + mindmapSection + swotSection + dashboardSection;
    // Inject before the closing </div> of .article-content
    Eif (injection) {
      const closingTag = '</div>';
      const lastIdx = base.lastIndexOf(closingTag);
      Eif (lastIdx !== -1) {
        return base.slice(0, lastIdx) + injection + '\n' + base.slice(lastIdx);
      }
    }
    return base;
  }
 
  /**
   * Return language-specific metadata for the breaking news article.
   *
   * @param data - Breaking news data payload
   * @param lang - Target language code
   * @returns Localised metadata
   */
  getMetadata(data: BreakingNewsArticleData, lang: LanguageCode): ArticleMetadata {
    const titleFn = getLocalizedString(BREAKING_NEWS_TITLES, lang);
    const { title: baseTitle, subtitle: baseSubtitle } = titleFn(data.date);
    const suffix = lang === 'en' ? buildBreakingTitleSuffix(data.feedData) : '';
    const title = suffix ? `${baseTitle} — ${suffix}` : baseTitle;
    const description = lang === 'en' ? buildBreakingDescription(data.date, data.feedData) : '';
    const subtitle = description || baseSubtitle;
    const keywords = buildBreakingKeywords(data.feedData);
    if (data.feedData) {
      const score = scoreBreakingNewsSignificance(data.feedData);
      if (score.overallScore >= SIGNIFICANCE_THRESHOLD) {
        keywords.push(`significance:${score.overallScore}`);
      }
    }
    return {
      title,
      subtitle,
      keywords,
      category: ArticleCategory.BREAKING_NEWS,
      sources: [],
    };
  }
}
 
/** Singleton instance for use by the strategy registry */
export const breakingNewsStrategy = new BreakingNewsStrategy();