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 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 | 3x 3x 3x 35x 9x 9x 9x 63x 9x 9x 54x 9x 9x 54x 9x 9x 54x 9x 9x 9x 9x 9x 9x 9x 72x 197x 197x 26x 26x 9x 9x 9x 54x 54x 9x 8x 31x 14x 140x 14x 148x 8x 8x 8x 8x 7x 7x 7x 7x 7x 7x 7x 11x 11x 11x 11x 2x 9x 9x 9x 7x 7x 30x 4x 10x 10x 6x 232x 13x 13x 13x 13x 78x 78x 78x 16x 16x 16x 13x 13x 13x 13x 13x 13x 8x 8x 25x 5x 5x 25x 13x 10x 11x 10x 10x 10x 10x 10x 10x 10x 10x 10x 6x 6x 1x 5x 5x 5x 5x 5x 1x 5x 4x 5x 3x 5x 5x 5x 3x 5x 3x 5x 6x 3x 5x 5x 5x 5x 3x 5x 5x 5x 5x 5x 5x 5x 3x 5x 3x 5x 3x 5x 3x 5x 3x 5x 8x 8x 8x 8x 8x 8x 8x 8x 3x | #!/usr/bin/env node
/**
* @module Intelligence/ContentQuality
* @category Intelligence Operations / Supporting Infrastructure
* @name Article Quality Enhancer - Political Intelligence Content Validation Framework (TypeScript)
*
* @description
* Comprehensive content quality assurance system implementing OSINT/INTOP-driven editorial standards
* for political intelligence journalism. This utility validates article structure, analytical depth, source attribution,
* and perspective diversity to ensure intelligence reporting meets rigorous transparency requirements.
*
* @author Hack23 AB (Content Intelligence Team)
* @license Apache-2.0
* @version 2.0.0
*/
import fs from 'fs';
import type { QualityThresholds, QualityMetrics, QualityResult } from './types/validation.js';
import { hasEconomicContext } from './world-bank-context.js';
import { hasSCBContext } from './scb-context.js';
import { hasStatisticalClaims } from './statistical-claims-detector.js';
/**
* Map of normalized party codes to their common name variants.
* Prevents double-counting when both full names and abbreviations appear.
*/
const PARTY_VARIANTS: Readonly<Record<string, readonly string[]>> = {
S: ['Socialdemokraterna', 'Social Democrats', 'S'],
M: ['Moderaterna', 'Moderate', 'M'],
SD: ['Sverigedemokraterna', 'Sweden Democrats', 'SD'],
C: ['Centerpartiet', 'Centre Party', 'C'],
V: ['Vänsterpartiet', 'Left Party', 'V'],
KD: ['Kristdemokraterna', 'Christian Democrats', 'KD'],
L: ['Liberalerna', 'Liberals', 'L'],
MP: ['Miljöpartiet', 'Green Party', 'MP'],
} as const;
/**
* Riksdag/Regering document ID patterns
*/
const DOCUMENT_ID_PATTERNS: readonly RegExp[] = [
/\b[A-Z]{1,3}\d{1,4}\/\d{2}:\d+\b/g, // Committee reports: AU10/24:1
/\bProp\.\s*\d{4}\/\d{2}:\d+\b/gi, // Propositions: Prop. 2024/25:1
/\bBet\.\s*\d{4}\/\d{2}:[A-Z]{1,3}\d+\b/gi, // Committee reports: Bet. 2024/25:FiU10
/\bMot\.\s*\d{4}\/\d{2}:\d+\b/gi, // Motions: Mot. 2024/25:123
/\bIP\s*\d{4}\/\d{2}:\d+\b/gi, // Interpellations: IP 2024/25:45
/\bFr\.\s*\d{4}\/\d{2}:\d+\b/gi, // Questions: Fr. 2024/25:67
];
/**
* Default quality thresholds based on political intelligence editorial standards
*/
const DEFAULT_THRESHOLDS: QualityThresholds = {
minQualityScore: 0.80,
minAnalyticalDepth: 0.6,
minPartySources: 6,
minCrossReferences: 3,
requireWhyThisMatters: true,
requireHistoricalContext: true,
recommendHistoricalContext: true,
recommendInternationalComparison: false,
recommendEconomicContext: true,
recommendSCBContext: true,
recommendWhatHappensNext: true,
recommendWinnersLosers: true,
minSpecificClaims: 3,
};
/**
* Strip HTML tags from content
*/
function stripHtml(html: string): string {
return html.replace(/<[^>]*>/g, ' ').replace(/\s+/g, ' ').trim();
}
/**
* Assess analytical depth of article content
*
* Looks for:
* - Causal reasoning ("because", "therefore", "as a result")
* - Comparative analysis ("compared to", "in contrast", "while")
* - Trend analysis ("trend", "pattern", "shift")
* - Evidence-based claims (references to data, studies, reports)
* - Multiple perspectives (quotes from different actors)
*
* @param content - HTML content of article
* @returns Score 0.0-1.0
*/
function assessAnalyticalDepth(content: string): number {
const text: string = stripHtml(content).toLowerCase();
let score: number = 0.0;
// Causal reasoning indicators (0.2 max)
const causalWords: readonly string[] = ['because', 'therefore', 'as a result', 'consequently', 'due to', 'leads to', 'caused by'];
const causalCount: number = causalWords.filter((word: string) => text.includes(word)).length;
score += Math.min(causalCount * 0.04, 0.2);
// Comparative analysis (0.2 max)
const comparativeWords: readonly string[] = ['compared to', 'in contrast', 'while', 'whereas', 'on the other hand', 'however'];
const comparativeCount: number = comparativeWords.filter((word: string) => text.includes(word)).length;
score += Math.min(comparativeCount * 0.04, 0.2);
// Trend/pattern analysis (0.2 max)
const trendWords: readonly string[] = ['trend', 'pattern', 'shift', 'change', 'evolution', 'development'];
const trendCount: number = trendWords.filter((word: string) => text.includes(word)).length;
score += Math.min(trendCount * 0.04, 0.2);
// Evidence-based claims (0.2 max)
const evidenceWords: readonly string[] = ['data shows', 'according to', 'study', 'report', 'statistics', 'evidence'];
const evidenceCount: number = evidenceWords.filter((word: string) => text.includes(word)).length;
score += Math.min(evidenceCount * 0.04, 0.2);
// Multiple perspectives (0.2 max) - count quotes
const quoteCount: number = (content.match(/<blockquote>/gi) || []).length +
(text.match(/"\w/g) || []).length / 2;
score += Math.min(quoteCount * 0.04, 0.2);
return Math.min(score, 1.0);
}
/**
* Count unique party perspectives mentioned in article.
*
* Uses PARTY_VARIANTS pattern to prevent double-counting when both
* full names and abbreviations appear in the same text.
*
* @param content - HTML content of article
* @returns Number of unique parties mentioned
*/
function countPartyPerspectives(content: string): number {
const text: string = content;
const partiesFound: Set<string> = new Set();
// Iterate through party codes and check all variants
(Object.entries(PARTY_VARIANTS) as [string, readonly string[]][]).forEach(([code, variants]: [string, readonly string[]]) => {
// Check if any variant of this party is mentioned
for (const variant of variants) {
const regex: RegExp = new RegExp(`\\b${variant}\\b`, 'gi');
if (regex.test(text)) {
partiesFound.add(code);
break; // Stop checking variants once party is found
}
}
});
return partiesFound.size;
}
/**
* Count cross-referenced Riksdag/Regering documents
*
* @param content - HTML content of article
* @returns Number of unique document IDs found
*/
function countCrossReferences(content: string): number {
const documentIds: Set<string> = new Set();
DOCUMENT_ID_PATTERNS.forEach((pattern: RegExp) => {
const matches: RegExpMatchArray | null = content.match(pattern);
(matches || []).forEach((match: string) => documentIds.add(match));
});
return documentIds.size;
}
/**
* Detect "Why This Matters" section
*
* @param content - HTML content of article
* @returns True if section exists
*/
function hasWhyThisMatters(content: string): boolean {
const patterns: readonly RegExp[] = [
/why\s+this\s+matters/i,
/varför\s+detta\s+betyder/i,
/betydelse/i,
/implications/i,
/konsekvenser/i,
];
return patterns.some((pattern: RegExp) => pattern.test(content));
}
/**
* Detect "What Happens Next" timeline section.
* Looks for the rendered section class or heading variants across supported languages.
* Covers: en, sv, da, no, fi, de, fr, es, nl, ar, he, ja, ko, zh.
*
* @param content - HTML content of article
* @returns True if the section is present
*/
function hasWhatHappensNext(content: string): boolean {
const patterns: readonly RegExp[] = [
/class=["'][^"']*\bwhat-happens-next\b/,
/what\s+happens\s+next/i,
/vad\s+händer\s+härnäst/i,
/hvad\s+sker\s+der\s+nu/i,
/hva\s+skjer\s+videre/i,
/mitä\s+tapahtuu\s+seuraavaksi/i,
/was\s+passiert\s+als\s+nächstes/i,
/la\s+suite\s+des\s+événements/i,
/qué\s+sucede\s+a\s+continuación/i,
/wat\s+gebeurt\s+er\s+nu/i,
/ماذا يحدث بعد ذلك/,
/מה קורה בהמשך/,
/次のステップ/,
/다음\s+단계/,
/下一步/,
];
return patterns.some((p: RegExp) => p.test(content));
}
/**
* Detect "Winners & Losers" analysis section.
* Looks for the rendered section class or heading variants across supported languages.
* Covers: en, sv, da, no, fi, de, fr, es, nl, ar, he, ja, ko, zh.
*
* @param content - HTML content of article
* @returns True if the section is present
*/
function hasWinnersLosers(content: string): boolean {
const patterns: readonly RegExp[] = [
/class=["'][^"']*\bwinners-losers\b/,
/winners\s*(?:&|and)\s*losers/i,
/vinnare\s+och\s+förlorare/i,
/vindere\s+og\s+tabere/i,
/vinnere\s+og\s+tapere/i,
/voittajat\s+ja\s+häviäjät/i,
/gewinner\s+und\s+verlierer/i,
/gagnants\s+et\s+perdants/i,
/ganadores\s+y\s+perdedores/i,
/winnaars\s+en\s+verliezers/i,
/الرابحون والخاسرون/,
/מנצחים ומפסידים/,
/勝者と敗者/,
/승자와\s+패자/,
/赢家与输家/,
];
return patterns.some((p: RegExp) => p.test(content));
}
/**
* Count approximate words in a specific HTML section identified by its CSS class.
* Returns 0 if the section is not found.
*
* @param content - Full HTML content of article
* @param sectionClass - CSS class of the target section element
* @returns Estimated word count within the section
*/
function countSectionWords(content: string, sectionClass: string): number {
// Find the opening tag with the requested class, then scan forward to the
// matching closing tag while tracking nested <section>/<div> elements.
const escapedClass = sectionClass.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const openingTagPattern = new RegExp(
`<(section|div)\\b[^>]*class=(?:"|')[^"']*\\b${escapedClass}\\b[^"']*(?:"|')[^>]*>`,
'i',
);
const openingMatch = openingTagPattern.exec(content);
if (!openingMatch || openingMatch.index < 0) return 0;
const rootTag = openingMatch[1].toLowerCase();
const contentStart = openingMatch.index + openingMatch[0].length;
const tagPattern = /<\/?(section|div)\b[^>]*>/gi;
tagPattern.lastIndex = contentStart;
const stack: string[] = [rootTag];
let tagMatch: RegExpExecArray | null = tagPattern.exec(content);
while (tagMatch) {
const matchedTag = tagMatch[0];
const tagName = tagMatch[1].toLowerCase();
const isClosingTag = matchedTag.startsWith('</');
if (!isClosingTag) {
stack.push(tagName);
} else if (Estack.length > 0 && stack[stack.length - 1] === tagName) {
stack.pop();
if (stack.length === 0) {
const innerHtml = content.slice(contentStart, tagMatch.index);
const text = innerHtml.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
return text.split(' ').filter((w: string) => w.length > 0).length;
}
}
tagMatch = tagPattern.exec(content);
}
return 0;
}
/**
* Validate that the lede paragraph has sufficient depth (minimum 30 words).
* A lede shorter than this is likely a stub or template placeholder.
*
* @param content - HTML content of article
* @returns True if lede meets the minimum word count
*/
function hasSubstantialLede(content: string): boolean {
const ledeMatch = content.match(/<p[^>]*class=["'][^"']*\blede\b[^"']*["'][^>]*>([\s\S]*?)<\/p>/i);
if (!ledeMatch?.[1]) return false;
const text = ledeMatch[1].replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
return text.split(' ').filter((w: string) => w.length > 0).length >= 30;
}
/**
* Count specific claim indicators in article text.
* Looks for patterns that indicate potentially verifiable, specific content:
* - Explicit document references (Prop., Bet., Mot., IP)
* - Percentage figures
* - Named MPs or ministers matching the pattern "Firstname Lastname (Party)"
*
* @param content - HTML content of article
* @returns Number of detected specific claim indicators
*/
function countSpecificClaims(content: string): number {
const text = stripHtml(content);
let count = 0;
// Count unique normalized document IDs rather than every occurrence to
// prevent repeated mentions of the same citation from inflating the score.
// Cap at 5, consistent with other claim signals below.
const uniqueDocumentReferences = new Set<string>();
DOCUMENT_ID_PATTERNS.forEach((pattern: RegExp) => {
const flags = pattern.global ? pattern.flags : `${pattern.flags}g`;
const globalPattern = new RegExp(pattern.source, flags);
for (const match of text.matchAll(globalPattern)) {
const documentReference = match[0]?.trim();
Eif (documentReference) {
uniqueDocumentReferences.add(documentReference.replace(/\s+/g, ' ').toLowerCase());
}
}
});
count += Math.min(uniqueDocumentReferences.size, 5);
// Percentage figures (e.g. "12%", "3.5%")
// Cap at 5 to prevent a heavily statistics-driven article from
// single-handedly satisfying the minSpecificClaims threshold via
// repetitive figures alone (e.g. budget tables with 20+ percentages).
const percentMatches = text.match(/\b\d+(?:\.\d+)?%/g);
count += percentMatches ? Math.min(percentMatches.length, 5) : 0;
// Named MPs or ministers (Swedish name pattern: "Firstname Lastname (Party)")
// Capped at 5 for the same reason as percentage matches: prevents a roster
// of names without substantive claims from satisfying the threshold.
const namedActors = text.match(/[A-ZÅÄÖ][a-zåäö]+\s+[A-ZÅÄÖ][a-zåäö]+\s*\([A-ZÅÄÖ]{1,3}\)/g);
count += namedActors ? Math.min(namedActors.length, 5) : 0;
return count;
}
/**
* Detect historical context
*
* @param content - HTML content of article
* @returns True if historical context present
*/
function hasHistoricalContext(content: string): boolean {
const text: string = stripHtml(content).toLowerCase();
const patterns: readonly RegExp[] = [
/historically/i,
/in \d{4}/,
/since \d{4}/,
/tidigare/i,
/historiskt/i,
];
return patterns.some((pattern: RegExp) => pattern.test(text));
}
/**
* Detect international comparison
*
* @param content - HTML content of article
* @returns True if international comparison present
*/
function hasInternationalComparison(content: string): boolean {
const text: string = stripHtml(content).toLowerCase();
const patterns: readonly RegExp[] = [
/compared to.*country/i,
/international.*comparison/i,
/other.*countries/i,
/jämfört med.*länder/i,
/internationell.*jämförelse/i,
];
return patterns.some((pattern: RegExp) => pattern.test(text));
}
/**
* Detect language switcher navigation
*
* @param content - HTML content of article
* @returns True if language switcher nav is present
*/
function hasLanguageSwitcher(content: string): boolean {
return /class=["'][^"']*\blanguage-switcher\b/.test(content);
}
/**
* Detect article-top-nav with back-to-news link
*
* @param content - HTML content of article
* @returns True if article-top-nav div is present
*/
function hasArticleTopNav(content: string): boolean {
return /class=["'][^"']*\barticle-top-nav\b/.test(content);
}
/**
* Detect back-to-news link (in top nav or footer)
*
* @param content - HTML content of article
* @returns True if back-to-news link is present
*/
function hasBackToNews(content: string): boolean {
return /class=["'][^"']*\bback-to-news\b/.test(content);
}
/** Weight configuration for quality score calculation */
interface QualityWeights {
readonly analyticalDepth: number;
readonly partyPerspectives: number;
readonly crossReferences: number;
readonly whyThisMatters: number;
readonly historicalContext: number;
readonly internationalComparison: number;
}
/**
* Calculate overall quality score
*
* Weights:
* - Analytical depth: 30%
* - Party perspectives: 25%
* - Cross-references: 25%
* - "Why This Matters": 10%
* - Historical context: 5%
* - International comparison: 5%
*
* @param metrics - Individual quality metrics
* @returns Overall score 0.0-1.0
*/
function calculateQualityScore(metrics: QualityMetrics): number {
const weights: QualityWeights = {
analyticalDepth: 0.30,
partyPerspectives: 0.25,
crossReferences: 0.25,
whyThisMatters: 0.10,
historicalContext: 0.05,
internationalComparison: 0.05,
};
let score: number = 0.0;
// Analytical depth (already 0-1)
score += metrics.analyticalDepth * weights.analyticalDepth;
// Party perspectives (normalize: 6+ parties = 1.0, reflecting 8-party Swedish system)
score += Math.min(metrics.partyCount / 6, 1.0) * weights.partyPerspectives;
// Cross-references (normalize: 3+ refs = 1.0)
score += Math.min(metrics.crossReferences / 3, 1.0) * weights.crossReferences;
// Binary checks
score += (metrics.hasWhyThisMatters ? 1.0 : 0.0) * weights.whyThisMatters;
score += (metrics.hasHistoricalContext ? 1.0 : 0.0) * weights.historicalContext;
score += (metrics.hasInternationalComparison ? 1.0 : 0.0) * weights.internationalComparison;
return Math.min(score, 1.0);
}
/**
* Enhance article quality and validate against thresholds
*
* @param articlePath - Path to article HTML file
* @param thresholds - Quality thresholds (optional, merged with defaults)
* @returns Quality assessment result
*/
export async function enhanceArticleQuality(
articlePath: string,
thresholds: Partial<QualityThresholds> = {},
): Promise<QualityResult> {
const options: QualityThresholds = { ...DEFAULT_THRESHOLDS, ...thresholds };
if (!fs.existsSync(articlePath)) {
return {
passed: false,
error: 'Article file not found',
articlePath,
};
}
const content: string = fs.readFileSync(articlePath, 'utf-8');
// Collect metrics
const metrics: QualityMetrics = {
analyticalDepth: assessAnalyticalDepth(content),
partyCount: countPartyPerspectives(content),
crossReferences: countCrossReferences(content),
hasWhyThisMatters: hasWhyThisMatters(content),
hasHistoricalContext: hasHistoricalContext(content),
hasInternationalComparison: hasInternationalComparison(content),
hasEconomicContext: hasEconomicContext(content),
hasSCBContext: hasSCBContext(content),
hasStatisticalClaims: hasStatisticalClaims(content),
hasLanguageSwitcher: hasLanguageSwitcher(content),
hasArticleTopNav: hasArticleTopNav(content),
hasBackToNews: hasBackToNews(content),
hasWhatHappensNext: hasWhatHappensNext(content),
hasWinnersLosers: hasWinnersLosers(content),
specificClaimsCount: countSpecificClaims(content),
hasSubstantialLede: hasSubstantialLede(content),
};
// Calculate overall score
const qualityScore: number = calculateQualityScore(metrics);
// Validate against thresholds
const issues: string[] = [];
if (qualityScore < options.minQualityScore) {
issues.push(`Quality score ${qualityScore.toFixed(2)} below threshold ${options.minQualityScore}`);
}
if (metrics.analyticalDepth < options.minAnalyticalDepth) {
issues.push(`Analytical depth ${metrics.analyticalDepth.toFixed(2)} below threshold ${options.minAnalyticalDepth}`);
}
if (metrics.partyCount < options.minPartySources) {
issues.push(`Only ${metrics.partyCount} party perspectives (need ${options.minPartySources})`);
}
Eif (metrics.crossReferences < options.minCrossReferences) {
issues.push(`Only ${metrics.crossReferences} cross-references (need ${options.minCrossReferences})`);
}
if (options.requireWhyThisMatters && !metrics.hasWhyThisMatters) {
issues.push('Missing "Why This Matters" section');
}
if (options.requireHistoricalContext && !metrics.hasHistoricalContext) {
issues.push('Missing required historical context (at least one historical comparison required)');
}
// Content depth validation — minimum specific claims
const minClaims = options.minSpecificClaims ?? 0;
if (minClaims > 0 && (metrics.specificClaimsCount ?? 0) < minClaims) {
issues.push(
`Only ${metrics.specificClaimsCount ?? 0} specific verifiable claims detected (need ${minClaims}). ` +
'Add document references, percentage figures, or named actors with party attributions.',
);
}
// Separate warnings (recommendations) from blocking failures
const warnings: string[] = [];
// Only warn about historical context if it is not already a blocking error
Iif (options.recommendHistoricalContext && !options.requireHistoricalContext && !metrics.hasHistoricalContext) {
warnings.push('Recommended: Add historical context');
}
Iif (options.recommendInternationalComparison && !metrics.hasInternationalComparison) {
warnings.push('Recommended: Add international comparison');
}
if (options.recommendEconomicContext && !metrics.hasEconomicContext) {
warnings.push('Recommended: Add economic context (World Bank indicators, GDP, unemployment data)');
}
Eif (options.recommendSCBContext && !metrics.hasSCBContext) {
warnings.push('Recommended: Add Swedish statistical context (SCB official statistics)');
}
Eif (options.recommendWhatHappensNext && !metrics.hasWhatHappensNext) {
warnings.push('Recommended: Add "What Happens Next" timeline section with legislative pipeline dates');
}
Eif (options.recommendWinnersLosers && !metrics.hasWinnersLosers) {
warnings.push('Recommended: Add "Winners & Losers" section naming political actors with evidence');
}
if (!metrics.hasSubstantialLede) {
warnings.push('Lede paragraph appears thin (< 30 words) — consider expanding with the most newsworthy fact');
}
if (metrics.hasStatisticalClaims) {
warnings.push('Info: Article contains statistical claims — consider adding fact-check section');
}
// Navigation structure warnings (generated by template — fallback fix: scripts/fix-article-navigation.py)
if (!metrics.hasLanguageSwitcher) {
warnings.push('Missing language-switcher nav (should be generated by article template)');
}
if (!metrics.hasArticleTopNav) {
warnings.push('Missing article-top-nav div (should be generated by article template)');
}
if (!metrics.hasBackToNews) {
warnings.push('Missing back-to-news link (should be generated by article template)');
}
return {
passed: issues.length === 0, // Only blocking issues affect passed status
qualityScore,
metrics,
issues,
warnings, // Non-blocking recommendations
thresholds: options,
articlePath,
};
}
/**
* Batch enhance multiple articles
*
* @param articlePaths - Array of article paths
* @param thresholds - Quality thresholds (optional, merged with defaults)
* @returns Array of quality results
*/
export async function batchEnhanceQuality(
articlePaths: readonly string[],
thresholds: Partial<QualityThresholds> = {},
): Promise<QualityResult[]> {
const results: QualityResult[] = [];
for (const articlePath of articlePaths) {
const result: QualityResult = await enhanceArticleQuality(articlePath, thresholds);
results.push(result);
}
return results;
}
/**
* Fix common HTML nesting errors in article content.
*
* Corrects invalid block-level nesting patterns:
* - `<p><ul>` → removes the enclosing `<p>` so the `<ul>` list is not nested inside a `<p>` paragraph
* - `<p><ol>` → removes the enclosing `<p>` so the `<ol>` list is not nested inside a `<p>` paragraph
* - `<p><div>` → removes the enclosing `<p>` so the block-level `<div>` is not nested inside a `<p>` paragraph
* - Orphaned `</p>` immediately after `</ul>` → removed
* - Orphaned `</p>` immediately after `</ol>` → removed
* - Orphaned `</p>` immediately after `</div>` (when wrapped by `<p>`) → removed
*
* @param content - Raw HTML content
* @returns Fixed HTML content
*/
export function fixArticleHtmlNesting(content: string): string {
let fixed = content;
// Fix <p><ul>: remove the enclosing <p> so the list is not nested inside a paragraph
fixed = fixed.replace(/<p([^>]*)>\s*(<ul[\s>])/g, '$2');
// Fix <p><ol>: remove the enclosing <p> so the ordered list is not nested inside a paragraph
fixed = fixed.replace(/<p([^>]*)>\s*(<ol[\s>])/g, '$2');
// Fix <p><div>: remove enclosing <p> around block-level div
fixed = fixed.replace(/<p([^>]*)>\s*(<div[\s>])/g, '$2');
// Fix orphaned </p> immediately after </ul>
fixed = fixed.replace(/<\/ul>\s*<\/p>/g, '</ul>');
// Fix orphaned </p> immediately after </ol>
fixed = fixed.replace(/<\/ol>\s*<\/p>/g, '</ol>');
// Fix orphaned </p> immediately after </div> that was wrapped in <p>
fixed = fixed.replace(/<\/div>\s*<\/p>/g, '</div>');
return fixed;
}
/**
* Fix HTML nesting errors in a file in-place.
*
* @param filePath - Path to the HTML file to fix
* @returns True if the file was modified
*/
export function fixHtmlNestingInFile(filePath: string): boolean {
if (!fs.existsSync(filePath)) {
return false;
}
const original = fs.readFileSync(filePath, 'utf-8');
const fixed = fixArticleHtmlNesting(original);
if (fixed !== original) {
fs.writeFileSync(filePath, fixed, 'utf-8');
return true;
}
return false;
}
// CLI entry point: support --fix flag to fix HTML nesting in news/*-*.html article files
Iif (import.meta.url === `file://${process.argv[1]}`) {
if (process.argv.includes('--fix')) {
const globPattern = process.argv[process.argv.indexOf('--fix') + 1];
const targetGlob = (globPattern && !globPattern.startsWith('-')) ? globPattern : 'news/*-*.html';
const { globSync } = await import('glob');
const files: string[] = globSync(targetGlob);
let fixedCount = 0;
for (const file of files) {
if (fixHtmlNestingInFile(file)) {
console.log(`Fixed HTML nesting in: ${file}`);
fixedCount++;
}
}
console.log(`Fixed ${fixedCount} of ${files.length} files.`);
}
}
// Export individual assessment functions for testing
export {
assessAnalyticalDepth,
countPartyPerspectives,
countCrossReferences,
hasWhyThisMatters,
hasWhatHappensNext,
hasWinnersLosers,
hasHistoricalContext,
hasInternationalComparison,
hasLanguageSwitcher,
hasArticleTopNav,
hasBackToNews,
countSpecificClaims,
hasSubstantialLede,
countSectionWords,
calculateQualityScore,
DEFAULT_THRESHOLDS,
};
|