/** * Preemption Risk Scoring Engine * * Calculates risk scores and generates compliance impact assessments * * @author Jason Pellerin AI Solutionist */ import { RISK_WEIGHTS, PREEMPTION_PRECEDENTS } from '../utils/constants.js'; import { STATE_AI_REGULATIONS } from '../utils/types.js'; import type { Input, PreemptionEvent, PreemptionRisk, ComplianceImpact, RagChunk, PreemptionBasis, RiskTimeline, StateConflict, ConflictAnalysis, StrategicOption, StateRegulation, } from '../utils/types.js'; // ═══════════════════════════════════════════════════════════════════════════ // Risk Calculation // ═══════════════════════════════════════════════════════════════════════════ export function calculatePreemptionRisk( event: PreemptionEvent, input: Input ): { risk: PreemptionRisk; impact: ComplianceImpact } { // Start with base score from event type let score = 0; const basisFactors: PreemptionBasis[] = []; // Event type weight (0-100) const eventTypeWeight = RISK_WEIGHTS.eventType[event.eventType] || 0.5; score += eventTypeWeight * 30; // Federal authority weight const authorityWeight = RISK_WEIGHTS.authority[event.federalAuthority] || 0.5; score += authorityWeight * 25; // Detect preemption basis from text const textContent = `${event.title} ${event.summary}`.toLowerCase(); const detectedBasis = detectPreemptionBasis(textContent); basisFactors.push(...detectedBasis); // Add basis weights for (const basis of detectedBasis) { const basisWeight = RISK_WEIGHTS.basis[basis] || 0.5; score += basisWeight * 10; } // State-specific relevance boost const stateRelevance = calculateStateRelevance(event.affectedStates, input.targetStates); score += stateRelevance * 20; // Timeline urgency const timeline = inferTimeline(event); const timelineWeight = RISK_WEIGHTS.timeline[timeline]; score += timelineWeight * 15; // Cap at 100 score = Math.min(Math.round(score), 100); // Determine risk level const level = score >= 80 ? 'critical' : score >= 60 ? 'high' : score >= 40 ? 'medium' : 'low'; // Generate reasoning const reasoning = generateRiskReasoning(event, score, basisFactors, timeline); // Calculate confidence based on data completeness const confidence = calculateConfidence(event); const risk: PreemptionRisk = { score, level, basis: basisFactors, timeline, confidence, reasoning, }; // Generate compliance impact const impact = generateComplianceImpact(event, risk, input); return { risk, impact }; } /** * Detect preemption basis from event text */ function detectPreemptionBasis(text: string): PreemptionBasis[] { const basis: PreemptionBasis[] = []; // Express preemption signals if (/explicitly preempt|express preemption|preempts state|federal law supersede/i.test(text)) { basis.push('express_preemption'); } // Field preemption signals if (/occupy.*field|comprehensive.*scheme|pervasive.*regulation|exclusive.*jurisdiction/i.test(text)) { basis.push('field_preemption'); } // Conflict preemption signals if (/conflict.*with|obstacle.*federal|frustrate.*purpose|impossib.*comply/i.test(text)) { basis.push('conflict_preemption'); } // Commerce clause signals if (/burden.*interstate.*commerce|commerce clause|dormant commerce/i.test(text)) { basis.push('commerce_clause'); } // Supremacy clause signals if (/supremacy clause|supreme law|constitution.*preempt/i.test(text)) { basis.push('supremacy_clause'); } // Federal agency exclusive authority if (/exclusive authority|sole jurisdiction|federal agency.*exclusive/i.test(text)) { basis.push('agency_exclusive'); } // Federal funding threat (EO 14281 style) if (/withhold.*fund|condition.*grant|federal.*funding.*threat|broadband grant/i.test(text)) { basis.push('federal_funding_threat'); } // Default to conflict preemption if preemption mentioned without specifics if (basis.length === 0 && /preempt/i.test(text)) { basis.push('conflict_preemption'); } return basis; } /** * Infer timeline from event data */ function inferTimeline(event: PreemptionEvent): RiskTimeline { const now = new Date(); // Active litigation or enforcement if (event.eventType === 'enforcement_action' || event.eventType === 'preemption_challenge') { return 'immediate'; } // Check for effective dates if (event.dateEffective) { const effectiveDate = new Date(event.dateEffective); const monthsUntil = (effectiveDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24 * 30); if (monthsUntil <= 0) return 'immediate'; if (monthsUntil <= 6) return 'near_term'; if (monthsUntil <= 18) return 'medium_term'; return 'long_term'; } // Court opinions have immediate effect if (event.eventType === 'court_opinion') { return 'immediate'; } // Executive orders typically immediate if (event.eventType === 'executive_order') { return 'near_term'; } // Final rules usually near term if (event.eventType === 'federal_rule_final') { return 'near_term'; } // Proposed rules are medium term if (event.eventType === 'federal_rule_proposed') { return 'medium_term'; } return 'speculative'; } /** * Calculate state relevance factor */ function calculateStateRelevance(affectedStates: string[], targetStates: string[]): number { if (targetStates.includes('ALL')) return 1.0; if (affectedStates.length === 0) return 0.5; // Unknown applicability const overlap = affectedStates.filter(s => targetStates.includes(s)).length; return overlap / targetStates.length; } /** * Calculate confidence score based on data completeness */ function calculateConfidence(event: PreemptionEvent): number { let confidence = 50; // Base confidence if (event.summary && event.summary.length > 100) confidence += 10; if (event.dateEffective) confidence += 10; if (event.affectedStates.length > 0) confidence += 10; if (event.affectedProvisions.length > 0) confidence += 10; if (event.citations && event.citations.length > 0) confidence += 10; return Math.min(confidence, 95); } /** * Generate human-readable risk reasoning */ function generateRiskReasoning( event: PreemptionEvent, score: number, basis: PreemptionBasis[], timeline: RiskTimeline ): string { const parts: string[] = []; // Event type context const eventTypeDescriptions: Record = { executive_order: 'Executive Order with direct presidential authority', court_opinion: 'Federal court decision with binding precedent', court_case: 'Pending federal litigation', doj_action: 'DOJ enforcement or policy action', federal_rule_final: 'Final federal rule with force of law', federal_rule_proposed: 'Proposed rule signaling federal intent', agency_guidance: 'Federal agency guidance document', }; parts.push(eventTypeDescriptions[event.eventType] || 'Federal action'); // Basis description if (basis.includes('express_preemption')) { parts.push('explicitly preempts state regulation'); } else if (basis.includes('field_preemption')) { parts.push('may occupy the regulatory field'); } else if (basis.includes('conflict_preemption')) { parts.push('creates potential conflict with state requirements'); } else if (basis.includes('federal_funding_threat')) { parts.push('threatens federal funding for non-compliance'); } // Timeline context const timelineDescriptions: Record = { immediate: 'Requires immediate compliance attention', near_term: 'Action needed within 6 months', medium_term: 'Monitor and prepare for 6-18 month horizon', long_term: 'Track for strategic planning', speculative: 'Uncertain timeline - monitor for developments', }; parts.push(timelineDescriptions[timeline]); return parts.join('. ') + '.'; } // ═══════════════════════════════════════════════════════════════════════════ // Compliance Impact Generation // ═══════════════════════════════════════════════════════════════════════════ function generateComplianceImpact( event: PreemptionEvent, risk: PreemptionRisk, input: Input ): ComplianceImpact { const severity = risk.level === 'critical' ? 'urgent' : risk.level === 'high' ? 'actionable' : risk.level === 'medium' ? 'advisory' : 'informational'; // Identify affected requirements based on provisions const affectedRequirements: string[] = []; for (const provision of event.affectedProvisions) { if (provision.includes('6-1-1602')) { affectedRequirements.push('Algorithmic discrimination testing requirements'); } if (provision.includes('6-1-1703')) { affectedRequirements.push('Annual impact assessment requirements'); } if (provision.includes('6-1-1703.4')) { affectedRequirements.push('Consumer notification obligations'); } if (provision.includes('SB 1047')) { affectedRequirements.push('Frontier AI safety evaluations'); } } // Generate recommended actions based on risk level const recommendedActions: string[] = []; if (risk.level === 'critical' || risk.level === 'high') { recommendedActions.push('Immediate legal review of compliance strategy'); recommendedActions.push('Assess operational impact on AI deployments'); recommendedActions.push('Document current compliance posture for potential defense'); } if (risk.basis.includes('federal_funding_threat')) { recommendedActions.push('Inventory federal grants and funding at risk'); recommendedActions.push('Evaluate cost-benefit of maintaining state compliance vs. federal alignment'); } if (risk.timeline === 'immediate' || risk.timeline === 'near_term') { recommendedActions.push('Engage compliance counsel for strategy adjustment'); recommendedActions.push('Monitor for implementation guidance'); } else { recommendedActions.push('Add to compliance monitoring calendar'); recommendedActions.push('Include in next quarterly risk assessment'); } // Compile deadlines const deadlines = event.complianceImpact?.deadlines || []; return { severity, affectedRequirements, recommendedActions, deadlines, }; } // ═══════════════════════════════════════════════════════════════════════════ // RAG Chunk Generation // ═══════════════════════════════════════════════════════════════════════════ export function generateRagChunks(event: PreemptionEvent): RagChunk[] { const chunks: RagChunk[] = []; const baseMetadata = { source: event.source, date: event.datePublished, relevanceScore: event.preemptionRisk?.score || 50, }; // Summary chunk chunks.push({ id: `${event.id}-summary`, content: `${event.title}\n\n${event.summary}`, chunkType: 'summary', metadata: { ...baseMetadata, tokens: estimateTokens(event.title + event.summary) }, }); // Requirements chunk if applicable if (event.affectedProvisions.length > 0) { const requirementsContent = `Affected State Provisions:\n${event.affectedProvisions.map(p => `- ${p}`).join('\n')}`; chunks.push({ id: `${event.id}-requirements`, content: requirementsContent, chunkType: 'requirement', metadata: { ...baseMetadata, tokens: estimateTokens(requirementsContent) }, }); } // Deadline chunk if applicable const deadlines = event.complianceImpact?.deadlines || []; if (deadlines.length > 0) { const deadlineContent = `Key Deadlines:\n${deadlines.map(d => `- ${d.date}: ${d.description}`).join('\n')}`; chunks.push({ id: `${event.id}-deadlines`, content: deadlineContent, chunkType: 'deadline', metadata: { ...baseMetadata, tokens: estimateTokens(deadlineContent) }, }); } // Citation chunk if applicable const citations = event.citations || []; if (citations.length > 0) { const citationContent = `Legal Citations:\n${citations.map(c => `- ${c.citation}`).join('\n')}`; chunks.push({ id: `${event.id}-citations`, content: citationContent, chunkType: 'citation', metadata: { ...baseMetadata, tokens: estimateTokens(citationContent) }, }); } return chunks; } function estimateTokens(text: string): number { // Rough estimate: ~4 characters per token return Math.ceil(text.length / 4); } // ═══════════════════════════════════════════════════════════════════════════ // State Conflict Analysis // ═══════════════════════════════════════════════════════════════════════════ export function analyzeStateConflicts( events: PreemptionEvent[], targetStates: string[] ): StateConflict[] { const conflicts: StateConflict[] = []; const relevantRegulations = STATE_AI_REGULATIONS.filter( (r: StateRegulation) => targetStates.includes(r.state) || targetStates.includes('ALL') ); for (const regulation of relevantRegulations) { for (const event of events) { // Check if event affects this state if (!event.affectedStates.includes(regulation.state) && event.affectedStates.length > 0) { continue; } // Determine conflict type const conflictType = determineConflictType(event, regulation); if (!conflictType) continue; // Calculate severity const conflictSeverity = event.preemptionRisk.level; // Generate analysis const analysis = generateConflictAnalysis(event, regulation); // Generate strategic options const strategicOptions = generateStrategicOptions(event, regulation, analysis); conflicts.push({ id: `conflict-${regulation.state}-${event.id}`, stateRegulation: regulation, federalEvent: event, conflictType, conflictSeverity, analysis, strategicOptions, }); } } return conflicts; } function determineConflictType( event: PreemptionEvent, regulation: import('../utils/types.js').StateRegulation ): import('../utils/types.js').ConflictType | null { const text = `${event.title} ${event.summary}`.toLowerCase(); // Check for direct conflicts with specific provisions for (const conflictPoint of regulation.federalConflictPoints) { if (text.includes(conflictPoint.toLowerCase().split(' ')[0])) { return 'direct_conflict'; } } // Check for enforcement conflicts if (/enforcement|attorney general|penalt/i.test(text)) { return 'enforcement_conflict'; } // Check for definitional conflicts if (/defin|meaning|interpret/i.test(text)) { return 'definitional_conflict'; } // Check for coverage overlap if (/high.risk|consequential decision|algorithm/i.test(text)) { return 'coverage_overlap'; } // If strong preemption language but no specific match if (event.preemptionRisk.score >= 50) { return 'implicit_conflict'; } return null; } function generateConflictAnalysis( event: PreemptionEvent, regulation: import('../utils/types.js').StateRegulation ): ConflictAnalysis { return { summary: `${event.title} creates potential ${event.preemptionRisk.level} risk for ${regulation.title} compliance`, federalPosition: `Federal action ${event.preemptionRisk.basis.map(b => b.replace(/_/g, ' ')).join(', ')}`, statePosition: `${regulation.state} maintains ${regulation.keyProvisions.length} key provisions including ${regulation.keyProvisions[0]}`, likelyOutcome: event.preemptionRisk.score >= 70 ? 'High probability of federal preemption or compliance friction' : 'Uncertain outcome - monitor for additional developments', precedents: PREEMPTION_PRECEDENTS.slice(0, 2).map(p => `${p.case} - ${p.holding}`), openQuestions: [ 'Will federal courts apply field or conflict preemption analysis?', 'Does state law frustrate federal objectives or merely add to them?', 'Will federal agency assert exclusive jurisdiction?', ], }; } function generateStrategicOptions( event: PreemptionEvent, regulation: import('../utils/types.js').StateRegulation, analysis: ConflictAnalysis ): StrategicOption[] { const options: StrategicOption[] = []; // Option 1: Maintain state compliance with federal monitoring options.push({ strategy: 'State Compliance Priority', description: `Continue ${regulation.state} compliance while monitoring federal developments`, pros: [ 'Maintains affirmative defense under state law', 'Protects against state enforcement ($20K/violation in CO)', 'Demonstrates good faith compliance posture', ], cons: [ 'May create friction with federal requirements if preemption succeeds', 'Potential compliance cost duplication', ], estimatedCost: { estimatedRange: { low: 50000, high: 200000 }, basis: 'Based on typical compliance implementation costs', affectedOrganizations: 'Deployers of high-risk AI in consequential decisions', }, timeline: 'Ongoing through June 2026 CAIA deadline', riskLevel: 'medium', }); // Option 2: Federal alignment with state modification if (event.preemptionRisk.score >= 70) { options.push({ strategy: 'Federal Alignment', description: 'Prioritize federal requirements and seek state law modifications or waivers', pros: [ 'Reduces conflict exposure', 'May preserve federal funding eligibility', 'Simpler nationwide compliance if federal becomes dominant', ], cons: [ 'State enforcement risk during transition', 'May lose state-level competitive advantages', 'Uncertain timeline for federal clarity', ], estimatedCost: { estimatedRange: { low: 100000, high: 500000 }, basis: 'Legal advocacy, compliance restructuring, potential penalties', affectedOrganizations: 'Multi-state AI deployers', }, timeline: '12-24 months for federal landscape clarity', riskLevel: 'high', }); } // Option 3: Wait and see options.push({ strategy: 'Active Monitoring', description: 'Monitor developments closely before committing to compliance strategy', pros: [ 'Preserves flexibility', 'Lower upfront cost', 'May benefit from regulatory clarity', ], cons: [ 'Risk of rushed compliance if deadlines approach', 'May miss early mover advantages', 'State enforcement exposure', ], estimatedCost: { estimatedRange: { low: 10000, high: 50000 }, basis: 'Legal monitoring and periodic assessments', affectedOrganizations: 'All AI deployers', }, timeline: 'Quarterly review cycle', riskLevel: 'low', }); return options; }