All files / src/aggregator article-meta.ts

88.88% Statements 96/108
65.3% Branches 32/49
94.44% Functions 17/18
94.38% Lines 84/89

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                                                                                                                                                                                        5x       5x     5x                                       46x 46x 46x 63x 66x 63x   46x                         3x 3x 3x 3x   3x 6x 3x 3x 3x 3x 3x 3x 3x   3x     3x 6x 6x       6x 6x 6x 3x 3x                       3x 3x 3x   3x     3x 3x     18x             3x                               23x         23x 63x 63x 3x 3x 3x   20x                         23x           23x   23x 23x                         23x         23x 33x 33x 18x 18x 18x   5x                       23x 23x 3x 3x 3x                     23x           23x 57x 23x 23x 18x                     22x 22x 22x 22x 22x 22x 22x 22x 22x 22x                                                   22x                                 330x                             21x                
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Aggregator/ArticleMeta
 * @description Deterministic emitter for `article-meta.json` — a small
 * structured sidecar written next to `article.md` in every analysis run
 * directory. Consumers (HTML SEO/structured data, news indexes, RSS) read
 * this file instead of re-parsing the article body.
 *
 * The file is a pure function of the run inputs:
 *   - `manifest.json`     → article type, date, run id, gate result
 *   - `executive-brief.md`/`synthesis-summary.md` → top finding (lead)
 *   - `intelligence/synthesis-summary.md`         → key takeaways (3–7 bullets)
 *   - `risk-scoring/risk-matrix.md` (if present)  → top risks
 *   - `intelligence/parliamentary-calendar-projection.md` /
 *     `extended/forward-indicators.md`            → key dates / what to watch
 *   - `intelligence/economic-context.md`          → IMF / WorldBank macro hook
 *
 * Same artifact bytes in → same `article-meta.json` bytes out (verified by
 * the determinism test).
 */
 
import fs from 'fs';
import path from 'path';
import {
  extractExecutiveLead,
  extractLeadParagraph,
  trimToLeadSentence,
} from './lead-extractor.js';
import {
  buildKeyTakeaways as _buildKeyTakeaways,
  jaccardSimilarity,
  extractStrongBullets,
  harvestCandidates,
  MAX_TAKEAWAYS,
  MIN_TAKEAWAYS,
} from './key-takeaways.js';
 
/** Shape of `article-meta.json`. */
export interface ArticleMeta {
  /** ISO date of the run (`YYYY-MM-DD`). */
  readonly date: string;
  /** Article type slug (e.g. `breaking`). */
  readonly articleType: string;
  /** Stable run identifier from the manifest. */
  readonly runId: string;
  /** Latest non-PENDING gate result. */
  readonly gateResult: string;
  /** Article slug used by the news pages (`<date>-<type>[-<suffix>]`). */
  readonly slug: string;
  /** Run-relative path of the canonical `article.md`. */
  readonly articlePath: string;
  /** One-sentence executive lead — the strongest finding, distilled. */
  readonly topFinding: string;
  /** 3–7 deterministic key takeaways harvested from synthesis-summary. */
  readonly keyTakeaways: readonly string[];
  /** Top political risks (artifact-driven, may be empty). */
  readonly topRisks: readonly string[];
  /** Key dated triggers / "what to watch" items. */
  readonly keyDates: readonly string[];
  /** Key actors / political groups identified by the artifacts. */
  readonly keyActors: readonly string[];
  /** Optional IMF / WorldBank macro hook surfaced as a sidebar callout. */
  readonly macroContext: string;
  /**
   * Run-relative paths of every artifact whose content fed into this meta
   * record — emitted so the HTML SEO layer can build `isBasedOn` arrays
   * without re-walking the run directory.
   */
  readonly sources: readonly string[];
}
 
/** Options for {@link buildArticleMeta}. */
export interface BuildArticleMetaOptions {
  /** Absolute path to the analysis run directory. */
  readonly runDir: string;
  /** Absolute path to the repository root (used for repo-relative paths). */
  readonly repoRoot: string;
  /** ISO date of the run (`YYYY-MM-DD`). */
  readonly date: string;
  /** Article type slug. */
  readonly articleType: string;
  /** Stable run identifier from the manifest. */
  readonly runId: string;
  /** Latest non-PENDING gate result. */
  readonly gateResult: string;
  /** Article slug used by the news pages. */
  readonly slug: string;
}
 
/** Hard cap on how many entries each list field carries. */
const MAX_LIST_ENTRIES = 8;
 
/** Regex matching a YYYY-MM-DD date, month-year, or Qn YYYY pattern. */
const DATE_TRIGGER_RE =
  /\b(\d{4}-\d{2}-\d{2}|Q[1-4]\s+\d{4}|(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+\d{4})\b/i;
 
/** Headings in economic-context artifacts that contain macro prose. */
const MACRO_PREFERRED_HEADINGS = [
  'judgement',
  'judgment',
  'imf weo',
  'imf baseline',
  'salient economic',
  'macro',
  'eurozone macro',
];
 
/**
 * De-duplicate candidates using Jaccard similarity, capped at `maxItems`.
 * Unlike `dedupeTakeaways` from key-takeaways.ts, this helper does
 * not impose the `MAX_TAKEAWAYS` ceiling — callers provide their own cap.
 *
 * @param candidates - Ordered list of bullet body strings
 * @param maxItems - Maximum number of de-duplicated items to return
 * @returns De-duplicated list capped at `maxItems`
 */
function dedupeItems(candidates: readonly string[], maxItems: number): string[] {
  const THRESHOLD = 0.7;
  const out: string[] = [];
  for (const candidate of candidates) {
    Iif (out.length >= maxItems) break;
    const isDuplicate = out.some((existing) => jaccardSimilarity(existing, candidate) >= THRESHOLD);
    Eif (!isDuplicate) out.push(candidate);
  }
  return out;
}
 
/**
 * Extract a macro-context lead from an economic-context artifact, targeting
 * IMF / Judgement headings. Falls back to the first prose paragraph after
 * skipping metadata-style preamble lines.
 *
 * @param markdown - Raw artifact Markdown
 * @returns Trimmed lead sentence, or `''`
 */
function extractMacroLeadParagraph(markdown: string): string {
  // Try to find a macro-specific preferred section first.
  const lines = markdown.split(/\r?\n/);
  let heading = '';
  let buffer: string[] = [];
  let inFence = false;
 
  const tryExtract = (buf: string[]): string => {
    for (const rawLine of buf) {
      const trimmed = (rawLine ?? '').trim();
      Iif (trimmed === '' || /^[-*+]\s+/.test(trimmed) || /^\d+\.\s+/.test(trimmed)) continue;
      Iif (/^(>|<|!?\[)/.test(trimmed)) continue;
      Iif (/^\*\*\s*[A-Za-z][^*]+:\*\*/.test(trimmed)) continue;
      Iif (/^\|/.test(trimmed)) continue; // skip table rows
      Iif (/^-{2,}$/.test(trimmed)) continue; // skip horizontal rules
      return trimmed;
    }
    return '';
  };
 
  for (const rawLine of lines) {
    const line = rawLine ?? '';
    Iif (/^```/.test(line)) {
      inFence = !inFence;
      continue;
    }
    Iif (inFence) continue;
    const headingMatch = /^(#{1,6})\s+(.*)$/.exec(line);
    if (headingMatch) {
      const prev = tryExtract(buffer);
      Iif (
        prev &&
        MACRO_PREFERRED_HEADINGS.some((h) =>
          heading
            .toLowerCase()
            .replace(/[^\p{L}\p{N}\s]+/gu, ' ')
            .trim()
            .includes(h)
        )
      ) {
        return prev;
      }
      heading = (headingMatch[2] ?? '').trim();
      buffer = [];
      continue;
    }
    buffer.push(line);
  }
  // Flush last section.
  const lastPrev = tryExtract(buffer);
  Eif (
    lastPrev &&
    MACRO_PREFERRED_HEADINGS.some((h) =>
      heading
        .toLowerCase()
        .replace(/[^\p{L}\p{N}\s]+/gu, ' ')
        .trim()
        .includes(h)
    )
  ) {
    return lastPrev;
  }
  // Final fallback: use the generic extractor result (lazy, avoids double parse in the common path).
  return extractLeadParagraph(markdown);
}
 
/**
 * Mine top political risks from `risk-scoring/risk-matrix.md` (or its
 * historic variants under the same directory). Falls back to the first
 * bullets in `risk-scoring/quantitative-swot.md` when the matrix is
 * absent. Returns at most {@link MAX_LIST_ENTRIES} bullets.
 *
 * @param runDir - Absolute path to the analysis run directory
 * @returns Ordered list of risk bullet bodies
 */
export function extractTopRisks(runDir: string): string[] {
  const sources = [
    'risk-scoring/risk-matrix.md',
    'risk-scoring/political-risk.md',
    'risk-scoring/quantitative-swot.md',
  ];
  for (const rel of sources) {
    const abs = path.join(runDir, rel);
    if (!fs.existsSync(abs)) continue;
    const markdown = fs.readFileSync(abs, 'utf8');
    const bullets = extractStrongBullets(markdown).slice(0, MAX_LIST_ENTRIES);
    Eif (bullets.length > 0) return bullets;
  }
  return [];
}
 
/**
 * Mine forward-looking dated items from
 * `intelligence/parliamentary-calendar-projection.md` and
 * `extended/forward-indicators.md`. Returns at most
 * {@link MAX_LIST_ENTRIES} bullets, de-duplicated across the two sources.
 *
 * @param runDir - Absolute path to the analysis run directory
 * @returns Ordered list of dated trigger bullet bodies
 */
export function extractKeyDates(runDir: string): string[] {
  const sources = [
    'intelligence/parliamentary-calendar-projection.md',
    'extended/forward-indicators.md',
    'intelligence/legislative-pipeline-forecast.md',
    'intelligence/scenario-forecast.md',
  ];
  const candidates = harvestCandidates(runDir, sources);
  // Filter for bullets that contain an explicit date trigger, then dedupe.
  const dated = candidates.filter((t) => DATE_TRIGGER_RE.test(t.body)).map((t) => t.body);
  return dedupeItems(dated, MAX_LIST_ENTRIES);
}
 
/**
 * Mine key actors / political groups from
 * `classification/actor-mapping.md` and `intelligence/stakeholder-map.md`.
 * Falls through to coalition-dynamics when the canonical actor map is
 * missing. Returns at most {@link MAX_LIST_ENTRIES} bullets.
 *
 * @param runDir - Absolute path to the analysis run directory
 * @returns Ordered list of actor bullet bodies
 */
export function extractKeyActors(runDir: string): string[] {
  const sources = [
    'classification/actor-mapping.md',
    'intelligence/stakeholder-map.md',
    'intelligence/coalition-dynamics.md',
  ];
  for (const rel of sources) {
    const abs = path.join(runDir, rel);
    if (!fs.existsSync(abs)) continue;
    const markdown = fs.readFileSync(abs, 'utf8');
    const bullets = extractStrongBullets(markdown).slice(0, MAX_LIST_ENTRIES);
    Eif (bullets.length > 0) return bullets;
  }
  return [];
}
 
/**
 * Resolve a one-line IMF / WorldBank macro context callout from
 * `intelligence/economic-context.md`. Returns the trimmed lead sentence
 * of the artifact, or `''` when the artifact is missing.
 *
 * @param runDir - Absolute path to the analysis run directory
 * @returns IMF-backed macro hook, or `''`
 */
export function extractMacroContext(runDir: string): string {
  const abs = path.join(runDir, 'intelligence/economic-context.md');
  if (!fs.existsSync(abs)) return '';
  const markdown = fs.readFileSync(abs, 'utf8');
  const paragraph = extractMacroLeadParagraph(markdown);
  return trimToLeadSentence(paragraph);
}
 
/**
 * Resolve the deterministic 3–7 key-takeaway bullets used in both the
 * Markdown article body and `article-meta.json`.
 *
 * @param runDir - Absolute path to the analysis run directory
 * @returns Ordered list of takeaway bodies (3–7 entries)
 */
export function extractKeyTakeaways(runDir: string): string[] {
  const sources: readonly string[] = [
    'intelligence/synthesis-summary.md',
    'intelligence/intelligence-assessment.md',
    'extended/executive-brief.md',
    'executive-brief.md',
  ];
  const candidates = harvestCandidates(runDir, sources);
  const bodies = candidates.map((t) => t.body);
  const selected = dedupeItems(bodies, MAX_TAKEAWAYS);
  if (selected.length < MIN_TAKEAWAYS) return [];
  return selected;
}
 
/**
 * Build the deterministic `ArticleMeta` record for one run. Pure function
 * of the on-disk artifacts plus the resolved manifest fields.
 *
 * @param options - Run-level metadata + absolute run directory
 * @returns Frozen, JSON-serialisable {@link ArticleMeta}
 */
export function buildArticleMeta(options: BuildArticleMetaOptions): ArticleMeta {
  const { runDir, repoRoot, date, articleType, runId, gateResult, slug } = options;
  const topFinding = extractExecutiveLead(runDir);
  const keyTakeaways = extractKeyTakeaways(runDir);
  const topRisks = extractTopRisks(runDir);
  const keyDates = extractKeyDates(runDir);
  const keyActors = extractKeyActors(runDir);
  const macroContext = extractMacroContext(runDir);
  const sources = computeSources(runDir);
  const runDirRelPath = path.relative(repoRoot, runDir).split(path.sep).join('/');
  return {
    date,
    articleType,
    runId,
    gateResult,
    slug,
    articlePath: `${runDirRelPath}/article.md`,
    topFinding,
    keyTakeaways,
    topRisks,
    keyDates,
    keyActors,
    macroContext,
    sources,
  };
}
 
/**
 * Compute the run-relative paths of every artifact that fed into the meta
 * record, in deterministic alphabetical order. Used as `isBasedOn` data
 * by the HTML SEO layer.
 *
 * @param runDir - Absolute path to the analysis run directory
 * @returns Sorted list of run-relative paths that exist on disk
 */
function computeSources(runDir: string): string[] {
  const candidates = [
    'executive-brief.md',
    'extended/executive-brief.md',
    'intelligence/synthesis-summary.md',
    'intelligence/intelligence-assessment.md',
    'intelligence/economic-context.md',
    'intelligence/parliamentary-calendar-projection.md',
    'intelligence/legislative-pipeline-forecast.md',
    'intelligence/scenario-forecast.md',
    'extended/forward-indicators.md',
    'risk-scoring/risk-matrix.md',
    'risk-scoring/political-risk.md',
    'risk-scoring/quantitative-swot.md',
    'classification/actor-mapping.md',
    'intelligence/stakeholder-map.md',
    'intelligence/coalition-dynamics.md',
  ];
  return candidates.filter((rel) => fs.existsSync(path.join(runDir, rel))).sort();
}
 
/**
 * Serialise an {@link ArticleMeta} as a stable JSON string with a trailing
 * newline. Keys are emitted in declaration order (insertion-order, matching
 * the interface layout). Determinism guarantee: same input → same bytes.
 *
 * @param meta - Article meta record
 * @returns JSON string ready to be written next to `article.md`
 */
export function serializeArticleMeta(meta: ArticleMeta): string {
  // JSON.stringify emits keys in insertion order — the {@link ArticleMeta}
  // shape declares its keys in canonical reading order, so the output is
  // already deterministic. We add a trailing newline for POSIX hygiene.
  return `${JSON.stringify(meta, null, 2)}\n`;
}
 
/**
 * Convenience wrapper that re-exports {@link _buildKeyTakeaways} so the
 * aggregator can import the rendered Markdown block from a single module.
 */
export { _buildKeyTakeaways as buildKeyTakeawaysMarkdown };