euparliamentmonitor 0.8.35 → 0.8.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "euparliamentmonitor",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.37",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "European Parliament Intelligence Platform - Monitor political activity with systematic transparency",
|
|
6
6
|
"main": "scripts/index.js",
|
|
@@ -68,6 +68,7 @@
|
|
|
68
68
|
"retrofit-analysis": "npx tsx src/utils/retrofit-analysis-links.ts",
|
|
69
69
|
"validate-articles": "npx tsx src/utils/validate-articles.ts",
|
|
70
70
|
"validate-articles:strict": "npx tsx src/utils/validate-articles.ts --strict",
|
|
71
|
+
"validate-analysis": "npx tsx src/utils/validate-analysis-completeness.ts",
|
|
71
72
|
"validate-ep-api": "npx tsx src/utils/validate-ep-api.ts",
|
|
72
73
|
"htmlhint": "sh -c 'htmlhint *.html; set -- news/*.html; if [ -e \"$1\" ]; then htmlhint \"$@\"; else echo \"No news/*.html files to lint\"; fi'",
|
|
73
74
|
"serve": "python3 -m http.server 8080",
|
|
@@ -0,0 +1,665 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
/**
|
|
4
|
+
* @module Utils/ValidateAnalysisCompleteness
|
|
5
|
+
* @description Pre-article-generation blocking gate that enforces
|
|
6
|
+
* `analysis/methodologies/ai-driven-analysis-guide.md` §Reference-Quality Depth
|
|
7
|
+
* Requirements and Rule 19 (Mandatory Pre-Flight Analysis Reading).
|
|
8
|
+
*
|
|
9
|
+
* This validator is the hard precondition that agentic news workflows MUST pass
|
|
10
|
+
* before invoking any article generator. It verifies that the analysis run
|
|
11
|
+
* directory contains the mandatory intelligence artifacts with sufficient depth,
|
|
12
|
+
* no placeholder markers, and a well-formed `manifest.json` listing every
|
|
13
|
+
* artifact under `files.*`.
|
|
14
|
+
*
|
|
15
|
+
* Exit codes:
|
|
16
|
+
* - 0 — all mandatory artifacts present, each ≥ `--min-lines` (default 30),
|
|
17
|
+
* no placeholder markers, manifest lists every on-disk artifact.
|
|
18
|
+
* - 1 — one or more mandatory artifacts missing, too short, contain
|
|
19
|
+
* placeholder markers, or manifest omits an on-disk artifact.
|
|
20
|
+
* - 2 — usage error (missing `--analysis-dir`, unreadable directory, invalid
|
|
21
|
+
* `manifest.json`, etc.).
|
|
22
|
+
*
|
|
23
|
+
* Usage:
|
|
24
|
+
* npx tsx src/utils/validate-analysis-completeness.ts --analysis-dir=analysis/daily/2026-04-18/breaking-run184
|
|
25
|
+
* npx tsx src/utils/validate-analysis-completeness.ts --analysis-dir=<dir> --article-type=week-in-review
|
|
26
|
+
* npx tsx src/utils/validate-analysis-completeness.ts --analysis-dir=<dir> --json
|
|
27
|
+
*/
|
|
28
|
+
import fs from 'node:fs';
|
|
29
|
+
import path from 'node:path';
|
|
30
|
+
import { PROJECT_ROOT } from '../constants/config.js';
|
|
31
|
+
// ─── Types ────────────────────────────────────────────────────────────────────
|
|
32
|
+
/** Minimum line count below which an artifact is considered a stub */
|
|
33
|
+
const DEFAULT_MIN_LINES = 30;
|
|
34
|
+
/**
|
|
35
|
+
* Load the Rule 22 per-artifact threshold catalogue for a given article type.
|
|
36
|
+
*
|
|
37
|
+
* Returns a `Map<relativePath, minLines>` containing every per-file floor
|
|
38
|
+
* defined under `thresholds.<articleType>` in
|
|
39
|
+
* `analysis/methodologies/reference-quality-thresholds.json`. When the
|
|
40
|
+
* catalogue file is missing, unreadable, malformed, or lacks an entry for the
|
|
41
|
+
* article type, an empty map is returned and the caller's flat
|
|
42
|
+
* `DEFAULT_MIN_LINES` floor applies to every artifact.
|
|
43
|
+
*
|
|
44
|
+
* This load is deliberately tolerant: a missing catalogue must not break
|
|
45
|
+
* existing article types whose depth is still enforced only by the flat floor.
|
|
46
|
+
*
|
|
47
|
+
* @param articleType - Article category slug (e.g. `breaking`).
|
|
48
|
+
* @param overrideFile - Optional absolute path to a thresholds JSON file,
|
|
49
|
+
* overriding the default `THRESHOLDS_FILE`. Intended for
|
|
50
|
+
* tests that need fixture thresholds without touching the
|
|
51
|
+
* repo-wide catalogue.
|
|
52
|
+
* @returns Map from `relativePath` → per-file `minLines` threshold.
|
|
53
|
+
*/
|
|
54
|
+
function loadPerArtifactThresholds(articleType, overrideFile) {
|
|
55
|
+
// `overrideFile` may be absolute or relative. Relative paths are resolved
|
|
56
|
+
// against `PROJECT_ROOT` (matching how `--analysis-dir` is resolved) so that
|
|
57
|
+
// callers invoking the CLI from any working directory get consistent
|
|
58
|
+
// behaviour; otherwise the file is silently treated as missing and Rule 22
|
|
59
|
+
// floors fall back to the flat `--min-lines` value.
|
|
60
|
+
let file;
|
|
61
|
+
if (overrideFile === undefined) {
|
|
62
|
+
file = THRESHOLDS_FILE;
|
|
63
|
+
}
|
|
64
|
+
else if (path.isAbsolute(overrideFile)) {
|
|
65
|
+
file = overrideFile;
|
|
66
|
+
}
|
|
67
|
+
else {
|
|
68
|
+
file = path.join(PROJECT_ROOT, overrideFile);
|
|
69
|
+
}
|
|
70
|
+
if (!fs.existsSync(file))
|
|
71
|
+
return new Map();
|
|
72
|
+
let parsed;
|
|
73
|
+
try {
|
|
74
|
+
parsed = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
return new Map();
|
|
78
|
+
}
|
|
79
|
+
const entry = parsed.thresholds?.[articleType];
|
|
80
|
+
if (!entry || typeof entry !== 'object')
|
|
81
|
+
return new Map();
|
|
82
|
+
const result = new Map();
|
|
83
|
+
for (const [rel, n] of Object.entries(entry)) {
|
|
84
|
+
if (typeof n === 'number' && Number.isFinite(n) && n > 0) {
|
|
85
|
+
result.set(rel, n);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Resolve the effective `minLines` floor for a specific artifact.
|
|
92
|
+
*
|
|
93
|
+
* When a Rule 22 per-artifact threshold is defined for the active
|
|
94
|
+
* `articleType`, the effective floor is `max(perArtifactFloor, flatFallback)`
|
|
95
|
+
* so `--min-lines` can raise (but never silently lower) a per-artifact floor.
|
|
96
|
+
* This keeps behaviour consistent between required-set artifacts and
|
|
97
|
+
* supplemental (manifest-listed) artifacts — both paths apply the same rule.
|
|
98
|
+
*
|
|
99
|
+
* @param relPath - Artifact path relative to the run directory.
|
|
100
|
+
* @param perArtifact - Per-artifact threshold map for the active article type.
|
|
101
|
+
* @param fallback - Flat floor supplied by the CLI (`--min-lines`, default
|
|
102
|
+
* `DEFAULT_MIN_LINES`). Used directly when no per-artifact
|
|
103
|
+
* entry exists; otherwise combined via `max` with the
|
|
104
|
+
* per-artifact entry.
|
|
105
|
+
* @returns Effective `minLines` threshold.
|
|
106
|
+
*/
|
|
107
|
+
function effectiveMinLines(relPath, perArtifact, fallback) {
|
|
108
|
+
const configured = perArtifact.get(relPath);
|
|
109
|
+
if (configured === undefined)
|
|
110
|
+
return fallback;
|
|
111
|
+
return Math.max(configured, fallback);
|
|
112
|
+
}
|
|
113
|
+
/** Placeholder markers that indicate an incomplete analysis artifact */
|
|
114
|
+
const PLACEHOLDER_MARKERS = [
|
|
115
|
+
'[AI_ANALYSIS_REQUIRED]',
|
|
116
|
+
'AI_ANALYSIS_PENDING',
|
|
117
|
+
'[TO BE FILLED BY AI AGENT]',
|
|
118
|
+
'[TBD]',
|
|
119
|
+
'TODO:',
|
|
120
|
+
];
|
|
121
|
+
/**
|
|
122
|
+
* Location of the Rule 22 per-artifact depth-floor catalogue.
|
|
123
|
+
* When present, per-artifact thresholds defined here override the flat
|
|
124
|
+
* `DEFAULT_MIN_LINES` floor for matching `articleType × relativePath` tuples.
|
|
125
|
+
*/
|
|
126
|
+
const THRESHOLDS_FILE = path.join(PROJECT_ROOT, 'analysis', 'methodologies', 'reference-quality-thresholds.json');
|
|
127
|
+
/**
|
|
128
|
+
* The seven reference-quality intelligence artifacts per
|
|
129
|
+
* `analysis/methodologies/ai-driven-analysis-guide.md` §Reference-Quality Depth
|
|
130
|
+
* Requirements (basis: breaking-run184).
|
|
131
|
+
*/
|
|
132
|
+
const REFERENCE_QUALITY_INTELLIGENCE = [
|
|
133
|
+
'intelligence/pestle-analysis.md',
|
|
134
|
+
'intelligence/stakeholder-map.md',
|
|
135
|
+
'intelligence/scenario-forecast.md',
|
|
136
|
+
'intelligence/threat-model.md',
|
|
137
|
+
'intelligence/historical-baseline.md',
|
|
138
|
+
'intelligence/economic-context.md',
|
|
139
|
+
'intelligence/wildcards-blackswans.md',
|
|
140
|
+
];
|
|
141
|
+
/**
|
|
142
|
+
* Artifacts required on top of the reference-quality seven.
|
|
143
|
+
* These provide the pre-flight entry point (analysis-index) and the
|
|
144
|
+
* composition layer (synthesis-summary) per Rule 19.
|
|
145
|
+
*/
|
|
146
|
+
const COMMON_REQUIRED = [
|
|
147
|
+
'intelligence/analysis-index.md',
|
|
148
|
+
'intelligence/synthesis-summary.md',
|
|
149
|
+
];
|
|
150
|
+
/**
|
|
151
|
+
* Per-article-type additional mandatory artifacts.
|
|
152
|
+
* Weekly / monthly reviews require a historical-baseline (already in the seven);
|
|
153
|
+
* breaking additionally requires coalition-dynamics and an MCP reliability audit
|
|
154
|
+
* during plenary-recess windows when API availability is degraded.
|
|
155
|
+
*/
|
|
156
|
+
const ARTICLE_TYPE_EXTRAS = {
|
|
157
|
+
breaking: ['intelligence/coalition-dynamics.md'],
|
|
158
|
+
'week-in-review': [],
|
|
159
|
+
'month-in-review': [],
|
|
160
|
+
'week-ahead': [],
|
|
161
|
+
'month-ahead': [],
|
|
162
|
+
'committee-reports': [],
|
|
163
|
+
motions: [],
|
|
164
|
+
propositions: [],
|
|
165
|
+
};
|
|
166
|
+
// ─── CLI parsing ──────────────────────────────────────────────────────────────
|
|
167
|
+
/**
|
|
168
|
+
* Apply a single CLI argument token to an in-progress options object.
|
|
169
|
+
*
|
|
170
|
+
* @param arg - The raw CLI token.
|
|
171
|
+
* @param opts - Mutable options being built.
|
|
172
|
+
* @returns `true` when the arg is recognised, `false` otherwise.
|
|
173
|
+
*/
|
|
174
|
+
function applyArg(arg, opts) {
|
|
175
|
+
if (arg.startsWith('--analysis-dir=')) {
|
|
176
|
+
opts.analysisDir = arg.slice('--analysis-dir='.length);
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
if (arg.startsWith('--article-type=')) {
|
|
180
|
+
opts.articleType = arg.slice('--article-type='.length);
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
if (arg.startsWith('--min-lines=')) {
|
|
184
|
+
const parsed = parseInt(arg.slice('--min-lines='.length), 10);
|
|
185
|
+
if (Number.isFinite(parsed) && parsed > 0)
|
|
186
|
+
opts.minLines = parsed;
|
|
187
|
+
return true;
|
|
188
|
+
}
|
|
189
|
+
if (arg.startsWith('--thresholds-file=')) {
|
|
190
|
+
opts.thresholdsFile = arg.slice('--thresholds-file='.length);
|
|
191
|
+
return true;
|
|
192
|
+
}
|
|
193
|
+
if (arg === '--json') {
|
|
194
|
+
opts.json = true;
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
if (arg === '--warn-only') {
|
|
198
|
+
opts.warnOnly = true;
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Parse command-line arguments into a `CliOptions` record.
|
|
205
|
+
*
|
|
206
|
+
* @param argv - CLI arguments excluding the `node` + script entries.
|
|
207
|
+
* @returns Parsed options; exits with code 2 if required args are missing.
|
|
208
|
+
*/
|
|
209
|
+
function parseArgs(argv) {
|
|
210
|
+
const opts = {
|
|
211
|
+
analysisDir: '',
|
|
212
|
+
minLines: DEFAULT_MIN_LINES,
|
|
213
|
+
json: false,
|
|
214
|
+
warnOnly: false,
|
|
215
|
+
};
|
|
216
|
+
for (const arg of argv) {
|
|
217
|
+
if (arg === '--help' || arg === '-h') {
|
|
218
|
+
printHelp();
|
|
219
|
+
process.exit(0);
|
|
220
|
+
}
|
|
221
|
+
applyArg(arg, opts);
|
|
222
|
+
}
|
|
223
|
+
if (!opts.analysisDir) {
|
|
224
|
+
console.error('❌ Missing required argument: --analysis-dir=<path>');
|
|
225
|
+
printHelp();
|
|
226
|
+
process.exit(2);
|
|
227
|
+
}
|
|
228
|
+
return opts;
|
|
229
|
+
}
|
|
230
|
+
function printHelp() {
|
|
231
|
+
console.log(`
|
|
232
|
+
validate-analysis-completeness — pre-article-generation blocking gate
|
|
233
|
+
|
|
234
|
+
Usage:
|
|
235
|
+
npx tsx src/utils/validate-analysis-completeness.ts \\
|
|
236
|
+
--analysis-dir=analysis/daily/<date>/<type>-run<id> \\
|
|
237
|
+
[--article-type=<slug>] \\
|
|
238
|
+
[--min-lines=30] \\
|
|
239
|
+
[--json] \\
|
|
240
|
+
[--warn-only]
|
|
241
|
+
|
|
242
|
+
Options:
|
|
243
|
+
--analysis-dir=<path> Run directory to validate (required).
|
|
244
|
+
Path is resolved relative to PROJECT_ROOT.
|
|
245
|
+
--article-type=<slug> Article category slug (breaking, week-in-review, …).
|
|
246
|
+
When omitted, inferred from manifest.json.
|
|
247
|
+
--min-lines=<n> Minimum line count per artifact (default 30).
|
|
248
|
+
Used as fallback when no Rule 22 per-artifact
|
|
249
|
+
threshold is defined for this article type × path.
|
|
250
|
+
--thresholds-file=<path> Override the Rule 22 thresholds catalogue (default:
|
|
251
|
+
analysis/methodologies/reference-quality-thresholds.json).
|
|
252
|
+
Primarily for tests.
|
|
253
|
+
--json Emit a JSON report on stdout instead of text.
|
|
254
|
+
--warn-only Exit 0 on validation failure (report only). Use for
|
|
255
|
+
local exploration; workflows MUST NOT pass this flag.
|
|
256
|
+
|
|
257
|
+
Exit codes:
|
|
258
|
+
0 = all mandatory artifacts present, no placeholders, manifest consistent
|
|
259
|
+
1 = validation failed
|
|
260
|
+
2 = usage error (missing args, unreadable dir, invalid manifest)
|
|
261
|
+
`);
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Extract all analysis file paths from the manifest's `files` field.
|
|
265
|
+
* Supports two shapes: nested `{ intelligence: [...] }` or flat `{ "path": "desc" }`.
|
|
266
|
+
*
|
|
267
|
+
* @param filesField - The `files` object from manifest.json.
|
|
268
|
+
* @returns Array of relative artifact paths listed in the manifest.
|
|
269
|
+
*/
|
|
270
|
+
function extractListedPaths(filesField) {
|
|
271
|
+
if (!filesField || typeof filesField !== 'object')
|
|
272
|
+
return [];
|
|
273
|
+
const allListed = [];
|
|
274
|
+
const firstValue = Object.values(filesField)[0];
|
|
275
|
+
if (Array.isArray(firstValue)) {
|
|
276
|
+
// Nested shape: { category: string[] }
|
|
277
|
+
for (const arr of Object.values(filesField)) {
|
|
278
|
+
if (!Array.isArray(arr))
|
|
279
|
+
continue;
|
|
280
|
+
for (const rel of arr) {
|
|
281
|
+
if (typeof rel === 'string')
|
|
282
|
+
allListed.push(rel);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
return allListed;
|
|
286
|
+
}
|
|
287
|
+
if (firstValue !== undefined) {
|
|
288
|
+
// Flat shape: { "path": "description" }
|
|
289
|
+
return Object.keys(filesField);
|
|
290
|
+
}
|
|
291
|
+
return allListed;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Load and parse `manifest.json` from a run directory, returning any schema
|
|
295
|
+
* errors and the set of listed artifact paths.
|
|
296
|
+
*
|
|
297
|
+
* @param runDir - Absolute path to the analysis run directory.
|
|
298
|
+
* @returns Parsed manifest, list of artifact paths, and any schema errors.
|
|
299
|
+
*/
|
|
300
|
+
function loadManifest(runDir) {
|
|
301
|
+
const manifestPath = path.join(runDir, 'manifest.json');
|
|
302
|
+
const errors = [];
|
|
303
|
+
if (!fs.existsSync(manifestPath)) {
|
|
304
|
+
return { raw: {}, allListedPaths: [], errors: ['manifest.json is missing'] };
|
|
305
|
+
}
|
|
306
|
+
let raw;
|
|
307
|
+
try {
|
|
308
|
+
const text = fs.readFileSync(manifestPath, 'utf-8');
|
|
309
|
+
raw = JSON.parse(text);
|
|
310
|
+
}
|
|
311
|
+
catch (err) {
|
|
312
|
+
return {
|
|
313
|
+
raw: {},
|
|
314
|
+
allListedPaths: [],
|
|
315
|
+
errors: [`manifest.json is not valid JSON: ${err.message}`],
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
if (!raw.articleType || typeof raw.articleType !== 'string') {
|
|
319
|
+
errors.push('manifest.json is missing top-level "articleType" (Rule 6)');
|
|
320
|
+
}
|
|
321
|
+
const filesField = raw.files;
|
|
322
|
+
if (!filesField || typeof filesField !== 'object') {
|
|
323
|
+
errors.push('manifest.json is missing "files" object');
|
|
324
|
+
return { raw, allListedPaths: [], errors };
|
|
325
|
+
}
|
|
326
|
+
return { raw, allListedPaths: extractListedPaths(filesField), errors };
|
|
327
|
+
}
|
|
328
|
+
// ─── Artifact inspection ─────────────────────────────────────────────────────
|
|
329
|
+
/**
|
|
330
|
+
* Read and inspect a single artifact, producing the data needed by the
|
|
331
|
+
* aggregate pass/fail logic in `countErrors` / `artifactIssues`.
|
|
332
|
+
*
|
|
333
|
+
* @param runDir - Absolute path to the analysis run directory.
|
|
334
|
+
* @param relPath - Path relative to `runDir` of the artifact to inspect.
|
|
335
|
+
* @param listedInManifest - Whether the artifact appears under `manifest.files.*`.
|
|
336
|
+
* @param minLines - Effective `minLines` floor (Rule 22 per-artifact threshold
|
|
337
|
+
* when defined for this path, or the flat fallback otherwise).
|
|
338
|
+
* @returns Presence, line count, placeholder findings, and manifest-listing flag.
|
|
339
|
+
*/
|
|
340
|
+
function inspectArtifact(runDir, relPath, listedInManifest, minLines) {
|
|
341
|
+
const abs = path.join(runDir, relPath);
|
|
342
|
+
if (!fs.existsSync(abs)) {
|
|
343
|
+
return {
|
|
344
|
+
relativePath: relPath,
|
|
345
|
+
present: false,
|
|
346
|
+
lineCount: 0,
|
|
347
|
+
minLines,
|
|
348
|
+
placeholdersFound: [],
|
|
349
|
+
listedInManifest,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
const text = fs.readFileSync(abs, 'utf-8');
|
|
353
|
+
const lines = text.split('\n');
|
|
354
|
+
const lineCount = lines.length;
|
|
355
|
+
const placeholders = findUnfilledPlaceholders(lines);
|
|
356
|
+
// NOTE: `lineCount < minLines` is intentionally not flagged here — the caller
|
|
357
|
+
// (`countErrors` / `artifactIssues`) is the single source of truth for
|
|
358
|
+
// short-file failures so the validator can report them with the correct
|
|
359
|
+
// formatting and exit semantics.
|
|
360
|
+
return {
|
|
361
|
+
relativePath: relPath,
|
|
362
|
+
present: true,
|
|
363
|
+
lineCount,
|
|
364
|
+
minLines,
|
|
365
|
+
placeholdersFound: placeholders,
|
|
366
|
+
listedInManifest,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Tests whether a given line is a meta-documentation reference to the placeholder
|
|
371
|
+
* marker (rather than a real unfilled slot). Table rows, negation sentences, and
|
|
372
|
+
* backtick-quoted marker names are considered documentation.
|
|
373
|
+
*
|
|
374
|
+
* @param raw - Raw line from the artifact file (with original indentation).
|
|
375
|
+
* @param trimmed - The same line after leading whitespace is stripped.
|
|
376
|
+
* @param marker - The placeholder marker being checked.
|
|
377
|
+
* @returns `true` when the line describes the marker rather than requiring it.
|
|
378
|
+
*/
|
|
379
|
+
function isMetaDocumentationLine(raw, trimmed, marker) {
|
|
380
|
+
if (trimmed.startsWith('|'))
|
|
381
|
+
return true;
|
|
382
|
+
if (/\b(zero|no|none|without|absent|replaced|replace every)\b/i.test(trimmed))
|
|
383
|
+
return true;
|
|
384
|
+
if (raw.includes('`' + marker + '`'))
|
|
385
|
+
return true;
|
|
386
|
+
return false;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Detect placeholder markers that represent an unfilled content slot, while
|
|
390
|
+
* ignoring lines where the marker is referenced in a meta-documentation context
|
|
391
|
+
* (e.g. "Zero [AI_ANALYSIS_REQUIRED] markers", table rows that document absence,
|
|
392
|
+
* or code fences quoting the marker for illustration).
|
|
393
|
+
*
|
|
394
|
+
* @param lines - Lines of the artifact file.
|
|
395
|
+
* @returns Sorted array of placeholder markers that were found as real slots.
|
|
396
|
+
*/
|
|
397
|
+
function findUnfilledPlaceholders(lines) {
|
|
398
|
+
const found = new Set();
|
|
399
|
+
let inCodeFence = false;
|
|
400
|
+
for (const raw of lines) {
|
|
401
|
+
const line = raw.trimStart();
|
|
402
|
+
if (line.startsWith('```')) {
|
|
403
|
+
inCodeFence = !inCodeFence;
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
if (inCodeFence)
|
|
407
|
+
continue;
|
|
408
|
+
for (const marker of PLACEHOLDER_MARKERS) {
|
|
409
|
+
if (!raw.includes(marker))
|
|
410
|
+
continue;
|
|
411
|
+
if (isMetaDocumentationLine(raw, line, marker))
|
|
412
|
+
continue;
|
|
413
|
+
found.add(marker);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
return Array.from(found).sort();
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* List all `.md` files directly inside `<runDir>/intelligence/`.
|
|
420
|
+
*
|
|
421
|
+
* @param runDir - Absolute path to the analysis run directory.
|
|
422
|
+
* @returns Array of paths relative to `runDir` (POSIX-style).
|
|
423
|
+
*/
|
|
424
|
+
function walkIntelligenceDir(runDir) {
|
|
425
|
+
const intelDir = path.join(runDir, 'intelligence');
|
|
426
|
+
if (!fs.existsSync(intelDir) || !fs.statSync(intelDir).isDirectory()) {
|
|
427
|
+
return [];
|
|
428
|
+
}
|
|
429
|
+
const out = [];
|
|
430
|
+
for (const entry of fs.readdirSync(intelDir)) {
|
|
431
|
+
if (entry.endsWith('.md'))
|
|
432
|
+
out.push(path.posix.join('intelligence', entry));
|
|
433
|
+
}
|
|
434
|
+
return out;
|
|
435
|
+
}
|
|
436
|
+
// ─── Validation orchestration ────────────────────────────────────────────────
|
|
437
|
+
/** Type-safe Map view of `ARTICLE_TYPE_EXTRAS` that avoids property-access injection. */
|
|
438
|
+
const ARTICLE_TYPE_EXTRAS_MAP = new Map(Object.entries(ARTICLE_TYPE_EXTRAS));
|
|
439
|
+
/**
|
|
440
|
+
* Compute the set of mandatory artifacts for a given article type.
|
|
441
|
+
*
|
|
442
|
+
* Combines the common `COMMON_REQUIRED` set, the seven reference-quality
|
|
443
|
+
* intelligence artifacts, and any article-type-specific extras.
|
|
444
|
+
*
|
|
445
|
+
* @param articleType - The article category slug (e.g. `breaking`).
|
|
446
|
+
* @returns Sorted list of required relative artifact paths.
|
|
447
|
+
*/
|
|
448
|
+
function computeRequired(articleType) {
|
|
449
|
+
const extras = ARTICLE_TYPE_EXTRAS_MAP.get(articleType) ?? [];
|
|
450
|
+
const set = new Set([...COMMON_REQUIRED, ...REFERENCE_QUALITY_INTELLIGENCE, ...extras]);
|
|
451
|
+
return Array.from(set).sort();
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Count how many artifact checks failed, combined with any manifest errors.
|
|
455
|
+
*
|
|
456
|
+
* Each check carries its own `minLines` threshold (Rule 22 per-artifact floor
|
|
457
|
+
* or the flat fallback), so no single `minLines` argument is needed here.
|
|
458
|
+
*
|
|
459
|
+
* @param checks - Per-artifact inspection results.
|
|
460
|
+
* @param manifestErrorCount - Number of manifest-level errors.
|
|
461
|
+
* @returns Total error count used for the pass/fail decision.
|
|
462
|
+
*/
|
|
463
|
+
function countErrors(checks, manifestErrorCount) {
|
|
464
|
+
let errorCount = manifestErrorCount;
|
|
465
|
+
for (const c of checks) {
|
|
466
|
+
if (!c.present)
|
|
467
|
+
errorCount++;
|
|
468
|
+
else if (c.lineCount < c.minLines)
|
|
469
|
+
errorCount++;
|
|
470
|
+
else if (c.placeholdersFound.length > 0)
|
|
471
|
+
errorCount++;
|
|
472
|
+
else if (!c.listedInManifest)
|
|
473
|
+
errorCount++;
|
|
474
|
+
}
|
|
475
|
+
return errorCount;
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Thrown by `validate()` for usage errors (missing/unreadable run directory).
|
|
479
|
+
* Carries the exit code that `main()` should use, so all `process.exit(…)`
|
|
480
|
+
* calls live in one place and the `validate()` function stays unit-testable.
|
|
481
|
+
*/
|
|
482
|
+
class ValidationUsageError extends Error {
|
|
483
|
+
exitCode;
|
|
484
|
+
constructor(message, exitCode = 2) {
|
|
485
|
+
super(message);
|
|
486
|
+
this.name = 'ValidationUsageError';
|
|
487
|
+
this.exitCode = exitCode;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Run the full validation pipeline for a given analysis run directory.
|
|
492
|
+
*
|
|
493
|
+
* @param options - Parsed CLI options.
|
|
494
|
+
* @returns Validation result with per-artifact checks and pass/fail flag.
|
|
495
|
+
* @throws {ValidationUsageError} When the analysis directory does not exist
|
|
496
|
+
* or is not a directory — the CLI entrypoint translates this into
|
|
497
|
+
* `process.exit(2)`.
|
|
498
|
+
*/
|
|
499
|
+
function validate(options) {
|
|
500
|
+
const absRunDir = path.isAbsolute(options.analysisDir)
|
|
501
|
+
? options.analysisDir
|
|
502
|
+
: path.join(PROJECT_ROOT, options.analysisDir);
|
|
503
|
+
if (!fs.existsSync(absRunDir) || !fs.statSync(absRunDir).isDirectory()) {
|
|
504
|
+
throw new ValidationUsageError(`Analysis directory not found or not a directory: ${absRunDir}`, 2);
|
|
505
|
+
}
|
|
506
|
+
const manifest = loadManifest(absRunDir);
|
|
507
|
+
const articleType = options.articleType ?? manifest.raw.articleType ?? 'unknown';
|
|
508
|
+
const required = computeRequired(articleType);
|
|
509
|
+
const listedSet = new Set(manifest.allListedPaths);
|
|
510
|
+
const perArtifactThresholds = loadPerArtifactThresholds(articleType, options.thresholdsFile);
|
|
511
|
+
const checks = required.map((rel) => inspectArtifact(absRunDir, rel, listedSet.has(rel), effectiveMinLines(rel, perArtifactThresholds, options.minLines)));
|
|
512
|
+
// Rule 22 supplemental enforcement: any manifest-listed file that has a
|
|
513
|
+
// per-artifact threshold entry but is NOT in the mandatory `required` set
|
|
514
|
+
// (e.g. `risk-scoring/*`, `documents/*`, `classification/*`) also has its
|
|
515
|
+
// depth floor enforced. This keeps `reference-quality-thresholds.json` and
|
|
516
|
+
// `.github/prompts/SHARED_PROMPT_PATTERNS.md §Per-Artifact Budgets` truthful
|
|
517
|
+
// about which files are machine-enforced.
|
|
518
|
+
const requiredSet = new Set(required);
|
|
519
|
+
const supplementalChecks = [];
|
|
520
|
+
for (const rel of perArtifactThresholds.keys()) {
|
|
521
|
+
if (requiredSet.has(rel))
|
|
522
|
+
continue;
|
|
523
|
+
if (!listedSet.has(rel))
|
|
524
|
+
continue;
|
|
525
|
+
supplementalChecks.push(inspectArtifact(absRunDir, rel, true, effectiveMinLines(rel, perArtifactThresholds, options.minLines)));
|
|
526
|
+
}
|
|
527
|
+
supplementalChecks.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
|
|
528
|
+
checks.push(...supplementalChecks);
|
|
529
|
+
const onDiskIntel = walkIntelligenceDir(absRunDir);
|
|
530
|
+
// O(1)-per-path lookup: build a lookup set that includes both required and
|
|
531
|
+
// supplemental-threshold artifacts so the orphan filter doesn't flag them.
|
|
532
|
+
const inspectedSet = new Set(checks.map((c) => c.relativePath));
|
|
533
|
+
const orphaned = onDiskIntel.filter((rel) => !listedSet.has(rel) && !inspectedSet.has(rel));
|
|
534
|
+
// Orphaned files are warnings, not errors (per Rule 6 "contamination risk"
|
|
535
|
+
// they're a signal but not a blocker — a second workflow may legitimately add files)
|
|
536
|
+
const errorCount = countErrors(checks, manifest.errors.length);
|
|
537
|
+
return {
|
|
538
|
+
analysisDir: absRunDir,
|
|
539
|
+
articleType,
|
|
540
|
+
required,
|
|
541
|
+
checks,
|
|
542
|
+
orphanedOnDisk: orphaned,
|
|
543
|
+
manifestValid: manifest.errors.length === 0,
|
|
544
|
+
manifestErrors: manifest.errors,
|
|
545
|
+
passed: errorCount === 0,
|
|
546
|
+
errorCount,
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
// ─── Reporting ────────────────────────────────────────────────────────────────
|
|
550
|
+
/**
|
|
551
|
+
* Build a list of issue labels for a single artifact check.
|
|
552
|
+
*
|
|
553
|
+
* Uses the per-check `minLines` (Rule 22 per-artifact floor or flat fallback).
|
|
554
|
+
*
|
|
555
|
+
* @param c - The artifact check result.
|
|
556
|
+
* @returns Array of short issue labels; empty if the artifact passes.
|
|
557
|
+
*/
|
|
558
|
+
function artifactIssues(c) {
|
|
559
|
+
if (!c.present)
|
|
560
|
+
return ['MISSING'];
|
|
561
|
+
const parts = [];
|
|
562
|
+
if (c.lineCount < c.minLines)
|
|
563
|
+
parts.push(`SHORT (${c.lineCount} < ${c.minLines} lines)`);
|
|
564
|
+
if (c.placeholdersFound.length > 0) {
|
|
565
|
+
parts.push(`PLACEHOLDERS (${c.placeholdersFound.join(', ')})`);
|
|
566
|
+
}
|
|
567
|
+
if (!c.listedInManifest)
|
|
568
|
+
parts.push('NOT_LISTED_IN_MANIFEST');
|
|
569
|
+
return parts;
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Print the header block of a text-mode report.
|
|
573
|
+
*
|
|
574
|
+
* @param result - Validation result.
|
|
575
|
+
* @param minLines - Flat fallback line floor (displayed as the default).
|
|
576
|
+
*/
|
|
577
|
+
function printHeader(result, minLines) {
|
|
578
|
+
console.log('━'.repeat(72));
|
|
579
|
+
console.log('🔍 Analysis Completeness Validator (Rule 19 + Rule 22 pre-flight gate)');
|
|
580
|
+
console.log('━'.repeat(72));
|
|
581
|
+
console.log(`📁 Run dir : ${path.relative(PROJECT_ROOT, result.analysisDir)}`);
|
|
582
|
+
console.log(`🏷️ Article type : ${result.articleType}`);
|
|
583
|
+
console.log(`📋 Required count : ${result.required.length}`);
|
|
584
|
+
console.log(`🧾 Min lines/file : ${minLines} (default) — per-artifact floors from Rule 22 thresholds`);
|
|
585
|
+
console.log('');
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Print the pass/fail footer of a text-mode report.
|
|
589
|
+
*
|
|
590
|
+
* @param result - Validation result.
|
|
591
|
+
*/
|
|
592
|
+
function printFooter(result) {
|
|
593
|
+
console.log('');
|
|
594
|
+
if (result.passed) {
|
|
595
|
+
console.log('✅ Pre-flight gate PASSED — article generation may proceed.');
|
|
596
|
+
}
|
|
597
|
+
else {
|
|
598
|
+
console.log(`❌ Pre-flight gate FAILED — ${result.errorCount} error(s). ` +
|
|
599
|
+
'Article generation MUST NOT proceed.');
|
|
600
|
+
console.log(' See analysis/methodologies/ai-driven-analysis-guide.md §Rule 19 / Rule 22 and');
|
|
601
|
+
console.log(' .github/prompts/SHARED_PROMPT_PATTERNS.md §Article Generation Pre-Flight.');
|
|
602
|
+
}
|
|
603
|
+
console.log('━'.repeat(72));
|
|
604
|
+
}
|
|
605
|
+
/**
|
|
606
|
+
* Render the full text-mode report to stdout.
|
|
607
|
+
*
|
|
608
|
+
* @param result - Validation result.
|
|
609
|
+
* @param minLines - Flat fallback line floor (per-artifact floors live on each check).
|
|
610
|
+
*/
|
|
611
|
+
function renderTextReport(result, minLines) {
|
|
612
|
+
printHeader(result, minLines);
|
|
613
|
+
if (!result.manifestValid) {
|
|
614
|
+
console.log('❌ Manifest errors:');
|
|
615
|
+
for (const err of result.manifestErrors)
|
|
616
|
+
console.log(` • ${err}`);
|
|
617
|
+
console.log('');
|
|
618
|
+
}
|
|
619
|
+
console.log('📊 Artifact checks:');
|
|
620
|
+
for (const c of result.checks) {
|
|
621
|
+
const issues = artifactIssues(c);
|
|
622
|
+
const status = issues.length === 0 ? '✅ ok' : `❌ ${issues.join('; ')}`;
|
|
623
|
+
const lineInfo = c.present ? ` (${c.lineCount}/${c.minLines} lines)` : '';
|
|
624
|
+
console.log(` ${status.padEnd(60)} ${c.relativePath}${lineInfo}`);
|
|
625
|
+
}
|
|
626
|
+
if (result.orphanedOnDisk.length > 0) {
|
|
627
|
+
console.log('');
|
|
628
|
+
console.log('⚠️ Intelligence files on disk not listed in manifest.files.*:');
|
|
629
|
+
for (const rel of result.orphanedOnDisk)
|
|
630
|
+
console.log(` • ${rel}`);
|
|
631
|
+
console.log(' → Update manifest.files.intelligence[] to include these');
|
|
632
|
+
console.log(' (or delete them if they are leftovers from a prior run).');
|
|
633
|
+
}
|
|
634
|
+
printFooter(result);
|
|
635
|
+
}
|
|
636
|
+
// ─── Main ─────────────────────────────────────────────────────────────────────
|
|
637
|
+
/**
|
|
638
|
+
* CLI entrypoint — parses args, runs validation, renders output, and owns
|
|
639
|
+
* every `process.exit(…)` decision for this module.
|
|
640
|
+
*/
|
|
641
|
+
function main() {
|
|
642
|
+
const options = parseArgs(process.argv.slice(2));
|
|
643
|
+
let result;
|
|
644
|
+
try {
|
|
645
|
+
result = validate(options);
|
|
646
|
+
}
|
|
647
|
+
catch (err) {
|
|
648
|
+
if (err instanceof ValidationUsageError) {
|
|
649
|
+
console.error(`❌ ${err.message}`);
|
|
650
|
+
process.exit(err.exitCode);
|
|
651
|
+
}
|
|
652
|
+
throw err;
|
|
653
|
+
}
|
|
654
|
+
if (options.json) {
|
|
655
|
+
console.log(JSON.stringify(result, null, 2));
|
|
656
|
+
}
|
|
657
|
+
else {
|
|
658
|
+
renderTextReport(result, options.minLines);
|
|
659
|
+
}
|
|
660
|
+
if (!result.passed && !options.warnOnly) {
|
|
661
|
+
process.exit(1);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
main();
|
|
665
|
+
//# sourceMappingURL=validate-analysis-completeness.js.map
|