All files / scripts/generate-news-enhanced config.ts

63.29% Statements 100/158
48.59% Branches 52/107
23.07% Functions 6/26
69.5% Lines 98/141

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                                        19x 19x       296x             19x       114x         19x 19x 19x 19x 19x 19x 19x     19x 19x 19x 19x     19x 19x         19x 19x         19x                 19x 19x 19x 19x 19x     19x   19x         19x 19x 19x 19x                     19x                         19x 19x 19x     19x     19x     19x     19x   19x 19x 19x                 19x             19x           19x       19x 19x           19x   19x       19x   19x           19x               19x   19x           19x     19x 19x 19x     19x   266x 266x   19x           19x 19x               19x 19x     19x     19x                             19x               19x                                   19x 19x 19x 19x 19x 19x           19x                   29x     6x 29x     29x 29x 29x 29x 2x 2x 2x     4x 4x 4x 4x             2x 29x   29x       19x 3x             19x              
/**
 * @module generate-news-enhanced/config
 * @description CLI argument parsing, language configuration, and shared state
 * for the enhanced news generation system.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { MCPClient } from '../mcp-client.js';
import type { Language } from '../types/language.js';
import type { GenerationStats } from '../types/article.js';
import type { BatchStatus } from './types.js';
 
/** Analysis depth levels for article generation */
export type AnalysisDepth = 'quick' | 'standard' | 'deep' | 'comprehensive';
 
const __filename: string = fileURLToPath(import.meta.url);
export const __dirname: string = path.dirname(__filename);
 
/** Extract YYYY-MM-DD from a Date, guaranteed non-undefined. */
export function toISODate(d: Date): string {
  return d.toISOString().slice(0, 10);
}
 
// ---------------------------------------------------------------------------
// CLI argument parsing
// ---------------------------------------------------------------------------
 
const args: string[] = process.argv.slice(2);
 
/** Extract the value after the first '=' from a CLI argument, or empty string if absent. */
function parseArgValue(arg: string | undefined): string {
  Eif (!arg) return '';
  const idx = arg.indexOf('=');
  return idx >= 0 ? arg.slice(idx + 1).trim() : '';
}
 
const typesArg: string | undefined = args.find(arg => arg.startsWith('--types='));
const languagesArg: string | undefined = args.find(arg => arg.startsWith('--languages='));
export const dryRunArg: boolean = args.includes('--dry-run');
const batchSizeArg: string | undefined = args.find(arg => arg.startsWith('--batch-size='));
export const skipExistingArg: boolean = args.includes('--skip-existing');
export const batchSize: number = batchSizeArg ? parseInt(parseArgValue(batchSizeArg) || '0', 10) : 0;
const qualityThresholdArg: string | undefined = args.find(arg => arg.startsWith('--quality-threshold='));
 
// Deep-inspection arguments: document IDs, URLs, focus topic, and analysis depth
const documentIdsArg: string | undefined = args.find(arg => arg.startsWith('--document-ids='));
const documentUrlsArg: string | undefined = args.find(arg => arg.startsWith('--document-urls='));
const focusTopicArg: string | undefined = args.find(arg => arg.startsWith('--focus-topic='));
const depthArg: string | undefined = args.find(arg => arg.startsWith('--depth='));
 
/** Comma-separated Riksdag document IDs for deep-inspection (e.g. H901FiU1,H901JuU25) */
const rawDocumentIds: string = parseArgValue(documentIdsArg);
export const documentIds: string[] = rawDocumentIds
  ? rawDocumentIds.split(',').map(id => id.trim()).filter(Boolean)
  : [];
 
/** Comma-separated URLs for deep-inspection analysis */
const rawDocumentUrls: string = parseArgValue(documentUrlsArg);
export const documentUrls: string[] = rawDocumentUrls
  ? rawDocumentUrls.split(',').map(u => u.trim()).filter(Boolean)
  : [];
 
/** Specific policy topic to focus deep-inspection analysis on */
export const focusTopic: string = parseArgValue(focusTopicArg);
 
/**
 * Analysis depth for deep-inspection (1–4).
 *  1 — surface analysis (what happened) — default, fastest
 *  2 — adds predictive assessment and historical context
 *  3 — adds executive intelligence summary and methodology (3 iterations)
 *  4 — full report: adds quality-review iteration in methodology (4 iterations)
 */
const rawDepth: string = parseArgValue(depthArg);
const depthArgProvided: boolean = !!depthArg;
const parsedDepthNum: number = rawDepth ? Number(rawDepth) : NaN;
const depthIsValid: boolean = Number.isInteger(parsedDepthNum) && parsedDepthNum >= 1 && parsedDepthNum <= 4;
Iif (depthArgProvided && !depthIsValid) {
  console.warn(`Invalid --depth value "${rawDepth}" (expected integer 1–4), falling back to default 1.`);
}
const safeDepth: number = depthIsValid ? parsedDepthNum : 1;
export const analysisDepth: 1 | 2 | 3 | 4 =
  safeDepth === 4 ? 4 :
  safeDepth === 3 ? 3 :
  safeDepth === 2 ? 2 :
  1;
// --iterations=N: number of AI analysis iterations for deep-inspection (default: 3)
const iterationsArg: string | undefined = args.find(arg => arg.startsWith('--iterations='));
const DEFAULT_ITERATIONS = 3;
let parsedIterations: number = DEFAULT_ITERATIONS;
Iif (iterationsArg) {
  const rawIter: string = parseArgValue(iterationsArg);
  const numIter: number = rawIter === '' ? NaN : Number(rawIter);
  if (Number.isFinite(numIter)) {
    // Clamp to 1–10; 0/negative values map to 1 rather than falling back to default
    parsedIterations = Math.min(10, Math.max(1, Math.floor(numIter)));
  } else {
    console.warn(`Invalid --iterations value "${rawIter}", falling back to default ${DEFAULT_ITERATIONS}.`);
  }
}
/** Number of AI analysis iterations for deep-inspection articles. Default: 3. */
export const analysisIterations: number = parsedIterations;
// ---------------------------------------------------------------------------
// Analysis depth (controls number of AI analysis iterations)
// ---------------------------------------------------------------------------
 
/**
 * --analysis-depth=<quick|standard|deep>
 *
 * Controls how many AI analysis iterations run for deep-inspection articles:
 * - `quick`    — 1 pass (initial analysis only; fast)
 * - `standard` — 2 passes (initial + SWOT refinement; default)
 * - `deep`     — 3 passes (initial + refinement + stakeholder validation)
 */
const analysisModeArg: string | undefined = args.find(arg => arg.startsWith('--analysis-depth='));
const rawAnalysisMode: string = parseArgValue(analysisModeArg ?? '').toLowerCase();
const VALID_ANALYSIS_DEPTHS: readonly AnalysisDepth[] = ['quick', 'standard', 'deep'];
 
function parseAnalysisDepth(raw: string): AnalysisDepth {
  Iif ((VALID_ANALYSIS_DEPTHS as readonly string[]).includes(raw)) {
    return raw as AnalysisDepth;
  }
  Iif (raw && raw !== '') {
    console.warn(`⚠️ Unknown --analysis-depth value "${raw}", falling back to "standard". Valid values: ${VALID_ANALYSIS_DEPTHS.join(', ')}`);
  }
  return 'standard';
}
 
export const analysisMode: AnalysisDepth = parseAnalysisDepth(rawAnalysisMode);
 
const DEFAULT_QUALITY_THRESHOLD = 40;
let parsedQualityThreshold: number = DEFAULT_QUALITY_THRESHOLD;
Iif (qualityThresholdArg) {
  const rawValue: string = parseArgValue(qualityThresholdArg);
  const numericValue: number = rawValue === '' ? NaN : Number(rawValue);
  if (Number.isFinite(numericValue)) {
    parsedQualityThreshold = Math.min(100, Math.max(0, numericValue));
  } else {
    console.warn(`Invalid --quality-threshold value "${rawValue}", falling back to default ${DEFAULT_QUALITY_THRESHOLD}.`);
  }
}
export const QUALITY_THRESHOLD: number = parsedQualityThreshold;
 
/**
 * Default threshold (0–100) for the multi-dimensional quality assessment
 * pipeline.  Articles scoring below this value are flagged but still written.
 * Referenced by `validateArticleQuality()` and the Check 13 validation script.
 */
export const MULTIDIM_QUALITY_THRESHOLD = 60;
 
/**
 * Breaking news significance threshold (0–100). Documents scoring at or above
 * this value are considered breaking news.
 */
export const BREAKING_NEWS_THRESHOLD = 60;
 
// --require-mcp flag: when true (default), abort if MCP server is unreachable after all retries.
// Set --require-mcp=false for local development/testing without a live MCP server.
const requireMcpArg: string | undefined = args.find(arg => arg.startsWith('--require-mcp'));
export const requireMcp: boolean = parseArgValue(requireMcpArg ?? '') !== 'false';
 
// ---------------------------------------------------------------------------
// Valid article types
// ---------------------------------------------------------------------------
 
export const VALID_ARTICLE_TYPES: readonly string[] = ['week-ahead', 'month-ahead', 'weekly-review', 'monthly-review', 'committee-reports', 'propositions', 'motions', 'interpellations', 'breaking', 'deep-inspection'];
 
const rawArticleTypes: string[] = typesArg
  ? parseArgValue(typesArg).split(',').map(t => t.trim()).filter(Boolean)
  : [];
 
const filteredArticleTypes: string[] = rawArticleTypes.filter(t => VALID_ARTICLE_TYPES.includes(t));
 
Iif (rawArticleTypes.length > 0 && filteredArticleTypes.length === 0) {
  throw new Error(
    `No valid article types specified via --types. Valid types are: ${VALID_ARTICLE_TYPES.join(', ')}`
  );
}
 
export const articleTypes: string[] = filteredArticleTypes.length > 0
  ? filteredArticleTypes
  : ['week-ahead'];
 
// ---------------------------------------------------------------------------
// Language configuration
// ---------------------------------------------------------------------------
 
export const ALL_LANGUAGES: readonly Language[] = ['en', 'sv', 'da', 'no', 'fi', 'de', 'fr', 'es', 'nl', 'ar', 'he', 'ja', 'ko', 'zh'];
 
export const LANGUAGE_PRESETS: Readonly<Record<string, Language[]>> = {
  'all': [...ALL_LANGUAGES],
  'nordic': ['en', 'sv', 'da', 'no', 'fi'],
  'eu-core': ['en', 'sv', 'de', 'fr', 'es', 'nl']
};
 
let languagesInput: string = languagesArg ? parseArgValue(languagesArg).trim().toLowerCase() : 'all';
 
// Expand presets (after trimming and normalizing)
const presetLanguages: Language[] | undefined = LANGUAGE_PRESETS[languagesInput];
Eif (presetLanguages) {
  languagesInput = presetLanguages.join(',');
}
 
export let languages: Language[] = languagesInput
  .split(',')
  .map(l => l.trim())
  .filter((l): l is Language => (ALL_LANGUAGES as readonly string[]).includes(l));
 
Iif (languages.length === 0) {
  console.error('❌ No valid language codes provided. Valid codes:', ALL_LANGUAGES.join(', '));
  process.exit(1);
}
 
// Log filtered article types (invalid types were removed during parsing above)
const filteredTypes: string[] = rawArticleTypes.filter(t => !VALID_ARTICLE_TYPES.includes(t));
Iif (filteredTypes.length > 0) {
  console.warn(`⚠️ Unknown article types filtered out: ${filteredTypes.join(', ')}. Valid types: ${VALID_ARTICLE_TYPES.join(', ')}`);
}
 
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
 
export const NEWS_DIR: string = path.join(__dirname, '..', '..', 'news');
export const METADATA_DIR: string = path.join(NEWS_DIR, 'metadata');
 
// Track full requested set before any filtering
export const allRequestedLanguages: Language[] = [...languages];
 
// Apply --skip-existing: remove languages that already have today's articles
Iif (skipExistingArg) {
  const today: string = toISODate(new Date());
  const existingFiles: string[] = fs.existsSync(NEWS_DIR)
    ? fs.readdirSync(NEWS_DIR).filter(f => f.startsWith(today) && f.endsWith('.html'))
    : [];
  const doneLangs: Language[] = languages.filter(lang =>
    existingFiles.some(f => f.endsWith(`-${lang}.html`))
  );
  if (doneLangs.length > 0) {
    console.log(`⏭️  Skipping already-generated languages: ${doneLangs.join(', ')}`);
    languages = languages.filter(l => !doneLangs.includes(l));
  }
}
 
// Apply --batch-size: limit to N languages per run
Iif (batchSize > 0 && languages.length > batchSize) {
  const remaining: Language[] = languages.slice(batchSize);
  languages = languages.slice(0, batchSize);
  console.log(`📦 Batch mode: processing ${languages.length} of ${allRequestedLanguages.length} requested languages`);
  console.log(`   This batch: ${languages.join(', ')}`);
  console.log(`   Remaining for next run(s): ${remaining.join(', ')}`);
}
 
Iif (languages.length === 0) {
  console.log('✅ All requested languages already generated. Nothing to do.');
  // Write a status metadata file so the workflow knows we're done
  if (!fs.existsSync(METADATA_DIR)) {
    fs.mkdirSync(METADATA_DIR, { recursive: true });
  }
  const batchStatus: BatchStatus = {
    complete: true,
    allDone: allRequestedLanguages,
    timestamp: new Date().toISOString(),
  };
  fs.writeFileSync(
    path.join(METADATA_DIR, 'batch-status.json'),
    JSON.stringify(batchStatus, null, 2)
  );
  process.exit(0);
}
 
console.log('📰 Enhanced News Generation Script');
console.log('Article types:', articleTypes.join(', '));
console.log('Languages:', languages.join(', '));
console.log('Batch size:', batchSize > 0 ? batchSize : 'all at once');
console.log('Skip existing:', skipExistingArg ? 'Yes' : 'No');
console.log('Dry run:', dryRunArg ? 'Yes (no files written)' : 'No');
 
// ---------------------------------------------------------------------------
// Shared MCP client (reuses connection/session across all generators)
// ---------------------------------------------------------------------------
 
let sharedClient: MCPClient | null = null;
 
/**
 * Get or create the shared MCPClient instance.
 * On first call, warms up the MCP server with a lightweight get_sync_status
 * request using an extended timeout to handle Render.com cold starts (30-60s).
 *
 * @returns Warmed-up shared client
 */
export async function getSharedClient(): Promise<MCPClient> {
  if (sharedClient) return sharedClient;
 
  // Use extended timeout for initial connection (cold start can take 30-60s)
  const coldStartTimeout: number = parseInt(process.env.MCP_CLIENT_TIMEOUT_MS ?? '', 10) || 90000;
  sharedClient = new MCPClient({ timeout: coldStartTimeout });
 
  // Warm up the MCP server before any data queries
  console.log('⏳ Warming up MCP server (may take 30-60s on cold start)...');
  console.log(`  🔗 Server: ${sharedClient.baseURL}`);
  try {
    const status: Record<string, unknown> = await sharedClient.request('get_sync_status', {});
    console.log('✅ MCP server ready');
    Eif (status && status['last_sync']) {
      console.log(`  📊 Last sync: ${status['last_sync'] as string}`);
    }
  } catch (error: unknown) {
    const message = (error as Error).message;
    Eif (requireMcp) {
      sharedClient = null;
      throw new Error(`MCP server unavailable: ${message}`, { cause: error });
    }
    console.warn(`⚠️ MCP warm-up failed: ${message}`);
    console.warn('  Continuing anyway — individual requests will retry with backoff');
  }
 
  // After warm-up succeeds, reduce timeout for normal requests
  const normalTimeout: number = parseInt(process.env.MCP_CLIENT_TIMEOUT_MS ?? '', 10) || 30000;
  (sharedClient as unknown as { timeout: number }).timeout = normalTimeout;
 
  return sharedClient;
}
 
// Ensure directories exist
if (!fs.existsSync(METADATA_DIR)) {
  fs.mkdirSync(METADATA_DIR, { recursive: true });
}
 
// ---------------------------------------------------------------------------
// Generation statistics
// ---------------------------------------------------------------------------
 
export const stats: GenerationStats = {
  generated: 0,
  errors: 0,
  articles: [],
  timestamp: new Date().toISOString(),
  qualityScores: []
};