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 | 2x 2x 2x 2x 2x 14x 2x 2x 102x 102x 103x 102x 84x 84x 18x 182x 182x 182x 152x 182x 6x 6x 27x 27x 26x 6x 6x 14x 6x 4x 4x 7x 7x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 2x 2x 2x 2x 4x 3x 3x 2x 2x 2x 8x 8x 8x 8x 14x 14x 6x 8x 5x 2x 18x 18x 18x 18x 18x 1x 1x 17x 17x 17x 17x 1x 17x 1x 1x 16x 16x 16x 4x 16x 16x 16x 144x 16x 5x 16x 16x 112x 112x 112x 112x 70x 70x 70x 72x 72x 20x 70x 20x 16x 48x 48x 33x 33x 48x 5x 16x 16x 1x 1x 1x 16x 3x 3x 5x 5x 4x 4x 1x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | #!/usr/bin/env node
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module scripts/validate-brief-translations
* @description Drift-guard / quality validator for executive-brief translations.
*
* Validates every `analysis/daily/<date>/<slug>/executive-brief_<lang>.md`
* companion in the repo (or a caller-supplied subset) against seven gates:
*
* 1. **Filename ↔ language code** — suffix `_<lang>.md` must use a code in
* `TARGET_LANGS`.
* 2. **Source presence** — a sibling `executive-brief.md` must exist.
* 3. **Length floor** — translation byte size ≥ 50% of source
* (CJK shrinks to ~70%; below 50% is almost certainly a stub).
* 4. **No English fall-through** — at most `MAX_ENGLISH_PATTERNS` (default 4)
* hits of the `EN_PATTERNS` regex set may appear in the body. Untranslated
* copies trip this gate.
* 5. **Fixed-token preservation** — proper nouns that must NEVER be
* localised (`IMF`, `WEO`, `World Bank`, `Fiscal Monitor`,
* `data-vintage="WEO-…"`, EP
* adopted-text IDs like `TA-10-2026-0160`) must appear in the translation
* whenever they appear in the source.
* 6. **Heading parity** — H1/H2/H3 heading counts must match
* the source closely (H1 must match exactly; H2/H3 may differ by at most
* `HEADING_TOLERANCE`). LLMs frequently collapse or skip subsections,
* and this gate catches that without flagging legitimate small
* reformattings.
* 7. **Mermaid block parity** — every ```` ```mermaid ```` block in the
* source must appear at least once in the translation. Mermaid syntax
* is a machine-readable fixed token; dropping a diagram silently breaks
* downstream HTML rendering.
*
* Each translation that fails any gate produces a structured report entry.
* The process exits with code 1 if any failures are present (unless
* `--no-fail` is passed for advisory mode).
*
* This script is invoked by:
* - `npm run validate:translations` (CI + local)
* - `news-translate` workflow Step 4 (per-run gate)
*
* Invocation:
* node scripts/validate-brief-translations.js \
* [--repo-root <path>] \
* [--paths <glob>...] # validate specific translation files only
* [--report <path>] # write JSON report; default stdout
* [--no-fail] # exit 0 even when violations found
* [--quiet] # suppress per-file logging
*/
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { TARGET_LANGS } from './discover-untranslated-briefs.js';
/**
* Minimum translated-byte-size as a fraction of the source size.
* CJK languages routinely shrink to ~60% (kanji are denser than English),
* so we set the floor at 50% rather than 80%.
*/
export const LENGTH_FLOOR_RATIO = 0.5;
/** Maximum number of English-only sentence patterns tolerated in a translation. */
export const MAX_ENGLISH_PATTERNS = 4;
/**
* Conservative set of English-only sentence patterns. A translation that
* contains more than `MAX_ENGLISH_PATTERNS` matches is almost certainly an
* untranslated copy of the English source. The patterns are intentionally
* narrow: short function words (`the`, `of`, `and`) match every European
* Latin-script language and would generate too many false positives.
*/
export const EN_PATTERNS = [
/\bthe European Parliament\b/i,
/\bbottom line up front\b/i,
/\bkey judgments?\b/i,
/\bbased on official EP\b/i,
/\bplenary session\b/i,
/\b60-second read\b/i,
/\bconfidence:\s*🟢\s*high\b/i,
/\bnext steps\b/i,
/\bin favour\b/i,
];
/**
* Proper-noun / fixed-string tokens that translators MUST preserve verbatim
* when they appear in the source. Tokens are matched case-sensitively.
*/
/**
* Tokens that MUST be preserved verbatim in every translation.
*
* Each pattern matches one class of "fixed token" — proper nouns, ID
* formats, or machine-readable attributes — that the translator agent
* must NOT localise. The fixed-token preservation gate applies the rule like this:
* every exact token instance from the SOURCE must also appear in the
* TRANSLATION at least the same number of times.
*
* - `IMF` — International Monetary Fund. Stays Latin-script even in
* Arabic, Hebrew, Japanese, Korean, Chinese translations.
* - `WEO` — IMF World Economic Outlook publication acronym.
* - `World Bank` — proper noun, never translated.
* - `Fiscal Monitor` — IMF publication name; stays English.
* - `data-vintage="WEO-<Month>-YYYY"` — machine-readable HTML attribute used
* by downstream renderers; the `WEO-Month-Year` shape
* must round-trip exactly.
* - `TA-NN-YYYY-NNNN` — European Parliament adopted-text reference
* (e.g. `TA-10-2026-0160`); cited verbatim in news articles.
* - `YYYY/NNNN(III)` — EP legislative procedure ID (e.g. `2024/0001(COD)`
* where `III` is one of COD, INI, NLE, RSP, BUD …); used
* as a stable handle by EUR-Lex / OEIL.
*
* Patterns are anchored with `\b` word boundaries where appropriate so that
* sub-string false positives (e.g. `WEOlogical` or `IMFinity`) do not match.
*
* @type {readonly RegExp[]}
*/
export const FIXED_TOKEN_PATTERNS = Object.freeze([
/\bIMF\b/,
/\bWEO\b/,
/\bWorld Bank\b/,
/\bFiscal Monitor\b/,
/data-vintage="WEO-[A-Za-z]+-\d{4}"/,
/\bTA-\d{1,2}-\d{4}-\d{4}\b/,
/\b\d{4}\/\d{4}\([A-Z]{3}\)/,
]);
/**
* Pre-compiled `g`-flag variants of FIXED_TOKEN_PATTERNS.
*
* `String#match(regex)` only returns ALL matches when the regex has the
* `g` flag. We pre-compile the global variants once at module load (instead
* of in the per-translation validation loop) to avoid creating a fresh
* RegExp object on every call to `validateTranslation`. Frozen so the
* collection cannot be mutated by callers.
*
* @type {readonly RegExp[]}
*/
const FIXED_TOKEN_PATTERNS_GLOBAL = Object.freeze(
FIXED_TOKEN_PATTERNS.map((re) => new RegExp(re.source, 'g')),
);
/**
* Tolerance (in absolute count) for H2/H3 heading-count drift between the
* source and the translation. H1 must match exactly: there is only one H1
* per brief by convention.
*
* Why a small non-zero floor? Translators sometimes legitimately fuse two
* very short sub-bullets into one paragraph, or split a long H3 into two
* for readability in CJK scripts where dense text harms scanability. A
* tolerance of 1 absorbs that without letting whole sections disappear.
*/
export const HEADING_TOLERANCE = 1;
/**
* Pattern that matches a fenced ```mermaid block opener (case-insensitive).
* We match only the opening fence — counting openers is enough because
* Mermaid blocks are always closed by a `` ``` `` line, and an unclosed
* block in source would already break Markdown rendering elsewhere.
*/
const MERMAID_OPENER = /^```mermaid\s*$/gim;
/** Count occurrences of a global regex in a string. */
function countGlobal(text, regex) {
// Clone to avoid lastIndex state bleeding across calls.
const re = new RegExp(regex.source, regex.flags);
let count = 0;
while (re.exec(text) !== null) count += 1;
return count;
}
/**
* Count Markdown heading lines at a given ATX level. Only matches the
* canonical leading-`#` form — setext (`===` / `---`) underlines are
* outside the executive-brief style guide.
*
* @param {string} text
* @param {1|2|3} level
*/
export function countHeadings(text, level) {
const re = new RegExp(`^#{${level}}\\s+\\S`, 'gm');
return countGlobal(text, re);
}
/** Count fenced \`\`\`mermaid blocks in the given text. */
export function countMermaidBlocks(text) {
return countGlobal(text, MERMAID_OPENER);
}
/** Count exact token occurrences returned by one fixed-token pattern. */
function countMatches(text, regex) {
const counts = new Map();
const matches = text.match(regex) || [];
for (const token of matches) {
counts.set(token, (counts.get(token) || 0) + 1);
}
return counts;
}
/**
* Aggregate a violation list into a `{ key: count }` map for the validator
* report. Items with falsy values at `key` are skipped so the filename-gate
* violation (which has `lang: ''`) doesn't pollute the byLang summary.
* Keys in the returned object are sorted alphabetically so the emitted JSON
* is byte-stable across runs.
*
* @param {Array<Object>} items
* @param {string} key
* @returns {Object<string, number>}
*/
export function aggregateByKey(items, key) {
const counts = new Map();
for (const item of items) {
const value = item[key];
if (!value) continue;
counts.set(value, (counts.get(value) || 0) + 1);
}
const sorted = {};
for (const k of [...counts.keys()].sort()) {
sorted[k] = counts.get(k);
}
return sorted;
}
/**
* @typedef {Object} Violation
* @property {string} translationPath
* @property {string} sourcePath
* @property {string} lang
* @property {string} gate
* @property {string} message
*/
/** Parse CLI argv. Exported for unit tests. */
export function parseArgs(argv) {
const opts = {
repoRoot: process.cwd(),
paths: [],
report: null,
fail: true,
quiet: false,
};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
switch (arg) {
case '--repo-root':
opts.repoRoot = argv[i + 1];
i += 1;
break;
case '--paths':
while (i + 1 < argv.length && !argv[i + 1].startsWith('--')) {
opts.paths.push(argv[i + 1]);
i += 1;
}
break;
case '--report':
opts.report = argv[i + 1];
i += 1;
break;
case '--no-fail':
opts.fail = false;
break;
case '--quiet':
opts.quiet = true;
break;
case '--help':
case '-h':
process.stdout.write(
'Usage: validate-brief-translations.js [--repo-root <path>] ' +
'[--paths <file>...] [--report <path>] [--no-fail] [--quiet]\n'
);
process.exit(0);
break;
default:
if (arg.startsWith('--')) {
throw new Error(`Unknown flag: ${arg}`);
}
}
}
return opts;
}
/** Recursively find every `executive-brief_*.md` under `analysis/daily/`. */
export function findAllTranslations(repoRoot) {
const dailyDir = path.join(repoRoot, 'analysis', 'daily');
if (!fs.existsSync(dailyDir)) return [];
const out = [];
const stack = [dailyDir];
while (stack.length > 0) {
const dir = stack.pop();
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
continue;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
stack.push(full);
} else if (entry.isFile() && /^executive-brief_[a-z]{2}\.md$/.test(entry.name)) {
out.push(full);
}
}
}
return out;
}
/** Validate one translation file. Returns an array of Violation entries. */
export function validateTranslation(translationPath, repoRoot) {
const violations = [];
const rel = path.relative(repoRoot, translationPath);
const base = path.basename(translationPath);
const match = base.match(/^executive-brief_([a-z]{2})\.md$/);
if (!match) {
violations.push({
translationPath: rel,
sourcePath: '',
lang: '',
gate: 'filename',
message: `Filename must match executive-brief_<lang>.md`,
});
return violations;
}
const lang = match[1];
const sourcePath = path.join(path.dirname(translationPath), 'executive-brief.md');
const sourceRel = path.relative(repoRoot, sourcePath);
if (!TARGET_LANGS.includes(lang)) {
violations.push({
translationPath: rel,
sourcePath: sourceRel,
lang,
gate: 'language-code',
message: `Language code "${lang}" is not one of the 13 supported target languages: ${TARGET_LANGS.join(', ')}`,
});
}
if (!fs.existsSync(sourcePath)) {
violations.push({
translationPath: rel,
sourcePath: sourceRel,
lang,
gate: 'source-presence',
message: `Source executive-brief.md missing — orphaned translation`,
});
return violations;
}
const sourceBytes = fs.statSync(sourcePath).size;
const targetBytes = fs.statSync(translationPath).size;
if (sourceBytes > 0 && targetBytes < sourceBytes * LENGTH_FLOOR_RATIO) {
violations.push({
translationPath: rel,
sourcePath: sourceRel,
lang,
gate: 'length-floor',
message:
`Translation byte size ${targetBytes} is below ` +
`${Math.round(LENGTH_FLOOR_RATIO * 100)}% of source ${sourceBytes} — likely a stub`,
});
}
const targetText = fs.readFileSync(translationPath, 'utf8');
let englishHits = 0;
for (const re of EN_PATTERNS) {
if (re.test(targetText)) englishHits += 1;
}
if (englishHits > MAX_ENGLISH_PATTERNS) {
violations.push({
translationPath: rel,
sourcePath: sourceRel,
lang,
gate: 'english-fallthrough',
message:
`Translation contains ${englishHits} English-only sentence patterns ` +
`(max ${MAX_ENGLISH_PATTERNS}); content was likely copied from the English source`,
});
}
const sourceText = fs.readFileSync(sourcePath, 'utf8');
for (let i = 0; i < FIXED_TOKEN_PATTERNS_GLOBAL.length; i++) {
const reGlobal = FIXED_TOKEN_PATTERNS_GLOBAL[i];
const reSingle = FIXED_TOKEN_PATTERNS[i];
const sourceCounts = countMatches(sourceText, reGlobal);
if (sourceCounts.size === 0) continue;
const targetCounts = countMatches(targetText, reGlobal);
const missingTokens = [];
for (const [token, sourceCount] of sourceCounts.entries()) {
const targetCount = targetCounts.get(token) || 0;
if (targetCount < sourceCount) {
missingTokens.push(`${token} (${targetCount}/${sourceCount})`);
}
}
if (missingTokens.length > 0) {
violations.push({
translationPath: rel,
sourcePath: sourceRel,
lang,
gate: 'fixed-token-preservation',
message:
`Translation is missing exact ${reSingle} token(s): ${missingTokens.join(', ')} ` +
`— proper noun / data-vintage identifiers MUST be preserved verbatim`,
});
}
}
// Gate 6 — heading parity. H1 must match exactly (briefs have exactly one
// by style guide); H2/H3 may drift by HEADING_TOLERANCE in absolute count.
for (const level of [1, 2, 3]) {
const sourceCount = countHeadings(sourceText, level);
if (sourceCount === 0) continue;
const targetCount = countHeadings(targetText, level);
const tolerance = level === 1 ? 0 : HEADING_TOLERANCE;
if (Math.abs(sourceCount - targetCount) > tolerance) {
violations.push({
translationPath: rel,
sourcePath: sourceRel,
lang,
gate: 'heading-parity',
message:
`Translation has ${targetCount} H${level} heading(s); source has ${sourceCount} ` +
`(tolerance ±${tolerance}). Whole subsections appear to be missing or merged.`,
});
}
}
// Gate 7 — Mermaid block parity. Every ```mermaid opener in the source
// must appear at least once in the translation. Diagrams are fixed
// machine-readable assets and must round-trip verbatim.
const sourceMermaid = countMermaidBlocks(sourceText);
if (sourceMermaid > 0) {
const targetMermaid = countMermaidBlocks(targetText);
Eif (targetMermaid < sourceMermaid) {
violations.push({
translationPath: rel,
sourcePath: sourceRel,
lang,
gate: 'mermaid-parity',
message:
`Translation contains ${targetMermaid} \`\`\`mermaid block(s); source has ${sourceMermaid}. ` +
`Mermaid diagram syntax MUST be preserved verbatim — the downstream renderer parses these blocks.`,
});
}
}
return violations;
}
/** Run validation against a list of translation paths. */
export function runValidation(translationPaths, repoRoot, { quiet = false } = {}) {
const allViolations = [];
for (const p of translationPaths) {
const v = validateTranslation(p, repoRoot);
if (v.length > 0) {
allViolations.push(...v);
Iif (!quiet) {
for (const entry of v) {
process.stderr.write(
`❌ ${entry.translationPath} [${entry.gate}] ${entry.message}\n`
);
}
}
} else Iif (!quiet) {
process.stdout.write(`✅ ${path.relative(repoRoot, p)}\n`);
}
}
return allViolations;
}
/** Main entry point. */
export function main(argv) {
const opts = parseArgs(argv);
const paths = opts.paths.length > 0
? opts.paths.map((p) => path.resolve(opts.repoRoot, p))
: findAllTranslations(opts.repoRoot);
const violations = runValidation(paths, opts.repoRoot, { quiet: opts.quiet });
const report = {
generatedAt: new Date().toISOString(),
totals: {
filesChecked: paths.length,
violations: violations.length,
byGate: aggregateByKey(violations, 'gate'),
byLang: aggregateByKey(violations, 'lang'),
},
violations,
};
const json = `${JSON.stringify(report, null, 2)}\n`;
if (opts.report) {
fs.mkdirSync(path.dirname(opts.report), { recursive: true });
fs.writeFileSync(opts.report, json);
} else Eif (!opts.quiet) {
process.stdout.write(json);
}
Iif (violations.length > 0 && opts.fail) {
process.exit(1);
}
return report;
}
/* c8 ignore start */
if (import.meta.url === `file://${process.argv[1]}`) {
try {
main(process.argv.slice(2));
} catch (err) {
process.stderr.write(`validate-brief-translations: ${err.message}\n`);
process.exit(1);
}
}
/* c8 ignore stop */
|