All files / scripts/agentic analysis-gate.ts

94.6% Statements 351/371
87.72% Branches 193/220
100% Functions 28/28
95.07% Lines 328/345

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 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195                                                                                                                                    3x     3x     3x     3x     3x     3x     3x     3x     3x     3x     3x   126x 3x                             7x 7x 161x 161x 70x           91x 1x             90x               7x                           7x 7x   7x 3x     4x 4x   4x 1x         1x     3x 3x 6x 6x                   3x             8x 8x 8x 5x               6x           6x 14x 14x                           8x     8x   8x 53x 53x 53x 212x 6x                   8x 4x             8x                       11x 11x 11x 11x 11x 57x 57x 3x 54x 53x     11x                             8x   8x 8x   8x       1x   1x   1x   1x   1x             8x 8x 8x   5x 5x 5x 5x   5x 50x 9x 9x 9x   41x 5x 5x 5x   36x   29x 11x 11x     18x 13x 1x             13x     5x                             5x 4x               5x         1x   1x                   8x 8x 8x   5x 5x 5x 5x   5x 33x 1x 1x 1x   32x 1x 1x     31x 3x 1x               1x     28x 12x 12x       16x 1x           1x       15x 4x 3x 3x 2x                     5x 4x               5x                         7x   7x 112x 112x   20x   20x 20x 1x           1x       19x       112x 1x             18x                 7x                       1x                     7x 7x   7x 154x 154x   25x     25x 25x 25x       25x 23x         25x 2x 2x 2x 2x         25x 2x             23x                 7x                         14x     14x     14x     14x     14x     14x     14x   14x             14x 14x 14x   3x   3x 3x 1x               3x 3x                 3x 2x               3x                 14x 14x 14x   3x         3x 27x 3x 3x 1x                 3x     3x 14x                   3x 3x                 3x 2x               3x             14x 14x 14x   3x 3x 3x   14x 1x             2x               3x             14x 14x 14x   2x 2x     2x   14x               2x               2x                 14x 14x 14x   3x   3x         14x               3x               3x                 14x 14x 14x   3x     3x 3x       14x 16x 8x 6x 4x     14x   14x               3x               3x                         8x     8x     8x   8x             8x 8x 8x   4x       4x 4x 4x   8x 1x             3x               4x                 8x 8x 8x   3x 3x   3x 1x             2x               3x                                                   1x       1x       1x           12x 12x   12x 3x         3x       9x 9x 9x   1x         1x       8x 8x 48x                   8x 1x               8x                   8x 1x               8x 6x   6x 1x             6x 18x 1x               6x 1x             6x 1x                   6x 1x           6x 1x               8x 3x             8x                           7x 7x 7x   5x     5x 5x   2x           2x         3x   3x 1x             2x               3x    
/**
 * @module scripts/agentic/analysis-gate
 * @description TypeScript implementation of the analysis gate validation
 *              logic defined in `.github/prompts/05-analysis-gate.md`.
 *
 * This module extracts a subset of the inline bash gate checks into
 * testable, strictly-typed functions. It implements checks 1–9b of the
 * prompt specification. Additional prompt-level gates (e.g. check 10
 * full-text outcomes, supplementary/editorial gates) are NOT covered
 * here and must be validated separately.
 *
 * Implemented checks:
 *   1. Artifact existence (all 23 files present and non-empty)
 *   2. Per-document coverage (Family E vs manifest)
 *   3. No stub placeholders (recursive scan)
 *   4. Evidence citations in SWOT and significance-scoring
 *   5. Mermaid diagrams with colour config
 *   6. Pass-2 evidence (mtime or pass1/ snapshot)
 *   7. Family C structure checks
 *   8. Family D structure checks
 *   9. PIR status sidecar validation
 *   9b. Statskontoret evidence in implementation-feasibility
 *
 * @example
 *   import { validateAnalysisGate } from './analysis-gate.js';
 *   const result = await validateAnalysisGate('analysis/daily/2026-05-01/propositions');
 *   if (!result.passed) {
 *     result.checks.filter(c => !c.passed).forEach(c => console.error(c.message));
 *   }
 *
 * @see .github/prompts/05-analysis-gate.md — canonical gate specification
 * @see scripts/agentic/artifact-inventory.ts — artifact definitions
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import { readFile, stat, readdir } from 'node:fs/promises';
import { existsSync, statSync } from 'node:fs';
import { join } from 'node:path';
 
import {
  type GateCheckResult,
  type GateValidationResult,
  REQUIRED_ARTIFACT_FILENAMES,
  MERMAID_REQUIRED_ARTIFACTS,
  PASS2_REQUIRED_ARTIFACTS,
  STUB_PLACEHOLDERS,
  DOK_ID_PATTERN,
  EVIDENCE_PATTERN,
  RECOGNISED_AGENCIES,
} from './artifact-inventory.js';
 
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
 
/**
 * Run all analysis gate checks against an analysis directory.
 *
 * @param analysisDir - Absolute or relative path to the analysis subfolder
 *                      (e.g. `analysis/daily/2026-05-01/propositions`).
 * @returns Aggregate validation result with per-check details.
 */
export async function validateAnalysisGate(
  analysisDir: string,
): Promise<GateValidationResult> {
  const checks: GateCheckResult[] = [];
 
  // Check 1 — Artifact existence
  checks.push(...checkArtifactExistence(analysisDir));
 
  // Check 2 — Per-document coverage
  checks.push(...(await checkPerDocumentCoverage(analysisDir)));
 
  // Check 3 — No stubs
  checks.push(...(await checkNoStubs(analysisDir)));
 
  // Check 4 — Evidence citations
  checks.push(...(await checkEvidenceCitations(analysisDir)));
 
  // Check 5 — Mermaid diagrams
  checks.push(...(await checkMermaidDiagrams(analysisDir)));
 
  // Check 6 — Pass-2 evidence
  checks.push(...(await checkPass2Evidence(analysisDir)));
 
  // Check 7 — Family C structure
  checks.push(...(await checkFamilyCStructure(analysisDir)));
 
  // Check 8 — Family D structure
  checks.push(...(await checkFamilyDStructure(analysisDir)));
 
  // Check 9 — PIR status sidecar
  checks.push(...(await checkPirStatus(analysisDir)));
 
  // Check 9b — Statskontoret evidence
  checks.push(...(await checkStatskontoretEvidence(analysisDir)));
 
  const failureCount = checks.filter((c) => !c.passed).length;
  return {
    passed: failureCount === 0,
    checks,
    failureCount,
  };
}
 
// ---------------------------------------------------------------------------
// Check 1 — Artifact existence
// ---------------------------------------------------------------------------
 
/**
 * Verify all 23 required artifacts exist and are non-empty.
 */
export function checkArtifactExistence(analysisDir: string): GateCheckResult[] {
  const results: GateCheckResult[] = [];
  for (const filename of REQUIRED_ARTIFACT_FILENAMES) {
    const filePath = join(analysisDir, filename);
    if (!existsSync(filePath)) {
      results.push({
        checkId: 'artifact-existence',
        passed: false,
        message: `Missing artifact: ${filename}`,
        artifact: filename,
      });
    } else if (statSync(filePath).size === 0) {
      results.push({
        checkId: 'artifact-existence',
        passed: false,
        message: `Empty artifact (zero bytes): ${filename}`,
        artifact: filename,
      });
    } else {
      results.push({
        checkId: 'artifact-existence',
        passed: true,
        message: `Artifact present: ${filename}`,
        artifact: filename,
      });
    }
  }
  return results;
}
 
// ---------------------------------------------------------------------------
// Check 2 — Per-document coverage
// ---------------------------------------------------------------------------
 
/**
 * Extract dok_ids from the data-download-manifest and verify each has
 * a corresponding analysis document in the `documents/` subdirectory.
 */
export async function checkPerDocumentCoverage(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const manifestPath = join(analysisDir, 'data-download-manifest.md');
 
  if (!existsSync(manifestPath)) {
    return results; // Manifest missing handled by check 1
  }
 
  const content = await readFile(manifestPath, 'utf-8');
  const dokIds = extractDokIds(content);
 
  if (dokIds.length === 0) {
    results.push({
      checkId: 'per-document-coverage',
      passed: false,
      message: 'Manifest has no dok_id entries',
    });
    return results;
  }
 
  const documentsDir = join(analysisDir, 'documents');
  for (const dokId of dokIds) {
    const found = hasDocumentAnalysis(documentsDir, dokId);
    results.push({
      checkId: 'per-document-coverage',
      passed: found,
      message: found
        ? `Document analysis found for ${dokId}`
        : `documents/${dokId}.md or documents/${dokId}-analysis.md missing (any case)`,
      artifact: `documents/${dokId}-analysis.md`,
    });
  }
 
  return results;
}
 
/**
 * Extract unique dok_ids from markdown content.
 */
export function extractDokIds(content: string): string[] {
  const globalPattern = new RegExp(DOK_ID_PATTERN.source, 'g');
  const matches = content.match(globalPattern);
  if (!matches) return [];
  return [...new Set(matches)];
}
 
/**
 * Check if a document analysis file exists and is non-empty (any case variant).
 * Mirrors the prompt gate's `-s` check (file exists AND size > 0).
 */
function hasDocumentAnalysis(documentsDir: string, dokId: string): boolean {
  const variants = [
    `${dokId}.md`,
    `${dokId}-analysis.md`,
    `${dokId.toLowerCase()}.md`,
    `${dokId.toLowerCase()}-analysis.md`,
  ];
  return variants.some((v) => {
    const p = join(documentsDir, v);
    return existsSync(p) && statSync(p).size > 0;
  });
}
 
// ---------------------------------------------------------------------------
// Check 3 — No stubs
// ---------------------------------------------------------------------------
 
/**
 * Scan all markdown files under the analysis directory (recursive, including
 * `documents/` and `pass1/` subdirs) for stub placeholder strings. The
 * canonical gate uses a recursive grep over the entire `$ANALYSIS_DIR`.
 */
export async function checkNoStubs(analysisDir: string): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
 
  // Recursively collect all .md files under analysisDir
  const mdFiles = await collectMdFilesRecursive(analysisDir, '');
 
  for (const relPath of mdFiles) {
    const filePath = join(analysisDir, relPath);
    const content = await readFile(filePath, 'utf-8');
    for (const stub of STUB_PLACEHOLDERS) {
      if (content.includes(stub)) {
        results.push({
          checkId: 'no-stubs',
          passed: false,
          message: `Stub placeholder "${stub}" found in ${relPath}`,
          artifact: relPath,
        });
      }
    }
  }
 
  if (results.length === 0) {
    results.push({
      checkId: 'no-stubs',
      passed: true,
      message: 'No stub placeholders detected',
    });
  }
 
  return results;
}
 
/**
 * Recursively collect all `.md` files under a directory, returning paths
 * relative to `baseDir`. Used by the stub scanner to mirror the canonical
 * gate's recursive grep over the entire analysis tree.
 */
async function collectMdFilesRecursive(
  baseDir: string,
  prefix: string,
): Promise<string[]> {
  const results: string[] = [];
  const currentDir = prefix ? join(baseDir, prefix) : baseDir;
  Iif (!existsSync(currentDir)) return results;
  const entries = await readdir(currentDir, { withFileTypes: true });
  for (const entry of entries) {
    const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
    if (entry.isDirectory()) {
      results.push(...(await collectMdFilesRecursive(baseDir, relPath)));
    } else if (entry.name.endsWith('.md')) {
      results.push(relPath);
    }
  }
  return results;
}
 
// ---------------------------------------------------------------------------
// Check 4 — Evidence citations
// ---------------------------------------------------------------------------
 
/**
 * Verify that swot-analysis.md and significance-scoring.md contain primary-
 * source evidence (a dok_id or recognised URL host) in each bullet/table row.
 * Mirrors the awk-based gate in `05-analysis-gate.md` (check 4).
 */
export async function checkEvidenceCitations(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
 
  results.push(...(await checkSwotEvidence(analysisDir)));
  results.push(...(await checkSignificanceScoringEvidence(analysisDir)));
 
  return results;
}
 
/** SWOT section headings that trigger per-line evidence enforcement. */
const SWOT_SECTION_RE = /^###\s+.*(Strengths|Weaknesses|Opportunities|Threats)\b/i;
/** Any heading resets the active SWOT section. */
const ANY_HEADING_RE = /^#{1,6}\s+/;
/** Bullet lines (- or * style). */
const BULLET_RE = /^\s*[-*]\s+/;
/** Table row (starts with |). */
const TABLE_ROW_RE = /^\s*\|/;
/** Separator row (only |, :, -, whitespace). */
const TABLE_SEP_RE = /^\s*[|:\-\s]+$/;
 
/**
 * Check swot-analysis.md: every bullet and table row inside a SWOT section
 * must contain at least one evidence citation.
 */
async function checkSwotEvidence(analysisDir: string): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'swot-analysis.md');
  if (!existsSync(filePath)) return results;
 
  const content = await readFile(filePath, 'utf-8');
  const lines = content.split('\n');
  let currentSection = '';
  let tableRowCount = 0;
 
  for (const line of lines) {
    if (SWOT_SECTION_RE.test(line)) {
      currentSection = line.trim();
      tableRowCount = 0;
      continue;
    }
    if (ANY_HEADING_RE.test(line)) {
      currentSection = '';
      tableRowCount = 0;
      continue;
    }
    if (!currentSection) continue;
 
    if (/^\s*$/.test(line)) {
      tableRowCount = 0;
      continue;
    }
 
    if (BULLET_RE.test(line)) {
      if (!EVIDENCE_PATTERN.test(line)) {
        results.push({
          checkId: 'evidence-citations',
          passed: false,
          message: `swot-analysis.md ${currentSection}: bullet missing evidence (dok_id or primary-source URL): ${line.trim()}`,
          artifact: 'swot-analysis.md',
        });
      }
      continue; // bullet lines are never also table rows
    }
 
    Iif (TABLE_ROW_RE.test(line)) {
      if (TABLE_SEP_RE.test(line)) continue;
      tableRowCount++;
      if (tableRowCount === 1) continue; // skip header row
      if (!EVIDENCE_PATTERN.test(line)) {
        results.push({
          checkId: 'evidence-citations',
          passed: false,
          message: `swot-analysis.md ${currentSection}: table row missing evidence (dok_id or primary-source URL): ${line.trim()}`,
          artifact: 'swot-analysis.md',
        });
      }
    }
  }
 
  if (results.length === 0) {
    results.push({
      checkId: 'evidence-citations',
      passed: true,
      message: 'swot-analysis.md: evidence citations present',
      artifact: 'swot-analysis.md',
    });
  }
 
  return results;
}
 
/** Mermaid structural keywords — these lines are never checked for evidence. */
const MERMAID_STRUCTURAL_RE =
  /^\s*(%%|style\b|classDef\b|class\b|linkStyle\b|subgraph\b|end\b|graph\b|flowchart\b|quadrantChart\b|mindmap\b|timeline\b|journey\b|gantt\b|pie\b|xychart-beta\b|sequenceDiagram\b|stateDiagram(-v2)?\b|erDiagram\b|sankey-beta\b|gitGraph\b|requirementDiagram\b|block-beta\b)/;
/** Mermaid node/label content — lines with bracket/paren/curly-enclosed content indicate node labels. */
const MERMAID_NODE_RE = /\[[^\]\n]+\]|\([^)\n]+\)|\{[^}\n]+\}/;
 
/**
 * Check significance-scoring.md: every ranked bullet/list item and table
 * row (outside Mermaid) must contain evidence. Mermaid node labels are
 * also checked unless they are structural keywords.
 */
async function checkSignificanceScoringEvidence(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'significance-scoring.md');
  if (!existsSync(filePath)) return results;
 
  const content = await readFile(filePath, 'utf-8');
  const lines = content.split('\n');
  let inMermaid = false;
  let tableRowCount = 0;
 
  for (const line of lines) {
    if (/^```mermaid\s*$/.test(line)) {
      inMermaid = true;
      tableRowCount = 0;
      continue;
    }
    if (inMermaid && /^```\s*$/.test(line)) {
      inMermaid = false;
      continue;
    }
 
    if (inMermaid) {
      if (MERMAID_STRUCTURAL_RE.test(line)) continue;
      Iif (MERMAID_NODE_RE.test(line) && !EVIDENCE_PATTERN.test(line)) {
        results.push({
          checkId: 'evidence-citations',
          passed: false,
          message: `significance-scoring.md Mermaid node missing evidence (dok_id or primary-source URL): ${line.trim()}`,
          artifact: 'significance-scoring.md',
        });
      }
      continue;
    }
 
    if (/^\s*$/.test(line)) {
      tableRowCount = 0;
      continue;
    }
 
    // Ranked bullet (- or * or numbered)
    if (/^\s*([0-9]+\.\s+|[-*]\s+)/.test(line) && !EVIDENCE_PATTERN.test(line)) {
      results.push({
        checkId: 'evidence-citations',
        passed: false,
        message: `significance-scoring.md ranked item missing evidence (dok_id or primary-source URL): ${line.trim()}`,
        artifact: 'significance-scoring.md',
      });
      continue;
    }
 
    // Table rows
    if (TABLE_ROW_RE.test(line)) {
      if (TABLE_SEP_RE.test(line)) continue;
      tableRowCount++;
      if (tableRowCount === 1) continue; // skip header row
      Iif (!EVIDENCE_PATTERN.test(line)) {
        results.push({
          checkId: 'evidence-citations',
          passed: false,
          message: `significance-scoring.md ranking table row missing evidence (dok_id or primary-source URL): ${line.trim()}`,
          artifact: 'significance-scoring.md',
        });
      }
    }
  }
 
  if (results.length === 0) {
    results.push({
      checkId: 'evidence-citations',
      passed: true,
      message: 'significance-scoring.md: evidence citations present',
      artifact: 'significance-scoring.md',
    });
  }
 
  return results;
}
 
// ---------------------------------------------------------------------------
// Check 5 — Mermaid diagrams
// ---------------------------------------------------------------------------
 
/**
 * Verify Mermaid diagrams with colour-coded config exist in required files.
 */
export async function checkMermaidDiagrams(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
 
  for (const filename of MERMAID_REQUIRED_ARTIFACTS) {
    const filePath = join(analysisDir, filename);
    if (!existsSync(filePath)) continue;
 
    const content = await readFile(filePath, 'utf-8');
 
    const hasMermaid = /^```mermaid/m.test(content);
    if (!hasMermaid) {
      results.push({
        checkId: 'mermaid-diagrams',
        passed: false,
        message: `${filename}: missing Mermaid block`,
        artifact: filename,
      });
      continue;
    }
 
    const hasColourConfig =
      /^\s*style\s+/m.test(content) ||
      /themeVariables/m.test(content) ||
      /%%\{\s*init/m.test(content);
 
    if (!hasColourConfig) {
      results.push({
        checkId: 'mermaid-diagrams',
        passed: false,
        message: `${filename}: missing Mermaid colour-coded config`,
        artifact: filename,
      });
    } else {
      results.push({
        checkId: 'mermaid-diagrams',
        passed: true,
        message: `${filename}: Mermaid with colour config present`,
        artifact: filename,
      });
    }
  }
 
  return results;
}
 
// ---------------------------------------------------------------------------
// Check 6 — Pass-2 evidence
// ---------------------------------------------------------------------------
 
/**
 * Minimum mtime delta (ms) from birth time that constitutes evidence of a
 * second-pass edit (180 seconds = 3 minutes, matching the bash gate threshold
 * in `05-analysis-gate.md §Check 6`).
 */
const PASS2_MTIME_THRESHOLD_MS = 180_000;
 
/**
 * Verify that Pass-2 iteration was performed on each artifact: either a
 * `pass1/` snapshot exists on disk that differs from the current file, OR
 * the file's mtime is at least 180 s after its birth time (Linux birth time
 * may not be reliable; the `pass1/` check is the preferred mechanism).
 */
export async function checkPass2Evidence(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const pass1Dir = join(analysisDir, 'pass1');
 
  for (const filename of PASS2_REQUIRED_ARTIFACTS) {
    const filePath = join(analysisDir, filename);
    if (!existsSync(filePath)) continue;
 
    let pass2Done = false;
 
    // Primary evidence: a differing pass1/ snapshot
    const pass1Path = join(pass1Dir, filename);
    Eif (existsSync(pass1Path)) {
      const [current, snapshot] = await Promise.all([
        readFile(filePath, 'utf-8'),
        readFile(pass1Path, 'utf-8'),
      ]);
      if (current !== snapshot) {
        pass2Done = true;
      }
    }
 
    // Fallback: mtime >= birthtime + 180 s (where birth time is available)
    if (!pass2Done) {
      const fileStat = await stat(filePath);
      const birthtimeMs = fileStat.birthtimeMs;
      const mtimeMs = fileStat.mtimeMs;
      Iif (birthtimeMs > 0 && mtimeMs >= birthtimeMs + PASS2_MTIME_THRESHOLD_MS) {
        pass2Done = true;
      }
    }
 
    if (!pass2Done) {
      results.push({
        checkId: 'pass2-evidence',
        passed: false,
        message: `${filename}: Pass-2 evidence missing (mtime < birth+180s and no differing pass1/ snapshot)`,
        artifact: filename,
      });
    } else {
      results.push({
        checkId: 'pass2-evidence',
        passed: true,
        message: `${filename}: Pass-2 evidence confirmed`,
        artifact: filename,
      });
    }
  }
 
  return results;
}
 
// ---------------------------------------------------------------------------
// Check 7 — Family C structure
// ---------------------------------------------------------------------------
 
/**
 * Validate Family C structural requirements.
 */
export async function checkFamilyCStructure(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
 
  // executive-brief.md: BLUF + Decisions sections
  results.push(...(await checkExecutiveBrief(analysisDir)));
 
  // intelligence-assessment.md: ≥3 Key Judgments + confidence + PIR
  results.push(...(await checkIntelligenceAssessment(analysisDir)));
 
  // scenario-analysis.md: ≥3 scenarios
  results.push(...(await checkScenarioAnalysis(analysisDir)));
 
  // devils-advocate.md: ≥3 hypotheses
  results.push(...(await checkDevilsAdvocate(analysisDir)));
 
  // methodology-reflection.md: ICD 203 or improvements
  results.push(...(await checkMethodologyReflection(analysisDir)));
 
  // comparative-international.md: comparator set or ≥2 rows
  results.push(...(await checkComparativeInternational(analysisDir)));
 
  return results;
}
 
/**
 * Check executive-brief.md for BLUF and Decisions sections.
 */
async function checkExecutiveBrief(analysisDir: string): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'executive-brief.md');
  if (!existsSync(filePath)) return results;
 
  const content = await readFile(filePath, 'utf-8');
 
  const hasBluf = /^##\s.*BLUF/m.test(content);
  if (!hasBluf) {
    results.push({
      checkId: 'family-c-structure',
      passed: false,
      message: "executive-brief.md: missing '## BLUF' section",
      artifact: 'executive-brief.md',
    });
  }
 
  const hasDecisions = /^##\s.*(Decision|Decisions\s+This\s+Brief)/m.test(content);
  Iif (!hasDecisions) {
    results.push({
      checkId: 'family-c-structure',
      passed: false,
      message: "executive-brief.md: missing 'Decisions' section",
      artifact: 'executive-brief.md',
    });
  }
 
  if (hasBluf && hasDecisions) {
    results.push({
      checkId: 'family-c-structure',
      passed: true,
      message: 'executive-brief.md: BLUF and Decisions present',
      artifact: 'executive-brief.md',
    });
  }
 
  return results;
}
 
/**
 * Check intelligence-assessment.md for Key Judgments, confidence labels, PIR.
 */
async function checkIntelligenceAssessment(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'intelligence-assessment.md');
  if (!existsSync(filePath)) return results;
 
  const content = await readFile(filePath, 'utf-8');
 
  // ≥3 Key Judgments — count distinct matching lines (not raw occurrences)
  // to mirror the canonical gate's `grep -cE` behaviour. A line like
  // "Key Judgment KJ-1" counts as 1, not 2.
  const kjPattern = /(Key\s+Judgment|KJ-?\d+)/;
  const kjLines = content.split('\n').filter((line) => kjPattern.test(line));
  const kjCount = kjLines.length;
  if (kjCount < 3) {
    results.push({
      checkId: 'family-c-structure',
      passed: false,
      message: `intelligence-assessment.md: fewer than 3 Key Judgments (found ${kjCount})`,
      artifact: 'intelligence-assessment.md',
    });
  }
 
  // ≥3 confidence labels
  const confMatches = content.match(
    /\b(VERY\s+HIGH|VERY\s+LOW|HIGH|MEDIUM|LOW)\b/g,
  );
  const confCount = confMatches ? confMatches.length : 0;
  Iif (confCount < 3) {
    results.push({
      checkId: 'family-c-structure',
      passed: false,
      message: `intelligence-assessment.md: fewer than 3 confidence labels (found ${confCount})`,
      artifact: 'intelligence-assessment.md',
    });
  }
 
  // PIR reference
  const hasPir = /PIR/i.test(content);
  Iif (!hasPir) {
    results.push({
      checkId: 'family-c-structure',
      passed: false,
      message: 'intelligence-assessment.md: no PIR reference',
      artifact: 'intelligence-assessment.md',
    });
  }
 
  if (kjCount >= 3 && confCount >= 3 && hasPir) {
    results.push({
      checkId: 'family-c-structure',
      passed: true,
      message: 'intelligence-assessment.md: structure valid',
      artifact: 'intelligence-assessment.md',
    });
  }
 
  return results;
}
 
/**
 * Check scenario-analysis.md for ≥3 distinct scenarios.
 */
async function checkScenarioAnalysis(analysisDir: string): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'scenario-analysis.md');
  if (!existsSync(filePath)) return results;
 
  const content = await readFile(filePath, 'utf-8');
  const scenarioMatches = content.match(/^##?\s+.*Scenario/gm);
  const count = scenarioMatches ? scenarioMatches.length : 0;
 
  if (count < 3) {
    results.push({
      checkId: 'family-c-structure',
      passed: false,
      message: `scenario-analysis.md: fewer than 3 scenarios (found ${count})`,
      artifact: 'scenario-analysis.md',
    });
  } else {
    results.push({
      checkId: 'family-c-structure',
      passed: true,
      message: `scenario-analysis.md: ${count} scenarios found`,
      artifact: 'scenario-analysis.md',
    });
  }
 
  return results;
}
 
/**
 * Check devils-advocate.md for ≥3 competing hypotheses.
 */
async function checkDevilsAdvocate(analysisDir: string): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'devils-advocate.md');
  if (!existsSync(filePath)) return results;
 
  const content = await readFile(filePath, 'utf-8');
  const hyMatches = content.match(
    /^#{2,4}\s*(Hypothesis|H[0-9]+\s*[:.—-])/gm,
  );
  const count = hyMatches ? hyMatches.length : 0;
 
  Iif (count < 3) {
    results.push({
      checkId: 'family-c-structure',
      passed: false,
      message: `devils-advocate.md: fewer than 3 competing hypotheses (found ${count})`,
      artifact: 'devils-advocate.md',
    });
  } else {
    results.push({
      checkId: 'family-c-structure',
      passed: true,
      message: `devils-advocate.md: ${count} hypotheses found`,
      artifact: 'devils-advocate.md',
    });
  }
 
  return results;
}
 
/**
 * Check methodology-reflection.md for ICD 203 audit or named improvements.
 */
async function checkMethodologyReflection(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'methodology-reflection.md');
  if (!existsSync(filePath)) return results;
 
  const content = await readFile(filePath, 'utf-8');
  const hasIcd203 =
    /ICD\s+203/i.test(content) ||
    /Methodology\s+Improvements/i.test(content) ||
    /Improvement\s+1/i.test(content) ||
    /^#{2,4}\s+.*Improvements/m.test(content);
 
  Iif (!hasIcd203) {
    results.push({
      checkId: 'family-c-structure',
      passed: false,
      message: 'methodology-reflection.md: missing ICD 203 audit or Methodology Improvements',
      artifact: 'methodology-reflection.md',
    });
  } else {
    results.push({
      checkId: 'family-c-structure',
      passed: true,
      message: 'methodology-reflection.md: ICD 203 / improvements present',
      artifact: 'methodology-reflection.md',
    });
  }
 
  return results;
}
 
/**
 * Check comparative-international.md for comparator set or ≥2 rows.
 */
async function checkComparativeInternational(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'comparative-international.md');
  if (!existsSync(filePath)) return results;
 
  const content = await readFile(filePath, 'utf-8');
 
  // Check for "Comparator set:" line with non-empty value
  const COMPARATOR_SET_RE = /^\s*\*{0,2}Comparator set\*{0,2}\s*:/m;
  const hasComparatorSet = COMPARATOR_SET_RE.test(content) &&
    !/^\s*\*{0,2}Comparator set\*{0,2}\s*:\s*[-–—]*\s*$/m.test(content);
 
  // Count non-header table rows (excluding separator rows)
  const tableRows = content.split('\n').filter((line) => {
    if (!/^\|/.test(line)) return false;
    if (/^\|[\s:-]+(\|[\s:-]+)+\|?\s*$/.test(line)) return false;
    if (/^\|\s*(Jurisdiction|Comparator|Country)\s*\|/.test(line)) return false;
    return true;
  });
 
  const hasEnoughRows = tableRows.length >= 2;
 
  Iif (!hasComparatorSet && !hasEnoughRows) {
    results.push({
      checkId: 'family-c-structure',
      passed: false,
      message: 'comparative-international.md: missing comparator set or fewer than 2 comparator rows',
      artifact: 'comparative-international.md',
    });
  } else {
    results.push({
      checkId: 'family-c-structure',
      passed: true,
      message: 'comparative-international.md: comparator data present',
      artifact: 'comparative-international.md',
    });
  }
 
  return results;
}
 
// ---------------------------------------------------------------------------
// Check 8 — Family D structure
// ---------------------------------------------------------------------------
 
/**
 * Validate Family D structural requirements.
 */
export async function checkFamilyDStructure(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
 
  // forward-indicators.md: ≥10 dated indicators
  results.push(...(await checkForwardIndicators(analysisDir)));
 
  // coalition-mathematics.md: seat-count table
  results.push(...(await checkCoalitionMathematics(analysisDir)));
 
  return results;
}
 
/**
 * Check forward-indicators.md for ≥10 dated indicators.
 */
async function checkForwardIndicators(analysisDir: string): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'forward-indicators.md');
  if (!existsSync(filePath)) return results;
 
  const content = await readFile(filePath, 'utf-8');
  // Loose date detection (not strict calendar validation) — matches the
  // original bash gate pattern; false positives are acceptable here since
  // the goal is to verify the author included date-anchored indicators.
  const datePattern = /20[0-9]{2}-[0-1][0-9]-[0-3][0-9]|20[0-9]{2}Q[1-4]|\+[0-9]+\s*(h|d|day|week|month)/g;
  const matches = content.match(datePattern);
  const count = matches ? matches.length : 0;
 
  if (count < 10) {
    results.push({
      checkId: 'family-d-structure',
      passed: false,
      message: `forward-indicators.md: fewer than 10 dated indicators (found ${count})`,
      artifact: 'forward-indicators.md',
    });
  } else {
    results.push({
      checkId: 'family-d-structure',
      passed: true,
      message: `forward-indicators.md: ${count} dated indicators found`,
      artifact: 'forward-indicators.md',
    });
  }
 
  return results;
}
 
/**
 * Check coalition-mathematics.md for seat-count / vote-breakdown table.
 */
async function checkCoalitionMathematics(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'coalition-mathematics.md');
  if (!existsSync(filePath)) return results;
 
  const content = await readFile(filePath, 'utf-8');
  const hasTable = /^\|.*(Ja|Nej|Avstår|Frånvarande|Seats|Mandat)/m.test(content);
 
  if (!hasTable) {
    results.push({
      checkId: 'family-d-structure',
      passed: false,
      message: 'coalition-mathematics.md: missing seat-count / vote-breakdown table',
      artifact: 'coalition-mathematics.md',
    });
  } else {
    results.push({
      checkId: 'family-d-structure',
      passed: true,
      message: 'coalition-mathematics.md: vote/seat table present',
      artifact: 'coalition-mathematics.md',
    });
  }
 
  return results;
}
 
// ---------------------------------------------------------------------------
// Check 9 — PIR status sidecar
// ---------------------------------------------------------------------------
 
/** PIR status JSON schema structure. */
interface PirStatusFile {
  readonly schema_version?: string;
  readonly cycle?: string;
  readonly date?: string;
  readonly subfolder?: string;
  readonly pirs?: readonly PirEntry[];
  readonly generated_at?: string;
}
 
/** A single PIR entry in the sidecar file. */
interface PirEntry {
  readonly pir_id?: string;
  readonly statement?: string;
  readonly status?: string;
  readonly confidence?: string;
  readonly answer_summary?: string;
}
 
const VALID_PIR_STATUSES = new Set([
  'open', 'answered', 'superseded', 'deferred', 'cancelled',
]);
 
const VALID_CONFIDENCE_LEVELS = new Set([
  'VERY HIGH', 'HIGH', 'MEDIUM', 'LOW', 'VERY LOW',
]);
 
const PIR_ID_PATTERN = /^PIR-[A-Za-z0-9]+(-[A-Za-z0-9]+)*$/;
 
/**
 * Validate pir-status.json exists and has valid structure.
 */
export async function checkPirStatus(analysisDir: string): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'pir-status.json');
 
  if (!existsSync(filePath)) {
    results.push({
      checkId: 'pir-status',
      passed: false,
      message: 'pir-status.json missing or empty',
    });
    return results;
  }
 
  let data: PirStatusFile;
  try {
    const raw = await readFile(filePath, 'utf-8');
    data = JSON.parse(raw) as PirStatusFile;
  } catch {
    results.push({
      checkId: 'pir-status',
      passed: false,
      message: 'pir-status.json: invalid JSON',
    });
    return results;
  }
 
  // Required top-level fields
  const requiredFields = ['schema_version', 'cycle', 'date', 'subfolder', 'pirs', 'generated_at'] as const;
  for (const field of requiredFields) {
    Iif (!(field in data) || data[field as keyof PirStatusFile] === undefined) {
      results.push({
        checkId: 'pir-status',
        passed: false,
        message: `pir-status.json: missing required field '${field}'`,
      });
    }
  }
 
  // schema_version check
  if (data.schema_version !== '1.0') {
    results.push({
      checkId: 'pir-status',
      passed: false,
      message: "pir-status.json: schema_version must be '1.0'",
    });
  }
 
  // pirs must be an array
  Iif (!Array.isArray(data.pirs)) {
    results.push({
      checkId: 'pir-status',
      passed: false,
      message: "pir-status.json: 'pirs' field must be a JSON array",
    });
    return results;
  }
 
  // subfolder must equal cycle
  if (data.subfolder !== data.cycle) {
    results.push({
      checkId: 'pir-status',
      passed: false,
      message: `pir-status.json: subfolder='${data.subfolder}' must equal cycle='${data.cycle}'`,
    });
  }
 
  // Validate each PIR entry
  for (const pir of data.pirs) {
    const pid = pir.pir_id ?? '(no id)';
 
    if (!pir.pir_id || !PIR_ID_PATTERN.test(pir.pir_id)) {
      results.push({
        checkId: 'pir-status',
        passed: false,
        message: `pir-status.json pir=${pid}: invalid pir_id format`,
      });
    }
 
    for (const field of ['statement', 'status', 'confidence'] as const) {
      if (!pir[field]) {
        results.push({
          checkId: 'pir-status',
          passed: false,
          message: `pir-status.json pir=${pid}: missing required field "${field}"`,
        });
      }
    }
 
    if (pir.status && !VALID_PIR_STATUSES.has(pir.status)) {
      results.push({
        checkId: 'pir-status',
        passed: false,
        message: `pir-status.json pir=${pid}: invalid status '${pir.status}'`,
      });
    }
 
    if (pir.confidence && !VALID_CONFIDENCE_LEVELS.has(pir.confidence)) {
      results.push({
        checkId: 'pir-status',
        passed: false,
        message: `pir-status.json pir=${pid}: invalid confidence '${pir.confidence}'`,
      });
    }
 
    // Conditional: answer_summary required iff status == 'answered'; must
    // not be present for any other status (the canonical Python gate enforces
    // both directions as a cross-field invariant).
    if (pir.status === 'answered' && !pir.answer_summary) {
      results.push({
        checkId: 'pir-status',
        passed: false,
        message: `pir-status.json pir=${pid}: status=answered requires non-empty answer_summary`,
      });
    }
    if (pir.status !== 'answered' && pir.answer_summary !== undefined) {
      results.push({
        checkId: 'pir-status',
        passed: false,
        message: `pir-status.json pir=${pid}: status=${pir.status} must not carry answer_summary`,
      });
    }
  }
 
  if (results.length === 0) {
    results.push({
      checkId: 'pir-status',
      passed: true,
      message: 'pir-status.json: valid',
    });
  }
 
  return results;
}
 
// ---------------------------------------------------------------------------
// Check 9b — Statskontoret evidence
// ---------------------------------------------------------------------------
 
/**
 * When implementation-feasibility.md names a recognised agency, verify
 * the Statskontoret relevance row has a URL or 'none found'.
 */
export async function checkStatskontoretEvidence(
  analysisDir: string,
): Promise<GateCheckResult[]> {
  const results: GateCheckResult[] = [];
  const filePath = join(analysisDir, 'implementation-feasibility.md');
  if (!existsSync(filePath)) return results;
 
  const content = await readFile(filePath, 'utf-8');
 
  // Check if any recognised agency is mentioned
  const agencyPattern = new RegExp(RECOGNISED_AGENCIES.join('|'), 'i');
  if (!agencyPattern.test(content)) {
    // No agency mentioned, check passes
    results.push({
      checkId: 'statskontoret-evidence',
      passed: true,
      message: 'implementation-feasibility.md: no recognised agency mentioned',
      artifact: 'implementation-feasibility.md',
    });
    return results;
  }
 
  // Agency mentioned — check for Statskontoret relevance row
  const statskontoretRow =
    /^\|\s*\*{0,2}Statskontoret relevance\*{0,2}\s*\|\s*([^|]*statskontoret\.se[^|]*|[^|]*none found[^|]*)\|/im;
 
  if (!statskontoretRow.test(content)) {
    results.push({
      checkId: 'statskontoret-evidence',
      passed: false,
      message: "implementation-feasibility.md: names a recognised agency but Statskontoret relevance row lacks a statskontoret.se URL or 'none found'",
      artifact: 'implementation-feasibility.md',
    });
  } else {
    results.push({
      checkId: 'statskontoret-evidence',
      passed: true,
      message: 'implementation-feasibility.md: Statskontoret evidence present',
      artifact: 'implementation-feasibility.md',
    });
  }
 
  return results;
}