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 | 21x 32x 31x 31x 31x 31x 23x 172x 172x 110x 98x 98x 4x 21x 24x 1460x 1460x 118x 118x 118x 1x 1x 23x 118x 118x 703x 1x 1x 1x 1x 117x 31x 549x 549x 549x 65x 549x 65x 8x 65x 1511x 1502x 1502x 14x 1511x 1511x 42x 98x 98x 98x 3x 95x 95x 2x 93x 93x 2x 91x 91x 1x 90x 90x 1x 1x 90x 21x 3x 3x 104x 104x 104x 102x 1x 1x 1x 1x 1x 1x 9x 9x 9x 8x 8x 8x 7x 7x 7x 7x 8x 8x 8x 8x 8x 8x 8x 13x 13x 6x 5x 7x 7x 7x 6x 6x 8x | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module Aggregator/Metadata/PriorityFindingHighlight
* @description Priority-finding headline/summary extractor split out from
* artifact-highlight.ts to keep individual file sizes under 600 LOC.
*
* Public entry point: extractPriorityFindingHighlight(body) β used by
* artifact-highlight.ts when an artefact has no usable H1.
*/
import { normaliseHeadingText } from './heading-rules.js';
import { cleanPriorityHeadline, stripPriorityTailMetadata } from './priority-finding-cleaning.js';
import {
DESCRIPTION_MAX_LENGTH,
shouldSkipDescriptionLine,
stripInlineMarkdown,
stripLeadingProseLabel,
truncateDescription,
} from './text-utils.js';
import { findTitleRejectionReason } from './title-rejection.js';
/**
* Section headings inside the executive brief that introduce the
* named-priority-finding block (matched case-insensitively against the
* decoration-stripped heading text, see {@link normaliseHeadingText}).
*/
const PRIORITY_FINDING_SECTION_HEADINGS: readonly string[] = [
'key developments',
'key findings',
'key intelligence summary',
'key judgements',
'key judgments',
'headline intelligence',
'headline judgements',
'headline judgments',
'lead story',
'policy intelligence alerts',
'priority dossiers',
'priority dossiers under committee scrutiny',
'priority findings',
'priority intelligence assessment',
'priority items',
'top findings',
'top developments',
'top dossiers',
'top trigger events',
'top triggers',
'trigger events',
'top documents',
'top procedures',
'top 3 triggers',
'wep assessment',
'high priority',
'highest priority',
];
/**
* Mine the FIRST named priority finding from an executive-briefβstyle
* artefact body. Looks for a section heading from
* {@link PRIORITY_FINDING_SECTION_HEADINGS} and returns the first dossier
* name + descriptive paragraph found inside it. Supports the three
* canonical Stage-B authoring patterns:
*
* 1. **Bold-in-numbered-list** (breaking briefs):
* `1. **Digital Markets Act Enforcement** (TA-10-2026-0160, 2026-04-30)`
* ` Parliament adopted a resolution β¦`
* 2. **Numbered subheading** (committee briefs):
* `### 1. Clean Industrial Deal Implementation (ITRE/ENVI)`
* `The Clean Industrial Deal framework β¦`
* 3. **Bold-leading paragraph** (synthesis variants):
* `**Trigger 1: DMA Enforcement Resolution** (TA-10-2026-0160)`
* `- Significance: π’ HIGH IMPACT β¦`
*
* Trailing parenthesised metadata (`(TA-10-2026-0160, 2026-04-30)`,
* `(ITRE/ENVI)`) is stripped from the headline so it stays headline-shaped
* (`Digital Markets Act Enforcement`) rather than boilerplate
* (`Digital Markets Act Enforcement (TA-10-2026-0160, 2026-04-30)`).
*
* @param body - Editorial artefact body
* @returns `{headline, summary}` when a priority finding was identified;
* `null` when the body has no priority section or no usable item inside
*/
export function extractPriorityFindingHighlight(
body: string
): { readonly headline: string; readonly summary: string } | null {
if (!body) return null;
const lines = body.split('\n');
return scanPrioritySection(lines) ?? scanH2StoryHeadings(lines);
}
/**
* Strategy 1 β scan inside the first recognised priority-finding
* section heading for a usable item (Pattern A/B/C/D). Returns `null`
* when the section is absent or contains no matchable item.
*
* @param lines - Body lines (already split on `\n`)
* @returns `{headline, summary}` when an item was identified
*/
function scanPrioritySection(
lines: readonly string[]
): { readonly headline: string; readonly summary: string } | null {
const sectionStart = findPrioritySectionStart(lines);
if (sectionStart < 0) return null;
for (let i = sectionStart + 1; i < lines.length; i++) {
const line = (lines[i] ?? '').trim();
if (!line) continue;
// Stop at the next H2 (sibling section) but allow `### β¦` and
// `#### β¦` subheadings inside (e.g. `### π΄ HIGH PRIORITY` between
// the section header and the first list item).
if (/^##(?!#)/.test(line)) return null;
const candidate = extractPriorityFindingItem(lines, i);
if (candidate) return candidate;
}
return null;
}
/**
* Story-keyword tokens used by `## Lead Story:` / `## Story N:` /
* `## Trigger N:` H2 heading detection. Kept as a runtime list so the
* regex stays bounded and bypasses the unsafe-regex lint by avoiding
* deep alternation.
*/
const H2_STORY_TOKENS: readonly string[] = [
'Lead Story',
'Story',
'Trigger',
'Alert',
'Judgement',
'Judgment',
];
/**
* Strategy 2 β walk every `## β¦` H2 heading and try to recognise a
* story-style heading (`## π Lead Story: Russia Accountability`,
* `## Story 1 β DMA Enforcement`). Used as a fallback when no priority
* section was found, because motions briefs publish each lead story as
* its own H2 without a parent section.
*
* @param lines - Body lines (already split on `\n`)
* @returns `{headline, summary}` when a story heading was identified
*/
function scanH2StoryHeadings(
lines: readonly string[]
): { readonly headline: string; readonly summary: string } | null {
for (let i = 0; i < lines.length; i++) {
const line = (lines[i] ?? '').trim();
if (!line.startsWith('## ')) continue;
const headingText = line.replace(/^##\s+/u, '');
const storyHeadline = extractH2StoryHeadline(headingText);
if (!storyHeadline) continue;
const result = buildPriorityResult(storyHeadline, '', lines, i);
Eif (result?.headline) return result;
}
return null;
}
/**
* Recognise the H2-story shape (`π Lead Story: Title`, `Story 1 β
* Title`, `Trigger 2: Title`) and return the residual headline portion.
* Returns an empty string when the heading does not match a story
* keyword. Implemented as discrete string operations (rather than one
* dense regex) to keep the function under the unsafe-regex linter and
* cognitive-complexity budgets.
*
* @param headingText - Heading text with the leading `## ` already removed
* @returns Residual headline or empty string
*/
function extractH2StoryHeadline(headingText: string): string {
// Strip a short leading decoration / emoji block (up to 4 non-alphanumerics).
const stripped = headingText.replace(/^[^A-Za-z0-9]{0,4}\s*/u, '');
for (const token of H2_STORY_TOKENS) {
if (!stripped.toLowerCase().startsWith(token.toLowerCase())) continue;
let rest = stripped.slice(token.length).trim();
// `Story 1` / `Trigger 2` β accept and consume the trailing digit.
Iif (token !== 'Lead Story') {
const digit = rest.match(/^\d+\b/u);
if (!digit) continue;
rest = rest.slice(digit[0].length).trim();
}
// Require an explicit `:` / `β` / `β` / `-` / `.` separator before
// the residual headline so plain prose H2s never match.
const sep = rest.match(/^[:ββ\-.]\s+(.+)$/u);
Eif (sep?.[1]) return sep[1].trim();
}
return '';
}
/**
* Locate the line index of the first priority-finding section heading
* inside an artefact body. Returns `-1` when no such heading exists.
*
* @param lines - Body lines (already split on `\n`)
* @returns Line index of the `## β¦` heading, or `-1`
*/
function findPrioritySectionStart(lines: readonly string[]): number {
for (let i = 0; i < lines.length; i++) {
const line = (lines[i] ?? '').trim();
const match = line.match(/^#{2,4}\s+(.+)$/u);
if (!match) continue;
const text = normaliseHeadingText(match[1] ?? '');
Iif (!text) continue;
if (headingMatchesPriorityProbe(text)) return i;
}
return -1;
}
/**
* Word-boundary substring matcher for the priority-finding section
* detector. Extracted from {@link findPrioritySectionStart} to keep its
* cognitive complexity within budget.
*
* @param text - Heading text already normalised by {@link normaliseHeadingText}
* @returns `true` when one of {@link PRIORITY_FINDING_SECTION_HEADINGS}
* appears as a word-bounded substring of {@link text}
*/
function headingMatchesPriorityProbe(text: string): boolean {
for (const probe of PRIORITY_FINDING_SECTION_HEADINGS) {
if (text === probe) return true;
const idx = text.indexOf(probe);
if (idx < 0) continue;
const before = idx === 0 ? ' ' : (text[idx - 1] ?? ' ');
const after = text[idx + probe.length] ?? ' ';
if (!/[A-Za-z0-9]/.test(before) && !/[A-Za-z0-9]/.test(after)) return true;
}
return false;
}
/**
* Try to recognise a priority-finding item starting at {@link i}. Returns
* the resolved `{headline, summary}` pair when the item matches one of the
* three authoring patterns; returns `null` otherwise so the caller can
* advance to the next line.
*
* @param lines - Body lines (already split on `\n`)
* @param i - Index of the candidate line
* @returns Priority-finding pair when matched, `null` otherwise
*/
function extractPriorityFindingItem(
lines: readonly string[],
i: number
): { readonly headline: string; readonly summary: string } | null {
const line = (lines[i] ?? '').trim();
// Pattern A β numbered list item with bold title:
// `1. **Digital Markets Act Enforcement** (TA-10-2026-0160, 2026-04-30)`
const numberedBold = line.match(/^\d+\.\s+\*\*([^*]+?)\*\*\s*(.*)$/u);
if (numberedBold) {
return buildPriorityResult(numberedBold[1] ?? '', numberedBold[2] ?? '', lines, i);
}
// Pattern B β numbered subheading. Requires an explicit separator
// (`:` / `.` / `)` / `Β·` / `β` / `β` / `-`) after the number so
// dotted decimal section labels like `### 2.1 Close to Adoption`
// do NOT leak into the headline. Examples:
// `### 1. Clean Industrial Deal Implementation (ITRE/ENVI)`
// `### 1 Β· Headline Judgements` (middle dot)
// `### KJ-1: Digital Regulation Enforcement β¦`
// `### KF-3: Banking Union Completion`
// `### T-2: DMA Enforcement Resolution`
// Two narrow patterns instead of one wide alternation to keep the
// pattern within the unsafe-regex linter's complexity budget.
const numericHeading = line.match(/^#{3,4}\s+\d+[:.)Β·ββ\s-]\s*(.+)$/u);
if (numericHeading) {
return buildPriorityResult(numericHeading[1] ?? '', '', lines, i);
}
const tagHeading = line.match(/^#{3,4}\s+[A-Z]{1,3}-?\d+[:.)Β·ββ\s-]\s*(.+)$/u);
if (tagHeading) {
return buildPriorityResult(tagHeading[1] ?? '', '', lines, i);
}
// Pattern D β word-prefixed subheading (`### Alert 1 β Title π΄`,
// `### Judgement 1 β Title`, `### Trigger 1: DMA Enforcement`):
const wordTaggedHeading = line.match(
/^#{3,4}\s+(?:Alert|Judgement|Judgment|Finding|Story|Item|Trigger|Highlight|Dossier|Priority|Top)\s+\d+\s*[:.)Β·ββ\s-]+(.+)$/iu
);
if (wordTaggedHeading) {
return buildPriorityResult(wordTaggedHeading[1] ?? '', '', lines, i);
}
// Pattern C β bold-leading paragraph trigger:
// `**Trigger 1: DMA Enforcement Resolution** (TA-10-2026-0160)`
// `**Digital Markets Act Enforcement**`
// Rejected when:
// - the bold body is longer than a plausible headline (>110 chars) β
// that's a bold paragraph lede masquerading as a headline (e.g.
// `**This period captures the April 2026 Strasbourg β¦**`)
// - the bold body is a metadata key (`**Admiralty Grade: B/2**`,
// `**Reporting Window:** β¦`, `**Date:** β¦`) β these are banner
// rows, not editorial headlines
const boldOnly = line.match(/^\*\*([^*]+?)\*\*\s*(.*)$/u);
if (boldOnly && !line.startsWith('**Confidence') && !isMetadataBoldLine(line)) {
const candidate = (boldOnly[1] ?? '').trim();
Iif (candidate.length > 0 && candidate.length <= 110) {
return buildPriorityResult(candidate, boldOnly[2] ?? '', lines, i);
}
}
return null;
}
/**
* Bold prefix tokens that indicate a metadata banner row rather than an
* editorial headline. The Stage-B brief template uses these consistently
* as the lede block (`**Reporting Window:** 3 Apr β 1 May 2026`,
* `**Admiralty Grade:** B/2`, `**Date:** 2026-05-15`); they must never
* leak into `<title>`.
*/
const PRIORITY_METADATA_BOLD_PREFIXES: readonly string[] = [
'admiralty',
'admiralty scale',
'admiralty scale used',
'analysis owner',
'analyst note',
'analytical quality',
'bluf',
'bottom line up front',
'caveats and gaps',
'classification',
'composition layer',
'confidence',
'confidence summary',
'data quality',
'data sources',
'date',
'emerging patterns',
'forward indicators',
'gate target',
'generated',
'headline judgement',
'headline judgment',
'horizon',
'imf status',
'issue',
'key assumptions',
'key assumptions check',
'key intelligence',
'key risk indicators',
'lead author',
'master assumptions',
'master narrative',
'methodology',
'parliamentary status',
'period',
'prepared',
'purpose',
'quality of information check',
'reporting',
'reporting window',
'run',
'sat documentation',
'sat documentation below',
'scope',
'session',
'signal assessment',
'source',
'sources',
'threat level',
'tier 1 priority issues',
'tier 2 priority issues',
'tier 3 priority issues',
'tier 1 priority',
'tier 2 priority',
'tier 3 priority',
'time horizon',
'top line',
'top-line judgement',
'top-line judgment',
'wep',
'wep band',
'wep bands',
'wep bands applied',
'window',
];
/**
* Recognise a metadata-banner bold line (`**Admiralty Grade: B/2**`,
* `**Reporting Window:** 3 Apr β 1 May 2026`). The check is
* deliberately case-insensitive and tolerant of trailing colons inside
* or outside the bold delimiters.
*
* @param line - Trimmed source line (already known to start with `**`)
* @returns `true` when the line is a metadata banner that must be
* skipped by Pattern C
*/
function isMetadataBoldLine(line: string): boolean {
const inner = line
.replace(/^\*\*([^*]+?)\*\*.*$/u, '$1')
.trim()
.toLowerCase();
for (const prefix of PRIORITY_METADATA_BOLD_PREFIXES) {
Iif (inner === prefix) return true;
Iif (inner.startsWith(`${prefix}:`)) return true;
if (inner.startsWith(`${prefix} `) && inner.includes(':')) return true;
Iif (inner.startsWith(`${prefix}β`) || inner.startsWith(`${prefix} β`)) return true;
}
// Pipe-banner shape: two or more `|`-separated segments inside the
// bold body indicate a methodology / SAT-tag banner row, never an
// editorial headline (e.g.
// `**WEP Bands Applied | Admiralty Scale Used | SAT Documentation**`).
// Single `|` is allowed because it occurs in legitimate headlines
// ("Brexit | A Decade On"). Three or more delimiters is the threshold.
const pipeSegments = inner
.split('|')
.map((s) => s.trim())
.filter((s) => s.length > 0);
Iif (pipeSegments.length >= 3) return true;
// Trailing-ellipsis bold: `**Some long banner lineβ¦**` was clipped by
// the brief author and is not a usable editorial headline.
Iif (inner.endsWith('β¦') || inner.endsWith('...')) return true;
return false;
}
/**
* Compose the `{headline, summary}` pair for one matched priority-finding
* item. Cleans `Trigger N:` / `N.` prefixes off the headline, strips the
* trailing `(TA-10-β¦, β¦)` / `(ITRE/ENVI)` metadata, and gathers the
* following prose lines as the summary.
*
* @param rawHeadline - Raw bold title or numbered-heading text
* @param tail - Same-line trailing text (after the bold close / heading)
* @param lines - Body lines (already split on `\n`)
* @param i - Index of the matched line
* @returns Cleaned `{headline, summary}` β headline may be empty when
* cleaning collapses it below a minimum length, in which case the
* caller falls through
*/
function buildPriorityResult(
rawHeadline: string,
tail: string,
lines: readonly string[],
i: number
): { readonly headline: string; readonly summary: string } | null {
const cleaned = cleanPriorityHeadline(rawHeadline);
Iif (cleaned.length < 5) return null;
// Reject bold-prose section labels (`Strategic significance`,
// `Threat Level`, `Convergence themes`, β¦) and other denylisted
// tokens. Without this, the priority-finding loop would surface a
// `**Strategic significance:** β¦` line β which the executive-brief
// template uses inside every dossier subsection β as the article
// title. See `title-rejection.ts` for the full denylist.
if (findTitleRejectionReason(cleaned)) return null;
const summaryLines = collectPrioritySummaryLines(tail, lines, i);
const summary = truncateDescription(summaryLines.join(' '));
return { headline: cleaned, summary };
}
/**
* Decide whether a follow-up line is a hard stop for priority-finding
* summary gathering (next heading / next list item) β collapses three
* boolean checks out of {@link buildPriorityResult}'s main loop.
*
* @param line - Trimmed follow-up line
* @returns `true` when the gathering loop must break
*/
function isPrioritySummaryStopper(line: string): boolean {
Iif (/^#{1,6}\s/.test(line)) return true;
Iif (/^\d+\.\s/.test(line)) return true;
Iif (/^[-*]\s/.test(line)) return true;
return false;
}
/**
* Gather the summary prose for a priority-finding item β the same-line
* tail (with leading procedure-code parens stripped) plus subsequent
* prose lines until a blank line / new heading / new bullet is hit.
*
* @param tail - Same-line text that trails the bold/heading
* @param lines - Full body lines
* @param i - Index of the matched headline line
* @returns Ordered list of summary segments (already clean)
*/
function collectPrioritySummaryLines(
tail: string,
lines: readonly string[],
i: number
): readonly string[] {
const summaryLines: string[] = [];
// Strip leading parens-metadata (`(TA-10-2026-0160, 2026-04-30)`) and
// trailing parens-metadata from the tail so the summary starts with
// editorial prose, not a procedure-code citation.
let tailText = stripInlineMarkdown(tail).trim();
tailText = tailText.replace(/^\([^()]{3,80}\)\s*/u, '');
tailText = stripPriorityTailMetadata(tailText).trim();
// Strip leading all-caps prose labels (`BLUF:`, `SITUATION:`, `WEP:`,
// `KEY MOTION:`) that the lede-extractor walker already removes β
// priority-finding summaries flow into the same `<meta description>`
// surface and the HTML pipeline test forbids the all-caps opener.
tailText = stripLeadingProseLabel(tailText);
if (tailText) summaryLines.push(tailText);
for (let j = i + 1; j < lines.length; j++) {
const next = (lines[j] ?? '').trim();
if (!next) {
if (summaryLines.length > 0) break;
continue;
}
Iif (isPrioritySummaryStopper(next)) break;
Iif (next.startsWith('**Confidence') || next.startsWith('- **Confidence')) continue;
if (shouldSkipDescriptionLine(next)) continue;
summaryLines.push(stripLeadingProseLabel(stripInlineMarkdown(next)));
Iif (summaryLines.join(' ').length >= DESCRIPTION_MAX_LENGTH) break;
}
return summaryLines;
}
|