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 | 3x 3x 29x 11x 3x 8x 8x 1x 7x 7x 13x 13x 13x 9x 7x 3x 3x 3x 23x 23x 23x 23x 23x 23x 23x 23x 23x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 23x 154x 154x 23x 29x 23x 29x 29x 29x 29x 29x 23x 23x 23x 22x 22x 84x 22x 22x 25x 25x 21x 21x 21x 21x 21x 21x 21x 21x 21x 105x 36x 21x 20x 118x 20x 80x 80x 20x 20x 21x 21x 3x 20x 1x 20x 20x 20x 20x 18x 18x 3x 20x 20x 20x 21x 21x 20x 20x 20x 20x 4x 16x 1x 21x 21x 4x 4x 17x 16x 16x 1x 22x 20x 23x 1x 1x 1x | /**
* @module parliamentary-data/data-downloader
* @description Downloads all relevant parliamentary documents from riksdag-regering-mcp
* for the current Swedish parliamentary session (riksmöte). Returns typed `RawDocument[]`
* collections plus a manifest of which MCP tools returned successful results and how many
* documents each returned.
*
* Note: The download methods fetch session-wide latest documents (bounded by `limit`
* and `rm`). Date-specific filtering should be applied by the caller after download
* (e.g., filtering by the `datum` field on each `RawDocument`).
*
* This module is intentionally side-effect-free with respect to the filesystem;
* callers are responsible for writing any output.
*
* @author Hack23 AB
* @license Apache-2.0
*/
import type { RawDocument } from '../data-transformers/types.js';
import { isPersonProfileText } from '../data-transformers/helpers.js';
import type { MCPClient } from '../mcp-client/client.js';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/**
* Strict lower bound for `fullText`/`fullContent` fields to be classified as
* meaningful full-text content (not empty/placeholder). Content must be
* longer than `FULL_TEXT_MIN_LENGTH` characters (`> 100`), so exactly 100
* characters does not qualify. Used in data-downloader enrichment and
* referenced by quality gate checks (Checks 9/10 in
* SHARED_PROMPT_PATTERNS.md) which use the same `> 100` threshold via jq.
*/
export const FULL_TEXT_MIN_LENGTH = 100;
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/** Supported document type keys for scoped downloads. */
export type DocumentTypeKey =
| 'propositions'
| 'motions'
| 'committeeReports'
| 'votes'
| 'speeches'
| 'questions'
| 'interpellations';
export interface DownloadedData {
/** Government propositions */
propositions: RawDocument[];
/** Parliamentary motions */
motions: RawDocument[];
/** Committee reports */
committeeReports: RawDocument[];
/** Parliamentary votes */
votes: RawDocument[];
/** Parliamentary speeches (anföranden) */
speeches: RawDocument[];
/** Written questions */
questions: RawDocument[];
/** Interpellations */
interpellations: RawDocument[];
}
export interface DownloadManifest {
/** Names of MCP tools with successful fetch + post-processing during download */
dataSources: string[];
/** Document counts per type */
docCounts: Record<string, number>;
/** Total download duration in milliseconds */
durationMs: number;
}
export interface DownloadResult {
data: DownloadedData;
manifest: DownloadManifest;
}
/** Maximum number of documents to enrich with full-text content per type. */
export const MAX_ENRICHMENT_PER_TYPE = 5;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function normalise(raw: unknown[]): RawDocument[] {
return (raw as RawDocument[]).filter(Boolean);
}
/**
* Subtract a number of business days (Mon–Fri) from a YYYY-MM-DD date string.
* Returns the resulting date in YYYY-MM-DD format.
*
* Fractional values are rounded down, and negative values are treated as 0.
*
* @param dateStr - ISO date string (YYYY-MM-DD)
* @param days - Number of business days to subtract
* @throws {RangeError} If `dateStr` is not a valid YYYY-MM-DD date string
*/
export function subtractBusinessDays(dateStr: string, days: number): string {
if (!/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
throw new RangeError(`subtractBusinessDays: invalid date string "${dateStr}" — expected YYYY-MM-DD`);
}
const d = new Date(`${dateStr}T00:00:00Z`);
if (Number.isNaN(d.getTime())) {
throw new RangeError(`subtractBusinessDays: "${dateStr}" is not a valid calendar date`);
}
let remaining = Math.max(0, Math.floor(days));
while (remaining > 0) {
d.setUTCDate(d.getUTCDate() - 1);
const dow = d.getUTCDay(); // 0=Sun, 6=Sat
if (dow !== 0 && dow !== 6) {
remaining--;
}
}
return d.toISOString().slice(0, 10);
}
/** Maximum number of business days to look back when zero documents match the requested date. */
export const MAX_LOOKBACK_BUSINESS_DAYS = 5;
/** All internal fetch task names, kept in sync with the `fetchTasks` array
* inside `downloadAllDocuments()`. Used to derive the `FetchTaskName` type
* and to validate the `FETCH_TASK_TYPE_MAP` at compile time. */
const FETCH_TASK_NAMES = [
'fetchPropositions',
'fetchMotions',
'fetchCommitteeReports',
'fetchVotingRecords',
'searchSpeeches',
'fetchWrittenQuestions',
'fetchInterpellations',
] as const;
type FetchTaskName = typeof FETCH_TASK_NAMES[number];
/** Maps internal fetch task names to their corresponding DocumentTypeKey.
* `satisfies` ensures every FetchTaskName maps to a valid DocumentTypeKey
* at compile time — adding/renaming a task without updating the map is a
* compile error. */
const FETCH_TASK_TYPE_MAP: Record<FetchTaskName, DocumentTypeKey> = {
fetchPropositions: 'propositions',
fetchMotions: 'motions',
fetchCommitteeReports: 'committeeReports',
fetchVotingRecords: 'votes',
searchSpeeches: 'speeches',
fetchWrittenQuestions: 'questions',
fetchInterpellations: 'interpellations',
} as const satisfies Record<FetchTaskName, DocumentTypeKey>;
/**
* Returns the current Swedish parliamentary session (riksmöte) in `YYYY/YY` format.
* The Swedish parliamentary year runs from October to September:
* - October–December of year N: session is `N/N+1`
* - January–September of year N: session is `N-1/N`
*
* Examples: 2025-11 → "2025/26", 2026-03 → "2025/26", 2026-10 → "2026/27"
*/
function currentRm(): string {
const now = new Date();
const year = now.getUTCFullYear();
const month = now.getUTCMonth() + 1; // 1-based
// Swedish parliamentary year runs roughly October–September
if (month >= 10) {
return `${year}/${String(year + 1).slice(-2)}`;
}
return `${year - 1}/${String(year).slice(-2)}`;
}
// ---------------------------------------------------------------------------
// Download orchestration
// ---------------------------------------------------------------------------
/**
* Download all relevant documents from riksdag-regering-mcp.
*
* Each document type is fetched with a configurable limit (default 20).
* Failures in individual calls are caught so a partial result is returned
* rather than failing the entire pipeline.
*
* When `docTypes` is provided, only the listed document types are fetched.
* This prevents multiple workflows (e.g. propositions and committee-reports)
* from downloading the same documents and writing conflicting analysis.
*
* @param client - MCPClient instance (caller-supplied for testability)
* @param options - Optional overrides for limits, riksmöte, and document type scoping
*/
export async function downloadAllDocuments(
client: MCPClient,
options: { limit?: number; rm?: string; docTypes?: DocumentTypeKey[]; enrichLimit?: number } = {},
): Promise<DownloadResult> {
const start = Date.now();
const limit = options.limit ?? 20;
const rm = options.rm ?? currentRm();
const docTypes = options.docTypes ?? null; // null means fetch all types
const dataSources: string[] = [];
const data: DownloadedData = {
propositions: [],
motions: [],
committeeReports: [],
votes: [],
speeches: [],
questions: [],
interpellations: [],
};
// Run independent MCP fetches in parallel to reduce total latency while
// still collecting partial results on failure.
const fetchTasks = [
{
name: 'fetchPropositions',
source: 'get_propositioner',
fetch: () => client.fetchPropositions(limit, rm),
assign: (raw: RawDocument[]) => { data.propositions = raw; },
},
{
name: 'fetchMotions',
source: 'get_motioner',
fetch: () => client.fetchMotions(limit, rm),
assign: (raw: RawDocument[]) => { data.motions = raw; },
},
{
name: 'fetchCommitteeReports',
source: 'get_betankanden',
fetch: () => client.fetchCommitteeReports(limit, rm),
assign: (raw: RawDocument[]) => { data.committeeReports = raw; },
},
{
name: 'fetchVotingRecords',
source: 'search_voteringar',
fetch: () => client.fetchVotingRecords({ limit, rm }),
assign: (raw: RawDocument[]) => { data.votes = raw; },
},
{
name: 'searchSpeeches',
source: 'search_anforanden',
fetch: () => client.searchSpeeches({ limit, rm }),
assign: (raw: RawDocument[]) => { data.speeches = raw; },
},
{
name: 'fetchWrittenQuestions',
source: 'get_fragor',
fetch: () => client.fetchWrittenQuestions({ limit, rm }),
assign: (raw: RawDocument[]) => { data.questions = raw; },
},
{
name: 'fetchInterpellations',
source: 'get_interpellationer',
fetch: () => client.fetchInterpellations({ limit, rm }),
assign: (raw: RawDocument[]) => { data.interpellations = raw; },
},
] as const;
// When docTypes is specified, only fetch the listed document types.
// task.name is typed as FetchTaskName via the `as const` assertion on
// fetchTasks, so the lookup is safe without a cast.
const activeTasks = docTypes
? fetchTasks.filter(task => {
const mapped = FETCH_TASK_TYPE_MAP[task.name];
return docTypes.includes(mapped);
})
: fetchTasks;
const fetchResults = await Promise.allSettled(
activeTasks.map(task => task.fetch()),
);
fetchResults.forEach((result, index) => {
const task = activeTasks[index]!;
if (result.status === 'fulfilled') {
try {
task.assign(normalise(result.value as unknown[]));
dataSources.push(task.source);
} catch (err) {
console.warn(
`[pre-analysis] ${task.name} post-processing failed:`,
err instanceof Error ? err.message : String(err),
);
}
} else E{
console.warn(
`[pre-analysis] ${task.name} failed:`,
result.reason instanceof Error ? result.reason.message : String(result.reason),
);
}
});
const docCounts: Record<string, number> = {
propositions: data.propositions.length,
motions: data.motions.length,
committeeReports: data.committeeReports.length,
votes: data.votes.length,
speeches: data.speeches.length,
questions: data.questions.length,
interpellations: data.interpellations.length,
};
// -----------------------------------------------------------------------
// Enrichment pass: fetch full-text content for top documents per type.
// Uses fetchDocumentDetails(dok_id, true) to request actual full text
// via get_dokument_innehall. Without this step, the analysis pipeline
// produces LOW-confidence metadata-only analysis.
// -----------------------------------------------------------------------
const enrichLimit = options.enrichLimit ?? MAX_ENRICHMENT_PER_TYPE;
if (enrichLimit > 0) {
const enrichableTypes: DocumentTypeKey[] = [
'propositions', 'committeeReports', 'motions', 'interpellations',
];
const typesToEnrich = docTypes
? enrichableTypes.filter(t => docTypes.includes(t))
: enrichableTypes;
let anyEnriched = false;
for (const docType of typesToEnrich) {
const docs = data[docType];
if (!docs || docs.length === 0) continue;
const toEnrich = docs.slice(0, enrichLimit);
// Enrich with limited parallelism (concurrency of 3) using Promise.allSettled
const CONCURRENCY = 3;
let fullTextCount = 0;
let detailsOnlyCount = 0;
for (let i = 0; i < toEnrich.length; i += CONCURRENCY) {
const batch = toEnrich.slice(i, i + CONCURRENCY);
const results = await Promise.allSettled(
batch.map(async (doc) => {
const docRecord = doc as Record<string, unknown>;
const dokId = [
docRecord['dok_id'],
docRecord['dokument_id'],
docRecord['rel_dok_id'],
docRecord['id'],
docRecord['dokumentnamn'],
]
.map((value) => typeof value === 'string' ? value.trim() : '')
.find((value): value is string => value.length > 0);
if (!dokId) return null;
const details = await client.fetchDocumentDetails(dokId, true) as Record<string, unknown>;
// Normalize MCP response fields to match RawDocument conventions.
// get_dokument_innehall returns: { text, snippet, fulltext_available, ... }
// details.text → raw Riksdag dump (metadata + embedded HTML) — use as fullContent
// details.snippet → 400-char excerpt — use as summary fallback
// Legacy fields (fullText, html, summary, notis) are NOT returned by the
// current MCP server but are kept as fallbacks for compatibility.
const str = (v: unknown): string => typeof v === 'string' ? v : '';
// Sanitize text fields: filter out MP profile/deceased-notice text
// (consistent with weekly-review/data-loader.ts sanitization pattern)
const sanitize = (v: unknown): string => {
const s = str(v).trim();
return isPersonProfileText(s) ? '' : s;
};
// Primary: MCP returns 'text' (raw dump with embedded HTML)
// Fallback: legacy 'fullText' field (if MCP server format changes)
const rawText = str(details['text']).trim();
const verifiedFullText = sanitize(details['fullText']) || '';
// Use raw 'text' as fullContent (it contains embedded HTML from Riksdag)
// Fallback: legacy 'html' field
const verifiedFullContent = rawText.length > FULL_TEXT_MIN_LENGTH
? rawText
: str(details['html']).trim();
// Only set fullText/fullContent when exceeding FULL_TEXT_MIN_LENGTH
// to avoid leaving short/placeholder values that downstream pipeline
// code may misinterpret as meaningful full-text content.
if (verifiedFullContent.length > FULL_TEXT_MIN_LENGTH) {
docRecord['fullContent'] = verifiedFullContent;
}
if (verifiedFullText.length > FULL_TEXT_MIN_LENGTH) {
docRecord['fullText'] = verifiedFullText;
}
// Propagate summary: prefer MCP 'snippet', fall back to legacy fields
const detailsSnippet = sanitize(details['snippet']);
const detailsSummary = sanitize(details['summary']);
const detailsNotis = sanitize(details['notis']);
if (!docRecord['summary']) {
const bestSummary = detailsSnippet || detailsSummary || '';
if (bestSummary.length > 0) {
docRecord['summary'] = bestSummary;
}
}
Iif (!docRecord['notis'] && detailsNotis.length > 0) {
docRecord['notis'] = detailsNotis;
}
docRecord['contentFetched'] = true;
return { fullText: verifiedFullText, fullContent: verifiedFullContent };
}),
);
for (const result of results) {
if (result.status === 'fulfilled' && result.value !== null) {
const details = result.value as Record<string, unknown>;
// Only count as full-text if fullText or fullContent is actually populated
const hasFullText = typeof details['fullText'] === 'string' && (details['fullText'] as string).length > FULL_TEXT_MIN_LENGTH;
const hasFullContent = typeof details['fullContent'] === 'string' && (details['fullContent'] as string).length > FULL_TEXT_MIN_LENGTH;
if (hasFullText || hasFullContent) {
fullTextCount++;
} else {
detailsOnlyCount++;
}
} else if (Iresult.status === 'rejected') {
console.warn(
`[pre-analysis] ⚠️ Failed to enrich document:`,
result.reason instanceof Error ? result.reason.message : String(result.reason),
);
}
}
// Small delay between batches to avoid rate limiting on get_dokument_innehall
// (consistent with weekly-review/data-loader.ts pattern)
Iif (i + CONCURRENCY < toEnrich.length) {
await new Promise<void>(r => setTimeout(r, 300));
}
}
if (fullTextCount > 0) {
anyEnriched = true;
console.log(`[pre-analysis] ✅ Enriched ${fullTextCount} ${docType} documents with full text` +
(detailsOnlyCount > 0 ? `, ${detailsOnlyCount} with details/summary only` : ''));
} else if (detailsOnlyCount > 0) {
anyEnriched = true;
console.log(`[pre-analysis] ℹ️ Fetched details for ${detailsOnlyCount} ${docType} documents (no full text returned)`);
} else {
console.warn(
`[pre-analysis] ⚠️ ${docType} enrichment produced no content (metadata-only analysis)`,
);
}
}
if (anyEnriched && !dataSources.includes('get_dokument_innehall')) {
dataSources.push('get_dokument_innehall');
}
}
return {
data,
manifest: {
dataSources,
docCounts,
durationMs: Date.now() - start,
},
};
}
/**
* Flatten all downloaded document collections into a single array,
* deduplicated by a best-effort document identifier.
*
* The primary deduplication key is `dok_id` when present. If `dok_id` is
* missing or empty, the function falls back in order to:
* `dokument_id`, `id`, `dok_url`, `url`, `rel_dok_id`, `titel`, and `title`.
* The first non-empty string among these fields is used as the dedup key,
* and documents resolving to the same key are treated as duplicates.
*/
export function flattenDocuments(data: DownloadedData): RawDocument[] {
const all: RawDocument[] = [
...data.propositions,
...data.motions,
...data.committeeReports,
...data.votes,
...data.speeches,
...data.questions,
...data.interpellations,
];
const seen = new Set<string>();
return all.filter(doc => {
if (!doc) return false;
const record = doc as Record<string, unknown>;
const idCandidates = [
record['dok_id'],
record['dokument_id'],
record['id'],
record['dok_url'],
record['url'],
record['rel_dok_id'],
record['titel'],
record['title'],
];
const id = idCandidates.find((candidate): candidate is string =>
typeof candidate === 'string' && candidate.trim().length > 0,
)?.trim() ?? '';
if (!id || seen.has(id)) return false;
seen.add(id);
return true;
});
}
|