All files / scripts dump-article-seo.js

76.85% Statements 186/242
59.82% Branches 70/117
75% Functions 12/16
80.18% Lines 178/222

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                                                                                                                                                          2x                       10x 10x 10x 10x 10x 10x   10x 10x 10x           2x 2x 2x   1x 1x 1x   1x 1x 1x   5x 5x 3x   2x 2x 1x   1x 1x 1x                   1x       5x 1x         4x       9x 9x     9x                                                                               7x 7x     6x 6x         6x 6x 6x 6x   6x 6x 6x     6x           6x     6x       12x                                                         6x 6x 6x               6x 6x           6x 6x 6x   6x                                                                       19x 19x                     19x 19x         19x                                   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x     4x     4x 4x     4x 4x 4x 4x 4x       12x   12x                                         3x   660x 3x 3x 3x   3x 3x 3x 3x 3x         3x 3x 3x 3x 3x 3x 3x   3x 3x   3x                     3x 3x   3x 3x   3x 3x                 3x   3x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x             3x 3x 3x 3x 3x     3x 3x 3x   3x                                   3x 3x       3x                               3x 3x   3x 1x 1x   3x 1x 1x     3x                                                                   3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x     3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x               3x             3x 3x         2x     2x                    
#!/usr/bin/env node
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module scripts/dump-article-seo
 * @description Read-only preview of the SEO `<head>` metadata that the
 * deterministic article generator **would produce** for every executive
 * brief committed under `analysis/daily/`. Use this before running
 * `npm run generate-article:all` to audit and improve titles,
 * descriptions, and keywords without touching any `news/*.html` file.
 *
 * **Source: executive briefs, not HTML.**
 * The script reads each analysis run's `executive-brief.md` (and its
 * translated siblings) via the same resolver chain that the real
 * article generator uses. No HTML files are read or written; the script
 * is purely additive and fully idempotent.
 *
 * **Identical code path to the real renderer.** The script intentionally
 * imports the same helpers that `scripts/aggregator/article-generator.js`
 * (the engine behind `npm run generate-article:all` and the
 * `regenerate-articles.yml` workflow) uses:
 *
 *   1. `discoverAnalysisRuns(repoRoot)` — same run discovery as the batch
 *      renderer (`generator/render-batch.js`).
 *   2. `aggregateAnalysisRun({ runDir, repoRoot })` — same Markdown
 *      aggregation that feeds `resolveArticleMetadata`, which in turn
 *      reads `executive-brief.md` and its translated siblings.
 *   3. `resolveArticleMetadata({ articleType, date, markdown, manifest,
 *      runDir })` — the single source of truth for per-language `(title,
 *      description, extendedDescription, keywords, source)` documented in
 *      `src/aggregator/article-metadata.ts`. The entry returned here is
 *      *bit-for-bit identical* to the one passed into
 *      `src/aggregator/html/shell.ts` for the `<title>`,
 *      `<meta name="description">`, and `<meta name="keywords">` tags.
 *
 * **Two-part output per run.**
 *   - *Field analysis* — human-readable breakdown of each SEO field
 *     (length, content, resolution tier) for quick editorial review.
 *   - *HTML head snippet* — the **complete `<head>` block** that the
 *     article generator will emit, produced by calling
 *     `wrapArticleHtml()` from `src/aggregator/html/shell.ts` with an
 *     empty body and slicing out `<head>...</head>`. This includes the
 *     `<title>`, `<meta name="description">`, `<meta name="keywords">`,
 *     all `<meta property="og:*">` and `<meta name="twitter:*">` tags,
 *     `<link rel="canonical">`, hreflang alternates, JSON-LD
 *     `NewsArticle` + `BreadcrumbList`, and every other tag the real
 *     renderer emits — because the snippet *is* the real renderer's
 *     output. Copy-paste these into a browser extension or SEO tool to
 *     preview how the article will appear in search results and social
 *     cards before committing to HTML generation.
 *
 * Invocation:
 *   node scripts/dump-article-seo.js \
 *     [--repo-root <path>]   # defaults to process.cwd()
 *     [--lang en]            # defaults to en
 *     [--out <path>]         # also write the human-readable dump here
 *     [--json <path>]        # also write a machine-readable JSONL dump
 *     [--limit <N>]          # only process the first N runs (debug)
 *     [--quiet]              # suppress per-run stdout (file output only)
 */
 
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
 
import { discoverAnalysisRuns } from './aggregator/generator/discovery.js';
import {
  aggregateAnalysisRun,
  resolveArticleTypeFromManifest,
} from './aggregator/analysis-aggregator.js';
import { resolveArticleMetadata } from './aggregator/article-metadata.js';
import { buildArticleSlug } from './aggregator/generator/slug.js';
import { getArticleFilename } from './aggregator/html/hreflang.js';
import { wrapArticleHtml } from './aggregator/html/shell.js';
import { ALL_LANGUAGES, isSupportedLanguage } from './constants/language-core.js';
 
const SUPPORTED_LANGS = new Set(ALL_LANGUAGES);
 
/**
 * Parse the small CLI surface used by this script. Kept inline so the
 * dumper has no extra dependencies beyond the same compiled-from-TS
 * helpers the real renderer uses.
 *
 * @param {readonly string[]} argv - `process.argv.slice(2)`
 * @returns {{repoRoot: string, lang: string, outPath: string|null,
 *           jsonPath: string|null, limit: number, quiet: boolean}}
 */
export function parseArgs(argv) {
  let repoRoot = process.cwd();
  let lang = 'en';
  let outPath = null;
  let jsonPath = null;
  let limit = Number.POSITIVE_INFINITY;
  let quiet = false;
 
  for (let i = 0; i < argv.length; i += 1) {
    const arg = argv[i];
    switch (arg) {
      case '--repo-root':
        repoRoot = path.resolve(requireValue(argv, i, arg));
        i += 1;
        break;
      case '--lang':
        lang = requireValue(argv, i, arg);
        i += 1;
        break;
      case '--out':
        outPath = path.resolve(requireValue(argv, i, arg));
        i += 1;
        break;
      case '--json':
        jsonPath = path.resolve(requireValue(argv, i, arg));
        i += 1;
        break;
      case '--limit': {
        const raw = requireValue(argv, i, arg);
        if (!/^\d+$/u.test(raw)) {
          throw new Error(`--limit expects a positive integer, got "${raw}"`);
        }
        const parsed = Number.parseInt(raw, 10);
        if (!Number.isFinite(parsed) || parsed < 1) {
          throw new Error(`--limit expects a positive integer, got "${raw}"`);
        }
        limit = parsed;
        i += 1;
        break;
      }
      case '--quiet':
        quiet = true;
        break;
      case '--help':
      case '-h':
        printHelpAndExit();
        break;
      default:
        throw new Error(`Unknown argument: ${arg}`);
    }
  }
 
  if (!isSupportedLanguage(lang)) {
    throw new Error(
      `Unsupported --lang "${lang}". Expected one of: ${[...SUPPORTED_LANGS].join(', ')}`
    );
  }
 
  return { repoRoot, lang, outPath, jsonPath, limit, quiet };
}
 
function requireValue(argv, i, flag) {
  const value = argv[i + 1];
  Iif (value === undefined) {
    throw new Error(`${flag} requires a value`);
  }
  return value;
}
 
function printHelpAndExit() {
  process.stdout.write(
    [
      'Usage: node scripts/dump-article-seo.js [options]',
      '',
      'Read-only preview of the SEO <head> metadata (title, description,',
      'keywords, og:*, twitter:*) that the article generator would produce',
      'from each executive brief — without generating any HTML files.',
      '',
      'Options:',
      '  --repo-root <path>   Repository root (default: cwd)',
      '  --lang <code>        Language to dump (default: en)',
      '  --out <path>         Write the human-readable report here',
      '  --json <path>        Also write a JSONL record per run',
      '  --limit <N>          Process only the first N runs (debug)',
      '  --quiet              Suppress per-run stdout',
      '  -h, --help           Show this help',
      '',
    ].join('\n')
  );
  process.exit(0);
}
 
/**
 * Mirror of the private `readManifestMetadata` helper inside
 * `scripts/aggregator/generator/render-one.js`. We re-implement it here
 * rather than export it from the renderer because the metadata-relevant
 * subset of a manifest is intentionally a *contract*, not a public API:
 * the resolver only consumes the seven keys listed below and silently
 * ignores everything else. Re-implementing keeps the dumper aligned
 * with that contract without leaking unrelated manifest fields into
 * `resolveArticleMetadata`.
 *
 * @param {string} runDir - Absolute path to the analysis run
 * @returns {object} Metadata-relevant manifest fields (possibly empty)
 */
export function readManifestMetadata(runDir) {
  const manifestPath = path.join(runDir, 'manifest.json');
  if (!fs.existsSync(manifestPath)) return {};
 
  let parsed;
  try {
    parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
  } catch {
    return {};
  }
 
  const manifest = {};
  const resolvedType = resolveArticleTypeFromManifest(parsed);
  Eif (resolvedType && resolvedType !== 'unknown') {
    manifest.articleType = resolvedType;
  }
  Eif (typeof parsed.date === 'string') manifest.date = parsed.date;
  Eif (typeof parsed.runId === 'string') manifest.runId = parsed.runId;
  Iif (typeof parsed.title === 'string' || isLanguageMapLike(parsed.title)) {
    manifest.title = parsed.title;
  }
  Iif (
    typeof parsed.description === 'string' ||
    isLanguageMapLike(parsed.description)
  ) {
    manifest.description = parsed.description;
  }
  Iif (typeof parsed.committee === 'string') {
    manifest.committee = parsed.committee;
  }
  return manifest;
}
 
function isLanguageMapLike(value) {
  Eif (!value || typeof value !== 'object' || Array.isArray(value)) return false;
  for (const entry of Object.values(value)) {
    if (typeof entry !== 'string') return false;
  }
  return true;
}
 
/**
 * Resolve the SEO metadata for one analysis run by reading its executive
 * brief and applying the same resolver chain as the article generator.
 * Pure: no files written, no stdout side-effects.
 *
 * @param {object} opts
 * @param {string} opts.runDir  - Absolute path to the analysis run
 * @param {string} opts.repoRoot - Repository root (for relative paths)
 * @param {string} opts.lang    - Language code to extract
 * @returns {{
 *   runDir: string,
 *   runDirRel: string,
 *   date: string,
 *   articleType: string,
 *   slug: string,
 *   filename: string,
 *   entry: {title: string, description: string,
 *           extendedDescription: string, keywords: readonly string[],
 *           source: string}
 * }}
 */
export function resolveRunSeo({ runDir, repoRoot, lang }) {
  const aggregated = aggregateAnalysisRun({ runDir, repoRoot });
  const manifestMetadata = readManifestMetadata(runDir);
  const resolved = resolveArticleMetadata({
    articleType: aggregated.articleType,
    date: aggregated.date,
    markdown: aggregated.markdown,
    manifest: manifestMetadata,
    runDir,
  });
 
  const entry = resolved[lang];
  Iif (!entry) {
    throw new Error(
      `resolveArticleMetadata returned no entry for lang="${lang}" in ${runDir}`
    );
  }
 
  const slug = buildArticleSlug(aggregated.date, aggregated.articleType);
  const filename = getArticleFilename(slug, lang);
  const runDirRel = path.relative(repoRoot, runDir).split(path.sep).join('/');
 
  return {
    runDir,
    runDirRel,
    date: aggregated.date,
    articleType: aggregated.articleType,
    slug,
    filename,
    entry: {
      title: entry.title,
      description: entry.description,
      extendedDescription: entry.extendedDescription,
      keywords: entry.keywords ?? [],
      source: entry.source,
    },
  };
}
 
/**
 * Build the full `<head>` block that the article generator will emit for
 * this run. The output is **bit-for-bit identical** to the `<head>`
 * produced by `wrapArticleHtml()` in `src/aggregator/html/shell.ts` for
 * the same metadata — including all SEO, Open Graph, Twitter card,
 * `<link rel>`, theme-color, and JSON-LD tags — because this function
 * literally invokes `wrapArticleHtml()` with an empty body and slices
 * out the `<head>...</head>` block from the resulting document. There
 * is no duplicated head-rendering code path.
 *
 * Use this to preview how the article will appear in search results and
 * social-card previews **before** running the full HTML generator.
 *
 * @param {ReturnType<typeof resolveRunSeo>} record
 * @param {string} lang - Language code passed through to `wrapArticleHtml`
 * @returns {string} The complete `<head>...</head>` block from the
 *                   real article renderer, ready to paste for review.
 */
export function buildHtmlHeadSnippet(record, lang) {
  const { entry } = record;
  const html = wrapArticleHtml({
    lang,
    articleSlug: record.slug,
    body: '',
    title: entry.title,
    description: entry.description,
    extendedDescription: entry.extendedDescription,
    keywords: entry.keywords ?? [],
    date: record.date,
    articleType: record.articleType,
  });
  const match = html.match(/<head>[\s\S]*?<\/head>/);
  Iif (!match) {
    throw new Error(
      `buildHtmlHeadSnippet: could not locate <head> block in wrapArticleHtml output for ${record.slug}`
    );
  }
  return match[0];
}
 
/**
 * Format one resolved-SEO record as the human/AI-readable block used in
 * the stdout dump. Each block contains two sections:
 *   1. *Field analysis* — per-field character/term counts and the
 *      resolution tier so editors can spot template fallbacks instantly.
 *   2. *HTML head snippet* — the exact tags the article generator will
 *      emit, ready to paste into a browser/SEO tool for preview.
 *
 * @param {ReturnType<typeof resolveRunSeo>} record
 * @param {number} index - 1-based position within the dump
 * @param {number} total - Total number of records being dumped
 * @param {string} [lang] - Language code (used for the HTML snippet; defaults to 'en')
 * @returns {string}
 */
export function formatRecord(record, index, total, lang = 'en') {
  const lines = [];
  lines.push('='.repeat(80));
  lines.push(`[${index}/${total}] ${record.slug}`);
  lines.push('='.repeat(80));
  lines.push(`run-dir         : ${record.runDirRel}`);
  lines.push(`date            : ${record.date}`);
  lines.push(`article-type    : ${record.articleType}`);
  lines.push(`resolution-tier : ${record.entry.source}`);
  lines.push(`html-file       : news/${record.filename}`);
  lines.push('');
  lines.push('--- Field analysis (from executive-brief.md → resolveArticleMetadata) ---');
  lines.push(
    `<title>            (${record.entry.title.length} chars): ${formatInline(record.entry.title)}`
  );
  lines.push(
    `<meta description> (${record.entry.description.length} chars): ${formatInline(record.entry.description)}`
  );
  lines.push(
    `<meta description-extended> (${record.entry.extendedDescription.length} chars): ${formatInline(record.entry.extendedDescription)}`
  );
  const keywords = record.entry.keywords;
  lines.push(
    `<meta keywords>    (${keywords.length} terms): ${keywords.length ? keywords.join(', ') : '(empty)'}`
  );
  lines.push('');
  lines.push('--- HTML <head> block (verbatim output of wrapArticleHtml — same code path as the article generator) ---');
  lines.push(buildHtmlHeadSnippet(record, lang));
  lines.push('');
  return lines.join('\n');
}
 
function formatInline(value) {
  Iif (!value) return '(empty)';
  // Strip newlines so each field stays on one line.
  return value.replace(/\s+/g, ' ').trim();
}
 
/**
 * Run the full dump: discover analysis runs, resolve SEO metadata from
 * each executive brief, print field analysis + HTML head snippet, and
 * optionally write to disk. Returns summary statistics so unit tests and
 * downstream tooling can assert on histograms without re-parsing stdout.
 *
 * @param {ReturnType<typeof parseArgs>} opts
 * @returns {{
 *   discovered: number,
 *   total: number,
 *   processed: number,
 *   resolutionTiers: Record<string, number>,
 *   emptyKeywordCount: number,
 *   shortDescriptionCount: number,
 *   records: ReadonlyArray<ReturnType<typeof resolveRunSeo>>
 * }}
 */
export function dumpArticleSeo(opts) {
  const { repoRoot, lang, outPath, jsonPath, limit, quiet } = opts;
 
  const allRuns = discoverAnalysisRuns(repoRoot).map((run) => run.runDir);
  const discovered = allRuns.length;
  const targetRuns = Number.isFinite(limit) ? allRuns.slice(0, limit) : allRuns;
  const total = targetRuns.length;
 
  const records = [];
  const failures = [];
  const resolutionTiers = Object.create(null);
  let emptyKeywordCount = 0;
  let shortDescriptionCount = 0;
  // Phase-6 quality-flag counters — added 2026-05 to drive the
  // "make SEO uniformly excellent" iteration. None of these abort the
  // dump (the run still returns success); they surface in the Quality
  // flags section so the next agent run can target the residual offenders.
  let titleTooShortCount = 0; // < 30 chars (SERP under-utilisation)
  let titleTooLongCount = 0; // > 65 chars (SERP truncation)
  let descTooShortCount = 0; // < 120 chars (snippet under-utilisation)
  let descTooLongCount = 0; // > 160 chars (SERP truncation)
  let emptyExtendedDescriptionCount = 0;
  let pollutedArticleTypeCount = 0; // sanity gate post-Phase-5
  const titleOccurrences = new Map();
 
  const textChunks = [];
  const jsonLines = [];
  const header =
    `# Executive Brief SEO Preview\n` +
    `# Source         : executive-brief.md under analysis/daily/*/\n` +
    `# repo-root      : ${repoRoot}\n` +
    `# language       : ${lang}\n` +
    `# total runs     : ${discovered}\n` +
    `# selected runs  : ${total}\n` +
    `# generated by   : scripts/dump-article-seo.js\n` +
    `# resolver       : src/aggregator/article-metadata.ts → resolveArticleMetadata()\n` +
    `# rendered by    : src/aggregator/html/shell.ts (same call path as npm run generate-article:all)\n` +
    `# purpose        : review and improve SEO before generating HTML\n\n`;
 
  Iif (!quiet) process.stdout.write(header);
  textChunks.push(header);
 
  for (let i = 0; i < targetRuns.length; i += 1) {
    const runDir = targetRuns[i];
    let record;
    try {
      record = resolveRunSeo({ runDir, repoRoot, lang });
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      failures.push({ runDir, message });
      const failBlock = `--- FAILED ${path.relative(repoRoot, runDir)}: ${message}\n\n`;
      if (!quiet) process.stderr.write(failBlock);
      textChunks.push(failBlock);
      continue;
    }
    records.push(record);
 
    const tier = record.entry.source;
    resolutionTiers[tier] = (resolutionTiers[tier] ?? 0) + 1;
    Iif (record.entry.keywords.length === 0) emptyKeywordCount += 1;
    Iif (record.entry.description.length < 70) shortDescriptionCount += 1;
    // Phase-6 quality flags — soft SERP-budget warnings.
    const titleLen = record.entry.title.length;
    Iif (titleLen > 0 && titleLen < 30) titleTooShortCount += 1;
    Iif (titleLen > 65) titleTooLongCount += 1;
    const descLen = record.entry.description.length;
    Eif (descLen > 0 && descLen < 120) descTooShortCount += 1;
    Iif (descLen > 160) descTooLongCount += 1;
    Iif (!record.entry.extendedDescription) emptyExtendedDescriptionCount += 1;
    Iif (typeof record.articleType === 'string' && /-run[a-zA-Z0-9-]*\d+$/u.test(record.articleType)) {
      pollutedArticleTypeCount += 1;
    }
    // Duplicate-title detection — zero tolerance across the corpus.
    // We group by exact byte-match of the resolved title; same-title
    // collisions on different (date, articleType) pairs are the
    // SERP-cannibalisation pattern that the dump is meant to surface.
    const titleKey = record.entry.title;
    Eif (titleKey) {
      const bucket = titleOccurrences.get(titleKey) ?? [];
      bucket.push(record.slug);
      titleOccurrences.set(titleKey, bucket);
    }
 
    const block = formatRecord(record, i + 1, total, lang);
    Iif (!quiet) process.stdout.write(`${block}\n`);
    textChunks.push(`${block}\n`);
 
    jsonLines.push(
      JSON.stringify({
        slug: record.slug,
        runDir: record.runDirRel,
        date: record.date,
        articleType: record.articleType,
        lang,
        filename: record.filename,
        source: record.entry.source,
        title: record.entry.title,
        description: record.entry.description,
        extendedDescription: record.entry.extendedDescription,
        keywords: record.entry.keywords,
        htmlHeadSnippet: buildHtmlHeadSnippet(record, lang),
      })
    );
  }
 
  const duplicateTitleGroups = Array.from(titleOccurrences.entries())
    .filter(([, slugs]) => slugs.length > 1)
    .map(([title, slugs]) => ({ title, count: slugs.length, slugs: [...slugs] }))
    .sort((a, b) => b.count - a.count || a.title.localeCompare(b.title));
 
  const summary = buildSummary({
    discovered,
    total,
    processed: records.length,
    failures,
    resolutionTiers,
    emptyKeywordCount,
    shortDescriptionCount,
    titleTooShortCount,
    titleTooLongCount,
    descTooShortCount,
    descTooLongCount,
    emptyExtendedDescriptionCount,
    pollutedArticleTypeCount,
    duplicateTitleGroups,
  });
  Iif (!quiet) process.stdout.write(summary);
  textChunks.push(summary);
 
  if (outPath) {
    fs.mkdirSync(path.dirname(outPath), { recursive: true });
    fs.writeFileSync(outPath, textChunks.join(''), 'utf8');
  }
  if (jsonPath) {
    fs.mkdirSync(path.dirname(jsonPath), { recursive: true });
    fs.writeFileSync(jsonPath, `${jsonLines.join('\n')}\n`, 'utf8');
  }
 
  return {
    discovered,
    total,
    processed: records.length,
    resolutionTiers,
    emptyKeywordCount,
    shortDescriptionCount,
    titleTooShortCount,
    titleTooLongCount,
    descTooShortCount,
    descTooLongCount,
    emptyExtendedDescriptionCount,
    pollutedArticleTypeCount,
    duplicateTitleGroups,
    records,
  };
}
 
function buildSummary({
  discovered,
  total,
  processed,
  failures,
  resolutionTiers,
  emptyKeywordCount,
  shortDescriptionCount,
  titleTooShortCount,
  titleTooLongCount,
  descTooShortCount,
  descTooLongCount,
  emptyExtendedDescriptionCount,
  pollutedArticleTypeCount,
  duplicateTitleGroups,
}) {
  const tierEntries = Object.entries(resolutionTiers).sort(
    ([a], [b]) => a.localeCompare(b)
  );
  const lines = [];
  lines.push('='.repeat(80));
  lines.push('SUMMARY');
  lines.push('='.repeat(80));
  lines.push(`total runs discovered : ${discovered}`);
  lines.push(`selected for preview  : ${total}`);
  lines.push(`successfully resolved : ${processed}`);
  lines.push(`failed runs           : ${failures.length}`);
  lines.push('');
  lines.push('Resolution-tier histogram (alphabetical by source label):');
  Iif (tierEntries.length === 0) {
    lines.push('  (no runs resolved)');
  } else {
    for (const [tier, count] of tierEntries) {
      lines.push(`  ${tier.padEnd(20)} ${count}`);
    }
  }
  lines.push('');
  lines.push('Quality flags:');
  lines.push(`  runs with empty <meta keywords>                       : ${emptyKeywordCount}`);
  lines.push(`  runs with <meta description> shorter than 70 chars    : ${shortDescriptionCount}`);
  lines.push(`  runs with <title> shorter than 30 chars               : ${titleTooShortCount}`);
  lines.push(`  runs with <title> longer than 65 chars (SERP-clipped) : ${titleTooLongCount}`);
  lines.push(`  runs with <meta description> shorter than 120 chars   : ${descTooShortCount}`);
  lines.push(`  runs with <meta description> longer than 160 chars    : ${descTooLongCount}`);
  lines.push(`  runs with empty og:description (extendedDescription)  : ${emptyExtendedDescriptionCount}`);
  lines.push(`  runs with -run<N>-polluted articleType                : ${pollutedArticleTypeCount}`);
  lines.push(`  duplicate title groups (SERP cannibalisation)         : ${duplicateTitleGroups.length}`);
  Iif (duplicateTitleGroups.length > 0) {
    for (const group of duplicateTitleGroups) {
      lines.push(`    [${group.count}×] ${group.title}`);
      for (const slug of group.slugs) {
        lines.push(`        - ${slug}`);
      }
    }
  }
  Iif (failures.length > 0) {
    lines.push('');
    lines.push('Failures:');
    for (const fail of failures) {
      lines.push(`  - ${fail.runDir}: ${fail.message}`);
    }
  }
  lines.push('');
  return `${lines.join('\n')}`;
}
 
// Run as a script only when invoked directly (not when imported by tests).
const invokedDirectly =
  import.meta.url === `file://${process.argv[1]}` ||
  process.argv[1]?.endsWith('dump-article-seo.js');
 
Iif (invokedDirectly) {
  try {
    const opts = parseArgs(process.argv.slice(2));
    dumpArticleSeo(opts);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    process.stderr.write(`dump-article-seo: ${message}\n`);
    process.exit(1);
  }
}