-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathvalidate-analysis-completeness.js
More file actions
1366 lines (1248 loc) · 51.3 KB
/
validate-analysis-completeness.js
File metadata and controls
1366 lines (1248 loc) · 51.3 KB
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
#!/usr/bin/env node
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* Stage-C analysis completeness validator.
*
* Hard-enforces the contract between `analysis/templates/*.md` and the
* artifacts produced under `analysis/daily/<date>/<run>/`. Article-html
* quality has historically suffered when artifacts skip mandatory sections,
* Mermaid diagrams, Admiralty grades, WEP bands, or required reader-perspective
* blocks. This validator is the script-side enforcement called for in
* `.github/prompts/03-analysis-completeness-gate.md` §1.
*
* Invocation:
* node scripts/validate-analysis-completeness.js <runDir>
* npm run validate-analysis -- analysis/daily/2026-04-23/breaking-run-1776928781
* npm run validate-analysis -- <runDir> --json (machine-readable summary)
* npm run validate-analysis -- <runDir> --strict (fail on warnings too)
*
* Exit codes:
* 0 GREEN — every mandatory artifact passes every check
* 1 RED — at least one blocking violation
* 2 USAGE — bad CLI invocation
*
* The validator reads:
* - `<runDir>/manifest.json` (articleType, files.*)
* - `analysis/methodologies/reference-quality-thresholds.json` (rules)
*
* Per-artifact checks (in order; fast-fail per artifact):
* 1. file exists and is non-empty
* 2. line count ≥ per-artifact floor (or DEFAULT_MIN_LINES = 30)
* 3. no placeholder markers ("[AI_ANALYSIS_REQUIRED]", "[TBD]", "TODO:",
* "AI_ANALYSIS_PENDING", "[TO BE FILLED]") outside meta-doc contexts
* 4. mermaid presence (≥1 ```mermaid fenced block) for diagram-required
* artifacts (mermaidRequired list in JSON, plus every artifact under
* intelligence/, classification/, risk-scoring/, threat-assessment/)
* 5. all required H2 sections present (requiredSections per relativePath)
* 6. WEP band marker present (Almost Certain|Likely|Even Chance|Unlikely|
* Almost No Chance OR `WEP:` prefix) for wepBandRequired list
* 7. Admiralty grade marker present (regex /\b[A-F][1-6]\b/ on a header,
* table row, or "Admiralty:" line) for admiraltyGradeRequired list
* 8. ICD 203 BLUF marker for icd203BlufRequired list
* 9. SAT documentation (≥10 SATs listed) for satDocumentationRequired list
* 10. Reader-perspective block present (one of: "## Reader", "## What this
* means", "## For Citizens", "## Reader Briefing") for readerBlockRequired
* list — news-journalist quality signal.
* 11. Source diversity: ≥1 evidence row OR ≥1 explicit MCP tool reference
* (e.g. get_procedures, analyze_*, semantic_*) for sourceDiversityRequired
* list.
*
* Output format:
* STAGE_C_GATE: GREEN articleType=<t> artifacts=<N> lines=<L>
* STAGE_C_GATE: RED articleType=<t> missing=<m> short=<s> placeholders=<p>
*
* The validator NEVER mutates the run directory. It reads only.
*/
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { getHorizonConfig } from './config/article-horizons.js';
import { readExpiredUnresolved } from './aggregator/forward-statements-registry.js';
const ROOT = process.cwd();
const DEFAULT_MIN_LINES = 30;
// Family-D artifacts required when electoralOverlay is true.
const FAMILY_D_ARTIFACTS = [
'intelligence/seat-projection.md',
'intelligence/term-arc.md',
'intelligence/mandate-fulfilment-scorecard.md',
];
// Minimum scenarioMaxHorizonMonths threshold that triggers structural-break
// requirement (3 years — long enough to span an EP election cycle).
const LONG_HORIZON_THRESHOLD_MONTHS = 36;
// Regex for structural-break / regime-change content in scenario-forecast.md
const STRUCTURAL_BREAK_RE =
/\b(structural[- ]break|regime[- ]change|regime[- ]shift)\b/i;
const PLACEHOLDER_PATTERNS = [
/\[AI_ANALYSIS_REQUIRED\]/,
/AI_ANALYSIS_PENDING/,
/\[TO BE FILLED\]/,
/\[TBD\]/i,
/^TODO:/m,
];
// dataMode threshold reduction factors — when manifest.dataMode declares a
// degraded data availability state, line floors are multiplied by this factor.
// Structural checks (mermaid, WEP, Admiralty, SATs) are never reduced.
const DATA_MODE_REDUCTION = {
'full': 1.0,
'green': 1.0, // alias — prefetch-ep-feeds.sh emits 'full' since v1.6.0
'title-only': 0.75,
'degraded-imf': 0.85,
'degraded-voting': 0.85,
'degraded-feeds': 0.80,
'minimal': 0.65,
};
const WEP_BAND_RE =
/\b(Almost Certain|Highly Likely|Likely|Roughly Even|Even Chance|About even|Unlikely|Highly Unlikely|Almost No Chance|WEP\s*:)\b/i;
const ADMIRALTY_RE = /(^|[\s|`(])([A-F][1-6])([\s|`)]|$)/;
const BLUF_RE = /\bBLUF\s*[:.]/i;
const READER_BLOCK_RE =
/^##+\s+(?:[^\n]*?)?(Reader|For Citizens|What This Means|Reader Briefing|Citizen Briefing|Newsroom)/im;
const SAT_LIST_RE = /(?:^|\n)\s*(?:[-*+]|\d+\.)\s+[^\n]+/g; // crude bullet matcher
// MCP tool references — at least one must appear when sourceDiversityRequired
const MCP_TOOL_RE =
/\b(get_(?:procedures|adopted_texts|plenary_sessions|voting_records|meps|parliamentary_questions|speeches|committee_documents)|search_(?:documents|code|issues|repositories)|analyze_(?:voting_patterns|coalition_dynamics|country_delegation)|semantic_(?:issues_search|issue_similarity_search)|monitor_legislative_pipeline|track_legislation|track_mep_attendance|generate_political_landscape|early_warning_system|correlate_intelligence)\b/;
const IMF_SOURCE_FIELD_RE =
/^\|\s*\*\*IMF Source\*\*\s*\|\s*`?([^`|\]]+?)`?\s*\|/im;
// Keep the proximity window wide enough for one short citation clause
// ("IMF WEO April 2026 reports Germany at 1.1%...") but narrow enough to
// avoid treating a generic methodology paragraph as a numeric IMF claim.
const IMF_FIGURE_CLAIM_RE =
/\bIMF\b[\s\S]{0,160}\b\d+(?:\.\d+)?\s*(?:%|pp|percentage points|GDP|EUR|USD|billion|trillion|million)/i;
// IMF-primary editorial policy: IMF is the sole authoritative source for
// economic / fiscal / monetary / trade / FDI / exchange-rate /
// banking-soundness claims inside economic-context.md. World Bank is
// used for non-economic domains. Two complementary detectors:
//
// 1. WB economic indicator codes — surface the offending SDMX-style
// identifier when an economic-context artifact still cites raw WB
// economic series (NY.GDP.*, FP.CPI.*, SL.UEM.*, GC.DOD.*, NE.EXP.*,
// NE.TRD.*, BX.KLT.*, NY.GNP.*, GC.TAX.*, NE.CON.GOVT.*).
// 2. WB economic prose claim — match "World Bank" within 120 chars of an
// economic noun (GDP, inflation, unemployment, fiscal balance, debt,
// trade, FDI, exchange rate). The window is intentionally narrow so
// a sentence like "World Bank WGI governance index" (legitimate
// non-economic domain) does not trigger.
//
// Both detectors deliberately exclude the narrative "Retired from WB
// (now IMF-primary…)" and "legacy WB economic codes (… retained for
// backward compatibility but MUST NOT…)" wording that appears in the
// methodology files themselves — those files are not validated as run
// artifacts. The detectors only run against `intelligence/economic-
// context.md` and only when the artifact is also flagged as making
// numeric IMF claims (i.e. the artifact actually carries economic
// content), see callers in `evaluateArtifact`.
const WB_ECONOMIC_INDICATOR_CODE_RE =
/\b(NY\.GDP\.[A-Z0-9.]+|NY\.GNP\.[A-Z0-9.]+|FP\.CPI\.[A-Z0-9.]+|SL\.UEM\.[A-Z0-9.]+|GC\.DOD\.[A-Z0-9.]+|GC\.TAX\.[A-Z0-9.]+|NE\.EXP\.[A-Z0-9.]+|NE\.IMP\.[A-Z0-9.]+|NE\.TRD\.[A-Z0-9.]+|NE\.CON\.GOVT\.[A-Z0-9.]+|BX\.KLT\.[A-Z0-9.]+|BN\.KLT\.[A-Z0-9.]+|FR\.INR\.[A-Z0-9.]+)\b/;
const WB_ECONOMIC_CLAIM_RE =
/\bWorld\s+Bank\b[\s\S]{0,120}\b(?:GDP(?:\s+growth|\s+per\s+capita)?|inflation|CPI|unemployment(?:\s+rate)?|fiscal\s+balance|primary\s+balance|government\s+debt|public\s+debt|current\s+account|trade(?:\s+balance)?|FDI|foreign\s+direct\s+investment|exchange\s+rate|REER|policy\s+rate|reserve\s+assets|capital\s+adequacy|NPL\s+ratio)\b/i;
// Bypass placeholder scan only on template-instruction blocks themselves —
// NOT on every artifact that happens to link to a methodology document.
// Matching `methodology` here would suppress placeholder detection for any
// artifact citing e.g. `political-risk-methodology.md` and let real
// `[AI_ANALYSIS_REQUIRED]` markers slip through.
const META_DOC_HINT_RE =
/(template-instructions|placeholder reference|TODO list of)/i;
/**
* Default fallback rules. The threshold JSON may override per-artifact for
* specific articleType × relativePath combinations. This is the floor when
* the JSON is silent.
*/
const DIAGRAM_DIRS = ['intelligence', 'classification', 'risk-scoring', 'threat-assessment'];
function usage(code = 2) {
const msg = [
'Usage: node scripts/validate-analysis-completeness.js <runDir> [--json] [--strict] [--min-lines N]',
'',
' <runDir> Path to analysis/daily/<date>/<run>/',
' --json Emit machine-readable JSON summary in addition to STAGE_C_GATE line',
' --strict Treat warnings (missing readerBlock, single-source) as RED',
' --min-lines N Override DEFAULT_MIN_LINES floor (only raises, never lowers)',
'',
'Examples:',
' npm run validate-analysis -- analysis/daily/2026-04-23/breaking-run-1776928781',
' node scripts/validate-analysis-completeness.js path/to/run --strict --json',
].join('\n');
process.stderr.write(`${msg}\n`);
process.exit(code);
}
function parseArgs(argv) {
const args = argv.slice(2);
if (args.length === 0) usage(2);
const opts = {
runDir: null,
json: false,
strict: false,
minLines: DEFAULT_MIN_LINES,
minLinesExplicit: false,
thresholdsPath: null,
};
for (let i = 0; i < args.length; i += 1) {
const a = args[i];
if (a === '--json') opts.json = true;
else if (a === '--strict') opts.strict = true;
else if (a === '--min-lines') {
const n = parseInt(args[i + 1], 10);
if (!Number.isFinite(n) || n < 1) usage(2);
// The flag may only RAISE the floor — never lower it below DEFAULT_MIN_LINES.
opts.minLines = Math.max(DEFAULT_MIN_LINES, n);
opts.minLinesExplicit = true;
i += 1;
} else if (a === '--thresholds') {
opts.thresholdsPath = args[i + 1];
if (!opts.thresholdsPath) usage(2);
i += 1;
} else if (a === '--help' || a === '-h') usage(0);
else if (!opts.runDir) opts.runDir = a;
else usage(2);
}
if (!opts.runDir) usage(2);
return opts;
}
function readJson(filePath) {
const raw = fs.readFileSync(filePath, 'utf8');
return JSON.parse(raw);
}
function safeReadJson(filePath) {
try {
return readJson(filePath);
} catch (err) {
return { __error: err.message };
}
}
function loadThresholds(customPath) {
const p = customPath
? path.resolve(ROOT, customPath)
: path.resolve(ROOT, 'analysis/methodologies/reference-quality-thresholds.json');
if (!fs.existsSync(p)) return null;
return readJson(p);
}
function countLines(content) {
if (!content) return 0;
return content.split(/\r?\n/).length;
}
function findPlaceholders(content) {
if (META_DOC_HINT_RE.test(content)) return [];
const hits = [];
for (const re of PLACEHOLDER_PATTERNS) {
const m = content.match(re);
if (m) hits.push(m[0]);
}
return hits;
}
function hasMermaid(content) {
return /(^|\n)```mermaid\s/i.test(content);
}
function listH2Sections(content) {
const out = [];
const re = /^##\s+(.+?)\s*$/gm;
let m;
while ((m = re.exec(content)) !== null) {
out.push(m[1].trim());
}
return out;
}
function sectionMatches(actualHeadings, requiredFragment) {
const needle = requiredFragment.toLowerCase();
return actualHeadings.some((h) => h.toLowerCase().includes(needle));
}
function checkRequiredSections(content, requiredSections) {
const headings = listH2Sections(content);
const missing = [];
for (const need of requiredSections) {
if (!sectionMatches(headings, need)) missing.push(need);
}
return missing;
}
function hasWepBand(content) {
return WEP_BAND_RE.test(content);
}
function hasAdmiraltyGrade(content) {
// Avoid trivial false positives — require the token on a line that mentions
// sources, evidence, citation, or admiralty, OR appears in a table row.
const lines = content.split(/\r?\n/);
for (const line of lines) {
if (!ADMIRALTY_RE.test(line)) continue;
if (
/admiralty|source|grade|reliability|credibility|evidence/i.test(line) ||
/^\s*\|/.test(line)
) {
return true;
}
}
return false;
}
function hasBluf(content) {
return BLUF_RE.test(content);
}
function countSatBullets(content) {
// Count bullet rows under a "SAT" / "Structured Analytic Techniques" section
const re = /(?:^|\n)#+\s*(?:§\s*\d+\s*[·.]?\s*)?(?:Structured Analytic Techniques|SATs Applied|SAT Catalog)[^\n]*\n([\s\S]*?)(?=\n#|\n*$)/i;
const m = content.match(re);
if (!m) return 0;
const block = m[1];
return (block.match(SAT_LIST_RE) || []).length;
}
function hasReaderBlock(content) {
return READER_BLOCK_RE.test(content);
}
function hasMcpToolReference(content) {
return MCP_TOOL_RE.test(content);
}
function isEconomicContextArtifact(relativePath) {
return relativePath.replace(/\\/g, '/').endsWith('economic-context.md');
}
function parseImfSourceField(content) {
const match = content.match(IMF_SOURCE_FIELD_RE);
if (!match) return null;
const raw = match[1].trim().toLowerCase();
if (raw.startsWith('live')) return 'live';
if (raw.startsWith('cache')) return 'cache';
if (raw.startsWith('knowledge-only')) return 'knowledge-only';
// Unknown value (including untouched template placeholders like
// "<live | cache | knowledge-only>") must not bypass the provenance gate.
return null;
}
function claimsImfFigures(content) {
return IMF_FIGURE_CLAIM_RE.test(content);
}
/**
* IMF-primary editorial policy.
*
* Detect WB economic-policy violations inside `intelligence/economic-
* context.md`:
*
* - Any WB economic indicator code (NY.GDP.*, FP.CPI.*, SL.UEM.*,
* GC.DOD.*, NE.EXP.*, NE.TRD.*, BX.KLT.*, NY.GNP.*, GC.TAX.*,
* NE.CON.GOVT.*, FR.INR.*) — these belong in IMF SDMX form (NGDP,
* PCPIPCH, LUR, GGXWDG_NGDP, BCA_NGDPD, …).
* - Any "World Bank … <economic noun>" prose claim within 120 chars
* (GDP, inflation, unemployment, fiscal balance, debt, trade, FDI,
* exchange rate, policy rate, banking soundness).
*
* The detector deliberately runs only on `intelligence/economic-
* context.md`. Other artifacts may legitimately reference WB for non-
* economic context (governance WGI, demographics, social, environment,
* defence-spending, agriculture, innovation, education, health) and
* the WB methodology files themselves describe legacy codes for
* backward-compatibility — neither path is validated here.
*
* Returns `{ codes, prose }` arrays of offending excerpts. Empty arrays
* mean clean.
*/
function detectWorldBankEconomicViolations(content) {
// Use matchAll() so callers get every offending excerpt, not just the
// first hit — an artifact that cites several WB economic series
// ("NY.GDP.MKTP.KD.ZG and FP.CPI.TOTL.ZG and SL.UEM.TOTL.ZS") must
// surface all three to the editor in a single Stage-C pass.
const codes = [];
const codeRe = new RegExp(WB_ECONOMIC_INDICATOR_CODE_RE.source, 'gi');
for (const m of content.matchAll(codeRe)) {
codes.push(m[1]);
}
const prose = [];
const proseRe = new RegExp(WB_ECONOMIC_CLAIM_RE.source, 'gi');
for (const m of content.matchAll(proseRe)) {
prose.push(m[0].replace(/\s+/g, ' ').trim().slice(0, 100));
}
return { codes, prose };
}
// Stage C IMF evidence gate. The probe always writes a summary JSON even
// when `available:false`, so a generic "any .json file" check is insufficient
// — it would let a failed probe satisfy the gate. Require:
// 1. At least one canonical WEO evidence file (`weo-*.json`) that is
// non-empty, AND
// 2. If `imf-probe-summary.json` is present, it must report
// `available:true` (the probe writes `available:false` when the live
// fetch failed and no cache was hit).
function hasImfCacheJson(runDir) {
const cacheDir = path.join(runDir, 'cache', 'imf');
let entries;
try {
entries = fs.readdirSync(cacheDir, { withFileTypes: true });
} catch {
return false;
}
const hasWeoEvidence = entries.some((entry) => {
if (
!entry.isFile() ||
!entry.name.startsWith('weo-') ||
!entry.name.endsWith('.json')
) {
return false;
}
try {
return fs.statSync(path.join(cacheDir, entry.name)).size > 0;
} catch {
return false;
}
});
if (!hasWeoEvidence) return false;
const summaryPath = path.join(cacheDir, 'imf-probe-summary.json');
try {
const summary = JSON.parse(fs.readFileSync(summaryPath, 'utf8'));
if (summary && summary.available === false) return false;
} catch {
// No summary, unreadable, or malformed — fall back to the WEO evidence
// check above. The summary is best-effort additional confirmation.
}
return true;
}
function dirOfArtifact(relativePath) {
const norm = relativePath.replace(/\\/g, '/');
const idx = norm.indexOf('/');
return idx === -1 ? '' : norm.slice(0, idx);
}
function isDiagramRequired(relativePath, mermaidRequiredList) {
if (mermaidRequiredList && mermaidRequiredList.includes(relativePath)) return true;
const dir = dirOfArtifact(relativePath);
return DIAGRAM_DIRS.includes(dir);
}
/**
* Walk run directory, collecting every .md artifact path relative to runDir.
* Skips data/, runs/, pass1/, and the article.* root files.
*/
function walkArtifacts(runDir) {
const out = [];
const skipDirs = new Set(['data', 'runs', 'pass1']);
function walk(dir, rel) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
const abs = path.join(dir, entry.name);
const childRel = rel ? `${rel}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
if (skipDirs.has(entry.name)) continue;
walk(abs, childRel);
continue;
}
if (!entry.isFile()) continue;
if (!entry.name.endsWith('.md')) continue;
// skip article.md / article.<lang>.md at root + README
if (
rel === ''
&& (
entry.name.toLowerCase() === 'article.md'
|| /^article\./i.test(entry.name)
)
) continue;
if (entry.name.toLowerCase() === 'readme.md') continue;
out.push(childRel);
}
}
walk(runDir, '');
return out.sort();
}
function validateArtifact({
runDir,
relativePath,
rules,
options,
dataModeReduction = 1.0,
}) {
const abs = path.join(runDir, relativePath);
const result = {
relativePath,
exists: false,
lines: 0,
minLines: options.minLines,
issues: [],
warnings: [],
mermaid: false,
placeholders: [],
};
if (!fs.existsSync(abs)) {
result.issues.push('missing');
return result;
}
const content = fs.readFileSync(abs, 'utf8');
result.exists = true;
result.lines = countLines(content);
const perFloor = rules.perArtifactFloors?.[relativePath] ?? null;
// dataMode reduction applies to per-artifact floors AND the default floor,
// but NOT to the CLI-provided --min-lines value. This preserves the contract
// that --min-lines can only raise floors, never lower them.
const baseFloor = perFloor != null ? perFloor : DEFAULT_MIN_LINES;
const reducedFloor = Math.max(1, Math.floor(baseFloor * dataModeReduction));
// When --min-lines is explicitly set, it acts as a hard minimum that the
// reduction cannot breach. When not set, use the reduced floor directly.
result.minLines = options.minLinesExplicit
? Math.max(options.minLines, reducedFloor)
: reducedFloor;
if (result.lines < result.minLines) {
result.issues.push(
`short:${result.lines}<${result.minLines}`,
);
}
const placeholders = findPlaceholders(content);
if (placeholders.length > 0) {
result.placeholders = placeholders;
result.issues.push(`placeholders:${placeholders.length}`);
}
if (isDiagramRequired(relativePath, rules.mermaidRequired)) {
result.mermaid = hasMermaid(content);
if (!result.mermaid) {
result.issues.push('mermaid:missing');
}
} else {
result.mermaid = hasMermaid(content);
}
const requiredSections = rules.requiredSections?.[relativePath];
if (Array.isArray(requiredSections) && requiredSections.length > 0) {
const missingSections = checkRequiredSections(content, requiredSections);
if (missingSections.length > 0) {
result.issues.push(
`sections-missing:${missingSections.map((s) => s.replace(/[,\s]/g, '_')).join(',')}`,
);
}
}
if (rules.wepBandRequired?.includes(relativePath) && !hasWepBand(content)) {
result.issues.push('wep:missing');
}
if (
rules.admiraltyGradeRequired?.includes(relativePath) &&
!hasAdmiraltyGrade(content)
) {
result.issues.push('admiralty:missing');
}
if (rules.icd203BlufRequired?.includes(relativePath) && !hasBluf(content)) {
result.issues.push('bluf:missing');
}
if (rules.satDocumentationRequired?.includes(relativePath)) {
const sats = countSatBullets(content);
if (sats < 10) {
result.issues.push(`sat:${sats}<10`);
}
}
if (rules.readerBlockRequired?.includes(relativePath) && !hasReaderBlock(content)) {
if (options.strict) result.issues.push('reader-block:missing');
else result.warnings.push('reader-block:missing');
}
if (
rules.sourceDiversityRequired?.includes(relativePath) &&
!hasSourceDiversityEvidence(content)
) {
if (options.strict) result.issues.push('source-diversity:no-evidence-or-mcp-ref');
else result.warnings.push('source-diversity:no-evidence-or-mcp-ref');
}
if (isEconomicContextArtifact(relativePath) && claimsImfFigures(content)) {
const imfSource = parseImfSourceField(content);
if (!imfSource) {
result.issues.push('imf-source:missing');
} else if (imfSource === 'knowledge-only') {
result.issues.push('imf-source:knowledge-only');
} else if ((imfSource === 'live' || imfSource === 'cache') && !hasImfCacheJson(runDir)) {
result.issues.push('imf-cache:missing');
}
}
// IMF-primary editorial policy: economic-context.md must not
// cite World Bank for economic claims regardless of whether IMF prose
// is also present. Run on every economic-context artifact (not gated
// on claimsImfFigures) so an article that drops IMF entirely and
// tries to satisfy economic context with WB alone is caught.
if (isEconomicContextArtifact(relativePath)) {
const { codes: wbCodes, prose: wbProse } =
detectWorldBankEconomicViolations(content);
// Surface every offending code (de-duplicated to keep the issue
// list concise when the same series is cited many times in one
// artifact). Stage-C editors get the full picture in one pass.
for (const code of [...new Set(wbCodes)]) {
result.issues.push(`economic-context:wb-economic-code:${code}`);
}
if (wbProse.length > 0) {
result.issues.push('economic-context:wb-economic-claim');
}
}
return result;
}
/**
* Detect a markdown table with a Source / Evidence / Reference header column.
* A v2.0 template's "Data Sources & Provenance" section satisfies this.
*/
function hasEvidenceTableRow(content) {
const lines = content.split(/\r?\n/);
const separatorPattern = /^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)+\|?$/;
const headerPattern = /\|\s*(source|evidence|reference)\s*\|/i;
for (let i = 0; i < lines.length - 2; i += 1) {
const headerLine = lines[i].trim();
const separatorLine = lines[i + 1].trim();
const dataLine = lines[i + 2].trim();
if (
headerPattern.test(headerLine) &&
separatorPattern.test(separatorLine) &&
/^\|.*\|$/.test(dataLine)
) {
return true;
}
}
return false;
}
function hasSourceDiversityEvidence(content) {
return hasEvidenceTableRow(content) || hasMcpToolReference(content);
}
function hasOpenForwardStatementItems(runDir) {
const openJsonPath = path.join(runDir, 'data', 'forward-statements-open.json');
if (!fs.existsSync(openJsonPath)) return false;
const openRaw = fs.readFileSync(openJsonPath, 'utf8').trim();
if (!openRaw) return false;
try {
const openItems = JSON.parse(openRaw);
if (Array.isArray(openItems)) return openItems.length > 0;
// Valid JSON but unexpected shape — treat any non-empty file as open data
// so the carried-forward section check cannot be silently bypassed.
return true;
} catch {
// Malformed JSON — treat as non-empty to force the check.
return true;
}
}
function validateForwardStatementsRegistryCoverage(runDir, articleType) {
// Determine if this article type requires forward-statements coverage.
// Registry-driven: any slug with forwardStatementsHorizonDays > 0 requires it.
// Legacy fallback: hardcoded list for types not in the registry.
const horizonCfg = getHorizonConfig(articleType);
const requiresForwardStatements = horizonCfg
? horizonCfg.forwardStatementsHorizonDays > 0
: ['week-ahead', 'month-ahead'].includes(articleType);
if (!requiresForwardStatements) return null;
if (!hasOpenForwardStatementItems(runDir)) return null;
const relativePath = 'intelligence/synthesis-summary.md';
const synthPath = path.join(runDir, relativePath);
if (!fs.existsSync(synthPath)) return null;
const synthContent = fs.readFileSync(synthPath, 'utf8');
const hasCarriedSection = /##[^#\n]*carried[-\s]forward\s+forward\s+statements/i.test(synthContent);
if (hasCarriedSection) return null;
return {
relativePath,
exists: true,
lines: countLines(synthContent),
minLines: 0,
issues: ['forward-registry:missing-carried-forward-section'],
warnings: [],
mermaid: hasMermaid(synthContent),
placeholders: [],
};
}
function mergeUnique(left, right) {
return [...new Set([...(left || []), ...(right || [])])];
}
function mergeSyntheticResult(results, syntheticResult) {
if (!syntheticResult) return;
const existingResultIndex = results.findIndex(
(result) => result.relativePath === syntheticResult.relativePath,
);
if (existingResultIndex >= 0) {
const existingResult = results[existingResultIndex];
results[existingResultIndex] = {
...existingResult,
issues: mergeUnique(existingResult.issues, syntheticResult.issues),
warnings: mergeUnique(existingResult.warnings, syntheticResult.warnings),
};
return;
}
results.push(syntheticResult);
}
/**
* Return the portion of a scenario-forecast artifact that should contribute
* to the scenario-count gate.
*
* Worked examples in the template may contain `### Scenario ...` headings
* that must not satisfy the minimum authored-scenarios requirement, so
* everything from the first `## ... Worked example` H2 onwards is excluded.
*/
function getScenarioCountableContent(content) {
const workedExampleHeader = /^##\s+.*Worked example\b.*$/im;
const match = workedExampleHeader.exec(content);
if (!match || typeof match.index !== 'number') {
return content;
}
return content.slice(0, match.index);
}
/**
* Count the number of scenario headings in a scenario-forecast artifact.
* Matches authored `### Scenario N:` and `### Scenario N —` patterns and
* also supports hyphen-separated alphanumeric identifiers such as `A-24`.
* Underscore-containing identifiers are still excluded to avoid false
* positives. Headings in the worked-example section are ignored.
*/
function countScenarios(content) {
const countableContent = getScenarioCountableContent(content);
// Match "### Scenario 1:", "### Scenario A —", or "### Scenario A-24 —"
// while rejecting underscore-containing identifiers.
const re = /^###\s+Scenario\s+[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*\s*[:—]/gm;
const matches = countableContent.match(re);
return matches ? matches.length : 0;
}
/**
* Validate the long-horizon scenario-count gate.
*
* When the article type is in `longHorizonScenarioGate.articleTypes`,
* `intelligence/scenario-forecast.md` MUST contain at least
* `longHorizonScenarioGate.minScenarios` scenario headings.
* Returns a synthetic result object if the gate fires, or null if it passes.
*/
function validateLongHorizonScenarioGate(runDir, rules) {
if (!rules.longHorizonScenarioGate) return null;
const { artifact, minScenarios } = rules.longHorizonScenarioGate;
// Reject absolute paths or path-traversal segments to prevent reading
// arbitrary files outside runDir.
if (path.isAbsolute(artifact) || artifact.includes('..')) {
throw new Error(
`long-horizon-scenario-gate:invalid-config artifact="${artifact}" ` +
'must be a relative path without ".." segments.'
);
}
const absPath = path.resolve(runDir, artifact);
if (!absPath.startsWith(path.resolve(runDir) + path.sep)) {
throw new Error(
`long-horizon-scenario-gate:invalid-config artifact="${artifact}" ` +
'resolves outside runDir.'
);
}
if (!fs.existsSync(absPath)) return null; // already caught as missing artifact
const content = fs.readFileSync(absPath, 'utf8');
const count = countScenarios(content);
if (count >= minScenarios) return null; // gate passes
return {
relativePath: artifact,
exists: true,
lines: countLines(content),
minLines: 0,
issues: [`long-horizon-scenario-count:${count}<${minScenarios}`],
warnings: [],
mermaid: hasMermaid(content),
placeholders: [],
};
}
function buildRules(thresholdsJson, articleType) {
const empty = {
perArtifactFloors: {},
mermaidRequired: [],
requiredSections: {},
wepBandRequired: [],
admiraltyGradeRequired: [],
icd203BlufRequired: [],
satDocumentationRequired: [],
readerBlockRequired: [],
sourceDiversityRequired: [],
longHorizonScenarioGate: null,
};
if (!thresholdsJson) return empty;
const perArtifactFloors = thresholdsJson.thresholds?.[articleType] || {};
const tradecraft = thresholdsJson.tradecraftQualitySignals || {};
const structural = thresholdsJson.structuralRequirements || {};
// Load long-horizon scenario gate config from JSON if present.
const lhGateCfg = structural.longHorizonScenarioGate || null;
let longHorizonScenarioGate = null;
if (
lhGateCfg &&
Array.isArray(lhGateCfg.articleTypes) &&
lhGateCfg.articleTypes.includes(articleType)
) {
// Both artifact and minScenarios are required fields — do not silently
// default them; a malformed config must fail Stage C instead of bypassing
// the gate for targeted article types.
const hasValidArtifact =
typeof lhGateCfg.artifact === 'string' && lhGateCfg.artifact.trim().length > 0;
const hasValidMinScenarios =
typeof lhGateCfg.minScenarios === 'number' && lhGateCfg.minScenarios > 0;
if (!hasValidArtifact || !hasValidMinScenarios) {
throw new Error(
`long-horizon-scenario-gate:invalid-config articleType=${articleType} ` +
'structuralRequirements.longHorizonScenarioGate must define a non-empty ' +
'`artifact` and a positive numeric `minScenarios` for targeted article types.',
);
}
longHorizonScenarioGate = {
artifact: lhGateCfg.artifact.trim(),
minScenarios: lhGateCfg.minScenarios,
};
}
return {
perArtifactFloors,
mermaidRequired: structural.mermaidRequired || [],
requiredSections: structural.requiredSections || {},
wepBandRequired: tradecraft.wepBandRequired || [],
admiraltyGradeRequired: tradecraft.admiraltyGradeRequired || [],
icd203BlufRequired: tradecraft.icd203BlufRequired || [],
satDocumentationRequired: tradecraft.satDocumentationRequired || [],
readerBlockRequired: structural.readerBlockRequired || [],
sourceDiversityRequired: structural.sourceDiversityRequired || [],
longHorizonScenarioGate,
};
}
function listMandatoryArtifacts(rules, manifestArtifacts, articleType) {
// Mandatory artifacts are determined as follows:
// - If the slug is in the article-horizons registry → use registry's
// mandatoryArtifacts[] as the primary set (source of truth), unioned
// with manifest.files.* entries.
// - If the slug is NOT in the registry (legacy / unknown) → fall back to
// the old behavior: threshold keys ∪ manifest.files.*.
const set = new Set();
const horizonCfg = getHorizonConfig(articleType);
if (horizonCfg) {
// Registry-driven: use mandatoryArtifacts from the registry
for (const a of horizonCfg.mandatoryArtifacts) set.add(a);
} else {
// Legacy fallback: threshold keys serve as mandatory list
for (const k of Object.keys(rules.perArtifactFloors || {})) set.add(k);
}
// Always include manifest entries (agent-declared artifacts)
for (const a of manifestArtifacts) set.add(a);
return Array.from(set).sort();
}
function flattenManifestArtifacts(manifest) {
const out = [];
const files = manifest?.files;
if (!files || typeof files !== 'object') return out;
for (const v of Object.values(files)) {
if (!Array.isArray(v)) continue;
for (const entry of v) {
if (typeof entry === 'string') out.push(entry);
else if (entry && typeof entry.path === 'string') out.push(entry.path);
}
}
return Array.from(new Set(out));
}
function summarize(results) {
let missing = 0;
let short = 0;
let placeholders = 0;
let mermaidMissing = 0;
let other = 0;
for (const r of results) {
if (!r.exists) {
missing += 1;
continue;
}
// Count placeholders exactly once per artifact, regardless of how many
// issue strings reference them — the artifact owns the placeholders array.
placeholders += (r.placeholders?.length ?? 0);
let counted = false;
for (const issue of r.issues) {
if (issue.startsWith('short:')) {
short += 1;
counted = true;
} else if (issue.startsWith('placeholders:')) {
// Already counted above; just mark that we accounted for this issue
// string so it doesn't fall through to `other`.
counted = true;
} else if (issue === 'mermaid:missing') {
mermaidMissing += 1;
counted = true;
}
}
if (!counted && r.issues.length > 0) other += r.issues.length;
}
const totalIssues = results.reduce((s, r) => s + r.issues.length, 0);
const totalLines = results.reduce((s, r) => s + (r.lines || 0), 0);
return { missing, short, placeholders, mermaidMissing, other, totalIssues, totalLines };
}
function main() {
const opts = parseArgs(process.argv);
const runDir = path.resolve(ROOT, opts.runDir);
if (!fs.existsSync(runDir) || !fs.statSync(runDir).isDirectory()) {
process.stderr.write(`error: runDir does not exist or is not a directory: ${runDir}\n`);
process.exit(2);
}
const manifestPath = path.join(runDir, 'manifest.json');
if (!fs.existsSync(manifestPath)) {
process.stderr.write(`error: missing manifest.json at ${manifestPath}\n`);
process.stdout.write(
`STAGE_C_GATE: RED articleType=unknown missing=1 short=0 placeholders=0\n`,
);
process.exit(1);
}
const manifest = safeReadJson(manifestPath);
if (manifest.__error) {
process.stderr.write(`error: cannot parse manifest.json: ${manifest.__error}\n`);
process.stdout.write(
`STAGE_C_GATE: RED articleType=unknown missing=1 short=0 placeholders=0\n`,
);
process.exit(1);
}
const articleType = manifest.articleType || manifest.article_type || 'unknown';
if (articleType === 'unknown') {
process.stderr.write(
'warning: manifest.json missing top-level articleType (Rule 6)\n',
);
}
// ── Data-mode threshold adjustment (§dataMode) ────────────────────────
// When manifest.dataMode declares a degraded data availability state,
// the validator applies a line-floor reduction factor so that structurally
// constrained runs (missing full text, IMF unavailable, roll-call lag)
// can still pass Stage C without inflating thresholds that cannot be met
// with the available data. The reduction ONLY applies to line floors —
// structural requirements (mermaid, WEP, Admiralty, SATs) remain unchanged.
const dataMode = manifest.dataMode || 'full';
const dataModeReduction = DATA_MODE_REDUCTION[dataMode];
if (dataModeReduction === undefined) {
process.stderr.write(
`warning: manifest.dataMode="${dataMode}" is not a recognized value ` +
`(expected: ${Object.keys(DATA_MODE_REDUCTION).join(', ')}). Treating as "full".\n`,
);
}
const effectiveReduction = dataModeReduction ?? 1.0;
if (dataMode !== 'full' && dataModeReduction !== undefined) {
process.stderr.write(
`info: dataMode="${dataMode}" — applying ${Math.round((1 - effectiveReduction) * 100)}% line-floor reduction\n`,
);
}
const thresholdsJson = loadThresholds(opts.thresholdsPath);
let rules;
try {
rules = buildRules(thresholdsJson, articleType);
} catch (err) {
process.stderr.write(`error: ${err.message}\n`);
process.stdout.write(
`STAGE_C_GATE: RED articleType=${articleType} missing=0 short=0 placeholders=0\n`,
);
process.exit(1);
}
const manifestArtifacts = flattenManifestArtifacts(manifest);
const onDisk = walkArtifacts(runDir);
const orphans = onDisk.filter((p) => !manifestArtifacts.includes(p));
const mandatory = listMandatoryArtifacts(rules, manifestArtifacts, articleType);