All files / src/tools monitorLegislativePipeline.ts

92.08% Statements 128/139
88% Branches 110/125
100% Functions 30/30
96.49% Lines 110/114

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                                                                                                                                                                  4x           130x 130x 130x 126x 126x         65x 15x 15x         65x 31x 15x         17x 17x 17x         24x 9x 8x 8x             65x 65x                   65x 65x 65x 65x 65x 65x 65x           65x 65x 65x 65x               65x 65x 65x 55x 10x     65x 65x 65x   65x                                                       38x 34x 38x                   68x 65x 65x         65x 40x     37x       3x             33x           24x 24x 33x 17x 17x 17x 17x     24x 17x           8x             33x 33x 33x 33x 24x 24x             24x 24x 24x     24x                                                                                   26x   26x 26x   24x 24x               48x 24x 24x 24x 24x 24x   24x 26x         26x 24x 12x       24x     26x 76x 76x 76x 8x   68x     65x       26x 37x     26x 65x 33x   26x 26x 26x 26x   26x                                                                           26x   1x 1x             4x                                                                            
/**
 * MCP Tool: monitor_legislative_pipeline
 * 
 * Real-time legislative pipeline status with bottleneck detection
 * and timeline forecasting.
 * 
 * **Intelligence Perspective:** Pipeline monitoring tool providing situational
 * awareness of legislative progress—enables early warning for stalled procedures,
 * bottleneck identification, and timeline forecasting.
 * 
 * ISMS Policy: SC-002 (Input Validation), AC-003 (Least Privilege)
 */
 
import { MonitorLegislativePipelineSchema } from '../schemas/europeanParliament.js';
import { epClient } from '../clients/europeanParliamentClient.js';
import type { Procedure } from '../types/europeanParliament.js';
import type { ToolResult } from './shared/types.js';
 
/** Computed attributes for a single pipeline item */
interface PipelineItemComputedAttrs {
  progressPercentage: number;
  velocityScore: number;
  complexityIndicator: string;
  estimatedCompletionDays: number;
  bottleneckRisk: string;
}
 
/** A single procedure in the pipeline */
interface PipelineItem {
  procedureId: string;
  title: string;
  type: string;
  currentStage: string;
  committee: string;
  daysInCurrentStage: number;
  isStalled: boolean;
  nextExpectedAction: string;
  computedAttributes: PipelineItemComputedAttrs;
}
 
/** Bottleneck analysis */
interface BottleneckInfo {
  stage: string;
  procedureCount: number;
  avgDaysStuck: number;
  severity: string;
}
 
/** Full pipeline analysis result */
interface LegislativePipelineAnalysis {
  period: { from: string; to: string };
  filter: { committee?: string; status: string };
  pipeline: PipelineItem[];
  summary: {
    totalProcedures: number;
    activeCount: number;
    stalledCount: number;
    completedCount: number;
    avgDaysInPipeline: number;
  };
  bottlenecks: BottleneckInfo[];
  computedAttributes: {
    pipelineHealthScore: number;
    throughputRate: number;
    bottleneckIndex: number;
    stalledProcedureRate: number;
    estimatedClearanceTime: number;
    legislativeMomentum: string;
  };
  confidenceLevel: 'HIGH' | 'MEDIUM' | 'LOW';
  dataFreshness: string;
  sourceAttribution: string;
  methodology: string;
  dataQualityWarnings: string[];
}
 
/**
 * Default recency window (years) applied to the ACTIVE status filter when no
 * explicit dateFrom is provided. Procedures whose best available date predates
 * this window cannot be confirmed as currently active and are excluded.
 */
const ACTIVE_RECENCY_YEARS = 10;
 
/**
 * Calculate days between two date strings (or since a date).
 */
function daysBetween(dateStr: string, endStr?: string): number {
  const start = new Date(dateStr);
  const end = endStr !== undefined && endStr !== '' ? new Date(endStr) : new Date();
  if (isNaN(start.getTime())) return 0;
  Iif (isNaN(end.getTime())) return 0;
  return Math.max(0, Math.round((end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24)));
}
 
/** Classify complexity from days in stage */
function classifyComplexity(days: number): string {
  if (days > 60) return 'HIGH';
  Iif (days > 30) return 'MEDIUM';
  return 'LOW';
}
 
/** Classify bottleneck risk */
function classifyBottleneckRisk(isStalled: boolean, days: number): string {
  if (isStalled) return 'HIGH';
  if (days > 45) return 'MEDIUM';
  return 'LOW';
}
 
/** Classify bottleneck severity */
function classifyBottleneckSeverity(count: number): string {
  Iif (count > 3) return 'CRITICAL';
  Iif (count > 1) return 'HIGH';
  return 'MODERATE';
}
 
/** Classify legislative momentum */
function classifyMomentum(healthScore: number): string {
  if (healthScore > 80) return 'STRONG';
  if (healthScore > 60) return 'MODERATE';
  Iif (healthScore > 40) return 'SLOW';
  return 'STALLED';
}
 
/**
 * Check if a procedure status indicates completion.
 */
function isStatusCompleted(status: string): boolean {
  const lower = status.toLowerCase();
  return lower.includes('adopted') || lower.includes('completed');
}
 
/**
 * Compute progress metrics for a procedure.
 */
function computePipelineMetrics(proc: Procedure): {
  daysInStage: number; isCompleted: boolean; isStalled: boolean;
  totalDays: number; progressEstimate: number; velocityScore: number; estimatedDays: number;
} {
  const lastActivity = proc.dateLastActivity !== '' ? proc.dateLastActivity : proc.dateInitiated;
  const daysInStage = daysBetween(lastActivity);
  const isCompleted = isStatusCompleted(proc.status);
  const isStalled = !isCompleted && daysInStage > 60;
  const initiated = proc.dateInitiated !== '' ? proc.dateInitiated : '';
  const lastAct = proc.dateLastActivity !== '' ? proc.dateLastActivity : undefined;
  const totalDays = daysBetween(initiated, lastAct);
  // Progress bounded to 5-90% for active procedures:
  // 5% floor: newly initiated procedures have at least entered the legislative cycle
  // 90% ceiling: only completed procedures should report 100%; active ones may still stall
  // Linear estimate: totalDays/10 means 900 days ≈ 90% (the ceiling); this is a rough proxy
  // since EU legislative procedures typically span 12-36 months (360-1080 days)
  const progressEstimate = isCompleted ? 100 : Math.min(90, Math.max(5, Math.round(totalDays / 10)));
  const velocityScore = isStalled ? 20 : Math.min(100, 100 - Math.min(80, daysInStage));
  const estimatedDays = isCompleted ? 0 : Math.max(30, daysInStage * 2);
  return { daysInStage, isCompleted, isStalled, totalDays, progressEstimate, velocityScore, estimatedDays };
}
 
/**
 * Transform a real EP API Procedure into a PipelineItem.
 * All data is derived from the real procedure fields.
 */
function procedureToPipelineItem(proc: Procedure): PipelineItem {
  const m = computePipelineMetrics(proc);
  let currentStage = 'Unknown';
  if (proc.stage !== '') {
    currentStage = proc.stage;
  } else if (Iproc.status !== '') {
    currentStage = proc.status;
  }
  const committee = proc.responsibleCommittee !== '' ? proc.responsibleCommittee : 'Unknown';
  const stageLabel = proc.stage !== '' ? proc.stage : 'processing';
  const nextAction = m.isCompleted ? 'COMPLETED' : `Continue ${stageLabel}`;
 
  return {
    procedureId: proc.id,
    title: proc.title,
    type: proc.type,
    currentStage,
    committee,
    daysInCurrentStage: m.daysInStage,
    isStalled: m.isStalled,
    nextExpectedAction: nextAction,
    computedAttributes: {
      progressPercentage: m.progressEstimate,
      velocityScore: m.velocityScore,
      complexityIndicator: classifyComplexity(m.daysInStage),
      estimatedCompletionDays: m.estimatedDays,
      bottleneckRisk: classifyBottleneckRisk(m.isStalled, m.daysInStage),
    },
  };
}
 
/**
 * Check if a procedure's dates pass the recency cut-off for the ACTIVE filter.
 * Returns false if the procedure has no temporal data or is older than the cut-off.
 */
function isWithinRecencyCutoff(
  lastActivity: string,
  initiated: string | undefined,
  cutoffDate: string
): boolean {
  if (lastActivity === '' && initiated === undefined) return false;
  const referenceDate = lastActivity !== '' ? lastActivity : initiated;
  return referenceDate !== undefined && referenceDate >= cutoffDate;
}
 
/** Check if a procedure matches an explicit date range (dateFrom / dateTo) */
function matchesDateRange(
  lastActivity: string,
  initiated: string | undefined,
  dateFrom: string | undefined,
  dateTo: string | undefined
): boolean {
  if (dateFrom !== undefined && lastActivity !== '' && lastActivity < dateFrom) return false;
  Iif (dateTo !== undefined && initiated !== undefined && initiated > dateTo) return false;
  return true;
}
 
/** Check if item matches status filter */
function matchesStatusFilter(item: PipelineItem, status: string): boolean {
  if (status === 'ALL') return true;
  if (status === 'ACTIVE') {
    // Exclude items with missing enrichment (Unknown stage) — these are historical
    // or incomplete records that cannot be confirmed as currently active
    return !item.isStalled
      && item.computedAttributes.progressPercentage < 100
      && item.currentStage !== 'Unknown';
  }
  Eif (status === 'STALLED') return item.isStalled;
  if (status === 'COMPLETED') return item.computedAttributes.progressPercentage >= 100;
  return true;
}
 
/** Check if item matches committee filter */
function matchesCommitteeFilter(item: PipelineItem, committee: string | undefined): boolean {
  Eif (committee === undefined) return true;
  return item.committee === committee;
}
 
/** Detect bottlenecks from stalled pipeline items */
function detectBottlenecks(pipeline: PipelineItem[]): BottleneckInfo[] {
  const stageCounts: Record<string, { count: number; totalDays: number }> = {};
  for (const item of pipeline) {
    if (item.isStalled) {
      const entry = stageCounts[item.currentStage] ?? { count: 0, totalDays: 0 };
      entry.count++;
      entry.totalDays += item.daysInCurrentStage;
      stageCounts[item.currentStage] = entry;
    }
  }
  return Object.entries(stageCounts)
    .map(([stage, data]) => ({
      stage,
      procedureCount: data.count,
      avgDaysStuck: Math.round(data.totalDays / data.count),
      severity: classifyBottleneckSeverity(data.count),
    }))
    .sort((a, b) => b.procedureCount - a.procedureCount);
}
 
/** Compute pipeline summary statistics */
function computePipelineSummary(pipeline: PipelineItem[]): {
  activeCount: number; stalledCount: number; completedCount: number; avgDays: number;
} {
  const activeCount = pipeline.filter(p => !p.isStalled && p.computedAttributes.progressPercentage < 100).length;
  const stalledCount = pipeline.filter(p => p.isStalled).length;
  const completedCount = pipeline.filter(p => p.computedAttributes.progressPercentage >= 100).length;
  const totalDays = pipeline.reduce((sum, p) => sum + p.daysInCurrentStage, 0);
  const avgDays = pipeline.length > 0 ? Math.round(totalDays / pipeline.length) : 0;
  return { activeCount, stalledCount, completedCount, avgDays };
}
 
/** Compute pipeline health metrics */
function computeHealthMetrics(pipeline: PipelineItem[], summary: ReturnType<typeof computePipelineSummary>): {
  healthScore: number; throughputRate: number; stalledRate: number;
} {
  const stalledRate = pipeline.length > 0 ? summary.stalledCount / pipeline.length : 0;
  const healthScore = Math.round((1 - stalledRate) * 100 * 100) / 100;
  const throughputRate = pipeline.length > 0
    ? Math.round((summary.completedCount / pipeline.length) * 100 * 100) / 100
    : 0;
  return { healthScore, throughputRate, stalledRate };
}
 
/**
 * Handles the monitor_legislative_pipeline MCP tool request.
 *
 * Monitors the European Parliament's active legislative pipeline by fetching real
 * procedures from the EP API and computing health metrics including bottleneck
 * detection, stalled-procedure rate, throughput rate, and legislative momentum.
 * All procedure data (title, type, stage, status, dates, committee) is sourced
 * directly from the EP API; computed attributes are derived from real dates and stages.
 *
 * @param args - Raw tool arguments, validated against {@link MonitorLegislativePipelineSchema}
 * @returns MCP tool result containing pipeline items with stage and status,
 *   summary counts (active/stalled/completed), detected bottlenecks, pipeline health
 *   score, throughput rate, bottleneck index, and legislative momentum classification
 * @throws - If `args` fails schema validation (e.g., missing required fields or invalid format)
 * - If the European Parliament API is unreachable or returns an error response
 *
 * @example
 * ```typescript
 * const result = await handleMonitorLegislativePipeline({
 *   status: 'ACTIVE',
 *   committee: 'ENVI',
 *   dateFrom: '2024-01-01',
 *   dateTo: '2024-12-31',
 *   limit: 20
 * });
 * // Returns pipeline health score, stalled/active/completed counts,
 * // bottleneck list, and legislative momentum assessment
 * ```
 *
 * @security - Input is validated with Zod before any API call.
 * - Personal data in responses is minimised per GDPR Article 5(1)(c).
 * - All requests are rate-limited and audit-logged per ISMS Policy AU-002.
 * @since 0.8.0
 * @see {@link monitorLegislativePipelineToolMetadata} for MCP schema registration
 * @see {@link handleTrackLegislation} for individual procedure stage and timeline tracking
 */
export async function handleMonitorLegislativePipeline(
  args: unknown
): Promise<ToolResult> {
  const params = MonitorLegislativePipelineSchema.parse(args);
 
  try {
    const procedures = await epClient.getProcedures({ limit: params.limit });
 
    const dateFrom = params.dateFrom;
    const dateTo = params.dateTo;
 
    // When the caller supplies neither dateFrom nor dateTo, default to a
    // last-30-days window anchored on "now". Previously the response carried
    // a fixed `2024-01-01..2024-12-31` placeholder, which surfaced as Defect
    // #6 in the Hack23/euparliamentmonitor 2026-04-24 propositions audit
    // (`monitor_legislative_pipeline returned empty … period.from: 2024-01-01,
    // period.to: 2024-12-31`).
    const toIsoDate = (d: Date): string => d.toISOString().slice(0, 10);
    const todayIso = toIsoDate(new Date());
    const defaultFromIso = ((): string => {
      const d = new Date();
      d.setUTCDate(d.getUTCDate() - 30);
      return toIsoDate(d);
    })();
    const reportFrom = dateFrom ?? defaultFromIso;
    const reportTo = dateTo ?? todayIso;
 
    // Compute default recency cut-off date for the ACTIVE filter.
    // When dateFrom is not explicitly set, procedures whose best available date
    // predates the cut-off window are excluded — they cannot be confirmed as active.
    const activeCutoffDate: string | undefined = ((): string | undefined => {
      if (params.status !== 'ACTIVE' || dateFrom !== undefined) return undefined;
      const referenceYear = parseInt(
        (dateTo ?? new Date().toISOString().slice(0, 10)).slice(0, 4),
        10
      );
      return `${String(referenceYear - ACTIVE_RECENCY_YEARS)}-01-01`;
    })();
 
    const filteredProcs = procedures.data.filter(proc => {
      const lastActivity = proc.dateLastActivity !== '' ? proc.dateLastActivity : proc.dateInitiated;
      const initiated = proc.dateInitiated !== '' ? proc.dateInitiated : undefined;
      if (activeCutoffDate !== undefined && !isWithinRecencyCutoff(lastActivity, initiated, activeCutoffDate)) {
        return false;
      }
      return matchesDateRange(lastActivity, initiated, dateFrom, dateTo);
    });
 
    const allMappedItems = filteredProcs.map(proc => procedureToPipelineItem(proc));
 
    // Count items with missing enrichment before applying the status filter so we
    // can surface a data-quality warning in the response.
    const unknownEnrichmentCount = params.status === 'ACTIVE'
      ? allMappedItems.filter(item => item.currentStage === 'Unknown').length
      : 0;
 
    const allItems = allMappedItems
      .filter(item => matchesStatusFilter(item, params.status))
      .filter(item => matchesCommitteeFilter(item, params.committee));
 
    const pipeline = allItems.slice(0, params.limit);
    const summary = computePipelineSummary(pipeline);
    const bottlenecks = detectBottlenecks(pipeline);
    const health = computeHealthMetrics(pipeline, summary);
 
    const analysis: LegislativePipelineAnalysis = {
      period: { from: reportFrom, to: reportTo },
      filter: { ...(params.committee !== undefined ? { committee: params.committee } : {}), status: params.status },
      pipeline,
      summary: {
        totalProcedures: pipeline.length,
        activeCount: summary.activeCount,
        stalledCount: summary.stalledCount,
        completedCount: summary.completedCount,
        avgDaysInPipeline: summary.avgDays,
      },
      bottlenecks,
      computedAttributes: {
        pipelineHealthScore: health.healthScore,
        throughputRate: health.throughputRate,
        bottleneckIndex: Math.round(health.stalledRate * summary.avgDays * 100) / 100,
        stalledProcedureRate: Math.round(health.stalledRate * 100 * 100) / 100,
        estimatedClearanceTime: summary.avgDays * Math.max(1, summary.activeCount),
        legislativeMomentum: classifyMomentum(health.healthScore),
      },
      confidenceLevel: pipeline.length >= 10 ? 'MEDIUM' : 'LOW',
      dataFreshness: 'Real-time EP API data — procedures from EP Open Data /procedures endpoint',
      sourceAttribution: 'European Parliament Open Data Portal - data.europarl.europa.eu',
      methodology: 'Real-time pipeline analysis using EP API /procedures endpoint. '
        + 'All procedure data (title, type, stage, status, dates, committee) sourced from '
        + 'European Parliament open data. Computed attributes (health score, velocity, '
        + 'bottleneck risk, momentum) are derived from real procedure dates and stages. '
        + 'Data source: https://data.europarl.europa.eu/api/v2/procedures',
      dataQualityWarnings: [
        ...(pipeline.length < 10
          ? ['Small procedure sample (< 10) — pipeline health metrics may not be statistically representative']
          : []),
        ...(unknownEnrichmentCount > 0
          ? [`${String(unknownEnrichmentCount)} procedure(s) excluded from ACTIVE filter due to missing enrichment data (stage/committee unknown) — these may be historical or incomplete records`]
          : []),
      ],
    };
 
    return { content: [{ type: 'text', text: JSON.stringify(analysis, null, 2) }] };
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : 'Unknown error';
    throw new Error(`Failed to monitor legislative pipeline: ${errorMessage}`);
  }
}
 
/**
 * Tool metadata for MCP registration
 */
export const monitorLegislativePipelineToolMetadata = {
  name: 'monitor_legislative_pipeline',
  description: 'Monitor legislative pipeline status with bottleneck detection and timeline forecasting. Tracks procedures through stages (proposal → committee → plenary → trilogue → adoption). Returns pipeline health score, throughput rate, bottleneck index, stalled procedure rate, and legislative momentum assessment.',
  inputSchema: {
    type: 'object' as const,
    properties: {
      committee: {
        type: 'string',
        description: 'Filter by committee',
        minLength: 1,
        maxLength: 100
      },
      status: {
        type: 'string',
        enum: ['ALL', 'ACTIVE', 'STALLED', 'COMPLETED'],
        description: 'Pipeline status filter',
        default: 'ACTIVE'
      },
      dateFrom: {
        type: 'string',
        description: 'Analysis start date (YYYY-MM-DD format)',
        pattern: '^\\d{4}-\\d{2}-\\d{2}$'
      },
      dateTo: {
        type: 'string',
        description: 'Analysis end date (YYYY-MM-DD format)',
        pattern: '^\\d{4}-\\d{2}-\\d{2}$'
      },
      limit: {
        type: 'number',
        description: 'Maximum results to return (1-100)',
        minimum: 1,
        maximum: 100,
        default: 20
      }
    }
  }
};