import { createClient } from '@supabase/supabase-js'; import dotenv from 'dotenv'; import fs from 'fs'; import path from 'path'; const envLocalPath = path.resolve(process.cwd(), '.env.local'); if (fs.existsSync(envLocalPath)) { dotenv.config({ path: envLocalPath }); } else { dotenv.config(); } const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseServiceKey) { console.error('Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env.local'); process.exit(1); } const supabase = createClient(supabaseUrl, supabaseServiceKey, { auth: { persistSession: false }, }); const GENERIC_TAGS = new Set([ 'ai', 'artificial intelligence', 'general ai', 'technology', 'tech', 'news', 'updates', ]); const TAXONOMY = [ { name: 'Large Language Models', icon: 'Brain', keywords: ['llm', 'large language model', 'gpt-4', 'gpt-5', 'claude', 'gemini', 'mistral', 'llama', 'foundation model'] }, { name: 'Natural Language Processing', icon: 'Languages', keywords: ['nlp', 'natural language', 'token', 'text processing', 'semantic search'] }, { name: 'Computer Vision', icon: 'Eye', keywords: ['computer vision', 'image recognition', 'object detection', 'segmentation', 'vision model'] }, { name: 'Robotics', icon: 'Bot', keywords: ['robot', 'robotics', 'humanoid', 'automation hardware', 'manipulation'] }, { name: 'AI Agents', icon: 'Bot', keywords: ['agent', 'autonomous agent', 'agentic', 'multi-agent', 'tool use'] }, { name: 'Prompt Engineering', icon: 'MessageSquare', keywords: ['prompt', 'prompting', 'system prompt', 'chain-of-thought', 'instruction tuning'] }, { name: 'Generative AI', icon: 'Sparkles', keywords: ['generative ai', 'genai', 'generation', 'content generation', 'diffusion', 'sora'] }, { name: 'Multimodal AI', icon: 'Layers', keywords: ['multimodal', 'text and image', 'audio and video', 'vision-language'] }, { name: 'Speech Recognition', icon: 'Mic', keywords: ['speech-to-text', 'asr', 'voice recognition', 'transcription'] }, { name: 'Text-to-Speech', icon: 'Volume2', keywords: ['text-to-speech', 'tts', 'voice synthesis', 'speech synthesis'] }, { name: 'AI Coding', icon: 'Code2', keywords: ['code generation', 'coding assistant', 'copilot', 'developer assistant', 'software engineering ai'] }, { name: 'Developer Tools', icon: 'Wrench', keywords: ['sdk', 'api', 'framework', 'developer tool', 'platform', 'cli'] }, { name: 'MLOps', icon: 'GitBranch', keywords: ['mlops', 'deployment', 'model serving', 'model monitoring', 'pipeline', 'orchestration'] }, { name: 'Data Analysis', icon: 'BarChart3', keywords: ['analytics', 'data analysis', 'bi', 'insights', 'dashboard'] }, { name: 'Vector Databases', icon: 'Database', keywords: ['vector database', 'embedding store', 'pinecone', 'weaviate', 'chroma', 'pgvector'] }, { name: 'Retrieval-Augmented Generation', icon: 'Search', keywords: ['rag', 'retrieval-augmented generation', 'retrieval augmented generation', 'knowledge retrieval'] }, { name: 'Fine-Tuning', icon: 'SlidersHorizontal', keywords: ['fine-tuning', 'fine tuning', 'sft', 'rlhf', 'adapters', 'lora'] }, { name: 'Open Source AI', icon: 'Code', keywords: ['open source', 'open-weight', 'github model', 'community model'] }, { name: 'Model Evaluation', icon: 'ClipboardCheck', keywords: ['benchmark', 'evaluation', 'evals', 'hallucination', 'accuracy testing'] }, { name: 'AI Safety', icon: 'Shield', keywords: ['ai safety', 'alignment', 'red team', 'guardrails', 'risk mitigation'] }, { name: 'AI Ethics', icon: 'Scale', keywords: ['ethics', 'bias', 'fairness', 'responsible ai', 'transparency'] }, { name: 'AI Governance', icon: 'Building2', keywords: ['governance', 'policy', 'compliance framework', 'accountability'] }, { name: 'AI Regulation', icon: 'Gavel', keywords: ['regulation', 'regulatory', 'law', 'legal compliance', 'eu ai act', 'ftc'] }, { name: 'Healthcare AI', icon: 'HeartPulse', keywords: ['healthcare', 'medical', 'clinical', 'diagnostic', 'hospital'] }, { name: 'Finance AI', icon: 'Landmark', keywords: ['finance', 'fintech', 'trading', 'banking', 'risk modeling'] }, { name: 'Education AI', icon: 'GraduationCap', keywords: ['education', 'learning', 'tutoring', 'edtech', 'student'] }, { name: 'Marketing AI', icon: 'Megaphone', keywords: ['marketing', 'ad copy', 'campaign', 'seo', 'social media'] }, { name: 'Enterprise AI', icon: 'Briefcase', keywords: ['enterprise', 'b2b', 'workflow automation', 'business operations'] }, { name: 'Customer Support AI', icon: 'Headphones', keywords: ['customer support', 'support bot', 'helpdesk', 'ticket automation'] }, { name: 'Deep Learning', icon: 'Network', keywords: ['deep learning', 'neural network', 'transformer', 'cnn', 'rnn'] }, { name: 'Reinforcement Learning', icon: 'Gamepad2', keywords: ['reinforcement learning', 'rl', 'policy gradient', 'reward model'] }, { name: 'Autonomous Vehicles', icon: 'Car', keywords: ['autonomous vehicle', 'self-driving', 'autopilot'] }, { name: 'Edge AI', icon: 'Cpu', keywords: ['edge ai', 'on-device', 'edge inference', 'mobile inference'] }, { name: 'AI Hardware', icon: 'Cpu', keywords: ['gpu', 'npu', 'accelerator', 'chip', 'inference hardware'] }, { name: 'Synthetic Media', icon: 'Image', keywords: ['synthetic media', 'deepfake', 'ai image', 'ai video', 'image generation'] }, { name: 'AI Startups', icon: 'Rocket', keywords: ['startup', 'funding', 'seed round', 'series a', 'vc'] }, { name: 'AI Research', icon: 'FlaskConical', keywords: ['research', 'paper', 'arxiv', 'study', 'novel method'] }, ]; const FALLBACK_TAGS = ['Generative AI', 'Developer Tools', 'AI Research', 'Enterprise AI', 'AI Agents']; const tableCandidates = { news: ['news', 'news_stories'], postsJunction: ['post_categories', 'posts_categories', 'blog_posts_categories'], newsJunction: ['news_categories'], }; function slugify(input) { return String(input || '') .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/(^-|-$)/g, ''); } function isGenericTag(tagName) { return GENERIC_TAGS.has(String(tagName || '').trim().toLowerCase()); } async function detectTable(candidates) { for (const table of candidates) { const { error } = await supabase.from(table).select('*').limit(1); if (!error) return table; const msg = String(error.message || '').toLowerCase(); if (msg.includes('does not exist') || msg.includes('relation') || msg.includes('schema cache')) { continue; } } return null; } function countKeywordMatches(text, keyword) { if (!keyword) return 0; const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const regex = new RegExp(`\\b${escaped}\\b`, 'gi'); const matches = text.match(regex); return matches ? matches.length : 0; } function inferTagNames(item, existingCategoryNames) { const title = String(item.title || '').toLowerCase(); const body = `${item.summary || ''}\n${item.content || ''}`.toLowerCase().slice(0, 35000); const combined = `${title}\n${body}`; const scoreMap = new Map(); for (const def of TAXONOMY) { let score = 0; for (const keyword of def.keywords) { const titleHits = countKeywordMatches(title, keyword); const bodyHits = countKeywordMatches(body, keyword); score += titleHits * 4 + bodyHits; } if (score > 0) scoreMap.set(def.name, score); } for (const existingName of existingCategoryNames) { if (isGenericTag(existingName)) continue; const current = scoreMap.get(existingName) || 0; scoreMap.set(existingName, current + 3); } const sorted = [...scoreMap.entries()].sort((a, b) => b[1] - a[1]); const selected = []; for (const [name] of sorted) { if (!selected.includes(name)) selected.push(name); if (selected.length >= 5) break; } for (const existingName of existingCategoryNames) { if (selected.length >= 5) break; if (isGenericTag(existingName)) continue; if (!selected.includes(existingName)) selected.push(existingName); } for (const fallback of FALLBACK_TAGS) { if (selected.length >= 3) break; if (!selected.includes(fallback)) selected.push(fallback); } if (selected.length === 0) { selected.push('Generative AI', 'Developer Tools', 'AI Research'); } return selected.slice(0, 5); } async function fetchAllRows(table, fields) { const all = []; const pageSize = 1000; let from = 0; while (true) { const to = from + pageSize - 1; const { data, error } = await supabase.from(table).select(fields).range(from, to); if (error) throw new Error(`Failed querying ${table}: ${error.message}`); if (!data || data.length === 0) break; all.push(...data); if (data.length < pageSize) break; from += pageSize; } return all; } async function fetchWithFieldFallbacks(table, fieldOptions) { let lastError = null; for (const fields of fieldOptions) { try { const rows = await fetchAllRows(table, fields); return rows; } catch (error) { lastError = error; } } throw lastError || new Error(`Failed querying ${table}`); } async function ensureCategory(name, categoriesByName, categoriesById, stats) { const key = name.toLowerCase(); const existing = categoriesByName.get(key); if (existing) return existing; const def = TAXONOMY.find((t) => t.name.toLowerCase() === key); const icon = def?.icon || 'Tag'; const slug = slugify(name); const description = `${name} resources, news, and analysis`; const now = new Date().toISOString(); const { data, error } = await supabase .from('categories') .insert({ name, slug, icon, description, created_at: now, updated_at: now }) .select('id, name, slug, icon, description') .single(); if (error) { throw new Error(`Failed creating category "${name}": ${error.message}`); } categoriesByName.set(key, data); categoriesById.set(data.id, data); stats.categoriesCreated += 1; console.log(`+ Created category: ${name} (id=${data.id}, icon=${icon}, slug=${slug})`); return data; } async function syncItemCategories({ item, itemType, contentTable, junctionTable, itemKey, categoriesByName, categoriesById, existingLinksByItemId, stats, }) { const existingLinks = existingLinksByItemId.get(item.id) || []; const existingNames = existingLinks .map((x) => categoriesById.get(x.category_id)?.name) .filter(Boolean); const inferredNames = inferTagNames(item, existingNames); const targetCategories = []; for (const name of inferredNames) { const category = await ensureCategory(name, categoriesByName, categoriesById, stats); targetCategories.push(category); } const targetIds = new Set(targetCategories.map((c) => c.id)); const targetIdList = [...targetIds]; const primaryId = targetIdList[0]; const existingIdSet = new Set(existingLinks.map((x) => x.category_id)); const existingById = new Map(existingLinks.map((x) => [x.category_id, x])); const existingNamesById = new Map(existingLinks.map((x) => [x.category_id, (categoriesById.get(x.category_id)?.name || '').toLowerCase()])); const toAdd = targetIdList.filter((id) => !existingIdSet.has(id)); const toRemove = [...existingIdSet].filter((id) => { if (targetIds.has(id)) return false; const existingName = existingNamesById.get(id) || ''; return isGenericTag(existingName) || true; }); if (toAdd.length === 0 && toRemove.length === 0 && existingLinks.some((x) => x.is_primary && x.category_id === primaryId)) { return; } console.log(`\n[${itemType}] ${item.title}`); console.log(`- slug: ${item.slug || 'n/a'}`); console.log(`- existing: ${existingNames.length ? existingNames.join(', ') : '(none)'}`); console.log(`- target: ${targetCategories.map((c) => c.name).join(', ')}`); if (toRemove.length > 0) { const { error } = await supabase .from(junctionTable) .delete() .eq(itemKey, item.id) .in('category_id', toRemove); if (error) throw new Error(`Failed removing categories from ${junctionTable}: ${error.message}`); stats.linksRemoved += toRemove.length; console.log(`- removed category ids: ${toRemove.join(', ')}`); } if (toAdd.length > 0) { const rows = toAdd.map((categoryId) => ({ [itemKey]: item.id, category_id: categoryId, is_primary: categoryId === primaryId, })); const { error } = await supabase.from(junctionTable).insert(rows); if (error) throw new Error(`Failed adding categories to ${junctionTable}: ${error.message}`); stats.linksAdded += toAdd.length; console.log(`- added category ids: ${toAdd.join(', ')}`); } const { error: clearPrimaryError } = await supabase .from(junctionTable) .update({ is_primary: false }) .eq(itemKey, item.id); if (clearPrimaryError) throw new Error(`Failed clearing primary flags: ${clearPrimaryError.message}`); const { error: setPrimaryError } = await supabase .from(junctionTable) .update({ is_primary: true }) .eq(itemKey, item.id) .eq('category_id', primaryId); if (setPrimaryError) throw new Error(`Failed setting primary flag: ${setPrimaryError.message}`); const { error: updateItemError } = await supabase.from(contentTable).update({ primary_category_id: primaryId }).eq('id', item.id); if (updateItemError) { const { error: retryError } = await supabase .from(contentTable) .update({ primary_category_id: primaryId }) .eq('id', item.id); if (retryError) throw new Error(`Failed updating ${contentTable}.primary_category_id: ${retryError.message}`); } stats.itemsUpdated += 1; console.log(`- primary category id set: ${primaryId}`); } async function main() { const startedAt = new Date(); const stats = { categoriesCreated: 0, linksAdded: 0, linksRemoved: 0, itemsUpdated: 0, }; const newsTable = await detectTable(tableCandidates.news); const postsJunctionTable = await detectTable(tableCandidates.postsJunction); const newsJunctionTable = await detectTable(tableCandidates.newsJunction); if (!newsTable) throw new Error(`Could not find news table from: ${tableCandidates.news.join(', ')}`); if (!postsJunctionTable) throw new Error(`Could not find posts junction table from: ${tableCandidates.postsJunction.join(', ')}`); if (!newsJunctionTable) throw new Error(`Could not find news junction table from: ${tableCandidates.newsJunction.join(', ')}`); const postsItemKey = postsJunctionTable === 'blog_posts_categories' ? 'blog_post_id' : 'post_id'; const newsItemKey = 'news_id'; console.log('Detected tables:'); console.log(`- news: ${newsTable}`); console.log(`- posts junction: ${postsJunctionTable} (${postsItemKey})`); console.log(`- news junction: ${newsJunctionTable} (${newsItemKey})`); const [categories, posts, news, postLinks, newsLinks] = await Promise.all([ fetchAllRows('categories', 'id, name, slug, icon, description'), fetchWithFieldFallbacks('posts', [ 'id, title, content, slug, summary, primary_category_id', 'id, title, content, slug, primary_category_id', 'id, title, content, slug', ]), fetchWithFieldFallbacks(newsTable, [ 'id, title, content, slug, primary_category_id', 'id, title, content, slug', ]), fetchAllRows(postsJunctionTable, `${postsItemKey}, category_id, is_primary`), fetchAllRows(newsJunctionTable, `${newsItemKey}, category_id, is_primary`), ]); const categoriesByName = new Map(categories.map((c) => [String(c.name).toLowerCase(), c])); const categoriesById = new Map(categories.map((c) => [c.id, c])); const postLinksByPostId = new Map(); for (const link of postLinks) { const key = link[postsItemKey]; if (!key) continue; if (!postLinksByPostId.has(key)) postLinksByPostId.set(key, []); postLinksByPostId.get(key).push(link); } const newsLinksByNewsId = new Map(); for (const link of newsLinks) { const key = link[newsItemKey]; if (!key) continue; if (!newsLinksByNewsId.has(key)) newsLinksByNewsId.set(key, []); newsLinksByNewsId.get(key).push(link); } console.log('\nFetched records:'); console.log(`- categories: ${categories.length}`); console.log(`- posts: ${posts.length}`); console.log(`- news: ${news.length}`); console.log(`- post links: ${postLinks.length}`); console.log(`- news links: ${newsLinks.length}`); for (const post of posts) { await syncItemCategories({ item: post, itemType: 'Post', contentTable: 'posts', junctionTable: postsJunctionTable, itemKey: postsItemKey, categoriesByName, categoriesById, existingLinksByItemId: postLinksByPostId, stats, }); } for (const story of news) { await syncItemCategories({ item: story, itemType: 'News', contentTable: newsTable, junctionTable: newsJunctionTable, itemKey: newsItemKey, categoriesByName, categoriesById, existingLinksByItemId: newsLinksByNewsId, stats, }); } const endedAt = new Date(); console.log('\nTag audit complete'); console.log(`- started: ${startedAt.toISOString()}`); console.log(`- ended: ${endedAt.toISOString()}`); console.log(`- categories created: ${stats.categoriesCreated}`); console.log(`- links added: ${stats.linksAdded}`); console.log(`- links removed: ${stats.linksRemoved}`); console.log(`- items updated: ${stats.itemsUpdated}`); } main().catch((error) => { console.error('\nTag audit failed:'); console.error(error); process.exit(1); });