All files / src/aggregator/metadata briefing-highlight.ts

88.42% Statements 168/190
81.96% Branches 150/183
100% Functions 17/17
95.13% Lines 137/144

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                                                                                                                              22x             22x                                   6911x 6695x 6161x 6146x 3895x 2791x 2299x 2271x 1307x                             534x         534x 1566x 1549x 1547x 1547x   1547x 1547x 1547x   515x                                               161x                   7x 7x       23x 12x 12x     23x                                   399x 399x 386x 382x                                 133x 133x 6x 6x 6x 6x 6x   127x       127x                                   55x 55x 1727x 1727x 1727x 54x 54x   1673x 1556x 133x 133x   1423x 26x   55x 5x                                 26x 5x 5x 5x 5x 5x   21x 11x 6x   5x 5x 5x 5x                                 106x 106x 3442x 3442x 3442x 108x 108x   3334x 3100x 266x 266x   2834x 28x   106x                                   266x 266x 266x 266x                           28x 15x   13x 13x 2x 2x                                                 56x 56x 1742x 1742x 1742x 54x 54x   1688x 1571x 135x 135x 135x 135x   1436x 18x   56x                         18x 13x 5x 5x 13x 5x   5x                                   55x 55x 5x           50x 50x 1x                                   56x 56x 56x 6x 56x 56x         56x     56x 6x                               52x 52x 52x 6x 1x           5x    
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Aggregator/Metadata/BriefingHighlight
 * @description Highlight extractor specialised on the executive-brief
 * style guide introduced for the May-2026 EP10 briefing series. Where
 * {@link editorial-highlight.ts} treats every Stage-B artefact uniformly
 * (first non-generic H1 → headline; first prose paragraph → summary),
 * this module knows that an `executive-brief.md` carries two strong
 * editorial sections that should outrank a generic `## Key Findings`
 * walk:
 *
 *   1. `## Strategic Intelligence Summary` — the synthesis paragraph.
 *      The first `### Sub-section` heading underneath it (e.g.
 *      "The Three-Coalition Paradox") makes a clean, journalistic
 *      `<title>`. The first prose paragraph that follows that
 *      sub-heading makes a clean `<meta description>`.
 *
 *   2. `## Reader Briefing` (a.k.a. `Reader Briefing (Plain Language)`)
 *      — the actionable priority list. When the section is structured
 *      as a numbered list (`1. **Immediate priority**: …`), the bold
 *      label + tail of the first item makes a strong `<title>`. When
 *      it is structured as a single prose paragraph (the
 *      term-outlook style), the paragraph is used verbatim as
 *      description and the first sentence becomes the headline.
 *
 * Both extractors are tolerant of missing sections — they return
 * `null` so the resolver can fall back to the existing
 * `extractArtifactHighlight` ladder for the 200+ historical briefs
 * that pre-date this style guide.
 *
 * Pure leaf module under `metadata/` — depends only on
 * {@link stripInlineMarkdown}, {@link truncateTitle},
 * {@link truncateDescription}, and {@link truncateExtendedDescription}
 * from `text-utils`. No I/O, no upward imports.
 */
 
import {
  EXTENDED_DESCRIPTION_MAX_LENGTH,
  shouldSkipDescriptionLine,
  stripInlineMarkdown,
  stripLeadingBoldLabel,
  stripLeadingProseLabel,
  truncateDescription,
  truncateExtendedDescription,
  truncateTitle,
} from './text-utils.js';
 
/**
 * One resolved brief highlight. Both `headline` and `summary` may be
 * empty when the underlying section is absent or too short to publish.
 * `extendedSummary` is only emitted when the BLUF/synthesis paragraph
 * exceeds the regular description budget — see
 * {@link truncateExtendedDescription} for the cutoff.
 */
export interface BriefingHighlight {
  readonly headline: string;
  readonly summary: string;
  readonly extendedSummary: string;
}
 
/** Heading text that opens the Strategic Intelligence Summary block. */
const STRATEGIC_SECTION_HEADINGS: readonly string[] = [
  'strategic intelligence summary',
  'strategic assessment',
  'intelligence assessment',
];
 
/** Heading text that opens the Reader Briefing block. */
const READER_BRIEFING_HEADINGS: readonly string[] = [
  'reader briefing',
  'reader briefing (plain language)',
  'reader briefing — plain language',
];
 
/** Sentinel returned by {@link classifyLine} when the line is benign prose. */
type LineKind = 'fence' | 'h2' | 'h3' | 'blank' | 'structural' | 'numbered' | 'bullet' | 'prose';
 
/**
 * Classify a trimmed Markdown line into one of the structural buckets
 * the section walker cares about. Extracted from the inline walker
 * loops to keep their cognitive complexity below the 15-point limit.
 *
 * @param line - Trimmed Markdown line
 * @returns Line kind sentinel
 */
function classifyLine(line: string): LineKind {
  if (line.startsWith('```') || line.startsWith('~~~')) return 'fence';
  if (line.startsWith('## ')) return 'h2';
  if (line.startsWith('### ')) return 'h3';
  if (line === '') return 'blank';
  if (line.startsWith('|') || line.startsWith('>') || line.startsWith('<')) return 'structural';
  if (line.startsWith('---') || line.startsWith('===')) return 'structural';
  if (/^\d+\.\s+/u.test(line)) return 'numbered';
  if (line.startsWith('-') || line.startsWith('*')) return 'bullet';
  return 'prose';
}
 
/**
 * Compare a raw `## …` heading line against a whitelist of expected
 * section names. The comparison strips inline Markdown decorations and
 * leading non-alphanumeric characters (emoji, punctuation) so a brief
 * that writes the heading as `## 🧭 Strategic Intelligence Summary`
 * still matches.
 *
 * @param raw - Heading text without the leading `#`s
 * @param needles - Lower-case whitelist entries
 * @returns `true` when the heading text matches any whitelist entry
 */
function headingMatches(raw: string, needles: readonly string[]): boolean {
  const normalized = stripInlineMarkdown(raw)
    .replace(/[*_`#]+/g, '')
    .replace(/^[^A-Za-z0-9]+/, '')
    .trim()
    .toLowerCase();
  for (const needle of needles) {
    if (normalized === needle) return true;
    if (normalized.startsWith(`${needle} `)) return true;
    Iif (normalized.startsWith(`${needle}:`)) return true;
    Iif (normalized.startsWith(`${needle}(`)) return true;
    // Em-dash, en-dash, hyphen separators.
    Iif (normalized.startsWith(`${needle} —`)) return true;
    Iif (normalized.startsWith(`${needle} –`)) return true;
    Iif (normalized.startsWith(`${needle} -`)) return true;
  }
  return false;
}
 
/**
 * Mutable iterator state used by the section walkers. The fence-state
 * flag tracks ``` / ~~~ pairs so we never enter a section that lives
 * inside a code block; `inSection` flips on/off as we cross `## …`
 * boundaries; `subHeading` captures the first `### …` we see inside
 * the matched section (only used by the synthesis extractor).
 */
interface WalkerState {
  inFence: boolean;
  inSection: boolean;
  subHeading: string;
  lines: string[];
  byteCount: number;
}
 
/**
 * Build an empty walker state.
 *
 * @returns Fresh, fence-aware {@link WalkerState} with empty buffers.
 */
function newState(): WalkerState {
  return { inFence: false, inSection: false, subHeading: '', lines: [], byteCount: 0 };
}
 
/**
 * Push a prose line into the walker's collected buffer.
 *
 * @param state - Walker state (mutated)
 * @param line - Cleaned line to append
 */
function appendLine(state: WalkerState, line: string): void {
  state.lines.push(line);
  state.byteCount += line.length + 1;
}
 
function normalizeBriefingLine(line: string, preserveLeadingLabel = false): string {
  if (shouldSkipDescriptionLine(line)) return '';
  const withoutMarkdown = stripInlineMarkdown(line);
  const normalized = preserveLeadingLabel
    ? withoutMarkdown
    : stripLeadingProseLabel(stripLeadingBoldLabel(withoutMarkdown));
  return normalized.replace(/^[:;—–-]\s+/u, '').trim();
}
 
/**
 * Decide what to do when the walker sees a `## …` heading.
 *
 * @param state - Walker state
 * @param raw - Raw heading line (already trimmed)
 * @param needles - Lower-case section whitelist
 * @returns `'enter'` when the heading opens the target section,
 *          `'leave'` when it closes an already-open target section,
 *          `'skip'` otherwise.
 */
function transitionForH2(
  state: WalkerState,
  raw: string,
  needles: readonly string[]
): 'enter' | 'leave' | 'skip' {
  const headingText = raw.replace(/^##\s+/, '');
  if (headingMatches(headingText, needles)) return 'enter';
  if (state.inSection) return 'leave';
  return 'skip';
}
 
/**
 * Handle a `## …` line for the sub-section walker. Returns `true`
 * when the caller should stop walking.
 *
 * @param state - Walker state (mutated)
 * @param line - Trimmed `## …` line
 * @param needles - Section whitelist
 * @returns `true` to stop walking
 */
function handleH2ForSubsection(
  state: WalkerState,
  line: string,
  needles: readonly string[]
): boolean {
  const t = transitionForH2(state, line, needles);
  if (t === 'enter') {
    state.inSection = true;
    state.subHeading = '';
    state.lines.length = 0;
    state.byteCount = 0;
    return false;
  }
  Iif (t === 'leave') {
    if (state.subHeading && state.lines.length > 0) return true;
    state.inSection = false;
  }
  return false;
}
 
/**
 * Walk the brief body line-by-line and return the first `### …`
 * heading + its first prose paragraph that occur **inside** the
 * matched `## …` block. Returns `null` when the matched block does
 * not contain a `### …` sub-heading.
 *
 * @param markdown - Brief body (SPDX preamble already stripped)
 * @param sectionNeedles - Lower-case `## …` whitelist
 * @returns First `{subHeading, paragraph}` pair under the matched
 *          section, or `null` when no sub-heading exists
 */
function extractFirstSubsectionUnderSection(
  markdown: string,
  sectionNeedles: readonly string[]
): { readonly subHeading: string; readonly paragraph: string } | null {
  const state = newState();
  for (const raw of markdown.split('\n')) {
    const line = raw.trim();
    const kind = classifyLine(line);
    if (kind === 'fence') {
      state.inFence = !state.inFence;
      continue;
    }
    if (state.inFence) continue;
    if (kind === 'h2') {
      Iif (handleH2ForSubsection(state, line, sectionNeedles)) break;
      continue;
    }
    if (!state.inSection) continue;
    if (collectSubsectionLine(state, line, kind)) break;
  }
  if (!state.subHeading || state.lines.length === 0) return null;
  return {
    subHeading: state.subHeading.trim(),
    paragraph: state.lines.join(' ').trim(),
  };
}
 
/**
 * Process one non-heading line inside the matched section for the
 * sub-section extractor. Returns `true` to signal the caller should
 * stop walking (paragraph boundary reached or budget exceeded).
 *
 * @param state - Walker state (mutated)
 * @param line - Trimmed line being processed
 * @param kind - Pre-classified line kind from {@link classifyLine}
 * @returns `true` to stop walking
 */
function collectSubsectionLine(state: WalkerState, line: string, kind: LineKind): boolean {
  if (kind === 'h3') {
    Iif (state.subHeading && state.lines.length > 0) return true;
    state.subHeading = stripInlineMarkdown(line.replace(/^###\s+/, ''));
    state.lines.length = 0;
    state.byteCount = 0;
    return false;
  }
  if (!state.subHeading) return false;
  if (kind === 'blank' || kind === 'structural') {
    return state.lines.length > 0;
  }
  const clean = normalizeBriefingLine(line);
  Iif (!clean) return state.lines.length > 0;
  appendLine(state, clean);
  return state.byteCount >= EXTENDED_DESCRIPTION_MAX_LENGTH;
}
 
/**
 * Walk the brief body and return the first prose paragraph that occurs
 * **inside** the matched `## …` block (ignoring any `### …`
 * sub-headings). Used as the fallback extractor when the section is a
 * single-paragraph block (the term-outlook Reader Briefing style).
 *
 * @param markdown - Brief body (SPDX preamble already stripped)
 * @param sectionNeedles - Lower-case `## …` whitelist
 * @returns First prose paragraph, or empty string when absent
 */
function extractFirstParagraphUnderSection(
  markdown: string,
  sectionNeedles: readonly string[]
): string {
  const state = newState();
  for (const raw of markdown.split('\n')) {
    const line = raw.trim();
    const kind = classifyLine(line);
    if (kind === 'fence') {
      state.inFence = !state.inFence;
      continue;
    }
    if (state.inFence) continue;
    if (kind === 'h2') {
      Iif (handleH2ForParagraph(state, line, sectionNeedles)) break;
      continue;
    }
    if (!state.inSection || kind === 'h3') continue;
    if (collectParagraphLine(state, line, kind)) break;
  }
  return state.lines.length === 0 ? '' : state.lines.join(' ').trim();
}
 
/**
 * Handle a `## …` line for the first-paragraph walker. Returns `true`
 * when the caller should stop walking (a complete paragraph was
 * already captured in a prior matched section).
 *
 * @param state - Walker state (mutated)
 * @param line - Trimmed `## …` line
 * @param needles - Section whitelist
 * @returns `true` to stop walking
 */
function handleH2ForParagraph(
  state: WalkerState,
  line: string,
  needles: readonly string[]
): boolean {
  Iif (state.inSection && state.lines.length > 0) return true;
  const t = transitionForH2(state, line, needles);
  state.inSection = t === 'enter';
  return false;
}
 
/**
 * Process one non-heading line inside the matched section for the
 * first-paragraph extractor. Returns `true` when the caller should
 * stop walking.
 *
 * @param state - Walker state (mutated)
 * @param line - Trimmed line being processed
 * @param kind - Pre-classified line kind from {@link classifyLine}
 * @returns `true` to stop walking
 */
function collectParagraphLine(state: WalkerState, line: string, kind: LineKind): boolean {
  if (kind === 'blank' || kind === 'structural') {
    return state.lines.length > 0;
  }
  const clean = normalizeBriefingLine(line);
  if (!clean) return state.lines.length > 0;
  appendLine(state, clean);
  return state.byteCount >= EXTENDED_DESCRIPTION_MAX_LENGTH;
}
 
/** Mutable accumulator for {@link extractFirstNumberedItemUnderSection}. */
interface NumberedItemState {
  inFence: boolean;
  inSection: boolean;
  item: string[];
}
 
/**
 * Walk the brief body and return the first numbered-list item that
 * appears **inside** the matched `## …` block. Recognises the
 * `1. **Immediate priority**: …` shape used by the May-2026
 * Reader Briefing style guide. The bold label and tail are joined into
 * a single headline-shaped string.
 *
 * @param markdown - Brief body
 * @param sectionNeedles - `## …` whitelist
 * @returns Flattened first list item, or empty string when absent
 */
function extractFirstNumberedItemUnderSection(
  markdown: string,
  sectionNeedles: readonly string[]
): string {
  const state: NumberedItemState = { inFence: false, inSection: false, item: [] };
  for (const raw of markdown.split('\n')) {
    const line = raw.trim();
    const kind = classifyLine(line);
    if (kind === 'fence') {
      state.inFence = !state.inFence;
      continue;
    }
    if (state.inFence) continue;
    if (kind === 'h2') {
      Iif (state.inSection && state.item.length > 0) break;
      const headingText = line.replace(/^##\s+/, '');
      state.inSection = headingMatches(headingText, sectionNeedles);
      continue;
    }
    if (!state.inSection) continue;
    if (handleNumberedLine(state, line, kind)) break;
  }
  return state.item.join(' ').trim();
}
 
/**
 * Process one line inside the matched section for the numbered-item
 * extractor. Returns `true` when the caller should stop walking.
 *
 * @param state - Numbered-item walker state (mutated)
 * @param line - Trimmed line being processed
 * @param kind - Pre-classified line kind from {@link classifyLine}
 * @returns `true` to stop walking
 */
function handleNumberedLine(state: NumberedItemState, line: string, kind: LineKind): boolean {
  if (state.item.length === 0) {
    if (kind !== 'numbered') return false;
    const m = /^1\.\s+(.*)$/u.exec(line);
    const clean = m?.[1] ? normalizeBriefingLine(m[1], true) : '';
    if (clean) state.item.push(clean);
    return false;
  }
  Eif (kind === 'blank' || kind === 'numbered' || kind === 'bullet') return true;
  if (kind === 'h2' || kind === 'h3') return true;
  const clean = normalizeBriefingLine(line);
  if (!clean) return state.item.length > 0;
  state.item.push(clean);
  return false;
}
 
/**
 * Extract the {@link BriefingHighlight} for a `## Strategic
 * Intelligence Summary` (or compatible) section. Prefers the first
 * `### Sub-section` heading as headline; falls back to the section's
 * first prose paragraph when no sub-heading exists.
 *
 * @param markdown - Brief body
 * @returns Resolved highlight, or `null` when the section is absent
 */
export function extractStrategicSynthesisHighlight(markdown: string): BriefingHighlight | null {
  const sub = extractFirstSubsectionUnderSection(markdown, STRATEGIC_SECTION_HEADINGS);
  if (sub) {
    return {
      headline: truncateTitle(sub.subHeading),
      summary: truncateDescription(sub.paragraph),
      extendedSummary: truncateExtendedDescription(sub.paragraph),
    };
  }
  const paragraph = extractFirstParagraphUnderSection(markdown, STRATEGIC_SECTION_HEADINGS);
  if (!paragraph) return null;
  return {
    headline: '',
    summary: truncateDescription(paragraph),
    extendedSummary: truncateExtendedDescription(paragraph),
  };
}
 
/**
 * Extract the {@link BriefingHighlight} for a `## Reader Briefing` (or
 * compatible) section. Prefers the first numbered-list item as
 * headline when the section is structured as a priority list; falls
 * back to the first prose paragraph when it is written as plain prose
 * (the term-outlook style).
 *
 * @param markdown - Brief body
 * @returns Resolved highlight, or `null` when the section is absent
 */
export function extractReaderBriefingHighlight(markdown: string): BriefingHighlight | null {
  const firstItem = extractFirstNumberedItemUnderSection(markdown, READER_BRIEFING_HEADINGS);
  const paragraph = extractFirstParagraphUnderSection(markdown, READER_BRIEFING_HEADINGS);
  if (!firstItem && !paragraph) return null;
  const headlineSource = firstItem || paragraph;
  const headline = headlineSource ? truncateTitle(headlineSource) : '';
  const summary = paragraph
    ? truncateDescription(paragraph)
    : firstItem
      ? truncateDescription(firstItem)
      : '';
  const extendedSummary = paragraph
    ? truncateExtendedDescription(paragraph)
    : truncateExtendedDescription(firstItem);
  Iif (!headline && !summary) return null;
  return { headline, summary, extendedSummary };
}
 
/**
 * Combined extractor that runs the Strategic Intelligence Summary path
 * first (highest editorial value) and falls back to Reader Briefing
 * when Strategic Intelligence Summary is absent. Merges the two so a
 * brief that contains **both** sections can use the strategic
 * sub-heading as headline and the reader-briefing prose as the
 * extended description.
 *
 * @param markdown - Brief body (SPDX preamble already stripped)
 * @returns Best `{headline, summary, extendedSummary}`, or `null`
 *          when neither section exists
 */
export function extractBriefingHighlight(markdown: string): BriefingHighlight | null {
  const strategic = extractStrategicSynthesisHighlight(markdown);
  const reader = extractReaderBriefingHighlight(markdown);
  if (!strategic && !reader) return null;
  if (strategic && reader) {
    return {
      headline: strategic.headline || reader.headline,
      summary: strategic.summary || reader.summary,
      extendedSummary: strategic.extendedSummary || reader.extendedSummary,
    };
  }
  return strategic ?? reader;
}