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; const isDryRun = String(process.env.DRY_RUN || '').toLowerCase() === '1' || String(process.env.DRY_RUN || '').toLowerCase() === 'true'; if (!supabaseUrl || !supabaseServiceKey) { console.error('Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY'); process.exit(1); } const supabase = createClient(supabaseUrl, supabaseServiceKey, { auth: { persistSession: false, autoRefreshToken: false }, db: { schema: 'public' }, }); const KNOWN_MODEL_PATTERNS = [ /\bchatgpt\b/i, /\bgpt(?:-[0-9a-z.]+)?\b/i, /\bclaude(?:\s+[0-9a-z.-]+)?\b/i, /\bgemini(?:\s+[0-9a-z.-]+)?\b/i, /\bllama(?:\s*[0-9a-z.-]+)?\b/i, /\bmistral(?:\s*[0-9a-z.-]+)?\b/i, /\bmixtral\b/i, /\bphi(?:-[0-9a-z.]+)?\b/i, /\bcommand\s*r\b/i, /\bqwen(?:\s*[0-9a-z.-]+)?\b/i, /\bdeepseek(?:\s*[0-9a-z.-]+)?\b/i, /\bfalcon(?:\s*[0-9a-z.-]+)?\b/i, /\bpalm(?:\s*[0-9a-z.-]+)?\b/i, ]; const DIRECT_LLM_TERMS = [ 'large language model', 'large language models', 'llm', 'llms', 'foundation model', 'foundation models', 'language model', 'language models', 'open-weight model', 'open-weights model', ]; const ABOUT_LLM_CONTEXT_TERMS = [ 'model architecture', 'model weights', 'weights', 'benchmark', 'eval', 'evaluation', 'inference', 'pretraining', 'training', 'fine-tuning', 'tokenizer', 'context window', 'reasoning model', ]; const NEGATIVE_TOOL_CUES = [ 'code editor', 'design tool', 'writing assistant', 'grammar checker', 'meeting assistant', 'video editor', 'image generator', 'transcription tool', 'email assistant', ]; const FALLBACK_BY_KIND = { tools: ['Developer Tools', 'Productivity', 'Workflow Automation', 'APIs', 'Machine Learning', 'Natural Language Processing'], news: ['Research', 'Machine Learning', 'Natural Language Processing', 'APIs', 'Developer Tools'], posts: ['Tutorials', 'Documentation', 'Research', 'Machine Learning', 'Natural Language Processing'], learning: ['Courses', 'Tutorials', 'Documentation', 'Machine Learning', 'Natural Language Processing'], }; function normalize(v) { return String(v || '').trim().toLowerCase(); } function uniq(arr) { const seen = new Set(); return arr.filter((v) => { const key = normalize(v); if (!key || seen.has(key)) return false; seen.add(key); return true; }); } function containsWord(text, term) { const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); return new RegExp(`(^|[^a-z0-9])${escaped}([^a-z0-9]|$)`, 'i').test(text); } function scoreCategoryForItem(category, text) { const name = String(category.name || ''); const slug = String(category.slug || ''); const desc = String(category.description || ''); const nameN = normalize(name); const slugParts = normalize(slug).split('-').filter(Boolean); const nameParts = nameN.split(/[^a-z0-9]+/).filter((p) => p.length > 2); let score = 0; if (nameN && containsWord(text, nameN)) score += 10; if (desc && containsWord(text, normalize(desc).slice(0, 80))) score += 2; for (const p of nameParts) { if (containsWord(text, p)) score += 2; } for (const p of slugParts) { if (p.length > 2 && containsWord(text, p)) score += 1; } return score; } function classifyLLM(item) { const text = `${item.title || ''}\n${item.description || ''}`.toLowerCase(); const hasKnownModel = KNOWN_MODEL_PATTERNS.some((r) => r.test(text)); const hasDirectTerm = DIRECT_LLM_TERMS.some((t) => containsWord(text, t)); const hasContext = ABOUT_LLM_CONTEXT_TERMS.some((t) => containsWord(text, t)); const hasNegativeCue = NEGATIVE_TOOL_CUES.some((t) => containsWord(text, t)); const keep = hasKnownModel || (hasDirectTerm && hasContext) || (hasDirectTerm && !hasNegativeCue); let reason = 'not directly about language models'; if (hasKnownModel) reason = 'mentions specific LLM/model family'; else if (hasDirectTerm && hasContext) reason = 'directly discusses LLM/model internals'; else if (hasDirectTerm && !hasNegativeCue) reason = 'directly references LLMs'; else if (hasNegativeCue) reason = 'describes an application/tool rather than an LLM'; return { keep, reason }; } async function detectTable(candidates) { for (const table of candidates) { const { error } = await supabase.from(table).select('*').limit(1); if (!error) return table; const msg = normalize(error.message); if ( msg.includes('does not exist') || msg.includes('could not find the table') || msg.includes('schema cache') || msg.includes('relation') ) { continue; } throw new Error(`Unexpected error checking table ${table}: ${error.message}`); } return null; } async function detectColumn(table, candidates) { for (const col of candidates) { const { error } = await supabase.from(table).select(col).limit(1); if (!error) return col; const msg = normalize(error.message); if (msg.includes('column') || msg.includes('schema cache')) continue; throw new Error(`Unexpected error checking column ${table}.${col}: ${error.message}`); } return null; } async function detectExistingColumns(table, candidates) { const found = []; for (const col of candidates) { const { error } = await supabase.from(table).select(col).limit(1); if (!error) { found.push(col); continue; } const msg = normalize(error.message); if (msg.includes('column') || msg.includes('schema cache')) { continue; } throw new Error(`Unexpected error checking column ${table}.${col}: ${error.message}`); } return found; } async function fetchAllRows(table, columns, filterFn) { const pageSize = 1000; const rows = []; let from = 0; while (true) { const to = from + pageSize - 1; let query = supabase.from(table).select(columns).range(from, to); if (filterFn) query = filterFn(query); const { data, error } = await query; if (error) throw new Error(`Failed fetching ${table}: ${error.message}`); if (!data || data.length === 0) break; rows.push(...data); if (data.length < pageSize) break; from += pageSize; } return rows; } function getItemDisplayName(kind, row) { if (kind === 'tools') return row.name || `Tool ${row.id}`; if (kind === 'news') return row.title || `News ${row.id}`; if (kind === 'posts') return row.title || `Post ${row.id}`; return row.title || `Learning ${row.id}`; } function getItemDescription(row) { return row.description || row.summary || row.excerpt || row.content || ''; } async function pickReplacementCategoryIds({ item, kind, categoriesById, llmCategoryId, existingCategoryIds }) { const text = `${item.title || ''}\n${item.description || ''}`.toLowerCase(); const candidates = []; for (const category of categoriesById.values()) { if (category.id === llmCategoryId) continue; if (existingCategoryIds.has(category.id)) continue; const score = scoreCategoryForItem(category, text); if (score > 0) candidates.push({ id: category.id, name: category.name, score }); } candidates.sort((a, b) => b.score - a.score); const selected = []; for (const c of candidates) { selected.push(c.id); if (selected.length >= 5) break; } if (selected.length > 0) return selected; const fallbackNames = FALLBACK_BY_KIND[kind] || []; const fallbackIds = []; for (const name of fallbackNames) { const found = [...categoriesById.values()].find((c) => normalize(c.name) === normalize(name)); if (found && !existingCategoryIds.has(found.id) && found.id !== llmCategoryId) { fallbackIds.push(found.id); } } return uniq(fallbackIds); } async function ensureMinimumTags({ kind, itemId, itemData, categoryIdColumn, junctionTable, categoriesById, llmCategoryId, changeLog, }) { const { data: currentRows, error } = await supabase .from(junctionTable) .select(`${categoryIdColumn}, category_id, is_primary`) .eq(categoryIdColumn === 'tool_id' ? 'tool_id' : categoryIdColumn, itemId); if (error) { throw new Error(`Failed loading current categories for ${junctionTable}/${itemId}: ${error.message}`); } const current = currentRows || []; const currentCategoryIds = new Set(current.map((r) => r.category_id)); if (currentCategoryIds.size >= 3) return { added: [] }; const needed = 3 - currentCategoryIds.size; const replacements = await pickReplacementCategoryIds({ item: itemData, kind, categoriesById, llmCategoryId, existingCategoryIds: currentCategoryIds, }); const toAdd = replacements.slice(0, needed); if (toAdd.length === 0) return { added: [] }; const payload = toAdd.map((cid) => ({ [categoryIdColumn]: itemId, category_id: cid, is_primary: false, })); if (!isDryRun) { const { error: insertError } = await supabase.from(junctionTable).insert(payload); if (insertError) { throw new Error(`Failed adding replacement categories in ${junctionTable}/${itemId}: ${insertError.message}`); } } const names = toAdd.map((id) => categoriesById.get(id)?.name || `Unknown(${id})`); changeLog.push({ action: 'added_replacement_categories', kind, item_id: itemId, junction_table: junctionTable, categories_added: names, dry_run: isDryRun, }); return { added: names }; } async function processKind({ kind, itemTable, junctionTable, itemIdColumn, titleCandidates, descriptionCandidates, llmCategoryId, categoriesById, summary, changeLog, }) { const linkRows = await fetchAllRows( junctionTable, `${itemIdColumn}, category_id, is_primary`, (q) => q.eq('category_id', llmCategoryId) ); if (linkRows.length === 0) return; const ids = uniq(linkRows.map((r) => r[itemIdColumn])); const idColumn = 'id'; const detectedTitleColumns = await detectExistingColumns(itemTable, titleCandidates); const detectedDescriptionColumns = await detectExistingColumns(itemTable, descriptionCandidates); const titleColumn = detectedTitleColumns[0] || titleCandidates[0]; const columns = uniq([idColumn, ...detectedTitleColumns, ...detectedDescriptionColumns]).join(', '); const items = await fetchAllRows(itemTable, columns, (q) => q.in(idColumn, ids)); const itemById = new Map(items.map((i) => [i.id, i])); for (const link of linkRows) { const itemId = link[itemIdColumn]; const row = itemById.get(itemId); if (!row) { summary.skippedMissing += 1; changeLog.push({ action: 'skipped_missing_item', kind, item_id: itemId, junction_table: junctionTable, }); continue; } const item = { id: row.id, title: row[titleColumn] || getItemDisplayName(kind, row), description: detectedDescriptionColumns.map((c) => row[c]).find(Boolean) || getItemDescription(row), }; const decision = classifyLLM(item); summary.reviewed += 1; if (decision.keep) { summary.kept += 1; changeLog.push({ action: 'kept_llm_tag', kind, item_id: item.id, title: item.title, reason: decision.reason, }); continue; } if (!isDryRun) { const { error: delError } = await supabase .from(junctionTable) .delete() .eq(itemIdColumn, itemId) .eq('category_id', llmCategoryId); if (delError) { throw new Error(`Failed removing LLM tag from ${junctionTable}/${itemId}: ${delError.message}`); } } summary.removed += 1; changeLog.push({ action: 'removed_llm_tag', kind, item_id: item.id, title: item.title, reason: decision.reason, dry_run: isDryRun, }); const minResult = await ensureMinimumTags({ kind, itemId: item.id, itemData: item, categoryIdColumn: itemIdColumn, junctionTable, categoriesById, llmCategoryId, changeLog, }); if (minResult.added.length > 0) { summary.replacementsAdded += minResult.added.length; } } } async function main() { const startedAt = new Date().toISOString(); console.log(`[audit-llm-tag] Start ${startedAt} ${isDryRun ? '(DRY RUN)' : ''}`); const { data: categories, error: catError } = await supabase .from('categories') .select('id, name, slug, icon, description'); if (catError) throw new Error(`Failed loading categories: ${catError.message}`); const categoriesById = new Map((categories || []).map((c) => [c.id, c])); const llmCategory = (categories || []).find((c) => normalize(c.name) === 'llms') || (categories || []).find((c) => normalize(c.slug) === 'llms'); if (!llmCategory) { throw new Error('Could not find category named/sluggified as "LLMs"'); } const llmCategoryId = llmCategory.id; console.log(`[audit-llm-tag] LLMs category id: ${llmCategoryId}`); const postJunction = await detectTable(['posts_categories', 'post_categories', 'blog_posts_categories']); const learningTable = await detectTable(['learning', 'learning_resources']); const learningIdColumn = await detectColumn('learning_categories', ['learning_id', 'learning_resource_id']); if (!postJunction) throw new Error('Could not detect posts junction table'); if (!learningTable) throw new Error('Could not detect learning table'); if (!learningIdColumn) throw new Error('Could not detect learning id column in learning_categories'); const postIdColumn = postJunction === 'blog_posts_categories' ? 'blog_post_id' : 'post_id'; const summary = { reviewed: 0, kept: 0, removed: 0, replacementsAdded: 0, skippedMissing: 0, }; const changeLog = []; await processKind({ kind: 'tools', itemTable: 'tools', junctionTable: 'tools_categories', itemIdColumn: 'tool_id', titleCandidates: ['name', 'title'], descriptionCandidates: ['description'], llmCategoryId, categoriesById, summary, changeLog, }); await processKind({ kind: 'news', itemTable: 'news', junctionTable: 'news_categories', itemIdColumn: 'news_id', titleCandidates: ['title', 'name', 'headline'], descriptionCandidates: ['description', 'summary', 'content'], llmCategoryId, categoriesById, summary, changeLog, }); await processKind({ kind: 'posts', itemTable: 'posts', junctionTable: postJunction, itemIdColumn: postIdColumn, titleCandidates: ['title', 'name'], descriptionCandidates: ['description', 'excerpt', 'content'], llmCategoryId, categoriesById, summary, changeLog, }); await processKind({ kind: 'learning', itemTable: learningTable, junctionTable: 'learning_categories', itemIdColumn: learningIdColumn, titleCandidates: ['title', 'name'], descriptionCandidates: ['description', 'summary', 'content'], llmCategoryId, categoriesById, summary, changeLog, }); const endedAt = new Date().toISOString(); const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); const outDir = path.resolve(process.cwd(), 'logs'); if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true }); const outPath = path.join(outDir, `audit-llm-tag-${timestamp}.json`); const payload = { started_at: startedAt, ended_at: endedAt, dry_run: isDryRun, llms_category: llmCategory, detected_tables: { posts_junction: postJunction, posts_item_id_column: postIdColumn, learning_table: learningTable, learning_item_id_column: learningIdColumn, }, summary, changes: changeLog, }; fs.writeFileSync(outPath, JSON.stringify(payload, null, 2), 'utf8'); console.log('[audit-llm-tag] Summary'); console.log(JSON.stringify(summary, null, 2)); console.log(`[audit-llm-tag] Change log written: ${outPath}`); } main().catch((err) => { console.error(`[audit-llm-tag] Failed: ${err instanceof Error ? err.message : String(err)}`); process.exit(1); });