// Turns standard.site records into the numbers panoptiblog publishes. // // Everything here is pure: it takes records already read from a PDS and // returns metrics. The formulas are deliberately small and visible rather // than learned, so a reader can see why a publication ranked where it did, // and so a run is reproducible. // // The composite is a weighted average of *percentiles*, not a sum of raw // values. Reach and recommends have long tails; a sum of logs still lets one // signal dominate. Ranking each component within the cohort first gives every // element a comparable 0-100 scale, and the weights below decide how much // each one contributes. export const DAY = 24 * 60 * 60 * 1000 /** Lower bound for a plausible standard.site timestamp. */ const STANDARD_START = Date.parse('2023-01-01') /** Canonical score-tree version. Bump with a score-tree-history entry. */ export const SCORE_VERSION = 16 /** Words per minute used for every reading-time number. */ export const READING_WPM = 200 const MIN_ZIPF = 1 const WORD = /[\p{L}\p{N}]/u const TOKEN = /[\p{L}\p{N}]+(?:['’][\p{L}\p{N}]+)*/gu const LINK = /https?:\/\/[^\s<>"')\]]+/giu const AT_URI = /at:\/\/[^\s<>"')\]]+/giu const DID = /did:[a-z]+:[a-z0-9._:%-]+/giu const MARKDOWN_LINK = /\[[^\]]*\]\((https?:\/\/[^)\s]+)\)/giu const MARKDOWN_LINK_INLINE = /\[([^\]]*)\]\(\s*(?:<([^>]+)>|([^\s)]+))(?:\s+["'][^"']*["'])?\s*\)/gu const MARKDOWN_IMAGE = /!\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/gu const MARKDOWN_LINK_TEXT = /\[([^\]]*)\]\((?:[^()]|\([^()]*\))*\)/gu const MARKDOWN_IMAGE_REFERENCE = /!\[([^\]]*)\]\[[^\]]*\]/gu const MARKDOWN_REFERENCE = /\[([^\]]*)\]\[([^\]]*)\]/gu const MARKDOWN_LINK_DEFINITION = /^[ \t]*\[([^\]]+)\]:[ \t]*(https?:\/\/[^\s>]+)>?[^\n]*$/gmu const FENCED_CODE = /```[\s\S]*?```|~~~[\s\S]*?~~~/gu const INLINE_CODE = /`[^`\n]+`/gu const HTML_COMMENT = //gu const HTML_RAW = /<(script|style)\b[^>]*>[\s\S]*?<\/\1>/giu const HTML_PRE = /
]*>[\s\S]*?<\/pre>/giu
const HTML_TAG = /<\/?[A-Za-z][^>]*>/gu
const HTML_LINK = /]*\bhref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))[^>]*>/giu
const HTML_ENTITY = /&(?:#\d+|#x[0-9a-f]+|[a-z][a-z0-9]+);/giu
const FOOTNOTE = /\[\^[^\]]+\]/gu
const PUNCT = /[.,;:!?…—–()\[\]"'“”‘’]/gu
const EMOJI = /\p{Extended_Pictographic}/gu
const SOCIAL_HOSTS = new Set([
'bsky.app',
'twitter.com',
'x.com',
'facebook.com',
'instagram.com',
'linkedin.com',
'youtube.com',
'youtu.be',
'tiktok.com',
'reddit.com',
'discord.gg',
'discord.com',
'threads.net',
'mastodon.social',
'tumblr.com',
'pinterest.com',
'medium.com',
])
const ATPROTO_HOSTS = new Set([
'bsky.app',
'atproto.com',
'docs.bsky.app',
'standard.site',
'leaflet.pub',
'pdsls.dev',
'plc.directory',
'tangled.org',
])
const PRONOUNS = {
firstSingular: new Set(['i', 'me', 'my', 'mine', 'myself']),
firstPlural: new Set(['we', 'us', 'our', 'ours', 'ourselves']),
second: new Set(['you', 'your', 'yours', 'yourself', 'yourselves']),
}
/**
* Prose in a document body, with markup removed.
*
* The index reads what a reader sees, not the syntax around it. Fenced code,
* HTML pre, script, and style blocks, Markdown and HTML tags, URLs, at://
* references, link definitions, image links, HTML comments, entities, and
* footnote markers are dropped before tokenizing. Link text, Markdown image
* alt text, and footnote prose remain, because they are words the author
* wrote. HTML attributes are not prose.
*/
export function stripMarkup(text) {
if (typeof text !== 'string' || text.length === 0) return ''
return text
.replace(HTML_COMMENT, ' ')
.replace(HTML_RAW, ' ')
.replace(FENCED_CODE, ' ')
.replace(HTML_PRE, ' ')
.replace(MARKDOWN_IMAGE, '$1')
.replace(MARKDOWN_LINK_TEXT, '$1')
.replace(MARKDOWN_IMAGE_REFERENCE, '$1')
.replace(MARKDOWN_REFERENCE, '$1')
.replace(MARKDOWN_LINK_DEFINITION, ' ')
.replace(HTML_TAG, ' ')
.replace(FOOTNOTE, ' ')
.replace(LINK, ' ')
.replace(AT_URI, ' ')
.replace(DID, ' ')
.replace(HTML_ENTITY, ' ')
}
/**
* Words in a document's plain-text body.
*
* Whitespace-delimited tokens containing at least one letter or number. This
* undercounts scripts that do not separate words with spaces, which is a
* known limit of a cheap count; the alternative is a segmenter per document,
* and the ranking is not precise enough to notice either way.
*/
export function countWords(text) {
if (typeof text !== 'string' || text.length === 0) return 0
let words = 0
for (const token of text.split(/\s+/u)) if (WORD.test(token)) words++
return words
}
function normalizeText(text) {
return text.normalize('NFKC').toLowerCase().replace(/\s+/gu, ' ').trim()
}
/** A digest of a document's opening, or null when it is too short to matter. */
export function textSignature(text, { digest }) {
if (typeof text !== 'string') return null
const normalized = normalizeText(text)
if (normalized.length < 80) return null
return digest(normalized.slice(0, 2_000))
}
/** A title with numbers and punctuation reduced to separators. */
export function titleSignature(title) {
if (typeof title !== 'string') return null
const normalized = title
.normalize('NFKC')
.toLowerCase()
.replace(/[0-9a-f]{6,}/g, '#')
.replace(/\d+/g, '#')
.replace(/[^\p{L}\p{N}#]+/gu, ' ')
.trim()
return normalized.length > 0 ? normalized : null
}
export function median(values) {
if (values.length === 0) return 0
const sorted = [...values].sort((a, b) => a - b)
const middle = Math.floor(sorted.length / 2)
return sorted.length % 2 === 0 ? (sorted[middle - 1] + sorted[middle]) / 2 : sorted[middle]
}
function entropy(counts) {
const total = [...counts.values()].reduce((sum, n) => sum + n, 0)
if (total === 0) return 0
let value = 0
for (const count of counts.values()) {
const p = count / total
value -= p * Math.log2(p)
}
return value
}
function gini(values) {
if (values.length === 0) return 0
const sorted = [...values].sort((a, b) => a - b)
const n = sorted.length
const sum = sorted.reduce((total, value) => total + value, 0)
if (sum === 0) return 0
let cumulative = 0
for (let i = 0; i < n; i++) cumulative += (i + 1) * sorted[i]
return (2 * cumulative) / (n * sum) - (n + 1) / n
}
/**
* The body text a record carries.
*
* `textContent` is the standard.site field and the first choice. Publishing
* tools that predate it, or that keep their own block format, often leave it
* out and put the prose in `content`: Leaflet nests `plaintext` under
* pages/blocks, pckt under items. Walk for those keys rather than for every
* string, so an image's base64 placeholder or alt text never becomes words.
*/
export function extractText(record) {
if (typeof record?.textContent === 'string' && record.textContent.length > 0) {
return record.textContent
}
const parts = []
collectText(record?.content, parts)
return parts.join('\n')
}
const TEXT_KEYS = new Set(['plaintext', 'text', 'content'])
function collectText(value, out) {
if (Array.isArray(value)) {
for (const item of value) collectText(item, out)
return
}
if (!value || typeof value !== 'object') return
for (const [key, child] of Object.entries(value)) {
if (typeof child === 'string' && TEXT_KEYS.has(key)) out.push(child)
else collectText(child, out)
}
}
function collectStructure(value, counts) {
if (Array.isArray(value)) {
for (const item of value) collectStructure(item, counts)
return
}
if (!value || typeof value !== 'object') return
const type = typeof value.$type === 'string' ? value.$type.toLowerCase() : ''
const typeName = type.includes('header') || type.includes('heading')
? 'heading'
: type.includes('list')
? 'list'
: type.includes('quote')
? 'quote'
: type.includes('code')
? 'code'
: type.includes('image') || type.includes('photo')
? 'image'
: undefined
if (typeName) counts.set(typeName, (counts.get(typeName) ?? 0) + 1)
for (const child of Object.values(value)) {
if (child && typeof child === 'object') collectStructure(child, counts)
}
}
function cleanUrl(value) {
if (typeof value !== 'string') return undefined
const trimmed = value.replace(/[.,;:!?…'"”’)\]]+$/u, '')
try {
const url = new URL(trimmed)
return url.protocol === 'http:' || url.protocol === 'https:' ? url.toString() : undefined
} catch {
return undefined
}
}
function cleanAtUri(value) {
const trimmed = value.replace(/[.,;:!?…'"”’)\]]+$/u, '')
return trimmed.startsWith('at://') ? trimmed : undefined
}
/**
* Links the author put in the article: raw URLs, Markdown links, HTML anchors,
* the content union's link facets, and the document's own `links` field.
*
* Image embeds are not links. A Markdown image, an HTML `
`, a reference
* image, and a URL inside inline or fenced code are skipped. An image wrapped
* in a link — Markdown or `` — contributes the link target, not the
* image source.
*/
export function extractLinks(record, text) {
const urls = new Set()
if (typeof text === 'string') {
const withoutCode = text
.replace(HTML_COMMENT, ' ')
.replace(HTML_RAW, ' ')
.replace(FENCED_CODE, ' ')
.replace(HTML_PRE, ' ')
.replace(INLINE_CODE, ' ')
const definitions = new Map()
for (const match of withoutCode.matchAll(MARKDOWN_LINK_DEFINITION)) {
const url = cleanUrl(match[2])
if (url) definitions.set(match[1].trim().toLowerCase(), url)
}
for (const match of withoutCode.matchAll(HTML_LINK)) {
const url = cleanUrl(match[1] ?? match[2] ?? match[3])
if (url) urls.add(url)
}
const withoutImages = withoutCode
.replace(MARKDOWN_IMAGE, ' ')
.replace(MARKDOWN_IMAGE_REFERENCE, ' ')
for (const match of withoutImages.matchAll(MARKDOWN_LINK_INLINE)) {
const url = cleanUrl(match[2] ?? match[3])
if (url) urls.add(url)
}
for (const match of withoutImages.matchAll(MARKDOWN_REFERENCE)) {
const label = (match[2] || match[1]).trim().toLowerCase()
const url = definitions.get(label)
if (url) urls.add(url)
}
const withoutDefinitions = withoutImages.replace(MARKDOWN_LINK_DEFINITION, ' ')
for (const [label, url] of definitions) {
if (withoutDefinitions.toLowerCase().includes(`[${label}]`)) urls.add(url)
}
const withoutInline = withoutDefinitions
.replace(MARKDOWN_LINK_INLINE, '$1')
.replace(MARKDOWN_REFERENCE, '$1')
const withoutTags = withoutInline.replace(HTML_TAG, ' ')
for (const match of withoutTags.matchAll(LINK)) {
const url = cleanUrl(match[0])
if (url) urls.add(url)
}
}
collectLinks(record?.content, urls)
collectLinks(record?.links, urls)
return [...urls]
}
function collectLinks(value, out) {
if (Array.isArray(value)) {
for (const item of value) collectLinks(item, out)
return
}
if (!value || typeof value !== 'object') return
if (typeof value.$type === 'string') {
const type = value.$type.toLowerCase()
if (type.includes('image') || type.includes('photo')) {
// The blob, src, and alt are not citations. A clickable image may carry
// its target separately; count that target, not the image source.
const link = value.href ?? value.link ?? value.linkUrl
if (typeof link === 'string') {
const url = cleanUrl(link)
if (url) out.add(url)
} else if (link && typeof link === 'object') {
collectLinks(link, out)
}
return
}
if (type.endsWith('#link')) {
const url = cleanUrl(value.uri ?? value.url)
if (url) out.add(url)
}
}
for (const [key, child] of Object.entries(value)) {
if (typeof child === 'string' && (key === 'uri' || key === 'url')) {
const url = cleanUrl(child)
if (url) out.add(url)
} else {
collectLinks(child, out)
}
}
}
/**
* at:// references and Bluesky embeds the text scan cannot see: quote posts,
* link facets and record refs stored as structured content.
*/
function collectAtproto(value, refs, embeds) {
if (Array.isArray(value)) {
for (const item of value) collectAtproto(item, refs, embeds)
return
}
if (!value || typeof value !== 'object') return
if (typeof value.$type === 'string' && value.$type.startsWith('app.bsky.embed.')) {
embeds.add(value)
}
for (const child of Object.values(value)) {
if (typeof child === 'string') {
for (const match of child.matchAll(AT_URI)) {
const uri = cleanAtUri(match[0])
if (uri) refs.add(uri)
}
} else {
collectAtproto(child, refs, embeds)
}
}
}
function webUrl(url) {
try {
const parsed = new URL(url)
return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed : undefined
} catch {
return undefined
}
}
function linkHost(url) {
return url.hostname.toLowerCase().replace(/^www\./, '')
}
function isAtprotoHost(host) {
return (
ATPROTO_HOSTS.has(host) ||
host.endsWith('.leaflet.pub') ||
host.endsWith('.standard.site')
)
}
function syllableCount(word) {
const cleaned = word.toLowerCase().replace(/[^a-z]/g, '')
if (!cleaned) return 0
const groups = cleaned.match(/[aeiouy]+/g)?.length ?? 0
const silent = cleaned.endsWith('e') && groups > 1 ? 1 : 0
return Math.max(1, groups - silent)
}
function splitSentences(text) {
return text
.replace(LINK, ' ')
.replace(MARKDOWN_LINK, '$1')
.split(/(?<=[.!?])\s+|\n+/u)
.map((sentence) => sentence.trim())
.filter(Boolean)
}
/** Measure of Textual Lexical Diversity; length-robust than a raw TTR. */
function mtldPass(tokens, threshold = 0.72) {
if (tokens.length === 0) return 0
let segments = 0
let start = 0
let unique = 0
const counts = new Map()
for (let i = 0; i < tokens.length; i++) {
const token = tokens[i]
const count = counts.get(token) ?? 0
counts.set(token, count + 1)
if (count === 0) unique++
if (unique / (i - start + 1) <= threshold) {
segments++
start = i + 1
unique = 0
counts.clear()
}
}
const remaining = tokens.length - start
if (remaining > 0) {
const ttr = unique / remaining
segments += Math.max(0, (1 - ttr) / (1 - threshold))
}
return segments > 0 ? tokens.length / segments : tokens.length
}
function mtld(tokens) {
if (tokens.length < 50) return 0
return (mtldPass(tokens) + mtldPass([...tokens].reverse())) / 2
}
function yulesK(tokens) {
if (tokens.length < 50) return 0
const counts = new Map()
for (const token of tokens) counts.set(token, (counts.get(token) ?? 0) + 1)
let sumSquares = 0
for (const count of counts.values()) sumSquares += count * count
return (10_000 * (sumSquares - tokens.length)) / (tokens.length * tokens.length)
}
function readability(tokens, sentences, syllables, complexWords, characters) {
const words = tokens.length
if (words === 0) return undefined
const sentenceCount = Math.max(1, sentences)
const wordsPerSentence = words / sentenceCount
const syllablesPerWord = syllables / words
const lettersPer100 = (characters / words) * 100
const sentencesPer100 = (sentenceCount / words) * 100
return {
fleschKincaid: 0.39 * wordsPerSentence + 11.8 * syllablesPerWord - 15.59,
fleschReadingEase: 206.835 - 1.015 * wordsPerSentence - 84.6 * syllablesPerWord,
gunningFog: 0.4 * (wordsPerSentence + (complexWords / words) * 100),
smog: 1.043 * Math.sqrt(30 * (complexWords / sentenceCount)) + 3.1291,
colemanLiau: 0.0588 * lettersPer100 - 0.296 * sentencesPer100 - 15.8,
ari: 4.71 * (characters / words) + 0.5 * wordsPerSentence - 21.43,
}
}
export function sum(values) {
return values.reduce((total, value) => total + value, 0)
}
export function medianOf(values) {
return median(values.filter((value) => Number.isFinite(value)))
}
/**
* The parts of one document the index keeps. The body itself is dropped here,
* after counting, so a walk over every repository never holds the corpus in
* memory at once.
*/
export function analyzeDocument(record, { digest, wordFrequency } = {}) {
const rawText = extractText(record)
const text = stripMarkup(rawText)
const tokens = text.normalize('NFKC').toLowerCase().match(TOKEN) ?? []
const sentences = splitSentences(text)
const sentenceLengths = sentences.map((sentence) => countWords(sentence))
const syllables = sum(tokens.map(syllableCount))
const complexWords = tokens.filter((token) => syllableCount(token) >= 3).length
// The readability formulas are English-centric. Skip them for text that is
// mostly not Latin script rather than report a meaningless grade level.
const latinTokens = tokens.filter((token) => /[a-z]/.test(token)).length
const latinCharacters = (text.match(/[A-Za-z]/gu) ?? []).length
const frequencies = new Map()
for (const token of tokens) frequencies.set(token, (frequencies.get(token) ?? 0) + 1)
const hapax = [...frequencies.values()].filter((count) => count === 1).length
const punctuation = new Map()
for (const mark of text.match(PUNCT) ?? []) {
punctuation.set(mark, (punctuation.get(mark) ?? 0) + 1)
}
const emoji = (text.match(EMOJI) ?? []).length
const paragraphs = text.split(/\n\s*\n/u).map((part) => countWords(part)).filter((n) => n > 0)
const blockCounts = new Map()
const structureText = rawText.replace(FENCED_CODE, ' ').replace(HTML_PRE, ' ')
const block = (name, pattern) => {
const count = (structureText.match(pattern) ?? []).length
if (count > 0) blockCounts.set(name, count)
}
block('heading', /^(?: {0,3}#{1,6}\s)|\s?| 0) blockCounts.set('paragraph', paragraphs.length)
const structuralVariety =
blockCounts.size > 0 ? entropy(blockCounts) / Math.log2(6) : 0
const zipf =
wordFrequency && tokens.length > 0
? sum(
tokens.map((token) =>
Number.isFinite(wordFrequency[token]) ? wordFrequency[token] : MIN_ZIPF,
),
) / tokens.length
: undefined
const atprotoRefs = new Set()
const embeds = new Set()
collectAtproto(record?.content, atprotoRefs, embeds)
collectAtproto(record?.links, atprotoRefs, embeds)
collectAtproto(record?.embed, atprotoRefs, embeds)
collectAtproto(record?.embeds, atprotoRefs, embeds)
const pronounCounts = {
firstSingular: tokens.filter((token) => PRONOUNS.firstSingular.has(token)).length,
firstPlural: tokens.filter((token) => PRONOUNS.firstPlural.has(token)).length,
second: tokens.filter((token) => PRONOUNS.second.has(token)).length,
}
const per1000 = (count) => (tokens.length > 0 ? (count / tokens.length) * 1000 : 0)
const meanSentence = sentenceLengths.length > 0 ? sum(sentenceLengths) / sentenceLengths.length : 0
const sentenceVariance =
sentenceLengths.length > 0
? sum(sentenceLengths.map((length) => (length - meanSentence) ** 2)) / sentenceLengths.length
: 0
const sentenceCounts = new Map()
for (const length of sentenceLengths) sentenceCounts.set(length, (sentenceCounts.get(length) ?? 0) + 1)
return {
words: countWords(text),
tokens: tokens.length,
signature: textSignature(text, { digest }),
titleSignature: titleSignature(record?.title),
publishedAt: typeof record?.publishedAt === 'string' ? record.publishedAt : undefined,
updatedAt: typeof record?.updatedAt === 'string' ? record.updatedAt : undefined,
tags: [
...new Set((Array.isArray(record?.tags) ? record.tags : []).map(normalizeTag).filter(Boolean)),
],
linkUrls: extractLinks(record, rawText),
atprotoRefs: atprotoRefs.size,
embeds: embeds.size,
lexical: {
ttr: tokens.length > 0 ? frequencies.size / tokens.length : 0,
mtld: mtld(tokens),
yulesK: yulesK(tokens),
hapaxRatio: tokens.length > 0 ? hapax / tokens.length : 0,
zipf,
// Length and syllable count are crude rarity proxies.
longWordRatio: tokens.length > 0 ? tokens.filter((t) => t.length >= 7).length / tokens.length : 0,
complexWordRatio: tokens.length > 0 ? complexWords / tokens.length : 0,
},
readability:
tokens.length > 0 && latinTokens / tokens.length >= 0.5
? readability(tokens, sentences.length, syllables, complexWords, latinCharacters)
: undefined,
style: {
sentenceLengthMean: meanSentence,
sentenceLengthStd: Math.sqrt(sentenceVariance),
sentenceLengthEntropy: entropy(sentenceCounts),
punctuationEntropy: entropy(punctuation),
firstSingularPer1000: per1000(pronounCounts.firstSingular),
firstPluralPer1000: per1000(pronounCounts.firstPlural),
secondPer1000: per1000(pronounCounts.second),
emojiPer1000: per1000(emoji),
questionPer1000: per1000((text.match(/\?/gu) ?? []).length),
exclamationPer1000: per1000((text.match(/!/gu) ?? []).length),
},
structure: {
paragraphs: paragraphs.length,
paragraphWordsMean: paragraphs.length > 0 ? sum(paragraphs) / paragraphs.length : 0,
structuralVariety,
},
}
}
export function pathMatches(targetPath, linkPath) {
return (
linkPath === targetPath ||
(targetPath === '' ? linkPath.startsWith('/') : linkPath.startsWith(`${targetPath}/`))
)
}
function linkHealth(entries, publicationHost, { stansiteHosts, stansiteTargets } = {}) {
const hosts = new Set()
const sourceHosts = new Set()
const hostCounts = new Map()
let total = 0
let external = 0
let internal = 0
let social = 0
let sources = 0
let stansite = 0
let atproto = 0
let atprotoRefs = 0
let embeds = 0
let docsWithLinks = 0
for (const entry of entries) {
atprotoRefs += entry.atprotoRefs ?? 0
embeds += entry.embeds ?? 0
const urls = entry.linkUrls ?? []
if (urls.length > 0) docsWithLinks++
const seen = new Set()
for (const value of urls) {
const url = webUrl(value)
if (!url) continue
const key = url.href
if (seen.has(key)) continue
seen.add(key)
total++
const host = linkHost(url)
if (publicationHost && host === publicationHost) {
internal++
} else {
external++
hosts.add(host)
hostCounts.set(host, (hostCounts.get(host) ?? 0) + 1)
const targets = stansiteTargets?.get(host)
const path = url.pathname.replace(/\/+$/u, '')
const stansiteLink = targets
? targets.some((target) => pathMatches(target, path))
: stansiteHosts?.has(host)
const atprotoLink = isAtprotoHost(host)
if (stansiteLink) stansite++
else if (atprotoLink) atproto++
if (SOCIAL_HOSTS.has(host)) social++
else if (!stansiteLink && !atprotoLink) {
sources++
sourceHosts.add(host)
}
}
}
}
const words = sum(entries.map((entry) => entry.words))
const per1000 = (count) => (words > 0 ? (count / words) * 1000 : 0)
return {
total,
external,
internal,
social,
sources,
stansite,
atproto,
atprotoRefs,
embeds,
docsWithLinks,
uniqueExternalHosts: hosts.size,
uniqueSourceHosts: sourceHosts.size,
hosts: [...hosts],
hostEntropy: entropy(hostCounts),
per1000Words: per1000(external),
stansitePer1000Words: per1000(stansite),
atprotoPer1000Words: per1000(atproto),
ecosystemPer1000Words: per1000(stansite + atproto),
atprotoRefsPer1000Words: per1000(atprotoRefs),
}
}
function cadence(published) {
const dates = [...published].sort((a, b) => a - b)
const gaps = []
for (let i = 1; i < dates.length; i++) gaps.push((dates[i] - dates[i - 1]) / DAY)
const activeDays =
dates.length > 1 ? Math.max(1, (dates[dates.length - 1] - dates[0]) / DAY) : 1
return {
posts: dates.length,
postsPerMonth: dates.length > 0 ? dates.length / Math.max(activeDays / 30, 1) : 0,
medianGapDays: gaps.length > 0 ? median(gaps) : 0,
gapGini: gini(gaps),
}
}
/**
* Per-publication metrics over the compact entries `analyzeDocument` returns.
* A document with no `textContent` still counts as a post; it contributes zero
* words and is part of the `noTextRatio` that separates a linkblog from a
* generated corpus.
*/
export function analyzeDocuments(
entries,
{
now = Date.now(),
publicationHost,
stansiteHosts,
stansiteTargets,
publicationCreatedAt,
} = {},
) {
const words = []
const signatures = new Map()
const titles = new Map()
const tagCounts = new Map()
const languageCounts = new Map()
const published = []
let postsLast24h = 0
let postsLast7d = 0
let postsLast30 = 0
let postsLast90 = 0
let postsLast365 = 0
let readingMinutes = 0
let readingMinutesLast24h = 0
let readingMinutesLast7d = 0
let readingMinutesLast30d = 0
let recentWords90 = 0
let priorWords90 = 0
for (const doc of entries) {
words.push(doc.words)
const minutes = (doc.words ?? 0) / READING_WPM
readingMinutes += minutes
if (doc.signature) signatures.set(doc.signature, (signatures.get(doc.signature) ?? 0) + 1)
if (doc.titleSignature) {
titles.set(doc.titleSignature, (titles.get(doc.titleSignature) ?? 0) + 1)
}
for (const tag of doc.tags ?? []) tagCounts.set(tag, (tagCounts.get(tag) ?? 0) + 1)
if (doc.language) languageCounts.set(doc.language, (languageCounts.get(doc.language) ?? 0) + 1)
const at = Date.parse(doc.publishedAt ?? '')
// A future timestamp is a scheduled or clock-skewed post, not something
// published now. It still counts as a document, but not as recent activity.
if (!Number.isNaN(at) && at <= now) {
published.push(at)
if (now - at <= DAY) {
postsLast24h++
readingMinutesLast24h += minutes
}
if (now - at <= 7 * DAY) {
postsLast7d++
readingMinutesLast7d += minutes
}
if (now - at <= 30 * DAY) {
postsLast30++
readingMinutesLast30d += minutes
}
if (now - at <= 90 * DAY) {
postsLast90++
recentWords90 += doc.words ?? 0
} else if (now - at <= 180 * DAY) {
priorWords90 += doc.words ?? 0
}
if (now - at <= 365 * DAY) postsLast365++
}
}
const docCount = entries.length
const wordCount = sum(words)
const first = published.length > 0 ? Math.min(...published) : undefined
const last = published.length > 0 ? Math.max(...published) : undefined
const activeDays =
first !== undefined && last !== undefined ? Math.max(1, (last - first) / DAY) : 1
const created = Date.parse(publicationCreatedAt ?? '')
const rawStart = Number.isFinite(created) && created <= now ? created : first
const start =
rawStart === undefined ? undefined : Math.min(now, Math.max(STANDARD_START, rawStart))
const WEEKS = 7 * DAY
const HALF_LIFE_WEEKS = 26
let presence = 0
let datedPosts = 0
if (start !== undefined) {
const startWeek = Math.floor(start / WEEKS)
const endWeek = Math.floor(now / WEEKS)
const active = new Set()
for (const at of published) {
if (at < start) continue
datedPosts++
active.add(Math.floor(at / WEEKS))
}
let numerator = 0
let denominator = 0
for (let week = startWeek; week <= endWeek; week++) {
const weight = 0.5 ** ((endWeek - week) / HALF_LIFE_WEEKS)
denominator += weight
if (active.has(week)) numerator += weight
}
const evidence = Math.min(1, datedPosts / 5)
presence = denominator > 0 ? (numerator / denominator) * evidence : 0
}
const acceleration =
recentWords90 > 0 ? (recentWords90 + 1) / (priorWords90 + 1) : 0
const signatureDocs = [...signatures.values()].reduce((total, n) => total + n, 0)
const duplicated = [...signatures.values()].filter((n) => n > 1).reduce((total, n) => total + n, 0)
const titleDocs = [...titles.values()].reduce((total, n) => total + n, 0)
const templated = titles.size > 0 ? Math.max(...titles.values()) : 0
const readabilityRows = entries.map((entry) => entry.readability).filter(Boolean)
const readabilityMedian = {}
for (const key of [
'fleschKincaid',
'fleschReadingEase',
'gunningFog',
'smog',
'colemanLiau',
'ari',
]) {
readabilityMedian[key] = medianOf(readabilityRows.map((row) => row[key]))
}
const lexicalMedian = {}
for (const key of ['ttr', 'mtld', 'yulesK', 'hapaxRatio', 'longWordRatio', 'complexWordRatio']) {
lexicalMedian[key] = medianOf(entries.map((entry) => entry.lexical?.[key]))
}
const zipfValues = entries.map((entry) => entry.lexical?.zipf).filter(Number.isFinite)
lexicalMedian.zipf = zipfValues.length > 0 ? medianOf(zipfValues) : undefined
const styleMedian = {}
for (const key of [
'sentenceLengthMean',
'sentenceLengthStd',
'sentenceLengthEntropy',
'punctuationEntropy',
'firstSingularPer1000',
'firstPluralPer1000',
'secondPer1000',
'emojiPer1000',
'questionPer1000',
'exclamationPer1000',
]) {
styleMedian[key] = medianOf(entries.map((entry) => entry.style?.[key]))
}
const paragraphMean = medianOf(entries.map((entry) => entry.structure?.paragraphWordsMean))
const structuralVariety = medianOf(entries.map((entry) => entry.structure?.structuralVariety))
const links = linkHealth(entries, publicationHost, { stansiteHosts, stansiteTargets })
return {
docCount,
wordCount,
meanWords: docCount > 0 ? wordCount / docCount : 0,
medianWords: median(words),
firstPublishedAt: first === undefined ? undefined : new Date(first).toISOString(),
lastPublishedAt: last === undefined ? undefined : new Date(last).toISOString(),
activeDays,
presence,
acceleration,
recentWords90,
priorWords90,
postsLast24h,
postsLast7d,
postsLast30,
postsLast90,
postsLast365,
readingMinutes,
readingHours: readingMinutes / 60,
readingMinutesLast24h,
readingMinutesLast7d,
readingMinutesLast30d,
readingMinutesPerPost: docCount > 0 ? readingMinutes / docCount : 0,
velocityPerDay: docCount / activeDays,
signatureDocs,
duplicateRatio: signatureDocs > 0 ? duplicated / signatureDocs : 0,
titleDocs,
templatedTitleRatio: titleDocs > 0 ? templated / titleDocs : 0,
noTextRatio: docCount > 0 ? words.filter((n) => n === 0).length / docCount : 0,
linksPer1000Words: links.per1000Words,
language: [...languageCounts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0],
languages: [...languageCounts.entries()]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.map(([language, documents]) => ({ language, documents })),
topTags: [...tagCounts.entries()]
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.slice(0, 10)
.map(([tag, count]) => ({ tag, count })),
health: {
readability: readabilityMedian,
lexical: lexicalMedian,
style: styleMedian,
structure: { paragraphWordsMean: paragraphMean, structuralVariety },
links,
cadence: cadence(published),
},
}
}
/**
* Reasons a publication looks generated rather than written, and whether that
* is enough to keep it out of a ranking.
*/
export const SCORE_TREE = {
categories: [
{
id: 'audience',
name: 'Audience',
icon: 'reach',
vibe: 'Who follows and endorses it.',
detail:
'Weighted average of subscriber and recommender percentiles. Zero counts score zero; positive counts are ranked only against other publications with a positive count. Self-edges are excluded.',
weight: 1 / 6,
factors: [
{
id: 'reach',
name: 'Subscribers',
positiveCohort: true,
weight: 0.6,
scale: 'log1p(distinct subscribers)',
detail:
'Distinct accounts with a subscription record for this publication. Zero scores zero; positive counts are ranked only against publications with at least one subscriber. Self-subscriptions are excluded.',
},
{
id: 'recommends',
name: 'Recommenders',
positiveCohort: true,
weight: 0.4,
scale: 'log1p(distinct recommenders)',
detail:
'Distinct accounts recommending any of this publication’s documents. Zero scores zero; positive counts are ranked only against publications with at least one recommender. Self-recommends are excluded.',
},
],
},
{
id: 'output',
name: 'Volume',
icon: 'output',
vibe: 'How much has been published.',
detail: 'Weighted average of prose words and posts.',
weight: 1 / 6,
factors: [
{
id: 'volume',
name: 'Words',
weight: 0.6,
scale: 'log1p(words / 1000)',
detail:
'Total prose words across ranked posts, divided by 1,000 and log-scaled. Percentile-ranked, so a few very long posts cannot run away with the category.',
},
{
id: 'consistency',
name: 'Posts',
weight: 0.4,
scale: 'posts',
detail:
'Ranked post count. The percentile rank handles scale, so there is no cap.',
},
],
},
{
id: 'longevity',
name: 'Consistency',
icon: 'longevity',
vibe: 'How long it has kept going, and how evenly.',
detail:
'Weighted average of Presence and cadence regularity, both discounted until five dated posts establish a history.',
weight: 1 / 6,
factors: [
{
id: 'longevity',
name: 'Presence',
weight: 0.55,
scale: 'EWMA active-week coverage',
detail:
'Exponentially weighted share of weeks containing a post since the publication record was created, with a 26-week half-life. A five-post evidence multiplier applies. It measures showing up, not the date it started.',
},
{
id: 'cadenceRegularity',
name: 'Cadence',
weight: 0.45,
scale: '1 - gap Gini',
detail:
'One minus the Gini coefficient of gaps between dated posts, discounted until five dated posts establish a history. Even spacing scores high; bursts score low.',
},
],
},
{
id: 'craft',
name: 'Style',
icon: 'voice',
vibe: 'What the prose is like to read.',
detail:
'Weighted average of depth, vocabulary, rarity, readability, and structure. It asks how the prose reads and how well it is arranged.',
weight: 1 / 6,
factors: [
{
id: 'depth',
name: 'Depth',
weight: 0.3,
scale: 'median words per post',
detail:
'Median words per post. The median keeps one link-dump post from carrying the factor; the percentile rank handles scale, so there is no 800-word cap.',
},
{
id: 'lexicalDiversity',
name: 'Vocabulary',
weight: 0.2,
scale: 'MTLD',
detail:
"MTLD over the publication's posts. Higher means a wider working vocabulary; short corpora are noisy.",
},
{
id: 'rareWords',
name: 'Rarity',
weight: 0.15,
scale: '1 - mean Zipf / 8',
detail:
'Mean Zipf frequency of the prose tokens, from the bundled English frequency list, inverted so higher means rarer. It is a per-token average, not a length-sensitive hapax ratio.',
},
{
id: 'readability',
name: 'Readability',
weight: 0.2,
scale: '1 - min(|Flesch-Kincaid - 10| / 10, 1)',
detail:
'Closeness to a Flesch-Kincaid grade of 10: 1 - min(|grade - 10| / 10, 1). Very dense and very simple prose both score lower.',
},
{
id: 'structuralVariety',
name: 'Structure',
weight: 0.15,
scale: 'normalized block-type entropy',
detail:
'Entropy of headings, lists, quotes, code blocks, images, and paragraphs per post, normalized by six types. It rewards posts arranged for reading, not just long paragraphs.',
},
],
},
{
id: 'activity',
name: 'Pulse',
icon: 'pulse',
vibe: 'Whether it is alive now, and whether fresh attention is arriving.',
detail:
'Weighted average of smoothed recency and new audience in the last 90 days. Recent citations are a diagnostic.',
weight: 1 / 6,
factors: [
{
id: 'freshness',
name: 'Recency',
weight: 0.64,
scale: 'exp(-days / 90)',
detail:
'Exponential decay by days since the latest valid post, with a 90-day time constant. Future-dated posts are ignored.',
},
{
id: 'audienceInflow',
name: 'Audience inflow',
weight: 0.36,
scale: 'log1p(distinct new accounts / 90d)',
detail:
'Distinct accounts whose subscription or first recommendation appeared in the last 90 days. Gross surviving inflow, not net growth; self-edges are excluded.',
},
],
},
{
id: 'sourcing',
name: 'Network',
icon: 'evidence',
vibe: 'Who cites it, how widely it draws on sources, and whether it quotes the conversation.',
detail:
'Weighted average of inbound citations, source range, and embedded posts. Outbound density, ecosystem links, and source mix are diagnostics.',
weight: 1 / 6,
factors: [
{
id: 'inboundReferences',
name: 'Citations',
weight: 0.4,
scale: 'log1p(distinct ranked publications)',
detail:
"Distinct other ranked publications whose outbound links point at this publication's URL. Self-links and links from the same author are excluded; reciprocal links count.",
},
{
id: 'sourceDiversity',
name: 'Sources',
weight: 0.35,
scale: 'host entropy',
detail:
'Shannon entropy of outbound link hosts. Many distinct sources score higher than one source linked repeatedly.',
},
{
id: 'atprotoRefs',
name: 'Embeds',
weight: 0.25,
scale: 'at:// refs per kiloword',
detail:
'Bluesky post references, quote embeds, and at:// links inside the post body, per kiloword. These are links a plain URL scan misses; the percentile rank handles the tail.',
},
],
},
],
}
const READABILITY_TARGET = 10
function recency(lastPublishedAt, now) {
const last = Date.parse(lastPublishedAt ?? '')
if (Number.isNaN(last)) return 0
const days = (now - last) / DAY
if (days < 0) return 0
return Math.exp(-days / 90)
}
/** Raw factor values. Percentiles are a cohort question, not an entity one. */
export function factorValues(metrics, health = metrics?.health, { now = Date.now() } = {}) {
const grade = health?.readability?.fleschKincaid
const readability = Number.isFinite(grade)
? Math.max(0, 1 - Math.min(Math.abs(grade - READABILITY_TARGET) / READABILITY_TARGET, 1))
: undefined
const gapGini = health?.cadence?.gapGini
const datedPosts = health?.cadence?.posts ?? 0
// A post count is evidence of a habit. Two posts can be a cadence-shaped
// pair; five posts establish enough history for the spacing to mean much.
const consistencyEvidence = Math.min(1, datedPosts / 5)
const zipf = health?.lexical?.zipf
return {
reach: Math.log1p(metrics.subscribers ?? 0),
recommends: Math.log1p(metrics.recommends ?? 0),
inboundReferences: Number.isFinite(metrics.inboundReferences)
? Math.log1p(metrics.inboundReferences)
: undefined,
volume: Math.log1p((metrics.wordCount ?? 0) / 1_000),
consistency: metrics.docCount ?? 0,
longevity: metrics.presence ?? 0,
depth: metrics.medianWords ?? 0,
lexicalDiversity: health?.lexical?.mtld ?? 0,
rareWords: Number.isFinite(zipf) ? 1 - Math.min(Math.max(zipf, 0), 8) / 8 : undefined,
structuralVariety: health?.structure?.structuralVariety ?? 0,
readability,
freshness: recency(metrics.lastPublishedAt, now),
audienceInflow: Number.isFinite(metrics.newAudience90)
? Math.log1p(metrics.newAudience90)
: undefined,
cadenceRegularity:
Number.isFinite(gapGini) && datedPosts > 1
? consistencyEvidence * Math.max(0, 1 - gapGini)
: 0,
sourceDiversity: health?.links?.hostEntropy ?? 0,
atprotoRefs: health?.links?.atprotoRefsPer1000Words ?? 0,
}
}
/**
* Percentile of each value within the cohort, 0-100, higher is better. Zero
* is the 0th percentile: absence earns no credit. Positive ties share the
* midpoint of their band so a row with no peers is not treated as the best
* possible.
*/
export function percentileRanks(values) {
if (values.length === 0) return []
const sorted = [...values].sort((a, b) => a - b)
return values.map((value) => {
if (value === 0) return 0
let low = 0
let high = sorted.length
while (low < high) {
const mid = (low + high) >> 1
if (sorted[mid] < value) low = mid + 1
else high = mid
}
const less = low
high = sorted.length
while (low < high) {
const mid = (low + high) >> 1
if (sorted[mid] <= value) low = mid + 1
else high = mid
}
const equal = low - less
return (100 * (less + 0.5 * equal)) / sorted.length
})
}
/** Percentiles for every factor in the tree, skipping unavailable factors. */
export function factorPercentiles(rows, tree = SCORE_TREE) {
const result = rows.map(() => ({}))
for (const category of tree.categories) {
for (const factor of category.factors) {
const values = []
for (let i = 0; i < rows.length; i++) {
const value = rows[i].factorValues?.[factor.id]
if (Number.isFinite(value)) values.push([i, value])
}
if (values.length === 0) continue
const eligible = factor.positiveCohort
? values.filter(([, value]) => value > 0)
: values
if (eligible.length === 0) continue
const percentiles = percentileRanks(eligible.map(([, value]) => value))
const byIndex = new Map(eligible.map(([index], position) => [index, percentiles[position]]))
for (const [index, value] of values) {
result[index][factor.id] = value === 0 ? 0 : byIndex.get(index)
}
}
}
return result
}
/**
* Weighted average of factor percentiles, renormalizing whatever is missing
* or zero. `weights` has the same shape as the tree's category/factor
* weights; omitted entries fall back to the tree.
*/
export function treeScore(factors, tree = SCORE_TREE, weights) {
let total = 0
let totalWeight = 0
for (const category of tree.categories) {
const categoryWeight = weights?.[category.id]?.weight ?? category.weight
if (!(categoryWeight > 0)) continue
const available = category.factors.filter((factor) => Number.isFinite(factors?.[factor.id]))
if (available.length === 0) continue
const factorWeight = available.reduce(
(sum, factor) => sum + (weights?.[category.id]?.factors?.[factor.id] ?? factor.weight),
0,
)
if (!(factorWeight > 0)) continue
const score = available.reduce((sum, factor) => {
const weight = weights?.[category.id]?.factors?.[factor.id] ?? factor.weight
return sum + (weight / factorWeight) * factors[factor.id]
}, 0)
total += categoryWeight * score
totalWeight += categoryWeight
}
return totalWeight > 0 ? total / totalWeight : 0
}
/** The default score is the tree score; warnings cost five points each. */
export function scoreWithWarnings(factors, spam = { reasons: [] }, tree = SCORE_TREE) {
return Math.max(0, treeScore(factors, tree) - (spam.reasons?.length ?? 0) * 5)
}
export function normalizeTag(value) {
if (typeof value !== 'string') return null
const tag = value.normalize('NFKC').trim().toLowerCase().replace(/^#+/, '').replace(/\s+/gu, ' ')
if (tag.length < 2 || tag.length > 60) return null
return tag
}
export function roundTo(value, places = 2) {
return Number.isFinite(value) ? Number(value.toFixed(places)) : 0
}
/**
* How a raw factor turns into the 0..1 value a single entity can report.
* `clamp` means the raw value is already on that scale; `divide` means raw is
* capped at `cap` and is divided by it; `none` means the factor has no absolute
* upper bound and needs a cohort or an outside reference.
*/
export const FACTOR_BOUNDS = {
reach: { bound: 'none' },
recommends: { bound: 'none' },
inboundReferences: { bound: 'none' },
volume: { bound: 'none' },
consistency: { bound: 'divide', cap: 20 },
longevity: { bound: 'clamp' },
depth: { bound: 'divide', cap: 800 },
lexicalDiversity: { bound: 'none' },
rareWords: { bound: 'clamp' },
structuralVariety: { bound: 'clamp' },
readability: { bound: 'clamp', cap: 10 },
freshness: { bound: 'clamp' },
audienceInflow: { bound: 'none' },
cadenceRegularity: { bound: 'clamp' },
sourceDiversity: { bound: 'none' },
atprotoRefs: { bound: 'divide', cap: 2 },
}
function clamp01(value) {
return Math.min(1, Math.max(0, value))
}
/** The category and factor weights, without descriptions or data rows. */
export function scoreTreeWeights(tree = SCORE_TREE) {
return tree.categories.map((category) => ({
id: category.id,
weight: category.weight,
factors: category.factors.map((factor) => {
const bounds = FACTOR_BOUNDS[factor.id]
return {
id: factor.id,
weight: factor.weight,
displayCap: bounds?.cap ?? null,
bound: bounds?.bound ?? 'none',
}
}),
}))
}
/**
* The tree as a stable JSON document for ports. Throws rather than emitting a
* factor with no declared bound, so a new factor cannot silently skip the
* single-entity mapping.
*/
export function scoreTreeDocument(tree = SCORE_TREE) {
const missing = []
const categories = tree.categories.map((category) => ({
id: category.id,
name: category.name,
icon: category.icon,
weight: category.weight,
vibe: category.vibe,
detail: category.detail,
factors: category.factors.map((factor) => {
const bounds = FACTOR_BOUNDS[factor.id]
if (!bounds) missing.push(factor.id)
return {
id: factor.id,
name: factor.name,
weight: factor.weight,
scale: factor.scale,
displayCap: bounds?.cap ?? null,
bound: bounds?.bound ?? 'none',
positiveCohort: factor.positiveCohort === true,
detail: factor.detail,
}
}),
}))
if (missing.length > 0) {
throw new Error(`score tree factors missing bounds: ${missing.join(', ')}`)
}
return {
schema: 1,
version: SCORE_VERSION,
composite:
'weighted average of category scores; each category is a weighted average of its factor percentiles',
categories,
}
}
/** Apply FACTOR_BOUNDS to raw factor values, leaving unbounded factors null. */
export function boundedFactorValues(raw, tree = SCORE_TREE) {
const bounded = {}
for (const category of tree.categories) {
for (const factor of category.factors) {
const value = raw[factor.id]
if (!Number.isFinite(value)) {
bounded[factor.id] = null
continue
}
const bounds = FACTOR_BOUNDS[factor.id]
if (!bounds || bounds.bound === 'none') {
bounded[factor.id] = null
} else if (bounds.bound === 'divide') {
bounded[factor.id] = clamp01(value / bounds.cap)
} else {
bounded[factor.id] = clamp01(value)
}
}
}
return bounded
}
/**
* Score one document or thread without a cohort.
*
* This is deliberately not a ranking: percentiles and the overall tree score
* need a cohort, so both are null. `raw` holds the factor values before
* percentiles; `bounded` holds a 0..1 value where the factor has an absolute
* scale. Reach and recommends are 0 because no subscription graph is supplied.
* Recency is absolute against `now`; acceleration compares recent prose with
* the prior window.
*/
export function scoreEntity(
records,
{
now = Date.now(),
tree = SCORE_TREE,
digest = () => null,
publicationHost,
stansiteHosts,
publicationCreatedAt,
wordFrequency,
} = {},
) {
const list = Array.isArray(records) ? records : [records]
const entries = list.map((record) => analyzeDocument(record, { digest, wordFrequency }))
const hosts = stansiteHosts instanceof Set ? stansiteHosts : new Set(stansiteHosts ?? [])
const metrics = analyzeDocuments(entries, {
now,
publicationHost,
stansiteHosts: hosts,
publicationCreatedAt,
})
const values = factorValues(metrics, metrics.health, { now })
const raw = Object.fromEntries(
Object.entries(values).map(([id, value]) => [id, Number.isFinite(value) ? value : null]),
)
for (const category of tree.categories) {
for (const factor of category.factors) {
if (!(factor.id in raw)) raw[factor.id] = null
}
}
return {
metrics: {
docCount: metrics.docCount,
wordCount: metrics.wordCount,
medianWords: metrics.medianWords,
firstPublishedAt: metrics.firstPublishedAt,
lastPublishedAt: metrics.lastPublishedAt,
postsLast90: metrics.postsLast90,
health: metrics.health,
},
raw,
bounded: boundedFactorValues(raw, tree),
weights: scoreTreeWeights(tree),
cohort: {
percentiles: null,
score: null,
note: 'No cohort: factor percentiles and the overall score are undefined. Use percentileRanks over a cohort for the ranked score.',
},
notes: {
percentiles: 'Cohort-dependent and deliberately absent here.',
reach:
'No subscription or recommend graph is supplied, so reach and recommends are 0 raw; their bounded values are null.',
recency: 'Absolute: computed from publishedAt against now; no cohort is needed.',
acceleration:
'Self-relative: compares prose words in the last 90 days with the prior 90 days.',
variety:
'The non-templating ratio is degenerate for a single document; read it from a corpus.',
unbounded: tree.categories
.flatMap((category) => category.factors)
.filter((factor) => FACTOR_BOUNDS[factor.id]?.bound === 'none')
.map((factor) => factor.id),
},
}
}