// The higher-level panoptiblog model: spam filters, publication ranking, and // ecosystem comparisons. // // The pure scoring core lives in ./scoring.mjs. This module re-exports its // public functions so existing indexer and test imports keep working. import { DAY, READING_WPM, roundTo } from './scoring.mjs' export { READING_WPM, analyzeDocument, analyzeDocuments, countWords, extractLinks, extractText, factorPercentiles, factorValues, median, medianOf, normalizeTag, percentileRanks, roundTo, SCORE_TREE, scoreWithWarnings, sum, textSignature, titleSignature, treeScore, } from './scoring.mjs' export function spamSignals(metrics) { const reasons = [] if (metrics.noTextRatio >= 0.5 && metrics.docCount >= 20) reasons.push('mostly-empty') if (metrics.duplicateRatio >= 0.5 && metrics.signatureDocs >= 5) reasons.push('duplicate-text') if (metrics.templatedTitleRatio >= 0.5 && metrics.docCount >= 20) reasons.push('templated-titles') if (metrics.velocityPerDay >= 20 && metrics.medianWords < 100 && metrics.docCount >= 50) { reasons.push('bulk-velocity') } if (metrics.docCount >= 5_000 && metrics.medianWords < 200) reasons.push('bulk-volume') const excluding = new Set(['duplicate-text', 'templated-titles', 'bulk-velocity']) return { reasons, excluded: reasons.some((reason) => excluding.has(reason)) } } /** An account that publishes at a scale no person reaches. */ export function isBulkAccount({ publicationCount, docCount, wordCount }) { return ( publicationCount >= 20 || (docCount >= 5_000 && publicationCount >= 2) || (wordCount >= 5_000_000 && publicationCount >= 10) ) } /** A validated theme color as CSS, or undefined for anything malformed. */ function cssColor(value) { if (!value || typeof value !== 'object') return undefined const { r, g, b } = value if (![r, g, b].every((n) => Number.isInteger(n) && n >= 0 && n <= 255)) return undefined return `rgb(${r} ${g} ${b})` } /** * A publication's basic theme as CSS colors. The accent is required; the rest * are optional. Every component is validated, so no record string reaches CSS. */ export function themeOf(record) { const basic = record?.basicTheme if (!basic || typeof basic !== 'object') return undefined const accent = cssColor(basic.accent) if (!accent) return undefined const theme = { accent } for (const key of ['background', 'foreground', 'accentForeground']) { const color = cssColor(basic[key]) if (color) theme[key] = color } return theme } /** * The score tree. Each category is a weighted average of its factor * percentiles; the overall score is a weighted average of the categories. * `factorValues` supplies the raw values, `factorPercentiles` makes them * comparable within a cohort, and `treeScore` can be called with any weights — * which is how the page's sliders experiment without different data. */ /** * Whether a publication enters the scored cohort. An undiscoverable * publication has opted out: it is indexed and shown in the filter counts, * but it gets no score, rank, or percentile label. The operator override is * for diagnostics, not the published run. */ export function scoreEligible( row, minimumWords, { includeUndiscoverable = false, includeNonEnglish = false } = {}, ) { return ( !row.spam?.excluded && (row.wordCount ?? 0) >= minimumWords && (row.discoverable || includeUndiscoverable) && (row.language === 'eng' || includeNonEnglish) ) } /** * Why a publication is not in the ranking. One disjoint label per row, in the * order the filters ran, so the counts add up to the publication total. */ export function exclusionReason(row, minimumWords) { if (row?.rank !== undefined) return 'included' if (row?.spam?.excluded) return 'spam' if (!row?.discoverable) return 'undiscoverable' if (row?.language !== undefined && row.language !== 'eng') return 'language' if (row?.docCount === 0) return 'no-posts' if (row?.wordCount < minimumWords) return 'below-minimum-words' return 'other' } /** Sort descending by `score`, then by a stable tie-breaker, and number them. */ export function rank(items, { scoreKey = 'score', tieKey = 'wordCount' } = {}) { const sorted = [...items].sort( (a, b) => (b[scoreKey] ?? 0) - (a[scoreKey] ?? 0) || (b[tieKey] ?? 0) - (a[tieKey] ?? 0) || String(a.uri ?? a.did ?? '').localeCompare(String(b.uri ?? b.did ?? '')), ) sorted.forEach((item, index) => { item.rank = index + 1 }) return sorted } /** Median of values weighted by post count; publication medians are noisy. */ function weightedMedian(rows, pick, weight = () => 1) { const pairs = [] for (const row of rows) { const value = pick(row) if (!Number.isFinite(value)) continue pairs.push({ value, weight: Math.max(1, weight(row) || 1) }) } if (pairs.length === 0) return 0 pairs.sort((a, b) => a.value - b.value) const total = pairs.reduce((sum, pair) => sum + pair.weight, 0) let cumulative = 0 for (const pair of pairs) { cumulative += pair.weight if (cumulative >= total / 2) return pair.value } return pairs[pairs.length - 1].value } function ratio(value, baseline) { if (!Number.isFinite(value) || !Number.isFinite(baseline) || baseline <= 0) return 0 return Math.min(1, value / baseline) } /** * The ecosystem view: a flow of reading time and posts, the corpus-wide craft * and sourcing medians, and growth. Unlike a publication score, these are not * relative to a cohort of publications; a baseline corpus turns them into a * comparison and a health index. */ export function ecosystemMetrics(publications, { now = Date.now() } = {}) { const rows = publications ?? [] const total = (pick) => rows.reduce((sum, row) => { const value = pick(row) return sum + (Number.isFinite(value) ? value : 0) }, 0) const readingMinutes = total((row) => row.readingMinutes) const minutesLast24h = total((row) => row.readingMinutesLast24h) const minutesLast7d = total((row) => row.readingMinutesLast7d) const minutesLast30d = total((row) => row.readingMinutesLast30d) const postsLast24h = total((row) => row.postsLast24h) const postsLast7d = total((row) => row.postsLast7d) const postsLast30 = total((row) => row.postsLast30) const wordCount = total((row) => row.wordCount) const externalLinks = total((row) => row.health?.links?.external) const socialLinks = total((row) => row.health?.links?.social) const hosts = new Set() for (const row of rows) { for (const host of row.health?.links?.hosts ?? []) hosts.add(host) } const reading = { wpm: READING_WPM, minutesLast24h: roundTo(minutesLast24h, 1), hoursLast24h: roundTo(minutesLast24h / 60), hoursPerDay7d: roundTo(minutesLast7d / 60 / 7), hoursPerDay30d: roundTo(minutesLast30d / 60 / 30), hoursTotal: roundTo(readingMinutes / 60, 1), postsLast24h, postsLast7d, postsPerDay30d: roundTo(postsLast30 / 30), activePublications30d: rows.filter((row) => (row.postsLast30 ?? 0) > 0).length, publicationCount: rows.length, newPublications30d: rows.filter( (row) => row.createdAt && now - Date.parse(row.createdAt) <= 30 * DAY, ).length, spamShare: rows.length > 0 ? roundTo(total((row) => (row.spam?.excluded ? 1 : 0)) / rows.length, 3) : 0, duplicateRatio: roundTo( weightedMedian(rows, (row) => row.duplicateRatio, (row) => row.docCount), 3, ), } const readability = {} for (const key of [ 'fleschKincaid', 'fleschReadingEase', 'gunningFog', 'smog', 'colemanLiau', 'ari', ]) { readability[key] = roundTo( weightedMedian(rows, (row) => row.health?.readability?.[key], (row) => row.docCount), 1, ) } const lexical = {} for (const key of ['mtld', 'ttr', 'hapaxRatio', 'longWordRatio', 'complexWordRatio']) { lexical[key] = roundTo( weightedMedian(rows, (row) => row.health?.lexical?.[key], (row) => row.docCount), 3, ) } const style = {} for (const key of [ 'sentenceLengthMean', 'sentenceLengthStd', 'sentenceLengthEntropy', 'punctuationEntropy', 'firstSingularPer1000', 'firstPluralPer1000', 'secondPer1000', 'emojiPer1000', 'questionPer1000', 'exclamationPer1000', ]) { style[key] = roundTo( weightedMedian(rows, (row) => row.health?.style?.[key], (row) => row.docCount), 2, ) } return { reading, readability, lexical, style, links: { external: externalLinks, social: socialLinks, uniqueExternalHosts: hosts.size, externalPer1000Words: roundTo(wordCount > 0 ? (externalLinks / wordCount) * 1000 : 0), socialShare: roundTo(externalLinks > 0 ? socialLinks / externalLinks : 0, 3), }, } } /** * Attach baseline comparisons and an ecosystem health index. Without a * baseline there is nothing to be healthy relative to, so `health` is null * rather than an arbitrary target. */ export function compareEcosystem(ecosystem, baselines = []) { const result = { ...ecosystem, baselines, comparison: null, health: null } const baseline = baselines[0] if (!baseline) return result const metrics = baseline.metrics ?? baseline const components = { readability: Number.isFinite(metrics.readability?.fleschKincaid) ? Math.max( 0, 1 - Math.min( Math.abs( ecosystem.readability.fleschKincaid - metrics.readability.fleschKincaid, ) / 10, 1, ), ) : 0, lexical: ratio(ecosystem.lexical.mtld, metrics.lexical?.mtld ?? 0), sourcing: ratio( ecosystem.links.externalPer1000Words, metrics.links?.externalPer1000Words ?? metrics.links?.per1000Words ?? 0, ), originality: Math.max(0, 1 - ecosystem.reading.spamShare), } const weights = { readability: 0.3, lexical: 0.25, sourcing: 0.25, originality: 0.2, } const score = Object.entries(weights).reduce( (sum, [key, weight]) => sum + weight * (components[key] ?? 0), 0, ) result.comparison = { name: baseline.name, metrics } result.health = { score: roundTo(score * 100, 1), components: Object.fromEntries( Object.entries(components).map(([key, value]) => [key, roundTo(value, 3)]), ), baseline: baseline.name, } return result }