All files / src/aggregator editorial-brief-resolver.ts

94.02% Statements 63/67
92.15% Branches 47/51
100% Functions 6/6
96.42% Lines 54/56

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                                                                                                                                                            494x 493x                                                           10x 10x       10x 10x 10x 13x 13x 2x 2x   11x 1x 1x   10x   1x 1x 1x 1x   9x   10x                           1x 4x                                 9x 9x 9x 7x   2x 2x 1x   1x                                                         491x 490x   489x 971x 971x   10x 10x   9x 9x 9x   971x 9x                 480x                                 3x 2x 2x 5x 3x 5x 5x 2x 2x       2x    
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Aggregator/EditorialBriefResolver
 * @description Language-aware editorial brief lookup.
 *
 * Companion to `article-metadata.ts`. Where that module's
 * `extractArtifactHighlight` is intentionally language-agnostic (the first
 * canonical editorial artefact wins, regardless of locale), this module
 * answers the **per-language** question:
 *
 *   "Given a run directory and a target language `<lang>`, is there a
 *   sibling `executive-brief_<lang>.md` (or `extended/…` variant) that
 *   the article-metadata resolver should prefer over the English brief?"
 *
 * The answer drives the localized-brief precedence rule documented in
 * [`.github/prompts/04-article-generation.md`](../../.github/prompts/04-article-generation.md) § 6.2:
 *
 *   1. translated `executive-brief_<lang>.md` (this module's job)
 *   2. translated `extended/executive-brief_<lang>.md` (also this module)
 *   3. English `executive-brief.md` — `article-metadata.ts` already
 *      handles this via the canonical candidate list
 *
 * The module is intentionally small and side-effect-free; it composes
 * the existing low-level helpers (`extractFirstH1`,
 * `extractLedeAfterHeading`, `extractStrongProseLine`, `isGenericHeading`,
 * `stripArtifactCategoryAffix`, `truncateTitle`) so the parsing rules
 * stay identical across the English and localized paths.
 */
 
import fs from 'fs';
import path from 'path';
 
import type { LanguageCode } from '../types/index.js';
import {
  extractFirstH1,
  extractLedeAfterHeading,
  extractStrongProseLine,
  isGenericHeading,
  stripArtifactCategoryAffix,
  truncateTitle,
} from './article-metadata.js';
 
/**
 * One resolved per-language brief highlight.
 *
 * `headline` and `summary` follow the same semantics as
 * `extractArtifactHighlight` in `article-metadata.ts` — either may be
 * empty when the localized brief lacks the relevant section.
 *
 * `sourceFile` is the run-relative path to the file that produced the
 * highlight; downstream callers can record this when populating
 * `manifest.metadataFallback` so editors can later audit which locales
 * fell through to English.
 *
 * `sourceLang` matches the language code of the brief that produced the
 * highlight (always equal to the requested language for a successful
 * lookup; the caller infers `"en"` fallback when this module returns
 * `null`).
 */
export interface LocalizedBriefHighlight {
  readonly headline: string;
  readonly summary: string;
  readonly sourceFile: string;
  readonly sourceLang: LanguageCode;
}
 
/**
 * Run-relative candidate paths for a translated brief, in precedence
 * order. Mirrors the `executive-brief.md` → `extended/executive-brief.md`
 * progression used by the English path so the localized resolution stays
 * symmetric.
 *
 * @param lang - Target language code
 * @returns Ordered run-relative paths to probe
 */
export function localizedBriefCandidates(lang: LanguageCode): readonly string[] {
  if (lang === 'en') return [];
  return [`executive-brief_${lang}.md`, `extended/executive-brief_${lang}.md`];
}
 
/**
 * Read an editorial artefact body while skipping any SPDX HTML-comment
 * preamble. Kept private here so the localized path doesn't depend on
 * non-exported helpers from `article-metadata.ts`.
 *
 * Both single-line (`<!-- … -->`) and multi-line comment blocks (where
 * `<!--` and `-->` appear on different lines) are stripped, so SPDX
 * headers written as
 *
 *   ```
 *   <!--
 *     SPDX-FileCopyrightText: 2024-2026 Hack23 AB
 *     SPDX-License-Identifier: Apache-2.0
 *   -->
 *   ```
 *
 * are handled symmetrically with the single-line form. An unterminated
 * `<!--` block (no closing `-->`) is treated as malformed and the body
 * is returned starting at that line — downstream `extractFirstH1` will
 * then fail to find a heading and the caller will return `null`, which
 * is the safe behaviour for a broken brief.
 *
 * @param abs - Absolute file path
 * @returns File contents with SPDX comment lines dropped, or `''` on error
 */
function readArtefactBody(abs: string): string {
  let text: string;
  try {
    text = fs.readFileSync(abs, 'utf8');
  } catch {
    return '';
  }
  const lines = text.split('\n');
  let i = 0;
  while (i < lines.length) {
    const line = (lines[i] ?? '').trim();
    if (line === '') {
      i++;
      continue;
    }
    if (line.startsWith('<!--') && line.endsWith('-->') && line.length >= 7) {
      i++;
      continue;
    }
    if (line.startsWith('<!--')) {
      // Multi-line comment block — scan forward to the closing `-->`.
      const closeIdx = findCommentClose(lines, i);
      Iif (closeIdx === -1) break; // malformed: bail out, retain content
      i = closeIdx + 1;
      continue;
    }
    break;
  }
  return lines.slice(i).join('\n');
}
 
/**
 * Locate the line index of the first line that ends with `-->` at or
 * after `start`. The terminator must appear at end-of-line (after a
 * trim) so an inline `-->` embedded in editorial prose cannot be
 * mis-read as the close of an SPDX preamble block.
 *
 * @param lines - File lines being scanned (read-only)
 * @param start - Line index where the unterminated `<!--` was seen
 * @returns Closing line index, or `-1` when no terminator is found.
 */
function findCommentClose(lines: readonly string[], start: number): number {
  for (let j = start; j < lines.length; j++) {
    if ((lines[j] ?? '').trimEnd().endsWith('-->')) return j;
  }
  return -1;
}
 
/**
 * Compute the editorial headline from a localized brief body. Returns
 * `''` when the H1 is fully generic and the stripped variant is also
 * generic. Kept private so callers don't need to know about generic-H1
 * stripping rules.
 *
 * @param body - Brief body with the SPDX preamble already stripped
 * @param articleType - Article-type slug (for {@link isGenericHeading})
 * @param date - ISO run date (for {@link isGenericHeading})
 * @returns Editorial headline, possibly empty
 */
function deriveHeadline(body: string, articleType: string, date: string): string {
  const rawHeadline = extractFirstH1(body);
  Iif (!rawHeadline) return '';
  if (!isGenericHeading(rawHeadline, articleType, date)) {
    return truncateTitle(rawHeadline);
  }
  const stripped = stripArtifactCategoryAffix(rawHeadline);
  if (stripped && !isGenericHeading(stripped, articleType, date)) {
    return truncateTitle(stripped);
  }
  return '';
}
 
/**
 * Attempt to resolve the localized brief highlight for one language.
 * Returns `null` when no `executive-brief_<lang>.md` (or extended
 * variant) exists in `runDir`. For `lang === 'en'` always returns `null`
 * — the English brief is handled by the canonical
 * `extractArtifactHighlight` resolver.
 *
 * The body of the localized brief is parsed with the same lede/H1
 * extractors used for the English path, so the semantic rules are
 * symmetric. Generic artefact-category headings
 * (e.g. `# Executive Brief — Breaking News (2026-05-15)`) are detected
 * and stripped via {@link stripArtifactCategoryAffix} so they cannot
 * leak into the SEO surfaces.
 *
 * @param runDir - Absolute run directory (the parent of the brief)
 * @param lang - Target language code
 * @param articleType - Article-type slug (for {@link isGenericHeading})
 * @param date - ISO run date (for {@link isGenericHeading})
 * @returns Resolved localized highlight, or `null` when no brief exists
 */
export function resolveLocalizedBriefHighlight(
  runDir: string,
  lang: LanguageCode,
  articleType: string,
  date: string
): LocalizedBriefHighlight | null {
  if (lang === 'en') return null;
  if (!runDir || !fs.existsSync(runDir)) return null;
 
  for (const rel of localizedBriefCandidates(lang)) {
    const abs = path.join(runDir, rel);
    if (!fs.existsSync(abs)) continue;
 
    const body = readArtefactBody(abs);
    if (!body) continue;
 
    const headline = deriveHeadline(body, articleType, date);
    const lede = extractLedeAfterHeading(body);
    const summary = lede || extractStrongProseLine(body);
 
    if (headline || summary) {
      return {
        headline,
        summary,
        sourceFile: rel,
        sourceLang: lang,
      };
    }
  }
 
  return null;
}
 
/**
 * Return the set of language codes for which a translated brief is
 * present in `runDir`. Useful for telemetry and for the `metadataFallback`
 * accounting that records which locales fall back to English.
 *
 * @param runDir - Absolute run directory
 * @param languages - Ordered list of language codes to probe
 * @returns Subset of {@link languages} for which at least one localized
 * brief candidate file exists
 */
export function discoverLocalizedBriefs(
  runDir: string,
  languages: readonly LanguageCode[]
): readonly LanguageCode[] {
  if (!runDir || !fs.existsSync(runDir)) return [];
  const out: LanguageCode[] = [];
  for (const lang of languages) {
    if (lang === 'en') continue;
    for (const rel of localizedBriefCandidates(lang)) {
      const abs = path.join(runDir, rel);
      if (fs.existsSync(abs)) {
        out.push(lang);
        break;
      }
    }
  }
  return out;
}