All files / scripts/parliamentary-data mcp-retry-queue.ts

71.27% Statements 67/94
55.88% Branches 38/68
100% Functions 7/7
70.96% Lines 66/93

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                        3x 3x   3x 3x 3x                                                                               4x                   7x 3x 3x 3x                           5x 5x                           5x 5x     5x                                   3x 3x   3x       3x 5x 5x 5x                     3x     1x   3x 3x                       3x 3x 3x 3x 3x 3x 3x 3x   3x 3x 3x 3x   3x 3x       3x       3x         3x 3x   3x 3x 3x                 2x                 2x 2x 2x 2x                   3x   1x 1x               1x                                 1x             1x   1x                                                           3x                                   3x                                                                           3x                   3x 3x 2x     3x                      
/**
 * @module parliamentary-data/mcp-retry-queue
 * @description File-backed deferred retry queue for MCP indexing/content gaps.
 */
 
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
 
import type { FetchVotingFilters, MCPCoverageState, MCPToolInvocationDiagnostic } from '../types/mcp.js';
import type { MCPClient } from '../mcp-client/client.js';
 
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(__dirname, '..', '..');
 
export const MCP_RETRY_QUEUE_SCHEMA = 'riksdagsmonitor-mcp-retry-queue/1.0';
export const DEFAULT_MCP_RETRY_QUEUE_PATH = path.join(REPO_ROOT, 'data', 'mcp-retry-queue.json');
const DEFAULT_EXPIRY_DAYS = 7;
 
export interface MCPRetryQueueEntry {
  resourceType: 'document_fulltext' | 'voteringar_search';
  resourceId: string;
  tool: string;
  docType?: string | null;
  coverageState: MCPCoverageState;
  requestedAt: string;
  expiresAt: string;
  attemptCount: number;
  params: Record<string, unknown>;
  reason?: string;
  lastAttemptAt?: string;
}
 
export interface MCPRetryQueueFile {
  schema: string;
  updatedAt: string;
  entries: MCPRetryQueueEntry[];
}
 
export interface MCPRetryDrainResult {
  queue: MCPRetryQueueFile;
  processed: number;
  resolved: number;
  retained: number;
  expired: number;
  resolvedDocuments: Record<string, Record<string, unknown>>;
  /**
   * Voting rows recovered from previously-deferred voteringar searches,
   * keyed by the queue entry's `resourceId` (the exact query payload).
   * Surfaced so callers can re-inject the rows into the run output even if
   * the original query is no longer selected by the current date/filter.
   */
  resolvedVoteringar: Record<string, unknown[]>;
  diagnostics: MCPToolInvocationDiagnostic[];
}
 
function emptyQueue(initialTimestamp = new Date(0).toISOString()): MCPRetryQueueFile {
  return {
    schema: MCP_RETRY_QUEUE_SCHEMA,
    updatedAt: initialTimestamp,
    entries: [],
  };
}
 
export function loadMcpRetryQueue(
  queuePath: string = DEFAULT_MCP_RETRY_QUEUE_PATH,
): MCPRetryQueueFile {
  if (!fs.existsSync(queuePath)) return emptyQueue();
  try {
    const parsed = JSON.parse(fs.readFileSync(queuePath, 'utf8')) as Partial<MCPRetryQueueFile>;
    return {
      schema: parsed.schema ?? MCP_RETRY_QUEUE_SCHEMA,
      updatedAt: parsed.updatedAt ?? new Date(0).toISOString(),
      entries: Array.isArray(parsed.entries) ? parsed.entries as MCPRetryQueueEntry[] : [],
    };
  } catch {
    return emptyQueue();
  }
}
 
export function saveMcpRetryQueue(
  queue: MCPRetryQueueFile,
  queuePath: string = DEFAULT_MCP_RETRY_QUEUE_PATH,
): void {
  fs.mkdirSync(path.dirname(queuePath), { recursive: true });
  fs.writeFileSync(queuePath, JSON.stringify(queue, null, 2) + '\n', 'utf8');
}
 
export function createRetryQueueEntry(options: {
  resourceType: MCPRetryQueueEntry['resourceType'];
  resourceId: string;
  tool: string;
  coverageState: MCPCoverageState;
  params: Record<string, unknown>;
  docType?: string | null;
  reason?: string;
  requestedAt?: string;
  expiresInDays?: number;
}): MCPRetryQueueEntry {
  const requestedAt = options.requestedAt ?? new Date().toISOString();
  const expiresAt = new Date(
    new Date(requestedAt).getTime() + ((options.expiresInDays ?? DEFAULT_EXPIRY_DAYS) * 86400000),
  ).toISOString();
  return {
    resourceType: options.resourceType,
    resourceId: options.resourceId,
    tool: options.tool,
    docType: options.docType ?? null,
    coverageState: options.coverageState,
    requestedAt,
    expiresAt,
    attemptCount: 0,
    params: { ...options.params },
    ...(options.reason ? { reason: options.reason } : {}),
  };
}
 
export function enqueueRetryEntries(
  entries: MCPRetryQueueEntry[],
  queuePath: string = DEFAULT_MCP_RETRY_QUEUE_PATH,
): MCPRetryQueueFile {
  const queue = loadMcpRetryQueue(queuePath);
  const deduped = new Map<string, MCPRetryQueueEntry>();
 
  for (const existing of queue.entries) {
    deduped.set(`${existing.resourceType}:${existing.resourceId}`, existing);
  }
 
  for (const entry of entries) {
    const key = `${entry.resourceType}:${entry.resourceId}`;
    const previous = deduped.get(key);
    deduped.set(key, previous
      ? {
          ...previous,
          ...entry,
          attemptCount: previous.attemptCount,
          requestedAt: previous.requestedAt,
          expiresAt: previous.expiresAt,
        }
      : entry);
  }
 
  const updated: MCPRetryQueueFile = {
    schema: MCP_RETRY_QUEUE_SCHEMA,
    updatedAt: new Date().toISOString(),
    entries: [...deduped.values()].sort((a, b) => a.resourceId.localeCompare(b.resourceId)),
  };
  saveMcpRetryQueue(updated, queuePath);
  return updated;
}
 
export async function drainMcpRetryQueue(
  client: MCPClient,
  options: {
    docType?: string | null;
    queuePath?: string;
    now?: Date;
    maxEntries?: number;
  } = {},
): Promise<MCPRetryDrainResult> {
  const queuePath = options.queuePath ?? DEFAULT_MCP_RETRY_QUEUE_PATH;
  const now = options.now ?? new Date();
  const queue = loadMcpRetryQueue(queuePath);
  const remaining: MCPRetryQueueEntry[] = [];
  const resolvedDocuments: Record<string, Record<string, unknown>> = {};
  const resolvedVoteringar: Record<string, unknown[]> = {};
  const diagnostics: MCPToolInvocationDiagnostic[] = [];
  const originalEntryCount = queue.entries.length;
 
  let processed = 0;
  let resolved = 0;
  let retained = 0;
  let expired = 0;
 
  for (const entry of queue.entries) {
    Iif (options.docType && entry.docType && entry.docType !== options.docType) {
      remaining.push(entry);
      continue;
    }
    Iif (new Date(entry.expiresAt).getTime() < now.getTime()) {
      expired++;
      continue;
    }
    Iif (options.maxEntries && processed >= options.maxEntries) {
      remaining.push(entry);
      continue;
    }
 
    processed++;
    const lastAttemptAt = now.toISOString();
 
    Eif (entry.resourceType === 'document_fulltext') {
      try {
        const result = await client.fetchDocumentDetailsWithCoverage(
          entry.resourceId,
          true,
          {
            requestedDate: (entry.params['requestedDate'] as string | undefined) ?? null,
            retrieval: 'retry_queue',
          },
        );
 
        diagnostics.push({
          tool: entry.tool,
          query: { ...entry.params, dok_id: entry.resourceId, include_full_text: true },
          resultCount: result.resultCount,
          coverageState: result.coverageState,
          provenance: result.provenance,
          notes: entry.reason,
        });
 
        Eif (result.coverageState === 'full_text') {
          resolved++;
          resolvedDocuments[entry.resourceId] = result.document;
          continue;
        }
 
        remaining.push({
          ...entry,
          attemptCount: entry.attemptCount + 1,
          coverageState: result.coverageState,
          reason: entry.reason ?? `Deferred ${entry.tool} retry still ${result.coverageState}`,
          lastAttemptAt,
        });
        retained++;
      } catch (drainErr) {
        const errMessage = drainErr instanceof Error ? drainErr.message : String(drainErr);
        console.warn(
          `[mcp-retry-queue] Document retry failed for ${entry.resourceId}:`,
          errMessage,
        );
        // Emit a `fetch_error` diagnostic so the manifest's
        // `## MCP Query Diagnostics` section exposes the exact failed
        // retry — without this the failure disappears into the aggregate
        // retained counter.
        diagnostics.push({
          tool: entry.tool,
          query: { ...entry.params, dok_id: entry.resourceId, include_full_text: true },
          resultCount: 0,
          coverageState: 'fetch_error',
          provenance: {
            provider: 'riksdag-regering',
            endpoint: client.baseURL,
            tool: entry.tool,
            query: { ...entry.params, dok_id: entry.resourceId, include_full_text: true },
            resultCount: 0,
            coverageState: 'fetch_error',
            retrieval: 'retry_queue',
            retrievedAt: now.toISOString(),
          },
          notes: `Retry failed: ${errMessage}`,
        });
        remaining.push({
          ...entry,
          attemptCount: entry.attemptCount + 1,
          coverageState: 'fetch_error',
          reason: `Retry failed: ${errMessage}`,
          lastAttemptAt,
        });
        retained++;
      }
      continue;
    }
 
    const votingParams = entry.params;
    if (typeof votingParams !== 'object' || votingParams === null) {
      remaining.push({
        ...entry,
        attemptCount: entry.attemptCount + 1,
        reason: 'retry queue entry has invalid voting params payload',
        lastAttemptAt,
      });
      retained++;
      continue;
    }
 
    try {
      const votingResult = await client.fetchVotingRecordsWithDiagnostics(
        votingParams as FetchVotingFilters,
      );
 
      diagnostics.push({
        tool: entry.tool,
        query: { ...(entry.params as Record<string, unknown>) },
        resultCount: votingResult.resultCount,
        coverageState: votingResult.coverageState,
        provenance: votingResult.provenance,
        notes: entry.reason,
        ...(votingResult.signal ? { signal: votingResult.signal } : {}),
      });
 
      Iif (votingResult.resultCount > 0) {
        resolved++;
        // Persist the recovered items so the caller can re-inject them into
        // the run output even if the original query is no longer part of
        // the current download selection.
        if (Array.isArray(votingResult.items)) {
          resolvedVoteringar[entry.resourceId] = votingResult.items as unknown[];
        }
        continue;
      }
 
      remaining.push({
        ...entry,
        attemptCount: entry.attemptCount + 1,
        coverageState: votingResult.coverageState,
        reason: votingResult.signal?.message ?? entry.reason,
        lastAttemptAt,
      });
      retained++;
    } catch (drainErr) {
      const errMessage = drainErr instanceof Error ? drainErr.message : String(drainErr);
      console.warn(
        `[mcp-retry-queue] Voting retry failed for ${entry.resourceId}:`,
        errMessage,
      );
      // Surface the failed voteringar retry as a `fetch_error` diagnostic so
      // the manifest preserves the exact query/error rather than silently
      // incrementing the retained counter.
      diagnostics.push({
        tool: entry.tool,
        query: { ...(entry.params as Record<string, unknown>) },
        resultCount: 0,
        coverageState: 'fetch_error',
        provenance: {
          provider: 'riksdag-regering',
          endpoint: client.baseURL,
          tool: entry.tool,
          query: { ...(entry.params as Record<string, unknown>) },
          resultCount: 0,
          coverageState: 'fetch_error',
          retrieval: 'retry_queue',
          retrievedAt: now.toISOString(),
        },
        notes: `Retry failed: ${errMessage}`,
      });
      remaining.push({
        ...entry,
        attemptCount: entry.attemptCount + 1,
        coverageState: 'fetch_error',
        reason: `Retry failed: ${errMessage}`,
        lastAttemptAt,
      });
      retained++;
    }
  }
 
  const updatedQueue: MCPRetryQueueFile = {
    schema: MCP_RETRY_QUEUE_SCHEMA,
    updatedAt: now.toISOString(),
    entries: remaining,
  };
 
  // Avoid touching the queue file when the queue was already empty AND we
  // had nothing to process. Without this guard, every news workflow would
  // dirty `data/mcp-retry-queue.json` with a fresh `updatedAt` even when no
  // retry work occurred, producing noisy PR diffs and merge conflicts.
  const hadWork = originalEntryCount > 0 || processed > 0 || expired > 0 || remaining.length > 0;
  if (hadWork) {
    saveMcpRetryQueue(updatedQueue, queuePath);
  }
 
  return {
    queue: updatedQueue,
    processed,
    resolved,
    retained,
    expired,
    resolvedDocuments,
    resolvedVoteringar,
    diagnostics,
  };
}