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 | 1x 13x 13x 13x 13x 62x 13x 1x 1x 12x 6x 6x 1x 1x 10x 1x 12x 12x 72x 12x 23x 5x 5x 5x 3x 3x 3x 11x 17x 11x 9x 9x 9x 9x 4x 4x 4x 4x 4x 4x 4x 4x 6x 6x 6x 1x 6x 1x 6x 6x 6x 1x 6x 6x 1x 6x 1x 6x 1x | /**
* Headline Quality Checker — content-side editorial gate for `executive-brief.md` H1s
*
* Catches editorial defects in the H1 line of every
* `analysis/daily/<date>/<subfolder>/executive-brief.md` *before* the SEO
* composer in `scripts/render-lib/article-seo.ts` is asked to clean and
* truncate it. The render pipeline's `cleanArticleTitle` is a best-effort
* cosmetic strip (it removes `Executive Brief — …` prefixes and trailing
* ISO dates); this validator instead enforces the content contract at
* source so the editorial team is forced to fix bad headlines rather than
* relying on the renderer to silently paper over them.
*
* The four rules enforced (one violation per H1 line, multiple rules can
* fire on the same H1):
*
* A. **Untranslated Swedish in EN H1** — definite-form party names
* (`Socialdemokraterna`, `Moderaterna`, …) and other un-localized
* Swedish nouns leak into English headlines. Proper nouns
* `Riksdagen`/`Regeringen`/`Riksmöte` are explicitly allowed (they
* are valid English-prose loanwords per the per-folder methodology;
* see `scripts/check-analysis-language.ts` comments).
* B. **Weekday-date prefix** — `Thursday 21 May 2026 closes with…`
* style calendar prefixes are tautological (the article URL slug
* and front-matter `date:` field already encode the date).
* C. **ISO date leading/trailing** — `2026-05-21 …` or `… — 2026-05-21`
* style file-system slugs masquerading as headlines.
* D. **Boilerplate scaffolding leftover** — `Executive Brief — `,
* `Realtime Monitor — `, `Pass 2`, `Methodology Reflection`, etc.
* These are intended for the brief's *file* heading, never the
* shipped article H1.
* E. **H1 equals prettified subfolder** — bare category labels like
* `# Government Propositions` (for the `propositions/` subfolder)
* or `# Election Cycle Current` (for `election-cycle/current/`).
* These trigger the renderer's silent BLUF-fallback path; this rule
* forces the editorial team to write a real actor+verb headline
* rather than relying on the renderer to paper over the laziness.
* Mirrors the content-side equivalent of `cleanArticleTitle`'s
* subfolder-equality guard in
* `scripts/render-lib/aggregator/seo/title.ts`.
*
* The validator walks every `analysis/daily/<date>/<subfolder>/executive-brief.md`
* (the English source from which all 14 locales are translated). Rules A-E
* apply to the EN brief only; translated `executive-brief_<lang>.md`
* variants are *not* scanned because Swedish loanwords are legitimate in
* `executive-brief_sv.md`, etc.
*
* @module scripts/check-headline-quality
* @author Hack23 AB
* @license Apache-2.0
*/
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join, relative } from 'node:path';
import { prettifyFallbackTitle } from './render-lib/aggregator/order.js';
// ─────────────────────────────────────────────────────────────────────────
// Rule A — Untranslated Swedish in EN H1
// ─────────────────────────────────────────────────────────────────────────
/**
* Swedish tokens that *must not* appear in an English news H1. Lower-cased
* for case-insensitive matching against tokenised H1 words. Limited to a
* focused subset so the rule is high-precision:
*
* - Definite-form party names (Swedish convention adds `-na`/`-erna`):
* `Socialdemokraterna` → `Social Democrats`.
* - Untranslated common nouns regularly seen in our daily briefs:
* `propositionen`, `utskottet`, `svarsdatum`, `näringsutskottet`, etc.
* - Tidö-coalition slugs left in their Swedish form:
* `Tidöavtalet` (the agreement) / `Tidöregeringen` (the cabinet).
*
* Explicitly *not* listed (allowed in EN headlines):
* - `Riksdag`, `Riksdagen`, `Regeringen`, `Riksmöte` — convention loans.
* - Party *abbreviations* (`S`, `M`, `SD`, `KD`, …) — single letters.
* - Person names (`Kristersson`, `Andersson`, …) — proper nouns.
* - Bill / proposition IDs (`HD03267`, `prop. 2025/26:267`).
*/
export const SWEDISH_HEADLINE_TOKENS = new Set<string>([
// Definite-form party names — translate to English forms
'socialdemokraterna',
'moderaterna',
'sverigedemokraterna',
'kristdemokraterna',
'centerpartiet',
'liberalerna',
'miljöpartiet',
'vänsterpartiet',
// Untranslated political-vocabulary nouns
'propositionen',
'utskottet',
'näringsutskottet',
'finansutskottet',
'justitieutskottet',
'socialutskottet',
'arbetsmarknadsutskottet',
'konstitutionsutskottet',
'svarsdatum',
'lagrådsremiss',
'lagrådsremissen',
'kommittédirektiv',
'kommittédirektivet',
// Tidö coalition slugs — translate to "Tidö coalition" / "Tidö government"
'tidöavtalet',
'tidöregeringen',
// Common Swedish function words — never valid in EN
'och',
'att',
'för',
'inte',
'enligt',
'samt',
'genom',
]);
/** Detect any token from {@link SWEDISH_HEADLINE_TOKENS} in the H1 text. */
export function findSwedishHeadlineTokens(h1: string): string[] {
const matches = h1.toLowerCase().match(/[a-zåäöéü]+/g);
Iif (!matches) return [];
const hits = new Set<string>();
for (const tok of matches) {
if (SWEDISH_HEADLINE_TOKENS.has(tok)) hits.add(tok);
}
return Array.from(hits).sort();
}
// ─────────────────────────────────────────────────────────────────────────
// Rule B — Weekday-date prefix
// ─────────────────────────────────────────────────────────────────────────
/**
* Match calendar prefixes like `Thursday 21 May 2026 …` /
* `Mon 4 Nov 2024 …` at the start of an H1. We don't enumerate full
* day-month names in a single huge regex — instead we require the
* sequence (weekday name) (digit-day) (month name) (4-digit year),
* which is precise enough to avoid false positives on legitimate
* headlines like "Monday morning briefing".
*/
const WEEKDAY_RE =
/^(?:Mon|Monday|Tue|Tuesday|Wed|Wednesday|Thu|Thursday|Fri|Friday|Sat|Saturday|Sun|Sunday)\b/i;
const MONTH_RE =
/\b(?:Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|Sept|September|Oct|October|Nov|November|Dec|December)\b/i;
export function hasWeekdayDatePrefix(h1: string): boolean {
if (!WEEKDAY_RE.test(h1)) return false;
// After the weekday, look for a number + month name + 4-digit year within
// the first ~40 characters; this is the calendar-prefix signature.
const head = h1.slice(0, 50);
return /\b\d{1,2}\b/.test(head) && MONTH_RE.test(head) && /\b(?:19|20)\d{2}\b/.test(head);
}
// ─────────────────────────────────────────────────────────────────────────
// Rule C — ISO-date leading / trailing
// ─────────────────────────────────────────────────────────────────────────
const ISO_DATE_LEADING_RE = /^\d{4}-\d{2}-\d{2}\b/;
// Trailing ISO date at the end of the H1, with an optional `—/–/-/:`
// separator before it. The optional-separator form deliberately also
// matches a plain " 2026-05-21" suffix (whitespace only), which is the
// most common file-slug-as-headline antipattern in our archive.
const ISO_DATE_TRAILING_RE = /(?:^|[\s\-–—:])\d{4}-\d{2}-\d{2}\s*$/;
export function hasIsoDateAffix(h1: string): { leading: boolean; trailing: boolean } {
return {
leading: ISO_DATE_LEADING_RE.test(h1),
trailing: ISO_DATE_TRAILING_RE.test(h1),
};
}
// ─────────────────────────────────────────────────────────────────────────
// Rule D — Boilerplate scaffolding leftover
// ─────────────────────────────────────────────────────────────────────────
/**
* Boilerplate H1 prefixes that signal the headline still carries the
* brief's scaffolding instead of an editorial title. The renderer's
* `cleanArticleTitle` strips these post-hoc; the editorial contract is
* that the source brief should not contain them in the first place.
*
* Note: `Executive Brief — …` is the *default* scaffolding emitted by
* older brief templates; the new contract is that the H1 should be a
* real headline ("Sweden Abolishes Permanent Residence …") with the
* `Executive Brief` label living in a separate `## Executive Brief`
* section header below.
*/
const BOILERPLATE_PREFIXES: ReadonlyArray<{ readonly label: string; readonly re: RegExp }> = [
{ label: 'Executive Brief', re: /^\s*(?:[#📋📰🎯⚡🧭]\s*)*executive\s+brief\b/iu },
{ label: 'Realtime Monitor', re: /^\s*(?:[#📋📰🎯⚡🧭]\s*)*realtime\s+monitor\b/iu },
{ label: 'Methodology Reflection', re: /^\s*methodology\s+reflection\b/i },
{ label: 'Pass 1', re: /^\s*pass\s*1\b/i },
{ label: 'Pass 2', re: /^\s*pass\s*2\b/i },
{ label: 'Daily Brief', re: /^\s*daily\s+brief\b/i },
];
export function findBoilerplatePrefixes(h1: string): string[] {
const hits: string[] = [];
for (const { label, re } of BOILERPLATE_PREFIXES) {
if (re.test(h1)) hits.push(label);
}
return hits;
}
// ─────────────────────────────────────────────────────────────────────────
// Rule E — H1 equals prettified subfolder slug
// ─────────────────────────────────────────────────────────────────────────
/**
* Lower-case, punctuation-stripped, whitespace-collapsed comparison form.
* Mirrors `normaliseTitleForCompare` in
* `scripts/render-lib/aggregator/seo/title.ts` so the content-side
* editorial gate fires on the same set of strings the renderer would
* silently null-out via its subfolder-equality guard.
*/
export function normaliseHeadlineForCompare(text: string): string {
return text
.toLowerCase()
.replace(/[^\p{L}\p{N}\s]/gu, ' ')
.replace(/\s+/g, ' ')
.trim();
}
/**
* Derive the "subfolder path" relative to `analysis/daily/<date>/` for a
* given brief filepath. Returns `null` when the brief is not inside the
* canonical `analysis/daily/<YYYY-MM-DD>/<subfolder...>/executive-brief.md`
* layout.
*
* Example: `analysis/daily/2026-05-08/election-cycle/current/executive-brief.md`
* → `election-cycle/current`.
*/
export function subfolderFromBriefPath(filepath: string): string | null {
const norm = filepath.split(/[\\/]/);
const idx = norm.indexOf('daily');
if (idx < 0 || idx + 2 >= norm.length) return null;
// norm[idx+1] is the YYYY-MM-DD bucket; the subfolder is everything between
// that and the final `executive-brief.md` filename.
const parts = norm.slice(idx + 2, -1);
Iif (parts.length === 0) return null;
return parts.join('/');
}
/**
* Build the prettified label for a multi-segment subfolder path. Joins
* each path segment via `prettifyFallbackTitle` so `election-cycle/current`
* → `Election Cycle Current`.
*/
export function prettifySubfolderPath(subfolder: string): string {
return subfolder
.split('/')
.filter(Boolean)
.map((seg) => prettifyFallbackTitle(seg))
.join(' ');
}
/**
* Detect a Rule-E violation: the H1 (after cosmetic normalisation) equals
* the prettified subfolder label (full path, or just the leaf segment).
*
* Both forms are checked because shallow briefs (`propositions/`) and
* nested briefs (`election-cycle/current/`) both fail the renderer's
* subfolder-equality guard but with different label forms.
*/
export function matchesPrettifiedSubfolder(h1: string, subfolder: string | null): boolean {
if (!subfolder) return false;
const headline = normaliseHeadlineForCompare(h1);
Iif (!headline) return false;
const fullLabel = normaliseHeadlineForCompare(prettifySubfolderPath(subfolder));
if (fullLabel && headline === fullLabel) return true;
const segments = subfolder.split('/').filter(Boolean);
const leaf = segments[segments.length - 1];
Iif (!leaf) return false;
const leafLabel = normaliseHeadlineForCompare(prettifyFallbackTitle(leaf));
return Boolean(leafLabel) && headline === leafLabel;
}
// ─────────────────────────────────────────────────────────────────────────
// H1 extraction
// ─────────────────────────────────────────────────────────────────────────
/**
* Pull the first `# …` H1 line out of the brief body. Skips YAML
* frontmatter (the leading `---\n…\n---` block) before scanning so a
* YAML key with `# inline comment` markers can't mislead the
* extractor. Returns `null` if no H1 is found.
*/
export function extractH1(markdown: string): string | null {
// Strip YAML frontmatter (anchored at start of file only — never
// multiline, otherwise a body `---` thematic break would swallow prose).
const body = markdown.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, '');
const m = body.match(/^# +(.+?)\s*$/m);
return m ? m[1].trim() : null;
}
// ─────────────────────────────────────────────────────────────────────────
// File discovery
// ─────────────────────────────────────────────────────────────────────────
/**
* Recursively find every `executive-brief.md` (English source) under the
* given `analysis/daily/` root. Excludes:
* - `executive-brief_<lang>.md` (translation outputs — Swedish loans OK)
* - `pass1/` and `full-text/` subdirectories
*/
export function findEnglishBriefs(dir: string): string[] {
const out: string[] = [];
function walk(currentDir: string): void {
let entries;
try {
entries = readdirSync(currentDir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
const fullPath = join(currentDir, entry.name);
if (entry.isDirectory()) {
if (entry.name === 'pass1' || entry.name === 'full-text') continue;
walk(fullPath);
} else if (entry.isFile() && entry.name === 'executive-brief.md') {
out.push(fullPath);
}
}
}
walk(dir);
return out;
}
// ─────────────────────────────────────────────────────────────────────────
// Validation
// ─────────────────────────────────────────────────────────────────────────
export interface HeadlineViolation {
readonly filepath: string;
readonly relpath: string;
readonly h1: string;
/** Each rule firing produces one entry, e.g. `'rule-A: Socialdemokraterna'`. */
readonly issues: ReadonlyArray<string>;
}
/**
* Validate a single H1 string against the five headline-quality rules.
* Pure function — exported for unit testing without filesystem I/O.
*
* @param h1 — the trimmed H1 line text (without the leading `# `).
* @param subfolder — the brief's containing subfolder relative to
* `analysis/daily/<date>/` (e.g. `propositions` or
* `election-cycle/current`). When provided, Rule E fires if the H1
* matches the prettified label of either the full path or its leaf.
*/
export function validateH1(h1: string, subfolder?: string | null): string[] {
const issues: string[] = [];
// Rule A — Swedish-in-EN tokens
const swedishHits = findSwedishHeadlineTokens(h1);
if (swedishHits.length > 0) {
issues.push(`rule-A (Swedish-in-EN H1): ${swedishHits.join(', ')}`);
}
// Rule B — Weekday-date prefix
if (hasWeekdayDatePrefix(h1)) {
issues.push('rule-B (weekday-date prefix): H1 begins with "Weekday DD Month YYYY …"');
}
// Rule C — ISO date leading / trailing
const iso = hasIsoDateAffix(h1);
Iif (iso.leading) {
issues.push('rule-C (ISO-date leading): H1 begins with a YYYY-MM-DD slug');
}
if (iso.trailing) {
issues.push('rule-C (ISO-date trailing): H1 ends with " — YYYY-MM-DD"');
}
// Rule D — Boilerplate scaffolding leftover
const boilerplate = findBoilerplatePrefixes(h1);
if (boilerplate.length > 0) {
issues.push(`rule-D (boilerplate prefix): ${boilerplate.join(', ')}`);
}
// Rule E — H1 equals prettified subfolder slug
if (subfolder && matchesPrettifiedSubfolder(h1, subfolder)) {
issues.push(
`rule-E (H1 == prettified subfolder): H1 is the bare category label for "${subfolder}"; write a real actor+verb headline`,
);
}
return issues;
}
/** Walk every English brief under `analysisDir` and collect H1 violations. */
export function validateHeadlines(analysisDir: string): HeadlineViolation[] {
const violations: HeadlineViolation[] = [];
const briefs = findEnglishBriefs(analysisDir);
for (const filepath of briefs) {
let markdown: string;
try {
markdown = readFileSync(filepath, 'utf8');
} catch {
continue;
}
const h1 = extractH1(markdown);
if (!h1) continue;
const subfolder = subfolderFromBriefPath(filepath);
const issues = validateH1(h1, subfolder);
if (issues.length > 0) {
violations.push({
filepath,
relpath: relative(process.cwd(), filepath),
h1,
issues,
});
}
}
return violations;
}
export function formatViolationReport(violations: HeadlineViolation[]): string {
if (violations.length === 0) return '';
const lines: string[] = [];
for (const v of violations) {
lines.push(`• ${v.relpath}`);
lines.push(` H1: ${v.h1}`);
for (const issue of v.issues) {
lines.push(` - ${issue}`);
}
lines.push('');
}
return lines.join('\n');
}
// ─────────────────────────────────────────────────────────────────────────
// CLI
// ─────────────────────────────────────────────────────────────────────────
/**
* CLI entry point.
*
* Usage:
* npx tsx scripts/check-headline-quality.ts [analysis-dir]
* npm run check:headline-quality -- [analysis-dir]
*
* Exit codes:
* 0 — no violations
* 1 — one or more H1s failed at least one rule (or `analysis-dir` missing)
*/
export async function main(): Promise<void> {
const args = process.argv.slice(2);
const analysisDir = args[0] && args[0].trim().length > 0 ? args[0] : 'analysis/daily';
try {
const stats = statSync(analysisDir);
if (!stats.isDirectory()) {
console.error(`❌ headline-quality: ${analysisDir} is not a directory`);
process.exit(1);
}
} catch {
console.error(`❌ headline-quality: ${analysisDir} does not exist`);
process.exit(1);
}
const violations = validateHeadlines(analysisDir);
const totalChecked = findEnglishBriefs(analysisDir).length;
if (violations.length > 0) {
console.error(
`❌ headline-quality: ${violations.length} violation(s) across ${totalChecked} executive-brief.md file(s)\n`,
);
console.error(formatViolationReport(violations));
console.error(
'Fix the editorial issues in the source executive-brief.md H1 line(s).\n' +
'Rules:\n' +
' A — translate Swedish tokens (Socialdemokraterna → Social Democrats)\n' +
' B — drop weekday-date prefixes (URL slug + frontmatter `date:` already encode this)\n' +
' C — drop ISO-date leading/trailing slugs (not headlines)\n' +
' D — drop scaffolding prefixes (Executive Brief — / Realtime Monitor — / Pass 2 / …)\n' +
' E — H1 must not be the bare prettified subfolder label (write a real actor+verb headline)',
);
process.exit(1);
}
console.log(`✅ headline-quality: 0 violations across ${totalChecked} executive-brief.md files`);
process.exit(0);
}
// Run CLI if invoked directly
Iif (import.meta.url === `file://${process.argv[1]}`) {
void main();
}
|