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 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 | 36x 36x 36x 36x 36x 250x 250x 250x 250x 123x 123x 123x 185x 185x 92x 31x 37x 81x 81x 18x 18x 196x 23x 23x 18x 14x 14x 13x 4x 3x 80x 80x 37x 30x 12x 12x 11x 4x 3x 6x 6x 2x 1x 1x 14x 14x 13x 4x 4x 10x 10x 10x 4x 4x 36x 36x 36x 48x 48x 38x 38x 48x 48x 48x 48x 38x 14x 14x 14x 14x 14x 14x 14x 14x 14x 12x 12x 12x 12x 12x 12x 12x 12x 9x 9x 9x 9x 9x 9x 9x 6x 6x 6x 6x 6x 6x 6x 6x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 10x 10x 10x 10x 10x 10x 10x 16x 16x 12x 12x 10x 8x 8x 8x 8x 8x 8x 8x 8x 8x 36x 36x 36x 98x 98x 98x 98x 98x 75x 14x 14x 14x 14x 14x 14x 14x 14x 14x 47x 14x 20x 20x 20x 64x 64x 64x 64x 64x 11x 5x 60x 17x 17x 14x 14x 3x 5x | /**
* @module analysis-reader
* @description Reads pre-computed political intelligence analysis files from
* `analysis/daily/YYYY-MM-DD/` and provides a structured TypeScript API for
* article generators to consume classification, risk, SWOT, threat, and
* significance data.
*
* Falls back gracefully when analysis files are absent ā backward compatible
* with article generators that do not yet consume pre-computed analysis.
*
* @example
* ```typescript
* import { readDailyAnalysis } from './analysis-reader.js';
*
* const analysis = await readDailyAnalysis('2026-03-26');
* if (analysis.hasAnalysis) {
* const { classification, riskAssessment, significance } = analysis;
* // Enrich article generation with pre-computed intelligence
* }
* ```
*
* @author Hack23 AB
* @license Apache-2.0
*/
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
import { existsSync } from 'node:fs';
import type { UrgencyLabel } from './ai-analysis/political-significance.js';
// ---------------------------------------------------------------------------
// Classification types
// ---------------------------------------------------------------------------
/** Political intelligence classification level */
export type ClassificationLevel = 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
/** Editorial priority level */
export type PriorityLevel = 'breaking' | 'major' | 'standard' | 'background';
/** Confidence label for analytical claims */
export type ConfidenceLabel = 'HIGH' | 'MEDIUM' | 'LOW';
/** Risk level for political assessments */
export type RiskLevel = 'high' | 'elevated' | 'moderate' | 'low';
// ---------------------------------------------------------------------------
// Analysis result types
// ---------------------------------------------------------------------------
/** Parsed classification results from `classification-results.md` */
export interface ClassificationResult {
/** Overall classification level */
level: ClassificationLevel;
/** Editorial priority */
priority: PriorityLevel;
/** Overall confidence in the classification */
confidence: ConfidenceLabel;
/** Raw summary text extracted from the markdown */
summary: string;
/** Document IDs classified in this analysis */
documentIds: string[];
/** Policy domains identified */
domains: string[];
}
/** Parsed risk assessment from `risk-assessment.md` */
export interface RiskAssessment {
/** Overall risk level */
level: RiskLevel;
/** Key risk factors (parsed bullet list) */
factors: string[];
/** Risk indicators (inline ā ļø tagged items) */
indicators: string[];
/** Overall confidence in the risk assessment */
confidence: ConfidenceLabel;
/** Raw summary text */
summary: string;
}
/** Single SWOT entry with confidence and impact */
export interface AnalysisSwotEntry {
/** Description text */
text: string;
/** Confidence level of this entry */
confidence: ConfidenceLabel;
/** Relative impact */
impact?: 'high' | 'medium' | 'low';
/** Source document IDs */
sourceDocIds?: string[];
}
/** Parsed SWOT analysis from `swot-analysis.md` */
export interface SwotAnalysisResult {
/** Subject of the SWOT analysis */
subject: string;
strengths: AnalysisSwotEntry[];
weaknesses: AnalysisSwotEntry[];
opportunities: AnalysisSwotEntry[];
threats: AnalysisSwotEntry[];
/** Additional context note */
context?: string;
}
/** Democratic health assessment label */
export type DemocraticHealthLabel = 'HIGH' | 'MEDIUM' | 'LOW' | 'AT_RISK';
/** Parsed threat analysis from `threat-analysis.md` */
export interface ThreatAnalysisResult {
/** Named threat indicators (šÆ tagged items) */
indicators: string[];
/** Democratic health assessment (HIGH/MEDIUM/LOW/AT_RISK) */
democraticHealth: DemocraticHealthLabel;
/** Key threat actors */
actors: string[];
/** Overall confidence in the threat analysis */
confidence: ConfidenceLabel;
/** Raw summary text */
summary: string;
}
/** Parsed stakeholder perspectives from `stakeholder-perspectives.md` */
export interface StakeholderPerspectivesResult {
/** Government/coalition perspective summary */
government: string;
/** Opposition perspective summary */
opposition: string;
/** Citizen perspective summary */
citizen: string;
/** Economic perspective summary */
economic: string;
/** International perspective summary */
international: string;
/** Media/discourse perspective summary */
media: string;
}
/** Parsed significance scoring from `significance-scoring.md` */
export interface SignificanceScoringResult {
/** Significance score (0ā100) */
score: number;
/** Urgency label */
urgency: UrgencyLabel;
/** Ranked list of most significant documents */
topDocuments: Array<{ docId: string; score: number; reason: string }>;
/** Overall confidence in significance scoring */
confidence: ConfidenceLabel;
}
/** Parsed synthesis summary from `synthesis-summary.md` */
export interface SynthesisSummaryResult {
/** Primary narrative direction for the lede */
narrativeDirection: string;
/** Key themes identified across all documents */
keyThemes: string[];
/** Recommended article focus */
articleFocus: string;
/** Forward indicators for "What to Watch Next" */
forwardIndicators: string[];
}
/** Complete pre-computed daily analysis for a given date */
export interface DailyAnalysis {
/** Date of the analysis (YYYY-MM-DD) */
date: string;
/** Classification results (from classification-results.md) */
classification: ClassificationResult | null;
/** Risk assessment (from risk-assessment.md) */
riskAssessment: RiskAssessment | null;
/** SWOT analysis (from swot-analysis.md) */
swot: SwotAnalysisResult | null;
/** Threat analysis (from threat-analysis.md) */
threatAnalysis: ThreatAnalysisResult | null;
/** Stakeholder perspectives (from stakeholder-perspectives.md) */
stakeholderPerspectives: StakeholderPerspectivesResult | null;
/** Significance scoring (from significance-scoring.md) */
significance: SignificanceScoringResult | null;
/** Synthesis summary (from synthesis-summary.md) */
synthesis: SynthesisSummaryResult | null;
/** Whether any analysis files were found */
hasAnalysis: boolean;
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** Regex pattern for matching Riksdag document IDs (e.g., H9011, H902A) */
const DOC_ID_PATTERN = /\b[A-Z]\d{3,7}[A-Z]?\b/g;
/** Default significance score when none is found in the markdown */
const DEFAULT_SIGNIFICANCE_SCORE = 50;
// ---------------------------------------------------------------------------
// Markdown parsing helpers
// ---------------------------------------------------------------------------
/**
* Extract the first heading level 2 section content from markdown.
* Returns the text content between the heading and the next heading.
*/
function extractSection(markdown: string, sectionName: string): string {
const escapedName = sectionName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(
`##\\s+${escapedName}\\s*\\n([\\s\\S]*?)(?=\\n##\\s|$)`,
'i',
);
const match = regex.exec(markdown);
return match?.[1]?.trim() ?? '';
}
/**
* Extract the value of a key-value pair from markdown.
* Supports formats: `**Key**: Value`, `- Key: Value`, `Key: Value`
*/
function extractValue(markdown: string, key: string): string {
const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const patterns = [
new RegExp(`\\*\\*${escapedKey}\\*\\*:\\s*(.+)`, 'i'),
new RegExp(`-\\s+${escapedKey}:\\s*(.+)`, 'i'),
new RegExp(`${escapedKey}:\\s*(.+)`, 'i'),
];
for (const pattern of patterns) {
const match = pattern.exec(markdown);
if (match?.[1]) {
return match[1].trim().replace(/\*\*/g, '').replace(/`/g, '');
}
}
return '';
}
/**
* Extract a bullet list from a markdown section as an array of strings.
* Handles both `- item` and `* item` formats.
*/
function extractBulletList(text: string): string[] {
return text
.split('\n')
.map(line => line.replace(/^[\s\-*]+/, '').trim())
.filter(line => line.length > 0 && !line.startsWith('#'));
}
/**
* Extract items tagged with a specific emoji icon from text.
*/
function extractIconTagged(text: string, icon: string): string[] {
const results: string[] = [];
for (const line of text.split('\n')) {
if (line.includes(icon)) {
const cleaned = line.replace(/^[\s\-*]+/, '').trim();
Eif (cleaned) results.push(cleaned);
}
}
return results;
}
/**
* Normalize a string to a ClassificationLevel.
* Returns 'MEDIUM' as default when unrecognized.
*/
function toClassificationLevel(value: string): ClassificationLevel {
const upper = value.toUpperCase().trim();
if (upper === 'CRITICAL') return 'CRITICAL';
if (upper === 'HIGH') return 'HIGH';
if (upper === 'LOW') return 'LOW';
return 'MEDIUM';
}
/**
* Normalize a string to a ConfidenceLabel.
* Returns 'MEDIUM' as default when unrecognized.
*/
function toConfidenceLabel(value: string): ConfidenceLabel {
const upper = value.toUpperCase().trim();
if (upper === 'HIGH') return 'HIGH';
if (upper === 'LOW') return 'LOW';
return 'MEDIUM';
}
/**
* Normalize a string to a RiskLevel.
* Returns 'moderate' as default when unrecognized.
*/
function toRiskLevel(value: string): RiskLevel {
const lower = value.toLowerCase().trim();
if (lower === 'high') return 'high';
if (lower === 'elevated') return 'elevated';
if (lower === 'low') return 'low';
return 'moderate';
}
/**
* Normalize a string to a DemocraticHealthLabel.
* Returns 'MEDIUM' as default when unrecognized.
*/
function toDemocraticHealthLabel(value: string): DemocraticHealthLabel {
const upper = value.toUpperCase().trim().replace(/[\s_-]+/g, '_');
if (upper === 'HIGH') return 'HIGH';
if (upper === 'LOW') return 'LOW';
Iif (upper === 'AT_RISK' || upper === 'ATRISK') return 'AT_RISK';
return 'MEDIUM';
}
/**
* Normalize a string to a PriorityLevel.
* Returns 'standard' as default when unrecognized.
*/
function toPriorityLevel(value: string): PriorityLevel {
const lower = value.toLowerCase().trim();
if (lower === 'breaking') return 'breaking';
if (lower === 'major') return 'major';
Iif (lower === 'background') return 'background';
return 'standard';
}
/**
* Normalize urgency labels to the known UrgencyLabel union.
* Returns 'standard' as safe default for unrecognized values.
*/
function toUrgencyLabel(value: string): UrgencyLabel {
const lower = value.toLowerCase().trim();
Iif (lower === 'breaking') return 'breaking';
if (lower === 'major') return 'major';
Iif (lower === 'background') return 'background';
return 'standard';
}
/**
* Parse SWOT entries from a markdown quadrant section.
*/
function parseSwotEntries(sectionText: string): AnalysisSwotEntry[] {
const entries: AnalysisSwotEntry[] = [];
const blocks = sectionText.split(/\n(?=[-*]|\d+\.)/);
for (const block of blocks) {
const text = block.replace(/^\s*(?:[-*]|\d+\.)\s+/, '').trim();
if (!text || text.startsWith('#')) continue;
// Detect confidence: HIGH, MEDIUM, LOW in square brackets or inline
const confMatch = /\[(HIGH|MEDIUM|LOW)\]/i.exec(text);
const confidence = confMatch ? toConfidenceLabel(confMatch[1]!) : 'MEDIUM';
// Detect impact
const impactMatch = /impact:\s*(high|medium|low)/i.exec(text);
const impact = impactMatch
? (impactMatch[1]!.toLowerCase() as 'high' | 'medium' | 'low')
: undefined;
// Detect source doc IDs (alphanumeric document ID patterns like H9011, H902A)
const docIdMatches = text.match(DOC_ID_PATTERN) ?? [];
entries.push({
text: text.replace(/\[(HIGH|MEDIUM|LOW)\]/gi, '').replace(/impact:\s*(high|medium|low)/gi, '').trim(),
confidence,
impact,
sourceDocIds: docIdMatches,
});
}
return entries.filter(e => e.text.length > 0);
}
// ---------------------------------------------------------------------------
// File parsers
// ---------------------------------------------------------------------------
/**
* Parse `classification-results.md` into a structured ClassificationResult.
*/
export function parseClassificationResults(markdown: string): ClassificationResult {
const level = toClassificationLevel(extractValue(markdown, 'Level') || extractValue(markdown, 'Classification Level'));
const priority = toPriorityLevel(extractValue(markdown, 'Priority'));
const confidence = toConfidenceLabel(extractValue(markdown, 'Confidence'));
// Extract document IDs mentioned in the text
const documentIds = Array.from(new Set(markdown.match(DOC_ID_PATTERN) ?? []));
// Extract domains from bullet list in Domains or Policy Domains section
const domainsSection = extractSection(markdown, 'Policy Domains') || extractSection(markdown, 'Domains');
const domains = domainsSection
? extractBulletList(domainsSection)
: extractBulletList(extractSection(markdown, 'Classification') || '');
// Summary: prefer explicit `## Summary` section, fallback to first non-heading paragraph
const summarySection = extractSection(markdown, 'Summary');
const summary =
(summarySection && summarySection.trim()) ||
/^(?!#)(.{30,})/m.exec(markdown)?.[1]?.trim() ||
markdown.split('\n').find(l => l.trim().length > 30)?.trim() ||
'';
return { level, priority, confidence, summary, documentIds, domains: domains.slice(0, 10) };
}
/**
* Parse `risk-assessment.md` into a structured RiskAssessment.
*/
export function parseRiskAssessment(markdown: string): RiskAssessment {
const level = toRiskLevel(extractValue(markdown, 'Overall Risk') || extractValue(markdown, 'Risk Level'));
const confidence = toConfidenceLabel(extractValue(markdown, 'Confidence'));
const factorsSection = extractSection(markdown, 'Risk Factors') || extractSection(markdown, 'Factors');
const factors = factorsSection ? extractBulletList(factorsSection) : [];
const indicators = extractIconTagged(markdown, 'ā ļø');
const summarySection = extractSection(markdown, 'Summary') || extractSection(markdown, 'Overview');
const summary = summarySection || markdown.split('\n').filter(l => l.trim().length > 30).slice(0, 2).join(' ');
return { level, factors: factors.slice(0, 10), indicators: indicators.slice(0, 8), confidence, summary };
}
/**
* Parse `swot-analysis.md` into a structured SwotAnalysisResult.
*/
export function parseSwotAnalysis(markdown: string): SwotAnalysisResult {
const subject = extractValue(markdown, 'Subject') || 'Swedish Parliament';
const context = extractSection(markdown, 'Context') || undefined;
const strengthsSection = extractSection(markdown, 'Strengths') || extractSection(markdown, 'šŖ Strengths');
const weaknessesSection = extractSection(markdown, 'Weaknesses') || extractSection(markdown, 'ā” Weaknesses');
const opportunitiesSection = extractSection(markdown, 'Opportunities') || extractSection(markdown, 'š Opportunities');
const threatsSection = extractSection(markdown, 'Threats') || extractSection(markdown, 'āļø Threats');
return {
subject,
strengths: parseSwotEntries(strengthsSection),
weaknesses: parseSwotEntries(weaknessesSection),
opportunities: parseSwotEntries(opportunitiesSection),
threats: parseSwotEntries(threatsSection),
context,
};
}
/**
* Parse `threat-analysis.md` into a structured ThreatAnalysisResult.
*/
export function parseThreatAnalysis(markdown: string): ThreatAnalysisResult {
const indicators = extractIconTagged(markdown, 'šÆ');
const democraticHealth = toDemocraticHealthLabel(extractValue(markdown, 'Democratic Health') || extractValue(markdown, 'Health Status') || 'MEDIUM');
const confidence = toConfidenceLabel(extractValue(markdown, 'Confidence'));
const actorsSection = extractSection(markdown, 'Key Actors') || extractSection(markdown, 'Actors');
const actors = actorsSection ? extractBulletList(actorsSection) : [];
const summarySection = extractSection(markdown, 'Summary') || extractSection(markdown, 'Overview');
const summary = summarySection || markdown.split('\n').filter(l => l.trim().length > 30).slice(0, 2).join(' ');
return { indicators: indicators.slice(0, 8), democraticHealth, actors: actors.slice(0, 6), confidence, summary };
}
/**
* Parse `stakeholder-perspectives.md` into a structured StakeholderPerspectivesResult.
*/
export function parseStakeholderPerspectives(markdown: string): StakeholderPerspectivesResult {
const government = extractSection(markdown, 'šļø Government') || extractSection(markdown, 'Government') || '';
const opposition = extractSection(markdown, 'āļø Opposition') || extractSection(markdown, 'Opposition') || '';
const citizen =
extractSection(markdown, 'š„ Citizen') ||
extractSection(markdown, 'Citizen') ||
extractSection(markdown, 'Citizens') ||
'';
const economic = extractSection(markdown, 'š° Economic') || extractSection(markdown, 'Economic') || '';
const international = extractSection(markdown, 'š International') || extractSection(markdown, 'International') || '';
const media = extractSection(markdown, 'š° Media') || extractSection(markdown, 'Media') || '';
return {
government: government.split('\n').filter(l => l.trim()).join(' ').trim(),
opposition: opposition.split('\n').filter(l => l.trim()).join(' ').trim(),
citizen: citizen.split('\n').filter(l => l.trim()).join(' ').trim(),
economic: economic.split('\n').filter(l => l.trim()).join(' ').trim(),
international: international.split('\n').filter(l => l.trim()).join(' ').trim(),
media: media.split('\n').filter(l => l.trim()).join(' ').trim(),
};
}
/**
* Parse `significance-scoring.md` into a structured SignificanceScoringResult.
*/
export function parseSignificanceScoring(markdown: string): SignificanceScoringResult {
const scoreStr = extractValue(markdown, 'Overall Score') || extractValue(markdown, 'Score');
const score = scoreStr ? Math.min(100, Math.max(0, parseInt(scoreStr, 10) || DEFAULT_SIGNIFICANCE_SCORE)) : DEFAULT_SIGNIFICANCE_SCORE;
const urgency = toUrgencyLabel(extractValue(markdown, 'Urgency') || 'standard');
const confidence = toConfidenceLabel(extractValue(markdown, 'Confidence'));
// Extract top documents from a list
const topDocumentsSection = extractSection(markdown, 'Top Documents') || extractSection(markdown, 'Significant Documents');
const topDocuments: Array<{ docId: string; score: number; reason: string }> = [];
for (const line of topDocumentsSection.split('\n')) {
const match = /([A-Z]\d{3,7}[A-Z]?).*?(\d{1,3})(?:%|\s+points?|\s+score)?[:\sā-]+(.+)/i.exec(line.trim());
if (match) {
const rawScore = parseInt(match[2]!, 10);
topDocuments.push({
docId: match[1]!,
score: Math.min(100, Math.max(0, Number.isFinite(rawScore) ? rawScore : 0)),
reason: match[3]!.trim(),
});
}
}
return { score, urgency, topDocuments: topDocuments.slice(0, 5), confidence };
}
/**
* Parse `synthesis-summary.md` into a structured SynthesisSummaryResult.
*/
export function parseSynthesisSummary(markdown: string): SynthesisSummaryResult {
const narrativeDirection = extractSection(markdown, 'Narrative Direction') || extractSection(markdown, 'Primary Narrative') || '';
const articleFocus = extractSection(markdown, 'Article Focus') || extractSection(markdown, 'Focus') || '';
const themesSection = extractSection(markdown, 'Key Themes') || extractSection(markdown, 'Themes');
const keyThemes = themesSection ? extractBulletList(themesSection) : [];
const forwardSection = extractSection(markdown, 'Forward Indicators') || extractSection(markdown, 'What to Watch');
const forwardIndicators = forwardSection ? extractBulletList(forwardSection) : [];
return {
narrativeDirection: narrativeDirection.split('\n').filter(l => l.trim()).join(' ').trim(),
keyThemes: keyThemes.slice(0, 8),
articleFocus: articleFocus.split('\n').filter(l => l.trim()).join(' ').trim(),
forwardIndicators: forwardIndicators.slice(0, 5),
};
}
// ---------------------------------------------------------------------------
// File reading helpers
// ---------------------------------------------------------------------------
/** Base path for the analysis directory relative to project root */
const ANALYSIS_BASE_PATH = 'analysis/daily';
/** Analysis file names within a daily directory */
const ANALYSIS_FILES = {
classification: 'classification-results.md',
risk: 'risk-assessment.md',
swot: 'swot-analysis.md',
threat: 'threat-analysis.md',
stakeholders: 'stakeholder-perspectives.md',
significance: 'significance-scoring.md',
synthesis: 'synthesis-summary.md',
} as const;
/** Strict YYYY-MM-DD format guard to prevent path traversal via `date`. */
const DATE_FORMAT_RE = /^\d{4}-\d{2}-\d{2}$/;
/**
* Attempt to read a markdown file from the analysis directory.
* Returns `null` if the file does not exist, cannot be read, or `date` is
* not a valid YYYY-MM-DD string (guards against path traversal).
*/
async function readAnalysisFile(date: string, filename: string, basePath?: string): Promise<string | null> {
Iif (!DATE_FORMAT_RE.test(date)) return null;
const resolvedBase = basePath ?? ANALYSIS_BASE_PATH;
const filePath = join(resolvedBase, date, filename);
try {
return await readFile(filePath, 'utf-8');
} catch {
return null;
}
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
* Read and parse all pre-computed analysis files for a given date.
*
* @param date - Date string in YYYY-MM-DD format
* @param basePath - Optional override for the base analysis directory path
* @returns Complete DailyAnalysis object; individual fields are `null` when
* the corresponding file is absent or cannot be parsed.
*
* @example
* ```typescript
* const analysis = await readDailyAnalysis('2026-03-26');
* if (analysis.hasAnalysis) {
* console.log(analysis.classification?.level); // 'HIGH'
* console.log(analysis.significance?.score); // 72
* }
* ```
*/
export async function readDailyAnalysis(date: string, basePath?: string): Promise<DailyAnalysis> {
const [
classificationMd,
riskMd,
swotMd,
threatMd,
stakeholdersMd,
significanceMd,
synthesisMd,
] = await Promise.all([
readAnalysisFile(date, ANALYSIS_FILES.classification, basePath),
readAnalysisFile(date, ANALYSIS_FILES.risk, basePath),
readAnalysisFile(date, ANALYSIS_FILES.swot, basePath),
readAnalysisFile(date, ANALYSIS_FILES.threat, basePath),
readAnalysisFile(date, ANALYSIS_FILES.stakeholders, basePath),
readAnalysisFile(date, ANALYSIS_FILES.significance, basePath),
readAnalysisFile(date, ANALYSIS_FILES.synthesis, basePath),
]);
const classification = classificationMd ? parseClassificationResults(classificationMd) : null;
const riskAssessment = riskMd ? parseRiskAssessment(riskMd) : null;
const swot = swotMd ? parseSwotAnalysis(swotMd) : null;
const threatAnalysis = threatMd ? parseThreatAnalysis(threatMd) : null;
const stakeholderPerspectives = stakeholdersMd ? parseStakeholderPerspectives(stakeholdersMd) : null;
const significance = significanceMd ? parseSignificanceScoring(significanceMd) : null;
const synthesis = synthesisMd ? parseSynthesisSummary(synthesisMd) : null;
const hasAnalysis = [
classification,
riskAssessment,
swot,
threatAnalysis,
stakeholderPerspectives,
significance,
synthesis,
].some(field => field !== null);
return {
date,
classification,
riskAssessment,
swot,
threatAnalysis,
stakeholderPerspectives,
significance,
synthesis,
hasAnalysis,
};
}
/**
* Derive the most recent date for which analysis files exist.
* Searches backwards from today up to `maxDaysBack` days.
*
* @param maxDaysBack - Maximum number of days to search back (default 7)
* @param basePath - Optional override for the base analysis directory path
* @returns ISO date string (YYYY-MM-DD) or `null` if no analysis found
*/
export async function findLatestAnalysisDate(maxDaysBack = 7, basePath?: string): Promise<string | null> {
const resolvedBase = basePath ?? ANALYSIS_BASE_PATH;
const today = new Date();
for (let i = 0; i < maxDaysBack; i++) {
const d = new Date(today);
d.setDate(d.getDate() - i);
const dateStr = d.toISOString().split('T')[0]!;
const dirPath = join(resolvedBase, dateStr);
if (existsSync(dirPath)) {
// Check at least one analysis file exists
const hasFile = Object.values(ANALYSIS_FILES).some(f => existsSync(join(dirPath, f)));
if (hasFile) return dateStr;
}
}
return null;
}
/**
* Read the most recent available daily analysis.
* Convenience wrapper around `findLatestAnalysisDate` + `readDailyAnalysis`.
*
* @param maxDaysBack - Maximum number of days to search back (default 7)
* @param basePath - Optional override for the base analysis directory path
* @returns DailyAnalysis for the most recent date found, or a stub with
* `hasAnalysis: false` when no analysis files exist.
*/
export async function readLatestAnalysis(maxDaysBack = 7, basePath?: string): Promise<DailyAnalysis> {
const date = await findLatestAnalysisDate(maxDaysBack, basePath);
if (!date) {
const today = new Date().toISOString().split('T')[0]!;
return {
date: today,
classification: null,
riskAssessment: null,
swot: null,
threatAnalysis: null,
stakeholderPerspectives: null,
significance: null,
synthesis: null,
hasAnalysis: false,
};
}
return readDailyAnalysis(date, basePath);
}
/**
* Derive article classification metadata from a DailyAnalysis.
* Returns safe defaults when analysis is absent.
*
* @param analysis - DailyAnalysis object (may have hasAnalysis: false)
* @returns Flattened metadata suitable for ArticleData enrichment
*/
export function deriveArticleClassificationMeta(analysis: DailyAnalysis): {
classificationLevel: ClassificationLevel;
riskLevel: RiskLevel;
confidenceLabel: ConfidenceLabel;
significanceScore: number | undefined;
urgency: UrgencyLabel | undefined;
} {
return {
classificationLevel: analysis.classification?.level ?? 'MEDIUM',
riskLevel: analysis.riskAssessment?.level ?? 'moderate',
confidenceLabel: analysis.classification?.confidence ?? analysis.riskAssessment?.confidence ?? 'MEDIUM',
significanceScore: analysis.significance?.score,
urgency: analysis.significance?.urgency,
};
}
|