All files / src/aggregator analysis-aggregator.ts

92.77% Statements 154/166
75% Branches 66/88
95.83% Functions 23/24
96.66% Lines 145/150

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 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641                                                                                                                                                                                                                                            30x 30x   1x 1x                       16x 11x 11x 30x   11x                         16x 16x 12x 12x 12x   6x                                       223x 223x 483x 40x 40x 96x   40x 2x 2x   443x 32x 32x     223x                       14x 14x 28x 28x 20x 20x 700x 690x       14x                       13x 13x 13x 44x 44x 75x 75x 75x 31x 31x 44x 31x       13x 13x                   679x     1575x                                                   14x 14x 14x                                               626x 626x 15x           15x 10x 10x 10x 155x 155x   10x   15x 11x 11x 11x 471x 471x   11x   15x                             13x 31x 31x   13x                                                                           31x 31x 31x 31x 31x       31x 31x 31x             31x         31x                               31x 31x 31x 31x 31x                                                     2x                   31x                           221x 31x 31x 31x 31x 31x 31x               31x 31x 31x 31x   31x 31x   31x                             14x 14x 1x   13x 13x 13x 13x   13x 13x     13x 13x   13x 13x 13x 13x 13x 13x   13x 221x 221x                           31x 13x                             13x 14x 14x 14x 14x 14x   14x 14x               14x 14x       14x 14x   14x                             14x                                              
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module Aggregator/AnalysisAggregator
 * @description Read an analysis run directory, consult its `manifest.json`,
 * and produce one canonical Markdown document that concatenates every
 * artifact in the order declared by {@link ARTIFACT_SECTIONS}. The
 * document is prefixed with a provenance block and suffixed with a
 * tradecraft-references appendix plus an analysis-index appendix so a
 * reader can trace every claim back to its source file on GitHub.
 */
 
import fs from 'fs';
import path from 'path';
import {
  ARTIFACT_SECTIONS,
  MANIFEST_SECTION_ID,
  MANIFEST_SECTION_TITLE,
  SUPPLEMENTARY_SECTION_ID,
  SUPPLEMENTARY_SECTION_TITLE,
  TRADECRAFT_SECTION_ID,
  TRADECRAFT_SECTION_TITLE,
  type ArtifactSection,
} from './artifact-order.js';
import { cleanArtifact, githubBlobUrl } from './clean-artifact.js';
 
/** Raw manifest shape as committed by the analysis pipeline. */
export interface AnalysisManifest {
  readonly articleType: string;
  readonly runId?: string;
  readonly date?: string;
  readonly analysisDir?: string;
  readonly files?: ManifestFiles;
  readonly history?: readonly ManifestHistoryEntry[];
}
 
/** `manifest.files` can be nested category → paths or flat path → description. */
export type ManifestFiles = Record<string, readonly string[] | Record<string, string>>;
 
/** One entry in `manifest.history[]`; only fields we read are typed. */
export interface ManifestHistoryEntry {
  readonly stage?: string;
  readonly completedAt?: string;
  readonly startedAt?: string;
  readonly finishedAt?: string;
  readonly runId?: string;
  readonly gateResult?: string;
  readonly summary?: string;
  readonly filesWritten?: readonly string[];
}
 
/** Result of {@link aggregateAnalysisRun}. */
export interface AggregatedRun {
  /** Final Markdown document (provenance + sections + appendices). */
  readonly markdown: string;
  /** Repo-relative path of the run dir (e.g. `analysis/daily/2026-01-15/breaking-run1`). */
  readonly runDirRelPath: string;
  /** Article type slug from the manifest. */
  readonly articleType: string;
  /** ISO date string of the run (YYYY-MM-DD). */
  readonly date: string;
  /** List of every artifact included, in the order they appear. */
  readonly includedArtifacts: readonly IncludedArtifact[];
  /** Latest resolved gate result read from `manifest.history[]`. */
  readonly gateResult: string;
  /**
   * Ordered list of top-level (H2) sections that were actually emitted into
   * the aggregate — used by the HTML renderer to build the article
   * table-of-contents sidebar. Includes canonical sections, the
   * supplementary-intelligence bucket, the tradecraft-references appendix,
   * and the analysis-index appendix, in document order.
   */
  readonly sectionToc: readonly TocSection[];
}
 
/** One entry in the article-level table of contents (H2 level). */
export interface TocSection {
  /** Fragment identifier — matches the `id="…"` on the rendered H2. */
  readonly id: string;
  /** Display title shown in the sidebar nav. */
  readonly title: string;
}
 
/** Metadata for one artifact included in the aggregate. */
export interface IncludedArtifact {
  /** Path relative to the run dir. */
  readonly runRelPath: string;
  /** Path relative to the repo root. */
  readonly repoRelPath: string;
  /** Id of the section this artifact belongs to. */
  readonly sectionId: string;
}
 
/** Options for {@link aggregateAnalysisRun}. */
export interface AggregateOptions {
  /** Absolute path to the analysis run directory. */
  readonly runDir: string;
  /** Absolute path to the repo root (used to build repo-relative paths). */
  readonly repoRoot: string;
  /**
   * Optional: all methodology files and template files that should be
   * listed in the tradecraft appendix. If omitted, the aggregator
   * discovers them under `analysis/methodologies/*.md` +
   * `analysis/templates/*.md`.
   */
  readonly tradecraftFiles?: readonly string[];
}
 
/**
 * Extract every string entry from a single `files` value (which may be an
 * array of strings or a `path → description` object). Split out so
 * {@link flattenManifestFiles} stays under the cognitive-complexity budget.
 *
 * @param value - One value from `Object.values(files)`
 * @returns Strings contained within, or `[]` when the shape is unknown
 */
function extractFileEntries(value: unknown): string[] {
  if (Array.isArray(value)) {
    return value.filter((e): e is string => typeof e === 'string');
  }
  Eif (value && typeof value === 'object') {
    return Object.keys(value as Record<string, unknown>);
  }
  return [];
}
 
/**
 * Normalise `manifest.files` into a flat list of `runRelPath` strings.
 *
 * @param files - Manifest `files` section (nested or flat)
 * @returns De-duplicated list of run-relative artifact paths
 */
export function flattenManifestFiles(files: ManifestFiles | undefined): string[] {
  if (!files) return [];
  const out: string[] = [];
  for (const value of Object.values(files)) {
    out.push(...extractFileEntries(value));
  }
  return out;
}
 
/**
 * Pick the latest non-PENDING gateResult from `manifest.history[]`, falling
 * back to `PENDING` if none is recorded. Mirrors the behaviour of
 * {@link readLatestResolvedGateResult} in `src/utils/file-utils.ts` but
 * operates on an in-memory manifest.
 *
 * @param manifest - Parsed manifest object
 * @returns The latest non-PENDING gate result, or `"PENDING"` when none found
 */
export function latestGateResult(manifest: AnalysisManifest): string {
  const history = manifest.history ?? [];
  for (let i = history.length - 1; i >= 0; i--) {
    const entry = history[i];
    const gr = entry?.gateResult;
    if (gr && gr !== 'PENDING') return gr;
  }
  return 'PENDING';
}
 
/**
 * Expand an `artifacts` entry from {@link ArtifactSection} into a list of
 * concrete artifact paths. Exact paths are kept as-is; directory prefixes
 * ending in `/` expand to every remaining `.md` under that directory
 * (lexical order), excluding files already claimed by higher-priority
 * sections.
 *
 * @param section - Canonical section descriptor from {@link ARTIFACT_SECTIONS}
 * @param available - Set of every known artifact path (run-relative)
 * @param consumed - Mutable set of paths already claimed by earlier sections
 * @returns Ordered list of artifact paths that belong to this section
 */
export function expandSectionArtifacts(
  section: ArtifactSection,
  available: Set<string>,
  consumed: Set<string>
): string[] {
  const out: string[] = [];
  for (const entry of section.artifacts) {
    if (entry.endsWith('/')) {
      const prefix = entry;
      const matching = [...available]
        .filter((p) => p.startsWith(prefix) && !consumed.has(p))
        .sort();
      for (const p of matching) {
        out.push(p);
        consumed.add(p);
      }
    } else if (available.has(entry) && !consumed.has(entry)) {
      out.push(entry);
      consumed.add(entry);
    }
  }
  return out;
}
 
/**
 * Discover tradecraft files (methodologies + templates) under a repo root.
 * Returned paths are repo-relative with POSIX separators and sorted
 * lexically.
 *
 * @param repoRoot - Absolute path of the repo root
 * @returns Sorted list of `analysis/methodologies/*.md` + `analysis/templates/*.md`
 */
export function discoverTradecraftFiles(repoRoot: string): string[] {
  const result: string[] = [];
  for (const sub of ['analysis/methodologies', 'analysis/templates']) {
    const dir = path.join(repoRoot, sub);
    if (!fs.existsSync(dir)) continue;
    const entries = fs.readdirSync(dir, { withFileTypes: true });
    for (const entry of entries) {
      if (entry.isFile() && entry.name.endsWith('.md')) {
        result.push(`${sub}/${entry.name}`);
      }
    }
  }
  return result.sort();
}
 
/**
 * Walk the run directory and return every `.md` file as a run-relative
 * POSIX path, excluding files under `data/` (raw MCP payloads, not meant
 * to be rendered).
 *
 * @param runDir - Absolute path to the analysis run directory
 * @returns Sorted list of run-relative `.md` paths
 */
function collectRunArtifacts(runDir: string): string[] {
  const result: string[] = [];
  Iif (!fs.existsSync(runDir)) return result;
  const walk = (dir: string, prefix: string): void => {
    const entries = fs.readdirSync(dir, { withFileTypes: true });
    for (const entry of entries) {
      const full = path.join(dir, entry.name);
      const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
      if (entry.isDirectory()) {
        Iif (entry.name === 'data' || entry.name === 'runs') continue;
        walk(full, rel);
      } else if (entry.isFile() && entry.name.endsWith('.md')) {
        result.push(rel);
      }
    }
  };
  walk(runDir, '');
  return result.sort();
}
 
/**
 * Human-friendly title derived from a file stem (kebab/snake → Title Case).
 *
 * @param stem - File stem (e.g. `synthesis-summary.md`)
 * @returns Humanised title (e.g. `Synthesis Summary`)
 */
function humanize(stem: string): string {
  return stem
    .replace(/[-_]+/g, ' ')
    .replace(/\.md$/i, '')
    .replace(/\b([a-z])/g, (_, c: string) => c.toUpperCase())
    .trim();
}
 
/**
 * Render the provenance block shown at the very top of the aggregated
 * document. Shows run metadata, gate result, and a direct link to the
 * manifest on GitHub so the reader can audit the full artifact set.
 *
 * @param params - Provenance metadata for the aggregated run
 * @param params.articleType - Article type slug (e.g. `breaking`)
 * @param params.date - ISO date of the run (`YYYY-MM-DD`)
 * @param params.runId - Stable identifier for the run
 * @param params.gateResult - Latest non-PENDING gate result
 * @param params.runDirRelPath - Repo-relative path of the run directory
 * @param params.manifestRelPath - Repo-relative path of `manifest.json`
 * @returns Markdown blockquote ready to be concatenated into the aggregate
 */
export function renderProvenanceBlock(params: {
  articleType: string;
  date: string;
  runId: string;
  gateResult: string;
  runDirRelPath: string;
  manifestRelPath: string;
}): string {
  const manifestUrl = githubBlobUrl(params.manifestRelPath);
  const treeUrl = `https://github.com/Hack23/euparliamentmonitor/tree/main/${params.runDirRelPath}`;
  return [
    '<!-- Aggregated analysis — do not edit; regenerate via `npm run generate-article`. -->',
    '',
    '> **Provenance**',
    '>',
    `> - **Article type:** \`${params.articleType}\``,
    `> - **Run date:** ${params.date}`,
    `> - **Run id:** \`${params.runId}\``,
    `> - **Gate result:** \`${params.gateResult}\``,
    `> - **Analysis tree:** [${params.runDirRelPath}](${treeUrl})`,
    `> - **Manifest:** [manifest.json](${manifestUrl})`,
    '',
  ].join('\n');
}
 
/**
 * Render the tradecraft-references appendix — one bullet per
 * methodology/template file with a GitHub blob link.
 *
 * @param files - Repo-relative paths under `analysis/methodologies/` and
 *                `analysis/templates/`
 * @returns Markdown block with two subsections (methodologies, templates)
 */
export function renderTradecraftAppendix(files: readonly string[]): string {
  const methods = files.filter((f) => f.startsWith('analysis/methodologies/'));
  const templates = files.filter((f) => f.startsWith('analysis/templates/'));
  const block: string[] = [
    `<h2 id="${TRADECRAFT_SECTION_ID}">${TRADECRAFT_SECTION_TITLE}</h2>`,
    '',
    'This article is produced under the [Hack23 AB](https://hack23.com) intelligence tradecraft library. Every methodology and artifact template applied to this run is linked below.',
    '',
  ];
  if (methods.length > 0) {
    block.push('### Methodologies');
    block.push('');
    for (const rel of methods) {
      const stem = rel.split('/').pop()?.replace(/\.md$/i, '') ?? rel;
      block.push(`- [${humanize(stem)}](${githubBlobUrl(rel)})`);
    }
    block.push('');
  }
  if (templates.length > 0) {
    block.push('### Artifact templates');
    block.push('');
    for (const rel of templates) {
      const stem = rel.split('/').pop()?.replace(/\.md$/i, '') ?? rel;
      block.push(`- [${humanize(stem)}](${githubBlobUrl(rel)})`);
    }
    block.push('');
  }
  return block.join('\n');
}
 
/**
 * Render the analysis-index appendix — a compact table of every included
 * artifact and its section, plus a direct link to the manifest.
 *
 * @param included - Artifacts that contributed to the aggregated document
 * @param manifestRelPath - Repo-relative path of `manifest.json`
 * @returns Markdown block with the index table
 */
export function renderAnalysisIndex(
  included: readonly IncludedArtifact[],
  manifestRelPath: string
): string {
  const rows = included.map((a) => {
    const stem = a.runRelPath.split('/').pop()?.replace(/\.md$/i, '') ?? a.runRelPath;
    return `| ${a.sectionId} | [${stem}](${githubBlobUrl(a.repoRelPath)}) | \`${a.runRelPath}\` |`;
  });
  return [
    `<h2 id="${MANIFEST_SECTION_ID}">${MANIFEST_SECTION_TITLE}</h2>`,
    '',
    `Every artifact below was read by the aggregator and contributed to this article. The raw [manifest.json](${githubBlobUrl(manifestRelPath)}) carries the full machine-readable list, including gate-result history.`,
    '',
    '| Section | Artifact | Path |',
    '|---|---|---|',
    ...rows,
    '',
  ].join('\n');
}
 
/**
 * Read a single artifact, clean it, and return the Markdown lines that
 * should be appended to the aggregated document along with the provenance
 * metadata. Split out so {@link aggregateAnalysisRun} stays under the
 * cognitive-complexity budget.
 *
 * @param runDir - Absolute path to the analysis run directory
 * @param runRel - Run-relative POSIX path of the artifact
 * @param runDirRelPath - Repo-relative POSIX path of the run directory
 * @param seenMermaid - Shared mermaid-body hash set for dedup
 * @param sectionId - Identifier of the owning section (for the index)
 * @param suppressHeader - When `true`, omit the `### {humanize(stem)}` heading
 *        (used when the section has a single artifact whose name already
 *        matches the section title, to avoid a redundant H3 immediately
 *        under the section H2)
 * @returns `{ lines, included }` ready to be appended; `null` when the file
 *          doesn't exist on disk
 */
function renderArtifactFragment(
  runDir: string,
  runRel: string,
  runDirRelPath: string,
  seenMermaid: Set<string>,
  sectionId: string,
  suppressHeader: boolean
): { lines: string[]; included: IncludedArtifact } | null {
  const abs = path.join(runDir, runRel);
  Iif (!fs.existsSync(abs)) return null;
  const raw = fs.readFileSync(abs, 'utf8');
  const repoRel = `${runDirRelPath}/${runRel}`;
  const cleaned = cleanArtifact(raw, {
    artifactRelPath: repoRel,
    seenMermaidHashes: seenMermaid,
  });
  const stem = runRel.split('/').pop()?.replace(/\.md$/i, '') ?? runRel;
  const headerLines = suppressHeader ? [] : ['', `### ${humanize(stem)}`];
  const lines = [
    ...headerLines,
    '',
    `<p class="artifact-source"><a href="${githubBlobUrl(repoRel)}" rel="noopener">View source: <code>${runRel}</code></a></p>`,
    '',
    cleaned.markdown,
  ];
  const included: IncludedArtifact = {
    runRelPath: runRel,
    repoRelPath: repoRel,
    sectionId,
  };
  return { lines, included };
}
 
/**
 * Decide whether the `### {humanize(stem)}` sub-heading can be suppressed
 * for a single-artifact section. The rule: when a section contains exactly
 * one artifact AND the humanised stem matches the section title
 * (case-insensitive), the sub-heading would restate the section H2 and is
 * dropped. This fixes the visible `<h2>Synthesis Summary</h2><h3>Synthesis
 * Summary</h3>` duplication seen in first-pass aggregates.
 *
 * @param paths - Run-relative artifact paths that belong to the section
 * @param sectionTitle - Display title of the owning section
 * @returns `true` when the single-artifact header should be suppressed
 */
function shouldSuppressFragmentHeader(paths: readonly string[], sectionTitle: string): boolean {
  Iif (paths.length !== 1) return false;
  const onlyPath = paths[0];
  Iif (!onlyPath) return false;
  const stem = onlyPath.split('/').pop()?.replace(/\.md$/i, '') ?? onlyPath;
  return humanize(stem).toLowerCase() === sectionTitle.toLowerCase();
}
 
/**
 * Append one canonical section to `sectionMarkdown`, reading every
 * fragment through {@link renderArtifactFragment}. Extracted so
 * {@link aggregateAnalysisRun} stays under the cognitive-complexity budget.
 *
 * @param runDir - Absolute run directory
 * @param runDirRelPath - Repo-relative run directory
 * @param sectionId - Section identifier
 * @param sectionTitle - Section title
 * @param paths - Run-relative paths to include
 * @param seenMermaid - Shared mermaid dedup set
 * @param sectionMarkdown - Mutable output buffer
 * @param included - Mutable list of included-artifact metadata
 * @param emittedSections - Mutable list of `(id, title)` pairs for the
 *        article-level TOC; a section is recorded only when at least one
 *        of its artifacts was actually rendered
 */
/**
 * Prefix applied to every article-level section id to avoid collisions
 * with artifact-generated heading anchors. A section like `stakeholder-map`
 * becomes `#section-stakeholder-map`, leaving the bare `#stakeholder-map`
 * slug free for an artifact that happens to contain a `### Stakeholder
 * Map` heading (which `markdown-it-anchor` will slug verbatim).
 */
const SECTION_ID_PREFIX = 'section-';
 
/**
 * Namespace a canonical section id so it cannot collide with an artifact
 * heading slug produced downstream by markdown-it-anchor.
 *
 * @param sectionId - Raw section identifier from `ARTIFACT_SECTIONS`
 * @returns Namespaced id like `section-stakeholder-map`
 */
function namespacedSectionId(sectionId: string): string {
  return `${SECTION_ID_PREFIX}${sectionId}`;
}
 
function appendSection(
  runDir: string,
  runDirRelPath: string,
  sectionId: string,
  sectionTitle: string,
  paths: readonly string[],
  seenMermaid: Set<string>,
  sectionMarkdown: string[],
  included: IncludedArtifact[],
  emittedSections: TocSection[]
): void {
  if (paths.length === 0) return;
  const emittedId = namespacedSectionId(sectionId);
  sectionMarkdown.push(`<h2 id="${emittedId}">${sectionTitle}</h2>`);
  const suppress = shouldSuppressFragmentHeader(paths, sectionTitle);
  let anyFragmentRendered = false;
  for (const runRel of paths) {
    const fragment = renderArtifactFragment(
      runDir,
      runRel,
      runDirRelPath,
      seenMermaid,
      emittedId,
      suppress
    );
    Iif (!fragment) continue;
    anyFragmentRendered = true;
    sectionMarkdown.push(...fragment.lines);
    included.push(fragment.included);
  }
  Eif (anyFragmentRendered) {
    emittedSections.push({ id: emittedId, title: sectionTitle });
  }
  sectionMarkdown.push('');
}
 
/**
 * Read, clean, and concatenate every artifact declared by the run's manifest
 * (with discovery fallback when manifest.files is missing), returning a
 * single aggregated Markdown document.
 *
 * The function is deterministic: given the same inputs it produces the
 * same output byte-for-byte.
 *
 * @param options - Aggregation options (run dir, repo root, tradecraft files)
 * @returns {@link AggregatedRun} describing the rendered document
 */
export function aggregateAnalysisRun(options: AggregateOptions): AggregatedRun {
  const { runDir, repoRoot } = options;
  if (!fs.existsSync(runDir)) {
    throw new Error(`Run directory does not exist: ${runDir}`);
  }
  const manifestPath = path.join(runDir, 'manifest.json');
  let manifest: AnalysisManifest = { articleType: 'unknown' };
  Eif (fs.existsSync(manifestPath)) {
    manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as AnalysisManifest;
  }
  const manifestFiles = flattenManifestFiles(manifest.files);
  const discovered = collectRunArtifacts(runDir);
  // Merge manifest-declared files with discovered files; manifest gives order
  // priority, discovery ensures nothing is missed.
  const availableSet = new Set<string>([...manifestFiles, ...discovered]);
  const available = [...availableSet].sort();
 
  const consumed = new Set<string>();
  const includedArtifacts: IncludedArtifact[] = [];
  const emittedSections: TocSection[] = [];
  const sectionMarkdown: string[] = [];
  const seenMermaid = new Set<string>();
  const runDirRelPath = path.relative(repoRoot, runDir).split(path.sep).join('/');
 
  for (const section of ARTIFACT_SECTIONS) {
    const paths = expandSectionArtifacts(section, new Set(available), consumed);
    appendSection(
      runDir,
      runDirRelPath,
      section.id,
      section.title,
      paths,
      seenMermaid,
      sectionMarkdown,
      includedArtifacts,
      emittedSections
    );
  }
 
  // Supplementary bucket: anything that didn't match a declared section
  const leftovers = available.filter((p) => !consumed.has(p));
  Iif (leftovers.length > 0) {
    appendSection(
      runDir,
      runDirRelPath,
      SUPPLEMENTARY_SECTION_ID,
      SUPPLEMENTARY_SECTION_TITLE,
      leftovers,
      seenMermaid,
      sectionMarkdown,
      includedArtifacts,
      emittedSections
    );
    for (const p of leftovers) consumed.add(p);
  }
 
  const tradecraftFiles = options.tradecraftFiles ?? discoverTradecraftFiles(repoRoot);
  const articleType = manifest.articleType ?? 'unknown';
  const date = manifest.date ?? guessDateFromRunDir(runDirRelPath);
  const runId = manifest.runId ?? path.basename(runDir);
  const gateResult = latestGateResult(manifest);
  const manifestRelPath = `${runDirRelPath}/manifest.json`;
 
  const documentTitle = `${humanize(articleType)} — ${date}`;
  const provenance = renderProvenanceBlock({
    articleType,
    date,
    runId,
    gateResult,
    runDirRelPath,
    manifestRelPath,
  });
  const tradecraft = renderTradecraftAppendix(tradecraftFiles);
  const analysisIndex = renderAnalysisIndex(includedArtifacts, manifestRelPath);
 
  // Both appendices emit their own <h2 id="…"> blocks — record them so the
  // article TOC mirrors the rendered document in document order.
  emittedSections.push({ id: TRADECRAFT_SECTION_ID, title: TRADECRAFT_SECTION_TITLE });
  emittedSections.push({ id: MANIFEST_SECTION_ID, title: MANIFEST_SECTION_TITLE });
 
  const markdown = [
    `# ${documentTitle}`,
    '',
    provenance,
    '',
    ...sectionMarkdown,
    '',
    tradecraft,
    '',
    analysisIndex,
    '',
  ]
    .join('\n')
    .replace(/\n{3,}/g, '\n\n');
 
  return {
    markdown,
    runDirRelPath,
    articleType,
    date,
    includedArtifacts,
    gateResult,
    sectionToc: emittedSections,
  };
}
 
/**
 * Extract a `YYYY-MM-DD` date from a path like
 * `analysis/daily/2026-01-15/run`. Falls back to the epoch date when no
 * ISO date is embedded in the path.
 *
 * @param runDirRelPath - Repo-relative path of the run directory
 * @returns ISO date string in `YYYY-MM-DD` form
 */
function guessDateFromRunDir(runDirRelPath: string): string {
  const match = /(\d{4}-\d{2}-\d{2})/.exec(runDirRelPath);
  return match ? (match[1] ?? '1970-01-01') : '1970-01-01';
}