Something went wrong. Try again.
Browser extension: detect and subscribe to standard.site publications on ATProto substandard.blog
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570#!/usr/bin/env node// Builds the panoptiblog dataset from the standard.site corpus.//// Discovery is the relay's listReposByCollection: one page list per collection// names every repository holding one. Each repository is then read directly// from its PDS. A run is a snapshot, so edits and deletions need no event log;// the next run simply sees the current records.//// Usage: node scripts/panoptiblog/index.mjs [--out FILE] [--top N]// --out FILE write the dataset here (default scripts/panoptiblog/out/panoptiblog.json)// --top N keep the top N publications and accounts; 0 keeps all (default 0)// --concurrency N repositories read at once (default 20)// --limit-repos N stop discovery at N repositories, for a smoke run// --relay URL repository enumerator (default the public relay)// --no-cache do not read or write the DID -> PDS cache// --include-undiscoverable rank publications that set showInDiscover=false// --max-failure-rate F exit non-zero when more than F of repositories fail (default 0.1)// --now ISO evaluate recency as of this time (default now)// --pretty indent the output
import { mkdir, readFile, writeFile } from 'node:fs/promises'import { dirname, resolve } from 'node:path'import { COLLECTIONS, DEFAULT_RELAY, PUBLIC_API, blobUrl, digest, listCollection, listRepoDids, normalizeAtUri, parseAtUri, requestJson, resolveDid,} from './relay.mjs'import { READING_WPM, SCORE_TREE, SCORE_VERSION, analyzeDocument, analyzeDocuments, extractText, factorPercentiles, factorValues, median, pathMatches, percentileRanks, scoreWithWarnings, stripMarkup,} from './scoring.mjs'import { compareEcosystem, ecosystemMetrics, exclusionReason, isBulkAccount, rank, scoreEligible, spamSignals, themeOf,} from './metrics.mjs'import { detectLanguage } from './language.mjs'
const HERE = import.meta.dirnameconst DEFAULT_OUT = resolve(HERE, 'out/panoptiblog.json')const DEFAULT_CACHE = resolve(HERE, '.cache/pds.json')const CACHE_TTL = 7 * 24 * 60 * 60 * 1000const DAY = 24 * 60 * 60 * 1000/** Below this a publication is a linkblog or an empty shell, not a ranked blog. */const MINIMUM_WORDS = 1000const USAGE = `usage: node scripts/panoptiblog/index.mjs [options]
--out FILE output path (default ${DEFAULT_OUT}) --top N keep the top N publications and accounts; 0 keeps all --concurrency N repositories read at once (default 20) --limit-repos N stop discovery at N repositories, for a smoke run --relay URL repository enumerator (default ${DEFAULT_RELAY}) --no-cache do not read or write the DID -> PDS cache --include-undiscoverable rank publications that opted out of discovery --max-failure-rate F exit non-zero above this failure fraction (default 0.1) --now ISO evaluate recency as of this time --compact trim fields the public site does not render --from FILE trim an existing dataset instead of walking the network --upload upload the dataset to S3 (PANOPTIBLOG_BUCKET, PANOPTIBLOG_KEY) --all-out FILE write the full dataset alongside the trimmed one --all-upload upload the full dataset (PANOPTIBLOG_ALL_KEY) --labeler-out FILE write the accounts-only dataset the labeler reads --labeler-upload upload the accounts-only dataset (PANOPTIBLOG_LABELER_KEY) --excluded-out FILE write excluded publications with their reasons, for audit --baseline FILE compare ecosystem metrics to a baseline corpus (repeatable) --pretty indent the output --help print this`
function usage() { console.error(USAGE)}
function parseArgs(argv) { const args = { out: DEFAULT_OUT, top: 0, concurrency: 20, limitRepos: 0, relay: DEFAULT_RELAY, cache: true, includeUndiscoverable: false, maxFailureRate: 0.1, now: Date.now(), compact: false, from: undefined, upload: false, allOut: undefined, allUpload: false, labelerOut: undefined, labelerUpload: false, excludedOut: undefined, baselines: [], pretty: false, } for (let i = 0; i < argv.length; i++) { const arg = argv[i] const next = () => { const value = argv[++i] if (value === undefined) throw new Error(`${arg} needs a value`) return value } switch (arg) { case '--out': args.out = resolve(next()) break case '--top': args.top = Number(next()) break case '--concurrency': args.concurrency = Number(next()) break case '--limit-repos': args.limitRepos = Number(next()) break case '--relay': args.relay = next() break case '--no-cache': args.cache = false break case '--include-undiscoverable': args.includeUndiscoverable = true break case '--max-failure-rate': args.maxFailureRate = Number(next()) break case '--now': args.now = Date.parse(next()) if (Number.isNaN(args.now)) throw new Error('--now is not a date') break case '--compact': args.compact = true break case '--from': args.from = resolve(next()) break case '--upload': args.upload = true break case '--all-out': args.allOut = resolve(next()) break case '--all-upload': args.allUpload = true break case '--labeler-out': args.labelerOut = resolve(next()) break case '--labeler-upload': args.labelerUpload = true break case '--excluded-out': args.excludedOut = resolve(next()) break case '--baseline': args.baselines.push(resolve(next())) break case '--pretty': args.pretty = true break case '--help': case '-h': usage() process.exit(0) break default: throw new Error(`unknown argument: ${arg}`) } } for (const [name, value] of [ ['top', args.top], ['concurrency', args.concurrency], ['limit-repos', args.limitRepos], ['max-failure-rate', args.maxFailureRate], ]) { if (!Number.isFinite(value) || value < 0) throw new Error(`--${name} must be a non-negative number`) } return args}
const log = (...parts) => console.error('[panoptiblog]', ...parts)
function intersectSize(a, b) { let count = 0 for (const value of a) if (b.has(value)) count++ return count}
/** PageRank over a directed publication citation graph, for diagnostics. */function pageRank(uris, outNeighbors, damping = 0.85, iterations = 100) { const n = uris.length if (n === 0) return new Map() const rank = new Map(uris.map((uri) => [uri, 1 / n])) for (let step = 0; step < iterations; step++) { const next = new Map(uris.map((uri) => [uri, (1 - damping) / n])) let dangling = 0 for (const uri of uris) { const out = outNeighbors.get(uri) if (!out || out.size === 0) { dangling += rank.get(uri) ?? 0 continue } const share = ((rank.get(uri) ?? 0) * damping) / out.size for (const target of out) next.set(target, (next.get(target) ?? 0) + share) } const danglingShare = (damping * dangling) / n for (const uri of uris) next.set(uri, (next.get(uri) ?? 0) + danglingShare) let delta = 0 for (const uri of uris) delta += Math.abs((next.get(uri) ?? 0) - (rank.get(uri) ?? 0)) for (const [uri, value] of next) rank.set(uri, value) if (delta < 1e-10) break } return rank}
function round(value, places = 4) { return Number(value.toFixed(places))}
/** Batched author profiles for attribution only. Never used in scoring. */async function fetchAuthorProfiles(dids) { const profiles = new Map() for (let i = 0; i < dids.length; i += 25) { const params = new URLSearchParams() for (const did of dids.slice(i, i + 25)) params.append('actors', did) try { const data = await requestJson( `${PUBLIC_API}/xrpc/app.bsky.actor.getProfiles?${params.toString()}`, { timeoutMs: 20_000 }, ) for (const profile of data.profiles ?? []) { profiles.set(profile.did, { did: profile.did, handle: profile.handle, displayName: profile.displayName, avatar: profile.avatar, }) } } catch (err) { log(`author profiles batch failed: ${err.message}`) } } return profiles}
/** Compact factor vectors for full-cohort weight experiments in the page. */function cohortOf(rows) { const factorIds = SCORE_TREE.categories.flatMap((category) => category.factors.map((factor) => factor.id), ) return rows.map((row) => ({ f: factorIds.map((id) => (Number.isFinite(row.factors?.[id]) ? row.factors[id] : null)), w: row.spam?.reasons?.length ?? 0, }))}
function hostOf(url) { if (typeof url !== 'string') return undefined try { return new URL(url).hostname.toLowerCase().replace(/^www\./, '') } catch { return undefined }}
const TID_ALPHABET = '234567abcdefghijklmnopqrstuvwxyz'
/** * A publication record's creation time, from its TID rkey. The rkey is the * only creation time every publication has; the record itself does not carry * one. Non-TID rkeys are ignored, and a timestamp outside the plausible * standard.site era is a sign the rkey is not a TID at all. */function publicationCreatedAt(uri) { const rkey = typeof uri === 'string' ? uri.split('/').at(-1) : undefined if (typeof rkey !== 'string' || rkey.length !== 13) return undefined let n = 0n for (const char of rkey) { const index = TID_ALPHABET.indexOf(char) if (index < 0) return undefined n = n * 32n + BigInt(index) } const ms = Number(n >> 10n) / 1000 if (!Number.isFinite(ms) || ms < Date.parse('2023-01-01') || ms > Date.now() + 86_400_000) { return undefined } return new Date(ms).toISOString()}
async function readJson(path) { try { return JSON.parse(await readFile(path, 'utf8')) } catch { return undefined }}
/** Run `fn` over items with bounded concurrency, reporting progress. */async function mapLimit(items, limit, fn, onProgress) { let next = 0 let done = 0 const width = Math.max(1, Math.min(limit, items.length)) const workers = Array.from({ length: width }, async () => { while (true) { const index = next++ if (index >= items.length) return await fn(items[index]) done++ if (done % 250 === 0) onProgress(done, items.length) } }) await Promise.all(workers) onProgress(done, items.length)}
async function discover(args) { const repoCollections = new Map() const counts = {} for (const [kind, collection] of Object.entries(COLLECTIONS)) { let dids = 0 for await (const page of listRepoDids(collection, { relay: args.relay })) { for (const did of page) { let collections = repoCollections.get(did) if (!collections) repoCollections.set(did, (collections = new Set())) collections.add(kind) dids++ } } counts[kind] = dids log(`discovery: ${dids} repositories hold ${collection}`) } if (args.limitRepos > 0 && repoCollections.size > args.limitRepos) { // Prefer repositories holding both a publication and its documents, so a // smoke run exercises the join rather than thirty publication-only repos. const score = (collections) => (collections.has('publication') && collections.has('document') ? 2 : 0) + (collections.has('document') ? 1 : 0) const kept = [...repoCollections.entries()] .sort(([, a], [, b]) => score(b) - score(a)) .slice(0, args.limitRepos) repoCollections.clear() for (const [did, collections] of kept) repoCollections.set(did, collections) log(`smoke run: keeping ${repoCollections.size} repositories`) } return { repoCollections, counts }}
/** * A repository that cannot be read because the account is gone, or because a * record it pointed at is gone, is not the same as a walk that fell over. The * relay can name a repository a PDS no longer serves; that costs one row, not * a failed run. */function isExpectedSkip(err) { const message = err instanceof Error ? err.message : String(err) return ( /^(?:400|404)\b/.test(message) || /No PDS service|Unsupported DID method|Not a DID|Could not resolve handle/.test(message) )}
/** Resolve a DID to its PDS once per run, reusing the on-disk cache. */async function resolveRepo(args, did, cache) { const cached = cache.get(did) if (cached && args.now - cached.at <= CACHE_TTL) return cached const info = { ...(await resolveDid(did)), at: args.now } cache.set(did, info) return info}
function noteFailure(err, did, failures, skipped) { const message = err instanceof Error ? err.message : String(err) if (isExpectedSkip(err)) skipped.set(did, message) else failures.set(did, message)}
/** Progress for one phase; failures are counted by unique DID, not attempt. */function phaseProgress(label, failures, skipped, onProgress) { return (done, total) => { log(`read ${done}/${total} ${label} (${failures.size} failed, ${skipped.size} skipped)`) onProgress?.(done) }}
/** * Phase one: every publication record. Its size is bounded by the number of * publications, not documents, so it can stay in memory for the join. */async function readPublications(args, repoCollections, cache, onProgress) { const publications = new Map() const failures = new Map() const skipped = new Map() let truncated = 0 const dids = [...repoCollections.entries()] .filter(([, collections]) => collections.has('publication')) .map(([did]) => did) log(`reading ${dids.length} publication repositories`)
await mapLimit( dids, args.concurrency, async (did) => { try { const info = await resolveRepo(args, did, cache) const listed = await listCollection(info.pds, did, COLLECTIONS.publication) if (listed.truncated) truncated++ for (const record of listed.records) { if (!parseAtUri(record.uri)) continue publications.set(record.uri, { uri: record.uri, did, pds: info.pds, handle: info.handle, record: record.value ?? {}, }) } } catch (err) { noteFailure(err, did, failures, skipped) } }, phaseProgress('publication repositories', failures, skipped, onProgress), ) return { publications, failures, skipped, truncated }}
/** * Phase two: every document. A document attached to a known publication * becomes a compact entry; a loose document (`site` is an https URL) or one * whose publication is missing is counted and dropped. Dropping the loose * ones here is what keeps the corpus out of memory. */async function readDocuments( args, repoCollections, publications, cache, handleCache, wordFrequency, onProgress,) { const byPublication = new Map() const documentOwners = new Map() const failures = new Map() const skipped = new Map() let documents = 0 let loose = 0 let orphans = 0 let truncated = 0 const dids = [...repoCollections.entries()] .filter(([, collections]) => collections.has('document')) .map(([did]) => did) log(`reading ${dids.length} document repositories`)
await mapLimit( dids, args.concurrency, async (did) => { try { const info = await resolveRepo(args, did, cache) const listed = await listCollection(info.pds, did, COLLECTIONS.document) if (listed.truncated) truncated++ for (const record of listed.records) { const value = record.value ?? {} let siteUri = null try { siteUri = await normalizeAtUri(value.site, { handleCache }) } catch { // A handle that no longer resolves is a loose document. } if (!siteUri) { loose++ continue } if (!publications.has(siteUri)) { orphans++ continue } const entry = { uri: record.uri, did, siteUri, language: detectLanguage(stripMarkup(extractText(value))), ...analyzeDocument(value, { digest, wordFrequency }), } let list = byPublication.get(siteUri) if (!list) byPublication.set(siteUri, (list = [])) list.push(entry) documentOwners.set(record.uri, did) documents++ } } catch (err) { noteFailure(err, did, failures, skipped) } }, phaseProgress('document repositories', failures, skipped, onProgress), ) return { byPublication, documentOwners, documents, loose, orphans, truncated, failures, skipped, }}
/** * Phases three and four: subscriptions and recommends. Only edges pointing at * an indexed publication or document are kept; the rest point at something * this run did not index. */async function readEdges( args, repoCollections, kind, field, target, ownerOf, cache, handleCache, onProgress,) { const edges = new Map() const failures = new Map() const skipped = new Map() let truncated = 0 let selfEdges = 0 const dids = [...repoCollections.entries()] .filter(([, collections]) => collections.has(kind)) .map(([did]) => did) log(`reading ${dids.length} ${kind} repositories`)
await mapLimit( dids, args.concurrency, async (did) => { try { const info = await resolveRepo(args, did, cache) const listed = await listCollection(info.pds, did, COLLECTIONS[kind]) if (listed.truncated) truncated++ for (const record of listed.records) { let uri try { uri = await normalizeAtUri(record.value?.[field], { handleCache }) } catch { continue } if (!uri || !target.has(uri)) continue // A person following or recommending their own work is not an // audience signal. Exact-DID only; a second account is invisible. if (ownerOf(uri) === did) { selfEdges++ continue } const createdAt = typeof record.value?.createdAt === 'string' ? record.value.createdAt : publicationCreatedAt(record.uri) let linkers = edges.get(uri) if (!linkers) edges.set(uri, (linkers = new Map())) const current = linkers.get(did) if (!linkers.has(did) || (createdAt && (!current || createdAt < current))) { linkers.set(did, createdAt) } } } catch (err) { noteFailure(err, did, failures, skipped) } }, phaseProgress(`${kind} repositories`, failures, skipped, onProgress), ) return { edges, failures, skipped, truncated, selfEdges }}
/** * Put the finished dataset where CloudFront serves it. The SDK is imported * only here, so a local run does not need it installed and the tests never * touch it. Credentials come from the task role in the scheduled job and from * the usual AWS chain anywhere else. */async function uploadDataset(path, key = process.env.PANOPTIBLOG_KEY ?? 'panoptiblog/data.json') { const bucket = process.env.PANOPTIBLOG_BUCKET if (!bucket) throw new Error('PANOPTIBLOG_BUCKET is not set') const { S3Client, PutObjectCommand } = await import('@aws-sdk/client-s3') const body = await readFile(path) await new S3Client({}).send( new PutObjectCommand({ Bucket: bucket, Key: key, Body: body, ContentType: 'application/json', // Short enough that a refreshed ranking is visible within a few minutes, // long enough that the page and the extension do not re-download it on // every open. CacheControl: 'public, max-age=300', }), ) log(`uploaded s3://${bucket}/${key}`)}
/** * The public file: the ranked head of a dataset that is already built. Used * to regenerate the site's snapshot from a full run without walking the * network again. */function trimHealth(health) { if (!health) return undefined return { readability: { fleschKincaid: round(health.readability?.fleschKincaid ?? 0, 1), fleschReadingEase: round(health.readability?.fleschReadingEase ?? 0, 1), gunningFog: round(health.readability?.gunningFog ?? 0, 1), smog: round(health.readability?.smog ?? 0, 1), colemanLiau: round(health.readability?.colemanLiau ?? 0, 1), ari: round(health.readability?.ari ?? 0, 1), }, lexical: { ttr: round(health.lexical?.ttr ?? 0, 3), mtld: round(health.lexical?.mtld ?? 0, 1), hapaxRatio: round(health.lexical?.hapaxRatio ?? 0, 3), zipf: round(health.lexical?.zipf ?? 0, 2), longWordRatio: round(health.lexical?.longWordRatio ?? 0, 3), complexWordRatio: round(health.lexical?.complexWordRatio ?? 0, 3), }, links: { total: health.links?.total ?? 0, external: health.links?.external ?? 0, stansite: health.links?.stansite ?? 0, atproto: health.links?.atproto ?? 0, atprotoRefs: health.links?.atprotoRefs ?? 0, embeds: health.links?.embeds ?? 0, uniqueExternalHosts: health.links?.uniqueExternalHosts ?? 0, uniqueSourceHosts: health.links?.uniqueSourceHosts ?? 0, per1000Words: round(health.links?.per1000Words ?? 0, 2), stansitePer1000Words: round(health.links?.stansitePer1000Words ?? 0, 2), atprotoPer1000Words: round(health.links?.atprotoPer1000Words ?? 0, 2), ecosystemPer1000Words: round(health.links?.ecosystemPer1000Words ?? 0, 2), atprotoRefsPer1000Words: round(health.links?.atprotoRefsPer1000Words ?? 0, 2), }, structure: { paragraphWordsMean: Math.round(health.structure?.paragraphWordsMean ?? 0), structuralVariety: round(health.structure?.structuralVariety ?? 0, 3), }, cadence: { postsPerMonth: round(health.cadence?.postsPerMonth ?? 0, 2), medianGapDays: round(health.cadence?.medianGapDays ?? 0, 1), }, }}
/** The accounts-only file: everything the labeler needs, nothing else. */function labelerDataset(base, accounts) { return { generatedAt: base.generatedAt, accounts: accounts.map((account) => ({ did: account.did, labels: account.labels, earlyAdopter: account.earlyAdopter ?? false, bestPublicationPercentile: account.bestPublicationPercentile, publisherPercentile: account.publisherPercentile, bestRealBloggerPercentile: account.bestRealBloggerPercentile, })), }}
function trimDataset(source, args) { const publications = (source.publications ?? []) .slice(0, args.top > 0 ? args.top : undefined) .map((row) => ({ ...row })) const accounts = args.top > 0 ? (source.accounts ?? []).filter((account) => account.rank !== undefined).slice(0, args.top) : (source.accounts ?? []).map((row) => ({ ...row })) if (args.compact) { for (const row of [...publications, ...accounts]) { if (typeof row.description === 'string') row.description = row.description.slice(0, 280) row.health = trimHealth(row.health) } } return { ...source, publications, accounts }}
/** * A baseline corpus for the ecosystem comparison. Two shapes are accepted: * `{ name, periodDays, documents: [{ text, title?, publishedAt? }] }`, which is * measured with the same text metrics, or `{ name, metrics }` with * precomputed values. */async function loadBaselines(files, now) { const baselines = [] for (const file of files) { const parsed = JSON.parse(await readFile(file, 'utf8')) const name = typeof parsed.name === 'string' ? parsed.name : file.split('/').pop() if (Array.isArray(parsed.documents)) { const periodDays = Number.isFinite(parsed.periodDays) ? parsed.periodDays : 30 const entries = parsed.documents.map((doc) => analyzeDocument( { textContent: doc.text ?? doc.textContent ?? '', title: doc.title, publishedAt: doc.publishedAt, tags: doc.tags, }, { digest }, ), ) const metrics = analyzeDocuments(entries, { now, publicationHost: parsed.publicationHost }) const { hosts, ...links } = metrics.health.links baselines.push({ name, metrics: { reading: { hoursPerDay30d: round( metrics.readingMinutesLast30d / 60 / Math.max(1, periodDays), 2, ), hoursPerDay: round(metrics.readingMinutes / 60 / Math.max(1, periodDays), 2), hoursTotal: round(metrics.readingMinutes / 60, 1), postsPerDay30d: round(metrics.postsLast30 / Math.max(1, periodDays), 2), }, readability: metrics.health.readability, lexical: metrics.health.lexical, style: metrics.health.style, links: { ...links, externalPer1000Words: links.per1000Words }, }, }) } else if (parsed.metrics) { baselines.push({ name, metrics: parsed.metrics }) } else { baselines.push({ name, metrics: parsed }) } } return baselines}
async function main() { const args = parseArgs(process.argv.slice(2))
if (args.from) { const source = JSON.parse(await readFile(args.from, 'utf8')) const loadedBaselines = await loadBaselines(args.baselines, args.now) const sourceEcosystem = { ...(source.totals?.ecosystem ?? ecosystemMetrics(source.publications ?? [], { now: args.now })), } if (sourceEcosystem.reading) { sourceEcosystem.reading = { ...sourceEcosystem.reading } delete sourceEcosystem.reading.accountCount delete sourceEcosystem.reading.newAccounts30d } const sourceTopBaseline = { name: 'top 100 ranked publications', metrics: ecosystemMetrics((source.publications ?? []).slice(0, 100), { now: args.now, }), } // A compact snapshot keeps only a few health fields. Reuse the baseline // the full run computed instead of remeasuring it from those rows. const sourceBaselines = Array.isArray(sourceEcosystem?.baselines) ? sourceEcosystem.baselines : [] const baselines = loadedBaselines.length > 0 ? loadedBaselines : sourceBaselines.length > 0 ? sourceBaselines : [sourceTopBaseline] const fullSource = { ...source, method: { ...source.method, version: SCORE_VERSION, tree: SCORE_TREE }, cohort: cohortOf(source.publications ?? []), totals: { ...source.totals, ecosystem: compareEcosystem(sourceEcosystem, baselines), }, } const output = trimDataset(fullSource, args) await mkdir(dirname(args.out), { recursive: true }) await writeFile(args.out, JSON.stringify(output, null, args.pretty ? 2 : 0) + '\n', 'utf8') if (args.upload) await uploadDataset(args.out) if (args.allOut) { const full = trimDataset(fullSource, { ...args, top: 0 }) await mkdir(dirname(args.allOut), { recursive: true }) await writeFile( args.allOut, JSON.stringify(full, null, args.pretty ? 2 : 0) + '\n', 'utf8', ) if (args.allUpload) { await uploadDataset( args.allOut, process.env.PANOPTIBLOG_ALL_KEY ?? 'panoptiblog/all.json', ) } } if (args.labelerOut) { const labeler = labelerDataset(fullSource, fullSource.accounts ?? []) await mkdir(dirname(args.labelerOut), { recursive: true }) await writeFile( args.labelerOut, JSON.stringify(labeler, null, args.pretty ? 2 : 0) + '\n', 'utf8', ) if (args.labelerUpload) { await uploadDataset( args.labelerOut, process.env.PANOPTIBLOG_LABELER_KEY ?? 'panoptiblog/accounts.json', ) } } log( `wrote ${args.out}: ${output.publications.length} publications, ` + `${output.totals.authors} authors (trimmed from ${args.from})`, ) return }
const cache = new Map() if (args.cache) { const stored = await readJson(DEFAULT_CACHE) if (stored && typeof stored === 'object') { for (const [did, info] of Object.entries(stored)) { if (info && typeof info.pds === 'string') cache.set(did, info) } log(`loaded ${cache.size} cached PDS resolutions`) } }
// A resolution is worth keeping even if the walk later fails; a first run // that times out at repository 3,000 should not pay for those lookups again. let cacheWrite = Promise.resolve() const persistCache = () => { if (!args.cache) return const snapshot = JSON.stringify(Object.fromEntries(cache)) cacheWrite = cacheWrite.then(async () => { await mkdir(dirname(DEFAULT_CACHE), { recursive: true }) await writeFile(DEFAULT_CACHE, snapshot, 'utf8') }) }
const { repoCollections, counts } = await discover(args) const handleCache = new Map() const onProgress = (done) => { if (done % 1_000 === 0) persistCache() }
const wordFrequency = Object.assign( {}, ...(await Promise.all( [1, 2].map(async (part) => JSON.parse( await readFile(new URL(`./word-zipf-en-${part}.json`, import.meta.url), 'utf8'), ), ), )), ) const publicationPhase = await readPublications(args, repoCollections, cache, onProgress) const documentPhase = await readDocuments( args, repoCollections, publicationPhase.publications, cache, handleCache, wordFrequency, onProgress, ) const subscriptionPhase = await readEdges( args, repoCollections, 'subscription', 'publication', publicationPhase.publications, (uri) => publicationPhase.publications.get(uri)?.did, cache, handleCache, onProgress, ) const recommendPhase = await readEdges( args, repoCollections, 'recommend', 'document', documentPhase.documentOwners, (uri) => documentPhase.documentOwners.get(uri), cache, handleCache, onProgress, ) persistCache() await cacheWrite
const publications = publicationPhase.publications const { byPublication, documents, loose, orphans } = documentPhase const subscribers = subscriptionPhase.edges const recommenders = recommendPhase.edges const selfEdges = subscriptionPhase.selfEdges + recommendPhase.selfEdges const failures = new Map([ ...publicationPhase.failures, ...documentPhase.failures, ...subscriptionPhase.failures, ...recommendPhase.failures, ]) const skipped = new Map([ ...publicationPhase.skipped, ...documentPhase.skipped, ...subscriptionPhase.skipped, ...recommendPhase.skipped, ]) const truncatedRepositories = publicationPhase.truncated + documentPhase.truncated + subscriptionPhase.truncated + recommendPhase.truncated
// Every publication's URL, so a link to one counts as an ecosystem link // rather than a generic external source. Match host and path, not host // alone: shared hosts carry many publications and non-publication pages. const stansiteTargets = new Map() for (const publication of publications.values()) { const raw = publication.record?.url if (typeof raw !== 'string') continue try { const url = new URL(raw) if (url.protocol !== 'http:' && url.protocol !== 'https:') continue const host = url.hostname.toLowerCase().replace(/^www\./, '') const path = url.pathname.replace(/\/+$/u, '') const paths = stansiteTargets.get(host) ?? [] paths.push(path) stansiteTargets.set(host, paths) } catch { // A malformed publication URL cannot classify a link. } }
const publicationRows = [] for (const publication of publications.values()) { const docs = byPublication.get(publication.uri) ?? [] const record = publication.record const createdAt = publicationCreatedAt(publication.uri) const metrics = analyzeDocuments(docs, { now: args.now, publicationHost: hostOf(record?.url), stansiteTargets, publicationCreatedAt: createdAt, }) const subscriberEdges = subscribers.get(publication.uri) ?? new Map() metrics.subscribers = subscriberEdges.size // Distinct recommenders across the publication's posts, not the sum of // each post's recommenders: one person recommending three posts is one // endorsement of the publication. const recommenderSet = new Set() const recommenderTimes = new Map() let endorsedDocuments = 0 for (const doc of docs) { const edges = recommenders.get(doc.uri) if (edges?.size) endorsedDocuments++ for (const [did, at] of edges ?? []) { recommenderSet.add(did) const current = recommenderTimes.get(did) if (!recommenderTimes.has(did) || (at && (!current || at < current))) { recommenderTimes.set(did, at) } } } metrics.recommends = recommenderSet.size const ageOf = (value) => { const at = Date.parse(value ?? '') return Number.isFinite(at) && at <= args.now ? args.now - at : undefined } const subscriberAges = [...subscriberEdges.values()].map(ageOf).filter(Number.isFinite) const recommenderAges = [...recommenderTimes.values()].map(ageOf).filter(Number.isFinite) const newSubscribers90 = subscriberAges.filter((age) => age <= 90 * DAY).length const newRecommenders90 = recommenderAges.filter((age) => age <= 90 * DAY).length const newAudience = new Set([ ...[...subscriberEdges].filter(([, at]) => { const age = ageOf(at) return Number.isFinite(age) && age <= 90 * DAY }).map(([did]) => did), ...[...recommenderTimes].filter(([, at]) => { const age = ageOf(at) return Number.isFinite(age) && age <= 90 * DAY }).map(([did]) => did), ]) metrics.newAudience90 = newAudience.size const subscriberSet = new Set(subscriberEdges.keys()) const union = new Set([...subscriberSet, ...recommenderSet]) const overlap = union.size > 0 ? intersectSize(subscriberSet, recommenderSet) / union.size : 0
const spam = spamSignals(metrics) const discoverable = record?.preferences?.showInDiscover !== false
publicationRows.push({ uri: publication.uri, did: publication.did, handle: publication.handle, createdAt, name: typeof record?.name === 'string' && record.name.trim() ? record.name : hostOf(record?.url) ?? publication.uri, url: typeof record?.url === 'string' ? record.url : undefined, language: metrics.language, description: typeof record?.description === 'string' ? record.description : undefined, icon: blobUrl(publication.pds, publication.did, record?.icon), theme: themeOf(record), docCount: metrics.docCount, wordCount: metrics.wordCount, readingMinutes: round(metrics.readingMinutes, 1), readingHours: round(metrics.readingHours, 2), readingMinutesLast24h: round(metrics.readingMinutesLast24h, 1), readingMinutesLast7d: round(metrics.readingMinutesLast7d, 1), readingMinutesLast30d: round(metrics.readingMinutesLast30d, 1), postsLast24h: metrics.postsLast24h, postsLast7d: metrics.postsLast7d, medianWords: round(metrics.medianWords, 1), meanWords: round(metrics.meanWords, 1), subscribers: metrics.subscribers, recommends: metrics.recommends, inboundReferences: 0, diagnostics: { audience: { newSubscribers90, newRecommenders90, medianSubscriberTenureDays: subscriberAges.length ? round(median(subscriberAges) / DAY, 1) : null, endorsementBreadth: metrics.docCount > 0 ? round(endorsedDocuments / metrics.docCount, 3) : 0, subscriberRecommenderOverlap: round(overlap, 3), }, citations: null, pulse: { acceleration: round(metrics.acceleration ?? 0, 3), recentWords90: metrics.recentWords90 ?? 0, priorWords90: metrics.priorWords90 ?? 0, }, bluesky: { collected: false }, }, firstPublishedAt: metrics.firstPublishedAt, lastPublishedAt: metrics.lastPublishedAt, postsLast30: metrics.postsLast30, postsLast90: metrics.postsLast90, topics: metrics.topTags.slice(0, 5).map((entry) => entry.tag), // Raw factor values are used for the cohort percentiles and dropped // before the dataset is written. factorValues: factorValues(metrics, metrics.health, { now: args.now }), factors: undefined, score: undefined, health: metrics.health, earlyAdopter: false, discoverable, spam: { excluded: spam.excluded, reasons: spam.reasons }, }) }
// The first 500 surviving publications by TID. Deleted records are absent // from the corpus, so this is the first cohort the index can still see. const datedPublications = publicationRows .filter((row) => row.createdAt) .sort((a, b) => a.createdAt.localeCompare(b.createdAt)) const earlyAdopterUris = new Set(datedPublications.slice(0, 500).map((row) => row.uri)) for (const row of publicationRows) row.earlyAdopter = earlyAdopterUris.has(row.uri) const earlyAdopterCutoff = datedPublications[499]?.createdAt
// A bulk publisher is judged across every publication it owns, because the // repetition is a property of the network, not of any one blog. const byDid = new Map() for (const row of publicationRows) { let aggregate = byDid.get(row.did) if (!aggregate) { byDid.set(row.did, (aggregate = { publicationCount: 0, docCount: 0, wordCount: 0 })) } aggregate.publicationCount++ aggregate.docCount += row.docCount aggregate.wordCount += row.wordCount } const bulkDids = new Set( [...byDid.entries()] .filter(([, aggregate]) => isBulkAccount(aggregate)) .map(([did]) => did), ) for (const row of publicationRows) { if (!bulkDids.has(row.did)) continue row.spam.excluded = true if (!row.spam.reasons.includes('bulk-account')) row.spam.reasons.push('bulk-account') }
const eligible = publicationRows.filter((row) => scoreEligible(row, MINIMUM_WORDS, args), )
// Inbound references are distinct ranked publications whose outbound links // point at this publication's URL. Match host and path prefix, not just host: // bsky.app, greengale.app and leaflet.pub host many publications. Reciprocal // links count; self-links and same-author links do not. The graph is built from eligible // publications so it cannot depend on the final rank. const targetsByHost = new Map() for (const row of eligible) { if (!row.url) continue try { const url = new URL(row.url) if (url.protocol !== 'http:' && url.protocol !== 'https:') continue const host = url.hostname.toLowerCase().replace(/^www\./, '') const path = url.pathname.replace(/\/+$/, '') const list = targetsByHost.get(host) ?? [] list.push({ row, path }) targetsByHost.set(host, list) } catch { // A malformed publication URL cannot receive path-level references. } } const inboundSources = new Map() // target URI -> Map(source URI -> { count, dates }) const outNeighbors = new Map() // source URI -> Set(target URI) for (const source of eligible) { const outgoing = new Set() for (const doc of byPublication.get(source.uri) ?? []) { const at = Date.parse(doc.publishedAt ?? '') for (const value of doc.linkUrls ?? []) { let url try { url = new URL(value) } catch { continue } if (url.protocol !== 'http:' && url.protocol !== 'https:') continue const host = url.hostname.toLowerCase().replace(/^www\./, '') const path = url.pathname.replace(/\/+$/, '') for (const target of targetsByHost.get(host) ?? []) { if (target.row === source || target.row.did === source.did) continue if (!pathMatches(target.path, path)) continue outgoing.add(target.row.uri) let bySource = inboundSources.get(target.row.uri) if (!bySource) inboundSources.set(target.row.uri, (bySource = new Map())) let edge = bySource.get(source.uri) if (!edge) bySource.set(source.uri, (edge = { count: 0, dates: new Set() })) edge.count++ if (Number.isFinite(at) && at <= args.now) edge.dates.add(at) } } } if (outgoing.size > 0) outNeighbors.set(source.uri, outgoing) } const ranks = pageRank( eligible.map((row) => row.uri), outNeighbors, ) for (const row of eligible) { const bySource = inboundSources.get(row.uri) row.inboundReferences = bySource?.size ?? 0 if (row.factorValues) { row.factorValues.inboundReferences = Math.log1p(row.inboundReferences) } const sources = [...(bySource?.keys() ?? [])] const counts = [...(bySource?.values() ?? [])].map((edge) => edge.count) const total = counts.reduce((sum, count) => sum + count, 0) const hhi = total > 0 ? counts.reduce((sum, count) => sum + (count / total) ** 2, 0) : 0 const months = new Set() let firstCitation let recentSources90 = 0 for (const edge of bySource?.values() ?? []) { let recent = false for (const at of edge.dates) { months.add(new Date(at).toISOString().slice(0, 7)) if (firstCitation === undefined || at < firstCitation) firstCitation = at if (args.now - at <= 90 * DAY) recent = true } if (recent) recentSources90++ } const reciprocal = sources.filter((source) => outNeighbors.get(row.uri)?.has(source)).length const firstMonth = firstCitation === undefined ? undefined : new Date(firstCitation) const monthSpan = firstMonth === undefined ? 0 : (new Date(args.now).getUTCFullYear() - firstMonth.getUTCFullYear()) * 12 + (new Date(args.now).getUTCMonth() - firstMonth.getUTCMonth()) + 1 const links = row.health?.links ?? {} const sourceMix = (() => { const sourcesCount = links.sources ?? 0 const social = links.social ?? 0 if (sourcesCount === 0) return 0 const share = (sourcesCount + 1) / (sourcesCount + social + 2) const breadth = sourcesCount > 1 ? (links.uniqueSourceHosts ?? 0) / sourcesCount : 0 return 0.65 * share + 0.35 * breadth })() if (row.diagnostics) { row.diagnostics.citations = { impact: round(ranks.get(row.uri) ?? 0, 8), evenness: sources.length > 1 ? round(Math.max(0, Math.min(1, (1 / hhi - 1) / (sources.length - 1))), 3) : null, reciprocalShare: row.inboundReferences > 0 ? round(reciprocal / row.inboundReferences, 3) : 0, recentSources90, citationMonths: months.size, citationPersistence: monthSpan > 0 ? round(months.size / monthSpan, 3) : 0, } row.diagnostics.network = { outboundPer1000Words: round(row.health?.links?.per1000Words ?? 0, 2), ecosystemPer1000Words: round(row.health?.links?.ecosystemPer1000Words ?? 0, 2), sourceMix: round(sourceMix, 3), } } } const inboundLinks = [...inboundSources.values()].reduce((total, bySource) => total + bySource.size, 0) log(`inbound references: ${inboundSources.size} publications, ${inboundLinks} links`)
// Percentile every factor within the ranked cohort, then compose the tree. // Raw values are kept only in memory for the calculation. const publicationFactors = factorPercentiles(eligible) eligible.forEach((row, index) => { row.factors = Object.fromEntries( Object.entries(publicationFactors[index]).map(([name, value]) => [name, round(value, 1)]), ) row.score = round(scoreWithWarnings(row.factors, row.spam), 2) })
const ranked = rank(eligible) const unranked = publicationRows.length - ranked.length
// Composite percentiles are display views of the same weighted factor // scores. The final rank still comes from the composite raw scores, so the // nonlinear percentile transform never changes the order. const compositeRaw = new Map() for (const category of SCORE_TREE.categories) { const raw = ranked.map((row) => { let total = 0 let weight = 0 for (const factor of category.factors) { const value = row.factors?.[factor.id] if (!(factor.weight > 0) || !Number.isFinite(value)) continue total += factor.weight * value weight += factor.weight } return weight > 0 ? total / weight : null }) const values = raw.filter(Number.isFinite) const percentiles = percentileRanks(values) let position = 0 ranked.forEach((row, index) => { row.composites ??= {} if (raw[index] === null) { row.composites[category.id] = { raw: null, percentile: null } } else { row.composites[category.id] = { raw: round(raw[index], 2), percentile: round(percentiles[position++], 2), } } }) } const overallPercentiles = percentileRanks(ranked.map((row) => row.score)) ranked.forEach((row, index) => { row.percentile = round(overallPercentiles[index], 2) })
for (const row of publicationRows) row.exclusion = exclusionReason(row, MINIMUM_WORDS)
if (args.excludedOut) { const excluded = publicationRows .filter((row) => row.exclusion !== 'included') .map((row) => ({ uri: row.uri, did: row.did, handle: row.handle, name: row.name, url: row.url, docCount: row.docCount, wordCount: row.wordCount, language: row.language, discoverable: row.discoverable, exclusion: row.exclusion, spam: row.spam, firstPublishedAt: row.firstPublishedAt, lastPublishedAt: row.lastPublishedAt, })) await mkdir(dirname(args.excludedOut), { recursive: true }) await writeFile( args.excludedOut, JSON.stringify({ generatedAt: new Date(args.now).toISOString(), publications: excluded }, null, 2), ) log(`wrote ${args.excludedOut}: ${excluded.length} excluded publications`) }
const belowMinimumWords = publicationRows.filter( (row) => !row.spam.excluded && row.wordCount < MINIMUM_WORDS, ).length const emptyPublications = publicationRows.filter((row) => row.docCount === 0).length const spamExcludedPublications = publicationRows.filter((row) => row.spam.excluded).length const undiscoverablePublications = publicationRows.filter((row) => !row.discoverable).length
// Each row has exactly one exclusion label, so these counts are disjoint and // add up to the publication total. Spam reasons add up to the spam count. const universe = { included: 0, excluded: { spam: 0, undiscoverable: 0, language: 0, 'no-posts': 0, 'below-minimum-words': 0, other: 0, }, spamReasons: {}, } for (const row of publicationRows) { if (row.exclusion === 'included') { universe.included++ continue } universe.excluded[row.exclusion]++ if (row.exclusion !== 'spam') continue const reason = row.spam.reasons?.[0] ?? 'bulk-account' universe.spamReasons[reason] = (universe.spamReasons[reason] ?? 0) + 1 }
// Author identity is attribution only. No author-level score, rank, or // label is computed: the publication is the scored entity. const authors = new Map() for (const row of publicationRows) { if (!authors.has(row.did)) authors.set(row.did, { did: row.did, handle: row.handle }) } const profiles = await fetchAuthorProfiles([...authors.keys()]) for (const row of publicationRows) { const profile = profiles.get(row.did) row.author = { did: row.did, handle: profile?.handle ?? row.handle, displayName: profile?.displayName, avatar: profile?.avatar, } }
const topicCounts = new Map() for (const row of ranked) { for (const doc of byPublication.get(row.uri) ?? []) { for (const tag of doc.tags) { let topic = topicCounts.get(tag) if (!topic) topicCounts.set(tag, (topic = { tag, documents: 0, words: 0, publications: new Set() })) topic.documents++ topic.words += doc.words topic.publications.add(row.uri) } } } const topics = [...topicCounts.values()] .map((topic) => ({ tag: topic.tag, documents: topic.documents, publications: topic.publications.size, words: topic.words, })) .sort((a, b) => b.documents - a.documents || a.tag.localeCompare(b.tag)) .slice(0, 100)
const loadedBaselines = await loadBaselines(args.baselines, args.now) const topBaseline = { name: 'top 100 ranked publications', metrics: ecosystemMetrics(ranked.slice(0, 100), { now: args.now }), } const ecosystem = compareEcosystem( ecosystemMetrics(publicationRows, { now: args.now }), loadedBaselines.length > 0 ? loadedBaselines : [topBaseline], )
// The host list exists only so author health can union it; the dataset // keeps the count and entropy. for (const row of publicationRows) { if (row.health?.links) delete row.health.links.hosts delete row.factorValues }
const base = { generatedAt: new Date(args.now).toISOString(), source: { relay: args.relay, collections: COLLECTIONS }, totals: { repositories: repoCollections.size, publications: publicationRows.length, rankedPublications: ranked.length, unrankedPublications: unranked, emptyPublications, spamExcludedPublications, undiscoverablePublications, belowMinimumWordsPublications: belowMinimumWords, universe, authors: authors.size, // Documents that name a publication. Loose documents point at an https // URL instead and are counted separately; they are not this index. documents, orphanDocuments: orphans, looseDocuments: loose, rankedWords: ranked.reduce((sum, row) => sum + row.wordCount, 0), rankedSubscribers: ranked.reduce((sum, row) => sum + row.subscribers, 0), rankedRecommends: ranked.reduce((sum, row) => sum + row.recommends, 0), selfEdgesExcluded: selfEdges, truncatedRepositories, failures: failures.size, skippedRepositories: skipped.size, failureRate: repoCollections.size > 0 ? round(failures.size / repoCollections.size) : 0, discovery: counts, ecosystem, }, topics, cohort: cohortOf(ranked), method: { version: SCORE_VERSION, composite: 'two-level weighted average of factor percentiles; each warning costs five points', tree: SCORE_TREE, reading: { wordsPerMinute: READING_WPM }, ecosystem: { reading: `words / ${READING_WPM} words per minute`, readability: 'median publication Flesch-Kincaid grade, weighted by post count', lexical: 'median publication MTLD, weighted by post count', links: 'external links per kiloword', baseline: 'default is the corpus against its top 100; --baseline replaces it with {name, periodDays, documents:[{text,publishedAt}]} or {name, metrics}', }, thresholds: { bloggedRecentlyDays: 30, stoppedBloggingDays: 180, newBloggerDays: 90, prolificWords: 100_000, minimumWords: MINIMUM_WORDS, earlyAdopterPubs: 500, bulkAccount: { publicationCount: 20, docCount: 5_000, wordCount: 5_000_000, }, }, earlyAdopterCutoff, filters: { included: 'ranked; passed every filter', spam: 'spam signals excluded it', undiscoverable: 'preferences.showInDiscover is false', language: 'not English; scored after language-specific normalization exists', 'no-posts': 'no documents', 'below-minimum-words': `fewer than ${MINIMUM_WORDS} words`, other: 'no filter matched', note: 'zero subscribers is not an exclusion; it is a low Audience factor', }, selfEdges: 'exact-DID self subscriptions and self recommends are excluded', health: { readability: 'Flesch-Kincaid, Flesch Reading Ease, Gunning Fog, SMOG, Coleman-Liau, ARI; median per publication', lexical: 'type-token ratio, MTLD, Yule’s K, hapax ratio, mean Zipf; median per publication', style: 'sentence length and punctuation entropy, pronoun and emoji density', structure: 'paragraph length and block-type variety', links: 'http links in text, markdown, content facets and the links field, plus at:// references and structured embeds; classified as stansite, atproto, or other', cadence: 'posts per month, median gap, gap Gini', }, diagnostics: { audience: 'new subscribers and recommenders in the last 90 days, median subscriber tenure, endorsement breadth, and subscriber-recommender overlap', citations: 'PageRank impact, source evenness, reciprocal share, recent citing sources, citation months, and citation persistence', pulse: 'posting acceleration, recent prose words, and prior-window prose words', network: 'outbound density, ecosystem link density, and source mix', bluesky: 'not collected in this release', }, spamReasons: { 'mostly-empty': 'at least half the documents have no text', 'duplicate-text': 'at least half the documents share an opening', 'templated-titles': 'at least half the titles reduce to one pattern', 'bulk-velocity': 'at least twenty documents a day and a median under a hundred words', 'bulk-volume': 'at least five thousand documents and a median under two hundred words', 'bulk-account': 'the account owns a network of publications or a bulk documentation set', }, }, failures: [...failures.entries()] .slice(0, 50) .map(([did, error]) => ({ did, error })), skipped: [...skipped.entries()] .slice(0, 20) .map(([did, error]) => ({ did, error })), }
const fullOutput = { ...base, publications: ranked, accounts: [], } const output = trimDataset(fullOutput, args)
await mkdir(dirname(args.out), { recursive: true }) await writeFile(args.out, JSON.stringify(output, null, args.pretty ? 2 : 0) + '\n', 'utf8') if (args.upload) await uploadDataset(args.out)
if (args.allOut) { const fullTrimmed = trimDataset(fullOutput, { ...args, top: 0 }) await mkdir(dirname(args.allOut), { recursive: true }) await writeFile( args.allOut, JSON.stringify(fullTrimmed, null, args.pretty ? 2 : 0) + '\n', 'utf8', ) if (args.allUpload) { await uploadDataset( args.allOut, process.env.PANOPTIBLOG_ALL_KEY ?? 'panoptiblog/all.json', ) } log( `wrote ${args.allOut}: ${fullTrimmed.publications.length} publications, ` + `${fullTrimmed.accounts.length} accounts (full)`, ) }
if (args.labelerOut) { const accounts = [] const labeler = labelerDataset(base, accounts) await mkdir(dirname(args.labelerOut), { recursive: true }) await writeFile( args.labelerOut, JSON.stringify(labeler, null, args.pretty ? 2 : 0) + '\n', 'utf8', ) if (args.labelerUpload) { await uploadDataset( args.labelerOut, process.env.PANOPTIBLOG_LABELER_KEY ?? 'panoptiblog/accounts.json', ) } log(`wrote ${args.labelerOut}: ${labeler.accounts.length} accounts (labeler)`) }
log( `wrote ${args.out}: ${output.totals.rankedPublications} ranked publications, ` + `${output.totals.authors} authors, ${output.totals.rankedWords} words, ` + `${output.totals.documents} documents, ${output.totals.failureRate} failure rate, ` + `${output.totals.skippedRepositories} skipped`, )
if (output.totals.failureRate > args.maxFailureRate) { log( `failure rate ${output.totals.failureRate} exceeds --max-failure-rate ${args.maxFailureRate}`, ) process.exitCode = 1 }}
await main()