1. What This System Does (The Big Picture)
Trumpxiety is a political anxiety barometer. Four times a day, it automatically harvests political news articles from multiple sources, has a judgment model read each story on its own, computes per-category anxiety scores in plain code, and exposes those scores through a REST API consumed by a frontend dashboard.
The core question the system answers is: based on what the news is saying right now, how much anxiety should a politically-aware person feel across nine distinct areas of political life?
The output is a number between 0 and 100 for each of nine categories, plus a confidence-weighted aggregate ("top-level") score. These are not counts of bad news stories. They are sentiment valence measurements — the emotional tone of coverage, not its volume.
On a normal run, no model computes a score. Models are used only for narrow, per-article questions ("how alarming is the framing of this article?", "is it about health?") and to write the explanatory text. Every number on the dashboard is computed by deterministic, unit-tested code from those per-article answers, so every score can be traced back to the articles behind it. The one exception is a fallback run: if the judgment model is unavailable or untrustworthy, that run is scored by a backup language-model engine instead (Stage Ten), and the run records which engine produced it.
2. System Architecture at a Glance
The system is organized as a Backend-for-Frontend (BFF) service. The frontend never touches the database directly. Every data request goes through this service's HTTP API.
The architecture has four runtime contexts:
The Scheduled Pipeline runs every six hours, triggered by an external scheduler (not by the HTTP server itself). It fetches articles, measures them, computes the scores, and writes the results to a relational database.
The AI News Run is a separate, independently triggered job that refreshes an informational AI News section. It never affects any score.
The HTTP Server is a read-mostly API server. It reads persisted scores from the database, applies the fallback rules for thin categories, and serves the result to the frontend in a structured JSON format.
The Database is the single source of truth. It stores every pipeline run, every snapshot, every article, every per-article measurement, every article weight, and the full scoring history.
External Scheduler (every 6 hours)
│
▼
POST /internal/pipeline/run
│
▼
Pipeline Execution
┌──────────────────────────────────────────────┐
│ 1. Fetch articles (3 providers, parallel) │
│ 2. Normalize + deduplicate │
│ 3. Top up thin categories │
│ 4. Enrich article content │
│ 5. Select up to 100 articles for scoring │
│ 6. Score: │
│ a. Collapse syndicated copies │
│ b. Judge each story (judgment model) │
│ c. Aggregate in code │
│ d. Write explanations (language model) │
│ (automatic fallback: language-model │
│ scoring engine) │
│ 7. Compute top-level score │
│ 8. Write to database │
└──────────────────────────────────────────────┘
│
▼
Relational Database (PostgreSQL)
│
▼
HTTP API (fallback rules applied) → Frontend Dashboard
3. The Nine Anxiety Categories
The system measures anxiety across exactly nine political domains. These are fixed in the schema and the scoring algorithm. Listed in the order the dashboard shows them, each has a defined scope:
Global Security covers military actions, defense posture, nuclear concerns, cyber threats, and armed conflicts.
International Affairs covers diplomatic relations, trade agreements, alliances, bilateral relations, and multilateral agreements.
Politics covers electoral dynamics, policy, legislation, partisan shifts, congressional activity, and campaigns.
Business covers economic policy, markets, corporate regulations, trade policy, labor dynamics, and inflation.
Climate covers climate policy, environmental regulation, energy transition, disasters, and emissions.
Health covers public health policy, healthcare access, pandemic response, and healthcare system impacts.
Culture covers social movements, identity discourse, media dynamics, misinformation, and social cohesion issues.
Education covers education policy, schools and universities, student rights, curriculum debates, and academic funding.
Science & Technology covers science policy, technology regulation, AI and data governance, research funding, and platform policy.
These nine categories are stored internally using snake_case identifiers (e.g., international_affairs) and exposed externally via the API using kebab-case identifiers (e.g., international-affairs).
4. The Anxiety Score: What It Actually Measures
Before diving into mechanics, it is critical to understand what the anxiety score represents — because the intuition is counterintuitive.
Anxiety reflects sentiment valence, not topic volume.
A heavily-covered positive development produces a low score. A lightly-covered credible threat produces a high score. The system is measuring emotional signal, not headline count.
The scale runs from 0 to 100 and is read in four bands, the same ones the dashboard, the share cards and the API label use (see Score Labels below):
- 0–24, Low: calm conditions; little threat framing.
- 25–49, Elevated: noticeable stress, but not a broad alarm.
- 50–74, High: significant concern across coverage.
- 75–100, Severe: intense, broad-based alarm.
Each article's own anxiety reading comes from a five-level scale (see Stage Seven), from reassuring to alarming, mapped onto 0–100. Those per-article readings are what the category scores are computed from; the four bands only label the result. Where a news provider supplies its own pre-computed sentiment (−1.0 for maximally negative to +1.0 for maximally positive), it is converted to the same scale:
anxietyScore = (1 − (sentimentScore + 1) / 2) × 100
A perfectly positive sentiment (+1.0) maps to anxiety 0, a neutral score (0.0) maps to 50, and a maximally negative sentiment (−1.0) maps to 100. Provider sentiment is a backup: it is used only when the judgment model is unsure about an article (see Stage Eight).
5. Stage One: Data Ingestion
Every pipeline run begins by fetching news articles from three complementary providers. They are queried in parallel using Promise.allSettled, so if one provider fails, the pipeline continues with the others rather than aborting.
Provider A — Aggregate Signal Provider (Free/Public)
This provider is a public global news index. It supplies article titles, URLs, outlets and timestamps, plus a pre-computed tone value where available. Tone is normalized from a −100 to +100 scale to −1.0 to +1.0 before being stored. Queries are restricted to English-language sources.
This provider returns at most 15 articles per request (a hard upstream limit) and allows roughly one request every five seconds. The system paces its requests, retries rate-limit and server errors with backoff, and uses a circuit breaker: after repeated rate-limit responses it stops calling the provider for a cooldown period. Because its servers are slow to accept connections, it gets longer connection timeouts (30 seconds) than the other providers.
Provider B — Article Breadth Provider
This provider supplies article titles, URLs, descriptions, and publication timestamps. It does not supply pre-computed sentiment. Its value is breadth and diversity — it covers a wide range of English-language news sources and provides descriptions that give the judgment model more context.
Provider C — Enrichment Provider
This provider supplies VADER sentiment scores pre-computed per article on the −1.0 to +1.0 scale, along with article body text, source names, and publication timestamps. It is queried with a structured boolean query (administration terms AND category terms), restricted to English, and sorted by date.
The Query Strategy
All three providers are queried with the same core keyword set targeting political coverage: articles mentioning the current U.S. president, the administration, and closely associated terms.
Each provider is asked for articles published within the last 6 hours, sorted by publication date, with a configurable maximum per provider (by default 50 for the breadth provider, 30 for the enrichment provider, and 15 for the aggregate signal provider). Articles older than the window are dropped even if a provider returns them, because some providers filter by whole days.
The Outlet Panel
Keyword queries return whoever published most recently, which can tilt the mix toward a few outlets. Since 17 November 2026 the pipeline also fetches a fixed panel of twelve outlets: four rated left, four center and four right by AllSides (The Guardian, The New York Times, The Washington Post and CNN; AP, Reuters, The Hill and Bloomberg; Fox News, the New York Post, the Washington Examiner and The Daily Caller). Each run asks for up to five recent articles from each, using the same keywords as the main fetch. These articles join the pool and go through the same deduplication, judgment and weighting as every other article; no outlet gets extra weight. If an outlet returns nothing or fails, the run continues without it. Because this changes which articles are scored, the index shows a one-time step around that date.
If the primary fetch returns no articles at all, the whole fetch is repeated once with a 24-hour window. Every category in such a run is marked with the stale_24h scoring tier (see Stage Twelve).
Request Budget
The pipeline avoids requests that cannot return anything new:
- Refused providers are skipped for the rest of the run. A response saying the key, plan, permissions, or quota does not allow the request (HTTP 401, 402, 403 or 429) marks that provider unavailable for every later request in the same run. The next run tries again, so a fixed key recovers automatically.
- Identical requests are made once per run. Responses are cached by request, so two windows that resolve to the same upstream query share one response.
Failure Handling
If a provider fails (network timeout, rate limit, API error), the pipeline logs the failure and continues with whatever articles the other providers returned. Every fetch — successful or not — is recorded in the database with its query, article count, timing, and error message. The run fails only if no articles are available at all.
6. Stage Two: Normalization
Every provider returns articles in a different shape. Before any further processing, all articles are converted into a common internal format called NormalizedArticle. This format contains:
- A content fingerprint: A SHA-256 hash of the article's title, source name, and publication hour (not minute — the hour-level granularity lets the same story published at slightly different times across providers share a fingerprint).
- Title and description: The description is stripped of HTML and truncated to 300 characters.
- URL: Used for deduplication and as a reference link in the API output.
- Source name: The news outlet name.
- Publication date: Normalized to UTC.
- Sentiment score: A float between −1.0 and +1.0 if pre-computed by the provider, otherwise
null. - Sentiment source: Which provider computed the sentiment, or
null. - Political lean: The outlet's lean (left, center, right), or unknown (see below).
- Article content: A structured content object (see Stage Five).
Articles that lack a title or URL are discarded. Articles whose titles contain foreign-language indicators (non-Latin scripts, foreign stopwords) are discarded to keep the corpus English-language only.
Outlet Lean
An outlet's lean comes from a built-in table matched on outlet name and web address. Leans follow the AllSides Media Bias Ratings: Left and Lean Left map to left, Center to center, Lean Right and Right to right. An outlet without a published rating stays unknown rather than being guessed, and international and state-owned outlets are deliberately left unlabeled, because a U.S. left–right axis does not describe them. Lean is never shown to the judgment model; it is used only for the disagreement flag and the source balance metrics. The source balance is published only when it can be trusted: at least five outlets must be rated and at least half of the contributing outlets must have a rating. Below that, the lean bar is hidden rather than showing a chart that mostly reports outlets we have not rated.
7. Stage Three: Deduplication
After normalization, all articles from all providers are merged into a single pool and deduplicated in two passes.
Pass One — URL Deduplication: Articles sharing the same URL (case-insensitive, query parameters stripped) are collapsed into one. When two articles share a URL, the one with richer metadata is kept. Richness is ranked in this order: extracted full text > long summary > sentiment score and description > description only > title and URL only.
Pass Two — Fingerprint Deduplication: Articles sharing the same content fingerprint (same title + source + hour of publication) are collapsed using the same ranking. This catches the same story published on slightly different URLs.
The result is a single list of unique articles, sorted by publication date descending.
8. Stage Four: Topping Up Thin Categories
After the primary fetch, the system estimates how many articles it has for each of the nine categories by scanning titles and descriptions for category keywords. If a category falls below its minimum, a targeted top-up fetch is made for that category.
| Category | Minimum articles |
|---|
| Politics | 5 |
| International Affairs | 5 |
| Global Security | 4 |
| Business | 4 |
| Culture | 3 |
| Health | 3 |
| Climate | 2 |
| Education | 2 |
| Science & Technology | 2 |
A top-up query combines the administration terms with category terms. For example, a thin Health category triggers a query like: (trump OR "donald trump" OR "trump administration" OR ...) AND ("RFK Jr" OR HHS OR FDA OR Medicaid OR Medicare OR vaccine OR ...).
Providers are tried in order: the enrichment provider first, then the breadth provider. The next provider is asked only when the previous one failed, refused, or added no new article. The aggregate signal provider is not used for top-ups, because a run can need up to 18 top-up requests and it allows only one request every five seconds.
If the 6-hour top-up still leaves the category thin, the system retries with a 24-hour window. A category that gains articles this way is marked with the stale_24h scoring tier, which lowers its confidence.
Top-up results are deduplicated against the existing pool and appended.
9. Stage Five: Article Content Enrichment
After the pool is assembled, the system tries to fetch the text of up to 40 articles by visiting their source URLs, with at most 5 fetches at a time and a 5-second timeout per article.
This stage is purely additive and never fails the pipeline. If an article's URL times out, returns a non-200 response, or returns non-HTML content, the article keeps whatever content the provider already supplied.
Security note: Before fetching any URL, the system checks whether the target resolves to a private, loopback, or link-local address, and skips it if so. This prevents server-side request forgery (SSRF), where a malicious article URL could make the server call internal infrastructure.
When a page is retrieved, the system removes scripts, styles, and HTML tags and produces a structured ArticleContent object of one of two types:
`extracted_article`: Enough article text (500+ characters) was retrieved. It is stored as up to 12 paragraphs of at most 1,200 characters each.
`long_summary`: The text was unavailable or too short, so a short summary is assembled from the outlet, title, and description.
If neither is possible, articleContent is null. This content is stored as evidence for human review and is what the frontend shows in article modals.
10. Stage Six: Selecting Articles for Scoring
At most 100 articles are scored per run. When there are more, the richest are kept (extracted text first, then long summaries, then articles with sentiment and a description, then description only), with newer articles winning ties.
11. Stage Seven: Scoring — Per-Article Judgments
Scoring is done by the judgment engine: a structured-decision model answers narrow questions about one article at a time and returns calibrated probabilities rather than free text. Plain code then turns those answers into scores (Stage Eight).
Collapsing Syndicated Copies
Before judging, copies of the same story are collapsed into one. Two headlines are treated as the same story only when, after removing any outlet-name suffix and common stopwords, every word of the shorter headline (at least six words) appears in the other, and the two were published within 24 hours of each other. This rule is deliberately strict: a looser similarity measure cannot tell "signs an order cutting funding for cities" from "...for universities", and merging two distinct stories does more harm than missing a duplicate.
The richest copy is judged and counted once. Every other outlet that ran the story still counts as an outlet for agreement and for the left-vs-right comparison, carrying the story's reading.
The Eleven Questions
Each story is sent in one request with eleven questions:
| Question | Answer type | Meaning |
|---|
| Anxiety | Five-level score | How much fear, threat, or alarm is in the framing |
| Relevance × 9 | Yes/no probability, one per category | Is the article's main subject, or a major consequence it reports, about this category? |
| Opinion | Yes/no probability | Is this opinion or commentary rather than news reporting? |
The anxiety levels run from Reassuring or positive through Mostly calm, Mixed or uncertain, and Elevated concern to Alarming: crisis, existential-threat or fear framing. The model returns a probability-weighted position on this scale, mapped to 0–100 as level / 4 × 100, together with its confidence.
The model sees only the article's title and description. The outlet name is deliberately not sent, so the left-vs-right comparison reflects how a story is written, not the model's assumptions about the publisher.
Category relevance is asked as nine independent yes/no questions rather than one multiple-choice question, because multiple-choice answers from this kind of model lean toward the first option listed.
Up to 10% of stories may fail to be judged; they are left out of the aggregate and reported. Beyond that, the whole run switches to the fallback engine (Stage Ten).
12. Stage Eight: Deterministic Aggregation
Everything in this stage is plain, unit-tested code. The same judgments always produce the same snapshot.
Article Weights
An article counts toward a category when its relevance probability is at least 0.50, keeping at most the four most relevant categories. The weights are normalized to sum to 1; any weight below 0.10 is dropped and the rest renormalized. An article that reaches 0.50 in no category is off-topic (for example, a news-roundup digest) and is excluded from every score rather than being forced into one.
Article Anxiety and Certainty
- The article's anxiety is the judgment model's reading — unless the model's confidence is below 0.30 and the provider supplied a sentiment score, in which case the provider's sentiment (converted as in Section 4) is used instead.
- A certainty weight
q is the model's confidence, kept between 0.2 and 1. - An opinion factor
f can reduce the weight of opinion pieces. It is currently set so that opinion pieces count exactly like news reporting.
Category Score
score = Σ(w · q · f · d · anxiety) / Σ(w · q · f · d)
The sum runs over every article with a weight w > 0 in the category. d = 1 / √n, where n is how many articles the same outlet has in that category, so one outlet publishing many pieces cannot dominate. A category with no articles scores 0 with confidence 0, so it cannot move the top-level score (and the fallback rules in Stage Twelve take over).
Confidence
Confidence (0.0–1.0) is the lower of two factors: min(agreementFactor, coverageFactor).
Coverage — how many articles contributed:
| Articles in category | 1 | 2 | 3 | 7 | 8 | 14 | 15+ |
|---|
| Coverage factor | 0.20 | 0.35 | 0.45 | 0.65 | 0.70 | 0.95 | 1.00 |
Agreement — the share of outlets on the majority side of the neutral line (an outlet's anxiety is the weighted mean of its articles, and it counts as anxious at 50 or above):
| Majority share | 0.5 | 0.6 | 0.8 | 1.0 |
|---|
| Agreement factor | 0.45 | 0.60 | 0.80 | 1.00 |
Values between the listed points are interpolated linearly. With a single outlet, agreement is 1.
Likely Range
Each fresh category score carries a likely range: the system resamples the category's stories 200 times, recomputes the score each time, and reports the 10th to 90th percentile (always widened to contain the score itself). A narrow range means the stories agree; a wide one means few or conflicting stories. It measures sampling uncertainty, not the model's accuracy, and the same inputs always give the same range. It is withheld when a category has fewer than three stories, and not shown for carried-forward or decayed scores, which are estimates built from history.
Disagreement Flags (Left vs Right)
A disagreement flag is raised when left-leaning and right-leaning outlets frame a category very differently: the mean anxiety of left outlets and of right outlets differs by 25 points or more, with at least two outlets on each side. The flag is sharp at a gap of 40 points or more. Center and unknown-lean outlets do not take part.
Each flag carries a one-line explanation, written by the language model from the most influential left and right articles (never from the numbers alone).
13. Stage Nine: Written Explanations
The judgment model cannot write prose, so a single language-model call per run writes the explanatory text: a 1–3 sentence reasoning string (at most 300 characters) for each category, a one-line explanation (at most 120 characters) for each disagreement flag, a two-to-three sentence summary of the overall mood (the "Today's read" paragraph), and, when a category has moved enough, a one-line headline.
The headline is about the story behind the biggest mover: the category whose score changed most since the previous reading, counting only categories that had fresh readings both times, were built on at least three articles, and moved at least five points. When nothing moved that much there is no headline and no "Biggest mover" line. The headline is not allowed to quote the index or a score, and it is checked for length and form before it is stored. The site describes what the coverage is about; it does not tell readers what to think of it.
The language model is given the computed evidence — the top stories in each category, a tone word for the computed score (reassuring, calm, mixed, tense, or alarming), and the most influential left and right article — but never sees or produces a number. Text is generated only for categories whose score will actually be shown. If the call fails or returns something malformed, the affected categories fall back to template text built from the same evidence (e.g., "Coverage of Health is led by …"), the summary falls back to a fixed template, there is no headline, and the run continues. Each run records whether its text was written by the model or the template, and a run that fell back entirely is reported as a warning.
14. Stage Ten: The Fallback Scoring Engine
The judgment model is an early-access service. If it cannot produce a trustworthy result — an outage, an authentication failure, a malformed response, more than 10% of stories unjudged, or no story relevant to any category — the run is automatically re-done with the language-model engine, and the reason is recorded with the run. Only if both engines fail does the run fail.
The language-model engine sends the articles to a general-purpose language model in batches of 25 and asks it to assign category weights, compute per-category scores and confidence, write the reasoning, and flag disagreement. Its output is validated strictly: malformed JSON triggers one repair attempt, and if that fails the batch is split in half and retried, down to batches of 8. Scores and confidence are clamped to their ranges, weights are normalized to sum to 1, and batch results are merged by averaging category scores weighted by each batch's article count. If the primary model is unavailable, the engine moves down a configured chain of alternative models.
Every run records which engine produced it, the model versions used, token usage, and cost, so the two can be told apart in the history.
15. Stage Eleven: The Top-Level Score
The top-level score is a confidence-weighted average of all nine category scores:
topLevelScore = Σ(category.score × category.confidence) / Σ(category.confidence)
A high-confidence category (say, 0.9) has nearly twice the influence of a low-confidence one (say, 0.5). The top-level confidence is the simple average of the nine category confidences.
Stored vs Displayed
The formula is applied at two points:
- Stored (written by the pipeline): over that run's raw category readings. A category with no coverage reads 0 at confidence 0 and drops out.
- Displayed (the dashboard headline, the top-level history chart, and the run report): over the categories after the fallback rules in Stage Twelve. A category with no coverage contributes its carried-forward estimate instead of dropping out.
Every public surface uses the displayed value, so the latest point on the history chart always equals the headline.
Score Labels
| Score Range | Label |
|---|
| 0–24 | low |
| 25–49 | elevated |
| 50–74 | high |
| 75–100 | severe |
Quiet Period Detection
A snapshot is marked a "quiet period" when five or more of the nine categories are using carried-forward, decayed, or insufficient readings rather than fresh ones. This tells users the current scores lean on historical data, and the dashboard adjusts its presentation.
16. Stage Twelve: Fallback Scoring for Thin Categories
Political news is uneven — some categories have thin coverage in any given six-hour window. Rather than showing a misleading zero, the API applies progressively weaker estimates. These rules run when scores are read, using the category's earlier readings.
A fresh reading is reliable when its confidence is at least 0.20 and its article count meets the category minimum (Stage Four). Otherwise the system looks at the category's most recent credible reading and its 30-day average.
Scoring Tiers
Every category score has a scoringTier field that says how it was derived:
`fresh`: A reliable reading from articles in the current 6-hour window. This is the ideal state.
`stale_24h`: A reliable reading that needed articles from a 24-hour window. Its confidence is reduced by 25% and capped at 0.6.
`carry_forward`: No reliable reading now, but a credible one exists from less than 48 hours ago. The score blends that reading with the 30-day average (70% recent, 30% average), at reduced confidence.
`decayed`: The last credible reading is between 48 hours and 7 days old. The score decays from it toward the 30-day average with a 24-hour half-life, and confidence decays faster, so the further back the last fresh reading, the closer the estimate gets to the average and the less it counts.
`insufficient`: No credible reading in the last 7 days. The score is the 30-day average when one exists, or a neutral baseline of 45 otherwise, at a low confidence of 0.25. The dashboard shows it with a caveat.
A category using a fallback shows the newest model-written summary from a reading that had coverage within the last 14 days, labelled with how many hours old it is, instead of a sentence about how its number was blended; that sentence stays available in the freshness note. If there is no such summary, the blending sentence is shown. The API also reports how many hours have passed since the last fresh reading. The result is always a complete nine-category snapshot, even in news deserts.
17. Stage Thirteen: Database Persistence
Everything is written in a single atomic transaction. If any write fails, the transaction rolls back and the run is marked failed. There are no partial writes.
The write order within the transaction is:
- Update the
pipeline_runs row to completed, recording article counts, timing, token usage, the scoring engine and model versions used, any fallback reason, and cost. - Insert one
score_snapshots row with the stored top-level score and confidence. - Insert nine
category_scores rows, including score, confidence, likely range, reasoning, article count, and scoring tier. - Insert zero or more
disagreement_flags rows. - Insert one
articles row per article in the scoring pool, including title, URL, outlet, description, article content, provider sentiment, political lean, and the judgment model's per-article measurements (anxiety, confidence, opinion probability). - Insert the per-article category weights, stored sparsely (only assigned categories).
- Record every provider fetch made during the run.
The score_snapshots table has a unique constraint on pipeline_run_id, preventing duplicate snapshots from retries. The articles table has a unique constraint on (pipeline_run_id, fingerprint).
Because per-article measurements are stored, any past run can be re-aggregated offline under different settings without calling the judgment model again. Only descriptions (at most 300 characters) and a bounded content excerpt per article are stored; full article pages are not.
18. Pipeline Run Lifecycle
Every pipeline execution creates a pipeline_runs record at startup with a running status. This record serves as:
- A lock: if a run is already in progress, new runs are rejected.
- A stale-run safety net: a run still marked
running after 6 minutes (the function's 5-minute limit plus a margin) is marked failed, and the next run proceeds.
The run record tracks articles fetched, articles scored, tokens used, cost, the scoring engine, and a per-stage timing breakdown.
19. Scheduling and Monitoring
The pipeline does not run on an internal timer. An external workflow scheduler, hosted separately from the application, sends a signed POST request to the internal pipeline endpoint four times a day (currently at about 05:30, 11:30, 17:30, and 23:30 UTC) and posts each run's summary to a private alert channel.
Because a scheduler that stops cannot report its own failure, a separate watchdog runs every 30 minutes from the code repository's CI system. It reads the health endpoint and raises an alert when the last completed run is more than 7 hours old (one missed run plus an hour of slack) or the health check fails. It is read-only: it never triggers a run, so it cannot double-run the pipeline.
Manual runs are always available through the same internal endpoint, protected by a timestamp-validated HMAC signature.
20. The AI News Section
The dashboard also shows a short AI News section. It is purely informational — it has no effect on any anxiety score, confidence value, category, history point, or spike.
AI News is refreshed by its own job, separate from the scoring pipeline. It fetches articles with a different keyword set (model releases, AI regulation and safety, chips, data centers), removes any article already used in the latest scoring snapshot, and asks the language model for a 1–2 sentence neutral summary and up to five ranked articles. If that call fails, it falls back to a deterministic headline digest.
21. The API Layer
The HTTP server exposes a small, read-mostly API consumed by the frontend. All public routes are GET; the internal routes are POST and require a signed request.
GET /scores/current
Returns the most recent snapshot in the frontend-facing format:
- The top-level score with its change from the previous snapshot, a qualitative label, a short summary paragraph (assembled in code from the leading stories, the most anxious categories, and the number of flags), and the quiet-period flag.
- All nine category cards, each with a score (0–100), confidence (percentage), reasoning text, disagreement display, the top-weighted article, scoring tier, article count, hours since the last fresh reading, and the likely range (
scoreRange) for fresh readings. - Coverage and source balance metrics for the snapshot and for each category.
Each category's topNews is the article with the highest weight for that category, with the newest winning ties. The same article is never used as topNews for two categories.
Responses are cacheable for 5 minutes, and may be served stale for up to an hour while a fresh copy is fetched.
GET /scores/history
Returns historical points for charting. Accepts window (7d, 30d, 90d, all) and categoryId (any public category ID or top-level). With includeAll=true it returns all ten series in one response, so the frontend can switch trend lines without more requests. Every point uses the same fallback rules as the current scores, so a history point always equals the score shown for that snapshot.
A point is flagged as a spike when the score rose by 25% or more relative to the previous point, or by at least 25 points from zero.
GET /scores/:snapshotId
Returns full detail for any past snapshot, including every contributing article, its category weights, and the reasoning for each category.
GET /ai-news/current
Returns the latest AI News section and the snapshot it was based on.
GET /health
Returns database connectivity and the time of the last completed pipeline run. The watchdog uses this endpoint.
Internal endpoints
POST /internal/pipeline/run triggers a scoring run and returns its summary (per-category scores, per-provider fetch statistics and engine provenance; stage timings are logged, not returned). POST /internal/ai-news/run refreshes AI News. POST /internal/logs/export exports recent application logs. All three require a timestamped HMAC signature, bound to the request's method and path and valid within ±2 minutes.
22. Coverage and Source Balance Metrics
A key transparency feature is the coverage and source balance metadata attached to each snapshot, derived from the articles that contributed to the scores.
Coverage metrics answer: how many unique stories and outlets contributed?
storyCount: The number of distinct articles with a positive weight for this category.outletCount: The number of distinct outlets contributing to this category.trackedOutletCount: The number of distinct outlets across the whole snapshot.fetchCoveragePct: outletCount / trackedOutletCount × 100. For the top level this is always 100%.windowHours: The lookback used for the snapshot (usually 6, or 24 if expanded).
Source balance metrics answer: what is the political lean of the contributing outlets?
These are computed over distinct outlets, not article volume — an outlet that published five articles counts once. Every outlet that ran a story counts, including syndicated copies collapsed in Stage Seven. Outlets without a rating count as unknown. When fewer than five outlets are rated, or fewer than half are, all four values are withheld (see Stage Six, Outlet Lean). The four percentages (left, center, right, unknown) use largest-remainder rounding so they sum to exactly 100.
23. Observability and Logging
Every significant pipeline and API event is recorded in an app_logs table. Each record has a stable fingerprint derived from its event type, request, status, run, and message, and duplicate fingerprints are discarded, preventing log flooding from retries.
Logs are exported to an external log aggregation service every 30 minutes; exported records are marked to prevent double-sending. Pipeline runs emit structured logs at every stage with timing, article counts, token usage, engine provenance, and error details.
24. Data Retention and Reproducibility
All scoring data is append-only. Historical snapshots, articles, measurements, and weights are retained indefinitely.
Given the same per-article judgments, aggregation always produces the same scores, ranges, and flags. The judgment model itself is not perfectly deterministic — identical requests can return slightly different probabilities — so re-running the same articles reproduces scores to within small noise. The unique constraint on pipeline_run_id prevents duplicate snapshots from retries.
Article fingerprints are content-addressed: the same article fetched from several providers produces the same fingerprint, making deduplication reliable.
25. Known Limitations
- Constants are initial values. The relevance cutoff, flag gaps, opinion weight, and outlet dampening listed above were set from small samples and will be re-tuned on larger batches.
- The outlet mix is not controlled. Providers are queried with keywords, newest first, in small pages, so the articles scored are whoever published most recently, and a provider outage changes the mix. In late 2026 a provider outage left one remaining source supplying most articles, and about 60% of articles came from outlets without an AllSides rating. An optional fixed panel of rated left, center and right outlets, fetched by name, exists but is switched off until it has been checked; enabling it would change which articles are scored and so the index, and this page will say when that happens.
- Lean coverage limits the disagreement flag. A flag needs at least two rated outlets on each side, so categories dominated by unrated or international outlets rarely get one.
- Engine change in October 2026. The judgment engine replaced the language-model engine as the primary scorer on October 4, 2026. Because categories with no coverage no longer count as confident zeros, stored top-level scores run higher from that date, and per-category article counts are lower. Each run records its engine, so the change can be identified in the history.
- Gaps in history. A run that does not happen leaves a gap rather than a backfilled point.
26. Replacing Any Vendor
The system is designed so that any news provider, either model, or the database can be replaced with minimal changes:
Replacing a news provider: Write a fetcher that implements the SourceFetcher interface — a sourceName and a fetch method that takes a context (config, time, lookback hours, optional category filter) and returns NormalizedArticle[] — and register it. No other code changes are required.
Replacing the judgment model: Any model that can return calibrated answers to a scored question and yes/no questions per article can fill this role; only the judging adapter changes. Aggregation is independent of the model.
Replacing the language model: The language model is reached through an OpenAI-compatible routing gateway, so changing models is a configuration change. Prompt construction and response validation are independent of the provider.
Replacing the database: The BackendStore interface defines every database operation. A different implementation with adapted migrations requires no application changes.
Replacing the deployment platform: The application exposes a standard Node.js HTTP server and a serverless handler. The core logic is platform-agnostic.
27. End-to-End Data Flow Summary
- The external scheduler sends a signed POST to
/internal/pipeline/run. - The pipeline creates a
running record in the database. - Three provider fetches run in parallel and are normalized to
NormalizedArticle[]. - Articles are merged and deduplicated by URL, then by fingerprint.
- Thin categories are topped up, with a 24-hour retry when needed.
- Article content is fetched from source URLs (with SSRF protection and timeouts).
- Up to 100 articles are selected; syndicated copies are collapsed into stories.
- The judgment model answers eleven questions per story.
- Code computes weights, category scores, confidence, likely ranges, and left-vs-right flags.
- The language model writes the explanations from the computed evidence.
- If the judgment engine cannot produce a trustworthy result, the language-model engine scores the run instead.
- The stored top-level score is computed, and everything is written in one transaction.
- When the frontend requests
/scores/current, the server applies the fallback tiers to thin categories, recomputes the displayed top-level score, adds coverage and source balance metrics, and returns the response.
28. Key Design Principles
Measure, then compute: Models answer narrow questions about single articles. Arithmetic is done by code, not by a model, except in a recorded fallback run (Stage Ten).
Separation of concerns: The scheduler, the pipeline, the database, and the HTTP server each do one thing. The watchdog that checks the scheduler runs somewhere else.
Failure isolation: A single provider failure does not abort the pipeline. A judgment-model failure falls back to another engine. A failed explanation falls back to template text. A thin category falls back to its history. AI News cannot affect scores.
Transparency: Every score comes with a scoring tier, a confidence, and — when fresh — a likely range. Every response carries coverage and source balance metadata. Every historical snapshot is queryable with its full article evidence.
Auditability: Every run, article, per-article measurement, weight, and engine choice is persisted. Any historical score can be traced back to the articles that produced it.
This document describes the system as of the date shown above. The specific vendors, models, and API keys in use at any given time are configuration concerns and do not affect the accuracy of this document.