AI Resource Pro / website / scripts / audit-llm-tag.mjs
| 1 | import { createClient } from '@supabase/supabase-js'; |
| 2 | import dotenv from 'dotenv'; |
| 3 | import fs from 'fs'; |
| 4 | import path from 'path'; |
| 5 | |
| 6 | const envLocalPath = path.resolve(process.cwd(), '.env.local'); |
| 7 | if (fs.existsSync(envLocalPath)) { |
| 8 | dotenv.config({ path: envLocalPath }); |
| 9 | } else { |
| 10 | dotenv.config(); |
| 11 | } |
| 12 | |
| 13 | const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 14 | const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; |
| 15 | const isDryRun = String(process.env.DRY_RUN || '').toLowerCase() === '1' || String(process.env.DRY_RUN || '').toLowerCase() === 'true'; |
| 16 | |
| 17 | if (!supabaseUrl || !supabaseServiceKey) { |
| 18 | console.error('Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY'); |
| 19 | process.exit(1); |
| 20 | } |
| 21 | |
| 22 | const supabase = createClient(supabaseUrl, supabaseServiceKey, { |
| 23 | auth: { persistSession: false, autoRefreshToken: false }, |
| 24 | db: { schema: 'public' }, |
| 25 | }); |
| 26 | |
| 27 | const KNOWN_MODEL_PATTERNS = [ |
| 28 | /\bchatgpt\b/i, |
| 29 | /\bgpt(?:-[0-9a-z.]+)?\b/i, |
| 30 | /\bclaude(?:\s+[0-9a-z.-]+)?\b/i, |
| 31 | /\bgemini(?:\s+[0-9a-z.-]+)?\b/i, |
| 32 | /\bllama(?:\s*[0-9a-z.-]+)?\b/i, |
| 33 | /\bmistral(?:\s*[0-9a-z.-]+)?\b/i, |
| 34 | /\bmixtral\b/i, |
| 35 | /\bphi(?:-[0-9a-z.]+)?\b/i, |
| 36 | /\bcommand\s*r\b/i, |
| 37 | /\bqwen(?:\s*[0-9a-z.-]+)?\b/i, |
| 38 | /\bdeepseek(?:\s*[0-9a-z.-]+)?\b/i, |
| 39 | /\bfalcon(?:\s*[0-9a-z.-]+)?\b/i, |
| 40 | /\bpalm(?:\s*[0-9a-z.-]+)?\b/i, |
| 41 | ]; |
| 42 | |
| 43 | const DIRECT_LLM_TERMS = [ |
| 44 | 'large language model', |
| 45 | 'large language models', |
| 46 | 'llm', |
| 47 | 'llms', |
| 48 | 'foundation model', |
| 49 | 'foundation models', |
| 50 | 'language model', |
| 51 | 'language models', |
| 52 | 'open-weight model', |
| 53 | 'open-weights model', |
| 54 | ]; |
| 55 | |
| 56 | const ABOUT_LLM_CONTEXT_TERMS = [ |
| 57 | 'model architecture', |
| 58 | 'model weights', |
| 59 | 'weights', |
| 60 | 'benchmark', |
| 61 | 'eval', |
| 62 | 'evaluation', |
| 63 | 'inference', |
| 64 | 'pretraining', |
| 65 | 'training', |
| 66 | 'fine-tuning', |
| 67 | 'tokenizer', |
| 68 | 'context window', |
| 69 | 'reasoning model', |
| 70 | ]; |
| 71 | |
| 72 | const NEGATIVE_TOOL_CUES = [ |
| 73 | 'code editor', |
| 74 | 'design tool', |
| 75 | 'writing assistant', |
| 76 | 'grammar checker', |
| 77 | 'meeting assistant', |
| 78 | 'video editor', |
| 79 | 'image generator', |
| 80 | 'transcription tool', |
| 81 | 'email assistant', |
| 82 | ]; |
| 83 | |
| 84 | const FALLBACK_BY_KIND = { |
| 85 | tools: ['Developer Tools', 'Productivity', 'Workflow Automation', 'APIs', 'Machine Learning', 'Natural Language Processing'], |
| 86 | news: ['Research', 'Machine Learning', 'Natural Language Processing', 'APIs', 'Developer Tools'], |
| 87 | posts: ['Tutorials', 'Documentation', 'Research', 'Machine Learning', 'Natural Language Processing'], |
| 88 | learning: ['Courses', 'Tutorials', 'Documentation', 'Machine Learning', 'Natural Language Processing'], |
| 89 | }; |
| 90 | |
| 91 | function normalize(v) { |
| 92 | return String(v || '').trim().toLowerCase(); |
| 93 | } |
| 94 | |
| 95 | function uniq(arr) { |
| 96 | const seen = new Set(); |
| 97 | return arr.filter((v) => { |
| 98 | const key = normalize(v); |
| 99 | if (!key || seen.has(key)) return false; |
| 100 | seen.add(key); |
| 101 | return true; |
| 102 | }); |
| 103 | } |
| 104 | |
| 105 | function containsWord(text, term) { |
| 106 | const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); |
| 107 | return new RegExp(`(^|[^a-z0-9])${escaped}([^a-z0-9]|$)`, 'i').test(text); |
| 108 | } |
| 109 | |
| 110 | function scoreCategoryForItem(category, text) { |
| 111 | const name = String(category.name || ''); |
| 112 | const slug = String(category.slug || ''); |
| 113 | const desc = String(category.description || ''); |
| 114 | |
| 115 | const nameN = normalize(name); |
| 116 | const slugParts = normalize(slug).split('-').filter(Boolean); |
| 117 | const nameParts = nameN.split(/[^a-z0-9]+/).filter((p) => p.length > 2); |
| 118 | |
| 119 | let score = 0; |
| 120 | if (nameN && containsWord(text, nameN)) score += 10; |
| 121 | if (desc && containsWord(text, normalize(desc).slice(0, 80))) score += 2; |
| 122 | |
| 123 | for (const p of nameParts) { |
| 124 | if (containsWord(text, p)) score += 2; |
| 125 | } |
| 126 | for (const p of slugParts) { |
| 127 | if (p.length > 2 && containsWord(text, p)) score += 1; |
| 128 | } |
| 129 | |
| 130 | return score; |
| 131 | } |
| 132 | |
| 133 | function classifyLLM(item) { |
| 134 | const text = `${item.title || ''}\n${item.description || ''}`.toLowerCase(); |
| 135 | const hasKnownModel = KNOWN_MODEL_PATTERNS.some((r) => r.test(text)); |
| 136 | const hasDirectTerm = DIRECT_LLM_TERMS.some((t) => containsWord(text, t)); |
| 137 | const hasContext = ABOUT_LLM_CONTEXT_TERMS.some((t) => containsWord(text, t)); |
| 138 | const hasNegativeCue = NEGATIVE_TOOL_CUES.some((t) => containsWord(text, t)); |
| 139 | |
| 140 | const keep = hasKnownModel || (hasDirectTerm && hasContext) || (hasDirectTerm && !hasNegativeCue); |
| 141 | let reason = 'not directly about language models'; |
| 142 | if (hasKnownModel) reason = 'mentions specific LLM/model family'; |
| 143 | else if (hasDirectTerm && hasContext) reason = 'directly discusses LLM/model internals'; |
| 144 | else if (hasDirectTerm && !hasNegativeCue) reason = 'directly references LLMs'; |
| 145 | else if (hasNegativeCue) reason = 'describes an application/tool rather than an LLM'; |
| 146 | |
| 147 | return { keep, reason }; |
| 148 | } |
| 149 | |
| 150 | async function detectTable(candidates) { |
| 151 | for (const table of candidates) { |
| 152 | const { error } = await supabase.from(table).select('*').limit(1); |
| 153 | if (!error) return table; |
| 154 | const msg = normalize(error.message); |
| 155 | if ( |
| 156 | msg.includes('does not exist') || |
| 157 | msg.includes('could not find the table') || |
| 158 | msg.includes('schema cache') || |
| 159 | msg.includes('relation') |
| 160 | ) { |
| 161 | continue; |
| 162 | } |
| 163 | throw new Error(`Unexpected error checking table ${table}: ${error.message}`); |
| 164 | } |
| 165 | return null; |
| 166 | } |
| 167 | |
| 168 | async function detectColumn(table, candidates) { |
| 169 | for (const col of candidates) { |
| 170 | const { error } = await supabase.from(table).select(col).limit(1); |
| 171 | if (!error) return col; |
| 172 | const msg = normalize(error.message); |
| 173 | if (msg.includes('column') || msg.includes('schema cache')) continue; |
| 174 | throw new Error(`Unexpected error checking column ${table}.${col}: ${error.message}`); |
| 175 | } |
| 176 | return null; |
| 177 | } |
| 178 | |
| 179 | async function detectExistingColumns(table, candidates) { |
| 180 | const found = []; |
| 181 | for (const col of candidates) { |
| 182 | const { error } = await supabase.from(table).select(col).limit(1); |
| 183 | if (!error) { |
| 184 | found.push(col); |
| 185 | continue; |
| 186 | } |
| 187 | const msg = normalize(error.message); |
| 188 | if (msg.includes('column') || msg.includes('schema cache')) { |
| 189 | continue; |
| 190 | } |
| 191 | throw new Error(`Unexpected error checking column ${table}.${col}: ${error.message}`); |
| 192 | } |
| 193 | return found; |
| 194 | } |
| 195 | |
| 196 | async function fetchAllRows(table, columns, filterFn) { |
| 197 | const pageSize = 1000; |
| 198 | const rows = []; |
| 199 | let from = 0; |
| 200 | while (true) { |
| 201 | const to = from + pageSize - 1; |
| 202 | let query = supabase.from(table).select(columns).range(from, to); |
| 203 | if (filterFn) query = filterFn(query); |
| 204 | const { data, error } = await query; |
| 205 | if (error) throw new Error(`Failed fetching ${table}: ${error.message}`); |
| 206 | if (!data || data.length === 0) break; |
| 207 | rows.push(...data); |
| 208 | if (data.length < pageSize) break; |
| 209 | from += pageSize; |
| 210 | } |
| 211 | return rows; |
| 212 | } |
| 213 | |
| 214 | function getItemDisplayName(kind, row) { |
| 215 | if (kind === 'tools') return row.name || `Tool ${row.id}`; |
| 216 | if (kind === 'news') return row.title || `News ${row.id}`; |
| 217 | if (kind === 'posts') return row.title || `Post ${row.id}`; |
| 218 | return row.title || `Learning ${row.id}`; |
| 219 | } |
| 220 | |
| 221 | function getItemDescription(row) { |
| 222 | return row.description || row.summary || row.excerpt || row.content || ''; |
| 223 | } |
| 224 | |
| 225 | async function pickReplacementCategoryIds({ item, kind, categoriesById, llmCategoryId, existingCategoryIds }) { |
| 226 | const text = `${item.title || ''}\n${item.description || ''}`.toLowerCase(); |
| 227 | const candidates = []; |
| 228 | for (const category of categoriesById.values()) { |
| 229 | if (category.id === llmCategoryId) continue; |
| 230 | if (existingCategoryIds.has(category.id)) continue; |
| 231 | const score = scoreCategoryForItem(category, text); |
| 232 | if (score > 0) candidates.push({ id: category.id, name: category.name, score }); |
| 233 | } |
| 234 | |
| 235 | candidates.sort((a, b) => b.score - a.score); |
| 236 | const selected = []; |
| 237 | for (const c of candidates) { |
| 238 | selected.push(c.id); |
| 239 | if (selected.length >= 5) break; |
| 240 | } |
| 241 | |
| 242 | if (selected.length > 0) return selected; |
| 243 | |
| 244 | const fallbackNames = FALLBACK_BY_KIND[kind] || []; |
| 245 | const fallbackIds = []; |
| 246 | for (const name of fallbackNames) { |
| 247 | const found = [...categoriesById.values()].find((c) => normalize(c.name) === normalize(name)); |
| 248 | if (found && !existingCategoryIds.has(found.id) && found.id !== llmCategoryId) { |
| 249 | fallbackIds.push(found.id); |
| 250 | } |
| 251 | } |
| 252 | return uniq(fallbackIds); |
| 253 | } |
| 254 | |
| 255 | async function ensureMinimumTags({ |
| 256 | kind, |
| 257 | itemId, |
| 258 | itemData, |
| 259 | categoryIdColumn, |
| 260 | junctionTable, |
| 261 | categoriesById, |
| 262 | llmCategoryId, |
| 263 | changeLog, |
| 264 | }) { |
| 265 | const { data: currentRows, error } = await supabase |
| 266 | .from(junctionTable) |
| 267 | .select(`${categoryIdColumn}, category_id, is_primary`) |
| 268 | .eq(categoryIdColumn === 'tool_id' ? 'tool_id' : categoryIdColumn, itemId); |
| 269 | |
| 270 | if (error) { |
| 271 | throw new Error(`Failed loading current categories for ${junctionTable}/${itemId}: ${error.message}`); |
| 272 | } |
| 273 | |
| 274 | const current = currentRows || []; |
| 275 | const currentCategoryIds = new Set(current.map((r) => r.category_id)); |
| 276 | |
| 277 | if (currentCategoryIds.size >= 3) return { added: [] }; |
| 278 | |
| 279 | const needed = 3 - currentCategoryIds.size; |
| 280 | const replacements = await pickReplacementCategoryIds({ |
| 281 | item: itemData, |
| 282 | kind, |
| 283 | categoriesById, |
| 284 | llmCategoryId, |
| 285 | existingCategoryIds: currentCategoryIds, |
| 286 | }); |
| 287 | |
| 288 | const toAdd = replacements.slice(0, needed); |
| 289 | if (toAdd.length === 0) return { added: [] }; |
| 290 | |
| 291 | const payload = toAdd.map((cid) => ({ |
| 292 | [categoryIdColumn]: itemId, |
| 293 | category_id: cid, |
| 294 | is_primary: false, |
| 295 | })); |
| 296 | |
| 297 | if (!isDryRun) { |
| 298 | const { error: insertError } = await supabase.from(junctionTable).insert(payload); |
| 299 | if (insertError) { |
| 300 | throw new Error(`Failed adding replacement categories in ${junctionTable}/${itemId}: ${insertError.message}`); |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | const names = toAdd.map((id) => categoriesById.get(id)?.name || `Unknown(${id})`); |
| 305 | changeLog.push({ |
| 306 | action: 'added_replacement_categories', |
| 307 | kind, |
| 308 | item_id: itemId, |
| 309 | junction_table: junctionTable, |
| 310 | categories_added: names, |
| 311 | dry_run: isDryRun, |
| 312 | }); |
| 313 | |
| 314 | return { added: names }; |
| 315 | } |
| 316 | |
| 317 | async function processKind({ |
| 318 | kind, |
| 319 | itemTable, |
| 320 | junctionTable, |
| 321 | itemIdColumn, |
| 322 | titleCandidates, |
| 323 | descriptionCandidates, |
| 324 | llmCategoryId, |
| 325 | categoriesById, |
| 326 | summary, |
| 327 | changeLog, |
| 328 | }) { |
| 329 | const linkRows = await fetchAllRows( |
| 330 | junctionTable, |
| 331 | `${itemIdColumn}, category_id, is_primary`, |
| 332 | (q) => q.eq('category_id', llmCategoryId) |
| 333 | ); |
| 334 | |
| 335 | if (linkRows.length === 0) return; |
| 336 | |
| 337 | const ids = uniq(linkRows.map((r) => r[itemIdColumn])); |
| 338 | const idColumn = 'id'; |
| 339 | const detectedTitleColumns = await detectExistingColumns(itemTable, titleCandidates); |
| 340 | const detectedDescriptionColumns = await detectExistingColumns(itemTable, descriptionCandidates); |
| 341 | const titleColumn = detectedTitleColumns[0] || titleCandidates[0]; |
| 342 | const columns = uniq([idColumn, ...detectedTitleColumns, ...detectedDescriptionColumns]).join(', '); |
| 343 | |
| 344 | const items = await fetchAllRows(itemTable, columns, (q) => q.in(idColumn, ids)); |
| 345 | const itemById = new Map(items.map((i) => [i.id, i])); |
| 346 | |
| 347 | for (const link of linkRows) { |
| 348 | const itemId = link[itemIdColumn]; |
| 349 | const row = itemById.get(itemId); |
| 350 | if (!row) { |
| 351 | summary.skippedMissing += 1; |
| 352 | changeLog.push({ |
| 353 | action: 'skipped_missing_item', |
| 354 | kind, |
| 355 | item_id: itemId, |
| 356 | junction_table: junctionTable, |
| 357 | }); |
| 358 | continue; |
| 359 | } |
| 360 | |
| 361 | const item = { |
| 362 | id: row.id, |
| 363 | title: row[titleColumn] || getItemDisplayName(kind, row), |
| 364 | description: detectedDescriptionColumns.map((c) => row[c]).find(Boolean) || getItemDescription(row), |
| 365 | }; |
| 366 | |
| 367 | const decision = classifyLLM(item); |
| 368 | summary.reviewed += 1; |
| 369 | |
| 370 | if (decision.keep) { |
| 371 | summary.kept += 1; |
| 372 | changeLog.push({ |
| 373 | action: 'kept_llm_tag', |
| 374 | kind, |
| 375 | item_id: item.id, |
| 376 | title: item.title, |
| 377 | reason: decision.reason, |
| 378 | }); |
| 379 | continue; |
| 380 | } |
| 381 | |
| 382 | if (!isDryRun) { |
| 383 | const { error: delError } = await supabase |
| 384 | .from(junctionTable) |
| 385 | .delete() |
| 386 | .eq(itemIdColumn, itemId) |
| 387 | .eq('category_id', llmCategoryId); |
| 388 | if (delError) { |
| 389 | throw new Error(`Failed removing LLM tag from ${junctionTable}/${itemId}: ${delError.message}`); |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | summary.removed += 1; |
| 394 | changeLog.push({ |
| 395 | action: 'removed_llm_tag', |
| 396 | kind, |
| 397 | item_id: item.id, |
| 398 | title: item.title, |
| 399 | reason: decision.reason, |
| 400 | dry_run: isDryRun, |
| 401 | }); |
| 402 | |
| 403 | const minResult = await ensureMinimumTags({ |
| 404 | kind, |
| 405 | itemId: item.id, |
| 406 | itemData: item, |
| 407 | categoryIdColumn: itemIdColumn, |
| 408 | junctionTable, |
| 409 | categoriesById, |
| 410 | llmCategoryId, |
| 411 | changeLog, |
| 412 | }); |
| 413 | |
| 414 | if (minResult.added.length > 0) { |
| 415 | summary.replacementsAdded += minResult.added.length; |
| 416 | } |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | async function main() { |
| 421 | const startedAt = new Date().toISOString(); |
| 422 | console.log(`[audit-llm-tag] Start ${startedAt} ${isDryRun ? '(DRY RUN)' : ''}`); |
| 423 | |
| 424 | const { data: categories, error: catError } = await supabase |
| 425 | .from('categories') |
| 426 | .select('id, name, slug, icon, description'); |
| 427 | if (catError) throw new Error(`Failed loading categories: ${catError.message}`); |
| 428 | |
| 429 | const categoriesById = new Map((categories || []).map((c) => [c.id, c])); |
| 430 | const llmCategory = |
| 431 | (categories || []).find((c) => normalize(c.name) === 'llms') || |
| 432 | (categories || []).find((c) => normalize(c.slug) === 'llms'); |
| 433 | |
| 434 | if (!llmCategory) { |
| 435 | throw new Error('Could not find category named/sluggified as "LLMs"'); |
| 436 | } |
| 437 | |
| 438 | const llmCategoryId = llmCategory.id; |
| 439 | console.log(`[audit-llm-tag] LLMs category id: ${llmCategoryId}`); |
| 440 | |
| 441 | const postJunction = await detectTable(['posts_categories', 'post_categories', 'blog_posts_categories']); |
| 442 | const learningTable = await detectTable(['learning', 'learning_resources']); |
| 443 | const learningIdColumn = await detectColumn('learning_categories', ['learning_id', 'learning_resource_id']); |
| 444 | if (!postJunction) throw new Error('Could not detect posts junction table'); |
| 445 | if (!learningTable) throw new Error('Could not detect learning table'); |
| 446 | if (!learningIdColumn) throw new Error('Could not detect learning id column in learning_categories'); |
| 447 | |
| 448 | const postIdColumn = postJunction === 'blog_posts_categories' ? 'blog_post_id' : 'post_id'; |
| 449 | |
| 450 | const summary = { |
| 451 | reviewed: 0, |
| 452 | kept: 0, |
| 453 | removed: 0, |
| 454 | replacementsAdded: 0, |
| 455 | skippedMissing: 0, |
| 456 | }; |
| 457 | const changeLog = []; |
| 458 | |
| 459 | await processKind({ |
| 460 | kind: 'tools', |
| 461 | itemTable: 'tools', |
| 462 | junctionTable: 'tools_categories', |
| 463 | itemIdColumn: 'tool_id', |
| 464 | titleCandidates: ['name', 'title'], |
| 465 | descriptionCandidates: ['description'], |
| 466 | llmCategoryId, |
| 467 | categoriesById, |
| 468 | summary, |
| 469 | changeLog, |
| 470 | }); |
| 471 | |
| 472 | await processKind({ |
| 473 | kind: 'news', |
| 474 | itemTable: 'news', |
| 475 | junctionTable: 'news_categories', |
| 476 | itemIdColumn: 'news_id', |
| 477 | titleCandidates: ['title', 'name', 'headline'], |
| 478 | descriptionCandidates: ['description', 'summary', 'content'], |
| 479 | llmCategoryId, |
| 480 | categoriesById, |
| 481 | summary, |
| 482 | changeLog, |
| 483 | }); |
| 484 | |
| 485 | await processKind({ |
| 486 | kind: 'posts', |
| 487 | itemTable: 'posts', |
| 488 | junctionTable: postJunction, |
| 489 | itemIdColumn: postIdColumn, |
| 490 | titleCandidates: ['title', 'name'], |
| 491 | descriptionCandidates: ['description', 'excerpt', 'content'], |
| 492 | llmCategoryId, |
| 493 | categoriesById, |
| 494 | summary, |
| 495 | changeLog, |
| 496 | }); |
| 497 | |
| 498 | await processKind({ |
| 499 | kind: 'learning', |
| 500 | itemTable: learningTable, |
| 501 | junctionTable: 'learning_categories', |
| 502 | itemIdColumn: learningIdColumn, |
| 503 | titleCandidates: ['title', 'name'], |
| 504 | descriptionCandidates: ['description', 'summary', 'content'], |
| 505 | llmCategoryId, |
| 506 | categoriesById, |
| 507 | summary, |
| 508 | changeLog, |
| 509 | }); |
| 510 | |
| 511 | const endedAt = new Date().toISOString(); |
| 512 | const timestamp = new Date().toISOString().replace(/[:.]/g, '-'); |
| 513 | const outDir = path.resolve(process.cwd(), 'logs'); |
| 514 | if (!fs.existsSync(outDir)) fs.mkdirSync(outDir, { recursive: true }); |
| 515 | const outPath = path.join(outDir, `audit-llm-tag-${timestamp}.json`); |
| 516 | |
| 517 | const payload = { |
| 518 | started_at: startedAt, |
| 519 | ended_at: endedAt, |
| 520 | dry_run: isDryRun, |
| 521 | llms_category: llmCategory, |
| 522 | detected_tables: { |
| 523 | posts_junction: postJunction, |
| 524 | posts_item_id_column: postIdColumn, |
| 525 | learning_table: learningTable, |
| 526 | learning_item_id_column: learningIdColumn, |
| 527 | }, |
| 528 | summary, |
| 529 | changes: changeLog, |
| 530 | }; |
| 531 | |
| 532 | fs.writeFileSync(outPath, JSON.stringify(payload, null, 2), 'utf8'); |
| 533 | |
| 534 | console.log('[audit-llm-tag] Summary'); |
| 535 | console.log(JSON.stringify(summary, null, 2)); |
| 536 | console.log(`[audit-llm-tag] Change log written: ${outPath}`); |
| 537 | } |
| 538 | |
| 539 | main().catch((err) => { |
| 540 | console.error(`[audit-llm-tag] Failed: ${err instanceof Error ? err.message : String(err)}`); |
| 541 | process.exit(1); |
| 542 | }); |