/** * Source verification for the grounded teaching pipeline. * * Periodically verifies that cached source URLs are still live, * removes dead sources, and invalidates teaching caches that * fall below the minimum source threshold. */ import { prisma } from "@/lib/db"; import { verifyWikipediaUrl } from "./wikipedia"; import { MIN_SOURCES } from "./curate"; /** Sources older than this are considered stale and need re-verification. */ export const STALE_THRESHOLD_MS = 7 * 24 * 60 * 60 * 1000; // 7 days /** Maximum number of sources to verify in a single run (rate limiting). */ export const MAX_VERIFY_BATCH = 50; export interface VerificationResult { /** Total sources checked in this run. */ checked: number; /** Sources confirmed live. */ live: number; /** Sources removed (dead URLs). */ removed: number; /** Teaching caches invalidated due to insufficient sources. */ cachesInvalidated: number; /** Topic IDs whose caches were invalidated. */ invalidatedTopics: string[]; /** Duration of the verification run in milliseconds. */ durationMs: number; } /** * Get sources that need verification — either never verified or stale. */ export async function getStaleSources(limit: number = MAX_VERIFY_BATCH) { const staleDate = new Date(Date.now() - STALE_THRESHOLD_MS); return prisma.topicSource.findMany({ where: { OR: [ { verifiedAt: null }, { verifiedAt: { lt: staleDate } }, ], }, orderBy: [ { verifiedAt: "asc" }, // nulls first, then oldest ], take: limit, }); } /** * Verify a single source URL. * Returns true if the URL is live, false otherwise. */ export async function verifySourceUrl(url: string): Promise { return verifyWikipediaUrl(url); // Generic HEAD check } /** * Run a full verification pass on stale sources. * * 1. Finds sources with null or stale verifiedAt timestamps * 2. HEAD-checks each URL * 3. Updates verifiedAt for live URLs * 4. Deletes dead sources * 5. Invalidates teaching caches for topics that dropped below MIN_SOURCES */ export async function runVerification( limit: number = MAX_VERIFY_BATCH, ): Promise { const start = Date.now(); const staleSources = await getStaleSources(limit); let live = 0; let removed = 0; const affectedTopicIds = new Set(); for (const source of staleSources) { const isLive = await verifySourceUrl(source.url); if (isLive) { await prisma.topicSource.update({ where: { id: source.id }, data: { verifiedAt: new Date() }, }); live++; } else { await prisma.topicSource.delete({ where: { id: source.id }, }); removed++; affectedTopicIds.add(source.topicId); } } // Check if any affected topics dropped below the source threshold const invalidatedTopics: string[] = []; for (const topicId of affectedTopicIds) { const remainingCount = await prisma.topicSource.count({ where: { topicId }, }); if (remainingCount < MIN_SOURCES) { // Invalidate the teaching cache — it's no longer sufficiently grounded const deleted = await prisma.teachingCache.deleteMany({ where: { topicId }, }); if (deleted.count > 0) { invalidatedTopics.push(topicId); } } } return { checked: staleSources.length, live, removed, cachesInvalidated: invalidatedTopics.length, invalidatedTopics, durationMs: Date.now() - start, }; } /** * Get a summary of source health across all topics. */ export async function getSourceHealthSummary() { const staleDate = new Date(Date.now() - STALE_THRESHOLD_MS); const [totalSources, staleSources, neverVerified, totalCaches] = await Promise.all([ prisma.topicSource.count(), prisma.topicSource.count({ where: { verifiedAt: { lt: staleDate } }, }), prisma.topicSource.count({ where: { verifiedAt: null }, }), prisma.teachingCache.count(), ]); // Count unique topics with sources const topicsWithSources = await prisma.topicSource.groupBy({ by: ["topicId"], }); // Count topics with sufficient sources (>= MIN_SOURCES) const topicSourceCounts = await prisma.topicSource.groupBy({ by: ["topicId"], _count: { id: true }, }); const topicsAboveThreshold = topicSourceCounts.filter( (t) => t._count.id >= MIN_SOURCES, ).length; return { totalSources, staleSources: staleSources + neverVerified, neverVerified, freshSources: totalSources - staleSources - neverVerified, totalCaches, topicsWithSources: topicsWithSources.length, topicsAboveThreshold, minSourcesRequired: MIN_SOURCES, staleThresholdDays: STALE_THRESHOLD_MS / (24 * 60 * 60 * 1000), }; }