import { getSupabaseAdmin } from '../_shared/supabaseAdmin.js'; import { backendLogger as logger } from '../_shared/backendLogger.js'; import { normalizeSkillKey, SKILL_PROFILES } from './videoCatalog.js'; import { callGemma, extractJsonPayload } from './llm/client.js'; // ─── Types ───────────────────────────────────────────────────────────────────── export type SkillResolution = { normalizedKey: string; wasKnown: boolean; matchedVia: 'direct' | 'token' | 'fuzzy' | 'llm' | 'new'; }; export type LlmValidationResult = { valid: boolean; normalizedKey: string; category: string; aliases: string[]; confidence: number; }; // ─── In-memory known skill index (refreshed per call) ────────────────────────── type KnownSkill = { skillName: string; aliases: string[]; }; function levenshteinDistance(a: string, b: string): number { const m = a.length; const n = b.length; const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); for (let i = 0; i <= m; i++) dp[i][0] = i; for (let j = 0; j <= n; j++) dp[0][j] = j; for (let i = 1; i <= m; i++) { for (let j = 1; j <= n; j++) { dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]); } } return dp[m][n]; } // Simple metaphone-like phonetic encoding for English terms function phoneticKey(word: string): string { const s = word.toLowerCase().replace(/[^a-z]/g, ''); if (s.length < 2) return s; let result = s[0]; for (let i = 1; i < s.length; i++) { const c = s[i]; const prev = s[i - 1]; // Skip duplicate consecutive consonants (except when different) if (c === prev) continue; // Vowel reduction after first char if ('aeiou'.includes(c) && i > 1 && 'aeiou'.includes(prev)) continue; // Consonant grouping const ph = c === 'p' && s[i + 1] === 'h' ? 'f' : c === 'c' && 'iey'.includes(s[i + 1] || '') ? 's' : c === 'c' ? 'k' : c === 'g' && s[i + 1] === 'h' ? '' : c === 'j' ? 'j' : c === 'k' && prev === 'c' ? '' : c === 'm' && prev === 'n' ? '' : c === 'n' && prev === 'm' ? '' : c === 'q' ? 'k' : c === 'x' ? 'ks' : c === 'y' && i < s.length - 1 ? 'i' : c === 'z' ? 's' : c === 'w' && 'aeiou'.includes(s[i + 1] || '') ? 'w' : c === 'h' && 'aeiou'.includes(prev) && i < s.length - 1 && 'aeiou'.includes(s[i + 1]) ? '' : 'aeiou'.includes(c) ? '' : c; if (ph) result += ph; } return result.replace(/(.)\1+/g, '$1').slice(0, 4); } // ─── Build known skill index from catalog + DB ───────────────────────────────── function getCatalogKnownSkills(): KnownSkill[] { return SKILL_PROFILES .filter((p) => p.key !== 'default') .map((p) => ({ skillName: p.key, aliases: p.aliases, })); } async function getDbKnownSkills(): Promise { try { const supabase = getSupabaseAdmin(); const { data, error } = await supabase .from('known_skills') .select('skill_name, aliases'); if (error || !data) { logger.warn('[SkillValidation] Failed to fetch known_skills from DB', { error: error?.message }); return []; } return (data as Array<{ skill_name: string; aliases: string[] | string }>).map((row) => { const aliases: string[] = Array.isArray(row.aliases) ? row.aliases : typeof row.aliases === 'string' ? JSON.parse(row.aliases) : []; return { skillName: row.skill_name, aliases }; }); } catch (err) { logger.warn('[SkillValidation] DB known_skills lookup failed', { error: String(err) }); return []; } } function collectAllNames(known: KnownSkill[]): Array<{ name: string; key: string }> { const entries: Array<{ name: string; key: string }> = []; for (const ks of known) { entries.push({ name: ks.skillName.toLowerCase(), key: ks.skillName }); for (const alias of ks.aliases) { entries.push({ name: alias.toLowerCase(), key: ks.skillName }); } } return entries; } // ─── Stage 1: Direct match via existing normalizeSkillKey ────────────────────── function stage1Direct(skill: string): { key: string; matched: boolean } { // The existing normalizeSkillKey already does regex-based matching against SKILL_MATCHERS const key = normalizeSkillKey(skill); // Only consider it a match if it's not "default" and not a raw slug const isKnownKey = SKILL_PROFILES.some((p) => p.key === key && p.key !== 'default'); if (isKnownKey) { return { key, matched: true }; } return { key, matched: false }; } // ─── Stage 2: Token decomposition ───────────────────────────────────────────── const FILLER_WORDS = new Set([ 'in', 'the', 'a', 'an', 'for', 'of', 'to', 'and', 'or', 'with', 'using', 'on', 'at', 'by', 'is', 'it', 'engineering', 'engineer', 'developer', 'development', 'basics', 'fundamentals', 'programming', 'course', 'tutorial' ]); function stage2Token(skill: string, allNames: Array<{ name: string; key: string }>): string | null { const trimmed = skill.trim().toLowerCase(); // If the full string matches any known name, use that const exact = allNames.find((n) => n.name === trimmed); if (exact) return exact.key; // Tokenize: split on spaces, hyphens, slashes, commas const tokens = trimmed.split(/[\s\-/,;]+/).filter(Boolean); if (tokens.length < 2) return null; // Check n-grams of consecutive tokens first (prefers multi-word matches over single-token) for (let len = tokens.length; len >= 2; len--) { for (let start = 0; start <= tokens.length - len; start++) { const phrase = tokens.slice(start, start + len).join(' '); const match = allNames.find((n) => n.name === phrase); if (match) return match.key; } } // Check individual meaningful tokens after stripping filler words (e.g. "Framer Basics" -> "framer") const meaningful = tokens.filter((t) => !FILLER_WORDS.has(t)); for (const token of meaningful) { const match = allNames.find((n) => n.name === token); if (match) return match.key; } return null; } // ─── Stage 3: Levenshtein fuzzy match ───────────────────────────────────────── function stage3Fuzzy(skill: string, allNames: Array<{ name: string; key: string }>): string | null { const trimmed = skill.trim().toLowerCase(); const queryTokens = trimmed.split(/[\s\-/,;]+/).filter(Boolean); // Multi-word queries: strict tolerance to avoid altering distinct words if (queryTokens.length > 1) { let best: { key: string; distance: number } | null = null; for (const entry of allNames) { if (Math.abs(trimmed.length - entry.name.length) > 1) continue; const dist = levenshteinDistance(trimmed, entry.name); if (dist <= 1 && (!best || dist < best.distance)) { best = { key: entry.key, distance: dist }; } } return best?.key || null; } // Single-word typos: tolerance 1-2 based on length let best: { key: string; distance: number } | null = null; for (const entry of allNames) { if (Math.abs(trimmed.length - entry.name.length) > 2) continue; const dist = levenshteinDistance(trimmed, entry.name); const maxAllowed = trimmed.length <= 4 ? 1 : 2; if (dist <= maxAllowed && (!best || dist < best.distance)) { best = { key: entry.key, distance: dist }; } } return best?.key || null; } // ─── Stage 4: Phonetic match ─────────────────────────────────────────────────── function stage4Phonetic(skill: string, allNames: Array<{ name: string; key: string }>): string | null { const trimmed = skill.trim().toLowerCase(); const skillPhonetic = phoneticKey(trimmed); if (skillPhonetic.length < 2) return null; for (const entry of allNames) { const entryPhonetic = phoneticKey(entry.name); if (entryPhonetic.length > 1 && skillPhonetic === entryPhonetic) { return entry.key; } } return null; } // ─── Stage 5: LLM Validation ─────────────────────────────────────────────────── export function buildValidationPrompt(skill: string): string { return [ 'You are GetCert Skill Validator. Determine if the provided skill name is a legitimate, learnable technical/professional skill.', '', 'A valid skill must:', '- Be a recognized domain in programming, IT, data science, cloud, cybersecurity, DevOps, design, or related technical fields', '- Have a structured curriculum with measurable learning outcomes', '- Be assessable through standardized testing (MCQs, projects, or both)', '', 'An invalid skill is:', '- A hobby or non-technical activity (e.g., "cooking", "gardening", "dog walking")', '- A vague or meaningless term (e.g., "stuff", "things", "general knowledge")', '- A brand name without technical substance (e.g., just "Google" without "Google Cloud" or "Android")', '- Gibberish, spam, or profanity', '', `Skill to validate: "${skill}"`, '', 'Return strict JSON only with this exact schema:', '{', ' "valid": true|false,', ' "normalizedKey": "kebab-case-canonical-name",', ' "category": "frontend|backend|programming|data|devops|cloud|cybersecurity|design|mobile|ai|other",', ' "aliases": ["common", "alternative", "names"],', ' "confidence": 0.0-1.0', '}', '', 'Rules:', '- "normalizedKey" must be a short kebab-case identifier (e.g., "react", "google-cloud", "kubernetes")', '- "aliases" should include common alternative names and abbreviations', '- "confidence" reflects how certain you are (0.9+ for well-known skills, lower for obscure but valid ones)', '- If invalid, set "valid" to false and "confidence" below 0.5', '- No markdown fences. No explanatory prose outside JSON.', '- Be inclusive of emerging technologies and frameworks that have real curriculum potential.', ].join('\n'); } function cleanAliases(aliases: unknown): string[] { if (Array.isArray(aliases)) { return aliases .filter((a): a is string => typeof a === 'string') .map((a) => a.trim().toLowerCase()) .filter(Boolean); } return []; } export async function validateWithLlm(skill: string): Promise { const prompt = buildValidationPrompt(skill); const text = await callGemma( [ { role: 'system', content: 'You are GetCert Skill Validator. Respond only with valid JSON.' }, { role: 'user', content: prompt }, ], { temperature: 0.1, maxTokens: 600, responseFormat: 'json_object', timeoutMs: 60000, } ); const parsed = extractJsonPayload<{ valid: boolean; normalizedKey: string; category: string; aliases: string[]; confidence: number; }>(text); const aliases = cleanAliases(parsed.aliases); // Deduplicate: remove the skill name itself from aliases if present const filteredAliases = aliases.filter((a) => a !== skill.trim().toLowerCase() && a !== parsed.normalizedKey); return { valid: Boolean(parsed.valid) && parsed.confidence >= 0.3, normalizedKey: (parsed.normalizedKey || '').trim().toLowerCase().replace(/[^a-z0-9-]/g, '') || skill.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-'), category: parsed.category || 'other', aliases: filteredAliases, confidence: typeof parsed.confidence === 'number' ? parsed.confidence : 0, }; } // ─── Insert new skill into known_skills DB ────────────────────────────────────── export async function addNewSkillToDb(result: LlmValidationResult): Promise { try { const supabase = getSupabaseAdmin(); const existingAliases = [...new Set([result.normalizedKey, ...result.aliases])]; const { error } = await supabase .from('known_skills') .upsert( { skill_name: result.normalizedKey, aliases: JSON.stringify(existingAliases), category: result.category || 'other', source: 'llm_generated', }, { onConflict: 'skill_name', ignoreDuplicates: false } ); if (error) { logger.warn('[SkillValidation] Failed to insert new skill to DB', { error: error.message, skill: result.normalizedKey }); } else { logger.info('[SkillValidation] New skill indexed', { skill: result.normalizedKey, aliases: existingAliases }); } } catch (err) { logger.warn('[SkillValidation] DB insert failed', { error: String(err), skill: result.normalizedKey }); } } // ─── Log skill request for demand tracking ───────────────────────────────────── export async function logSkillRequest(params: { skillName: string; userId?: string; normalizedKey: string; wasKnown: boolean; }): Promise { try { const supabase = getSupabaseAdmin(); const { error } = await supabase .from('skill_requests') .insert({ skill_name: params.skillName.trim().toLowerCase(), user_id: params.userId || null, normalized_key: params.normalizedKey, was_known: params.wasKnown, }); if (error) { logger.warn('[SkillValidation] Failed to log skill request', { error: error.message }); } } catch (err) { logger.warn('[SkillValidation] Skill request log failed', { error: String(err) }); } } // ─── Daily rate limit check ──────────────────────────────────────────────────── export async function getUnknownSkillAttemptsToday(userId?: string): Promise { if (!userId) return 0; try { const supabase = getSupabaseAdmin(); const today = new Date(); today.setHours(0, 0, 0, 0); const { count, error } = await supabase .from('skill_requests') .select('id', { count: 'exact', head: true }) .eq('user_id', userId) .eq('was_known', false) .gte('created_at', today.toISOString()); if (error) { logger.warn('[SkillValidation] Rate limit check failed', { error: error.message }); return 0; } return count || 0; } catch (err) { logger.warn('[SkillValidation] Rate limit check error', { error: String(err) }); return 0; } } // ─── Main resolver: multi-stage known/unknown detection ──────────────────────── export async function resolveSkill( skill: string ): Promise { const trimmed = skill.trim(); if (!trimmed) { return { normalizedKey: 'default', wasKnown: false, matchedVia: 'new' }; } // Build the known skill index from catalog + DB const catalogKnown = getCatalogKnownSkills(); const dbKnown = await getDbKnownSkills(); const allKnown = [...catalogKnown]; // Merge DB skills that aren't already in catalog for (const db of dbKnown) { if (!allKnown.some((k) => k.skillName === db.skillName)) { allKnown.push(db); } } const allNames = collectAllNames(allKnown); // Stage 1: Direct match via normalizeSkillKey (SKILL_MATCHERS regex) const stage1 = stage1Direct(trimmed); if (stage1.matched) { return { normalizedKey: stage1.key, wasKnown: true, matchedVia: 'direct' }; } // Stage 2: Token decomposition const stage2 = stage2Token(trimmed, allNames); if (stage2) { return { normalizedKey: stage2, wasKnown: true, matchedVia: 'token' }; } // Stage 3: Levenshtein fuzzy match const stage3 = stage3Fuzzy(trimmed, allNames); if (stage3) { return { normalizedKey: stage3, wasKnown: true, matchedVia: 'fuzzy' }; } // Stage 4: Phonetic match const stage4 = stage4Phonetic(trimmed, allNames); if (stage4) { return { normalizedKey: stage4, wasKnown: true, matchedVia: 'fuzzy' }; } // Unknown skill — return the slugified version for possible LLM validation return { normalizedKey: trimmed.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'default', wasKnown: false, matchedVia: 'new', }; }