Skip to content

160-tool MCP server for real-time global intelligence from free public APIs: markets, liquidity, prediction markets, SEC filings, conflict, military, aircraft-cohort early warning, migration and border flows, cyber, climate, news and more. Dated observation history, 29 research prompts, cited briefs, geofences, SSE dashboard. MIT, no paid API keys.

News signals: hostility timeline, situations, top stories; RSS outage markers

Phoenix Agent (mac-studio)fa3acba2f2ae
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6311734..b930211 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,75 @@
# Changelog
+## Unreleased
+
+### Added: news signals (ROADMAP Phase 29)
+- `intel_hostility_timeline`: per UTC day, GDELT DOC 2.0 coverage of a
+ country or a pair of countries (`timelinevolraw`): matching articles,
+ articles that also use threat / sanction / force / criticism terms (one
+ GDELT query per category, every term listed in `queries`), GDELT's total
+ monitored articles, and average tone (`timelinetone`, weighted by the
+ per-bucket article counts). A failed call leaves its column null for
+ every day; a day GDELT did not return is null in every column; both are
+ listed in `data_gaps`. Partial days (GDELT answered 2026-10-17 in
+ 15-minute buckets for 3 days and hourly buckets for 7) are flagged
+ `partial`, and today's unfinished UTC day is flagged `in_progress`. The
+ module spaces its own GDELT calls 5.5 s apart and retries a failed call
+ once.
+- `intel_situations`: country pairs ("between": a headline naming two or
+ more countries) and single countries ("inside": a headline naming one)
+ ranked over a recent RSS window by most covered, most hostile (headline
+ keyword heuristic, `classifier.classify_hostility`) or biggest change.
+ Change is defined in the response: current minus prior window, counted
+ only over feeds whose retained history reaches back past the prior
+ window's start; the feeds that do not are named.
+- `intel_top_stories`: story clusters in the window carried by at least
+ `min_outlets` distinct outlets, plus attention: the countries and
+ organizations whose headline mentions grew most against the prior window.
+- `intel_news_clusters` clusters gain `outlets` and `outlet_count`
+ (distinct publishers among all members; sister feeds such as BBC World
+ and BBC Mundo count once). Existing keys are unchanged.
+- CLI: `intel hostility COUNTRY [OTHER]`, `intel situations`,
+ `intel top-stories`. Nulls render as `n/a`, never 0; partial days are
+ marked `*` and today `~`.
+- Collector: `situations` and `top_stories` (57 sources).
+
+### Changed
+- Concurrent `fetch_news_feed` reads of the same feed set share one
+ request per feed. The collector starts its four news sources in one
+ gather, and each used to request every feed itself; measured live
+ 2026-10-17, a news-group cycle made 119 feed requests for 119 feeds
+ (4 of 4 sources ok, 9.8 s). Each caller still gets its own limit and
+ its own item copies, and a caller's timeout does not cancel the read
+ the others are waiting on.
+
+### Fixed
+- RSS outage read as a slow news day (ROADMAP Phase 24.5):
+ `fetch_news_feed` returned `count: 0` with no marker when every feed
+ failed. It now reports `feeds_attempted`, `feeds_ok`, `feeds_failed` and
+ `feeds_stale` on every call, and `error` / `degraded` /
+ `reason: all_feeds_failed` when no feed answered live;
+ `intel_news_clusters` and `intel_trending_keywords` pass the marker
+ through, so `intel trending` prints an error instead of an empty
+ keyword table.
+- RSS outage behind a warm cache read as healthy news: a feed whose fetch
+ failed came back as its expired cached copy (the fetcher's stale
+ fallback, which marks only dict payloads), so in a running deployment
+ an outage counted every feed as fine until the expired copies were
+ evicted (the collector evicts about hourly; a server running without
+ the collector keeps them until `intel sync`). Such feeds are now listed
+ in `feeds_stale`, never counted in `feeds_ok`, and kept out of
+ situation and attention change figures.
+ Verified live 2026-10-17: with an expired copy seeded for DW Europe
+ (its feed answers 404), the europe category reported
+ `feeds_stale: ["DW Europe"]`.
+- Cluster `sources` was always empty: the clusterer read `source_name` /
+ `source`, but RSS items name their outlet `feed_name` (measured live
+ 2026-10-17: 23 of 23 clusters had `sources: []`, which also emptied
+ `intel_world_brief` top-story sources).
+- RSS `published` times were shifted by the host's UTC offset:
+ `_parse_published` read feedparser's UTC struct with `time.mktime`
+ (local time). On a UTC-4 host every stamp was four hours in the future.
+
## 0.11.0 - 2026-10-12
Cross-border migration (MCP tools, CLI, collector and a dashboard
diff --git a/README.md b/README.md
index 77f7474..2624367 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
[![Python 3.11+](https://img.shields.io/badge/Python-3.11%2B-green)](https://python.org)
[![License](https://img.shields.io/badge/License-MIT-yellow)](LICENSE)
-Real-time global intelligence across **30+ domains** with **139 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.
+Real-time global intelligence across **30+ domains** with **142 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.
Built for AI agents that need world awareness: market conditions, geopolitical risk, military posture, aircraft-cohort early warning, refugee and migration flows, supply chain disruptions, cyber threats, and more — all queryable via the Model Context Protocol. The vector store enables natural language queries like *"military activity near Taiwan"* or *"cyber threats targeting healthcare"* across all historical data.
@@ -35,6 +35,7 @@ Built for AI agents that need world awareness: market conditions, geopolitical r
| **Maritime** | 2 | NGA navigation warnings, vessel snapshots |
| **Aviation** | 5 | FAA airport delays, domestic flight snapshot, business-jet/military cohort early warning (adsb.lol live + globe_history heatmaps) |
| **News & Media** | 3 | 119 RSS feeds (4-tier), GDELT, trending keywords |
+| **News Signals** | 3 | GDELT DOC timelines (daily volume, hostile-term volume, tone) per country or pair; RSS situations ranked by coverage, hostility or change; top stories by distinct-outlet count with attention growth |
| **Intelligence Analysis** | 8 | Signal convergence, focal points, instability index, risk scores, escalation |
| **NLP Intelligence** | 4 | Entity extraction, event classification, news clustering, keyword spikes |
| **Strategic Synthesis** | 4 | Strategic posture, world brief, fleet report, population exposure |
@@ -64,7 +65,7 @@ Built for AI agents that need world awareness: market conditions, geopolitical r
| **Tropical Cyclones** | 2 | NHC (Atlantic, E/C Pacific) + JTWC (NW Pacific, N Indian, S Hemisphere) |
| **Situation Brief** | 1 | Cited situational awareness brief over MCP: bounded server-side overview synthesized via local Ollama, with a mechanically-cited fallback |
-**Total: 139 tools** across 30+ intelligence domains.
+**Total: 142 tools** across 30+ intelligence domains.
---
@@ -129,6 +130,9 @@ intel markets # stock indices
intel earthquakes --min-mag 5.0
intel migration-surges # year-over-year displacement jumps (UNHCR)
intel migration-flows -o Sudan
+intel hostility Iran Israel --days 7 # daily hostile coverage (GDELT)
+intel situations --sort change # ranked situations (RSS)
+intel top-stories -m 4 # stories carried by 4+ outlets
intel status # cache + circuit breaker health
```
@@ -147,7 +151,7 @@ collector.py (daemon) ─┘
- **CircuitBreaker**: Per-source tracking. 3 consecutive failures trips for 5 minutes. Each RSS feed gets its own breaker.
- **Cache**: SQLite WAL-mode TTL cache. `get()` returns live data, `get_stale()` returns expired data for fallback.
- **VectorStore**: Qdrant + FastEmbed (BAAI/bge-small-en-v1.5, 384-dim). Async background worker queue for non-blocking storage. Enables semantic search across all accumulated intelligence.
-- **Collector**: Standalone daemon that fetches all 55 sources in parallel and populates the vector store. Run once or as a daemon (default: 5-minute interval). Includes the AOI change sweep, so a running daemon continuously watches every defined geofence.
+- **Collector**: Standalone daemon that fetches all 57 sources in parallel and populates the vector store. Run once or as a daemon (default: 5-minute interval). Includes the AOI change sweep, so a running daemon continuously watches every defined geofence.
- **Sources** (`sources/*.py`): 30+ modules, each exports `async def fetch_*(fetcher, **kwargs) -> dict`.
- **Analysis** (`analysis/*.py`): Cross-domain synthesis — signal aggregation, instability indexing, NLP, company enrichment, macro composite.
- **Config** (`config/*.py`): Curated datasets — 22 hotspots, 70+ bases, 40 ports, 24 pipelines, 24 nuclear facilities, 34 cables, 48 datacenters, 27 spaceports, 82 exchanges.
@@ -289,6 +293,13 @@ collector.py (daemon) ─┘
| `intel_trending_keywords` | Trending terms with spike detection |
| `intel_gdelt_search` | GDELT 2.0 global news search |
+### News Signals (3)
+| Tool | Description |
+|------|-------------|
+| `intel_hostility_timeline` | Per-day GDELT coverage of a country or a pair: article count, articles using threat / sanction / force / criticism terms (GDELT keyword match, terms listed in the response), average tone. A failed call or a day GDELT did not return is null and listed in `data_gaps`, never zero |
+| `intel_situations` | Situations between countries (headlines naming two or more) and inside a country (headlines naming one), ranked by most covered, most hostile (headline keyword heuristic) or biggest change against the prior window; the response defines each measure and names the feeds excluded from change figures |
+| `intel_top_stories` | Stories carried by at least `min_outlets` distinct outlets (sister feeds of one publisher count once), plus the countries and organizations whose headline mentions grew most |
+
### Intelligence Analysis (8)
| Tool | Description |
|------|-------------|
@@ -306,7 +317,7 @@ collector.py (daemon) ─┘
|------|-------------|
| `intel_extract_entities` | Named entity extraction (countries, leaders, orgs, CVEs, APTs) |
| `intel_classify_event` | Event classification into 14 threat categories |
-| `intel_news_clusters` | Topic clustering by Jaccard similarity |
+| `intel_news_clusters` | Topic clustering by Jaccard similarity, with each cluster's distinct-outlet count |
| `intel_keyword_spikes` | Keyword spike detection with Welford's algorithm |
### Strategic Synthesis (4)
diff --git a/ROADMAP.md b/ROADMAP.md
index 7249537..b9ee920 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -575,8 +575,8 @@ dashboard.
| 1 | Capture history and revisions | Earlier saved copies of a source, and values a later copy revised | :red_circle: |
| 1 | Collection health | Per-source expected cadence; overdue / failing / never-run per source, measured from the run log, not inferred from cache freshness. Says what it cannot prove | :red_circle: |
| 1 | Research guide over MCP | MCP resources (guide generated from the live registry and source health, measures glossary, "what this server will not do") and MCP prompts (worked research questions, each naming the tools it needs and the limit to respect). Server exposed no prompts or resources before | :red_circle: |
-| 1 | Hostility timeline | Per country pair or country, daily counts of threat / sanction / force / criticism coverage plus tone; sortable by most covered, most hostile, biggest change | :red_circle: |
-| 1 | Story breadth | News clusters carry a distinct-outlet count; a top-stories view ranks by how many outlets carry a story | :red_circle: |
+| 1 | Hostility timeline | Per country pair or country, daily counts of threat / sanction / force / criticism coverage plus tone; sortable by most covered, most hostile, biggest change | :white_check_mark: Built 2026-10-17, unreleased: `intel_hostility_timeline` (GDELT DOC 2.0 `timelinevolraw` + `timelinetone`, one call per category, failed calls and missing days null) and `intel_situations` (RSS headlines, ranked by covered / hostile / change, change defined over feeds whose history spans both windows). Measured 2026-10-17: timeline modes answer (HTTP 200, `date_resolution` `hour` for `timespan=7d` and `15m` for `3d`, explicit zero buckets, `norm` = all monitored articles), but a `timespan=7d` request returned 54 hours (2026-10-15T10Z onward), and about half of calls drew 429 even 30 s apart (later probes, 16:51 to 16:53Z, 4 of 4 drew 429, so the resolution for 14 and 30 days and coverage before 2026-10-15 are unmeasured; a live MCP run at 17:00Z got 4 of 6 columns after the retry pass). Artlist was not used for daily counts: 250 records sorted by date covered 15 minutes. Situations see only the 22-country entity table |
+| 1 | Story breadth | News clusters carry a distinct-outlet count; a top-stories view ranks by how many outlets carry a story | :white_check_mark: Built 2026-10-17, unreleased: clusters gain `outlets` / `outlet_count` (sister feeds of one publisher count once); `intel_top_stories` ranks by outlet count with an attention list (countries and organizations by mention growth). Found on the way: cluster `sources` was empty in every live cluster (key mismatch, `feed_name` vs `source_name`) and RSS times were shifted by the host UTC offset; both fixed. Concurrent RSS reads now share one request per feed (a live collector news-group cycle: 119 requests for 119 feeds) |
| 1 | Liquidity and flows | Fed balance sheet, Treasury General Account, reverse repo and net liquidity (FRED keyless CSV), money supply (US M2, euro area M1/M2/M3, never summed), ECB, ICI fund flows and ETF net issuance, FINRA margin statistics, BLS series; amounts kept separate from flows | :red_circle: |
| 1 | Kalshi + cross-venue markets | Kalshi public market data next to Polymarket; same-event comparison with an explicit match confidence; settled markets scored against pre-settlement prices (Brier) | :red_circle: |
| 1 | News vs market reaction | Companies and countries named in story clusters mapped to tickers / country indices; same-day move against a benchmark | :red_circle: |
@@ -637,7 +637,7 @@ fail-quietly bugs below were fixed in the same-day follow-up
| Naval warnings apply to all 9 waterways identically (no proximity/NAVAREA filter); `total_nearby` computed but never emitted | `sources/intelligence.py` vessel snapshot | precision | :red_circle: |
| Country/company/leader entity matching was substring-based ("usa" inside "thousand", "hamas" inside "Bahamas") | `analysis/entities.py` | false positives | :white_check_mark: Fixed in 0.5.0 (word-boundary alternations, measured faster) |
| Category keywords matched substrings ("airstrike" bumped severity via "strike"; "denied" fired "ied") | `analysis/classifier.py` | false positives | :white_check_mark: Fixed in 0.5.0 (boundary-anchored stems, per-keyword overrides) |
-| Silent-empty degradation without a marker on RSS/API failure | `sources/prediction.py` (documented as intended), `sources/maritime.py`, `sources/news.py` RSS path, `sources/fleet.py` `_safe` wrapper | silent degradation | :red_circle: |
+| Silent-empty degradation without a marker on RSS/API failure | `sources/prediction.py` (documented as intended), `sources/maritime.py`, `sources/news.py` RSS path, `sources/fleet.py` `_safe` wrapper | silent degradation | :yellow_circle: `sources/news.py` RSS path fixed 2026-10-17 (every call reports `feeds_attempted` / `feeds_ok` / `feeds_failed` / `feeds_stale`; no feed answering live is `error` + `degraded` + `reason: all_feeds_failed`, including the warm-cache case where failed feeds came back as expired copies and counted as healthy; failing-first regression tests). prediction, maritime and fleet still open. The fetcher's stale fallback marks only dict payloads, so other text and XML sources can serve expired copies unmarked |
| 33 CLI commands rendered upstream errors as healthy empty states | `cli.py` | fail-reads-as-success | :white_check_mark: Fixed in 0.6.0 (shared bail-on-error path; 43 failing-first tests) |
| Rich markup swallowed lowercase bracketed values and let remote titles inject markup | `cli.py` | output corruption | :white_check_mark: Fixed in 0.6.0 (per-site escaping; injection test) |
| Remote data inside Rich TABLE cells was not markup-escaped | `cli.py` | output corruption | :white_check_mark: Fixed in 0.6.0 (`_cell` Text-wrapping convention, 11 injection tests; error styles unified across all 53 commands) |
diff --git a/src/world_intel_mcp/analysis/classifier.py b/src/world_intel_mcp/analysis/classifier.py
index 82184d9..7d14d95 100644
--- a/src/world_intel_mcp/analysis/classifier.py
+++ b/src/world_intel_mcp/analysis/classifier.py
@@ -254,6 +254,97 @@ def classify_event(text: str) -> dict:
}
+# ---------------------------------------------------------------------------
+# Hostility categories (headline heuristic for news_signals)
+#
+# Four kinds of hostile coverage between or toward countries. English
+# keywords over a headline, boundary-anchored like the categories above.
+# A keyword heuristic: it does not parse who acts on whom, negation
+# ("rules out strikes"), quotation, or sports and weather idiom beyond the
+# patterns pinned below. Non-English headlines match only through
+# spellings they share with English ("sanctions", "missile").
+# ---------------------------------------------------------------------------
+
+HOSTILITY_CATEGORIES: dict[str, list[str]] = {
+ "threat": [
+ "threat", "warns", "warned", "ultimatum", "retaliat", "vows revenge",
+ "vow revenge",
+ ],
+ "sanction": [
+ "sanction", "embargo", "blacklist", "export control", "export ban",
+ "asset freeze", "tariff", "trade war",
+ ],
+ "force": [
+ "airstrike", "air strike", "missile", "drone strike", "drone attack",
+ "attack", "bombing", "bombard", "shelling", "invasion", "invade",
+ "troops", "clash", "artillery", "offensive", "war", "raid",
+ "military strike", "strikes on", "strike on", "strike kill",
+ "strikes kill",
+ ],
+ "criticism": [
+ "condemn", "criticis", "criticiz", "denounce", "rebuke", "slams",
+ "slammed", "accuse", "accusation", "summons ambassador",
+ "summoned ambassador", "lambast",
+ ],
+}
+
+# Narrower than the default \bkw\w* stem where the stem would fire on
+# unrelated words: "war" not inside "warns"/"warrant"/"Warsaw", and not
+# a trade, price or culture war (a trade war counts as sanction); "raid"
+# not as "raiders" (sports teams); "attack" not as "attacker" (football);
+# "troops" not "troopship"-style compounds; "offensive" not before
+# remarks, comments or posts. Other idioms ("war on drugs", a "heart
+# attack") still match: a named limit.
+_HOSTILITY_OVERRIDES: dict[str, str] = {
+ "war": r"(?<!trade )(?<!price )(?<!culture )(?<!tariff )\bwars?\b(?! of words)",
+ "trade war": r"\btrade wars?\b",
+ "offensive": (
+ r"\boffensive\b(?! (?:remarks?|comments?|language|posts?|tweets?|jokes?|content))"
+ ),
+ "raid": r"\braid(?:s|ed)?\b",
+ "attack": r"\battack(?:s|ed|ing)?\b",
+ "clash": r"\bclash(?:es|ed)?\b",
+ "troops": r"\btroops\b",
+}
+
+_HOSTILITY_PATTERNS: dict[str, list[tuple[str, re.Pattern[str]]]] = {
+ cat: [
+ (
+ kw,
+ re.compile(_HOSTILITY_OVERRIDES[kw])
+ if kw in _HOSTILITY_OVERRIDES
+ else _compile_keyword(kw),
+ )
+ for kw in kws
+ ]
+ for cat, kws in HOSTILITY_CATEGORIES.items()
+}
+
+HOSTILITY_METHOD = (
+ "English keyword heuristic over headlines (classifier.HOSTILITY_CATEGORIES): "
+ "boundary-anchored stems, no parsing of who acts on whom, negation, "
+ "quotation or idiom; a headline can count in several categories. Written "
+ "for English: a non-English headline matches only through shared "
+ "spellings (French 'sanctions', 'missile'), so non-English coverage is "
+ "undercounted."
+)
+
+
+def classify_hostility(text: str) -> dict[str, list[str]]:
+ """Hostility categories a headline matches, with the keywords that hit.
+
+ Returns {category: [matched keywords]} for matching categories only;
+ an empty dict means no hostility keyword matched.
+ """
+ text_lower = (text or "").lower()
+ out: dict[str, list[str]] = {}
+ for cat, patterns in _HOSTILITY_PATTERNS.items():
+ hits = _matched_keywords(patterns, text_lower)
+ if hits:
+ out[cat] = hits
+ return out
+
+
async def fetch_classify_event(fetcher, text: str) -> dict:
"""Classify a text event. Thin async wrapper for MCP dispatch."""
return classify_event(text)
diff --git a/src/world_intel_mcp/analysis/clustering.py b/src/world_intel_mcp/analysis/clustering.py
index 9fcd8c9..0a4a0b0 100644
--- a/src/world_intel_mcp/analysis/clustering.py
+++ b/src/world_intel_mcp/analysis/clustering.py
@@ -117,7 +117,11 @@ async def fetch_news_clusters(
threshold: Jaccard similarity threshold (0.0 - 1.0).
Returns:
- Dict with clusters[], cluster_count, total_items, singleton_count, source.
+ Dict with clusters[], cluster_count, total_items, singleton_count,
+ source. Each cluster carries ``outlet_count``: distinct publishers
+ among ALL its members (sister feeds of one publisher count once,
+ see ``news.FEED_OUTLETS``). An RSS outage is passed through as
+ ``degraded``/``reason``/``error``, never a quiet cluster-free day.
"""
from datetime import datetime, timezone
from ..sources import news
@@ -140,7 +144,14 @@ async def fetch_news_clusters(
all_tokens |= _tokenize(art.get("title", ""))
member_items.append({
"title": art.get("title", ""),
- "source": art.get("source_name", art.get("source", "")),
+ # fetch_news_feed names the outlet "feed_name"; the
+ # source_name/source fallbacks serve other article shapes.
+ "source": (
+ art.get("feed_name")
+ or art.get("source_name")
+ or art.get("source")
+ or ""
+ ),
"link": art.get("link", ""),
})
@@ -151,17 +162,22 @@ async def fetch_news_clusters(
word_freq[w] = word_freq.get(w, 0) + 1
top_kw = sorted(word_freq, key=word_freq.get, reverse=True)[:8] # type: ignore[arg-type]
+ outlets = sorted(
+ {news.outlet_for(m["source"]) for m in member_items if m["source"]}
+ )
out_clusters.append({
"headline": rep.get("title", ""),
"size": c["member_count"],
"keywords": top_kw,
"sources": list({m["source"] for m in member_items if m["source"]}),
+ "outlets": outlets,
+ "outlet_count": len(outlets),
"items": member_items[:5],
})
singletons = sum(1 for c in raw_clusters if c["member_count"] == 1)
- return {
+ result = {
"clusters": out_clusters,
"cluster_count": len(out_clusters),
"total_items": len(items),
@@ -170,3 +186,7 @@ async def fetch_news_clusters(
"source": "jaccard-clustering",
"timestamp": datetime.now(timezone.utc).isoformat(),
}
+ for key in ("feeds_ok", "feeds_failed", "feeds_stale", "error", "degraded", "reason"):
+ if key in feed_data:
+ result[key] = feed_data[key]
+ return result
diff --git a/src/world_intel_mcp/analysis/news_signals.py b/src/world_intel_mcp/analysis/news_signals.py
new file mode 100644
index 0000000..06c847e
--- /dev/null
+++ b/src/world_intel_mcp/analysis/news_signals.py
@@ -0,0 +1,863 @@
+"""News signals: hostility timeline, ranked situations, story breadth.
+
+Three views over coverage the server already reads:
+
+- ``fetch_hostility_timeline``: per UTC day, how much GDELT-indexed
+ coverage names a country (or a pair of countries), how much of it uses
+ threat / sanction / force / criticism vocabulary, and GDELT's average
+ tone. Built on the GDELT DOC 2.0 ``timelinevolraw`` and ``timelinetone``
+ modes, measured live 2026-10-17 (see ROADMAP Phase 29).
+- ``fetch_situations``: country pairs ("between") and single countries
+ ("inside") ranked over a recent window of the RSS feeds by coverage,
+ hostile coverage, or change against the preceding window.
+- ``fetch_top_stories``: story clusters carried by at least N distinct
+ outlets, plus the countries and organizations whose coverage grew most.
+
+Honesty contract: a failed fetch is a data gap, never a zero. A day GDELT
+did not return is null, not a quiet day; a feed that cannot reach back
+across the comparison window, or that came back as an expired cached
+copy, is excluded from change figures and named.
+
+Gaps / not covered:
+- Hostility categories are keyword heuristics (GDELT's own keyword match
+ for the timeline, ``classifier.classify_hostility`` over headlines for
+ situations). Neither parses who acts on whom, negation or idiom.
+- Country detection uses ``entities.extract_entities`` (the 22-country
+ TIER1 table plus leader names); countries outside it (France, Egypt,
+ Saudi Arabia, ...) are invisible to ``fetch_situations`` and to the
+ attention ranking. The hostility timeline searches any name verbatim.
+- RSS feeds keep different amounts of history; change figures use only
+ feeds whose oldest retained item predates the prior window, so a feed
+ that keeps ten items never fakes a surge, but it also never counts.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import logging
+import time
+from collections import defaultdict
+from datetime import datetime, timedelta, timezone
+from itertools import combinations
+from typing import Any
+
+from ..config.countries import TIER1_COUNTRIES
+from ..sources import news
+from .classifier import HOSTILITY_CATEGORIES, HOSTILITY_METHOD, classify_hostility
+from .clustering import _tokenize, cluster_articles
+from .entities import extract_entities
+
+logger = logging.getLogger("world-intel-mcp.analysis.news_signals")
+
+# RSS reads take everything the feeds hold; windows are applied here.
+_ALL_ITEMS = 1_000_000
+
+# A published stamp this far past "now" is a publisher clock or timezone
+# error; such items are excluded and counted, never placed in a window.
+_FUTURE_TOLERANCE = timedelta(hours=1)
+
+_SORTS = ("covered", "hostile", "change")
+
+# Window bounds. Below an hour almost nothing lands in a window; past a
+# week almost no feed keeps enough history to be comparable.
+_MIN_HOURS = 1.0
+_MAX_HOURS = 168.0
+
+
+def _clamp_hours(hours: Any) -> float:
+ return max(_MIN_HOURS, min(float(hours), _MAX_HOURS))
+
+
+def _parse_ts(value: Any) -> datetime | None:
+ if not isinstance(value, str) or not value:
+ return None
+ try:
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if dt.tzinfo is None:
+ return None
+ return dt.astimezone(timezone.utc)
+
+
+def _iso(dt: datetime) -> str:
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _country_name(iso3: str) -> str:
+ info = TIER1_COUNTRIES.get(iso3)
+ return info["name"] if info else iso3
+
+
+def _countries_of(ents: dict) -> set[str]:
+ """ISO3 codes in extracted entities, directly or through a leader."""
+ found = {c["iso3"] for c in ents["countries"]}
+ for leader in ents["leaders"]:
+ if leader.get("country") in TIER1_COUNTRIES:
+ found.add(leader["country"])
+ return found
+
+
+def _headline_countries(title: str) -> set[str]:
+ """ISO3 codes a headline names, directly or through a leader."""
+ return _countries_of(extract_entities(title)["entities"])
+
+
+class _Windows:
+ """Current and prior RSS windows, plus which feeds can be compared.
+
+ current = (now - hours, now]; prior = (now - 2*hours, now - hours].
+ A feed is *comparable* when its oldest retained item is at or before
+ the prior window's start: its history covers both windows, so a zero
+ in the prior window is a real zero for that feed.
+ """
+
+ def __init__(self, feed: dict, hours: float, now: datetime):
+ self.now = now
+ self.hours = hours
+ self.current_start = now - timedelta(hours=hours)
+ self.prior_start = now - timedelta(hours=2 * hours)
+ self.current: list[dict] = []
+ self.prior: list[dict] = []
+ self.undated = 0
+ # Per feed: a feed whose items carry no date at all (Nikkei Asia,
+ # measured 2026-10-17: 50 of 50) is absent from every window, and
+ # only this count says so.
+ self.undated_by_feed: dict[str, int] = defaultdict(int)
+ self.future_dated = 0
+ oldest: dict[str, datetime] = {}
+ seen_links: set[str] = set()
+ for item in feed.get("items", []):
+ ts = _parse_ts(item.get("published"))
+ name = item.get("feed_name") or ""
+ if ts is None:
+ self.undated += 1
+ self.undated_by_feed[name or "(unnamed feed)"] += 1
+ continue
+ if ts > now + _FUTURE_TOLERANCE:
+ self.future_dated += 1
+ continue
+ if name and (name not in oldest or ts < oldest[name]):
+ oldest[name] = ts
+ if ts <= self.prior_start:
+ continue
+ link = item.get("link") or ""
+ if link:
+ if link in seen_links:
+ continue
+ seen_links.add(link)
+ row = dict(item, _ts=ts)
+ if ts > self.current_start:
+ self.current.append(row)
+ else:
+ self.prior.append(row)
+ # A feed served from an expired cached copy is missing its newest
+ # items, so it would fake a drop: kept in the windows, never compared.
+ self.stale_feeds = sorted(feed.get("feeds_stale") or [])
+ self.comparable_feeds = {
+ name
+ for name, ts in oldest.items()
+ if ts <= self.prior_start and name not in self.stale_feeds
+ }
+ self.not_comparable_feeds = sorted(
+ set(oldest) - self.comparable_feeds - set(self.stale_feeds)
+ )
+
+ def describe(self) -> dict:
+ return {
+ "hours": self.hours,
+ "current": {"start": _iso(self.current_start), "end": _iso(self.now)},
+ "prior": {"start": _iso(self.prior_start), "end": _iso(self.current_start)},
+ }
+
+ def coverage(self, feed: dict) -> dict:
+ comparable_current = sum(
+ 1 for r in self.current if r.get("feed_name") in self.comparable_feeds
+ )
+ return {
+ "items_read": len(feed.get("items", [])),
+ "items_current_window": len(self.current),
+ # Change figures rest on this subset only; a small share means
+ # the change ranking is a thin sample.
+ "items_current_window_comparable": comparable_current,
+ "items_prior_window": len(self.prior),
+ "undated_items": self.undated,
+ "future_dated_items": self.future_dated,
+ "feeds_ok": feed.get("feeds_ok"),
+ "feeds_failed": feed.get("feeds_failed", []),
+ "feeds_comparable": len(self.comparable_feeds),
+ "feeds_not_comparable": self.not_comparable_feeds,
+ "feeds_stale": self.stale_feeds,
+ }
+
+ def gaps(self, feed: dict) -> list[str]:
+ out: list[str] = []
+ failed = feed.get("feeds_failed") or []
+ if failed:
+ out.append(
+ f"{len(failed)} RSS feeds failed or timed out and are absent: "
+ + ", ".join(failed)
+ )
+ if self.stale_feeds:
+ out.append(
+ f"{len(self.stale_feeds)} feeds failed live and were served from an "
+ "expired cache copy; their items are kept but excluded from change "
+ "figures: " + ", ".join(self.stale_feeds)
+ )
+ if self.not_comparable_feeds:
+ out.append(
+ f"{len(self.not_comparable_feeds)} feeds keep no history before "
+ f"{_iso(self.prior_start)} and are excluded from change figures: "
+ + ", ".join(self.not_comparable_feeds)
+ )
+ if self.undated:
+ by_feed = ", ".join(
+ f"{name} {n}" for name, n in sorted(self.undated_by_feed.items())
+ )
+ out.append(
+ f"{self.undated} items had no parseable publish time and were "
+ f"skipped (by feed: {by_feed})"
+ )
+ if self.future_dated:
+ out.append(
+ f"{self.future_dated} items were stamped more than 1 h in the future "
+ "and were skipped"
+ )
+ return out
+
+
+def _change_fields(current_comparable: int, prior: int) -> dict:
+ return {
+ "current_comparable": current_comparable,
+ "prior": prior,
+ "change": current_comparable - prior,
+ "change_ratio": round((current_comparable + 1) / (prior + 1), 3),
+ }
+
+
+_CHANGE_DEFINITION = (
+ "change = articles in the current window minus articles in the prior "
+ "window of equal length, both counted only over comparable feeds (feeds "
+ "whose oldest retained item is at or before the prior window's start). "
+ "change_ratio = (current_comparable + 1) / (prior + 1). 'change' sort "
+ "orders by change, then by current articles."
+)
+
+
+def _degraded_feed_response(feed: dict, base: dict) -> dict:
+ out = dict(base)
+ out.update(
+ {
+ "error": feed.get("error", "RSS feed read failed"),
+ "degraded": True,
+ "reason": feed.get("reason", "rss_unavailable"),
+ "data_gaps": [
+ "every RSS feed failed: no coverage could be read, which is "
+ "not the same as no coverage"
+ ],
+ }
+ )
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Hostility timeline (GDELT DOC 2.0 timelines)
+# ---------------------------------------------------------------------------
+
+# GDELT word forms per category. GDELT matches the words given (this
+# server has not measured any stemming), so inflections are spelled out.
+GDELT_HOSTILITY_TERMS: dict[str, list[str]] = {
+ "threat": [
+ "threat", "threats", "threaten", "threatens", "threatened", "warns",
+ "ultimatum", "retaliation", "retaliate",
+ ],
+ "sanction": [
+ "sanction", "sanctions", "sanctioned", "embargo", "blacklist",
+ "tariff", "tariffs", '"export controls"',
+ ],
+ "force": [
+ "airstrike", "airstrikes", "missile", "missiles", '"drone strike"',
+ "attack", "attacks", "attacked", "bombing", "shelling", "invasion",
+ "troops", "clashes", "artillery",
+ ],
+ "criticism": [
+ "condemns", "condemned", "condemnation", "criticizes", "criticized",
+ "criticises", "criticised", "denounces", "denounced", "rebuke",
+ "accuses", "accused",
+ ],
+}
+
+# GDELT asks for at most one request per 5 s per client (its 429 body,
+# measured 2026-10-17). The shared Fetcher has no GDELT floor, so this
+# module spaces its own live calls; cache hits are not delayed.
+_GDELT_SPACING_S = 5.5
+_GDELT_RETRY_WAIT_S = 10.0
+_gdelt_last_call = 0.0
+
+# The DOC API serves roughly the last three months.
+_MAX_DAYS = 90
+
+# GDELT ``date_resolution`` values seen live 2026-10-17: "15m" (timespan=3d)
+# and "hour" (7d). A day's completeness is judged by the hours its buckets
+# cover, not by bucket count: in 15m mode GDELT returned 79 of 96
+# quarter-hours for 2026-10-16 yet covered all 24 hours, with the same
+# daily total (732) as hourly mode. Other resolutions are unmeasured.
+_SUBDAILY_RESOLUTIONS = {"15m", "hour"}
+
+
+def _gdelt_term(name: str) -> str:
+ return f'"{name}"' if (" " in name or "-" in name) else name
+
+
+def _resolve_country(value: str) -> tuple[str, str | None]:
+ """(search name, iso3 or None) for a country given as ISO3 or name."""
+ raw = (value or "").strip()
+ if raw.upper() in TIER1_COUNTRIES:
+ iso3 = raw.upper()
+ return TIER1_COUNTRIES[iso3]["name"], iso3
+ lower = raw.lower()
+ for iso3, info in TIER1_COUNTRIES.items():
+ if lower == info["name"].lower() or lower in (k.lower() for k in info["keywords"]):
+ return info["name"], iso3
+ return raw, None
+
+
+async def _gdelt_timeline(fetcher, query: str, mode: str, days: int) -> dict | None:
+ """One GDELT timeline call, spaced from this module's previous one."""
+ global _gdelt_last_call
+ digest = hashlib.sha1(f"{mode}|{days}|{query}".encode()).hexdigest()[:16]
+ cache_key = f"news_signals:gdelt:{mode}:{days}:{digest}"
+ live_call = fetcher.cache.get(cache_key) is None and fetcher.breaker.is_available("gdelt")
+ if live_call:
+ wait = _GDELT_SPACING_S - (time.monotonic() - _gdelt_last_call)
+ if wait > 0:
+ await asyncio.sleep(wait)
+ _gdelt_last_call = time.monotonic()
+ data = await fetcher.get_json(
+ news._GDELT_DOC_URL,
+ source="gdelt",
+ cache_key=cache_key,
+ cache_ttl=1800,
+ params={"query": query, "mode": mode, "timespan": f"{days}d", "format": "json"},
+ timeout=news.GDELT_TIMEOUT,
+ )
+ if not isinstance(data, dict) or not isinstance(data.get("timeline"), list):
+ return None
+ return data
+
+
+def _series_by_day(data: dict) -> tuple[dict[str, list[dict]], str | None]:
+ """Group a timeline's first series into UTC days (YYYY-MM-DD)."""
+ resolution = (data.get("query_details") or {}).get("date_resolution")
+ days: dict[str, list[dict]] = defaultdict(list)
+ series = data["timeline"][0]["data"] if data["timeline"] else []
+ for point in series:
+ stamp = str(point.get("date", ""))
+ if len(stamp) < 8 or not isinstance(point.get("value"), (int, float)):
+ continue
+ days[f"{stamp[:4]}-{stamp[4:6]}-{stamp[6:8]}"].append(point)
+ return days, resolution
+
+
+async def fetch_hostility_timeline(
+ fetcher,
+ country: str,
+ other: str | None = None,
+ days: int = 14,
+ now: datetime | None = None,
+) -> dict:
+ """Daily coverage and hostile-coverage counts for a country or pair.
+
+ Six GDELT calls: matching-article volume, one volume per hostility
+ category (the base query AND that category's terms), and average
+ tone. A call that fails leaves its column null for every day and is
+ listed in ``data_gaps``; a day GDELT did not return is null in every
+ column. Neither is ever reported as zero.
+ """
+ now = now or datetime.now(timezone.utc)
+ days = max(1, min(int(days), _MAX_DAYS))
+ name_a, iso_a = _resolve_country(country)
+ parties = [{"input": country, "name": name_a, "iso3": iso_a}]
+ base_query = _gdelt_term(name_a)
+ if other:
+ name_b, iso_b = _resolve_country(other)
+ parties.append({"input": other, "name": name_b, "iso3": iso_b})
+ base_query = f"{base_query} {_gdelt_term(name_b)}"
+
+ queries = {"articles": base_query}
+ for cat, terms in GDELT_HOSTILITY_TERMS.items():
+ queries[cat] = f"{base_query} ({' OR '.join(terms)})"
+
+ data_gaps: list[str] = []
+ for p in parties:
+ if p["iso3"] is None:
+ data_gaps.append(
+ f"'{p['input']}' is not in the country table; searched GDELT for it verbatim"
+ )
+
+ jobs = [(col, q, "timelinevolraw") for col, q in queries.items()]
+ jobs.append(("tone", base_query, "timelinetone"))
+ fetched: dict[str, dict] = {}
+ for col, query, mode in jobs:
+ data = await _gdelt_timeline(fetcher, query, mode, days)
+ if data is not None:
+ fetched[col] = data
+ # One spaced retry for failed calls: measured 2026-10-17, about half of
+ # GDELT calls drew a 429 even 30 s apart, and most succeeded on retry.
+ for col, query, mode in jobs:
+ if col in fetched or not fetcher.breaker.is_available("gdelt"):
+ continue
+ await asyncio.sleep(_GDELT_RETRY_WAIT_S)
+ data = await _gdelt_timeline(fetcher, query, mode, days)
+ if data is not None:
+ fetched[col] = data
+
+ by_series: dict[str, dict[str, list[dict]]] = {}
+ resolution: str | None = None
+ for col, _query, mode in jobs:
+ if col not in fetched:
+ kind = "tone" if mode == "timelinetone" else "volume"
+ data_gaps.append(f"{col}: GDELT {kind} timeline fetch failed; column is null")
+ continue
+ series, res = _series_by_day(fetched[col])
+ by_series[col] = series
+ resolution = resolution or res
+ tone_days = by_series.pop("tone", None)
+
+ base_out = {
+ "parties": parties,
+ "days_requested": days,
+ "queries": dict(queries, tone=base_query),
+ "source": "gdelt-doc-2.0",
+ "timestamp": _iso(now),
+ }
+ if not by_series and tone_days is None:
+ out = dict(base_out)
+ out.update(
+ {
+ "days": [],
+ "error": "Every GDELT timeline call failed (rate limited, API error, or malformed response)",
+ "degraded": True,
+ "reason": "gdelt_fetch_failed",
+ "data_gaps": data_gaps,
+ }
+ )
+ return out
+
+ subdaily = resolution in _SUBDAILY_RESOLUTIONS
+ if not subdaily:
+ data_gaps.append(
+ f"GDELT date_resolution {resolution!r} is not one this server has measured; "
+ "partial-day detection is off"
+ )
+ today = now.date()
+ rows = []
+ missing_days: list[str] = []
+ for offset in range(days - 1, -1, -1):
+ day = (today - timedelta(days=offset)).isoformat()
+ base_points = by_series["articles"].get(day) if "articles" in by_series else None
+ # Today's UTC day has not ended: its totals are not comparable with
+ # a full day's, whatever GDELT returned for the hours so far.
+ row: dict[str, Any] = {"date": day, "in_progress": day == today.isoformat()}
+ returned = None
+ if "articles" in by_series:
+ returned = len(base_points or [])
+ row["buckets_returned"] = returned
+ if subdaily and returned is not None:
+ # partial = some elapsed hour of the day has no bucket at all
+ # (missing data). Today counts only wholly elapsed hours, so the
+ # current one may be absent: GDELT's newest bucket lags the clock.
+ hours = {
+ str(p["date"])[9:11] for p in base_points or [] if len(str(p["date"])) >= 11
+ }
+ elapsed = now.hour if row["in_progress"] else 24
+ missing_hours = sorted({f"{h:02d}" for h in range(elapsed)} - hours)
+ row["hours_covered"] = len(hours)
+ row["partial"] = bool(hours) and bool(missing_hours)
+ if row["partial"]:
+ row["hours_missing"] = missing_hours
+ if "articles" in by_series:
+ if not base_points:
+ row["articles"] = None
+ missing_days.append(day)
+ else:
+ row["articles"] = int(sum(p["value"] for p in base_points))
+ norms = [p.get("norm") for p in base_points]
+ row["all_monitored_articles"] = (
+ int(sum(norms)) if all(isinstance(n, (int, float)) for n in norms) else None
+ )
+ else:
+ row["articles"] = None
+ hostile: dict[str, int | None] = {}
+ for cat in GDELT_HOSTILITY_TERMS:
+ if cat not in by_series:
+ hostile[cat] = None
+ continue
+ # GDELT returns explicit zero buckets (measured 2026-10-17: a
+ # category series carried the base series' exact buckets,
+ # zeros included), so a day with no buckets is missing data.
+ pts = by_series[cat].get(day)
+ hostile[cat] = int(sum(p["value"] for p in pts)) if pts else None
+ row["hostile"] = hostile
+ if row["articles"]:
+ row["hostile_share"] = {
+ cat: (round(v / row["articles"], 4) if v is not None else None)
+ for cat, v in hostile.items()
+ }
+ row["tone"] = _day_tone(
+ (tone_days or {}).get(day) if tone_days is not None else None,
+ base_points,
+ )
+ rows.append(row)
+
+ if missing_days:
+ data_gaps.append(
+ f"GDELT returned no buckets for {len(missing_days)} of {days} requested days "
+ f"({missing_days[0]} .. {missing_days[-1]}); those days are null, not zero"
+ )
+
+ out = dict(base_out)
+ out.update(
+ {
+ "days": rows,
+ "date_resolution": resolution,
+ "method": (
+ "GDELT DOC 2.0 timelinevolraw: 'articles' counts articles GDELT "
+ "matched to the base query per bucket, summed to UTC days; each "
+ "hostile column counts articles matching the base query AND any of "
+ "that category's terms (GDELT_HOSTILITY_TERMS, listed in 'queries'). "
+ "This is GDELT's keyword match over the text it indexes, not a "
+ "headline classifier and not a model: it cannot tell who threatens "
+ "whom, negation, or quotation, and one article can count in several "
+ "categories. 'all_monitored_articles' is GDELT's per-bucket total "
+ "('norm'). tone is GDELT timelinetone average tone, weighted by "
+ "the day's per-bucket article counts when those are available."
+ ),
+ "definitions": {
+ "partial": (
+ "GDELT returned no bucket for at least one elapsed hour of that "
+ "UTC day (for today, only wholly elapsed hours count); "
+ "hours_covered says how many hours had one"
+ ),
+ "in_progress": (
+ "the row is today's UTC day, which has not ended; its totals "
+ "are not comparable with a full day's"
+ ),
+ "null": "not measured (call failed or day not returned), never zero",
+ },
+ "data_gaps": data_gaps,
+ }
+ )
+ if len(by_series) < len(queries) or tone_days is None:
+ out["degraded"] = True
+ out["reason"] = "gdelt_partial"
+ return out
+
+
+def _day_tone(tone_points: list[dict] | None, base_points: list[dict] | None) -> float | None:
+ if not tone_points:
+ return None
+ weights = {p["date"]: p["value"] for p in (base_points or [])}
+ if weights:
+ num = sum(p["value"] * weights.get(p["date"], 0) for p in tone_points)
+ den = sum(weights.get(p["date"], 0) for p in tone_points)
+ if den > 0:
+ return round(num / den, 4)
+ return round(sum(p["value"] for p in tone_points) / len(tone_points), 4)
+
+
+# ---------------------------------------------------------------------------
+# Situations
+# ---------------------------------------------------------------------------
+
+
+async def fetch_situations(
+ fetcher,
+ hours: float = 24,
+ sort: str = "covered",
+ kind: str = "all",
+ limit: int = 20,
+ min_articles: int = 2,
+ now: datetime | None = None,
+) -> dict:
+ """Rank situations between countries and inside a country.
+
+ A headline naming two or more countries counts toward each pair it
+ names ("between"); a headline naming exactly one counts toward that
+ country ("inside"). Hostile = the headline matches any hostility
+ category.
+ """
+ now = now or datetime.now(timezone.utc)
+ hours = _clamp_hours(hours)
+ sort = sort if sort in _SORTS else "covered"
+ kind = kind if kind in ("all", "between", "inside") else "all"
+ base = {
+ "situations": [],
+ "count": 0,
+ "sort": sort,
+ "kind": kind,
+ "source": "rss-aggregator+news-signals",
+ "timestamp": _iso(now),
+ }
+ feed = await news.fetch_news_feed(fetcher, limit=_ALL_ITEMS)
+ if feed.get("degraded") or feed.get("error"):
+ return _degraded_feed_response(feed, base)
+
+ win = _Windows(feed, hours, now)
+
+ def _blank() -> dict:
+ return {
+ "articles": 0,
+ "hostile": 0,
+ "by_category": {c: 0 for c in HOSTILITY_CATEGORIES},
+ "outlets": set(),
+ "current_comparable": 0,
+ "prior": 0,
+ "headlines": [],
+ }
+
+ acc: dict[tuple[str, tuple[str, ...]], dict] = defaultdict(_blank)
+
+ def _keys(countries: set[str]) -> list[tuple[str, tuple[str, ...]]]:
+ if len(countries) >= 2:
+ return [("between", pair) for pair in combinations(sorted(countries), 2)]
+ if len(countries) == 1:
+ return [("inside", (next(iter(countries)),))]
+ return []
+
+ for row in win.current:
+ countries = _headline_countries(row.get("title") or "")
+ keys = _keys(countries)
+ if not keys:
+ continue
+ hostility = classify_hostility(row.get("title") or "")
+ comparable = row.get("feed_name") in win.comparable_feeds
+ for key in keys:
+ s = acc[key]
+ s["articles"] += 1
+ if comparable:
+ s["current_comparable"] += 1
+ if hostility:
+ s["hostile"] += 1
+ for cat in hostility:
+ s["by_category"][cat] += 1
+ if row.get("feed_name"):
+ s["outlets"].add(news.outlet_for(row["feed_name"]))
+ if len(s["headlines"]) < 3:
+ s["headlines"].append(
+ {
+ "title": row.get("title", ""),
+ "outlet": row.get("feed_name", ""),
+ "link": row.get("link", ""),
+ "published": row.get("published"),
+ "hostility": sorted(hostility),
+ }
+ )
+
+ for row in win.prior:
+ if row.get("feed_name") not in win.comparable_feeds:
+ continue
+ for key in _keys(_headline_countries(row.get("title") or "")):
+ acc[key]["prior"] += 1
+
+ situations = []
+ for (skind, codes), s in acc.items():
+ if kind != "all" and skind != kind:
+ continue
+ if s["articles"] < min_articles:
+ continue
+ situations.append(
+ {
+ "kind": skind,
+ "key": "-".join(codes),
+ "countries": [{"iso3": c, "name": _country_name(c)} for c in codes],
+ "articles": s["articles"],
+ "hostile_articles": s["hostile"],
+ "hostile_share": round(s["hostile"] / s["articles"], 3),
+ "by_category": s["by_category"],
+ "outlet_count": len(s["outlets"]),
+ **_change_fields(s["current_comparable"], s["prior"]),
+ "sample_headlines": s["headlines"],
+ }
+ )
+
+ if sort == "hostile":
+ situations.sort(key=lambda x: (x["hostile_articles"], x["hostile_share"], x["articles"]), reverse=True)
+ elif sort == "change":
+ situations.sort(key=lambda x: (x["change"], x["articles"]), reverse=True)
+ else:
+ situations.sort(key=lambda x: (x["articles"], x["hostile_articles"]), reverse=True)
+ situations = situations[:limit]
+
+ out = dict(base)
+ out.update(
+ {
+ "situations": situations,
+ "count": len(situations),
+ "window": win.describe(),
+ "min_articles": min_articles,
+ "definitions": {
+ "between": "a headline naming two or more countries counts once toward each pair it names",
+ "inside": (
+ "a headline naming exactly one country; it may describe that "
+ "country acting abroad against a party the headline does not name"
+ ),
+ "covered": "articles in the current window",
+ "hostile": (
+ "headlines matching any hostility category; sort orders by "
+ "hostile_articles, then hostile_share"
+ ),
+ "change": _CHANGE_DEFINITION,
+ },
+ "method": (
+ "RSS headlines from every configured feed; countries from "
+ "entities.extract_entities (country names, demonyms, capitals, "
+ "leader names mapped to their country) over its 22-country table, "
+ "so countries outside it never appear; a link seen twice counts "
+ "once. Hostility: " + HOSTILITY_METHOD
+ ),
+ "coverage": win.coverage(feed),
+ "data_gaps": win.gaps(feed),
+ }
+ )
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Top stories and attention
+# ---------------------------------------------------------------------------
+
+
+def _attention_counts(rows: list[dict], comparable: set[str] | None) -> dict:
+ counts: dict[tuple[str, str], int] = defaultdict(int)
+ for row in rows:
+ if comparable is not None and row.get("feed_name") not in comparable:
+ continue
+ ents = extract_entities(row.get("title") or "")["entities"]
+ for iso3 in _countries_of(ents):
+ counts[("country", iso3)] += 1
+ for o in ents["organizations"]:
+ counts[("organization", o["name"])] += 1
+ return counts
+
+
+async def fetch_top_stories(
+ fetcher,
+ hours: float = 24,
+ min_outlets: int = 3,
+ limit: int = 10,
+ attention_limit: int = 10,
+ threshold: float = 0.25,
+ now: datetime | None = None,
+) -> dict:
+ """Stories carried by at least ``min_outlets`` distinct outlets.
+
+ Clusters the current window's headlines (Jaccard, as in
+ ``intel_news_clusters``), counts distinct publishers per cluster
+ (sister feeds count once), and ranks by outlet count, then article
+ count. ``attention`` ranks named countries and organizations by
+ growth in mentions against the prior window.
+ """
+ now = now or datetime.now(timezone.utc)
+ hours = _clamp_hours(hours)
+ min_outlets = max(1, int(min_outlets))
+ base = {
+ "stories": [],
+ "count": 0,
+ "attention": [],
+ "min_outlets": min_outlets,
+ "source": "rss-aggregator+news-signals",
+ "timestamp": _iso(now),
+ }
+ feed = await news.fetch_news_feed(fetcher, limit=_ALL_ITEMS)
+ if feed.get("degraded") or feed.get("error"):
+ return _degraded_feed_response(feed, base)
+
+ win = _Windows(feed, hours, now)
+ rows = win.current
+ raw = cluster_articles(rows, similarity_threshold=threshold)
+
+ stories = []
+ for c in raw:
+ members = [rows[i] for i in c["member_indices"]]
+ outlets = sorted(
+ {news.outlet_for(m["feed_name"]) for m in members if m.get("feed_name")}
+ )
+ if len(outlets) < min_outlets:
+ continue
+ freq: dict[str, int] = defaultdict(int)
+ for m in members:
+ for w in _tokenize(m.get("title") or ""):
+ freq[w] += 1
+ stamps = [m["_ts"] for m in members]
+ stories.append(
+ {
+ "headline": c["representative"].get("title", ""),
+ "outlet_count": len(outlets),
+ "outlets": outlets,
+ "articles": len(members),
+ "keywords": sorted(freq, key=lambda w: (-freq[w], w))[:8],
+ "first_seen": _iso(min(stamps)),
+ "last_seen": _iso(max(stamps)),
+ "items": [
+ {
+ "title": m.get("title", ""),
+ "outlet": m.get("feed_name", ""),
+ "link": m.get("link", ""),
+ "published": m.get("published"),
+ }
+ for m in members[:5]
+ ],
+ }
+ )
+ stories.sort(key=lambda s: (s["outlet_count"], s["articles"], s["last_seen"]), reverse=True)
+ stories = stories[:limit]
+
+ cur = _attention_counts(win.current, win.comparable_feeds)
+ prior = _attention_counts(win.prior, win.comparable_feeds)
+ attention = []
+ for key in set(cur) | set(prior):
+ etype, ident = key
+ entry: dict[str, Any] = {"type": etype, "name": ident}
+ if etype == "country":
+ entry = {"type": etype, "name": _country_name(ident), "iso3": ident}
+ entry.update(_change_fields(cur.get(key, 0), prior.get(key, 0)))
+ attention.append(entry)
+ attention = [a for a in attention if a["change"] > 0]
+ attention.sort(key=lambda a: (a["change"], a["current_comparable"]), reverse=True)
+ attention = attention[:attention_limit]
+
+ out = dict(base)
+ out.update(
+ {
+ "stories": stories,
+ "count": len(stories),
+ "attention": attention,
+ "window": win.describe(),
+ "definitions": {
+ "outlet": (
+ "a publisher; sister feeds of one publisher (news.FEED_OUTLETS, "
+ "e.g. BBC World and BBC Mundo) count once"
+ ),
+ "story": (
+ f"a cluster of current-window headlines with Jaccard title "
+ f"similarity >= {threshold} to its first member"
+ ),
+ "attention": (
+ "countries (named directly or through a leader) and "
+ "organizations named in headlines, ranked by growth: "
+ + _CHANGE_DEFINITION + " Only entities that grew are listed."
+ ),
+ },
+ "method": (
+ "RSS headlines in the current window, clustered by title token "
+ "overlap; entity names from entities.extract_entities. Clustering "
+ "is lexical: one event told in different words can split into "
+ "several stories, and headlines in different languages never merge."
+ ),
+ "coverage": win.coverage(feed),
+ "data_gaps": win.gaps(feed),
+ }
+ )
+ return out
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index af3204c..e5bd837 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -850,6 +850,151 @@ def gdelt(ctx: click.Context, query: str, mode: str, limit: int) -> None:
_print_json(data)
+def _na(value: Any) -> str:
+ """A null measurement renders as n/a, never as 0."""
+ return "n/a" if value is None else str(value)
+
+
[email protected](name="hostility")
[email protected]("other", required=False)
[email protected]("--days", "-d", default=14, help="Days back including today (max 90)")
+def hostility_cmd(ctx: click.Context, country: str, other: str | None, days: int) -> None:
+ """Daily coverage and hostile coverage of a country or pair (GDELT)."""
+ from .analysis import news_signals
+
+ f = _get_fetcher()
+ data = _run(news_signals.fetch_hostility_timeline(f, country=country, other=other, days=days))
+
+ if _bail_on_error(ctx, data):
+ return
+
+ names = " / ".join(p["name"] for p in data.get("parties", []))
+ console.print(
+ f"[bold]Hostility timeline: {escape(names)}[/bold] "
+ f"({data.get('days_requested')} days, resolution {escape(str(data.get('date_resolution')))})\n"
+ )
+ table = Table(box=box.SIMPLE_HEAVY)
+ for col in ("Date", "Articles", "Threat", "Sanction", "Force", "Criticism", "Tone"):
+ table.add_column(col, justify="left" if col == "Date" else "right")
+ for d in data.get("days", []):
+ h = d.get("hostile", {})
+ date = d["date"] + (" *" if d.get("partial") else "") + (" ~" if d.get("in_progress") else "")
+ table.add_row(
+ date,
+ _na(d.get("articles")),
+ _na(h.get("threat")),
+ _na(h.get("sanction")),
+ _na(h.get("force")),
+ _na(h.get("criticism")),
+ _na(d.get("tone")),
+ )
+ console.print(table)
+ console.print(
+ "[dim]* partial day (GDELT returned fewer hours than elapsed); ~ day in progress; "
+ "n/a = not measured (fetch failed or day not returned)[/dim]"
+ )
+ _print_data_gaps(data)
+
+
[email protected](name="situations")
[email protected]("--hours", "-H", default=24.0, help="Window length in hours (1 to 168)")
+ "--sort", "-s", default="covered", type=click.Choice(["covered", "hostile", "change"])
+)
+ "--kind", "-k", default="all", type=click.Choice(["all", "between", "inside"])
+)
[email protected]("--limit", "-n", default=20, help="Max situations")
+def situations_cmd(ctx: click.Context, hours: float, sort: str, kind: str, limit: int) -> None:
+ """Ranked situations between and inside countries (RSS headlines)."""
+ from .analysis import news_signals
+
+ f = _get_fetcher()
+ data = _run(news_signals.fetch_situations(f, hours=hours, sort=sort, kind=kind, limit=limit))
+
+ if _bail_on_error(ctx, data):
+ return
+
+ win = data.get("window", {})
+ console.print(
+ f"[bold]Situations[/bold] by {sort}, window {win.get('current', {}).get('start', '?')} "
+ f".. {win.get('current', {}).get('end', '?')}\n"
+ )
+ table = Table(box=box.SIMPLE_HEAVY)
+ table.add_column("#", justify="right")
+ table.add_column("Kind")
+ table.add_column("Countries", style="bold")
+ table.add_column("Articles", justify="right")
+ table.add_column("Hostile", justify="right")
+ table.add_column("Change", justify="right")
+ table.add_column("Outlets", justify="right")
+ table.add_column("Headline")
+ for i, s in enumerate(data.get("situations", []), 1):
+ heads = s.get("sample_headlines") or [{}]
+ table.add_row(
+ str(i),
+ s["kind"],
+ _cell(" / ".join(c["name"] for c in s.get("countries", []))),
+ str(s["articles"]),
+ str(s["hostile_articles"]),
+ _signed(s["change"]),
+ str(s["outlet_count"]),
+ _cell((heads[0].get("title") or "")[:70]),
+ )
+ console.print(table)
+ _print_data_gaps(data)
+
+
[email protected](name="top-stories")
[email protected]("--hours", "-H", default=24.0, help="Window length in hours (1 to 168)")
[email protected]("--min-outlets", "-m", default=3, help="Minimum distinct outlets per story")
[email protected]("--limit", "-n", default=10, help="Max stories")
+def top_stories_cmd(ctx: click.Context, hours: float, min_outlets: int, limit: int) -> None:
+ """Stories carried by many outlets, plus who gained attention."""
+ from .analysis import news_signals
+
+ f = _get_fetcher()
+ data = _run(
+ news_signals.fetch_top_stories(f, hours=hours, min_outlets=min_outlets, limit=limit)
+ )
+
+ if _bail_on_error(ctx, data):
+ return
+
+ console.print(f"[bold]Top stories[/bold] (>= {min_outlets} outlets)\n")
+ table = Table(box=box.SIMPLE_HEAVY)
+ table.add_column("#", justify="right")
+ table.add_column("Outlets", justify="right")
+ table.add_column("Articles", justify="right")
+ table.add_column("Headline", style="bold")
+ for i, s in enumerate(data.get("stories", []), 1):
+ table.add_row(str(i), str(s["outlet_count"]), str(s["articles"]), _cell(s["headline"][:90]))
+ console.print(table)
+
+ attention = data.get("attention", [])
+ if attention:
+ att = Table(title="Attention (growth vs prior window)", box=box.SIMPLE_HEAVY)
+ att.add_column("Name", style="bold")
+ att.add_column("Type")
+ att.add_column("Now", justify="right")
+ att.add_column("Prior", justify="right")
+ att.add_column("Change", justify="right")
+ for a in attention:
+ att.add_row(
+ _cell(a["name"]),
+ a["type"],
+ str(a["current_comparable"]),
+ str(a["prior"]),
+ _signed(a["change"]),
+ )
+ console.print(att)
+ _print_data_gaps(data)
+
+
# ---------------------------------------------------------------------------
# Prediction
# ---------------------------------------------------------------------------
diff --git a/src/world_intel_mcp/collector.py b/src/world_intel_mcp/collector.py
index 4211562..fce0117 100644
--- a/src/world_intel_mcp/collector.py
+++ b/src/world_intel_mcp/collector.py
@@ -76,9 +76,14 @@ SOURCES = [
("nav_warnings", "sources.maritime", "fetch_nav_warnings", {}),
# Climate (1)
("climate_anomalies", "sources.climate", "fetch_climate_anomalies", {}),
- # News (2)
+ # News (4)
("news_feed", "sources.news", "fetch_news_feed", {}),
("trending_keywords", "sources.news", "fetch_trending_keywords", {}),
+ # Ranked situations and outlet-breadth stories over the same RSS read:
+ # fetch_news_feed shares one in-flight read among concurrent callers,
+ # so these four request each feed once per cycle.
+ ("situations", "analysis.news_signals", "fetch_situations", {}),
+ ("top_stories", "analysis.news_signals", "fetch_top_stories", {}),
# Prediction (1)
("prediction_markets", "sources.prediction", "fetch_prediction_markets", {}),
# Aviation (4)
@@ -161,7 +166,7 @@ DOMAIN_GROUPS = {
"infrastructure": ["internet_outages", "cable_health", "service_status"],
"maritime": ["nav_warnings"],
"climate": ["climate_anomalies"],
- "news": ["news_feed", "trending_keywords"],
+ "news": ["news_feed", "trending_keywords", "situations", "top_stories"],
"prediction": ["prediction_markets"],
"aviation": ["airport_delays", "domestic_flights", "bizjet_cohort", "military_cohort"],
"cyber": ["cyber_threats"],
diff --git a/src/world_intel_mcp/sources/news.py b/src/world_intel_mcp/sources/news.py
index 7c11078..f3d42ea 100644
--- a/src/world_intel_mcp/sources/news.py
+++ b/src/world_intel_mcp/sources/news.py
@@ -6,6 +6,7 @@ search via the GDELT 2.0 Doc API. No API keys required.
"""
import asyncio
+import functools
import logging
import re
import string
@@ -317,6 +318,29 @@ SOURCE_TIERS: dict[str, str] = {
"E&E News": "specialty",
}
+# Feeds that are sister editions of one publisher. Story breadth counts
+# outlets, not feeds: BBC World and BBC Mundo carrying a story is one
+# outlet's coverage. Feeds not listed are their own outlet.
+FEED_OUTLETS: dict[str, str] = {
+ "BBC World": "BBC",
+ "BBC Mundo": "BBC",
+ "DW News": "DW",
+ "DW Español": "DW",
+ "DW Deutsch": "DW",
+ "DW Europe": "DW",
+ "France24": "France 24",
+ "France24 Français": "France 24",
+ "UN News": "UN News",
+ "UN News Español": "UN News",
+ "UN News Français": "UN News",
+}
+
+
+def outlet_for(feed_name: str) -> str:
+ """The publisher behind a feed name (the feed name itself if unmapped)."""
+ return FEED_OUTLETS.get(feed_name, feed_name)
+
+
_STOPWORDS: set[str] = {
"the",
"a",
@@ -485,15 +509,17 @@ _PUNCT_RE = re.compile(f"[{re.escape(string.punctuation)}]")
def _parse_published(entry: dict) -> str | None:
"""Parse an RSS entry's published date to ISO 8601 UTC string.
- feedparser stores the parsed time struct in ``published_parsed``.
- Falls back to the raw ``published`` string if parsing fails.
+ feedparser stores the parsed time struct in ``published_parsed``, in
+ UTC. ``calendar.timegm`` reads it as UTC; ``time.mktime`` (used before
+ 2026-10-17) read it as local time and shifted every stamp by the host's
+ UTC offset. Falls back to the raw ``published`` string if parsing fails.
"""
- import time as _time
+ from calendar import timegm
parsed_tuple = entry.get("published_parsed")
if parsed_tuple is not None:
try:
- epoch = _time.mktime(parsed_tuple[:9])
+ epoch = timegm(parsed_tuple[:9])
dt = datetime.fromtimestamp(epoch, tz=timezone.utc)
return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
except (ValueError, TypeError, OverflowError):
@@ -503,7 +529,7 @@ def _parse_published(entry: dict) -> str | None:
updated_tuple = entry.get("updated_parsed")
if updated_tuple is not None:
try:
- epoch = _time.mktime(updated_tuple[:9])
+ epoch = timegm(updated_tuple[:9])
dt = datetime.fromtimestamp(epoch, tz=timezone.utc)
return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
except (ValueError, TypeError, OverflowError):
@@ -526,6 +552,30 @@ def _truncate(text: str | None, max_len: int = 200) -> str:
# Function 1: RSS News Feed Aggregation
# ---------------------------------------------------------------------------
+# In-flight all-feeds reads, keyed by (fetcher, event loop, feed set);
+# an entry lives only while its read runs.
+_INFLIGHT_READS: dict[tuple, asyncio.Future] = {}
+
+
+def _release_read(key: tuple, task: asyncio.Future) -> None:
+ if _INFLIGHT_READS.get(key) is task:
+ del _INFLIGHT_READS[key]
+ if not task.cancelled():
+ # Retrieved here so a read every caller abandoned never logs
+ # "exception was never retrieved"; awaiting callers still get it.
+ task.exception()
+
+
+def _stale_serves(fetcher: Fetcher, source: str) -> int:
+ """How many times the fetcher has served ``source`` from an expired copy.
+
+ Text payloads carry no inline ``_stale`` marker (fetcher._stale_fallback
+ counts them on the breaker instead), so a change in this count across
+ one fetch is the only sign that a feed came back as old cached XML.
+ """
+ count = fetcher.breaker.status().get(source, {}).get("total_stale_serves", 0)
+ return count if isinstance(count, int) else 0
+
async def fetch_news_feed(
fetcher: Fetcher,
@@ -571,6 +621,14 @@ async def fetch_news_feed(
categories_to_fetch = dict(_RSS_FEEDS)
all_items: list[dict] = []
+ # Feeds whose fetch failed or timed out. A dead feed used to contribute
+ # an empty list exactly like a quiet one, so a full outage read as a
+ # slow news day (ROADMAP Phase 24.5).
+ failed_feeds: list[str] = []
+ # Feeds whose live fetch failed but came back as an expired cached copy.
+ # In a running deployment the cache is warm, so an outage mostly looks
+ # like this, not like failed_feeds.
+ stale_feeds: list[str] = []
async def _fetch_single_feed(
feed_name: str,
@@ -579,9 +637,11 @@ async def fetch_news_feed(
) -> list[dict]:
"""Fetch and parse a single RSS feed, returning extracted items."""
safe_name = feed_name.lower().replace(" ", "_")
+ source = f"rss:{safe_name}"
+ stale_before = _stale_serves(fetcher, source)
xml_text = await fetcher.get_xml(
url,
- source=f"rss:{safe_name}",
+ source=source,
cache_key=f"news:rss:{safe_name}",
cache_ttl=300,
timeout=8.0,
@@ -589,7 +649,10 @@ async def fetch_news_feed(
if xml_text is None:
logger.debug("No data from RSS feed %s (%s)", feed_name, url)
+ failed_feeds.append(feed_name)
return []
+ if _stale_serves(fetcher, source) > stale_before:
+ stale_feeds.append(feed_name)
parsed = feedparser.parse(xml_text)
items: list[dict] = []
@@ -620,6 +683,7 @@ async def fetch_news_feed(
)
except asyncio.TimeoutError:
logger.debug("RSS feed %s timed out", feed_name)
+ failed_feeds.append(feed_name)
return []
# Fetch feeds with concurrency cap to avoid saturating the httpx pool.
@@ -631,14 +695,31 @@ async def fetch_news_feed(
async with sem:
return await _safe_fetch(feed_name, url, cat)
- all_tasks = [
- _throttled(feed_name, url, cat)
- for cat, feeds in categories_to_fetch.items()
- for feed_name, url in feeds
- ]
- results = await asyncio.gather(*all_tasks)
+ async def _read_all() -> tuple[list[list[dict]], list[str], list[str]]:
+ results = await asyncio.gather(
+ *(
+ _throttled(feed_name, url, cat)
+ for cat, feeds in categories_to_fetch.items()
+ for feed_name, url in feeds
+ )
+ )
+ return results, sorted(failed_feeds), sorted(stale_feeds)
+
+ # Concurrent reads of one feed set share a single fetch per feed: the
+ # collector starts news_feed, trending_keywords, situations and
+ # top_stories in one gather, and each used to request every feed.
+ # shield() keeps a caller's cancellation (a per-source timeout) from
+ # cancelling the read the other callers are waiting on.
+ key = (id(fetcher), id(asyncio.get_running_loop()), tuple(categories_to_fetch))
+ shared = _INFLIGHT_READS.get(key)
+ if shared is None:
+ shared = asyncio.ensure_future(_read_all())
+ _INFLIGHT_READS[key] = shared
+ shared.add_done_callback(functools.partial(_release_read, key))
+ results, failed, stale = await asyncio.shield(shared)
for items in results:
- all_items.extend(items)
+ # Copies: concurrent callers must not share mutable item dicts.
+ all_items.extend(dict(item) for item in items)
# Sort by published date descending (entries without dates go last)
all_items.sort(
@@ -649,13 +730,31 @@ async def fetch_news_feed(
# Apply limit
all_items = all_items[:limit]
- return {
+ feeds_attempted = sum(len(feeds) for feeds in categories_to_fetch.values())
+ result: dict = {
"items": all_items,
"count": len(all_items),
"categories_fetched": list(categories_to_fetch.keys()),
+ "feeds_attempted": feeds_attempted,
+ "feeds_ok": feeds_attempted - len(failed) - len(stale),
+ "feeds_failed": failed,
+ # Served from an expired cached copy after a failed fetch: their
+ # items are kept (each carries its own publish time) but are old.
+ "feeds_stale": stale,
"source": "rss-aggregator",
"timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
}
+ if feeds_attempted and result["feeds_ok"] == 0:
+ # No feed answered live: an outage, never "no news", whether or not
+ # old cached copies filled in. The items list keeps the normal shape
+ # so callers that only iterate still work.
+ error = f"All {feeds_attempted} RSS feeds failed or timed out"
+ if stale:
+ error += f" ({len(stale)} served from an expired cache copy)"
+ result["error"] = error
+ result["degraded"] = True
+ result["reason"] = "all_feeds_failed"
+ return result
# ---------------------------------------------------------------------------
@@ -716,12 +815,17 @@ async def fetch_trending_keywords(
# Return top 50
keywords = keywords[:50]
- return {
+ result = {
"keywords": keywords,
"total_items_analyzed": len(items),
"source": "keyword-analysis",
"timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
}
+ # An RSS outage is not "nothing trending".
+ for key in ("error", "degraded", "reason"):
+ if key in feed_data:
+ result[key] = feed_data[key]
+ return result
# ---------------------------------------------------------------------------
diff --git a/src/world_intel_mcp/tests/test_cli.py b/src/world_intel_mcp/tests/test_cli.py
index 5fdbb1b..1d22705 100644
--- a/src/world_intel_mcp/tests/test_cli.py
+++ b/src/world_intel_mcp/tests/test_cli.py
@@ -96,6 +96,9 @@ def test_command_registry() -> None:
"news",
"trending",
"gdelt",
+ "hostility",
+ "situations",
+ "top-stories",
"predictions",
"displacement",
"migration-flows",
diff --git a/src/world_intel_mcp/tests/test_clustering.py b/src/world_intel_mcp/tests/test_clustering.py
index d58e28d..30b17ab 100644
--- a/src/world_intel_mcp/tests/test_clustering.py
+++ b/src/world_intel_mcp/tests/test_clustering.py
@@ -132,3 +132,97 @@ async def test_fetch_news_clusters_reports_clusters_and_singletons(
"source": "BBC",
"link": "https://example.com/1",
}
+
+
+# Real producer shape: items as sources/news.fetch_news_feed emits them,
+# captured live 2026-10-17 (one story carried by seven outlets, plus two
+# items from the same publisher's sister feeds). fetch_news_feed names the
+# outlet "feed_name"; the clusterer used to read only source_name/source,
+# so every live cluster reported sources == [].
+_LIVE_POPE_ITEMS = [
+ {"title": "Pope Leo leaves hospital after lung cancer surgery", "link": "https://www.aljazeera.com/video/newsfeed/2026/10/17/pope-leo-leaves-hospital-after-lung-cancer-surgery?traffic_source=rss", "published": "2026-10-17T16:47:52Z", "feed_name": "Al Jazeera", "category": "geopolitics", "source_tier": "major"},
+ {"title": "Smiling pope returns to Vatican after cancer surgery", "link": "https://www.dawn.com/news/2037823/smiling-pope-returns-to-vatican-after-cancer-surgery", "published": "2026-10-17T16:20:04Z", "feed_name": "Dawn Pakistan", "category": "south_asia", "source_tier": "major"},
+ {"title": "Pope Leo XIV leaves hospital days after lung cancer surgery", "link": "https://www.npr.org/2026/10/17/nx-s1-6006762/pope-leo-xiv-leaves-hospital-days-after-lung-cancer-surgery", "published": "2026-10-17T16:10:14Z", "feed_name": "NPR World", "category": "geopolitics", "source_tier": "major"},
+ {"title": "Pope discharged from hospital days after lung cancer surgery", "link": "https://www.bbc.co.uk/news/articles/c5x2vkddrkrko?at_medium=RSS&at_campaign=rss", "published": "2026-10-17T14:51:36Z", "feed_name": "BBC World", "category": "geopolitics", "source_tier": "major"},
+ {"title": "Pope Leo discharged from hospital after cancer operation", "link": "https://www.theguardian.com/world/2026/oct/17/pope-leo-discharged-from-hospital-after-cancer-operation", "published": "2026-10-17T14:41:49Z", "feed_name": "The Guardian World", "category": "geopolitics", "source_tier": "major"},
+ {"title": "Vatican says Pope Leo to be released from the hospital after lung cancer surgery", "link": "https://www.timesofisrael.com/vatican-says-pope-leo-to-be-released-from-the-hospital-after-lung-cancer-surgery/", "published": "2026-10-17T12:18:32Z", "feed_name": "Times of Israel", "category": "middle_east", "source_tier": "unknown"},
+ {"title": "Pope Leo leaves hospital 4 days after lung cancer surgery", "link": "https://www.scmp.com/news/world/europe/article/3371256/pope-leo-leave-hospital-saturday-after-lung-cancer-surgery?utm_source=rss_feed", "published": "2026-10-17T11:26:27Z", "feed_name": "SCMP", "category": "asia_pacific", "source_tier": "unknown"},
+ # Sister feeds of one publisher: two feeds, one outlet.
+ {"title": "Pope Leo leaves hospital after lung cancer surgery, Vatican says", "link": "https://www.bbc.com/mundo/a1", "published": "2026-10-17T11:00:00Z", "feed_name": "BBC Mundo", "category": "multilingual", "source_tier": "major"},
+ {"title": "Unrelated: chess olympiad opens in Budapest", "link": "https://example.org/x", "published": "2026-10-17T10:00:00Z", "feed_name": "SCMP", "category": "asia_pacific", "source_tier": "unknown"},
+]
+
+
+async def test_fetch_news_clusters_reads_the_real_producer_outlet_key(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _fake_feed(fetcher, category=None, limit=100):
+ return {"items": list(_LIVE_POPE_ITEMS)}
+
+ monkeypatch.setattr(news, "fetch_news_feed", _fake_feed)
+ result = await fetch_news_clusters(fetcher)
+
+ assert result["cluster_count"] == 1
+ cluster = result["clusters"][0]
+ assert cluster["size"] == 8
+ assert sorted(cluster["sources"]) == sorted(
+ i["feed_name"] for i in _LIVE_POPE_ITEMS[:8]
+ )
+ assert cluster["items"][0]["source"] == "Al Jazeera"
+ # BBC World and BBC Mundo are one outlet (one publisher, two feeds).
+ assert cluster["outlet_count"] == 7
+ assert cluster["outlets"] == sorted(
+ ["Al Jazeera", "BBC", "Dawn Pakistan", "NPR World", "The Guardian World",
+ "Times of Israel", "SCMP"]
+ )
+
+
+async def test_fetch_news_clusters_marks_an_rss_outage(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """An all-feeds-down feed must not come back as a quiet, cluster-free
+ news day."""
+
+ async def _down(fetcher, category=None, limit=100):
+ return {
+ "items": [],
+ "count": 0,
+ "feeds_attempted": 3,
+ "feeds_ok": 0,
+ "feeds_failed": ["A", "B", "C"],
+ "error": "All 3 RSS feeds failed or timed out",
+ "degraded": True,
+ "reason": "all_feeds_failed",
+ }
+
+ monkeypatch.setattr(news, "fetch_news_feed", _down)
+ result = await fetch_news_clusters(fetcher)
+ assert result["clusters"] == []
+ assert result["degraded"] is True
+ assert result["reason"] == "all_feeds_failed"
+ assert result["feeds_failed"] == ["A", "B", "C"]
+
+
+async def test_fetch_news_clusters_healthy_feed_has_no_outage_marker(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _fake_feed(fetcher, category=None, limit=100):
+ return {"items": list(_LIVE_POPE_ITEMS), "feeds_failed": ["X"], "feeds_ok": 9}
+
+ monkeypatch.setattr(news, "fetch_news_feed", _fake_feed)
+ result = await fetch_news_clusters(fetcher)
+ assert "degraded" not in result
+ assert result["feeds_failed"] == ["X"]
+
+
+async def test_fetch_news_clusters_names_feeds_served_stale(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _fake_feed(fetcher, category=None, limit=100):
+ return {"items": list(_LIVE_POPE_ITEMS), "feeds_failed": [], "feeds_ok": 8,
+ "feeds_stale": ["SCMP"]}
+
+ monkeypatch.setattr(news, "fetch_news_feed", _fake_feed)
+ result = await fetch_news_clusters(fetcher)
+ assert result["feeds_stale"] == ["SCMP"]
+ assert result["clusters"][0]["outlet_count"] == 7
diff --git a/src/world_intel_mcp/tests/test_news_signals.py b/src/world_intel_mcp/tests/test_news_signals.py
new file mode 100644
index 0000000..632b6d2
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_news_signals.py
@@ -0,0 +1,921 @@
+"""Tests for analysis/news_signals.py and the hostility classifier.
+
+GDELT fixtures are the live ``timelinevolraw`` / ``timelinetone`` shape
+captured 2026-10-17 for the query ``Iran Israel`` (timespan 7d): hourly
+buckets 2026-10-15T10Z .. 2026-10-17T15Z, each volume bucket carrying
+``value`` (matching articles) and ``norm`` (all articles GDELT monitored).
+The base, sanction and tone values below are the captured values; the
+threat / force / criticism series reuse the captured bucket dates with
+values derived from the base series (no live capture of those three).
+
+RSS items use the live ``fetch_news_feed`` item shape (title, link,
+published, summary, feed_name, category, source_tier).
+
+Gaps / not covered: GDELT resolutions other than "hour" and "15m" (both
+seen live 2026-10-17; 14- and 30-day requests drew 429 on every attempt,
+so whether long spans answer in "day" buckets is unmeasured, and the 15m
+test's values are synthetic); real RSS feed depth, which changes hour to
+hour and decides which feeds are comparable.
+"""
+
+import asyncio as asyncio_mod
+from datetime import datetime, timedelta, timezone
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.analysis import news_signals as ns
+from world_intel_mcp.analysis.classifier import classify_hostility
+from world_intel_mcp.sources import news
+
+# ---------------------------------------------------------------------------
+# Live GDELT capture (2026-10-17, query "Iran Israel", timespan 7d)
+# ---------------------------------------------------------------------------
+
+_T0 = datetime(2026, 10, 15, 10, tzinfo=timezone.utc)
+_BASE = [(27, 5098), (19, 3390), (39, 5841), (46, 7762), (50, 12055), (50, 9595), (39, 7777), (18, 5031), (30, 4316), (42, 6521), (49, 10247), (41, 8548), (26, 5548), (17, 3544), (7, 4271), (21, 4579), (23, 4146), (1, 769), (49, 7947), (35, 6915), (44, 7664), (60, 12786), (46, 9761), (40, 7951), (60, 10619), (33, 7248), (30, 4446), (35, 7831), (19, 7133), (5, 2634), (33, 8123), (4, 1571), (15, 5152), (21, 5898), (16, 3995), (44, 5931), (40, 5153), (51, 7765), (45, 5962), (20, 1878), (9, 1700), (3, 1387), (45, 4971), (72, 7503), (33, 3328), (24, 3531), (32, 4220), (53, 6763), (50, 4567), (25, 4010), (58, 8293), (52, 6437), (16, 2958), (19, 4944)]
+_SANCTION = [2, 3, 2, 3, 3, 4, 3, 1, 2, 3, 4, 6, 3, 1, 0, 4, 1, 0, 5, 3, 6, 9, 6, 7, 6, 4, 1, 5, 2, 0, 5, 1, 1, 3, 1, 1, 2, 6, 5, 1, 1, 0, 29, 38, 17, 14, 19, 14, 17, 9, 12, 14, 2, 6]
+_TONE = [-3.4429, -2.766, -4.1908, -3.338, -3.5459, -2.8294, -3.0918, -3.1102, -3.8054, -2.9113, -3.0198, -3.1901, -2.7817, -2.5914, -2.1026, -1.8877, -2.3993, -3.8345, -3.065, -1.5778, -3.2848, -2.2168, -2.4771, -2.5812, -2.2363, -1.314, -3.168, -2.3672, -1.35, -3.4801, -2.7073, -3.8555, -1.9097, -3.1912, -3.1254, -3.4842, -3.5892, -3.7607, -3.535, -2.9224, -3.7986, -3.6808, -3.323, -3.0679, -3.3748, -3.1541, -3.5608, -3.3522, -3.8718, -4.0552, -3.4406, -4.0055, -4.2382, -4.1623]
+# Captured day totals (summed independently of the module under test).
+_DAY_ARTICLES = {"2026-10-15": 493, "2026-10-16": 732, "2026-10-17": 556}
+_DAY_NORM = {"2026-10-15": 95273, "2026-10-16": 150288, "2026-10-17": 72452}
+_DAY_SANCTION = {"2026-10-15": 40, "2026-10-16": 79, "2026-10-17": 198}
+_NOW_GDELT = datetime(2026, 10, 17, 15, 30, tzinfo=timezone.utc)
+
+
+def _stamps() -> list[str]:
+ return [(_T0 + timedelta(hours=i)).strftime("%Y%m%dT%H%M%SZ") for i in range(len(_BASE))]
+
+
+def _volraw(title: str, values: list[int]) -> dict:
+ return {
+ "query_details": {"title": title, "date_resolution": "hour"},
+ "timeline": [
+ {
+ "series": "Article Count",
+ "data": [
+ {"date": d, "value": v, "norm": n}
+ for d, v, (_, n) in zip(_stamps(), values, _BASE)
+ ],
+ }
+ ],
+ }
+
+
+def _tone(title: str) -> dict:
+ return {
+ "query_details": {"title": title, "date_resolution": "hour"},
+ "timeline": [
+ {
+ "series": "Average Tone",
+ "data": [{"date": d, "value": v} for d, v in zip(_stamps(), _TONE)],
+ }
+ ],
+ }
+
+
+_DERIVED = {
+ "threat": [v // 5 for v, _ in _BASE],
+ "force": [v // 2 for v, _ in _BASE],
+ "criticism": [v // 10 for v, _ in _BASE],
+}
+
+# Opening words of the live 429 body (the rest names a personal contact
+# address, left out of the fixture; the module never reads the body).
+_RATE_LIMIT_BODY = "Please limit requests to one every 5 seconds"
+
+
+def _category_of(query: str) -> str:
+ for cat, terms in ns.GDELT_HOSTILITY_TERMS.items():
+ if f"({' OR '.join(terms)})" in query:
+ return cat
+ return "articles"
+
+
+def _gdelt_router(fail: set[str] | None = None, fail_times: dict | None = None):
+ """respx side effect answering by mode and category; ``fail`` columns
+ always 429, ``fail_times`` columns 429 that many times first."""
+ fail = fail or set()
+ remaining = dict(fail_times or {})
+ calls: list[tuple[str, str]] = []
+
+ def _route(request: httpx.Request) -> httpx.Response:
+ mode = request.url.params["mode"]
+ query = request.url.params["query"]
+ col = "tone" if mode == "timelinetone" else _category_of(query)
+ calls.append((col, query))
+ if col in fail:
+ return httpx.Response(429, text=_RATE_LIMIT_BODY)
+ if remaining.get(col, 0) > 0:
+ remaining[col] -= 1
+ return httpx.Response(429, text=_RATE_LIMIT_BODY)
+ if col == "tone":
+ return httpx.Response(200, json=_tone(query))
+ if col == "articles":
+ return httpx.Response(200, json=_volraw(query, [v for v, _ in _BASE]))
+ if col == "sanction":
+ return httpx.Response(200, json=_volraw(query, _SANCTION))
+ return httpx.Response(200, json=_volraw(query, _DERIVED[col]))
+
+ return _route, calls
+
+
+def _fast(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ monkeypatch.setattr(ns, "_GDELT_SPACING_S", 0.0)
+ monkeypatch.setattr(ns, "_GDELT_RETRY_WAIT_S", 0.0)
+
+
+# ---------------------------------------------------------------------------
+# Hostility timeline
+# ---------------------------------------------------------------------------
+
+
+async def test_hostility_timeline_daily_values_from_live_shape(fetcher, _fast) -> None:
+ route, calls = _gdelt_router()
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(side_effect=route)
+
+ r = await ns.fetch_hostility_timeline(fetcher, "IRN", "Israel", days=5, now=_NOW_GDELT)
+
+ assert r["parties"][0] == {"input": "IRN", "name": "Iran", "iso3": "IRN"}
+ assert r["parties"][1]["iso3"] == "ISR"
+ assert r["queries"]["articles"] == "Iran Israel"
+ assert r["queries"]["sanction"].startswith("Iran Israel (sanction OR sanctions OR")
+ assert r["date_resolution"] == "hour"
+ assert "degraded" not in r
+ assert sorted(c for c, _ in calls) == sorted(
+ ["articles", "threat", "sanction", "force", "criticism", "tone"]
+ )
+
+ days = {d["date"]: d for d in r["days"]}
+ assert list(days) == ["2026-10-13", "2026-10-14", "2026-10-15", "2026-10-16", "2026-10-17"]
+ for day, n in _DAY_ARTICLES.items():
+ assert days[day]["articles"] == n
+ assert days[day]["all_monitored_articles"] == _DAY_NORM[day]
+ assert days[day]["hostile"]["sanction"] == _DAY_SANCTION[day]
+ # The sanction jump on 10-17 is in the captured data.
+ assert days["2026-10-17"]["hostile_share"]["sanction"] == round(198 / 556, 4)
+ assert days["2026-10-16"]["hostile"]["force"] == sum(v // 2 for v, _ in _BASE[14:38])
+ # 10-15 starts at 10:00 (14 of 24 hours); 10-17 has 16 of the 16
+ # hours elapsed at 15:30.
+ assert days["2026-10-15"]["partial"] is True
+ assert days["2026-10-15"]["buckets_returned"] == 14
+ assert days["2026-10-16"]["partial"] is False
+ assert days["2026-10-17"]["partial"] is False
+ # Tone weighted by hourly article counts, hand-checked against the
+ # capture: -2.6654 for 2026-10-16.
+ assert days["2026-10-16"]["tone"] == -2.6654
+
+
+async def test_hostility_timeline_days_gdelt_did_not_return_are_null_not_zero(
+ fetcher, _fast
+) -> None:
+ route, _ = _gdelt_router()
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(side_effect=route)
+
+ r = await ns.fetch_hostility_timeline(fetcher, "Iran", "Israel", days=5, now=_NOW_GDELT)
+ days = {d["date"]: d for d in r["days"]}
+ for day in ("2026-10-13", "2026-10-14"):
+ assert days[day]["articles"] is None
+ assert days[day]["hostile"] == {c: None for c in ns.GDELT_HOSTILITY_TERMS}
+ assert days[day]["tone"] is None
+ assert days[day]["buckets_returned"] == 0
+ assert any("no buckets for 2 of 5" in g for g in r["data_gaps"])
+
+
+async def test_hostility_timeline_outage_is_not_a_peaceful_timeline(fetcher, _fast) -> None:
+ route, _ = _gdelt_router(fail={"articles", "threat", "sanction", "force", "criticism", "tone"})
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(side_effect=route)
+
+ r = await ns.fetch_hostility_timeline(fetcher, "Iran", "Israel", days=5, now=_NOW_GDELT)
+ assert r["degraded"] is True
+ assert r["reason"] == "gdelt_fetch_failed"
+ assert "error" in r
+ assert r["days"] == []
+ for col in ("articles", "threat", "sanction", "force", "criticism", "tone"):
+ assert any(g.startswith(f"{col}:") for g in r["data_gaps"]), col
+
+
+async def test_hostility_timeline_one_failed_category_is_null_for_every_day(
+ fetcher, _fast
+) -> None:
+ route, _ = _gdelt_router(fail={"force"})
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(side_effect=route)
+
+ r = await ns.fetch_hostility_timeline(fetcher, "Iran", "Israel", days=3, now=_NOW_GDELT)
+ assert r["degraded"] is True
+ assert r["reason"] == "gdelt_partial"
+ assert any(g.startswith("force:") for g in r["data_gaps"])
+ for d in r["days"]:
+ assert d["hostile"]["force"] is None
+ assert d["hostile_share"]["force"] is None
+ assert d["hostile"]["sanction"] == _DAY_SANCTION[d["date"]]
+ assert d["articles"] == _DAY_ARTICLES[d["date"]]
+
+
+async def test_hostility_timeline_retries_a_rate_limited_call_once(fetcher, _fast) -> None:
+ # The Fetcher makes 3 attempts per call; the 4th request is this
+ # module's retry pass.
+ route, calls = _gdelt_router(fail_times={"sanction": 3})
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(side_effect=route)
+
+ r = await ns.fetch_hostility_timeline(fetcher, "Iran", "Israel", days=3, now=_NOW_GDELT)
+ assert "degraded" not in r
+ assert [c for c, _ in calls].count("sanction") == 4
+ assert {d["date"]: d["hostile"]["sanction"] for d in r["days"]} == _DAY_SANCTION
+
+
+async def test_hostility_timeline_failed_base_never_reports_zero_articles(
+ fetcher, _fast
+) -> None:
+ route, _ = _gdelt_router(fail={"articles"})
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(side_effect=route)
+
+ r = await ns.fetch_hostility_timeline(fetcher, "Iran", "Israel", days=3, now=_NOW_GDELT)
+ assert all(d["articles"] is None for d in r["days"])
+ assert all("hostile_share" not in d for d in r["days"])
+ # Tone falls back to an unweighted mean when volumes are missing.
+ d16 = next(d for d in r["days"] if d["date"] == "2026-10-16")
+ assert d16["tone"] == round(sum(_TONE[14:38]) / 24, 4)
+
+
+async def test_hostility_timeline_unknown_resolution_is_disclosed(fetcher, _fast) -> None:
+ payload = _volraw("Iran", [v for v, _ in _BASE])
+ payload["query_details"]["date_resolution"] = "15 minutes"
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(
+ return_value=httpx.Response(200, json=payload)
+ )
+ r = await ns.fetch_hostility_timeline(fetcher, "Iran", days=3, now=_NOW_GDELT)
+ assert any("'15 minutes'" in g for g in r["data_gaps"])
+ assert all("partial" not in d for d in r["days"])
+
+
+async def test_hostility_timeline_fifteen_minute_buckets_judged_by_hours_covered(
+ fetcher, _fast
+) -> None:
+ # Live 2026-10-17, timespan=3d: date_resolution "15m", and GDELT
+ # omitted quarter-hours (79 of 96 on 10-16) while still covering every
+ # hour, with the same daily total as hourly mode. Missing quarter-hours
+ # are not a partial day; a missing hour is. Shape as captured, values
+ # synthetic: 10-15 starts 10:00; 10-16 skips every 5th quarter-hour;
+ # 10-17 skips 03:00-03:59 entirely and runs to 15:15.
+ start = datetime(2026, 10, 15, 10, tzinfo=timezone.utc)
+ stamps = []
+ for i in range(56 + 96 + 62):
+ t = start + timedelta(minutes=15 * i)
+ if t.date().isoformat() == "2026-10-16" and i % 5 == 0:
+ continue
+ if t.date().isoformat() == "2026-10-17" and t.hour == 3:
+ continue
+ stamps.append(t.strftime("%Y%m%dT%H%M%SZ"))
+ payload = {
+ "query_details": {"title": "Iran", "date_resolution": "15m"},
+ "timeline": [{"series": "Article Count",
+ "data": [{"date": d, "value": 2, "norm": 100} for d in stamps]}],
+ }
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(
+ return_value=httpx.Response(200, json=payload)
+ )
+ r = await ns.fetch_hostility_timeline(fetcher, "Iran", days=3, now=_NOW_GDELT)
+ days = {d["date"]: d for d in r["days"]}
+ assert r["date_resolution"] == "15m"
+ assert not any("not one this server has measured" in g for g in r["data_gaps"])
+ got = {d: (v["buckets_returned"], v["hours_covered"], v["partial"]) for d, v in days.items()}
+ assert got == {
+ "2026-10-15": (56, 14, True),
+ "2026-10-16": (77, 24, False),
+ # 15:30: hours 00-14 have wholly elapsed and 03 is missing; the
+ # in-progress hour 15 does not make up for it.
+ "2026-10-17": (58, 15, True),
+ }
+ assert days["2026-10-15"]["hours_missing"] == [f"{h:02d}" for h in range(10)]
+ assert days["2026-10-17"]["hours_missing"] == ["03"]
+ assert "hours_missing" not in days["2026-10-16"]
+ assert days["2026-10-16"]["articles"] == 154
+
+
+def test_country_resolution_and_query_quoting() -> None:
+ assert ns._resolve_country("irn") == ("Iran", "IRN")
+ assert ns._resolve_country("Iranian") == ("Iran", "IRN")
+ assert ns._resolve_country("usa") == ("United States", "USA")
+ assert ns._resolve_country("Atlantis") == ("Atlantis", None)
+ assert ns._gdelt_term("United States") == '"United States"'
+ assert ns._gdelt_term("Iran") == "Iran"
+
+
+async def test_hostility_timeline_unknown_country_searched_verbatim_and_flagged(
+ fetcher, _fast
+) -> None:
+ route, calls = _gdelt_router()
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(side_effect=route)
+ r = await ns.fetch_hostility_timeline(fetcher, "Saudi Arabia", "USA", days=3, now=_NOW_GDELT)
+ assert r["queries"]["articles"] == '"Saudi Arabia" "United States"'
+ assert any("'Saudi Arabia' is not in the country table" in g for g in r["data_gaps"])
+
+
+async def test_hostility_timeline_marks_today_in_progress(fetcher, _fast) -> None:
+ route, _ = _gdelt_router()
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(side_effect=route)
+ r = await ns.fetch_hostility_timeline(fetcher, "Iran", "Israel", days=3, now=_NOW_GDELT)
+ flags = {d["date"]: d["in_progress"] for d in r["days"]}
+ assert flags == {"2026-10-15": False, "2026-10-16": False, "2026-10-17": True}
+ assert "in_progress" in r["definitions"]
+
+
+async def test_hostility_timeline_clamps_days_and_names_unreturned_days(fetcher, _fast) -> None:
+ route, calls = _gdelt_router()
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(side_effect=route)
+ r = await ns.fetch_hostility_timeline(fetcher, "Iran", days=500, now=_NOW_GDELT)
+ assert r["days_requested"] == 90
+ assert len(r["days"]) == 90
+ assert all(req.url.params["timespan"] == "90d" for req, _ in respx.calls)
+ # The capture holds 3 days; the other 87 are null and named.
+ assert any("no buckets for 87 of 90" in g for g in r["data_gaps"])
+ assert sum(1 for d in r["days"] if d["articles"] is None) == 87
+
+
+async def test_hostility_timeline_malformed_payload_is_a_failed_call(fetcher, _fast) -> None:
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(
+ return_value=httpx.Response(200, json={"timeline": "unavailable"})
+ )
+ r = await ns.fetch_hostility_timeline(fetcher, "Iran", days=3, now=_NOW_GDELT)
+ assert r["reason"] == "gdelt_fetch_failed"
+ assert r["days"] == []
+
+
+def test_series_by_day_skips_malformed_buckets() -> None:
+ days, resolution = ns._series_by_day(
+ {
+ "query_details": {"date_resolution": "hour"},
+ "timeline": [
+ {
+ "data": [
+ {"date": "2026", "value": 3},
+ {"date": "20261016T010000Z", "value": "n/a"},
+ {"date": "20261016T020000Z", "value": 4},
+ {"date": "20261017T000000Z", "value": 0},
+ ]
+ }
+ ],
+ }
+ )
+ assert resolution == "hour"
+ assert {d: [p["value"] for p in pts] for d, pts in days.items()} == {
+ "2026-10-16": [4],
+ "2026-10-17": [0],
+ }
+ assert ns._series_by_day({"timeline": []}) == ({}, None)
+
+
+async def test_hostility_timeline_spaces_live_calls_and_not_cache_hits(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ waits: list[float] = []
+
+ async def _record(delay, *args, **kwargs) -> None:
+ waits.append(delay)
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _record)
+ monkeypatch.setattr(ns, "_gdelt_last_call", 0.0)
+ route, calls = _gdelt_router()
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(side_effect=route)
+
+ await ns.fetch_hostility_timeline(fetcher, "Iran", "Israel", days=3, now=_NOW_GDELT)
+ # Six live calls: the first goes at once, each later one waits out
+ # GDELT's one-per-5-s floor.
+ assert len(calls) == 6
+ assert len(waits) == 5
+ assert all(5.0 < w <= ns._GDELT_SPACING_S for w in waits)
+
+ again = await ns.fetch_hostility_timeline(fetcher, "Iran", "Israel", days=3, now=_NOW_GDELT)
+ assert len(calls) == 6 and len(waits) == 5
+ assert again["days"][1]["articles"] == _DAY_ARTICLES["2026-10-16"]
+
+
+def test_parse_ts_rejects_naive_and_garbage() -> None:
+ assert ns._parse_ts("2026-10-17T10:00:00+02:00") == datetime(2026, 10, 17, 8, tzinfo=timezone.utc)
+ assert ns._parse_ts("2026-10-17T10:00:00Z") == datetime(2026, 10, 17, 10, tzinfo=timezone.utc)
+ assert ns._parse_ts("2026-10-17T10:00:00") is None
+ assert ns._parse_ts("yesterday") is None
+ assert ns._parse_ts(None) is None
+ assert ns._parse_ts(1760695200) is None
+
+
+# ---------------------------------------------------------------------------
+# RSS fixtures (live item shape)
+# ---------------------------------------------------------------------------
+
+_NOW = datetime(2026, 10, 17, 16, 0, tzinfo=timezone.utc)
+
+
+def _item(title: str, feed: str, hours_ago: float | None, link: str | None = None) -> dict:
+ published = None
+ if hours_ago is not None:
+ published = (_NOW - timedelta(hours=hours_ago)).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return {
+ "title": title,
+ "link": link or f"https://example.org/{feed.replace(' ', '-')}/{abs(hash(title))}",
+ "published": published,
+ "summary": "",
+ "feed_name": feed,
+ "category": "geopolitics",
+ "source_tier": news.SOURCE_TIERS.get(feed, "unknown"),
+ }
+
+
+_SITUATION_ITEMS = [
+ # BBC World: oldest item 76 h old, so it is comparable across 24 h windows.
+ _item("Russia launches missile strikes on Kyiv as Ukraine war grinds on", "BBC World", 2),
+ _item("Iran warns Israel against strikes on its nuclear sites", "BBC World", 3),
+ _item("Russia and Ukraine open talks in Geneva", "BBC World", 30),
+ _item("Chocolate festival opens in Bruges", "BBC World", 76),
+ # NPR World keeps only 8 h of history: not comparable.
+ _item("Russian drone attack hits Ukrainian grid", "NPR World", 1, link="https://npr.example/1"),
+ _item("Russian drone attack hits Ukrainian grid", "NPR World", 1, link="https://npr.example/1"),
+ _item("Quiet day at the zoo", "NPR World", 8),
+ # Al Jazeera: comparable.
+ _item("Mexico braces for strikes as budget protests spread", "Al Jazeera", 4),
+ _item("Mexico unveils new budget plan", "Al Jazeera", 5),
+ _item("Mexico budget vote delayed", "Al Jazeera", 26),
+ _item("Old story", "Al Jazeera", 60),
+ # Undated and future-stamped items are excluded and counted.
+ _item("India and Pakistan trade fire", "Al Jazeera", None),
+ _item("India and Pakistan trade fire again", "Al Jazeera", -5),
+]
+
+
+def _feed(items: list[dict], **extra) -> dict:
+ out = {"items": items, "count": len(items), "feeds_ok": 3, "feeds_failed": [], "feeds_attempted": 3}
+ out.update(extra)
+ return out
+
+
+def _patch_feed(monkeypatch: pytest.MonkeyPatch, payload: dict) -> None:
+ async def _fake(fetcher, category=None, limit=50):
+ return payload
+
+ monkeypatch.setattr(news, "fetch_news_feed", _fake)
+
+
+# ---------------------------------------------------------------------------
+# Situations
+# ---------------------------------------------------------------------------
+
+
+async def test_situations_counts_pairs_inside_and_change(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_feed(monkeypatch, _feed(_SITUATION_ITEMS))
+ r = await ns.fetch_situations(fetcher, min_articles=1, now=_NOW)
+
+ by_key = {s["key"]: s for s in r["situations"]}
+ rus_ukr = by_key["RUS-UKR"]
+ assert rus_ukr["kind"] == "between"
+ # BBC missile strike + NPR drone attack (the NPR duplicate link counts once).
+ assert rus_ukr["articles"] == 2
+ assert rus_ukr["hostile_articles"] == 2
+ assert rus_ukr["by_category"]["force"] == 2
+ assert rus_ukr["outlet_count"] == 2
+ # Change uses comparable feeds only: BBC 1 now vs BBC 1 prior.
+ assert (rus_ukr["current_comparable"], rus_ukr["prior"], rus_ukr["change"]) == (1, 1, 0)
+ assert rus_ukr["change_ratio"] == 1.0
+
+ irn_isr = by_key["IRN-ISR"]
+ assert irn_isr["by_category"]["threat"] == 1
+ assert irn_isr["by_category"]["force"] == 1
+
+ mex = by_key["MEX"]
+ assert mex["kind"] == "inside"
+ assert mex["articles"] == 2
+ # A labour strike is not force.
+ assert mex["hostile_articles"] == 0
+ assert (mex["current_comparable"], mex["prior"], mex["change"]) == (2, 1, 1)
+ assert mex["change_ratio"] == 1.5
+
+ assert "IND-PAK" not in by_key
+ cov = r["coverage"]
+ assert cov["undated_items"] == 1
+ assert cov["future_dated_items"] == 1
+ assert cov["feeds_not_comparable"] == ["NPR World"]
+ assert cov["items_current_window_comparable"] == 4
+ assert any("NPR World" in g and "excluded from change" in g for g in r["data_gaps"])
+ assert r["window"]["prior"] == {"start": "2026-10-15T16:00:00Z", "end": "2026-10-16T16:00:00Z"}
+ assert "change_ratio" in r["definitions"]["change"]
+
+
+async def test_situations_sorts(fetcher, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_feed(monkeypatch, _feed(_SITUATION_ITEMS))
+
+ async def _keys(**kw):
+ r = await ns.fetch_situations(fetcher, min_articles=1, now=_NOW, **kw)
+ return [s["key"] for s in r["situations"]]
+
+ assert await _keys(sort="covered") == ["RUS-UKR", "MEX", "IRN-ISR"]
+ assert await _keys(sort="hostile") == ["RUS-UKR", "IRN-ISR", "MEX"]
+ assert await _keys(sort="change") == ["MEX", "IRN-ISR", "RUS-UKR"]
+ assert await _keys(kind="inside") == ["MEX"]
+ assert await _keys(kind="between", limit=1) == ["RUS-UKR"]
+ default = await ns.fetch_situations(fetcher, now=_NOW)
+ assert [s["key"] for s in default["situations"]] == ["RUS-UKR", "MEX"]
+
+
+async def test_situations_leaders_map_to_countries_and_failed_feeds_are_named(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ items = [
+ _item("Trump threatens Xi with new tariffs", "BBC World", 2),
+ _item("Putin rebukes Zelenskyy over drone attack", "Al Jazeera", 3),
+ _item("Israeli strike kills five in Gaza", "BBC World", 4),
+ # NPR World keeps 30 h of history: not comparable, so its
+ # prior-window item must not count as prior coverage.
+ _item("Putin and Zelenskyy trade accusations", "NPR World", 1),
+ _item("Russia and Ukraine trade prisoners", "NPR World", 30),
+ _item("Archive item", "BBC World", 70),
+ _item("Archive item", "Al Jazeera", 70),
+ ]
+ _patch_feed(monkeypatch, _feed(items, feeds_failed=["CFR", "DW News"]))
+ r = await ns.fetch_situations(fetcher, min_articles=1, now=_NOW)
+ by_key = {s["key"]: s for s in r["situations"]}
+
+ usa_chn = by_key["CHN-USA"]
+ assert usa_chn["kind"] == "between"
+ assert usa_chn["by_category"] == {"threat": 1, "sanction": 1, "force": 0, "criticism": 0}
+
+ rus_ukr = by_key["RUS-UKR"]
+ assert rus_ukr["articles"] == 2
+ assert rus_ukr["by_category"] == {"threat": 0, "sanction": 0, "force": 1, "criticism": 2}
+ assert (rus_ukr["current_comparable"], rus_ukr["prior"], rus_ukr["change"]) == (1, 0, 1)
+
+ assert by_key["ISR-PSE"]["by_category"]["force"] == 1
+ assert r["coverage"]["feeds_failed"] == ["CFR", "DW News"]
+ assert any(
+ g.startswith("2 RSS feeds failed or timed out and are absent: CFR, DW News")
+ for g in r["data_gaps"]
+ )
+
+
+async def test_situations_never_compare_a_feed_served_stale(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # BBC World is the only comparable feed carrying Russia and Ukraine in
+ # both windows; served from an old cached copy, it would fake a drop.
+ _patch_feed(monkeypatch, _feed(_SITUATION_ITEMS, feeds_stale=["BBC World"]))
+ r = await ns.fetch_situations(fetcher, min_articles=1, now=_NOW)
+ rus_ukr = next(s for s in r["situations"] if s["key"] == "RUS-UKR")
+ assert rus_ukr["articles"] == 2
+ assert (rus_ukr["current_comparable"], rus_ukr["prior"]) == (0, 0)
+ assert r["coverage"]["feeds_stale"] == ["BBC World"]
+ assert "BBC World" not in r["coverage"]["feeds_not_comparable"]
+ assert r["coverage"]["feeds_comparable"] == 1
+ assert any(g.startswith("1 feeds failed live and were served from an expired cache copy")
+ and g.endswith("BBC World") for g in r["data_gaps"])
+
+
+async def test_windows_out_of_range_are_clamped_not_silently_empty(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ # A negative window used to invert the windows and drop every item,
+ # which read as "no situations".
+ recent = _item("Russia and Ukraine swap prisoners after drone attack", "BBC World", 0.5)
+ _patch_feed(monkeypatch, _feed(_SITUATION_ITEMS + [recent]))
+ r = await ns.fetch_situations(fetcher, hours=-5, min_articles=1, now=_NOW)
+ assert r["window"]["hours"] == 1.0
+ assert r["window"]["current"] == {"start": "2026-10-17T15:00:00Z", "end": "2026-10-17T16:00:00Z"}
+ # Only the 30-minute-old item is inside (15:00, 16:00]; the NPR item
+ # stamped exactly 15:00 belongs to the prior window.
+ assert [(s["key"], s["articles"]) for s in r["situations"]] == [("RUS-UKR", 1)]
+ wide = await ns.fetch_top_stories(fetcher, hours=10_000, min_outlets=0, now=_NOW)
+ assert wide["window"]["hours"] == 168.0
+ assert wide["min_outlets"] == 1
+
+
+async def test_situations_names_undated_items_by_feed(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ items = [
+ _item("Iran warns Israel", "BBC World", 1),
+ _item("Japan and China hold talks", "Nikkei Asia", None),
+ _item("China exports rise", "Nikkei Asia", None),
+ ]
+ _patch_feed(monkeypatch, _feed(items))
+ r = await ns.fetch_situations(fetcher, min_articles=1, now=_NOW)
+ assert r["coverage"]["undated_items"] == 2
+ assert any("2 items had no parseable publish time" in g and "Nikkei Asia 2" in g
+ for g in r["data_gaps"])
+
+
+async def test_situations_outage_is_not_a_quiet_world(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_feed(
+ monkeypatch,
+ {
+ "items": [],
+ "count": 0,
+ "feeds_attempted": 119,
+ "feeds_ok": 0,
+ "feeds_failed": ["BBC World"],
+ "error": "All 119 RSS feeds failed or timed out",
+ "degraded": True,
+ "reason": "all_feeds_failed",
+ },
+ )
+ r = await ns.fetch_situations(fetcher, now=_NOW)
+ assert r["situations"] == []
+ assert r["degraded"] is True
+ assert r["reason"] == "all_feeds_failed"
+ assert r["error"] == "All 119 RSS feeds failed or timed out"
+ assert r["data_gaps"]
+
+
+# ---------------------------------------------------------------------------
+# Top stories
+# ---------------------------------------------------------------------------
+
+_POPE = [
+ ("Pope Leo leaves hospital after lung cancer surgery", "Al Jazeera"),
+ ("Smiling pope returns to Vatican after cancer surgery", "Dawn Pakistan"),
+ ("Pope Leo XIV leaves hospital days after lung cancer surgery", "NPR World"),
+ ("Pope discharged from hospital days after lung cancer surgery", "BBC World"),
+ ("Pope Leo discharged from hospital after cancer operation", "The Guardian World"),
+ ("Vatican says Pope Leo to be released from the hospital after lung cancer surgery", "Times of Israel"),
+ ("Pope Leo leaves hospital 4 days after lung cancer surgery", "SCMP"),
+ ("Pope Leo leaves hospital after lung cancer surgery, Vatican says", "BBC Mundo"),
+]
+
+
+def _top_items() -> list[dict]:
+ items = [_item(t, f, 1 + i * 0.5) for i, (t, f) in enumerate(_POPE)]
+ # Comparable history for two feeds, and an attention signal: Yemen
+ # twice now and never before in those feeds; UN once in each window.
+ items += [
+ _item("Saudi strikes on Yemen kill 12, Houthis say", "BBC World", 2.5),
+ _item("Yemen ceasefire talks stall", "Al Jazeera", 3.5),
+ _item("UN warns of famine", "BBC World", 4.5),
+ _item("UN budget talks resume", "BBC World", 30),
+ _item("Archive item", "BBC World", 70),
+ _item("Archive item two", "Al Jazeera", 70),
+ ]
+ return items
+
+
+async def test_top_stories_ranks_by_distinct_outlets(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_feed(monkeypatch, _feed(_top_items()))
+ r = await ns.fetch_top_stories(fetcher, min_outlets=3, now=_NOW)
+ assert r["count"] == 1
+ story = r["stories"][0]
+ assert story["articles"] == 8
+ # BBC World and BBC Mundo are one outlet.
+ assert story["outlet_count"] == 7
+ assert "BBC" in story["outlets"] and "BBC Mundo" not in story["outlets"]
+ assert story["first_seen"] == "2026-10-17T11:30:00Z"
+ assert story["last_seen"] == "2026-10-17T15:00:00Z"
+ assert "hospital" in story["keywords"]
+
+ stricter = await ns.fetch_top_stories(fetcher, min_outlets=8, now=_NOW)
+ assert stricter["stories"] == []
+ assert "degraded" not in stricter
+
+
+async def test_top_stories_attention_growth(fetcher, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_feed(monkeypatch, _feed(_top_items()))
+ r = await ns.fetch_top_stories(fetcher, now=_NOW)
+ top = r["attention"][0]
+ assert top == {
+ "type": "country",
+ "name": "Yemen",
+ "iso3": "YEM",
+ "current_comparable": 2,
+ "prior": 0,
+ "change": 2,
+ "change_ratio": 3.0,
+ }
+ # UN: 1 now, 1 before: no growth, not listed.
+ assert all(a["name"] != "UN" for a in r["attention"])
+
+
+async def test_top_stories_attention_counts_a_leader_for_their_country(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ items = _top_items() + [_item("Trump threatens Xi with new tariffs", "BBC World", 1.5)]
+ _patch_feed(monkeypatch, _feed(items))
+ r = await ns.fetch_top_stories(fetcher, now=_NOW)
+ grew = {a.get("iso3"): a["change"] for a in r["attention"] if a["type"] == "country"}
+ assert grew["USA"] == 1 and grew["CHN"] == 1
+ assert "through a leader" in r["definitions"]["attention"]
+
+
+async def test_top_stories_outage_is_not_a_slow_news_day(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_feed(
+ monkeypatch,
+ {"items": [], "count": 0, "error": "All 3 RSS feeds failed or timed out",
+ "degraded": True, "reason": "all_feeds_failed", "feeds_failed": ["A", "B", "C"]},
+ )
+ r = await ns.fetch_top_stories(fetcher, now=_NOW)
+ assert r["stories"] == [] and r["attention"] == []
+ assert r["degraded"] is True
+ assert r["reason"] == "all_feeds_failed"
+
+
+# ---------------------------------------------------------------------------
+# Hostility classifier (headline heuristic)
+# ---------------------------------------------------------------------------
+
+
+ "title,expected",
+ [
+ # Live headlines, 2026-10-17.
+ ("Saudi strikes on Yemen kill 12, Houthis say", {"force"}),
+ ("Trump waives new Russia sanctions as Ukraine ties slump", {"sanction"}),
+ ("Belgium condemns Israeli settler attack on European diplomats in West Bank", {"criticism", "force"}),
+ ("Freeland Warns US Alliances Are Fraying", {"threat"}),
+ ("Pope Leo leaves hospital after lung cancer surgery", set()),
+ # Patterns pinned against idiom.
+ ("Warsaw court issues warrant", set()),
+ ("Raiders beat Chiefs in overtime", set()),
+ ("Chelsea attacker signs new deal", set()),
+ ("Mexico braces for strikes as budget protests spread", set()),
+ ("Israeli strike kills five in Gaza", {"force"}),
+ ("Russia launches new offensive near Kharkiv", {"force"}),
+ ("Senator apologizes for offensive remarks", set()),
+ ("China and US escalate trade war", {"sanction"}),
+ ("Trade warning from IMF", set()),
+ ("Price war hits airline stocks", set()),
+ ("War of words over Arctic claims", set()),
+ ("Apple blames weak demand for slump", set()),
+ ("Putin and Zelenskyy trade accusations", {"criticism"}),
+ ],
+)
+def test_classify_hostility(title: str, expected: set) -> None:
+ assert set(classify_hostility(title)) == expected
+
+
+def test_classify_hostility_returns_matched_keywords() -> None:
+ assert classify_hostility("Iran warns Israel against strikes on its nuclear sites") == {
+ "threat": ["warns"],
+ "force": ["strikes on"],
+ }
+ assert classify_hostility("") == {}
+
+
+# ---------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------
+
+from click.testing import CliRunner # noqa: E402
+
+from world_intel_mcp import cli # noqa: E402
+
+
+def _cli_env(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "cli-cache.db"))
+ monkeypatch.setenv("COLUMNS", "200")
+ monkeypatch.setattr(cli, "_fetcher", None)
+
+
+def _invoke(*args: str):
+ return CliRunner().invoke(cli.main, list(args), catch_exceptions=False)
+
+
+def _fake(payload, calls: list | None = None):
+ async def _f(*args, **kwargs):
+ if calls is not None:
+ calls.append(kwargs)
+ return payload
+
+ return _f
+
+
+def test_cli_hostility_renders_null_as_na_never_zero(
+ _cli_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls: list = []
+ payload = {
+ "parties": [{"name": "Iran"}, {"name": "Israel"}],
+ "days_requested": 2,
+ "date_resolution": "hour",
+ "days": [
+ {"date": "2026-10-16", "articles": 732, "partial": False, "tone": -2.6654,
+ "hostile": {"threat": 140, "sanction": 79, "force": None, "criticism": 70}},
+ {"date": "2026-10-17", "articles": None, "partial": True, "tone": None,
+ "hostile": {"threat": None, "sanction": None, "force": None, "criticism": None}},
+ ],
+ "data_gaps": ["force: GDELT volume timeline fetch failed; column is null"],
+ }
+ monkeypatch.setattr(ns, "fetch_hostility_timeline", _fake(payload, calls))
+ result = _invoke("hostility", "Iran", "Israel", "--days", "2")
+ assert result.exit_code == 0
+ assert calls == [{"country": "Iran", "other": "Israel", "days": 2}]
+ assert "Iran / Israel" in result.output
+ row16 = next(line for line in result.output.splitlines() if "2026-10-16" in line)
+ assert row16.split()[1:] == ["732", "140", "79", "n/a", "70", "-2.6654"]
+ row17 = next(line for line in result.output.splitlines() if "2026-10-17" in line)
+ assert " 0 " not in row17 and row17.count("n/a") == 6
+ assert "2026-10-17 *" in result.output
+ assert "Gap:" in result.output and "force" in result.output
+
+
+def test_cli_hostility_marks_the_day_in_progress(
+ _cli_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ payload = {
+ "parties": [{"name": "Iran"}],
+ "days_requested": 1,
+ "date_resolution": "hour",
+ "days": [
+ {"date": "2026-10-17", "articles": 556, "partial": False, "in_progress": True,
+ "tone": -3.5253, "hostile": {"threat": 205, "sanction": 198, "force": 460,
+ "criticism": 61}},
+ ],
+ "data_gaps": [],
+ }
+ monkeypatch.setattr(ns, "fetch_hostility_timeline", _fake(payload))
+ result = _invoke("hostility", "Iran", "-d", "1")
+ assert result.exit_code == 0
+ row = next(line for line in result.output.splitlines() if "2026-10-17" in line)
+ assert row.split() == ["2026-10-17", "~", "556", "205", "198", "460", "61", "-3.5253"]
+ assert "~ day in progress" in result.output
+
+
+def test_cli_hostility_outage_prints_error(_cli_env, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ ns, "fetch_hostility_timeline",
+ _fake({"error": "Every GDELT timeline call failed", "days": [], "degraded": True}),
+ )
+ result = _invoke("hostility", "Iran")
+ assert result.exit_code == 0
+ assert "Error:" in result.output
+ assert "Every GDELT timeline call failed" in result.output
+
+
+def test_cli_situations_passes_options_and_escapes(
+ _cli_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls: list = []
+ payload = {
+ "window": {"current": {"start": "2026-10-16T16:00:00Z", "end": "2026-10-17T16:00:00Z"}},
+ "situations": [
+ {"kind": "between", "countries": [{"name": "Russia"}, {"name": "United States"}],
+ "articles": 13, "hostile_articles": 12, "change": 1, "outlet_count": 12,
+ "sample_headlines": [{"title": "Trump waives [/] Russia sanctions"}]},
+ ],
+ "data_gaps": [],
+ }
+ monkeypatch.setattr(ns, "fetch_situations", _fake(payload, calls))
+ result = _invoke("situations", "--sort", "hostile", "--kind", "between", "-n", "5", "-H", "12")
+ assert result.exit_code == 0
+ assert calls == [{"hours": 12.0, "sort": "hostile", "kind": "between", "limit": 5}]
+ assert "Russia / United States" in result.output
+ assert "Trump waives [/] Russia sanctions" in result.output
+ assert "+1" in result.output
+
+
+def test_cli_top_stories_renders_stories_and_attention(
+ _cli_env, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls: list = []
+ payload = {
+ "stories": [{"headline": "Pope Leo leaves [hospital]", "outlet_count": 7, "articles": 8}],
+ "attention": [{"name": "Yemen", "type": "country", "current_comparable": 4,
+ "prior": 0, "change": 4}],
+ "data_gaps": ["32 feeds keep no history"],
+ }
+ monkeypatch.setattr(ns, "fetch_top_stories", _fake(payload, calls))
+ result = _invoke("top-stories", "-m", "4", "-n", "3")
+ assert result.exit_code == 0
+ assert calls == [{"hours": 24.0, "min_outlets": 4, "limit": 3}]
+ assert "Pope Leo leaves [hospital]" in result.output
+ assert "Yemen" in result.output and "+4" in result.output
+ assert "32 feeds keep no history" in result.output
+
+
+def test_cli_top_stories_json_output_is_raw(_cli_env, monkeypatch: pytest.MonkeyPatch) -> None:
+ payload = {"stories": [], "attention": [], "degraded": True, "error": "All 119 RSS feeds failed"}
+ monkeypatch.setattr(ns, "fetch_top_stories", _fake(payload))
+ result = _invoke("--json-output", "top-stories")
+ assert result.exit_code == 0
+ assert '"degraded": true' in result.output
diff --git a/src/world_intel_mcp/tests/test_server_registry.py b/src/world_intel_mcp/tests/test_server_registry.py
index 434764e..f334337 100644
--- a/src/world_intel_mcp/tests/test_server_registry.py
+++ b/src/world_intel_mcp/tests/test_server_registry.py
@@ -229,3 +229,44 @@ def test_readme_documents_every_registered_tool(server) -> None:
n = len(server.TOOLS)
assert f"**{n} MCP tools**" in readme
assert f"**Total: {n} tools**" in readme
+
+
+async def test_dispatch_news_signal_tools_pass_arguments_and_mark_outages(
+ server, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The Phase 29 news-signal tools through the real dispatcher, with
+ RSS and GDELT failing at the source boundary: the arguments reach the
+ analysis, and an outage comes back marked, never as an empty ranking
+ or a zero-hostility timeline."""
+ from world_intel_mcp.analysis import news_signals as ns
+ from world_intel_mcp.sources import news
+
+ async def _rss_down(fetcher, category=None, limit=50):
+ return {
+ "items": [], "count": 0, "feeds_attempted": 119, "feeds_ok": 0,
+ "feeds_failed": ["BBC World"], "error": "All 119 RSS feeds failed or timed out",
+ "degraded": True, "reason": "all_feeds_failed",
+ }
+
+ async def _gdelt_down(fetcher, query, mode, days):
+ return None
+
+ monkeypatch.setattr(news, "fetch_news_feed", _rss_down)
+ monkeypatch.setattr(ns, "_gdelt_timeline", _gdelt_down)
+ monkeypatch.setattr(ns, "_GDELT_RETRY_WAIT_S", 0.0)
+
+ sit = await server._dispatch("intel_situations", {"sort": "hostile", "kind": "between"})
+ assert (sit["sort"], sit["kind"], sit["situations"]) == ("hostile", "between", [])
+ assert sit["degraded"] is True and sit["reason"] == "all_feeds_failed"
+
+ top = await server._dispatch("intel_top_stories", {"min_outlets": 4})
+ assert top["min_outlets"] == 4 and top["stories"] == []
+ assert top["degraded"] is True
+
+ host = await server._dispatch(
+ "intel_hostility_timeline", {"country": "IRN", "other": "Israel", "days": 3}
+ )
+ assert [p["iso3"] for p in host["parties"]] == ["IRN", "ISR"]
+ assert host["days_requested"] == 3
+ assert host["days"] == [] and host["reason"] == "gdelt_fetch_failed"
diff --git a/src/world_intel_mcp/tests/test_sources_news.py b/src/world_intel_mcp/tests/test_sources_news.py
index b07abad..73da97c 100644
--- a/src/world_intel_mcp/tests/test_sources_news.py
+++ b/src/world_intel_mcp/tests/test_sources_news.py
@@ -8,7 +8,10 @@ paths, and the timeline degraded shape.
Gaps / not covered: live feed availability across the 119 configured
feeds; the asyncio.wait_for per-feed hard timeout (needs a slow fake
transport); the 25-way semaphore cap (behavioral, not observable from the
-result shape).
+result shape). Stale detection reads the breaker's per-source stale-serve
+count around each fetch, so a stale serve of the same feed by a separate,
+non-shared read in the same process at the same moment would be
+attributed to this one; no test drives that race.
"""
import asyncio as asyncio_mod
@@ -99,9 +102,9 @@ async def test_fetch_news_feed_unknown_category(fetcher: Fetcher) -> None:
async def test_fetch_news_feed_all_feeds_down(
fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
) -> None:
- """Observation (flagged in review, not fixed): dead feeds contribute
- nothing silently — a category-wide outage returns count=0 with no
- error/degraded marker, shape-identical to a slow news day."""
+ """ROADMAP Phase 24.5: a category-wide outage used to return count=0
+ with no marker, shape-identical to a slow news day. It must now say
+ every feed failed, and name them."""
async def _no_sleep(*args, **kwargs) -> None:
return None
@@ -114,7 +117,181 @@ async def test_fetch_news_feed_all_feeds_down(
assert result["items"] == []
assert result["count"] == 0
assert result["categories_fetched"] == ["security"]
- assert "error" not in result # current (dishonest-quiet) behavior
+ assert result["degraded"] is True
+ assert result["reason"] == "all_feeds_failed"
+ assert "error" in result
+ n_feeds = len(_RSS_FEEDS["security"])
+ assert result["feeds_attempted"] == n_feeds
+ assert result["feeds_ok"] == 0
+ assert sorted(result["feeds_failed"]) == sorted(
+ name for name, _ in _RSS_FEEDS["security"]
+ )
+
+
+async def test_fetch_news_feed_partial_outage_is_counted_not_fatal(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """One dead feed among live ones: items still flow, the dead feed is
+ named, and the response is not an outage."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ dead_name, dead_url = _RSS_FEEDS["security"][0]
+ respx.get(dead_url).mock(return_value=httpx.Response(503))
+ respx.route().mock(return_value=httpx.Response(200, text=_RSS))
+
+ result = await fetch_news_feed(fetcher, category="security")
+ n_feeds = len(_RSS_FEEDS["security"])
+ assert result["count"] == 2 * (n_feeds - 1)
+ assert result["feeds_failed"] == [dead_name]
+ assert result["feeds_ok"] == n_feeds - 1
+ assert result["feeds_attempted"] == n_feeds
+ assert "degraded" not in result
+ assert "error" not in result
+
+
+async def test_fetch_news_feed_reachable_but_empty_feeds_are_not_an_outage(
+ fetcher: Fetcher,
+) -> None:
+ """Every feed answered with a valid, empty channel: a genuinely quiet
+ result, so no outage marker."""
+ empty = '<?xml version="1.0"?><rss version="2.0"><channel><title>F</title></channel></rss>'
+ respx.route().mock(return_value=httpx.Response(200, text=empty))
+
+ result = await fetch_news_feed(fetcher, category="security")
+ assert result["count"] == 0
+ assert result["feeds_ok"] == len(_RSS_FEEDS["security"])
+ assert result["feeds_failed"] == []
+ assert "degraded" not in result
+
+
+def _rss_cache_key(feed_name: str) -> str:
+ return f"news:rss:{feed_name.lower().replace(' ', '_')}"
+
+
+async def test_fetch_news_feed_stale_fallback_is_not_a_live_feed(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A feed whose live fetch fails but whose expired copy is still cached
+ comes back as that copy (the fetcher's stale fallback), and text
+ payloads carry no inline marker. It must be named stale, not counted
+ as a live feed."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ stale_name, stale_url = _RSS_FEEDS["security"][0]
+ fetcher.cache.set(_rss_cache_key(stale_name), _RSS, ttl_seconds=-1)
+ respx.get(stale_url).mock(return_value=httpx.Response(503))
+ respx.route().mock(return_value=httpx.Response(200, text=_RSS))
+
+ result = await fetch_news_feed(fetcher, category="security")
+ n_feeds = len(_RSS_FEEDS["security"])
+ assert result["feeds_stale"] == [stale_name]
+ assert result["feeds_ok"] == n_feeds - 1
+ assert result["feeds_failed"] == []
+ # The old copy's items are kept: they carry their own publish times.
+ assert result["count"] == 2 * n_feeds
+ assert "degraded" not in result
+
+
+async def test_fetch_news_feed_outage_behind_a_warm_cache_is_still_an_outage(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """In a running deployment the cache is warm, so when every feed fails
+ most come back as expired copies. That is still an outage."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ names = [name for name, _ in _RSS_FEEDS["security"]]
+ for name in names:
+ fetcher.cache.set(_rss_cache_key(name), _RSS, ttl_seconds=-1)
+ respx.route().mock(return_value=httpx.Response(503))
+
+ result = await fetch_news_feed(fetcher, category="security")
+ assert result["degraded"] is True
+ assert result["reason"] == "all_feeds_failed"
+ assert result["feeds_ok"] == 0
+ assert result["feeds_stale"] == sorted(names)
+ assert "expired cache copy" in result["error"]
+
+
+def _gated_get_xml(calls: list[str], gate: asyncio_mod.Event):
+ async def _get_xml(url, source, cache_key=None, cache_ttl=300, timeout=None):
+ calls.append(url)
+ await gate.wait()
+ return _RSS
+
+ return _get_xml
+
+
+async def _let_tasks_start(n: int = 5) -> None:
+ for _ in range(n):
+ await asyncio_mod.sleep(0)
+
+
+async def test_fetch_news_feed_concurrent_reads_share_one_fetch_per_feed(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The collector starts news_feed, trending_keywords, situations and
+ top_stories in one gather; each used to request every feed itself.
+ Concurrent reads of the same feed set now share one request per feed,
+ while each caller keeps its own limit and its own item dicts."""
+ calls: list[str] = []
+ gate = asyncio_mod.Event()
+ monkeypatch.setattr(fetcher, "get_xml", _gated_get_xml(calls, gate))
+
+ first = asyncio_mod.ensure_future(fetch_news_feed(fetcher, category="security", limit=3))
+ second = asyncio_mod.ensure_future(fetch_news_feed(fetcher, category="security", limit=500))
+ await _let_tasks_start()
+ gate.set()
+ a, b = await asyncio_mod.gather(first, second)
+
+ n_feeds = len(_RSS_FEEDS["security"])
+ assert len(calls) == n_feeds
+ assert a["count"] == 3
+ assert b["count"] == 2 * n_feeds
+ assert a["feeds_ok"] == b["feeds_ok"] == n_feeds
+ a["items"][0]["title"] = "mutated by the first caller"
+ assert all(i["title"] != "mutated by the first caller" for i in b["items"])
+ assert news._INFLIGHT_READS == {}
+
+
+async def test_fetch_news_feed_cancelled_reader_leaves_the_shared_read_running(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A caller cancelled mid-read (the collector's per-source timeout)
+ must not cancel the read other callers are waiting on."""
+ calls: list[str] = []
+ gate = asyncio_mod.Event()
+ monkeypatch.setattr(fetcher, "get_xml", _gated_get_xml(calls, gate))
+
+ first = asyncio_mod.ensure_future(fetch_news_feed(fetcher, category="security"))
+ await _let_tasks_start()
+ second = asyncio_mod.ensure_future(fetch_news_feed(fetcher, category="security"))
+ await _let_tasks_start()
+ first.cancel()
+ gate.set()
+ b = await second
+ assert b["feeds_ok"] == len(_RSS_FEEDS["security"])
+ assert "degraded" not in b
+ with pytest.raises(asyncio_mod.CancelledError):
+ await first
@pytest.mark.asyncio
@@ -140,6 +317,31 @@ async def test_fetch_trending_keywords(
# "ukraine" appears 3x (possessive punctuation stripped); "drone" only
# 2x so it must fall below min_count=3.
assert result["keywords"] == [{"word": "ukraine", "count": 3}]
+ assert "degraded" not in result
+
+
+async def test_fetch_trending_keywords_rss_outage_is_not_no_trends(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _down(f, category=None, limit=50):
+ return {
+ "items": [],
+ "count": 0,
+ "feeds_attempted": 119,
+ "feeds_ok": 0,
+ "feeds_failed": ["BBC World"],
+ "error": "All 119 RSS feeds failed or timed out",
+ "degraded": True,
+ "reason": "all_feeds_failed",
+ }
+
+ monkeypatch.setattr(news, "fetch_news_feed", _down)
+ result = await fetch_trending_keywords(fetcher)
+ assert result["keywords"] == []
+ assert result["degraded"] is True
+ assert result["reason"] == "all_feeds_failed"
+ assert result["error"] == "All 119 RSS feeds failed or timed out"
@pytest.mark.asyncio
@@ -257,6 +459,26 @@ def test_parse_published_fallbacks() -> None:
assert _parse_published({}) is None
+def test_parse_published_is_utc_on_a_non_utc_host(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """feedparser's *_parsed structs are UTC. time.mktime read them as
+ local time, so on mac-studio (EDT) every published stamp came out
+ four hours in the future (measured live 2026-10-17: a feed's newest
+ item stamped 20:18Z at 16:20Z)."""
+ import time as time_mod
+
+ monkeypatch.setenv("TZ", "America/New_York")
+ time_mod.tzset()
+ try:
+ utc_struct = time_mod.gmtime(1700000000) # 2023-11-14 22:13:20 UTC
+ assert _parse_published({"published_parsed": utc_struct}) == "2023-11-14T22:13:20Z"
+ assert _parse_published({"updated_parsed": utc_struct}) == "2023-11-14T22:13:20Z"
+ finally:
+ monkeypatch.delenv("TZ")
+ time_mod.tzset()
+
+
@pytest.mark.asyncio
async def test_gdelt_search_uses_extended_timeout(fetcher, monkeypatch) -> None:
"""Measured live 2026-09-02 from mac-studio: api.gdeltproject.org
diff --git a/src/world_intel_mcp/tools/__init__.py b/src/world_intel_mcp/tools/__init__.py
index d1b68a7..645e974 100644
--- a/src/world_intel_mcp/tools/__init__.py
+++ b/src/world_intel_mcp/tools/__init__.py
@@ -31,6 +31,7 @@ from . import ( # noqa: E402
infrastructure,
intelligence,
markets,
+ news_signals,
society,
synthesis,
system,
@@ -48,6 +49,7 @@ _MODULES = [
intelligence,
geospatial,
synthesis,
+ news_signals,
finance,
vector,
aoi,
diff --git a/src/world_intel_mcp/tools/news_signals.py b/src/world_intel_mcp/tools/news_signals.py
new file mode 100644
index 0000000..583fbe8
--- /dev/null
+++ b/src/world_intel_mcp/tools/news_signals.py
@@ -0,0 +1,161 @@
+"""News-signal tools (Phase 29): hostility timeline, ranked situations,
+top stories by outlet breadth. Logic lives in analysis/news_signals.py;
+handlers reach shared infrastructure via ``runtime``.
+"""
+
+from typing import Any
+
+from mcp.types import Tool
+
+from .. import runtime
+
+TOOLS: list[Tool] = [
+ Tool(
+ name="intel_hostility_timeline",
+ description=(
+ "Per-day news coverage of a country, or of a pair of countries, from GDELT: "
+ "article count, articles using threat / sanction / force / criticism terms "
+ "(GDELT keyword match, listed in the response), and GDELT average tone. "
+ "A failed call or a day GDELT did not return is null and listed in "
+ "data_gaps, never zero."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "country": {
+ "type": "string",
+ "description": "Country name or ISO3 code (e.g. 'Iran' or 'IRN').",
+ },
+ "other": {
+ "type": "string",
+ "description": "Optional second country: coverage naming both.",
+ },
+ "days": {
+ "type": "integer",
+ "description": "Days back, including today (default: 14, max: 90).",
+ "default": 14,
+ },
+ },
+ "required": ["country"],
+ },
+ ),
+ Tool(
+ name="intel_situations",
+ description=(
+ "Ranked situations between countries (headlines naming two or more) and "
+ "inside a country (headlines naming one) over a recent window of the RSS "
+ "feeds. Sort by most covered, most hostile (headline keyword heuristic), "
+ "or biggest change against the preceding window; the response defines "
+ "each measure and names excluded feeds."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "hours": {
+ "type": "number",
+ "description": "Window length in hours, 1 to 168 (default: 24); the prior window is the same length.",
+ "default": 24,
+ },
+ "sort": {
+ "type": "string",
+ "enum": ["covered", "hostile", "change"],
+ "description": "Ranking (default: covered).",
+ "default": "covered",
+ },
+ "kind": {
+ "type": "string",
+ "enum": ["all", "between", "inside"],
+ "description": "Situation kind filter (default: all).",
+ "default": "all",
+ },
+ "limit": {
+ "type": "integer",
+ "description": "Max situations (default: 20).",
+ "default": 20,
+ },
+ "min_articles": {
+ "type": "integer",
+ "description": "Minimum current-window articles (default: 2).",
+ "default": 2,
+ },
+ },
+ },
+ ),
+ Tool(
+ name="intel_top_stories",
+ description=(
+ "Stories carried by at least min_outlets distinct outlets in a recent RSS "
+ "window (sister feeds of one publisher count once), ranked by outlet count, "
+ "plus attention: the countries and organizations whose headline mentions "
+ "grew most against the preceding window."
+ ),
+ inputSchema={
+ "type": "object",
+ "properties": {
+ "hours": {
+ "type": "number",
+ "description": "Window length in hours, 1 to 168 (default: 24).",
+ "default": 24,
+ },
+ "min_outlets": {
+ "type": "integer",
+ "description": "Minimum distinct outlets per story (default: 3).",
+ "default": 3,
+ },
+ "limit": {
+ "type": "integer",
+ "description": "Max stories (default: 10).",
+ "default": 10,
+ },
+ "attention_limit": {
+ "type": "integer",
+ "description": "Max attention entries (default: 10).",
+ "default": 10,
+ },
+ },
+ },
+ ),
+]
+
+
+async def _hostility_timeline(arguments: dict[str, Any]) -> Any:
+ from ..analysis.news_signals import fetch_hostility_timeline
+
+ return await fetch_hostility_timeline(
+ runtime.fetcher,
+ country=arguments["country"],
+ other=arguments.get("other"),
+ days=arguments.get("days", 14),
+ )
+
+
+async def _situations(arguments: dict[str, Any]) -> Any:
+ from ..analysis.news_signals import fetch_situations
+
+ return await fetch_situations(
+ runtime.fetcher,
+ hours=arguments.get("hours", 24),
+ sort=arguments.get("sort", "covered"),
+ kind=arguments.get("kind", "all"),
+ limit=arguments.get("limit", 20),
+ min_articles=arguments.get("min_articles", 2),
+ )
+
+
+async def _top_stories(arguments: dict[str, Any]) -> Any:
+ from ..analysis.news_signals import fetch_top_stories
+
+ return await fetch_top_stories(
+ runtime.fetcher,
+ hours=arguments.get("hours", 24),
+ min_outlets=arguments.get("min_outlets", 3),
+ limit=arguments.get("limit", 10),
+ attention_limit=arguments.get("attention_limit", 10),
+ )
+
+
+HANDLERS = {
+ "intel_hostility_timeline": _hostility_timeline,
+ "intel_situations": _situations,
+ "intel_top_stories": _top_stories,
+}