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 | 4x 4x 4x 4x 33x 33x 10x 6x 6x 4x 24x 47x 47x 47x 24x 24x 23x 23x 23x 23x 23x 24x 24x 1x 24x 25x 25x 25x 25x 19x 19x 19x 19x 3x 2x 2x 2x 2x 2x 1x 16x 16x 16x 16x 5x 5x 5x 4x 4x 4x 4x 4x 4x 1x 3x 3x 3x 2x 1x 1x 3x 1x 3x 3x 3x 3x 2x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x | // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
/**
* @module MCP/PendingDocuments
* @description Persistence sidecar for EP adopted texts that are indexed but
* not yet available (EP Open Data Portal 5–15-day indexing lag).
*
* When Stage B deep-fetch receives `UPSTREAM_404: document indexed but content
* not yet available` from the MCP server, the document identifier is recorded
* here with `{ docId, firstObservedAt, lastProbedAt, attempts }` so that
* subsequent workflow runs can re-probe with exponential back-off instead of
* treating the item as a permanent retrieval failure.
*
* Back-off schedule: initial 24 h, doubling each attempt, capped at 72 h.
* Documents older than 14 days are escalated (status = ESCALATED) so the
* wildcards-blackswans family can handle them.
*
* @see {@link https://data.europarl.europa.eu/en/developer-corner EP Open Data Portal — Developer Corner}
*/
import * as fs from 'fs/promises';
import * as path from 'path';
// ─── Types ───────────────────────────────────────────────────────────────────
/** Lifecycle status of a pending document */
export type PendingDocumentStatus = 'PENDING' | 'ESCALATED' | 'RESOLVED';
/**
* Record for a single EP adopted-text identifier that is indexed but whose
* content has not yet been populated by the EP Open Data Portal.
*/
export interface PendingDocument {
/** Document identifier (e.g., "TA-10-2026-0104") */
readonly docId: string;
/** ISO timestamp when the CONTENT_PENDING state was first observed */
firstObservedAt: string;
/** ISO timestamp of the most recent probe attempt */
lastProbedAt: string;
/** Total number of probe attempts including the initial observation */
attempts: number;
/** ISO timestamp after which the next probe may be issued */
nextProbeAfter: string;
/** Current lifecycle status */
status: PendingDocumentStatus;
}
/**
* Root store format persisted to `data/pending-documents.json`.
* Documents are keyed by docId for O(1) lookup.
*/
export interface PendingDocumentsStore {
/** Schema version for forward-compatibility */
version: string;
/** ISO timestamp of the last write */
lastUpdatedAt: string;
/** Map keyed by `docId` (e.g., `"TA-10-2026-0104"`) to the pending document record — O(1) lookup */
documents: Record<string, PendingDocument>;
}
// ─── Constants ───────────────────────────────────────────────────────────────
/** Schema version written to every store file */
export const STORE_VERSION = '1.0';
/** Initial back-off delay: 24 hours in milliseconds */
export const INITIAL_BACKOFF_MS = 24 * 60 * 60 * 1000;
/** Maximum back-off delay: 72 hours in milliseconds */
export const MAX_BACKOFF_MS = 72 * 60 * 60 * 1000;
/**
* Maximum tracking age before escalation: 14 days in milliseconds.
* After this period the document is escalated to the wildcards-blackswans
* analysis family rather than continued re-probing.
*/
export const MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
// ─── Pure computation helpers ─────────────────────────────────────────────────
/**
* Compute the ISO timestamp after which the next probe is due.
*
* The delay doubles with each attempt (exponential back-off), capped at
* {@link MAX_BACKOFF_MS}:
* - attempt 1 → 24 h
* - attempt 2 → 48 h
* - attempt 3+ → 72 h (capped)
*
* @param fromTime - ISO timestamp used as the reference point (lastProbedAt)
* @param attempts - Total probe attempts recorded so far (≥ 1)
* @returns ISO timestamp after which the next probe should be issued
*/
export function computeNextProbeAfter(fromTime: string, attempts: number): string {
const backoffMs = Math.min(INITIAL_BACKOFF_MS * Math.pow(2, attempts - 1), MAX_BACKOFF_MS);
return new Date(new Date(fromTime).getTime() + backoffMs).toISOString();
}
/**
* Return `true` when a PENDING document is due for a re-probe.
*
* @param doc - Pending document record
* @param now - Reference time (defaults to `new Date()`)
* @returns `true` if `doc.status` is PENDING and `doc.nextProbeAfter` has passed
*/
export function isDueForProbe(doc: PendingDocument, now: Date = new Date()): boolean {
if (doc.status !== 'PENDING') return false;
return new Date(doc.nextProbeAfter) <= now;
}
/**
* Return `true` when a PENDING document has exceeded the maximum tracking age
* and should be escalated to the wildcards-blackswans family.
*
* @param doc - Pending document record
* @param now - Reference time (defaults to `new Date()`)
* @returns `true` if `doc.status` is PENDING and `firstObservedAt + MAX_AGE_MS` is in the past
*/
export function isExpiredPending(doc: PendingDocument, now: Date = new Date()): boolean {
if (doc.status !== 'PENDING') return false;
return new Date(doc.firstObservedAt).getTime() + MAX_AGE_MS < now.getTime();
}
// ─── I/O helpers ─────────────────────────────────────────────────────────────
/**
* Resolve the default sidecar path: `<cwd>/data/pending-documents.json`.
* The caller may override this (e.g., for test isolation) via the optional
* `storePath` parameter accepted by every exported function.
*
* @returns Absolute path to the pending-documents sidecar file
*/
export function defaultStorePath(): string {
return path.resolve(process.cwd(), 'data', 'pending-documents.json');
}
/**
* Create an empty store with sensible defaults.
*
* @returns A fresh {@link PendingDocumentsStore} with no documents
*/
function emptyStore(): PendingDocumentsStore {
return {
version: STORE_VERSION,
lastUpdatedAt: new Date().toISOString(),
documents: {},
};
}
/**
* Load the pending documents store from disk.
* Returns an empty store when the file does not exist.
* Logs a warning and returns an empty store on any other read/parse error
* so a corrupted sidecar never blocks the workflow.
*
* @param storePath - Path override (defaults to `data/pending-documents.json`)
* @returns The loaded {@link PendingDocumentsStore}, or an empty store on ENOENT/parse error
*/
export async function loadPendingDocuments(storePath?: string): Promise<PendingDocumentsStore> {
const filePath = storePath ?? defaultStorePath();
try {
const raw = await fs.readFile(filePath, 'utf-8');
const parsed: unknown = JSON.parse(raw);
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
const obj = parsed as Record<string, unknown>;
// Validate required keys; merge defaults so a partially-written file never throws
const documents =
obj['documents'] && typeof obj['documents'] === 'object' && !Array.isArray(obj['documents'])
? (obj['documents'] as Record<string, PendingDocument>)
: {};
const version = typeof obj['version'] === 'string' ? obj['version'] : STORE_VERSION;
const lastUpdatedAt =
typeof obj['lastUpdatedAt'] === 'string' ? obj['lastUpdatedAt'] : new Date().toISOString();
return { version, lastUpdatedAt, documents };
}
return emptyStore();
} catch (err) {
const code = (err as NodeJS.ErrnoException).code;
if (code !== 'ENOENT') {
console.warn('⚠️ pending-documents: failed to load store:', (err as Error).message);
}
return emptyStore();
}
}
/**
* Persist the store to disk, creating the parent directory as needed.
* Updates `store.lastUpdatedAt` before writing.
*
* @param store - Store object to write
* @param storePath - Path override
*/
export async function savePendingDocuments(
store: PendingDocumentsStore,
storePath?: string
): Promise<void> {
const filePath = storePath ?? defaultStorePath();
await fs.mkdir(path.dirname(filePath), { recursive: true });
store.lastUpdatedAt = new Date().toISOString();
await fs.writeFile(filePath, JSON.stringify(store, null, 2) + '\n', 'utf-8');
}
// ─── Public API ───────────────────────────────────────────────────────────────
/**
* Record a document as CONTENT_PENDING.
*
* **Idempotent**: if the docId is already tracked as PENDING the function
* increments `attempts`, updates `lastProbedAt`, and recomputes
* `nextProbeAfter` — `firstObservedAt` is never overwritten.
* If the docId already has a terminal status (RESOLVED, ESCALATED) it is
* left unchanged.
*
* @param docId - Adopted-text identifier (e.g., "TA-10-2026-0104")
* @param storePath - Path override (for test isolation)
* @param now - Reference time (defaults to `new Date()`)
* @returns The updated or newly created {@link PendingDocument}
*/
export async function recordPendingDocument(
docId: string,
storePath?: string,
now: Date = new Date()
): Promise<PendingDocument> {
const store = await loadPendingDocuments(storePath);
const nowIso = now.toISOString();
const existing = store.documents[docId];
if (existing) {
if (existing.status === 'PENDING') {
// Update tracking fields; preserve firstObservedAt
existing.attempts += 1;
existing.lastProbedAt = nowIso;
existing.nextProbeAfter = computeNextProbeAfter(nowIso, existing.attempts);
await savePendingDocuments(store, storePath);
return existing;
}
// Terminal status — return as-is without write
return existing;
}
// New entry
const doc: PendingDocument = {
docId,
firstObservedAt: nowIso,
lastProbedAt: nowIso,
attempts: 1,
nextProbeAfter: computeNextProbeAfter(nowIso, 1),
status: 'PENDING',
};
store.documents[docId] = doc;
await savePendingDocuments(store, storePath);
return doc;
}
/**
* Mark a pending document as RESOLVED (content successfully retrieved on
* a subsequent probe).
*
* No-op when the docId is not in the store.
*
* @param docId - Adopted-text identifier
* @param storePath - Path override
* @param now - Reference time (defaults to `new Date()`)
*/
export async function markDocumentResolved(
docId: string,
storePath?: string,
now: Date = new Date()
): Promise<void> {
const store = await loadPendingDocuments(storePath);
const doc = store.documents[docId];
if (!doc) return;
doc.status = 'RESOLVED';
doc.lastProbedAt = now.toISOString();
await savePendingDocuments(store, storePath);
}
/**
* Return the docIds of PENDING documents whose `nextProbeAfter` has passed.
*
* @param storePath - Path override
* @param now - Reference time (defaults to `new Date()`)
* @returns Array of docIds due for reprobe (may be empty)
*/
export async function getPendingDocumentsForReprobe(
storePath?: string,
now: Date = new Date()
): Promise<string[]> {
const store = await loadPendingDocuments(storePath);
return Object.values(store.documents)
.filter((doc) => isDueForProbe(doc, now))
.map((doc) => doc.docId);
}
/**
* Escalate PENDING documents that have exceeded the 14-day maximum tracking
* age. Escalated documents are no longer returned by
* {@link getPendingDocumentsForReprobe} and should be handled by the
* wildcards-blackswans family instead.
*
* @param storePath - Path override
* @param now - Reference time (defaults to `new Date()`)
* @returns Array of docIds that were escalated
*/
export async function escalateExpiredDocuments(
storePath?: string,
now: Date = new Date()
): Promise<string[]> {
const store = await loadPendingDocuments(storePath);
const escalated: string[] = [];
for (const doc of Object.values(store.documents)) {
if (isExpiredPending(doc, now)) {
doc.status = 'ESCALATED';
escalated.push(doc.docId);
}
}
if (escalated.length > 0) {
await savePendingDocuments(store, storePath);
}
return escalated;
}
/**
* Return a human-readable summary of the sidecar for Stage B observability
* logging. Shows counts by status and lists docIds due for reprobe and
* docIds that have been escalated.
*
* @param storePath - Path override
* @param now - Reference time (defaults to `new Date()`)
* @returns Human-readable summary string for Stage B observability logging
*/
export async function getPendingDocumentsSummary(
storePath?: string,
now: Date = new Date()
): Promise<string> {
const store = await loadPendingDocuments(storePath);
const docs = Object.values(store.documents);
if (docs.length === 0) {
return 'Pending Documents: 0 tracked';
}
const pending = docs.filter((d) => d.status === 'PENDING');
const resolved = docs.filter((d) => d.status === 'RESOLVED');
const escalated = docs.filter((d) => d.status === 'ESCALATED');
const due = pending.filter((d) => isDueForProbe(d, now));
const lines: string[] = [
`Pending Documents: ${pending.length} pending, ${resolved.length} resolved, ${escalated.length} escalated`,
];
Eif (due.length > 0) {
lines.push(` Due for reprobe: ${due.map((d) => d.docId).join(', ')}`);
}
Eif (escalated.length > 0) {
lines.push(` Escalated (>14d): ${escalated.map((d) => d.docId).join(', ')}`);
}
return lines.join('\n');
}
|