All files / scripts/pre-article-analysis markdown-serializer.ts

99.53% Statements 216/217
68.05% Branches 49/72
97.36% Functions 37/38
100% Lines 197/197

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                                                                                                                                                                              64x 10x 5x       1x     18x 11x 3x 3x       73x               45x                                       12x 8x 8x               8x 2x     8x   8x 12x     8x   8x                       5x 8x     5x                   5x 8x 8x 8x 48x 96x     8x 8x 8x 8x 8x 8x 8x     5x 5x 5x 8x 8x     5x 5x   5x 5x   5x                       5x   5x                             5x 4x 4x     1x     5x 5x 5x 4x     5x 5x 10x     5x 5x   5x                       4x                   4x 3x   3x 3x 3x   3x 3x 3x   3x 3x 3x   3x 3x 3x     4x 4x   4x 4x   4x 4x   4x                     3x 2x 12x 24x 12x         3x 2x     3x                   3x 3x 12x 12x 12x     3x 2x 10x 2x     3x 3x   3x 3x   3x 3x   3x                       3x 3x       3x 3x 3x 18x 18x 18x       3x                   3x                 3x 18x 18x 18x 18x   18x 18x 18x 18x 18x     18x 18x 18x 18x 18x         3x 3x 3x   3x 3x   3x 3x   3x                     5x                       9x 5x 10x 10x 10x 10x 10x 10x     5x 10x 5x 10x 5x   5x 5x   5x 5x   5x                     4x                   4x 1x   3x 3x 6x 6x 6x     3x 6x 6x 6x 6x   6x       4x 4x   4x 4x   4x 4x   4x                     8x   8x                   12x   8x 8x 11x 11x 11x 11x 11x     8x 8x 8x   8x 8x   8x    
/**
 * @module pre-article-analysis/markdown-serializer
 * @description Serializes analysis framework results as structured markdown
 * files for persistence in `analysis/daily/YYYY-MM-DD/`.
 *
 * Each output file follows the standard analysis template:
 * ```markdown
 * # [Analysis Type] — YYYY-MM-DD
 * **Generated**: YYYY-MM-DD HH:MM UTC
 * **Data Sources**: [list]
 * **Documents Analyzed**: N
 * **Confidence**: HIGH/MEDIUM/LOW
 * ## Summary / ## Detailed Analysis / ## Key Findings / ## Implications
 * ```
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import type {
  DocumentAnalysisResult,
  PerspectiveAnalysis,
  DocumentLink,
} from '../analysis-framework/types.js';
 
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
 
export interface SerializationContext {
  /** ISO date string, e.g. "2026-03-26" */
  date: string;
  /** UTC timestamp of generation */
  generatedAt: string;
  /** List of MCP tool names called to download data */
  dataSources: string[];
}
 
export interface SignificanceEntry {
  dok_id: string;
  title: string;
  score: number;
  doctype: string;
}
 
export interface RiskAssessmentResult {
  coalitionRiskScore: number;
  riskLevel: 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
  riskSummary: string;
  anomalyFlags: Array<{ type: string; severity: string; description: string }>;
  implications: string[];
}
 
export interface SwotSummary {
  strengths: string[];
  weaknesses: string[];
  opportunities: string[];
  threats: string[];
  forStakeholder: string;
}
 
export interface CrossReferenceSummary {
  docCount: number;
  totalLinks: number;
  links: DocumentLink[];
}
 
export interface SynthesisSummary {
  totalDocs: number;
  executiveSummary: string;
  keyFindings: string[];
  topDocuments: SignificanceEntry[];
  overallConfidence: 'HIGH' | 'MEDIUM' | 'LOW';
  aggregateRiskLevel: string;
}
 
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
 
/**
 * Map a numeric confidence score (0–100) to a categorical label.
 * - ≥70: HIGH — strong evidence, full-text content available for most documents
 * - 40–69: MEDIUM — moderate evidence, mix of full-text and metadata-only
 * - <40: LOW — weak evidence, metadata-only documents or small batch
 */
function confidenceLabel(score: number): 'HIGH' | 'MEDIUM' | 'LOW' {
  if (score >= 70) return 'HIGH';
  if (score >= 40) return 'MEDIUM';
  return 'LOW';
}
 
/** Maximum number of documents shown in the detailed analysis section */
const MAX_DETAILED_RESULTS = 20;
 
function significanceLabel(score: number): string {
  if (score >= 8) return '🔴 Critical';
  if (score >= 6) return '🟠 High';
  Iif (score >= 4) return '🟡 Medium';
  return '🟢 Low';
}
 
function escapeMarkdownTableCell(value: string): string {
  return value
    .replace(/\\/g, '\\\\')
    .replace(/\r?\n/g, ' ')
    .replace(/\|/g, '\\|')
    .trim();
}
 
function frontmatter(ctx: SerializationContext, title: string, docCount: number, confidenceScore: number): string {
  return [
    `# ${title} — ${ctx.date}`,
    '',
    `**Generated**: ${ctx.generatedAt}`,
    `**Data Sources**: ${ctx.dataSources.join(', ')}`,
    `**Documents Analyzed**: ${docCount}`,
    `**Confidence**: ${confidenceLabel(confidenceScore)}`,
    '',
  ].join('\n');
}
 
// ---------------------------------------------------------------------------
// Data-download manifest
// ---------------------------------------------------------------------------
 
export function serializeDataManifest(
  ctx: SerializationContext,
  docCounts: Record<string, number>,
  dateFilteredTotal?: number,
): string {
  const totalDocs = Object.values(docCounts).reduce((a, b) => a + b, 0);
  const analyzedCount = dateFilteredTotal ?? totalDocs;
  const lines: string[] = [
    frontmatter(ctx, 'Data Download Manifest', analyzedCount, 100),
    '## Summary',
    '',
    `Downloaded **${totalDocs}** documents (session-wide) from ${ctx.dataSources.length} MCP data sources.`,
    '',
  ];
 
  if (dateFilteredTotal !== undefined) {
    lines.push(`After date filtering to **${ctx.date}**: **${dateFilteredTotal}** documents selected for analysis.`, '');
  }
 
  lines.push('## Document Counts by Type', '');
 
  for (const [type, count] of Object.entries(docCounts)) {
    lines.push(`- **${type}**: ${count} documents`);
  }
 
  lines.push('', '## Data Quality Notes', '', 'All documents sourced from official riksdag-regering-mcp API.');
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Classification results
// ---------------------------------------------------------------------------
 
export function serializeClassificationResults(
  ctx: SerializationContext,
  results: DocumentAnalysisResult[],
): string {
  const avgConfidence =
    results.length > 0
      ? results.reduce((sum, r) => sum + r.confidenceScore, 0) / results.length
      : 0;
 
  const lines: string[] = [
    frontmatter(ctx, 'Political Classification Results', results.length, avgConfidence),
    '## Summary',
    '',
    `Classified **${results.length}** parliamentary documents by sensitivity, impact, urgency, and domain.`,
    '',
    '## Detailed Analysis',
    '',
  ];
 
  for (const result of results.slice(0, MAX_DETAILED_RESULTS)) {
    const title = result.document.titel || result.document.title || result.document.dok_id || 'Unknown';
    const dokId = result.document.dok_id || 'N/A';
    const domains = result.perspectives
      .flatMap(p => p.relatedPolicies)
      .filter((v, i, arr) => arr.indexOf(v) === i)
      .slice(0, 3);
 
    lines.push(`### ${title}`);
    lines.push(`- **dok_id**: ${dokId}`);
    lines.push(`- **Type**: ${result.document.doktyp || 'unknown'}`);
    lines.push(`- **Significance**: ${significanceLabel(result.overallSignificance)} (${result.overallSignificance}/10)`);
    lines.push(`- **Domains**: ${domains.join(', ') || 'General'}`);
    lines.push(`- **Confidence**: ${confidenceLabel(result.confidenceScore)} (${Math.round(result.confidenceScore)}%)`);
    lines.push('');
  }
 
  lines.push('## Key Findings', '');
  const topDocs = [...results].sort((a, b) => b.overallSignificance - a.overallSignificance).slice(0, 5);
  topDocs.forEach((r, i) => {
    const title = r.document.titel || r.document.title || r.document.dok_id || 'Unknown';
    lines.push(`${i + 1}. **${title}** (dok_id: ${r.document.dok_id || 'N/A'}) — Significance: ${r.overallSignificance}/10`);
  });
 
  lines.push('', '## Implications', '');
  lines.push('Classification drives article prioritisation. High-significance documents should receive deep-inspection treatment.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push(`Classification confidence: ${confidenceLabel(avgConfidence)}. Higher confidence when full-text content is available.`);
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Risk assessment
// ---------------------------------------------------------------------------
 
export function serializeRiskAssessment(
  ctx: SerializationContext,
  docCount: number,
  risk: RiskAssessmentResult,
): string {
  const confidenceScore = risk.riskLevel === 'LOW' ? 80 : risk.riskLevel === 'MEDIUM' ? 60 : 40;
 
  const lines: string[] = [
    frontmatter(ctx, 'Political Risk Assessment', docCount, confidenceScore),
    '## Summary',
    '',
    risk.riskSummary,
    '',
    '## Detailed Analysis',
    '',
    `**Coalition Risk Score**: ${risk.coalitionRiskScore}/100`,
    `**Risk Level**: ${risk.riskLevel}`,
    '',
    '### Anomaly Flags',
    '',
  ];
 
  if (risk.anomalyFlags.length > 0) {
    for (const flag of risk.anomalyFlags) {
      lines.push(`- **[${flag.severity}]** ${flag.type}: ${flag.description}`);
    }
  } else {
    lines.push('No anomalous patterns detected in current data.');
  }
 
  lines.push('', '## Key Findings', '');
  lines.push(`1. Coalition stability at risk score **${risk.coalitionRiskScore}** (${risk.riskLevel})`);
  if (risk.anomalyFlags.length > 0) {
    lines.push(`2. **${risk.anomalyFlags.length}** anomaly flag(s) detected requiring monitoring`);
  }
 
  lines.push('', '## Implications', '');
  for (const impl of risk.implications) {
    lines.push(`- ${impl}`);
  }
 
  lines.push('', '## Data Quality Notes', '');
  lines.push('Risk assessment derived from CIA coalition metrics and document significance scores.');
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// SWOT analysis
// ---------------------------------------------------------------------------
 
export function serializeSwotAnalysis(
  ctx: SerializationContext,
  docCount: number,
  swots: SwotSummary[],
): string {
  const lines: string[] = [
    frontmatter(ctx, 'Political SWOT Analysis', docCount, 70),
    '## Summary',
    '',
    `Generated SWOT analysis for **${swots.length}** political actor(s) based on ${docCount} documents.`,
    '',
    '## Detailed Analysis',
    '',
  ];
 
  for (const swot of swots) {
    lines.push(`### ${swot.forStakeholder}`, '');
 
    lines.push('**Strengths**');
    swot.strengths.forEach(s => lines.push(`- ${s}`));
    lines.push('');
 
    lines.push('**Weaknesses**');
    swot.weaknesses.forEach(s => lines.push(`- ${s}`));
    lines.push('');
 
    lines.push('**Opportunities**');
    swot.opportunities.forEach(s => lines.push(`- ${s}`));
    lines.push('');
 
    lines.push('**Threats**');
    swot.threats.forEach(s => lines.push(`- ${s}`));
    lines.push('');
  }
 
  lines.push('## Key Findings', '');
  lines.push('1. SWOT entries derived from all six perspective analyses across downloaded documents.');
 
  lines.push('', '## Implications', '');
  lines.push('SWOT insights should inform stakeholder framing in generated articles.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push('SWOT confidence is proportional to document richness (full-text vs metadata-only).');
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Threat analysis
// ---------------------------------------------------------------------------
 
export function serializeThreatAnalysis(
  ctx: SerializationContext,
  results: DocumentAnalysisResult[],
): string {
  const threatEntries = results.flatMap(r =>
    r.perspectives.flatMap(p =>
      p.swotContribution
        .filter(c => c.quadrant === 'threat')
        .map(c => ({ title: r.document.titel || r.document.title || r.document.dok_id || 'Unknown', text: c.text, forStakeholder: c.forStakeholder }))
    )
  );
 
  const avgConfidence =
    results.length > 0
      ? results.reduce((sum, r) => sum + r.confidenceScore, 0) / results.length
      : 0;
 
  const lines: string[] = [
    frontmatter(ctx, 'Political Threat Analysis', results.length, avgConfidence),
    '## Summary',
    '',
    `Identified **${threatEntries.length}** threat indicators across ${results.length} documents.`,
    '',
    '## Detailed Analysis',
    '',
  ];
 
  const grouped = new Map<string, string[]>();
  for (const entry of threatEntries) {
    const arr = grouped.get(entry.forStakeholder) ?? [];
    arr.push(`[${entry.title}] ${entry.text}`);
    grouped.set(entry.forStakeholder, arr);
  }
 
  for (const [stakeholder, threats] of grouped) {
    lines.push(`### Threats for: ${stakeholder}`, '');
    threats.slice(0, 5).forEach(t => lines.push(`- ${t}`));
    lines.push('');
  }
 
  lines.push('## Key Findings', '');
  lines.push(`1. **${threatEntries.length}** threat indicators identified targeting ${grouped.size} stakeholder group(s)`);
 
  lines.push('', '## Implications', '');
  lines.push('Threat analysis should inform risk-focused article framing and editorial prioritisation.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push(`Analysis confidence: ${confidenceLabel(avgConfidence)}.`);
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Stakeholder perspectives
// ---------------------------------------------------------------------------
 
export function serializeStakeholderPerspectives(
  ctx: SerializationContext,
  results: DocumentAnalysisResult[],
): string {
  const avgConfidence =
    results.length > 0
      ? results.reduce((sum, r) => sum + r.confidenceScore, 0) / results.length
      : 0;
 
  // Aggregate perspectives by lens across all documents
  const lensMap = new Map<string, PerspectiveAnalysis[]>();
  for (const result of results) {
    for (const p of result.perspectives) {
      const arr = lensMap.get(p.lens) ?? [];
      arr.push(p);
      lensMap.set(p.lens, arr);
    }
  }
 
  const lines: string[] = [
    frontmatter(ctx, 'Stakeholder Perspective Analysis', results.length, avgConfidence),
    '## Summary',
    '',
    `Applied **6 analysis lenses** to **${results.length}** documents.`,
    '',
    '## Detailed Analysis',
    '',
  ];
 
  const lensEmoji: Record<string, string> = {
    government: '🏛️',
    opposition: '⚖️',
    citizen: '👥',
    economic: '💰',
    international: '🌍',
    media: '📰',
  };
 
  for (const [lens, perspectives] of lensMap) {
    const emoji = lensEmoji[lens] || '🔍';
    const high = perspectives.filter(p => p.impact === 'high').length;
    const avgConf = perspectives.reduce((s, p) => s + p.confidence, 0) / perspectives.length;
    const topActors = [...new Set(perspectives.flatMap(p => p.keyActors))].slice(0, 5);
 
    lines.push(`### ${emoji} ${lens.charAt(0).toUpperCase() + lens.slice(1)} Perspective`, '');
    lines.push(`- **Documents with High Impact**: ${high}/${perspectives.length}`);
    lines.push(`- **Avg Confidence**: ${Math.round(avgConf)}%`);
    lines.push(`- **Key Actors**: ${topActors.join(', ') || 'N/A'}`);
    lines.push('');
 
    // Show top 3 summaries
    const topThree = [...perspectives].sort((a, b) => b.confidence - a.confidence).slice(0, 3);
    for (const p of topThree) {
      Eif (p.summary) {
        lines.push(`> ${p.summary}`);
        lines.push('');
      }
    }
  }
 
  lines.push('## Key Findings', '');
  lines.push('1. All six stakeholder perspectives applied consistently across the document batch.');
  lines.push('2. Cross-perspective conflicts indicate politically contentious documents.');
 
  lines.push('', '## Implications', '');
  lines.push('Perspective analysis feeds directly into article stakeholder framing and balance.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push(`Aggregate confidence: ${confidenceLabel(avgConfidence)}.`);
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Significance scoring
// ---------------------------------------------------------------------------
 
export function serializeSignificanceScoring(
  ctx: SerializationContext,
  entries: SignificanceEntry[],
): string {
  const lines: string[] = [
    frontmatter(ctx, 'Document Significance Scoring', entries.length, 80),
    '## Summary',
    '',
    `Scored **${entries.length}** documents for political significance (0–10 scale).`,
    '',
    '## Detailed Analysis',
    '',
    '| Score | Level | Type | dok_id | Title |',
    '|-------|-------|------|--------|-------|',
  ];
 
  const sorted = [...entries].sort((a, b) => b.score - a.score);
  for (const entry of sorted.slice(0, 30)) {
    const level = escapeMarkdownTableCell(significanceLabel(entry.score).replace(/🔴|🟠|🟡|🟢/g, '').trim());
    const titleValue = entry.title.length > 50 ? entry.title.slice(0, 47) + '...' : entry.title;
    const doctype = escapeMarkdownTableCell(entry.doctype);
    const dokId = escapeMarkdownTableCell(entry.dok_id);
    const title = escapeMarkdownTableCell(titleValue);
    lines.push(`| ${entry.score}/10 | ${level} | ${doctype} | ${dokId} | ${title} |`);
  }
 
  lines.push('', '## Key Findings', '');
  const critical = sorted.filter(e => e.score >= 8);
  lines.push(`1. **${critical.length}** document(s) rated Critical (score ≥ 8)`);
  const high = sorted.filter(e => e.score >= 6 && e.score < 8);
  lines.push(`2. **${high.length}** document(s) rated High (score 6–7)`);
 
  lines.push('', '## Implications', '');
  lines.push('High-significance documents should be prioritised for deep-inspection article generation.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push('Significance scores use document type, committee tier, domain breadth, coalition context, and content richness.');
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Cross-reference map
// ---------------------------------------------------------------------------
 
export function serializeCrossReferenceMap(
  ctx: SerializationContext,
  summary: CrossReferenceSummary,
): string {
  const lines: string[] = [
    frontmatter(ctx, 'Cross-Reference Map', summary.docCount, 75),
    '## Summary',
    '',
    `Detected **${summary.totalLinks}** cross-document relationships.`,
    '',
    '## Detailed Analysis',
    '',
  ];
 
  if (summary.links.length === 0) {
    lines.push('No cross-document relationships detected in current batch.');
  } else {
    const byType = new Map<string, DocumentLink[]>();
    for (const link of summary.links) {
      const arr = byType.get(link.type) ?? [];
      arr.push(link);
      byType.set(link.type, arr);
    }
 
    for (const [type, links] of byType) {
      lines.push(`### ${type}`, '');
      for (const link of links.slice(0, 10)) {
        lines.push(`- **${link.sourceId}** → **${link.targetId}** (confidence: ${link.confidence}%)`);
        lines.push(`  _${link.reason}_`);
      }
      lines.push('');
    }
  }
 
  lines.push('## Key Findings', '');
  lines.push(`1. **${summary.totalLinks}** inter-document relationships mapped`);
 
  lines.push('', '## Implications', '');
  lines.push('Cross-references enrich article narratives by linking related legislative developments.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push('Cross-reference confidence is driven by shared policy domains and textual similarity.');
 
  return lines.join('\n');
}
 
// ---------------------------------------------------------------------------
// Synthesis summary
// ---------------------------------------------------------------------------
 
export function serializeSynthesisSummary(
  ctx: SerializationContext,
  synthesis: SynthesisSummary,
): string {
  const confScore = synthesis.overallConfidence === 'HIGH' ? 80 : synthesis.overallConfidence === 'MEDIUM' ? 55 : 30;
 
  const lines: string[] = [
    frontmatter(ctx, 'Analysis Synthesis Summary', synthesis.totalDocs, confScore),
    '## Summary',
    '',
    synthesis.executiveSummary,
    '',
    '## Key Findings',
    '',
  ];
 
  synthesis.keyFindings.forEach((f, i) => lines.push(`${i + 1}. ${f}`));
 
  lines.push('', '## Top Documents by Significance', '', '| Score | Type | dok_id | Title |', '|-------|------|--------|-------|');
  for (const doc of synthesis.topDocuments.slice(0, 10)) {
    const titleValue = doc.title.length > 50 ? doc.title.slice(0, 47) + '...' : doc.title;
    const doctype = escapeMarkdownTableCell(doc.doctype);
    const dokId = escapeMarkdownTableCell(doc.dok_id);
    const title = escapeMarkdownTableCell(titleValue);
    lines.push(`| ${doc.score}/10 | ${doctype} | ${dokId} | ${title} |`);
  }
 
  lines.push('', '## Implications', '');
  lines.push(`Overall political risk level: **${synthesis.aggregateRiskLevel}**`);
  lines.push('Articles should reference this synthesis to ensure analytical depth and consistency.');
 
  lines.push('', '## Data Quality Notes', '');
  lines.push(`Overall confidence: **${synthesis.overallConfidence}**. All analysis results are available in sibling files.`);
 
  return lines.join('\n');
}