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.

Test waves for the unexecuted layers: analysis NLP, sources, server registry, collector map (+265 tests, coverage 59% -> 81%)

Phoenix Agent (Marcs-Mac-Studio)5436ffafc214
diff --git a/src/world_intel_mcp/tests/test_alerts.py b/src/world_intel_mcp/tests/test_alerts.py
new file mode 100644
index 0000000..f7f7377
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_alerts.py
@@ -0,0 +1,220 @@
+"""Tests for analysis/alerts.py — cross-domain alert digest and weekly trends.
+
+Both tools compose source functions, so tests mock at the source-function
+boundary. Weekly-trends tests point temporal._DB_PATH at a tmp_path SQLite
+file; the coefficient of variation for the seeded row is hand-computed
+(n=10, mean=20, M2=900 -> sample variance 100, std 10, cv 50%).
+"""
+
+import sqlite3
+from pathlib import Path
+
+import pytest
+
+from world_intel_mcp.analysis import temporal
+from world_intel_mcp.analysis.alerts import fetch_alert_digest, fetch_weekly_trends
+from world_intel_mcp.sources import (
+ infrastructure,
+ intelligence,
+ shipping,
+ space_weather,
+)
+
+
+def _make_fake(payload: dict):
+ async def _fake(fetcher, *args, **kwargs):
+ return payload
+
+ return _fake
+
+
+def _patch_digest_sources(monkeypatch: pytest.MonkeyPatch, payloads: dict) -> None:
+ monkeypatch.setattr(
+ space_weather, "fetch_space_weather", _make_fake(payloads["space"])
+ )
+ monkeypatch.setattr(
+ intelligence, "fetch_instability_index", _make_fake(payloads["instability"])
+ )
+ monkeypatch.setattr(
+ intelligence, "fetch_military_surge", _make_fake(payloads["surge"])
+ )
+ monkeypatch.setattr(
+ infrastructure, "fetch_cable_health", _make_fake(payloads["cables"])
+ )
+ monkeypatch.setattr(
+ intelligence, "fetch_hotspot_escalation", _make_fake(payloads["hotspots"])
+ )
+ monkeypatch.setattr(
+ infrastructure, "fetch_internet_outages", _make_fake(payloads["outages"])
+ )
+ monkeypatch.setattr(
+ shipping, "fetch_shipping_index", _make_fake(payloads["shipping"])
+ )
+
+
+_STORMY_WORLD = {
+ "space": {"current_kp": 6.0, "kp_level": "Moderate storm"},
+ "instability": {
+ "countries": [
+ {"country_name": "Sudan", "instability_index": 75},
+ {"country_name": "Norway", "instability_index": 12},
+ ]
+ },
+ "surge": {"surge_count": 2, "surges": [{"region": "red_sea"}]},
+ "cables": {
+ "corridors": {
+ "red_sea": {"status_score": 2},
+ "asia_europe": {"status_score": 1}, # below threshold
+ }
+ },
+ "hotspots": {
+ "hotspots": [{"name": "gaza", "score": 82}, {"name": "oslo", "score": 10}]
+ },
+ "outages": {"outage_count": 7},
+ "shipping": {"stress_score": 65, "assessment": "severe"},
+}
+
+_QUIET_WORLD = {
+ "space": {"current_kp": 2.0, "kp_level": "Quiet"},
+ "instability": {"countries": [{"country_name": "Norway", "instability_index": 12}]},
+ "surge": {"surge_count": 0},
+ "cables": {"corridors": {"red_sea": {"status_score": 1}}},
+ "hotspots": {"hotspots": [{"name": "oslo", "score": 10}]},
+ "outages": {"outage_count": 2},
+ "shipping": {"stress_score": 10, "assessment": "normal"},
+}
+
+
+async def test_alert_digest_fires_on_every_threshold(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_digest_sources(monkeypatch, _STORMY_WORLD)
+ result = await fetch_alert_digest(fetcher)
+
+ assert result["alert_count"] == 7
+ assert result["by_priority"] == {"critical": 2, "high": 4, "medium": 1}
+ # Sorted critical > high > medium.
+ priorities = [a["priority"] for a in result["alerts"]]
+ assert priorities == sorted(
+ priorities, key={"critical": 0, "high": 1, "medium": 2}.get
+ )
+ assert priorities[0] == "critical"
+ assert priorities[-1] == "medium"
+
+ domains = {a["domain"] for a in result["alerts"]}
+ assert domains == {
+ "space",
+ "political",
+ "military",
+ "infrastructure",
+ "security",
+ "economic",
+ }
+ # Only the corridor at status_score >= 2 counts.
+ cable_alert = next(a for a in result["alerts"] if "corridors" in a)
+ assert cable_alert["corridors"] == ["red_sea"]
+ # Only the country at CII >= 70 counts.
+ instability_alert = next(a for a in result["alerts"] if "countries" in a)
+ assert instability_alert["countries"] == ["Sudan"]
+ # Shipping stress 65 escalates from medium to high.
+ shipping_alert = next(a for a in result["alerts"] if a["domain"] == "economic")
+ assert shipping_alert["priority"] == "high"
+
+
+async def test_alert_digest_quiet_world_is_silent(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The load-bearing negative: sub-threshold values must produce zero
+ alerts, otherwise the digest is noise."""
+ _patch_digest_sources(monkeypatch, _QUIET_WORLD)
+ result = await fetch_alert_digest(fetcher)
+ assert result["alert_count"] == 0
+ assert result["alerts"] == []
+ assert result["by_priority"] == {}
+ assert len(result["domains_checked"]) == 7
+
+
+async def test_alert_digest_moderate_shipping_stress_is_medium(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ payloads = dict(_QUIET_WORLD)
+ payloads["shipping"] = {"stress_score": 40, "assessment": "elevated"}
+ _patch_digest_sources(monkeypatch, payloads)
+ result = await fetch_alert_digest(fetcher)
+ assert result["alert_count"] == 1
+ assert result["alerts"][0]["domain"] == "economic"
+ assert result["alerts"][0]["priority"] == "medium"
+
+
+# ---------------------------------------------------------------------------
+# Weekly trends
+# ---------------------------------------------------------------------------
+
+
+def _seed_baselines(db_path: Path, rows: list[tuple]) -> None:
+ conn = sqlite3.connect(db_path)
+ conn.execute(
+ """CREATE TABLE baselines (
+ key TEXT PRIMARY KEY,
+ count INTEGER NOT NULL DEFAULT 0,
+ mean REAL NOT NULL DEFAULT 0.0,
+ m2 REAL NOT NULL DEFAULT 0.0,
+ updated_at TEXT NOT NULL
+ )"""
+ )
+ conn.executemany("INSERT INTO baselines VALUES (?, ?, ?, ?, ?)", rows)
+ conn.commit()
+ conn.close()
+
+
+async def test_weekly_trends_computes_volatility(
+ fetcher, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ db = tmp_path / "baselines.db"
+ ts = "2026-08-31T00:00:00+00:00"
+ _seed_baselines(
+ db,
+ [
+ # n=10, mean=20, M2=900: variance 100, std 10, cv 50.0
+ ("conflict:UKR:Monday:January", 10, 20.0, 900.0, ts),
+ # n=6, mean=5, M2=20: variance 4, std 2, cv 40.0
+ ("outage:EGY", 6, 5.0, 20.0, ts),
+ # Below the count>=5 floor: excluded.
+ ("quake:JPN", 3, 9.0, 10.0, ts),
+ # Malformed key without a region: skipped.
+ ("nocolon", 9, 1.0, 1.0, ts),
+ ],
+ )
+ monkeypatch.setattr(temporal, "_DB_PATH", str(db))
+ monkeypatch.setattr(
+ intelligence,
+ "fetch_temporal_anomalies",
+ _make_fake({"anomalies": [{"key": "conflict:UKR", "z_score": 3.0}]}),
+ )
+
+ result = await fetch_weekly_trends(fetcher)
+ assert result["trend_count"] == 2
+ # Sorted by volatility descending.
+ assert [t["volatility_cv"] for t in result["trends"]] == [50.0, 40.0]
+ top = result["trends"][0]
+ assert top["metric"] == "conflict"
+ assert top["region"] == "UKR"
+ assert top["weekday"] == "Monday"
+ assert top["month"] == "January"
+ assert top["mean"] == 20.0
+ assert top["std_dev"] == 10.0
+ assert top["observations"] == 10
+ # A key without weekday/month parts still parses.
+ assert result["trends"][1]["weekday"] == ""
+ assert result["current_anomaly_count"] == 1
+
+
+async def test_weekly_trends_missing_database_degrades_gracefully(
+ fetcher, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(temporal, "_DB_PATH", str(tmp_path / "does_not_exist.db"))
+ monkeypatch.setattr(intelligence, "fetch_temporal_anomalies", _make_fake({}))
+ result = await fetch_weekly_trends(fetcher)
+ assert result["trends"] == []
+ assert result["trend_count"] == 0
+ assert result["current_anomalies"] == []
diff --git a/src/world_intel_mcp/tests/test_cascade.py b/src/world_intel_mcp/tests/test_cascade.py
new file mode 100644
index 0000000..10b91cc
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_cascade.py
@@ -0,0 +1,91 @@
+"""Tests for analysis/cascade.py — infrastructure cascade simulation.
+
+Expected losses come straight from the module's CABLE_DEPENDENCIES table
+(e.g. red_sea: Djibouti 0.8, Egypt 0.5, Saudi Arabia 0.3).
+"""
+
+from world_intel_mcp.analysis.cascade import simulate_cascade
+
+
+def _impact_for(result: dict, country: str) -> dict:
+ return next(c for c in result["country_impacts"] if c["country"] == country)
+
+
+def test_single_corridor_full_disruption() -> None:
+ result = simulate_cascade(["red_sea"])
+ assert result["disrupted"] == ["red_sea"]
+
+ djibouti = _impact_for(result, "Djibouti")
+ assert djibouti["total_capacity_loss"] == 0.8
+ assert djibouti["impact_score"] == 80
+ assert djibouti["risk_level"] == "critical"
+ assert djibouti["affected_corridors"] == ["red_sea"]
+
+ # Sorted by impact descending: Djibouti (0.8) leads.
+ assert result["country_impacts"][0]["country"] == "Djibouti"
+ assert _impact_for(result, "Egypt")["risk_level"] == "high" # 50
+ assert _impact_for(result, "Sudan")["risk_level"] == "moderate" # 30
+ # A single-corridor disruption produces no cascading risks.
+ assert result["cascading_risks"] == []
+
+
+def test_low_risk_tier() -> None:
+ result = simulate_cascade(["transpacific"])
+ us = _impact_for(result, "United States")
+ assert us["impact_score"] == 10
+ assert us["risk_level"] == "low"
+
+
+def test_unknown_corridor_is_ignored() -> None:
+ result = simulate_cascade(["atlantis_cable"])
+ assert result["disrupted"] == []
+ assert result["country_impacts"] == []
+ assert result["cascading_risks"] == []
+
+
+def test_empty_input() -> None:
+ result = simulate_cascade([])
+ assert result == {"disrupted": [], "country_impacts": [], "cascading_risks": []}
+
+
+def test_health_status_scales_severity() -> None:
+ # status_score 1 (advisory) scales the simulated disruption by 0.8.
+ advisory = simulate_cascade(
+ ["red_sea"], current_health={"red_sea": {"status_score": 1}}
+ )
+ assert _impact_for(advisory, "Djibouti")["total_capacity_loss"] == 0.64
+
+ at_risk = simulate_cascade(
+ ["red_sea"], current_health={"red_sea": {"status_score": 2}}
+ )
+ assert _impact_for(at_risk, "Djibouti")["total_capacity_loss"] == 0.72
+
+ # Already-disrupted (3) and clear (0) corridors both simulate at 1.0.
+ for status in (0, 3):
+ full = simulate_cascade(
+ ["red_sea"], current_health={"red_sea": {"status_score": status}}
+ )
+ assert _impact_for(full, "Djibouti")["total_capacity_loss"] == 0.8
+
+
+def test_multi_corridor_losses_accumulate_and_cascades_flagged() -> None:
+ result = simulate_cascade(["red_sea", "asia_europe"])
+
+ # Saudi Arabia depends on both: 0.3 + 0.35 = 0.65.
+ saudi = _impact_for(result, "Saudi Arabia")
+ assert saudi["total_capacity_loss"] == 0.65
+ assert set(saudi["affected_corridors"]) == {"red_sea", "asia_europe"}
+ assert saudi["risk_level"] == "critical"
+
+ descriptions = [r["description"] for r in result["cascading_risks"]]
+ # Multi-corridor country risk plus two waterway chokes (Suez Canal and
+ # Bab-el-Mandeb both carry red_sea + asia_europe).
+ assert any("Multi-corridor disruption" in d for d in descriptions)
+ assert any("Suez Canal" in d for d in descriptions)
+ assert any("Bab-el-Mandeb" in d for d in descriptions)
+ multi = next(
+ r for r in result["cascading_risks"] if "Multi-corridor" in r["description"]
+ )
+ assert "Saudi Arabia" in multi["countries_affected"]
+ # Egypt sits on only one of the disrupted corridors.
+ assert "Egypt" not in multi["countries_affected"]
diff --git a/src/world_intel_mcp/tests/test_classifier.py b/src/world_intel_mcp/tests/test_classifier.py
new file mode 100644
index 0000000..3bc9ccc
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_classifier.py
@@ -0,0 +1,108 @@
+"""Tests for analysis/classifier.py — keyword threat classification.
+
+Pure-function tests with realistic headlines. Each positive case is paired
+with a negative (a text that must NOT trigger the same outcome) so a broken
+classifier cannot pass by over- or under-matching.
+"""
+
+from world_intel_mcp.analysis.classifier import (
+ CATEGORIES,
+ classify_event,
+ fetch_classify_event,
+)
+
+# Three military keywords ("troops", "artillery", "frontline"), no severity
+# modifiers, and no keywords from any other category.
+_MILITARY_TEXT = "Russian troops shelled the frontline with artillery near the border"
+
+# No category keyword or severity modifier appears anywhere in this text.
+_BENIGN_TEXT = "The bakery unveiled a fresh sourdough recipe on Sunday"
+
+
+def test_military_headline_classified() -> None:
+ result = classify_event(_MILITARY_TEXT)
+ assert result["primary_category"] == "military"
+ assert (
+ result["severity"] == CATEGORIES["military"]["severity_base"]
+ ) # 8, no modifiers
+ # 3 keyword hits -> confidence min(1.0, 3*0.2 + 0.3) = 0.9
+ assert result["confidence"] == 0.9
+ assert result["category_count"] == 1
+ assert result["severity_modifiers"] == []
+ matched = result["all_categories"][0]["keywords"]
+ assert "troops" in matched
+ assert "frontline" in matched
+ assert result["source"] == "keyword-classifier"
+
+
+def test_benign_text_is_unclassified() -> None:
+ """The load-bearing negative: a classifier that fires on everything
+ proves nothing when it fires on a real threat."""
+ result = classify_event(_BENIGN_TEXT)
+ assert result["primary_category"] == "unclassified"
+ assert result["severity"] == 0
+ assert result["confidence"] == 0.0
+ assert result["all_categories"] == []
+ assert result["category_count"] == 0
+ assert result["severity_modifiers"] == []
+
+
+def test_high_severity_modifier_and_cap_at_ten() -> None:
+ # 4 nuclear keywords; "nuclear" is also a high-severity modifier (+2),
+ # so 9 + 2 must cap at 10.
+ result = classify_event("IAEA warns of uranium enrichment at nuclear facility")
+ assert result["primary_category"] == "nuclear"
+ assert result["severity"] == 10
+ assert result["confidence"] == 1.0 # 4 hits saturates the scale
+ assert "nuclear" in result["severity_modifiers"]
+
+
+def test_moderate_severity_modifier_adds_one() -> None:
+ # Maritime base 5, "attack" is a moderate modifier -> 6.
+ result = classify_event("Piracy attack on a cargo ship near the strait")
+ assert result["primary_category"] == "maritime"
+ assert result["severity"] == 6
+ assert result["severity_modifiers"] == ["attack"]
+
+
+def test_high_modifier_wins_over_moderate_no_stacking() -> None:
+ # Both "killed" (high, +2) and "attack" (moderate, +1) appear; the
+ # bumps must not stack: maritime base 5 + 2 = 7, not 8.
+ result = classify_event("Piracy attack near the strait killed three seafarers")
+ assert result["primary_category"] == "maritime"
+ assert result["severity"] == 7
+ assert "killed" in result["severity_modifiers"]
+ assert "attack" in result["severity_modifiers"]
+
+
+def test_primary_category_is_most_keyword_hits() -> None:
+ # cyber matches 2 keywords ("ransomware", "hack"), maritime 1 ("port").
+ result = classify_event("Ransomware hack hits port operators")
+ assert result["primary_category"] == "cyber"
+ assert result["severity"] == CATEGORIES["cyber"]["severity_base"]
+ cats = [c["category"] for c in result["all_categories"]]
+ assert cats[0] == "cyber"
+ assert "maritime" in cats
+ assert result["category_count"] == 2
+
+
+def test_single_keyword_confidence_floor() -> None:
+ # 1 hit -> min(1.0, 0.2 + 0.3) = 0.5
+ result = classify_event("The satellite mission was a success")
+ assert result["primary_category"] == "space"
+ assert result["confidence"] == 0.5
+ assert result["severity"] == CATEGORIES["space"]["severity_base"]
+
+
+def test_classification_is_case_insensitive() -> None:
+ upper = classify_event(_MILITARY_TEXT.upper())
+ assert upper["primary_category"] == "military"
+ assert upper["confidence"] == 0.9
+
+
+async def test_fetch_classify_event_wraps_sync_classifier() -> None:
+ result = await fetch_classify_event(None, _MILITARY_TEXT)
+ direct = classify_event(_MILITARY_TEXT)
+ assert result["primary_category"] == direct["primary_category"]
+ assert result["severity"] == direct["severity"]
+ assert result["confidence"] == direct["confidence"]
diff --git a/src/world_intel_mcp/tests/test_clustering.py b/src/world_intel_mcp/tests/test_clustering.py
new file mode 100644
index 0000000..d58e28d
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_clustering.py
@@ -0,0 +1,134 @@
+"""Tests for analysis/clustering.py — Jaccard news clustering.
+
+Similarity values in comments are hand-computed from the token sets after
+stopword removal (e.g. "new" is a stopword and must not count).
+"""
+
+import pytest
+
+from world_intel_mcp.analysis.clustering import (
+ cluster_articles,
+ fetch_news_clusters,
+ jaccard_similarity,
+)
+from world_intel_mcp.sources import news
+
+
+def test_jaccard_identical_sets() -> None:
+ assert jaccard_similarity({"a", "b", "c"}, {"a", "b", "c"}) == 1.0
+
+
+def test_jaccard_disjoint_sets() -> None:
+ assert jaccard_similarity({"a", "b"}, {"c", "d"}) == 0.0
+
+
+def test_jaccard_partial_overlap() -> None:
+ # {a,b} vs {b,c}: intersection 1, union 3.
+ assert jaccard_similarity({"a", "b"}, {"b", "c"}) == pytest.approx(1 / 3)
+
+
+def test_jaccard_empty_set_is_zero() -> None:
+ assert jaccard_similarity(set(), {"a"}) == 0.0
+ assert jaccard_similarity({"a"}, set()) == 0.0
+
+
+def test_similar_titles_cluster_dissimilar_stay_apart() -> None:
+ """The load-bearing pair: near-duplicates merge, the unrelated story
+ does not get pulled in."""
+ articles = [
+ {"title": "Russia launches missile strikes on Kyiv energy grid"},
+ # Token overlap 6/7 with the first title ("new" is a stopword).
+ {"title": "Russia launches new missile strikes on Kyiv grid"},
+ {"title": "Chocolate festival delights visitors in Belgium"},
+ ]
+ clusters = cluster_articles(articles, similarity_threshold=0.3)
+ assert len(clusters) == 2
+ # Sorted by member count: the pair first.
+ assert clusters[0]["member_count"] == 2
+ assert clusters[0]["member_indices"] == [0, 1]
+ assert clusters[0]["representative"] is articles[0]
+ assert clusters[1]["member_count"] == 1
+ assert clusters[1]["representative"] is articles[2]
+
+
+def test_threshold_boundary_is_inclusive() -> None:
+ # {border,camps,flood} vs {border,camps,burn}: J = 2/4 = 0.5 exactly.
+ articles = [
+ {"title": "border camps flood"},
+ {"title": "border camps burn"},
+ ]
+ merged = cluster_articles(articles, similarity_threshold=0.5)
+ assert merged[0]["member_count"] == 2 # sim >= threshold merges
+ split = cluster_articles(articles, similarity_threshold=0.51)
+ assert all(c["member_count"] == 1 for c in split)
+
+
+def test_empty_input_returns_empty_list() -> None:
+ assert cluster_articles([]) == []
+
+
+def test_missing_or_none_titles_become_singletons() -> None:
+ articles = [{"title": None}, {}, {"title": "Real headline about earthquakes"}]
+ clusters = cluster_articles(articles)
+ assert len(clusters) == 3
+ assert all(c["member_count"] == 1 for c in clusters)
+
+
+def test_custom_title_field() -> None:
+ articles = [
+ {"headline": "Drought grips southern Europe farms"},
+ {"headline": "Drought grips southern Europe vineyards"},
+ ]
+ clusters = cluster_articles(articles, title_field="headline")
+ assert clusters[0]["member_count"] == 2
+
+
+async def test_fetch_news_clusters_reports_clusters_and_singletons(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ items = [
+ {
+ "title": "Russia launches missile strikes on Kyiv energy grid",
+ "source_name": "BBC",
+ "link": "https://example.com/1",
+ },
+ {
+ "title": "Russia missile strikes hit Kyiv grid overnight",
+ "source": "Reuters",
+ "link": "https://example.com/2",
+ },
+ {
+ "title": "Missile strikes on Kyiv grid continue as Russia presses",
+ "source_name": "BBC",
+ "link": "https://example.com/3",
+ },
+ {"title": "Chocolate festival delights visitors in Brussels"},
+ {"title": "Quantum computing startup raises funding round"},
+ ]
+
+ async def _fake_feed(fetcher, category=None, limit=100):
+ return {"items": items}
+
+ monkeypatch.setattr(news, "fetch_news_feed", _fake_feed)
+ result = await fetch_news_clusters(fetcher)
+
+ # Only multi-member clusters are surfaced; the two unrelated stories
+ # are counted as singletons, not clusters.
+ assert result["cluster_count"] == 1
+ assert result["singleton_count"] == 2
+ assert result["total_items"] == 5
+ assert result["threshold"] == 0.25
+ assert result["source"] == "jaccard-clustering"
+
+ cluster = result["clusters"][0]
+ assert cluster["size"] == 3
+ assert cluster["headline"] == items[0]["title"]
+ assert "kyiv" in cluster["keywords"]
+ assert "missile" in cluster["keywords"]
+ assert sorted(cluster["sources"]) == ["BBC", "Reuters"]
+ assert len(cluster["items"]) == 3
+ assert cluster["items"][0] == {
+ "title": items[0]["title"],
+ "source": "BBC",
+ "link": "https://example.com/1",
+ }
diff --git a/src/world_intel_mcp/tests/test_collector.py b/src/world_intel_mcp/tests/test_collector.py
new file mode 100644
index 0000000..02cf1cb
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_collector.py
@@ -0,0 +1,55 @@
+"""Tests for collector.py's source map.
+
+The collector daemon dynamically imports every fetch function it feeds
+the vector store from string references in ``SOURCES``. Nothing else
+executes those references: a renamed or deleted fetch function would
+break the 24/7 collector at runtime while the whole test suite stayed
+green. This file makes that class of drift a test failure instead.
+"""
+
+import inspect
+
+from world_intel_mcp import collector
+
+
+def test_sources_count_matches_docs() -> None:
+ # CLAUDE.md and the collector docstring both say 46; measured here.
+ assert len(collector.SOURCES) == 46
+
+
+def test_source_names_unique() -> None:
+ names = [name for name, _, _, _ in collector.SOURCES]
+ assert len(names) == len(set(names))
+
+
+def test_every_source_reference_resolves_to_an_async_fetcher() -> None:
+ """The load-bearing check: every (module, function) string pair in
+ SOURCES imports and is an async callable taking ``fetcher`` first."""
+ for name, module_path, fn_name, kwargs in collector.SOURCES:
+ fn = collector._import_fetch_fn(module_path, fn_name)
+ assert callable(fn), f"{name}: {module_path}.{fn_name} not callable"
+ assert inspect.iscoroutinefunction(fn), (
+ f"{name}: {module_path}.{fn_name} is not async"
+ )
+ params = list(inspect.signature(fn).parameters)
+ assert params and params[0] == "fetcher", (
+ f"{name}: {module_path}.{fn_name} does not take fetcher first"
+ )
+ assert isinstance(kwargs, dict), f"{name}: kwargs must be a dict"
+
+
+def test_every_source_kwarg_is_accepted_by_its_function() -> None:
+ """A typo'd kwarg in SOURCES would raise TypeError at collection
+ time in production; catch it here instead."""
+ for name, module_path, fn_name, kwargs in collector.SOURCES:
+ fn = collector._import_fetch_fn(module_path, fn_name)
+ sig = inspect.signature(fn)
+ accepts_var_kw = any(
+ p.kind is inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()
+ )
+ if accepts_var_kw:
+ continue
+ for kw in kwargs:
+ assert kw in sig.parameters, (
+ f"{name}: {module_path}.{fn_name} does not accept kwarg {kw!r}"
+ )
diff --git a/src/world_intel_mcp/tests/test_convergence.py b/src/world_intel_mcp/tests/test_convergence.py
new file mode 100644
index 0000000..599ef4a
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_convergence.py
@@ -0,0 +1,114 @@
+"""Tests for analysis/convergence.py — geographic multi-domain convergence.
+
+Pure grid math: expected scores are computed by hand from the documented
+formula ``type_count * (1 + sqrt(events)) * (total_weight / events)``.
+"""
+
+from world_intel_mcp.analysis.convergence import detect_convergence
+
+
+def _cell_events() -> list[dict]:
+ """Three events, two domains, all inside the 1-degree cell (10, 20)."""
+ return [
+ {"lat": 10.2, "lon": 20.3, "type": "conflict"},
+ {"lat": 10.4, "lon": 20.6, "type": "military"},
+ {"lat": 10.8, "lon": 20.9, "type": "conflict"},
+ ]
+
+
+def test_detects_multi_domain_cell_and_ignores_others() -> None:
+ """The load-bearing triple: a qualifying cell is reported; a monotype
+ cell and an under-populated cell are not."""
+ events = _cell_events() + [
+ # Three events of a single type: fails min_types=2.
+ {"lat": 40.1, "lon": 50.1, "type": "fire"},
+ {"lat": 40.2, "lon": 50.2, "type": "fire"},
+ {"lat": 40.3, "lon": 50.3, "type": "fire"},
+ # Two events of two types: fails min_total=3.
+ {"lat": 60.2, "lon": 70.2, "type": "conflict"},
+ {"lat": 60.3, "lon": 70.3, "type": "military"},
+ ]
+ hotspots = detect_convergence(events)
+ assert len(hotspots) == 1
+ hs = hotspots[0]
+ assert hs["lat"] == 10.5 # cell center
+ assert hs["lon"] == 20.5
+ assert hs["event_count"] == 3
+ assert hs["signal_types"] == ["conflict", "military"]
+ assert hs["type_count"] == 2
+ assert hs["total_weight"] == 3.0 # default weight 1.0 each
+ # 2 * (1 + sqrt(3)) * (3/3) = 5.4641...
+ assert hs["convergence_score"] == 5.46
+
+
+def test_invalid_coordinates_are_skipped_numeric_strings_accepted() -> None:
+ events = _cell_events() + [
+ {"lat": None, "lon": 20.5, "type": "conflict"},
+ {"lon": 20.5, "type": "conflict"}, # missing lat
+ {"lat": "not-a-number", "lon": 20.5, "type": "conflict"},
+ # Numeric strings must count: float("10.4") is valid.
+ {"lat": "10.4", "lon": "20.5", "type": "outage"},
+ ]
+ hotspots = detect_convergence(events)
+ assert len(hotspots) == 1
+ assert hotspots[0]["event_count"] == 4 # 3 base + the string-coord event
+ assert "outage" in hotspots[0]["signal_types"]
+
+
+def test_weights_scale_the_score() -> None:
+ events = [
+ {"lat": 10.1, "lon": 20.1, "type": "conflict", "weight": 2.0},
+ {"lat": 10.2, "lon": 20.2, "type": "military", "weight": 1.0},
+ {"lat": 10.3, "lon": 20.3, "type": "conflict", "weight": 3.0},
+ ]
+ hotspots = detect_convergence(events)
+ assert hotspots[0]["total_weight"] == 6.0
+ # 2 * (1 + sqrt(3)) * (6/3) = 10.928...
+ assert hotspots[0]["convergence_score"] == 10.93
+
+
+def test_resolution_controls_grouping() -> None:
+ # Spread over ~4 degrees: separate 1-degree cells, one 5-degree cell.
+ events = [
+ {"lat": 10.5, "lon": 20.5, "type": "conflict"},
+ {"lat": 12.5, "lon": 22.5, "type": "military"},
+ {"lat": 14.4, "lon": 24.4, "type": "conflict"},
+ ]
+ assert detect_convergence(events, resolution=1.0) == []
+ coarse = detect_convergence(events, resolution=5.0)
+ assert len(coarse) == 1
+ # Cell (2, 4) at resolution 5 -> center ((2+0.5)*5, (4+0.5)*5).
+ assert coarse[0]["lat"] == 12.5
+ assert coarse[0]["lon"] == 22.5
+
+
+def test_negative_coordinates_use_floor_not_truncation() -> None:
+ """floor(-0.2) is -1; int() truncation toward zero would put these
+ events in the wrong cell and report center 0.5 instead of -0.5."""
+ events = [
+ {"lat": -0.2, "lon": -0.3, "type": "conflict"},
+ {"lat": -0.4, "lon": -0.6, "type": "military"},
+ {"lat": -0.9, "lon": -0.9, "type": "conflict"},
+ ]
+ hotspots = detect_convergence(events)
+ assert len(hotspots) == 1
+ assert hotspots[0]["lat"] == -0.5
+ assert hotspots[0]["lon"] == -0.5
+
+
+def test_hotspots_sorted_by_score_descending() -> None:
+ strong = [
+ {"lat": 30.1 + i * 0.1, "lon": 40.1, "type": t}
+ for i, t in enumerate(["conflict", "military", "fire", "conflict"])
+ ]
+ weak = _cell_events()
+ hotspots = detect_convergence(strong + weak)
+ assert len(hotspots) == 2
+ # strong: 3 * (1 + sqrt(4)) * 1 = 9.0 beats weak's 5.46
+ assert hotspots[0]["convergence_score"] == 9.0
+ assert hotspots[0]["lat"] == 30.5
+ assert hotspots[0]["convergence_score"] > hotspots[1]["convergence_score"]
+
+
+def test_empty_input_returns_empty_list() -> None:
+ assert detect_convergence([]) == []
diff --git a/src/world_intel_mcp/tests/test_entities.py b/src/world_intel_mcp/tests/test_entities.py
new file mode 100644
index 0000000..1c76c31
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_entities.py
@@ -0,0 +1,139 @@
+"""Tests for analysis/entities.py — regex NER over config reference data.
+
+Fixtures use names that actually exist in config/countries.py and
+config/entities.py, so the tests exercise the real lookup tables rather
+than a parallel synthetic dataset. The news-path wrapper is tested by
+monkeypatching at the source-function boundary (pattern from test_aoi.py).
+"""
+
+import pytest
+
+from world_intel_mcp.analysis.entities import extract_entities, fetch_entity_extraction
+from world_intel_mcp.sources import news
+
+
+def _iso3s(result: dict) -> set[str]:
+ return {c["iso3"] for c in result["entities"]["countries"]}
+
+
+def test_countries_extracted_by_keyword_capital_and_excluded_when_absent() -> None:
+ result = extract_entities(
+ "Russia struck targets across Ukraine while Beijing watched"
+ )
+ assert _iso3s(result) == {"RUS", "UKR", "CHN"} # "beijing" maps to CHN
+ # The load-bearing exclusion: countries never mentioned must not appear.
+ assert "USA" not in _iso3s(result)
+ rus = next(c for c in result["entities"]["countries"] if c["iso3"] == "RUS")
+ assert rus["name"] == "Russia"
+ assert rus["baseline_risk"] == 55 # from config/countries.py
+
+
+def test_country_mentioned_multiple_ways_deduplicated() -> None:
+ result = extract_entities("Russian forces near Moscow, Russia")
+ assert _iso3s(result) == {"RUS"}
+ assert result["by_type"]["countries"] == 1
+
+
+def test_leaders_extracted_with_variant_dedup() -> None:
+ result = extract_entities("President Vladimir Putin met Xi Jinping in Beijing")
+ names = {ldr["name"] for ldr in result["entities"]["leaders"]}
+ # "vladimir putin" must not also emit a second entry via the "putin"
+ # variant, nor "xi jinping" via "xi".
+ assert names == {"Vladimir Putin", "Xi Jinping"}
+ putin = next(
+ l for l in result["entities"]["leaders"] if l["name"] == "Vladimir Putin"
+ )
+ assert putin["country"] == "RUS"
+ assert putin["title"] == "President"
+
+
+def test_short_org_abbreviations_require_word_boundary() -> None:
+ # "un" appears inside "tribunal" and "announced" but never as a word.
+ result = extract_entities("The tribunal announced sanctions on shipping firms")
+ assert result["entities"]["organizations"] == []
+
+ result = extract_entities("The UN and NATO convened")
+ names = {o["name"] for o in result["entities"]["organizations"]}
+ assert names == {"UN", "NATO"}
+ nato = next(o for o in result["entities"]["organizations"] if o["name"] == "NATO")
+ assert nato["type"] == "military_alliance"
+
+
+def test_org_long_form_and_abbreviation_deduplicated() -> None:
+ result = extract_entities("The UN said the United Nations would act")
+ assert result["by_type"]["organizations"] == 1
+ assert result["entities"]["organizations"][0]["name"] == "UN"
+
+
+def test_companies_extracted_with_ticker_and_sector() -> None:
+ result = extract_entities("Lockheed Martin and NVIDIA won new contracts")
+ companies = {c["name"]: c for c in result["entities"]["companies"]}
+ assert set(companies) == {"Lockheed Martin", "Nvidia"}
+ assert companies["Lockheed Martin"]["ticker"] == "LMT"
+ assert companies["Lockheed Martin"]["sector"] == "defense"
+ assert companies["Nvidia"]["ticker"] == "NVDA"
+
+
+def test_cves_deduplicated_and_case_insensitive() -> None:
+ result = extract_entities(
+ "Patch CVE-2024-3400 now; CVE-2024-3400 is exploited alongside CVE-2023-23397"
+ )
+ assert set(result["entities"]["cves"]) == {"CVE-2024-3400", "CVE-2023-23397"}
+ assert result["by_type"]["cves"] == 2
+
+ lowercase = extract_entities("cve-2025-1234 disclosed today")
+ assert lowercase["entities"]["cves"] == ["cve-2025-1234"]
+
+
+def test_apt_groups_extracted_lowercased() -> None:
+ result = extract_entities("APT29 and Cozy Bear ran a campaign; Lazarus was quiet")
+ assert set(result["entities"]["apt_groups"]) == {"apt29", "cozy bear", "lazarus"}
+ # Sandworm exists in the dataset but is not in the text.
+ assert "sandworm" not in result["entities"]["apt_groups"]
+
+
+def test_empty_text_yields_no_entities() -> None:
+ result = extract_entities("")
+ assert result["total_entities"] == 0
+ assert all(count == 0 for count in result["by_type"].values())
+ assert result["source"] == "regex-ner"
+
+
+def test_total_entities_matches_by_type_sum() -> None:
+ result = extract_entities(
+ "Putin discussed CVE-2024-3400 with NATO officials in Russia"
+ )
+ assert result["total_entities"] == sum(result["by_type"].values())
+ assert result["total_entities"] == 4 # RUS + Putin + NATO + one CVE
+
+
+async def test_fetch_entity_extraction_with_text(fetcher) -> None:
+ result = await fetch_entity_extraction(fetcher, text="Putin visited Russia")
+ assert _iso3s(result) == {"RUS"}
+ assert "input_source" not in result # direct text path, not news
+
+
+async def test_fetch_entity_extraction_from_news_feed(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _fake_feed(fetcher, limit=100, category=None):
+ return {
+ "items": [
+ {"title": "Putin visits Beijing", "summary": "talks with Xi Jinping"},
+ {"title": "New CVE-2026-0001 exploited", "summary": ""},
+ ]
+ }
+
+ monkeypatch.setattr(news, "fetch_news_feed", _fake_feed)
+ result = await fetch_entity_extraction(fetcher, text=None, use_news=True)
+ assert result["input_source"] == "news_feed"
+ assert result["items_analyzed"] == 2
+ assert "CHN" in _iso3s(result)
+ names = {l["name"] for l in result["entities"]["leaders"]}
+ assert names == {"Vladimir Putin", "Xi Jinping"}
+ assert result["entities"]["cves"] == ["CVE-2026-0001"]
+
+
+async def test_fetch_entity_extraction_no_text_no_news(fetcher) -> None:
+ result = await fetch_entity_extraction(fetcher, text=None, use_news=False)
+ assert result["total_entities"] == 0
diff --git a/src/world_intel_mcp/tests/test_exposure.py b/src/world_intel_mcp/tests/test_exposure.py
new file mode 100644
index 0000000..629a40c
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_exposure.py
@@ -0,0 +1,185 @@
+"""Tests for analysis/exposure.py — population exposure near active events.
+
+Composition tests mock the three event sources at the source-function
+boundary and run against the real config/population.py city dataset
+(Tokyo 35.68/139.69, Cairo 30.04/31.24, Seoul 37.57/126.98).
+"""
+
+import pytest
+
+from world_intel_mcp.analysis.exposure import (
+ _find_exposed_cities,
+ _format_pop,
+ fetch_population_exposure,
+)
+from world_intel_mcp.sources import conflict, seismology, wildfire
+
+
+def test_format_pop_tiers() -> None:
+ assert _format_pop(500) == "500"
+ assert _format_pop(45_000) == "45K"
+ assert _format_pop(2_500_000) == "2.5M"
+
+
+def test_find_exposed_cities_keeps_nearest_event_and_sorts() -> None:
+ cities = [
+ {"name": "Nearville", "country": "TST", "lat": 0.0, "lon": 0.0, "pop": 1000},
+ {"name": "Edgeton", "country": "TST", "lat": 0.6, "lon": 0.0, "pop": 2000},
+ {"name": "Farport", "country": "TST", "lat": 50.0, "lon": 50.0, "pop": 3000},
+ ]
+ events = [
+ {"lat": 0.5, "lon": 0.0, "type": "flood"}, # ~55.6 km from Nearville
+ {"lat": 0.1, "lon": 0.0, "type": "quake"}, # ~11.1 km from Nearville
+ {"lat": None, "lon": 0.0, "type": "broken"}, # skipped
+ ]
+ exposed = _find_exposed_cities(events, cities, radius_km=100.0)
+
+ names = [c["city"] for c in exposed]
+ assert "Farport" not in names # outside every radius
+ near = next(c for c in exposed if c["city"] == "Nearville")
+ # Both events are in range; the record must keep the CLOSER one.
+ assert near["nearest_event"] == "quake"
+ assert near["distance_km"] == pytest.approx(11.1, abs=0.2)
+ # Result sorted by distance ascending.
+ distances = [c["distance_km"] for c in exposed]
+ assert distances == sorted(distances)
+
+
+def _make_fake(payload: dict):
+ async def _fake(fetcher, *args, **kwargs):
+ return payload
+
+ return _fake
+
+
+async def test_population_exposure_across_three_domains(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ seismology,
+ "fetch_earthquakes",
+ _make_fake(
+ {
+ "earthquakes": [
+ {
+ "latitude": 35.68,
+ "longitude": 139.69,
+ "magnitude": 6.1,
+ "place": "near Tokyo",
+ }
+ ]
+ }
+ ),
+ )
+ monkeypatch.setattr(
+ wildfire,
+ "fetch_wildfires",
+ _make_fake(
+ {
+ "fires_by_region": {
+ "north_africa": {
+ "top_clusters": [
+ {
+ "lat": 30.04,
+ "lon": 31.24,
+ "max_frp": 500,
+ "fire_count": 12,
+ }
+ ]
+ }
+ }
+ }
+ ),
+ )
+ monkeypatch.setattr(
+ conflict,
+ "fetch_acled_events",
+ _make_fake(
+ {
+ "events": [
+ {
+ "latitude": 37.57,
+ "longitude": 126.98,
+ "event_type": "Battles",
+ "location": "Seoul",
+ }
+ ]
+ }
+ ),
+ )
+
+ result = await fetch_population_exposure(fetcher, radius_km=200.0)
+
+ assert result["events_analyzed"] == 3
+ assert result["radius_km"] == 200.0
+ assert result["event_types"] == ["conflict", "earthquake", "wildfire"]
+
+ by_city = {c["city"]: c for c in result["exposed_cities"]}
+ assert by_city["Tokyo"]["nearest_event"] == "earthquake"
+ assert by_city["Tokyo"]["distance_km"] == 0.0
+ assert by_city["Cairo"]["nearest_event"] == "wildfire"
+ assert by_city["Seoul"]["nearest_event"] == "conflict"
+
+ assert "JPN" in result["by_country"]
+ assert set(result["by_event_type"]) == {"earthquake", "wildfire", "conflict"}
+ # Tokyo alone is 37.4M, so the formatted total must be in millions.
+ assert result["total_exposed_population"] >= 37_400_000
+ assert result["total_exposed_population_formatted"].endswith("M")
+
+
+async def test_remote_event_exposes_no_cities(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The load-bearing negative: an event in the empty South Atlantic
+ must expose nobody."""
+ monkeypatch.setattr(
+ seismology,
+ "fetch_earthquakes",
+ _make_fake(
+ {"earthquakes": [{"latitude": -40.0, "longitude": -20.0, "magnitude": 5.5}]}
+ ),
+ )
+ monkeypatch.setattr(wildfire, "fetch_wildfires", _make_fake({}))
+ monkeypatch.setattr(conflict, "fetch_acled_events", _make_fake({}))
+
+ result = await fetch_population_exposure(fetcher, radius_km=200.0)
+ assert result["events_analyzed"] == 1
+ assert result["exposed_city_count"] == 0
+ assert result["total_exposed_population"] == 0
+ assert result["by_country"] == {}
+
+
+async def test_event_type_filter_skips_unrequested_sources(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ calls: list[str] = []
+
+ async def _recording(name: str):
+ async def _fake(fetcher, *args, **kwargs):
+ calls.append(name)
+ return {}
+
+ return _fake
+
+ monkeypatch.setattr(seismology, "fetch_earthquakes", await _recording("quake"))
+ monkeypatch.setattr(wildfire, "fetch_wildfires", await _recording("fire"))
+ monkeypatch.setattr(conflict, "fetch_acled_events", await _recording("conflict"))
+
+ result = await fetch_population_exposure(fetcher, event_types=["earthquake"])
+ assert result["event_types"] == ["earthquake"]
+ assert calls == ["quake"] # wildfire and conflict never fetched
+
+
+async def test_source_failure_degrades_to_empty(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _broken(fetcher, *args, **kwargs):
+ raise RuntimeError("upstream down")
+
+ monkeypatch.setattr(seismology, "fetch_earthquakes", _broken)
+ monkeypatch.setattr(wildfire, "fetch_wildfires", _make_fake({}))
+ monkeypatch.setattr(conflict, "fetch_acled_events", _make_fake({}))
+
+ result = await fetch_population_exposure(fetcher)
+ assert result["events_analyzed"] == 0
+ assert result["exposed_city_count"] == 0
diff --git a/src/world_intel_mcp/tests/test_focal_points.py b/src/world_intel_mcp/tests/test_focal_points.py
new file mode 100644
index 0000000..55c3f27
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_focal_points.py
@@ -0,0 +1,133 @@
+"""Tests for analysis/focal_points.py — entity signal convergence.
+
+Events without timestamps are treated as age zero (recency weight 1.0),
+which makes focal scores exactly computable:
+score = signal_count * (1 + type_diversity * 0.5) * mean_recency_weight.
+"""
+
+from datetime import datetime, timedelta, timezone
+
+from world_intel_mcp.analysis.focal_points import detect_focal_points
+
+
+def _iso_hours_ago(hours: float) -> str:
+ ts = datetime.now(timezone.utc) - timedelta(hours=hours)
+ return ts.isoformat().replace("+00:00", "Z")
+
+
+def test_min_signals_includes_pair_excludes_singleton() -> None:
+ """The load-bearing pair: two signals qualify, one does not."""
+ events = [
+ {"entity": "Iran", "type": "cyber"},
+ {"entity": "Iran", "type": "military"},
+ {"entity": "Norway", "type": "cyber"},
+ ]
+ result = detect_focal_points(events, min_signals=2)
+ assert [fp["entity"] for fp in result] == ["Iran"]
+ assert result[0]["signal_count"] == 2
+
+
+def test_min_signals_one_admits_singletons() -> None:
+ result = detect_focal_points([{"entity": "Norway", "type": "cyber"}], min_signals=1)
+ assert [fp["entity"] for fp in result] == ["Norway"]
+
+
+def test_entity_grouping_is_case_insensitive_display_keeps_first_casing() -> None:
+ events = [
+ {"entity": "Iran", "type": "cyber"},
+ {"entity": "iran", "type": "military"},
+ {"entity": "IRAN", "type": "maritime"},
+ ]
+ result = detect_focal_points(events)
+ assert len(result) == 1
+ assert result[0]["signal_count"] == 3
+ assert result[0]["entity"] == "Iran" # first event's casing
+
+
+def test_exact_focal_score_without_timestamps() -> None:
+ events = [
+ {"entity": "Strait of Hormuz", "type": "maritime", "country": "Iran"},
+ {"entity": "Strait of Hormuz", "type": "military", "country": "Oman"},
+ ]
+ result = detect_focal_points(events)
+ fp = result[0]
+ # 2 signals * (1 + 2 types * 0.5) * recency 1.0 = 4.0
+ assert fp["focal_score"] == 4.0
+ assert fp["signal_types"] == ["maritime", "military"]
+ assert fp["countries"] == ["Iran", "Oman"]
+ assert fp["urgency"] == "watch"
+
+
+def test_stale_events_are_discarded_and_can_disqualify_entity() -> None:
+ events = [
+ {"entity": "Iran", "type": "cyber", "timestamp": _iso_hours_ago(1)},
+ {"entity": "Iran", "type": "military", "timestamp": _iso_hours_ago(100)},
+ ]
+ # The stale event drops out, leaving 1 signal < min_signals=2.
+ assert detect_focal_points(events, min_signals=2, max_age_hours=48.0) == []
+ # With a wider window both events survive.
+ wide = detect_focal_points(events, min_signals=2, max_age_hours=200.0)
+ assert wide[0]["signal_count"] == 2
+
+
+def test_urgency_tiers() -> None:
+ events = (
+ [{"entity": "watchville", "type": "a"}] * 2
+ + [{"entity": "elevatia", "type": "a"}] * 5
+ + [{"entity": "criticalia", "type": "a"}] * 10
+ )
+ result = {fp["entity"]: fp["urgency"] for fp in detect_focal_points(events)}
+ assert result == {
+ "watchville": "watch",
+ "elevatia": "elevated",
+ "criticalia": "critical",
+ }
+
+
+def test_recent_events_capped_at_ten_and_internal_fields_stripped() -> None:
+ events = [{"entity": "Sudan", "type": "conflict", "id": i} for i in range(12)]
+ result = detect_focal_points(events)
+ fp = result[0]
+ assert fp["signal_count"] == 12
+ assert len(fp["recent_events"]) == 10
+ for ev in fp["recent_events"]:
+ assert not any(key.startswith("_") for key in ev)
+
+
+def test_events_without_entity_are_skipped() -> None:
+ assert detect_focal_points([{"type": "cyber"}, {"type": "military"}]) == []
+
+
+def test_sorted_by_focal_score_descending() -> None:
+ events = [{"entity": "busy", "type": t} for t in ["a", "b", "c", "a", "b", "c"]] + [
+ {"entity": "quiet", "type": "a"},
+ {"entity": "quiet", "type": "a"},
+ ]
+ result = detect_focal_points(events)
+ assert [fp["entity"] for fp in result] == ["busy", "quiet"]
+ # busy: 6 * (1 + 3*0.5) = 15.0; quiet: 2 * 1.5 = 3.0
+ assert result[0]["focal_score"] == 15.0
+ assert result[1]["focal_score"] == 3.0
+
+
+def test_timestamp_type_tolerance() -> None:
+ """datetime objects (aware and naive), unparseable strings, and junk
+ types must all be tolerated rather than crash or silently drop."""
+ now = datetime.now(timezone.utc)
+ events = [
+ {
+ "entity": "Red Sea",
+ "type": "maritime",
+ "timestamp": now - timedelta(hours=1),
+ },
+ {
+ "entity": "Red Sea",
+ "type": "military",
+ # Naive datetime is interpreted as UTC.
+ "timestamp": (now - timedelta(hours=2)).replace(tzinfo=None),
+ },
+ {"entity": "Red Sea", "type": "cyber", "timestamp": "not-a-date"},
+ {"entity": "Red Sea", "type": "conflict", "timestamp": 12345},
+ ]
+ result = detect_focal_points(events)
+ assert result[0]["signal_count"] == 4
diff --git a/src/world_intel_mcp/tests/test_instability.py b/src/world_intel_mcp/tests/test_instability.py
new file mode 100644
index 0000000..2c2e5a2
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_instability.py
@@ -0,0 +1,186 @@
+"""Tests for analysis/instability.py — Country Instability Index scorers.
+
+Expected values are hand-computed from the documented scoring curves
+(e.g. CII v2: weighted 0-25 components * 4, then multiplier, boosts,
+UCDP floor, and a 0-100 clamp).
+"""
+
+import pytest
+
+from world_intel_mcp.analysis.instability import (
+ compute_cii,
+ score_conflict_intensity,
+ score_conflict_v2,
+ score_economic_stress,
+ score_humanitarian_crisis,
+ score_information,
+ score_infrastructure_disruption,
+ score_military_activity,
+ score_security,
+ score_unrest,
+)
+
+# ---------------------------------------------------------------------------
+# v1 component scorers
+# ---------------------------------------------------------------------------
+
+
+def test_score_conflict_intensity_scales_and_caps() -> None:
+ assert score_conflict_intensity(0) == 0.0
+ assert score_conflict_intensity(150, days=30) == 10.0 # 5/day * 2
+ assert score_conflict_intensity(600, days=30) == 20.0 # capped
+
+
+def test_score_economic_stress_tiers() -> None:
+ assert score_economic_stress(None, None) == 0.0
+ assert score_economic_stress(25.0, -6.0) == 20.0 # 10 + 10
+ assert score_economic_stress(12.0, 0.5) == 8.0 # 5 + 3
+ assert score_economic_stress(6.0, 2.0) == 2.0 # 2 + 0
+ assert score_economic_stress(None, -3.0) == 7.0
+
+
+def test_score_humanitarian_crisis() -> None:
+ assert score_humanitarian_crisis(0) == 0.0
+ assert score_humanitarian_crisis(10) == 5.0
+ assert score_humanitarian_crisis(4, displacement_total=200_000) == 7.0
+ assert score_humanitarian_crisis(30, displacement_total=2_000_000) == 20.0
+
+
+def test_score_infrastructure_disruption() -> None:
+ assert score_infrastructure_disruption(0) == 0.0
+ assert score_infrastructure_disruption(3, cable_warnings=2) == 11.0
+ assert score_infrastructure_disruption(10, cable_warnings=10) == 20.0
+
+
+ "aircraft,expected",
+ [(0, 0.0), (3, 2.0), (8, 5.0), (15, 10.0), (30, 15.0), (60, 20.0)],
+)
+def test_score_military_activity_ladder(aircraft: int, expected: float) -> None:
+ assert score_military_activity(aircraft) == expected
+
+
+# ---------------------------------------------------------------------------
+# v2 component scorers (0-25)
+# ---------------------------------------------------------------------------
+
+
+def test_score_unrest() -> None:
+ assert score_unrest() == 0.0
+ assert score_unrest(protest_count=10, riot_count=4) == 5.0 # 3 + 2
+ assert score_unrest(protest_count=50, riot_count=20) == 25.0 # saturated
+
+
+def test_score_conflict_v2() -> None:
+ assert score_conflict_v2() == 0.0
+ assert score_conflict_v2(event_count=30, fatalities=200, days=30) == 3.0 # 1 + 2
+ assert score_conflict_v2(event_count=450, fatalities=1_000, days=30) == 25.0
+
+
+def test_score_security() -> None:
+ assert score_security() == 0.0
+ assert score_security(military_count=10, outage_count=1) == 4.0 # 2.4 + 1.6
+ assert score_security(military_count=50, outage_count=5, cable_warnings=3) == 25.0
+
+
+def test_score_information() -> None:
+ assert score_information() == 0.0
+ assert score_information(news_velocity=20, trending_count=4) == 5.0 # 3 + 2
+ assert score_information(news_velocity=100, trending_count=20) == 25.0
+
+
+# ---------------------------------------------------------------------------
+# compute_cii — v2 weighted path
+# ---------------------------------------------------------------------------
+
+
+def test_compute_cii_v2_weighted_index() -> None:
+ # 10*0.25 + 20*0.30 + 5*0.20 + 15*0.25 = 13.25; * 4 = 53.0
+ result = compute_cii(unrest=10, conflict=20, security=5, information=15)
+ assert result["instability_index"] == 53.0
+ assert result["risk_level"] == "high"
+ assert result["components"] == {
+ "unrest": 10,
+ "conflict": 20,
+ "security": 5,
+ "information": 15,
+ }
+ assert result["weights"]["conflict"] == 0.30
+
+
+def test_compute_cii_zero_is_low() -> None:
+ result = compute_cii()
+ assert result["instability_index"] == 0.0
+ assert result["risk_level"] == "low"
+
+
+def test_compute_cii_event_multiplier_and_cap() -> None:
+ boosted = compute_cii(
+ unrest=10, conflict=20, security=5, information=15, event_multiplier=1.5
+ )
+ assert boosted["instability_index"] == 79.5
+ assert boosted["risk_level"] == "critical"
+
+ capped = compute_cii(
+ unrest=25, conflict=25, security=25, information=25, event_multiplier=3.0
+ )
+ assert capped["instability_index"] == 100.0
+
+
+def test_compute_cii_boosts_are_additive() -> None:
+ result = compute_cii(
+ unrest=10,
+ conflict=20,
+ security=5,
+ information=15,
+ focal_boost=5.0,
+ displacement_boost=2.0,
+ )
+ assert result["instability_index"] == 60.0 # 53 + 5 + 2
+ assert result["focal_boost"] == 5.0
+ assert result["displacement_boost"] == 2.0
+
+
+def test_compute_cii_ucdp_floor_lifts_low_scores() -> None:
+ """An active war (UCDP floor) must not score near zero just because
+ live signal feeds are quiet."""
+ result = compute_cii(ucdp_floor=40.0)
+ assert result["instability_index"] == 40.0
+ assert result["risk_level"] == "medium"
+ assert result["ucdp_floor"] == 40.0
+ # The floor only lifts; it never drags a higher score down.
+ high = compute_cii(
+ unrest=25, conflict=25, security=25, information=25, ucdp_floor=40.0
+ )
+ assert high["instability_index"] == 100.0
+
+
+# ---------------------------------------------------------------------------
+# compute_cii — v1 backward-compat path
+# ---------------------------------------------------------------------------
+
+
+def test_compute_cii_v1_fallback_simple_sum() -> None:
+ result = compute_cii(
+ conflict=20.0,
+ economic=15.0,
+ humanitarian=10.0,
+ infrastructure=5.0,
+ military=20.0,
+ )
+ assert result["instability_index"] == 70.0
+ assert result["risk_level"] == "high"
+ # v1 responses carry the legacy component names and no weights.
+ assert result["components"]["conflict_intensity"] == 20.0
+ assert result["components"]["economic_stress"] == 15.0
+ assert "weights" not in result
+
+
+ "total,expected_level",
+ [(80.0, "critical"), (60.0, "high"), (30.0, "medium"), (10.0, "low")],
+)
+def test_compute_cii_v1_risk_tiers(total: float, expected_level: str) -> None:
+ result = compute_cii(conflict=total, economic=0.0)
+ assert result["instability_index"] == total
+ assert result["risk_level"] == expected_level
diff --git a/src/world_intel_mcp/tests/test_posture.py b/src/world_intel_mcp/tests/test_posture.py
new file mode 100644
index 0000000..968eb1d
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_posture.py
@@ -0,0 +1,187 @@
+"""Tests for analysis/posture.py — strategic posture composite.
+
+fetch_strategic_posture composes 11 source functions, so composition tests
+mock at the source-function boundary (pattern from test_aoi.py). The
+composite expectation is hand-computed from DOMAIN_WEIGHTS:
+0.18*32 + 0.16*80 + 0.16*80 + 0.10*30 + 0.10*40 + 0.08*20 + 0.07*40
++ 0.08*21 + 0.07*55 = 48.29 -> 48.3.
+"""
+
+import pytest
+
+from world_intel_mcp.analysis.posture import (
+ _risk_level,
+ fetch_strategic_posture,
+)
+from world_intel_mcp.sources import (
+ climate,
+ cyber,
+ health,
+ infrastructure,
+ intelligence,
+ military,
+ shipping,
+ space_weather,
+)
+
+
+ "score,level",
+ [
+ (80.0, "CRITICAL"),
+ (60.0, "HIGH"),
+ (40.0, "ELEVATED"),
+ (25.0, "GUARDED"),
+ (10.0, "LOW"),
+ ],
+)
+def test_risk_level_tiers(score: float, level: str) -> None:
+ assert _risk_level(score) == level
+
+
+def _make_fake(payload: dict):
+ async def _fake(fetcher, *args, **kwargs):
+ return payload
+
+ return _fake
+
+
+def _patch_all_sources(monkeypatch: pytest.MonkeyPatch, payloads: dict) -> None:
+ monkeypatch.setattr(
+ intelligence, "fetch_military_surge", _make_fake(payloads["surge"])
+ )
+ monkeypatch.setattr(
+ military, "fetch_theater_posture", _make_fake(payloads["theaters"])
+ )
+ monkeypatch.setattr(
+ intelligence, "fetch_instability_index", _make_fake(payloads["instability"])
+ )
+ monkeypatch.setattr(
+ intelligence, "fetch_hotspot_escalation", _make_fake(payloads["hotspots"])
+ )
+ monkeypatch.setattr(
+ infrastructure, "fetch_cable_health", _make_fake(payloads["cables"])
+ )
+ monkeypatch.setattr(
+ infrastructure, "fetch_internet_outages", _make_fake(payloads["outages"])
+ )
+ monkeypatch.setattr(
+ shipping, "fetch_shipping_index", _make_fake(payloads["shipping"])
+ )
+ monkeypatch.setattr(cyber, "fetch_cyber_threats", _make_fake(payloads["cyber"]))
+ monkeypatch.setattr(
+ health, "fetch_disease_outbreaks", _make_fake(payloads["health"])
+ )
+ monkeypatch.setattr(
+ climate, "fetch_climate_anomalies", _make_fake(payloads["climate"])
+ )
+ monkeypatch.setattr(
+ space_weather, "fetch_space_weather", _make_fake(payloads["space"])
+ )
+
+
+_ACTIVE_WORLD = {
+ # military: surge 20 + one active theater (>10 aircraft) 12 = 32
+ "surge": {
+ "surge_count": 1,
+ "surges": [{"region": "red_sea", "aircraft_count": 12}],
+ },
+ "theaters": {"theaters": {"middle_east": {"count": 20}, "arctic": {"count": 2}}},
+ # political: single country CII 80 -> avg 80
+ "instability": {
+ "countries": [
+ {"country_code": "SDN", "country_name": "Sudan", "instability_index": 80}
+ ]
+ },
+ # conflict: top-5 avg of (90 + 70) / 2 = 80
+ "hotspots": {
+ "hotspots": [{"name": "gaza", "score": 90}, {"name": "kyiv", "score": 70}]
+ },
+ # infrastructure: 1 at-risk corridor 15 + 3 outages * 5 = 30
+ "cables": {
+ "corridors": {
+ "red_sea": {"status_score": 2},
+ "transatlantic_north": {"status_score": 0},
+ }
+ },
+ "outages": {"outage_count": 3},
+ # economic: stress passthrough 40
+ "shipping": {"stress_score": 40, "assessment": "elevated"},
+ # cyber: 10 threats * 2 = 20
+ "cyber": {"threat_count": 10, "by_source": {"cisa": 6, "otx": 4}},
+ # health: 1 high-concern * 25 + 5 reports * 3 = 40
+ "health": {"count": 5, "high_concern_count": 1},
+ # climate: 1 extreme (>3C) * 15 + 2 anomalies * 3 = 21
+ "climate": {
+ "anomalies": [
+ {"zone": "arctic", "temp_deviation_c": 4.2},
+ {"zone": "sahel", "temp_deviation_c": 1.0},
+ ]
+ },
+ # space: Kp 5.0 * 11 = 55
+ "space": {"current_kp": 5.0, "kp_level": "Minor storm"},
+}
+
+
+async def test_posture_composite_weighted_from_all_domains(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_all_sources(monkeypatch, _ACTIVE_WORLD)
+ result = await fetch_strategic_posture(fetcher)
+
+ scores = {d: info["score"] for d, info in result["domain_scores"].items()}
+ assert scores == {
+ "military": 32.0,
+ "political": 80.0,
+ "conflict": 80.0,
+ "infrastructure": 30.0,
+ "economic": 40.0,
+ "cyber": 20.0,
+ "health": 40.0,
+ "climate": 21.0,
+ "space": 55.0,
+ }
+ assert result["composite_score"] == 48.3
+ assert result["risk_level"] == "ELEVATED"
+ assert result["domains_assessed"] == 9
+ assert result["domain_scores"]["political"]["level"] == "CRITICAL"
+
+ # Top threats come from the highest-scoring domains first.
+ assert result["top_threats"][0]["domain_score"] == 80.0
+ assert len(result["top_threats"]) <= 10
+ # Signals carry human-readable detail.
+ assert any("Sudan" in t["signal"] for t in result["top_threats"])
+
+
+async def test_posture_quiet_world_scores_zero(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Every source empty (the shape _safe() returns on failure): the
+ composite must be 0/LOW, not an exception or a phantom score."""
+ quiet = {key: {} for key in _ACTIVE_WORLD}
+ _patch_all_sources(monkeypatch, quiet)
+ result = await fetch_strategic_posture(fetcher)
+
+ assert result["composite_score"] == 0.0
+ assert result["risk_level"] == "LOW"
+ assert all(info["score"] == 0.0 for info in result["domain_scores"].values())
+ assert result["top_threats"] == []
+
+
+async def test_posture_survives_source_exception(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ payloads = dict(_ACTIVE_WORLD)
+ _patch_all_sources(monkeypatch, payloads)
+
+ async def _broken(fetcher, *args, **kwargs):
+ raise RuntimeError("upstream down")
+
+ monkeypatch.setattr(intelligence, "fetch_instability_index", _broken)
+ result = await fetch_strategic_posture(fetcher)
+
+ # The broken domain degrades to zero; the others still score.
+ assert result["domain_scores"]["political"]["score"] == 0.0
+ assert result["domain_scores"]["conflict"]["score"] == 80.0
+ # 48.29 - 0.16*80 = 35.49 -> 35.5, still ELEVATED.
+ assert result["composite_score"] == 35.5
diff --git a/src/world_intel_mcp/tests/test_server_registry.py b/src/world_intel_mcp/tests/test_server_registry.py
new file mode 100644
index 0000000..ac917cc
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_server_registry.py
@@ -0,0 +1,118 @@
+"""Import-based tests for server.py's tool registry and dispatcher.
+
+Every other test file reads server.py as *text* because importing it
+opens a live ``Cache()``/``AOIStore()`` at the default on-disk path.
+Here we import it for real, under a temp cache path
+(``WORLD_INTEL_CACHE_DB`` is honored by ``Cache`` before the module-level
+``cache = Cache()`` runs), which is what lets these tests verify the
+registry structurally instead of by regex: the TOOLS/_dispatch parity
+invariant, schema well-formedness, and the actual dispatch path for the
+pure (no-network) tools.
+"""
+
+import importlib
+import inspect
+import os
+import re
+import tempfile
+from pathlib import Path
+
+import pytest
+
+_TMP_CACHE = Path(tempfile.mkdtemp(prefix="wim-server-test-")) / "cache.db"
+
+
[email protected](scope="module")
+def server():
+ """Import server.py exactly once, cache pointed at a temp file."""
+ prior = os.environ.get("WORLD_INTEL_CACHE_DB")
+ os.environ["WORLD_INTEL_CACHE_DB"] = str(_TMP_CACHE)
+ try:
+ module = importlib.import_module("world_intel_mcp.server")
+ yield module
+ finally:
+ if prior is None:
+ os.environ.pop("WORLD_INTEL_CACHE_DB", None)
+ else:
+ os.environ["WORLD_INTEL_CACHE_DB"] = prior
+
+
+def test_server_cache_landed_in_temp_path(server) -> None:
+ """Guard for this file's own premise: if the env override stopped
+ working, every test here would be silently exercising (and writing
+ to) the developer's real cache."""
+ assert Path(server.cache.db_path) == _TMP_CACHE
+
+
+def test_tool_names_unique_and_conventional(server) -> None:
+ names = [t.name for t in server.TOOLS]
+ assert len(names) == len(set(names)), "duplicate tool name in TOOLS"
+ non_conforming = [n for n in names if not n.startswith("intel_")]
+ assert non_conforming == [], f"tools outside intel_* convention: {non_conforming}"
+
+
+def test_every_tool_has_description_and_object_schema(server) -> None:
+ for tool in server.TOOLS:
+ assert tool.description and tool.description.strip(), tool.name
+ assert isinstance(tool.inputSchema, dict), tool.name
+ assert tool.inputSchema.get("type") == "object", tool.name
+
+
+def test_tools_and_dispatch_are_in_one_to_one_parity(server) -> None:
+ """The invariant ROADMAP.md carries ('TOOLS and _dispatch are
+ aligned'), checked against the imported module rather than a text
+ scan of the repo: every registered tool has a dispatch case and
+ every dispatch case is a registered tool."""
+ registered = {t.name for t in server.TOOLS}
+ dispatch_src = inspect.getsource(server._dispatch)
+ dispatched = set(re.findall(r'case "(intel_[a-z0-9_]+)"', dispatch_src))
+ assert registered - dispatched == set(), "registered but never dispatched"
+ assert dispatched - registered == set(), "dispatched but never registered"
+
+
+def test_tool_count_matches_documented_surface(server) -> None:
+ """122 = 121 intelligence tools + intel_status. If this fails after
+ adding a tool, update README.md, ROADMAP.md, and this number in the
+ same change: the repo's history shows doc counts drifting stale
+ within weeks when nothing enforced them."""
+ assert len(server.TOOLS) == 122
+
+
+async def test_dispatch_unknown_tool_returns_error(server) -> None:
+ result = await server._dispatch("intel_no_such_tool", {})
+ assert result == {"error": "Unknown tool: intel_no_such_tool"}
+
+
+async def test_dispatch_reaches_real_aoi_store_round_trip(server) -> None:
+ """Drive define -> list -> update -> delete through the real
+ dispatcher and the module-level AOIStore (temp-backed): the tools
+ exist end-to-end, not just as registry entries."""
+ defined = await server._dispatch(
+ "intel_aoi_define",
+ {"name": "Registry Test", "lat": 40.44, "lon": -79.99, "radius_km": 25},
+ )
+ assert defined.get("aoi", {}).get("name") == "Registry Test"
+
+ listed = await server._dispatch("intel_aoi_list", {})
+ assert any(a["name"] == "Registry Test" for a in listed["aois"])
+
+ updated = await server._dispatch(
+ "intel_aoi_update", {"name": "Registry Test", "radius_km": 50}
+ )
+ assert updated.get("aoi", {}).get("radius_km") == 50.0
+
+ deleted = await server._dispatch("intel_aoi_delete", {"name": "Registry Test"})
+ assert deleted.get("deleted") == "Registry Test"
+
+
+async def test_dispatch_static_dataset_tool_works(server) -> None:
+ """A pure static-config tool through the real dispatcher: no
+ network, real data contract."""
+ result = await server._dispatch("intel_military_bases", {})
+ assert result.get("count", 0) >= 70
+ assert any(
+ b.get("name") == "Norfolk Naval Station" for b in result.get("bases", [])
+ )
diff --git a/src/world_intel_mcp/tests/test_signals.py b/src/world_intel_mcp/tests/test_signals.py
new file mode 100644
index 0000000..f1ab23c
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_signals.py
@@ -0,0 +1,146 @@
+"""Tests for analysis/signals.py — per-country multi-domain aggregation.
+
+Convergence scores in comments follow the documented formula:
+20 * unique_domains + min(30, 5 * total_signals) + 10 * high_severity.
+"""
+
+from world_intel_mcp.analysis.signals import aggregate_country_signals
+
+
+def test_no_inputs_yields_empty_dict() -> None:
+ assert aggregate_country_signals() == {}
+
+
+def test_conflict_events_aggregate_with_fatality_severity() -> None:
+ result = aggregate_country_signals(
+ conflict_events=[
+ {"country": "Ukraine", "fatalities": 12},
+ {"country": "Ukraine", "fatalities": 0},
+ {"country": "Sudan", "fatalities": 5},
+ ]
+ )
+ ukr = result["Ukraine"]
+ assert ukr["conflict_events"] == 2
+ assert ukr["fatalities"] == 12
+ assert ukr["active_domains"] == ["conflict"]
+ assert ukr["signal_count"] == 1
+ assert ukr["total_signals"] == 2
+ # 20*1 + min(30, 5*2) + 10*1 (one event with >10 fatalities) = 40
+ assert ukr["convergence_score"] == 40
+ # 20*1 + 5*1 + 0 = 25
+ assert result["Sudan"]["convergence_score"] == 25
+ # Sorted by convergence score descending.
+ assert list(result) == ["Ukraine", "Sudan"]
+
+
+def test_events_without_country_are_dropped() -> None:
+ assert aggregate_country_signals(conflict_events=[{"fatalities": 99}]) == {}
+
+
+def test_displacement_counts_severity_but_not_signal_volume() -> None:
+ result = aggregate_country_signals(
+ displacement_data=[
+ {"country": "Sudan", "total_displaced": 150_000},
+ {"country": "Chad", "total_displaced": "many"}, # non-numeric ignored
+ ]
+ )
+ sdn = result["Sudan"]
+ assert sdn["displaced_persons"] == 150_000
+ assert sdn["active_domains"] == ["displacement"]
+ # Displacement contributes a domain and severity but no signal volume:
+ # 20*1 + min(30, 5*0) + 10*1 = 30.
+ assert sdn["total_signals"] == 0
+ assert sdn["convergence_score"] == 30
+ assert result["Chad"]["displaced_persons"] == 0
+ assert result["Chad"]["convergence_score"] == 20
+
+
+def test_earthquake_country_parsed_from_usgs_place_string() -> None:
+ result = aggregate_country_signals(
+ earthquake_data=[
+ {"place": "80km SSE of Lima, Peru", "magnitude": 6.4},
+ {"place": "10km N of Tokyo, Japan", "magnitude": 4.0},
+ {"place": "central mid-Atlantic ridge", "magnitude": 5.0},
+ ]
+ )
+ assert result["Peru"]["earthquakes"] == 1
+ assert result["Peru"]["max_earthquake_mag"] == 6.4
+ # 20*1 + 5*1 + 10*1 (magnitude >= 6.0) = 35
+ assert result["Peru"]["convergence_score"] == 35
+ assert result["Japan"]["max_earthquake_mag"] == 4.0
+ assert result["Japan"]["convergence_score"] == 25 # no severity bonus
+ # A place string without ", Country" falls back to Unknown.
+ assert result["Unknown"]["earthquakes"] == 1
+
+
+def test_fires_use_country_or_region_mapping() -> None:
+ result = aggregate_country_signals(
+ fire_data=[
+ {"country": "Greece"},
+ {"region": "europe"}, # maps to first europe country: Greece
+ {"region": "atlantis"}, # unmapped region contributes nothing
+ "not-a-dict", # malformed entry skipped
+ ]
+ )
+ assert list(result) == ["Greece"]
+ assert result["Greece"]["fires"] == 2
+ assert result["Greece"]["active_domains"] == ["wildfire"]
+
+
+def test_outage_countries_accept_list_or_string() -> None:
+ result = aggregate_country_signals(
+ outage_data=[
+ {"countries": ["US", "CA"]},
+ {"countries": "GB"},
+ {"unrelated": True},
+ ]
+ )
+ assert result["US"]["outages"] == 1
+ assert result["CA"]["outages"] == 1
+ assert result["GB"]["outages"] == 1
+ assert result["GB"]["active_domains"] == ["infrastructure"]
+
+
+def test_military_flights_counted_by_origin_country() -> None:
+ result = aggregate_country_signals(
+ military_data=[
+ {"origin_country": "Russia"},
+ {"origin_country": None},
+ "not-a-dict",
+ ]
+ )
+ assert list(result) == ["Russia"]
+ assert result["Russia"]["military_aircraft"] == 1
+ assert result["Russia"]["active_domains"] == ["military"]
+
+
+def test_riots_split_from_protests_by_event_type() -> None:
+ result = aggregate_country_signals(
+ protest_data=[
+ {"country": "France", "event_type": "Riots"},
+ {"country": "France", "event_type": "Protests"},
+ {"country": "France"}, # missing event_type counts as protest
+ ]
+ )
+ fra = result["France"]
+ assert fra["riots"] == 1
+ assert fra["protests"] == 2
+ assert fra["active_domains"] == ["unrest"]
+ assert fra["total_signals"] == 3
+
+
+def test_domain_breadth_outranks_raw_volume() -> None:
+ """Three domains with one event each must outscore six events in a
+ single domain — that is the point of convergence scoring."""
+ result = aggregate_country_signals(
+ conflict_events=(
+ [{"country": "Kenya", "fatalities": 0}]
+ + [{"country": "Brazil", "fatalities": 0}] * 6
+ ),
+ earthquake_data=[{"place": "10km N of Nairobi, Kenya", "magnitude": 4.5}],
+ fire_data=[{"country": "Kenya"}],
+ )
+ # Kenya: 20*3 + 5*3 = 75. Brazil: 20*1 + min(30, 5*6) = 50.
+ assert result["Kenya"]["convergence_score"] == 75
+ assert result["Brazil"]["convergence_score"] == 50
+ assert list(result) == ["Kenya", "Brazil"]
diff --git a/src/world_intel_mcp/tests/test_sources_climate.py b/src/world_intel_mcp/tests/test_sources_climate.py
new file mode 100644
index 0000000..010916f
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_climate.py
@@ -0,0 +1,173 @@
+"""Tests for sources/climate.py — respx-mocked Open-Meteo anomaly math.
+
+Gaps / not covered: real Open-Meteo response schemas; leap-year baseline
+window edge (the module uses a fixed 365-day offset); the composite-cache
+read path (only the write is asserted).
+"""
+
+import asyncio as asyncio_mod
+from datetime import datetime, timezone, timedelta
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources.climate import (
+ CLIMATE_ZONES,
+ _compute_anomalies,
+ _safe_avg,
+ _safe_sum,
+ fetch_climate_anomalies,
+)
+
+# Current period: max/min pairs (10,0)->5 and (12,2)->7, third pair dropped
+# because max is None. Avg temp 6.0. Precip 5+3 (None ignored) = 8.0.
+_CURRENT = {
+ "daily": {
+ "temperature_2m_max": [10.0, 12.0, None],
+ "temperature_2m_min": [0.0, 2.0, 5.0],
+ "precipitation_sum": [5.0, 3.0, None],
+ }
+}
+# Baseline: avg temp 4.0, precip 40.0.
+_BASELINE = {
+ "daily": {
+ "temperature_2m_max": [8.0, 8.0],
+ "temperature_2m_min": [0.0, 0.0],
+ "precipitation_sum": [20.0, 20.0],
+ }
+}
+
+
+def _mock_archive() -> None:
+ """Route current vs baseline payloads by the start_date query param,
+ mirroring how the module derives its two windows."""
+ now = datetime.now(timezone.utc)
+ current_start = (now - timedelta(days=7)).strftime("%Y-%m-%d")
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ if request.url.params.get("start_date") == current_start:
+ return httpx.Response(200, json=_CURRENT)
+ return httpx.Response(200, json=_BASELINE)
+
+ respx.get(url__regex=r".*archive-api\.open-meteo\.com.*").mock(side_effect=_handler)
+
+
+async def test_fetch_climate_anomalies_single_zone(fetcher: Fetcher) -> None:
+ _mock_archive()
+
+ result = await fetch_climate_anomalies(fetcher, zones=["sahel"])
+
+ assert result["source"] == "open-meteo"
+ assert list(result["zones"].keys()) == ["sahel"]
+ zone = result["zones"]["sahel"]
+ assert zone["name"] == "Sahel Region"
+ assert zone["lat"] == 14.0
+ assert zone["lon"] == 0.0
+ # Derived from the mocked payloads, not from whatever the code emits.
+ assert zone["current_avg_temp_c"] == 6.0
+ assert zone["baseline_avg_temp_c"] == 4.0
+ assert zone["temp_anomaly_c"] == 2.0
+ assert zone["current_precip_mm"] == 8.0
+ assert zone["baseline_precip_mm"] == 40.0
+ assert zone["precip_anomaly_pct"] == -80.0
+ # |2.0| <= 3 C and |-80| <= 100% — not significant.
+ assert zone["is_significant"] is False
+ assert result["significant_anomalies"] == []
+
+ # Composite result cached under the "selected" label.
+ assert fetcher.cache.get("climate:anomalies:selected") is not None
+
+
+async def test_fetch_climate_anomalies_all_zones(fetcher: Fetcher) -> None:
+ _mock_archive()
+
+ result = await fetch_climate_anomalies(fetcher)
+ assert set(result["zones"].keys()) == set(CLIMATE_ZONES.keys())
+ assert len(result["zones"]) == 15
+ assert fetcher.cache.get("climate:anomalies:all") is not None
+
+
+async def test_fetch_climate_anomalies_unknown_zone(fetcher: Fetcher) -> None:
+ # No HTTP mocked: an unknown zone key must short-circuit without a fetch.
+ result = await fetch_climate_anomalies(fetcher, zones=["atlantis"])
+ assert result["zones"] == {}
+ assert result["significant_anomalies"] == []
+ assert result["source"] == "open-meteo"
+
+
+async def test_fetch_climate_anomalies_api_failure_omits_zone(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Suspected bug (documented, not fixed): a zone whose fetch fails is
+ silently omitted — the response carries no error/data_gaps marker, so a
+ full Open-Meteo outage returns {"zones": {}} indistinguishable in shape
+ from a valid run over zero requested zones."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+
+ respx.get(url__regex=r".*archive-api\.open-meteo\.com.*").mock(
+ return_value=httpx.Response(500)
+ )
+
+ result = await fetch_climate_anomalies(fetcher, zones=["sahel"])
+ assert result["zones"] == {}
+ assert result["significant_anomalies"] == []
+ assert "error" not in result # current (dishonest-quiet) behavior
+
+
+def test_compute_anomalies_significant_temp() -> None:
+ current = {
+ "daily": {
+ "temperature_2m_max": [12.0],
+ "temperature_2m_min": [8.0],
+ "precipitation_sum": [0.0],
+ }
+ }
+ baseline = {
+ "daily": {
+ "temperature_2m_max": [4.0],
+ "temperature_2m_min": [4.0],
+ "precipitation_sum": [0.0],
+ }
+ }
+ out = _compute_anomalies(current, baseline)
+ assert out["temp_anomaly_c"] == 6.0
+ assert out["is_significant"] is True
+
+
+def test_compute_anomalies_zero_baseline_precip_guard() -> None:
+ current = {"daily": {"precipitation_sum": [5.0]}}
+ baseline = {"daily": {"precipitation_sum": [0.0]}}
+ out = _compute_anomalies(current, baseline)
+ # Guard divides by max(baseline, 0.1): (5 - 0) / 0.1 * 100 = 5000%.
+ assert out["precip_anomaly_pct"] == 5000.0
+ assert out["is_significant"] is True # >100% precip anomaly
+
+
+def test_compute_anomalies_empty_inputs() -> None:
+ out = _compute_anomalies({}, {})
+ assert out["current_avg_temp_c"] == 0.0
+ assert out["baseline_avg_temp_c"] == 0.0
+ assert out["temp_anomaly_c"] == 0.0
+ assert out["precip_anomaly_pct"] == 0.0
+ assert out["is_significant"] is False
+
+
+def test_safe_avg_and_sum() -> None:
+ assert _safe_avg([]) == 0.0
+ assert _safe_avg([None, None]) == 0.0
+ assert _safe_avg([1.0, None, 3.0]) == 2.0
+ assert _safe_sum([]) == 0.0
+ assert _safe_sum([1.5, None, 2.5]) == 4.0
diff --git a/src/world_intel_mcp/tests/test_sources_cyber.py b/src/world_intel_mcp/tests/test_sources_cyber.py
new file mode 100644
index 0000000..4ee2d4b
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_cyber.py
@@ -0,0 +1,264 @@
+"""Tests for sources/cyber.py — respx-mocked feed aggregation.
+
+Gaps / not covered: live feed schemas may drift from the mocked payloads;
+the CISA KEV 30-day cutoff is exercised with a fixed old date, not a
+boundary-exact date; circuit-breaker interaction is not exercised here.
+"""
+
+import asyncio as asyncio_mod
+from datetime import datetime, timezone, timedelta
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources.cyber import (
+ _normalize_cisa_kev,
+ _normalize_feodo,
+ _normalize_sans_isc,
+ _normalize_urlhaus,
+ fetch_cyber_threats,
+)
+
+_RECENT = (datetime.now(timezone.utc) - timedelta(days=5)).strftime("%Y-%m-%d")
+
+_FEODO = [
+ {
+ "ip_address": "1.2.3.4",
+ "malware": "Emotet",
+ "status": "online",
+ "port": 443,
+ "hostname": "bad.example",
+ "as_number": 64500,
+ "as_name": "EVIL-AS",
+ "country": "US",
+ "first_seen": "2026-08-01",
+ "last_online": "2026-08-30",
+ },
+ {
+ "ip_address": "5.6.7.8",
+ "malware": "QakBot",
+ "status": "offline",
+ "first_seen": "2026-01-01",
+ },
+]
+
+_CISA = {
+ "vulnerabilities": [
+ {
+ "cveID": "CVE-2026-0001",
+ "vendorProject": "Acme",
+ "product": "Router",
+ "vulnerabilityName": "RCE in admin panel",
+ "dateAdded": _RECENT,
+ "knownRansomwareCampaignUse": "Known",
+ "dueDate": "2026-09-15",
+ "requiredAction": "Patch",
+ "notes": "",
+ },
+ {
+ "cveID": "CVE-2026-0002",
+ "vendorProject": "Beta",
+ "product": "CMS",
+ "vulnerabilityName": "SQLi",
+ "dateAdded": _RECENT,
+ "knownRansomwareCampaignUse": "Unknown",
+ },
+ {
+ # Older than the 30-day cutoff — must be filtered out.
+ "cveID": "CVE-2020-9999",
+ "vendorProject": "Old",
+ "product": "Legacy",
+ "vulnerabilityName": "Ancient bug",
+ "dateAdded": "2020-01-01",
+ "knownRansomwareCampaignUse": "Known",
+ },
+ ]
+}
+
+_SANS = [
+ {
+ "ip": "9.9.9.9",
+ "attacks": 1234,
+ "count": 10,
+ "firstseen": "2026-08-20",
+ "lastseen": "2026-08-31",
+ "asname": "SOME-AS",
+ "ascountry": "CN",
+ },
+ {"ip": "", "attacks": 5}, # no IP — skipped
+]
+
+_URLHAUS = {
+ "urls": [
+ {
+ "url": "http://evil.example/mal.exe",
+ "threat": "malware_download",
+ "url_status": "online",
+ "dateadded": "2026-08-30",
+ "tags": ["exe"],
+ "reporter": "abuse_ch",
+ },
+ {
+ "url": "http://old.example/gone.exe",
+ "threat": "malware_download",
+ "url_status": "offline",
+ "dateadded": "2026-08-01",
+ },
+ ]
+}
+
+
+def _mock_all_feeds() -> None:
+ respx.get(url__regex=r".*feodotracker\.abuse\.ch.*").mock(
+ return_value=httpx.Response(200, json=_FEODO)
+ )
+ respx.get(url__regex=r".*cisa\.gov.*").mock(
+ return_value=httpx.Response(200, json=_CISA)
+ )
+ respx.get(url__regex=r".*isc\.sans\.edu.*").mock(
+ return_value=httpx.Response(200, json=_SANS)
+ )
+ respx.get(url__regex=r".*urlhaus-api\.abuse\.ch.*").mock(
+ return_value=httpx.Response(200, json=_URLHAUS)
+ )
+
+
+async def test_fetch_cyber_threats_aggregates_all_feeds(fetcher: Fetcher) -> None:
+ _mock_all_feeds()
+
+ result = await fetch_cyber_threats(fetcher)
+
+ assert result["source"] == "cyber-feeds"
+ assert result["feeds_attempted"] == 4
+ assert result["feeds_successful"] == 4
+ # 2 feodo + 2 KEV (old one cut) + 1 SANS (empty-IP skipped) + 2 urlhaus
+ assert result["count"] == 7
+
+ # Severity ordering: criticals first, then high, medium, low.
+ severities = [t["severity"] for t in result["threats"]]
+ assert severities == [
+ "critical",
+ "critical",
+ "high",
+ "high",
+ "high",
+ "medium",
+ "low",
+ ]
+
+ # Within criticals, newest first_seen first (KEV added 5 days ago beats
+ # the feodo entry from 2026-08-01).
+ assert result["threats"][0]["indicator"] == "CVE-2026-0001"
+ assert result["threats"][1]["indicator"] == "1.2.3.4"
+
+ # Old KEV entry filtered by the 30-day cutoff.
+ indicators = {t["indicator"] for t in result["threats"]}
+ assert "CVE-2020-9999" not in indicators
+
+ assert result["by_type"] == {
+ "c2_ip": 2,
+ "vulnerability": 2,
+ "attack_ip": 1,
+ "malware_url": 2,
+ }
+ assert result["by_severity"] == {"critical": 2, "high": 3, "medium": 1, "low": 1}
+
+ # Field contract on one item per feed.
+ feodo = next(t for t in result["threats"] if t["indicator"] == "1.2.3.4")
+ assert feodo["type"] == "c2_ip"
+ assert feodo["threat"] == "Emotet"
+ assert feodo["source_feed"] == "feodo-tracker"
+ assert feodo["details"]["port"] == 443
+ assert feodo["details"]["country"] == "US"
+
+ kev = next(t for t in result["threats"] if t["indicator"] == "CVE-2026-0002")
+ assert kev["severity"] == "high" # not ransomware-linked
+ assert kev["threat"] == "Beta CMS: SQLi"
+
+ sans = next(t for t in result["threats"] if t["indicator"] == "9.9.9.9")
+ assert sans["threat"] == "DShield top attacker (1234 attacks)"
+ assert sans["details"]["as_country"] == "CN"
+
+ urlh = next(
+ t for t in result["threats"] if t["indicator"] == "http://evil.example/mal.exe"
+ )
+ assert urlh["severity"] == "high" # online
+ offline = next(
+ t for t in result["threats"] if t["indicator"] == "http://old.example/gone.exe"
+ )
+ assert offline["severity"] == "low"
+
+
+async def test_fetch_cyber_threats_limit(fetcher: Fetcher) -> None:
+ _mock_all_feeds()
+
+ result = await fetch_cyber_threats(fetcher, limit=2)
+ assert result["count"] == 2
+ assert [t["severity"] for t in result["threats"]] == ["critical", "critical"]
+
+
+async def test_fetch_cyber_threats_all_feeds_down(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """All 4 feeds failing must be visible via feeds_successful=0, never
+ reported as a quiet threat landscape with feeds_successful=4."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+
+ respx.get(url__regex=r".*").mock(return_value=httpx.Response(500))
+
+ result = await fetch_cyber_threats(fetcher)
+ assert result["feeds_successful"] == 0
+ assert result["feeds_attempted"] == 4
+ assert result["threats"] == []
+ assert result["count"] == 0
+ assert result["by_type"] == {}
+ assert result["by_severity"] == {}
+
+
+async def test_fetch_cyber_threats_partial_outage(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+
+ respx.get(url__regex=r".*feodotracker\.abuse\.ch.*").mock(
+ return_value=httpx.Response(200, json=_FEODO)
+ )
+ respx.get(url__regex=r".*cisa\.gov.*").mock(return_value=httpx.Response(500))
+ respx.get(url__regex=r".*isc\.sans\.edu.*").mock(return_value=httpx.Response(500))
+ respx.get(url__regex=r".*urlhaus-api\.abuse\.ch.*").mock(
+ return_value=httpx.Response(500)
+ )
+
+ result = await fetch_cyber_threats(fetcher)
+ assert result["feeds_successful"] == 1
+ assert result["count"] == 2
+ assert all(t["source_feed"] == "feodo-tracker" for t in result["threats"])
+
+
+def test_normalizers_reject_wrong_shapes() -> None:
+ assert _normalize_feodo(None) == []
+ assert _normalize_feodo({"not": "a list"}) == []
+ assert _normalize_cisa_kev(None) == []
+ assert _normalize_cisa_kev([1, 2]) == []
+ assert _normalize_sans_isc(None) == []
+ assert _normalize_sans_isc({}) == []
+ assert _normalize_urlhaus(None) == []
+ assert _normalize_urlhaus([]) == []
+ assert _normalize_urlhaus({"urls": "not-a-list"}) == []
diff --git a/src/world_intel_mcp/tests/test_sources_displacement.py b/src/world_intel_mcp/tests/test_sources_displacement.py
new file mode 100644
index 0000000..74a615f
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_displacement.py
@@ -0,0 +1,130 @@
+"""Tests for sources/displacement.py — respx-mocked UNHCR aggregation.
+
+Gaps / not covered: real UNHCR pagination (the module requests limit=100 and
+never pages); the top-30 truncation is not exercised with >30 countries.
+"""
+
+import asyncio as asyncio_mod
+from datetime import datetime, timezone
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources.displacement import _safe_int, fetch_displacement_summary
+
+_UNHCR = {
+ "items": [
+ {
+ "coo_name": "Syria",
+ "refugees": 100,
+ "asylum_seekers": 10,
+ "idps": 50,
+ "stateless": 0,
+ "ooc": 5,
+ },
+ # Second Syria row must aggregate into the first.
+ {"coo_name": "Syria", "refugees": 200},
+ {
+ "coo_name": "Ukraine",
+ "refugees": 1000,
+ "asylum_seekers": "not-a-number", # unparseable -> 0
+ "idps": 500,
+ },
+ # Missing coo_name buckets under "Unknown".
+ {"refugees": 7},
+ ]
+}
+
+
+async def test_fetch_displacement_summary_aggregates_by_origin(
+ fetcher: Fetcher,
+) -> None:
+ route = respx.get(url__regex=r".*api\.unhcr\.org.*").mock(
+ return_value=httpx.Response(200, json=_UNHCR)
+ )
+
+ result = await fetch_displacement_summary(fetcher)
+
+ assert result["source"] == "unhcr"
+ assert result["count"] == 3
+ # Sorted by total_displaced descending: Ukraine 1500, Syria 365, Unknown 7.
+ assert [e["country"] for e in result["by_origin"]] == [
+ "Ukraine",
+ "Syria",
+ "Unknown",
+ ]
+ ukraine = result["by_origin"][0]
+ assert ukraine["refugees"] == 1000
+ assert ukraine["asylum_seekers"] == 0 # unparseable string coerced to 0
+ assert ukraine["internally_displaced"] == 500
+ assert ukraine["total_displaced"] == 1500
+
+ syria = result["by_origin"][1]
+ assert syria["refugees"] == 300 # 100 + 200 across two rows
+ assert syria["total_displaced"] == 365
+
+ totals = result["global_totals"]
+ assert totals["total_refugees"] == 1307
+ assert totals["total_asylum_seekers"] == 10
+ assert totals["total_idps"] == 550
+ assert totals["total_stateless"] == 0
+ assert totals["total_ooc"] == 5
+ assert totals["grand_total"] == 1872
+
+ # Default year is the previous calendar year (UNHCR lags).
+ expected_year = datetime.now(timezone.utc).year - 1
+ assert result["year"] == expected_year
+ assert route.calls.last.request.url.params["yearFrom"] == str(expected_year)
+
+
+async def test_fetch_displacement_summary_year_coerced_from_string(
+ fetcher: Fetcher,
+) -> None:
+ route = respx.get(url__regex=r".*api\.unhcr\.org.*").mock(
+ return_value=httpx.Response(200, json={"items": []})
+ )
+
+ result = await fetch_displacement_summary(fetcher, year="2020")
+ assert result["year"] == 2020
+ assert result["by_origin"] == []
+ assert result["count"] == 0
+ assert route.calls.last.request.url.params["yearFrom"] == "2020"
+
+
+async def test_fetch_displacement_summary_api_down_returns_zeroed_shape(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Suspected bug (documented, not fixed): a UNHCR outage returns
+ global_totals of all zeros with NO error/degraded key — byte-shape
+ identical to a world with zero displaced persons. This is the
+ fail-reads-as-success class this repo treats as its worst bug family;
+ flagged in the review report rather than fixed here."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+
+ respx.get(url__regex=r".*api\.unhcr\.org.*").mock(return_value=httpx.Response(500))
+
+ result = await fetch_displacement_summary(fetcher)
+ assert result["by_origin"] == []
+ assert result["count"] == 0
+ assert result["global_totals"]["grand_total"] == 0
+ assert "error" not in result # current (dishonest-quiet) behavior
+
+
+def test_safe_int() -> None:
+ assert _safe_int(None) == 0
+ assert _safe_int(5) == 5
+ assert _safe_int(5.9) == 5
+ assert _safe_int("42") == 42
+ assert _safe_int("nope") == 0
diff --git a/src/world_intel_mcp/tests/test_sources_fleet.py b/src/world_intel_mcp/tests/test_sources_fleet.py
new file mode 100644
index 0000000..c475250
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_fleet.py
@@ -0,0 +1,168 @@
+"""Tests for sources/fleet.py — component aggregation is monkeypatched at
+the sibling-module boundary (fleet imports them inside the function, so
+patching the module attributes intercepts the real calls).
+
+Gaps / not covered: the real intelligence/military component functions are
+not exercised here (they have their own tests); naval-base static data is
+asserted only as non-empty, not for content.
+"""
+
+import pytest
+
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources import intelligence, military
+from world_intel_mcp.sources.fleet import _fleet_readiness, fetch_fleet_report
+
+
+def test_fleet_readiness_low_activity() -> None:
+ level, score = _fleet_readiness({}, [], [])
+ assert level == "LOW_ACTIVITY"
+ assert score == 0
+
+
+def test_fleet_readiness_high_activity() -> None:
+ # aircraft 60 -> capped 30; one critical waterway -> 30; one surge -> 15.
+ theaters = {"european": {"count": 60}}
+ waterways = [{"status": "critical"}]
+ surges = [{"region": "baltic_sea"}]
+ level, score = _fleet_readiness(theaters, waterways, surges)
+ assert score == 75
+ assert level == "HIGH_ACTIVITY"
+
+
+def test_fleet_readiness_normal_operations() -> None:
+ # aircraft 20 -> 10; one advisory waterway -> 10; no surges. Total 20.
+ theaters = {"a": {"count": 20}}
+ waterways = [{"status": "advisory"}]
+ level, score = _fleet_readiness(theaters, waterways, [])
+ assert score == 20
+ assert level == "NORMAL_OPERATIONS"
+
+
+def test_fleet_readiness_ignores_non_dict_theaters() -> None:
+ level, score = _fleet_readiness({"bad": "not-a-dict"}, [], [])
+ assert score == 0
+ assert level == "LOW_ACTIVITY"
+
+
+async def test_fetch_fleet_report(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _posture(f) -> dict:
+ return {
+ "theaters": {
+ "european": {
+ "count": 4,
+ "top_types": ["C-17", "KC-135", "F-16", "P-8"],
+ },
+ }
+ }
+
+ async def _vessels(f) -> dict:
+ return {
+ "waterways": [
+ {"name": "Suez Canal", "status": "elevated", "warning_count": 2},
+ ]
+ }
+
+ async def _surges(f) -> dict:
+ return {
+ "surges": [
+ {
+ "region": "black_sea",
+ "aircraft_count": 12,
+ "baseline": 5,
+ "ratio": 2.4,
+ },
+ ]
+ }
+
+ monkeypatch.setattr(military, "fetch_theater_posture", _posture)
+ monkeypatch.setattr(intelligence, "fetch_vessel_snapshot", _vessels)
+ monkeypatch.setattr(intelligence, "fetch_military_surge", _surges)
+
+ result = await fetch_fleet_report(fetcher)
+
+ assert result["source"] == "fleet-activity-report"
+ assert result["theater_count"] == 1
+ assert result["theater_summary"] == [
+ {
+ "name": "european",
+ "aircraft_count": 4,
+ "top_types": ["C-17", "KC-135", "F-16"], # truncated to 3
+ }
+ ]
+ assert result["waterway_summary"] == [
+ {"name": "Suez Canal", "status": "elevated", "warning_count": 2}
+ ]
+ assert result["active_surges"] == [
+ {"region": "black_sea", "aircraft_count": 12, "baseline": 5, "ratio": 2.4}
+ ]
+ assert result["surge_count"] == 1
+ assert result["total_tracked_aircraft"] == 4
+ # Static dataset ships naval bases; the report must see a non-zero count.
+ assert result["naval_base_count"] > 0
+
+ # Readiness: 4 aircraft -> 2; elevated waterway -> 20; 1 surge -> 15 = 37.
+ assert result["readiness_score"] == 37
+ assert result["readiness_level"] == "NORMAL_OPERATIONS"
+
+
+async def test_fetch_fleet_report_survives_component_failures(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Every dynamic component raising still yields a well-formed report.
+ Observation (flagged in review, not fixed): the report carries no
+ degraded marker, so three dead components read as a quiet fleet."""
+
+ async def _boom(f) -> dict:
+ raise RuntimeError("component down")
+
+ monkeypatch.setattr(military, "fetch_theater_posture", _boom)
+ monkeypatch.setattr(intelligence, "fetch_vessel_snapshot", _boom)
+ monkeypatch.setattr(intelligence, "fetch_military_surge", _boom)
+
+ result = await fetch_fleet_report(fetcher)
+
+ assert result["readiness_level"] == "LOW_ACTIVITY"
+ assert result["readiness_score"] == 0
+ assert result["theater_summary"] == []
+ assert result["waterway_summary"] == []
+ assert result["active_surges"] == []
+ assert result["total_tracked_aircraft"] == 0
+ assert "error" not in result # current (dishonest-quiet) behavior
+
+
+async def test_waterway_warning_count_from_real_vessel_snapshot_shape(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Regression: fetch_vessel_snapshot emits the count as
+ "naval_warnings", and the fleet report read only "warning_count",
+ so per-waterway warning counts were 0 in every real report (the
+ silent-zero class). The report must propagate the count from the
+ shape the snapshot actually emits."""
+ from world_intel_mcp.sources import intelligence, military
+
+ async def _snapshot_real_shape(f, **kwargs):
+ return {
+ "waterways": [
+ {"name": "Strait of Hormuz", "status": "critical", "naval_warnings": 3}
+ ]
+ }
+
+ async def _empty(f, **kwargs):
+ return {}
+
+ monkeypatch.setattr(intelligence, "fetch_vessel_snapshot", _snapshot_real_shape)
+ monkeypatch.setattr(military, "fetch_theater_posture", _empty)
+ monkeypatch.setattr(intelligence, "fetch_military_surge", _empty)
+
+ from world_intel_mcp.sources.fleet import fetch_fleet_report
+
+ result = await fetch_fleet_report(fetcher)
+ ww = result["waterway_summary"][0]
+ assert ww["name"] == "Strait of Hormuz"
+ assert ww["warning_count"] == 3
diff --git a/src/world_intel_mcp/tests/test_sources_intelligence.py b/src/world_intel_mcp/tests/test_sources_intelligence.py
new file mode 100644
index 0000000..de275c1
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_intelligence.py
@@ -0,0 +1,972 @@
+"""Tests for sources/intelligence.py success paths and degradation shapes.
+
+Complements tests/test_intelligence.py (which covers the issue-#3 ACLED
+failure-honesty paths for fetch_risk_scores and the hotspot-escalation
+unavailable-components disclosure). This file covers the remaining ten
+public functions.
+
+Patching strategy: intelligence.py binds ``acled_query``/
+``acled_failure_reason`` into its own namespace at import, so those are
+patched on the intelligence module; sibling sources (news, military,
+infrastructure, seismology, displacement, maritime, conflict) are imported
+inside each function body and looked up as module attributes at call time,
+so those are patched on their own modules.
+
+Gaps / not covered: the real ACLED OAuth flow (covered by
+test_intelligence.py via _acled_get_token); Ollama streaming; the
+TemporalBaseline anomaly-firing path (needs 10+ historical observations —
+only the recording path is exercised here); exact CII arithmetic
+(instability tests assert raw_data pass-through and the UCDP floor, not
+the weighted-sum internals, which belong to analysis/instability.py).
+"""
+
+from datetime import datetime, timezone
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.analysis.temporal import TemporalBaseline
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources import (
+ conflict,
+ displacement,
+ infrastructure,
+ intelligence,
+ maritime,
+ military,
+ news,
+ seismology,
+)
+from world_intel_mcp.sources.intelligence import _haversine_km, _risk_level
+
+
+def _async_return(value):
+ async def _fake(*args, **kwargs):
+ return value
+
+ return _fake
+
+
+def _fake_reason(reason: str):
+ async def _fake(data):
+ return reason
+
+ return _fake
+
+
+# ---------------------------------------------------------------------------
+# _risk_level / _haversine_km helpers
+# ---------------------------------------------------------------------------
+
+
+def test_risk_level_boundaries() -> None:
+ assert _risk_level(151) == "critical"
+ assert _risk_level(150) == "elevated"
+ assert _risk_level(101) == "elevated"
+ assert _risk_level(100) == "moderate"
+ assert _risk_level(51) == "moderate"
+ assert _risk_level(50) == "low"
+ assert _risk_level(0) == "low"
+
+
+def test_haversine_km() -> None:
+ assert _haversine_km(0.0, 0.0, 0.0, 0.0) == 0.0
+ # One degree of latitude is ~111 km.
+ d = _haversine_km(0.0, 0.0, 1.0, 0.0)
+ assert 110.0 < d < 112.5
+
+
+# ---------------------------------------------------------------------------
+# Function 1: fetch_country_brief
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_country_brief_with_ollama(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("OLLAMA_API_URL", "http://ollama.test")
+
+ respx.get("https://api.worldbank.org/v2/country/UA/indicator/NY.GDP.MKTP.CD").mock(
+ return_value=httpx.Response(
+ 200,
+ json=[
+ {"page": 1},
+ [
+ {"date": "2023", "value": 25000000000000},
+ {"date": "2022", "value": None}, # dropped
+ ],
+ ],
+ )
+ )
+ respx.get("https://api.worldbank.org/v2/country/UA/indicator/FP.CPI.TOTL.ZG").mock(
+ return_value=httpx.Response(
+ 200, json=[{"page": 1}, [{"date": "2023", "value": 3.2}]]
+ )
+ )
+ respx.post("http://ollama.test/api/generate").mock(
+ return_value=httpx.Response(200, json={"response": " Analytical brief. "})
+ )
+
+ # ACLED count query succeeds with a string count (exercises coercion).
+ monkeypatch.setattr(intelligence, "acled_query", _async_return({"count": "7"}))
+
+ result = await intelligence.fetch_country_brief(fetcher, country_code="UA")
+
+ assert result["source"] == "country-intelligence"
+ assert result["country_code"] == "UA"
+ assert result["llm_available"] is True
+ assert result["brief"] == "Analytical brief." # stripped
+ assert result["data"]["gdp"] == [{"year": "2023", "value": 25000000000000.0}]
+ assert result["data"]["inflation"] == [{"year": "2023", "value": 3.2}]
+ assert result["data"]["recent_events"] == 7
+ assert result["data_gaps"] == []
+
+
+async def test_fetch_country_brief_ollama_down_and_acled_gap(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("OLLAMA_API_URL", "http://ollama.test")
+
+ respx.get(url__regex=r".*api\.worldbank\.org.*").mock(
+ return_value=httpx.Response(200, json=[{"page": 1}, []])
+ )
+ respx.post("http://ollama.test/api/generate").mock(
+ side_effect=httpx.ConnectError("connection refused")
+ )
+
+ monkeypatch.setattr(intelligence, "acled_query", _async_return(None))
+ monkeypatch.setattr(
+ intelligence, "acled_failure_reason", _fake_reason("acled_unconfigured")
+ )
+
+ result = await intelligence.fetch_country_brief(fetcher, country_code="UA")
+
+ assert result["llm_available"] is False
+ assert result["brief"].startswith("LLM brief unavailable")
+ assert result["data"]["gdp"] == []
+ assert result["data"]["recent_events"] == 0
+ # The failed ACLED count is disclosed, not silently reported as 0 events.
+ assert result["data_gaps"] == ["acled_unconfigured"]
+
+
+# ---------------------------------------------------------------------------
+# Function 2: fetch_risk_scores (success path; failure paths live in
+# test_intelligence.py)
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_risk_scores_success(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ events = [{"country": "Syria"}] * 100 + [{"country": "Atlantis"}] * 60
+ monkeypatch.setattr(intelligence, "acled_query", _async_return({"data": events}))
+
+ result = await intelligence.fetch_risk_scores(fetcher)
+
+ assert result["source"] == "risk-analysis"
+ assert result["count"] == 2
+ # Atlantis has no curated baseline (defaults to 500/yr = 41.7/month):
+ # 60 events -> 144.0 -> elevated. Syria baseline 5000/yr = 416.7/month:
+ # 100 events -> 24.0 -> low. Sorted by risk descending.
+ atlantis, syria = result["countries"]
+ assert atlantis["country"] == "Atlantis"
+ assert atlantis["monthly_baseline"] == 41.7
+ assert atlantis["risk_score"] == 144.0
+ assert atlantis["risk_level"] == "elevated"
+ assert syria["country"] == "Syria"
+ assert syria["events_30d"] == 100
+ assert syria["monthly_baseline"] == 416.7
+ assert syria["risk_score"] == 24.0
+ assert syria["risk_level"] == "low"
+
+
+async def test_fetch_risk_scores_limit(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ events = [{"country": "Syria"}] * 10 + [{"country": "Atlantis"}] * 60
+ monkeypatch.setattr(intelligence, "acled_query", _async_return({"data": events}))
+
+ result = await intelligence.fetch_risk_scores(fetcher, limit=1)
+ assert result["count"] == 1
+ assert result["countries"][0]["country"] == "Atlantis"
+
+
+# ---------------------------------------------------------------------------
+# Function 3: fetch_instability_index
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_instability_index_single_country(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ acled_events = (
+ [{"event_type": "Protests", "fatalities": "0"}] * 2
+ + [{"event_type": "Riots", "fatalities": 0}]
+ + [{"event_type": "Battles", "fatalities": 10}] * 3
+ )
+ monkeypatch.setattr(
+ intelligence, "acled_query", _async_return({"data": acled_events})
+ )
+ monkeypatch.setattr(
+ infrastructure,
+ "fetch_internet_outages",
+ _async_return({"outages": [{"countries": ["SYR"]}, {"countries": ["UKR"]}]}),
+ )
+
+ seen_bbox: list = []
+
+ async def _fake_flights(f, bbox=None):
+ seen_bbox.append(bbox)
+ return {"count": 10}
+
+ monkeypatch.setattr(military, "fetch_military_flights", _fake_flights)
+ monkeypatch.setattr(news, "fetch_gdelt_search", _async_return({"count": 40}))
+
+ result = await intelligence.fetch_instability_index(fetcher, country_code="SYR")
+
+ assert result["source"] == "instability-index-v2"
+ assert result["country_code"] == "SYR"
+ assert result["country_name"] == "Syria"
+ # Raw counts derived from the injected payloads.
+ assert result["raw_data"] == {
+ "acled_events": 6,
+ "protests": 2,
+ "riots": 1,
+ "conflict_events": 3,
+ "fatalities": 30,
+ "military_aircraft": 10,
+ "internet_outages": 1, # only the SYR-matching outage
+ "news_articles": 40,
+ }
+ # Syria bbox from the curated table is plumbed into the military query.
+ assert seen_bbox == ["32,35,37,42"]
+ # Syria (baseline_risk 80) gets the UCDP active-war floor and the
+ # displacement boost; the index can never sit below the floor.
+ assert result["ucdp_floor"] == 70.0
+ assert result["displacement_boost"] == 3.0
+ assert result["event_multiplier"] == 1.2
+ assert result["instability_index"] >= 70.0
+ assert result["risk_level"] in ("high", "critical")
+ assert result["data_gaps"] == []
+
+
+async def test_fetch_instability_index_multi_country(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ events = [{"country": "Ukraine", "event_type": "Battles", "fatalities": 3}] * 5
+ monkeypatch.setattr(intelligence, "acled_query", _async_return({"data": events}))
+
+ result = await intelligence.fetch_instability_index(fetcher)
+
+ assert result["source"] == "instability-index-v2"
+ assert result["count"] == 10
+ codes = {c["country_code"] for c in result["countries"]}
+ assert codes == set(intelligence._FOCUS_COUNTRIES)
+
+ ukraine = next(c for c in result["countries"] if c["country_code"] == "UKR")
+ assert ukraine["events_30d"] == 5
+ # UKR baseline_risk 85 -> 70.0 floor.
+ assert ukraine["instability_index"] >= 70.0
+
+ # Sorted by instability_index descending.
+ indices = [c["instability_index"] for c in result["countries"]]
+ assert indices == sorted(indices, reverse=True)
+
+
+async def test_fetch_instability_index_multi_degraded(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(intelligence, "acled_query", _async_return(None))
+ monkeypatch.setattr(
+ intelligence, "acled_failure_reason", _fake_reason("acled_fetch_failed")
+ )
+
+ result = await intelligence.fetch_instability_index(fetcher)
+ assert result["degraded"] is True
+ assert "fetch failed" in result["error"]
+
+
+async def test_fetch_instability_index_multi_unconfigured(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(intelligence, "acled_query", _async_return(None))
+ monkeypatch.setattr(
+ intelligence, "acled_failure_reason", _fake_reason("acled_unconfigured")
+ )
+
+ result = await intelligence.fetch_instability_index(fetcher)
+ assert "not configured" in result["error"]
+ assert result.get("degraded") is None
+
+
+# ---------------------------------------------------------------------------
+# Function 4: fetch_signal_convergence
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_signal_convergence_custom_point(fetcher: Fetcher) -> None:
+ route = respx.get("https://earthquake.usgs.gov/fdsnws/event/1/query").mock(
+ return_value=httpx.Response(200, json={"features": [{} for _ in range(20)]})
+ )
+
+ result = await intelligence.fetch_signal_convergence(fetcher, lat=10.0, lon=20.0)
+
+ assert result["source"] == "signal-convergence"
+ assert len(result["hotspots"]) == 1
+ hotspot = result["hotspots"][0]
+ assert hotspot["name"] == "custom"
+ assert hotspot["signals"]["earthquakes"] == 20
+ # 20 quakes saturate the 0-5 earthquake band; a custom point gets no
+ # known-hotspot bonus, so the score is exactly 5.0.
+ assert hotspot["convergence_score"] == 5.0
+
+ # Bounding box derived from lat/lon +/- radius (default 5 degrees).
+ params = route.calls.last.request.url.params
+ assert float(params["minlatitude"]) == 5.0
+ assert float(params["maxlatitude"]) == 15.0
+ assert float(params["minlongitude"]) == 15.0
+ assert float(params["maxlongitude"]) == 25.0
+
+
+async def test_fetch_signal_convergence_default_hotspots(fetcher: Fetcher) -> None:
+ respx.get("https://earthquake.usgs.gov/fdsnws/event/1/query").mock(
+ return_value=httpx.Response(200, json={"features": []})
+ )
+
+ result = await intelligence.fetch_signal_convergence(fetcher)
+
+ assert len(result["hotspots"]) == 5
+ names = {h["name"] for h in result["hotspots"]}
+ assert names == set(intelligence._HOTSPOTS)
+ # No quakes: each known hotspot keeps only its 2.0 presence bonus.
+ assert all(h["convergence_score"] == 2.0 for h in result["hotspots"])
+
+
+async def test_fetch_signal_convergence_usgs_down(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import asyncio as asyncio_mod
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+
+ respx.get("https://earthquake.usgs.gov/fdsnws/event/1/query").mock(
+ return_value=httpx.Response(500)
+ )
+
+ result = await intelligence.fetch_signal_convergence(fetcher, lat=10.0, lon=20.0)
+ assert result["hotspots"][0]["signals"]["earthquakes"] == 0
+ assert result["hotspots"][0]["convergence_score"] == 0.0
+
+
+# ---------------------------------------------------------------------------
+# Function 5: fetch_focal_points
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_focal_points_converging_entity(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ now_iso = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
+
+ monkeypatch.setattr(
+ news,
+ "fetch_news_feed",
+ _async_return(
+ {"items": [{"title": "Ukraine strikes report", "published": now_iso}]}
+ ),
+ )
+ monkeypatch.setattr(
+ military,
+ "fetch_theater_posture",
+ _async_return(
+ {"theaters": {"european": {"count": 12, "countries": ["Ukraine"]}}}
+ ),
+ )
+ monkeypatch.setattr(
+ infrastructure,
+ "fetch_internet_outages",
+ _async_return(
+ {
+ "outages": [
+ {"countries": ["Ukraine"], "start": now_iso, "is_ongoing": True}
+ ]
+ }
+ ),
+ )
+ monkeypatch.setattr(
+ intelligence,
+ "acled_query",
+ _async_return({"data": [{"country": "Ukraine", "event_date": today}]}),
+ )
+
+ result = await intelligence.fetch_focal_points(fetcher)
+
+ assert result["source"] == "focal-point-analysis"
+ assert result["total_events_analyzed"] == 4
+ assert result["count"] == 1
+ assert result["data_gaps"] == []
+
+ fp = result["focal_points"][0]
+ assert fp["entity"] == "Ukraine"
+ assert fp["signal_count"] == 4
+ assert fp["signal_types"] == ["infrastructure", "military", "news", "protest"]
+ assert fp["urgency"] == "watch" # < 5 signals
+ assert fp["countries"] == ["Ukraine"]
+
+
+# ---------------------------------------------------------------------------
+# Function 6: fetch_signal_summary
+# ---------------------------------------------------------------------------
+
+
+def _patch_signal_summary_sources(
+ monkeypatch: pytest.MonkeyPatch,
+ conflict_result: dict,
+ protest_query_result: dict | None,
+) -> None:
+ monkeypatch.setattr(conflict, "fetch_acled_events", _async_return(conflict_result))
+ monkeypatch.setattr(
+ seismology, "fetch_earthquakes", _async_return({"earthquakes": []})
+ )
+ monkeypatch.setattr(
+ infrastructure, "fetch_internet_outages", _async_return({"outages": []})
+ )
+ monkeypatch.setattr(
+ military, "fetch_theater_posture", _async_return({"theaters": {}})
+ )
+ monkeypatch.setattr(
+ intelligence, "acled_query", _async_return(protest_query_result)
+ )
+ monkeypatch.setattr(
+ displacement,
+ "fetch_displacement_summary",
+ _async_return(
+ {"by_origin": [{"country": "Ukraine", "total_displaced": 250000}]}
+ ),
+ )
+
+
+async def test_fetch_signal_summary_aggregates_domains(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_signal_summary_sources(
+ monkeypatch,
+ conflict_result={
+ "events": [{"country": "Ukraine", "fatalities": 5}],
+ "count": 1,
+ },
+ protest_query_result={
+ "data": [{"country": "Ukraine", "event_type": "Protests"}]
+ },
+ )
+
+ result = await intelligence.fetch_signal_summary(fetcher)
+
+ assert result["source"] == "signal-aggregation-v2"
+ assert result["count"] == 1
+ assert result["data_gaps"] == []
+
+ ukraine = result["countries"][0]
+ assert ukraine["country"] == "Ukraine"
+ assert ukraine["conflict_events"] == 1
+ assert ukraine["fatalities"] == 5
+ assert ukraine["displaced_persons"] == 250000
+ assert ukraine["protests"] == 1
+ assert ukraine["active_domains"] == ["conflict", "displacement", "unrest"]
+ # 3 domains x 20 + min(30, 5 x 2 signals) + 10 x 1 high-severity
+ # (250k displaced) = 80.
+ assert ukraine["convergence_score"] == 80
+
+
+async def test_fetch_signal_summary_country_filter(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_signal_summary_sources(
+ monkeypatch,
+ conflict_result={
+ "events": [
+ {"country": "Ukraine", "fatalities": 5},
+ {"country": "Sudan", "fatalities": 2},
+ ],
+ "count": 2,
+ },
+ protest_query_result={"data": []},
+ )
+
+ result = await intelligence.fetch_signal_summary(fetcher, country="ukr")
+ assert result["count"] == 1
+ assert result["countries"][0]["country"] == "Ukraine"
+
+
+async def test_fetch_signal_summary_discloses_acled_gaps(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_signal_summary_sources(
+ monkeypatch,
+ conflict_result={
+ "events": [],
+ "count": 0,
+ "reason": "acled_fetch_failed",
+ "degraded": True,
+ },
+ protest_query_result=None,
+ )
+ monkeypatch.setattr(
+ intelligence, "acled_failure_reason", _fake_reason("acled_fetch_failed")
+ )
+
+ result = await intelligence.fetch_signal_summary(fetcher)
+ # Both gaps collapse into one deduplicated, sorted entry.
+ assert result["data_gaps"] == ["acled_fetch_failed"]
+
+
+# ---------------------------------------------------------------------------
+# Function 7: fetch_temporal_anomalies
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_temporal_anomalies_records_observations(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ monkeypatch.setattr(
+ intelligence, "_temporal", TemporalBaseline(db_path=str(tmp_path / "t.db"))
+ )
+ monkeypatch.setattr(
+ military,
+ "fetch_theater_posture",
+ _async_return(
+ {"theaters": {"european": {"count": 5}, "middle_east": {"count": 3}}}
+ ),
+ )
+ monkeypatch.setattr(
+ intelligence,
+ "acled_query",
+ _async_return(
+ {
+ "data": [
+ {"country": "Ukraine"},
+ {"country": "Ukraine"},
+ {"country": "Sudan"},
+ ]
+ }
+ ),
+ )
+
+ result = await intelligence.fetch_temporal_anomalies(fetcher)
+
+ assert result["source"] == "temporal-anomaly-detection"
+ # 2 theaters + 2 distinct ACLED countries.
+ assert result["observations_recorded"] == 4
+ # A fresh baseline (n=1 < 10) can never flag anomalies.
+ assert result["anomalies"] == []
+ assert result["anomaly_count"] == 0
+ assert result["data_gaps"] == []
+
+
+async def test_fetch_temporal_anomalies_acled_outage_disclosed(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ monkeypatch.setattr(
+ intelligence, "_temporal", TemporalBaseline(db_path=str(tmp_path / "t.db"))
+ )
+ monkeypatch.setattr(
+ military,
+ "fetch_theater_posture",
+ _async_return({"theaters": {"european": {"count": 5}}}),
+ )
+ monkeypatch.setattr(intelligence, "acled_query", _async_return(None))
+ monkeypatch.setattr(
+ intelligence, "acled_failure_reason", _fake_reason("acled_fetch_failed")
+ )
+
+ result = await intelligence.fetch_temporal_anomalies(fetcher)
+ assert result["observations_recorded"] == 1 # theaters only
+ assert result["data_gaps"] == ["acled_fetch_failed"]
+
+
+# ---------------------------------------------------------------------------
+# Function 8: fetch_unrest_events
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_unrest_events_parses_and_dedupes(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ raw = [
+ {
+ "event_date": "2026-08-30",
+ "event_type": "Protests",
+ "sub_event_type": "Peaceful protest",
+ "country": "France",
+ "admin1": "Ile-de-France",
+ "location": "Paris",
+ "latitude": "48.85",
+ "longitude": "2.35",
+ "fatalities": "0",
+ "actor1": "Protesters",
+ "notes": "march",
+ },
+ # Same day, ~7 km away: deduplicated into the first, which must
+ # inherit the higher fatality count.
+ {
+ "event_date": "2026-08-30",
+ "event_type": "Riots",
+ "country": "France",
+ "latitude": "48.90",
+ "longitude": "2.40",
+ "fatalities": 2,
+ },
+ # Same day but Marseille (~660 km away): kept.
+ {
+ "event_date": "2026-08-30",
+ "event_type": "Protests",
+ "country": "France",
+ "latitude": 43.30,
+ "longitude": 5.37,
+ "fatalities": 0,
+ },
+ # Same place, different day: kept.
+ {
+ "event_date": "2026-08-29",
+ "event_type": "Protests",
+ "country": "France",
+ "latitude": 48.85,
+ "longitude": 2.35,
+ "fatalities": 1,
+ },
+ # Unparseable coordinates: kept (cannot be deduplicated).
+ {
+ "event_date": "2026-08-30",
+ "event_type": "Protests",
+ "country": "France",
+ "latitude": "garbage",
+ "longitude": "2.0",
+ "fatalities": "n/a",
+ },
+ ]
+ monkeypatch.setattr(intelligence, "acled_query", _async_return({"data": raw}))
+
+ result = await intelligence.fetch_unrest_events(fetcher, country="France", days=3)
+
+ assert result["source"] == "acled-unrest"
+ assert result["count"] == 4
+ assert result["deduplicated"] == 1
+ assert result["query"] == {"country": "France", "days": 3}
+
+ first = result["events"][0]
+ assert first["location"] == "Paris"
+ assert first["latitude"] == 48.85 # string coerced to float
+ assert first["fatalities"] == 2 # merged from the deduplicated riot
+ assert first["sub_event_type"] == "Peaceful protest"
+
+ unparseable = result["events"][-1]
+ assert unparseable["latitude"] is None
+ assert unparseable["fatalities"] == 0 # "n/a" coerced to 0
+
+
+async def test_fetch_unrest_events_degraded_and_unconfigured(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(intelligence, "acled_query", _async_return(None))
+
+ monkeypatch.setattr(
+ intelligence, "acled_failure_reason", _fake_reason("acled_fetch_failed")
+ )
+ result = await intelligence.fetch_unrest_events(fetcher)
+ assert result["degraded"] is True
+ assert "fetch failed" in result["error"]
+
+ monkeypatch.setattr(
+ intelligence, "acled_failure_reason", _fake_reason("acled_unconfigured")
+ )
+ result = await intelligence.fetch_unrest_events(fetcher)
+ assert "not configured" in result["error"]
+ assert result.get("degraded") is None
+
+
+# ---------------------------------------------------------------------------
+# Function 9: fetch_hotspot_escalation (event-attribution path; the empty
+# path is covered by test_intelligence.py)
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_hotspot_escalation_attributes_nearby_events(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ acled_events = [
+ # Within 2 degrees of the gaza hotspot (31.42, 34.35).
+ {
+ "latitude": "31.50",
+ "longitude": "34.30",
+ "event_type": "Battles",
+ "fatalities": 12,
+ },
+ {
+ "latitude": "31.40",
+ "longitude": "34.40",
+ "event_type": "Protests",
+ "fatalities": 0,
+ },
+ ]
+ monkeypatch.setattr(
+ intelligence, "acled_query", _async_return({"data": acled_events})
+ )
+ monkeypatch.setattr(
+ military,
+ "fetch_theater_posture",
+ _async_return(
+ {
+ "theaters": {
+ "middle_east": {
+ "count": 10,
+ "countries": ["United States"],
+ "bbox": "10,25,45,65",
+ }
+ }
+ }
+ ),
+ )
+
+ result = await intelligence.fetch_hotspot_escalation(fetcher)
+
+ assert result["source"] == "hotspot-escalation"
+ assert result["count"] == len(result["hotspots"]) == 22
+ assert result["unavailable_components"] == ["news", "convergence"]
+ assert result["data_gaps"] == []
+
+ gaza = next(h for h in result["hotspots"] if h["name"] == "gaza")
+ comp = gaza["components"]
+ assert comp["baseline"] == 20.0 # baseline_escalation 5 x 4
+ # 1 conflict event x 0.5 + 12 fatalities x 0.1 = 1.7.
+ assert comp["conflict"] == 1.7
+ assert comp["social_unrest"] == 0.4 # 1 protest x 0.4
+ assert comp["news"] is None
+ assert comp["convergence"] is None
+ # Renormalized over measured components: 22.1 / 72 x 100 = 30.7.
+ assert gaza["score"] == 30.7
+ assert gaza["level"] == "watch"
+
+
+# ---------------------------------------------------------------------------
+# Function 10: fetch_military_surge
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_military_surge_detects_surge(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ monkeypatch.setattr(
+ intelligence, "_temporal", TemporalBaseline(db_path=str(tmp_path / "t.db"))
+ )
+ # 40 US aircraft in the european theater map onto baltic_sea, whose US
+ # baseline is 2 -> ratio 20 -> critical. black_sea has no US baseline,
+ # so nothing fires there.
+ monkeypatch.setattr(
+ military,
+ "fetch_theater_posture",
+ _async_return(
+ {"theaters": {"european": {"count": 40, "countries": ["United States"]}}}
+ ),
+ )
+
+ result = await intelligence.fetch_military_surge(fetcher)
+
+ assert result["source"] == "military-surge-detection"
+ assert result["regions_checked"] == 8
+ assert result["surge_count"] == 1
+ surge = result["surges"][0]
+ assert surge["region"] == "baltic_sea"
+ assert surge["country"] == "United States"
+ assert surge["current"] == 40
+ assert surge["baseline"] == 2
+ assert surge["surge_ratio"] == 20.0
+ assert surge["severity"] == "critical"
+
+
+async def test_fetch_military_surge_quiet_posture(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path
+) -> None:
+ monkeypatch.setattr(
+ intelligence, "_temporal", TemporalBaseline(db_path=str(tmp_path / "t.db"))
+ )
+ monkeypatch.setattr(
+ military, "fetch_theater_posture", _async_return({"theaters": {}})
+ )
+
+ result = await intelligence.fetch_military_surge(fetcher)
+ assert result["surges"] == []
+ assert result["surge_count"] == 0
+
+
+# ---------------------------------------------------------------------------
+# Function 11: fetch_vessel_snapshot
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_vessel_snapshot_naval_keywords(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Suspected bug (documented, not fixed): the loop matches naval
+ keywords against ALL warnings with no proximity/navarea filter, so
+ every one of the 9 waterways receives the identical naval count and
+ status — 3 naval warnings anywhere on Earth mark Panama and Hormuz
+ 'critical' alike."""
+ warnings = [
+ {"id": "2026-1", "text": "NAVAL EXERCISES IN AREA", "navarea": "IV"},
+ {"id": "2026-2", "text": "SUBMARINE OPERATIONS", "navarea": "XI"},
+ {"id": "2026-3", "text": "LIVE FIRING IN PROGRESS", "navarea": "IX"},
+ {"id": "2026-4", "text": "BUOY UNLIT", "navarea": "IV"},
+ ]
+ monkeypatch.setattr(
+ maritime, "fetch_nav_warnings", _async_return({"warnings": warnings})
+ )
+
+ result = await intelligence.fetch_vessel_snapshot(fetcher)
+
+ assert result["source"] == "nga-msi-vessel-snapshot"
+ assert result["count"] == 9
+ assert result["total_nav_warnings"] == 4
+
+ names = {w["name"] for w in result["waterways"]}
+ assert "Strait of Hormuz" in names
+ for ww in result["waterways"]:
+ assert ww["naval_warnings"] == 3 # keyword matches; BUOY UNLIT excluded
+ assert ww["status"] == "critical" # >= 3 naval warnings
+ assert len(ww["warning_details"]) == 3
+
+
+async def test_fetch_vessel_snapshot_clear(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(maritime, "fetch_nav_warnings", _async_return({"warnings": []}))
+
+ result = await intelligence.fetch_vessel_snapshot(fetcher)
+ assert all(ww["status"] == "clear" for ww in result["waterways"])
+ assert all(ww["naval_warnings"] == 0 for ww in result["waterways"])
+
+
+# ---------------------------------------------------------------------------
+# Function 12: fetch_cascade_analysis
+# ---------------------------------------------------------------------------
+
+
+async def test_fetch_cascade_analysis_specific_corridor(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ infrastructure,
+ "fetch_cable_health",
+ _async_return(
+ {"corridors": {"red_sea": {"status_score": 3, "status_label": "disrupted"}}}
+ ),
+ )
+
+ result = await intelligence.fetch_cascade_analysis(fetcher, corridor="red_sea")
+
+ assert result["source"] == "cascade-analysis"
+ assert result["scenario_count"] == 1
+ scenario = result["scenarios"][0]
+ assert scenario["scenario"] == "Disruption of red_sea"
+ assert scenario["corridors"] == ["red_sea"]
+ assert scenario["disrupted"] == ["red_sea"]
+ # Djibouti carries the highest red_sea dependency (0.8): with full
+ # disruption severity it must top the impact list at score 80.
+ top_impact = scenario["country_impacts"][0]
+ assert top_impact["country"] == "Djibouti"
+ assert top_impact["impact_score"] == 80
+ assert top_impact["risk_level"] == "critical"
+
+ assert result["current_health"]["red_sea"]["status_score"] == 3
+ assert result["current_health"]["red_sea"]["status_label"] == "disrupted"
+
+
+async def test_fetch_cascade_analysis_no_at_risk_corridors(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ infrastructure,
+ "fetch_cable_health",
+ _async_return(
+ {
+ "corridors": {
+ "red_sea": {"status_score": 0, "status_label": "clear"},
+ "asia_europe": {"status_score": 1, "status_label": "advisory"},
+ }
+ }
+ ),
+ )
+
+ result = await intelligence.fetch_cascade_analysis(fetcher)
+ assert result["scenario_count"] == 1
+ assert (
+ result["scenarios"][0]["scenario"]
+ == "Hypothetical: Red Sea corridor disruption"
+ )
+
+
+async def test_fetch_cascade_analysis_multiple_at_risk(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(
+ infrastructure,
+ "fetch_cable_health",
+ _async_return(
+ {
+ "corridors": {
+ "red_sea": {"status_score": 2, "status_label": "at_risk"},
+ "asia_europe": {"status_score": 3, "status_label": "disrupted"},
+ }
+ }
+ ),
+ )
+
+ result = await intelligence.fetch_cascade_analysis(fetcher)
+ # Two individual scenarios plus the combined worst case.
+ assert result["scenario_count"] == 3
+ labels = [s["scenario"] for s in result["scenarios"]]
+ assert "Disruption of red_sea" in labels
+ assert "Disruption of asia_europe" in labels
+ assert "Combined disruption (worst case)" in labels
+ combined = next(
+ s
+ for s in result["scenarios"]
+ if s["scenario"] == "Combined disruption (worst case)"
+ )
+ assert sorted(combined["corridors"]) == ["asia_europe", "red_sea"]
diff --git a/src/world_intel_mcp/tests/test_sources_maritime.py b/src/world_intel_mcp/tests/test_sources_maritime.py
new file mode 100644
index 0000000..8207f39
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_maritime.py
@@ -0,0 +1,170 @@
+"""Tests for sources/maritime.py — respx-mocked NGA MSI broadcast warnings.
+
+Gaps / not covered: live NGA payload variants beyond the three shapes the
+module handles (list, dict-with-key, single dict); coordinate strings with
+seconds notation (the regex only handles degrees-minutes).
+"""
+
+import asyncio as asyncio_mod
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources.maritime import (
+ NAVAREAS,
+ _extract_coords,
+ _is_active,
+ _parse_warning,
+ fetch_nav_warnings,
+)
+
+_W_GULF = {
+ "msgYear": 2026,
+ "msgNumber": 100,
+ "navArea": "IV",
+ "subregion": "24",
+ "status": "in force",
+ "issueDate": "2026-08-30",
+ "text": (
+ "GULF OF MEXICO. HAZARDOUS OPERATIONS 22-16.65N 097-44.48W. "
+ "WIDE BERTH REQUESTED."
+ ),
+ "authority": "NGA",
+}
+_W_CANCELLED = {
+ "msgYear": 2026,
+ "msgNumber": 90,
+ "navArea": "IV",
+ "issueDate": "2026-07-01",
+ "cancelDate": "2026-08-01",
+ "text": "CANCELLED WARNING.",
+}
+_W_PACIFIC = {
+ "msgYear": 2026,
+ "msgNumber": 200,
+ "navArea": "XII",
+ "issueDate": "2026-08-31",
+ "text": "ROCKET LAUNCHING HAZARD AREA.", # no coordinates
+}
+_W_LONG = {
+ "msgYear": 2026,
+ "msgNumber": 300,
+ "navArea": "IV",
+ "issueDate": "2026-08-29",
+ "text": "A" * 600,
+}
+
+
+async def test_fetch_nav_warnings_list_payload(fetcher: Fetcher) -> None:
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(
+ return_value=httpx.Response(
+ 200, json=[_W_GULF, _W_CANCELLED, _W_PACIFIC, _W_LONG]
+ )
+ )
+
+ result = await fetch_nav_warnings(fetcher)
+
+ assert result["source"] == "nga-msi"
+ # Cancelled warning excluded.
+ assert result["count"] == 3
+ ids = [w["id"] for w in result["warnings"]]
+ assert "2026-90" not in ids
+ # Sorted by issue_date descending: Aug 31, Aug 30, Aug 29.
+ assert ids == ["2026-200", "2026-100", "2026-300"]
+
+ gulf = next(w for w in result["warnings"] if w["id"] == "2026-100")
+ assert gulf["navarea"] == "IV"
+ assert gulf["subregion"] == "24"
+ assert gulf["status"] == "active"
+ assert gulf["cancel_date"] is None
+ # 22 + 16.65/60 = 22.2775 N; 97 + 44.48/60 = 97.7413 W (negative).
+ assert gulf["lat"] == 22.2775
+ assert gulf["lon"] == -97.7413
+
+ pacific = next(w for w in result["warnings"] if w["id"] == "2026-200")
+ assert pacific["lat"] is None
+ assert pacific["lon"] is None
+
+ long_w = next(w for w in result["warnings"] if w["id"] == "2026-300")
+ assert len(long_w["text"]) == 503 # 500 chars + "..."
+ assert long_w["text"].endswith("...")
+
+ assert result["by_navarea"] == {"XII": 1, "IV": 2}
+ assert result["navareas"] == NAVAREAS
+
+
+async def test_fetch_nav_warnings_navarea_filter_case_insensitive(
+ fetcher: Fetcher,
+) -> None:
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(
+ return_value=httpx.Response(200, json=[_W_GULF, _W_PACIFIC])
+ )
+
+ result = await fetch_nav_warnings(fetcher, navarea="xii")
+ assert result["count"] == 1
+ assert result["warnings"][0]["id"] == "2026-200"
+ assert result["by_navarea"] == {"XII": 1}
+
+
+async def test_fetch_nav_warnings_dict_payload_single_warning(
+ fetcher: Fetcher,
+) -> None:
+ # The API sometimes wraps a single warning dict under "broadcast-warn".
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(
+ return_value=httpx.Response(200, json={"broadcast-warn": _W_GULF})
+ )
+
+ result = await fetch_nav_warnings(fetcher)
+ assert result["count"] == 1
+ assert result["warnings"][0]["id"] == "2026-100"
+
+
+async def test_fetch_nav_warnings_api_down(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Observation (flagged in review, not fixed): an NGA outage returns
+ warnings=[] with no error key — shape-identical to calm seas."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(return_value=httpx.Response(500))
+
+ result = await fetch_nav_warnings(fetcher)
+ assert result["warnings"] == []
+ assert result["count"] == 0
+ assert result["by_navarea"] == {}
+ assert "error" not in result # current (dishonest-quiet) behavior
+
+
+def test_extract_coords() -> None:
+ assert _extract_coords("22-16.65N 097-44.48W") == (22.2775, -97.7413)
+ # Southern/eastern hemisphere signs.
+ assert _extract_coords("05-30.0S 120-15.0E") == (-5.5, 120.25)
+ assert _extract_coords("no coordinates here") == (None, None)
+ assert _extract_coords("") == (None, None)
+
+
+def test_is_active_and_parse_warning() -> None:
+ assert _is_active({"cancelDate": None}) is True
+ assert _is_active({"cancelDate": ""}) is True
+ assert _is_active({"cancelDate": "2026-08-01"}) is False
+
+ parsed = _parse_warning(_W_CANCELLED)
+ assert parsed["status"] == "cancelled"
+ assert parsed["cancel_date"] == "2026-08-01"
+
+ # Missing msgYear/msgNumber leaves id as None.
+ assert _parse_warning({"text": "x"})["id"] is None
diff --git a/src/world_intel_mcp/tests/test_sources_military.py b/src/world_intel_mcp/tests/test_sources_military.py
new file mode 100644
index 0000000..b07877a
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_military.py
@@ -0,0 +1,222 @@
+"""Tests for sources/military.py parsing/filtering helpers and bbox plumbing.
+
+Deliberately scoped to what test_sources.py does NOT already cover
+(fetch_aircraft_details_batch lives there): _is_military_icao,
+_is_military_callsign, _extract_aircraft, _icao_to_country, and the bbox
+parameter path through both the adsb.lol client-side filter and the
+OpenSky query-parameter fallback.
+
+Gaps / not covered: fetch_theater_posture aggregation (exercised
+indirectly by intelligence tests via monkeypatch, not live here);
+OpenSky auth-header construction with real credentials.
+"""
+
+import asyncio as asyncio_mod
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources.military import (
+ _extract_aircraft,
+ _icao_to_country,
+ _is_military_callsign,
+ _is_military_icao,
+ fetch_military_flights,
+)
+
+# OpenSky state vector: index 0 icao24, 1 callsign, 2 origin_country,
+# 5 lon, 6 lat, 7 baro alt, 8 on_ground, 9 velocity, 10 heading, 14 squawk.
+_MIL_STATE = [
+ "ae1234",
+ "RCH285 ",
+ "United States",
+ None,
+ None,
+ -70.0,
+ 40.0,
+ 10000.0,
+ False,
+ 250.0,
+ 90.0,
+ None,
+ None,
+ None,
+ "7700",
+ None,
+ None,
+]
+_CIV_STATE = [
+ "4ca123",
+ "UAL123 ",
+ "Ireland",
+ None,
+ None,
+ -71.0,
+ 41.0,
+ 11000.0,
+ False,
+ 240.0,
+ 91.0,
+ None,
+ None,
+ None,
+ "1200",
+ None,
+ None,
+]
+
+
+def test_is_military_icao() -> None:
+ assert _is_military_icao("AE1234") is True
+ assert _is_military_icao("ae1234") is True # case-insensitive
+ assert _is_military_icao("43C001") is True # UK military
+ assert _is_military_icao("ABC123") is True # "AB" US extended range
+ assert _is_military_icao("700111") is True # Pakistan
+ assert _is_military_icao("4CA123") is False # civilian Ireland
+ assert _is_military_icao("A00001") is False
+
+
+def test_is_military_callsign() -> None:
+ assert _is_military_callsign("RCH285") is True
+ assert _is_military_callsign(" duke01 ") is True # stripped + upper
+ assert _is_military_callsign("SAM946") is True
+ assert _is_military_callsign("UAL123") is False
+ assert _is_military_callsign("") is False
+ assert _is_military_callsign(None) is False
+
+
+def test_extract_aircraft_state_vector_mapping() -> None:
+ ac = _extract_aircraft(_MIL_STATE)
+ assert ac == {
+ "icao24": "ae1234",
+ "callsign": "RCH285", # stripped
+ "origin_country": "United States",
+ "latitude": 40.0,
+ "longitude": -70.0,
+ "altitude_m": 10000.0,
+ "velocity_ms": 250.0,
+ "heading": 90.0,
+ "on_ground": False,
+ "squawk": "7700",
+ }
+
+ # Empty callsign maps to None, not "".
+ no_callsign = list(_MIL_STATE)
+ no_callsign[1] = ""
+ assert _extract_aircraft(no_callsign)["callsign"] is None
+
+
+def test_icao_to_country_longest_prefix_wins() -> None:
+ assert _icao_to_country("ae9999") == "United States"
+ assert _icao_to_country("43C001") == "United Kingdom"
+ assert _icao_to_country("3AA111") == "France"
+ assert _icao_to_country("3F0000") == "Germany"
+ assert _icao_to_country("FFFFFF") == ""
+
+
+async def test_fetch_military_flights_adsblol_bbox_client_side_filter(
+ fetcher: Fetcher,
+) -> None:
+ respx.get(url__regex=r".*api\.adsb\.lol/v2/mil.*").mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "ac": [
+ {
+ "hex": "ae1234",
+ "flight": "RCH285 ",
+ "lat": 40.0,
+ "lon": -70.0,
+ "alt_baro": 30000,
+ "gs": 450,
+ "track": 90,
+ "squawk": "1200",
+ "t": "C17",
+ "r": "02-1099",
+ },
+ {
+ "hex": "3f8abc",
+ "flight": "GAF123",
+ "lat": 10.0,
+ "lon": 10.0,
+ "alt_baro": 25000,
+ },
+ # No position — dropped during normalization.
+ {"hex": "aaa000", "lat": None, "lon": 5.0},
+ ]
+ },
+ )
+ )
+
+ # Without bbox: both positioned aircraft survive.
+ result = await fetch_military_flights(fetcher)
+ assert result["source"] == "adsb.lol"
+ assert result["military_filter"] == "adsblol_mil_endpoint"
+ assert result["count"] == 2
+ us_bird = next(a for a in result["aircraft"] if a["icao24"] == "ae1234")
+ assert us_bird["callsign"] == "RCH285"
+ assert us_bird["origin_country"] == "United States" # derived from prefix
+ assert us_bird["aircraft_type"] == "C17"
+ assert us_bird["registration"] == "02-1099"
+ assert us_bird["on_ground"] is False
+
+ # With bbox: only the aircraft inside 35..45 lat / -80..-60 lon remains
+ # (second call is served from cache, so no rate-limit stall).
+ result = await fetch_military_flights(fetcher, bbox="35,-80,45,-60")
+ assert result["count"] == 1
+ assert result["aircraft"][0]["icao24"] == "ae1234"
+
+
+async def test_fetch_military_flights_opensky_fallback_bbox_params(
+ fetcher: Fetcher,
+) -> None:
+ # adsb.lol answers but with zero aircraft -> falls through to OpenSky.
+ respx.get(url__regex=r".*api\.adsb\.lol/v2/mil.*").mock(
+ return_value=httpx.Response(200, json={"ac": []})
+ )
+ opensky_route = respx.get(url__regex=r".*opensky-network\.org.*").mock(
+ return_value=httpx.Response(200, json={"states": [_MIL_STATE, _CIV_STATE]})
+ )
+
+ result = await fetch_military_flights(fetcher, bbox="10,20,30,40")
+
+ assert result["source"] == "opensky"
+ assert result["military_filter"] == "icao_prefix+callsign"
+ # Civilian state (non-military icao AND non-military callsign) filtered.
+ assert result["count"] == 1
+ assert result["aircraft"][0]["icao24"] == "ae1234"
+
+ # bbox must be plumbed into OpenSky query params, in OpenSky's naming.
+ params = opensky_route.calls.last.request.url.params
+ assert params["lamin"] == "10"
+ assert params["lomin"] == "20"
+ assert params["lamax"] == "30"
+ assert params["lomax"] == "40"
+
+
+async def test_fetch_military_flights_both_sources_down(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+
+ respx.get(url__regex=r".*api\.adsb\.lol.*").mock(return_value=httpx.Response(500))
+ respx.get(url__regex=r".*opensky-network\.org.*").mock(
+ return_value=httpx.Response(500)
+ )
+
+ result = await fetch_military_flights(fetcher)
+ # Honest degradation: source says "none" rather than claiming a feed.
+ assert result["source"] == "none"
+ assert result["aircraft"] == []
+ assert result["count"] == 0
diff --git a/src/world_intel_mcp/tests/test_sources_news.py b/src/world_intel_mcp/tests/test_sources_news.py
new file mode 100644
index 0000000..49086d4
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_news.py
@@ -0,0 +1,257 @@
+"""Tests for sources/news.py — RSS aggregation, trending keywords, GDELT.
+
+Complements test_sources.py, which already covers the GDELT artlist
+degraded-vs-zero distinction (issue #17). This file covers the RSS feed
+aggregation contract, keyword trending, the GDELT artlist/timeline success
+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).
+"""
+
+import asyncio as asyncio_mod
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources import news
+from world_intel_mcp.sources.news import (
+ _RSS_FEEDS,
+ _parse_published,
+ _truncate,
+ fetch_gdelt_search,
+ fetch_news_feed,
+ fetch_trending_keywords,
+)
+
+_LONG_SUMMARY = "S" * 250
+
+_RSS = f"""<?xml version="1.0" encoding="UTF-8"?>
+<rss version="2.0"><channel><title>Feed</title>
+<item>
+ <title>Newer headline</title>
+ <link>https://news.example/1</link>
+ <pubDate>Mon, 31 Aug 2026 14:00:00 GMT</pubDate>
+ <description>{_LONG_SUMMARY}</description>
+</item>
+<item>
+ <title>Older headline</title>
+ <link>https://news.example/2</link>
+ <pubDate>Sun, 30 Aug 2026 10:00:00 GMT</pubDate>
+ <description>Short summary.</description>
+</item>
+</channel></rss>"""
+
+
+async def test_fetch_news_feed_single_category(fetcher: Fetcher) -> None:
+ respx.route().mock(return_value=httpx.Response(200, text=_RSS))
+
+ result = await fetch_news_feed(fetcher, category="security")
+
+ assert result["source"] == "rss-aggregator"
+ assert result["categories_fetched"] == ["security"]
+ # Every security feed returns the same 2-item RSS document.
+ assert result["count"] == 2 * len(_RSS_FEEDS["security"])
+
+ item = result["items"][0]
+ assert item["category"] == "security"
+ assert item["feed_name"] in {name for name, _ in _RSS_FEEDS["security"]}
+ assert "source_tier" in item
+ # Sorted by published descending: every "Newer headline" copy precedes
+ # every "Older headline" copy.
+ titles = [i["title"] for i in result["items"]]
+ assert titles.index("Older headline") == len(_RSS_FEEDS["security"])
+ # 250-char summary truncated to 200 + ellipsis.
+ newer = next(i for i in result["items"] if i["title"] == "Newer headline")
+ assert newer["summary"] == "S" * 200 + "..."
+ assert newer["link"] == "https://news.example/1"
+ older = next(i for i in result["items"] if i["title"] == "Older headline")
+ assert older["summary"] == "Short summary."
+
+
+async def test_fetch_news_feed_limit(fetcher: Fetcher) -> None:
+ respx.route().mock(return_value=httpx.Response(200, text=_RSS))
+
+ result = await fetch_news_feed(fetcher, category="security", limit=3)
+ assert result["count"] == 3
+ assert len(result["items"]) == 3
+
+
+async def test_fetch_news_feed_unknown_category(fetcher: Fetcher) -> None:
+ result = await fetch_news_feed(fetcher, category="astrology")
+ assert "Unknown category" in result["error"]
+ assert result["items"] == []
+ assert result["count"] == 0
+ assert result["categories_fetched"] == []
+
+
+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."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+
+ respx.route().mock(return_value=httpx.Response(500))
+
+ result = await fetch_news_feed(fetcher, category="security")
+ assert result["items"] == []
+ assert result["count"] == 0
+ assert result["categories_fetched"] == ["security"]
+ assert "error" not in result # current (dishonest-quiet) behavior
+
+
+async def test_fetch_trending_keywords(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ items = [
+ {"title": "Ukraine's grid attacked"},
+ {"title": "Drone raid hits Ukraine depot"},
+ {"title": "Ukraine counteroffensive stalls; drone losses mount"},
+ {"title": ""}, # empty title tolerated
+ ]
+
+ async def _fake_feed(f, category=None, limit=50):
+ return {"items": items}
+
+ monkeypatch.setattr(news, "fetch_news_feed", _fake_feed)
+
+ result = await fetch_trending_keywords(fetcher, min_count=3)
+
+ assert result["source"] == "keyword-analysis"
+ assert result["total_items_analyzed"] == 4
+ # "ukraine" appears 3x (possessive punctuation stripped); "drone" only
+ # 2x so it must fall below min_count=3.
+ assert result["keywords"] == [{"word": "ukraine", "count": 3}]
+
+
+async def test_fetch_trending_keywords_min_count_filter(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _fake_feed(f, category=None, limit=50):
+ return {"items": [{"title": "Taiwan strait tension"}] * 2}
+
+ monkeypatch.setattr(news, "fetch_news_feed", _fake_feed)
+
+ result = await fetch_trending_keywords(fetcher, min_count=2)
+ words = {k["word"]: k["count"] for k in result["keywords"]}
+ # Stopwords and <3-char tokens never appear.
+ assert words == {"taiwan": 2, "strait": 2, "tension": 2}
+
+
+async def test_fetch_gdelt_search_artlist_success(fetcher: Fetcher) -> None:
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "articles": [
+ {
+ "title": "Border clash reported",
+ "url": "https://example.com/a1",
+ "seendate": "20260831T120000Z",
+ "socialimage": "",
+ "domain": "example.com",
+ "language": "English",
+ "sourcecountry": "France",
+ }
+ ]
+ },
+ )
+ )
+
+ result = await fetch_gdelt_search(fetcher, query="border clash", limit=10)
+
+ assert result["source"] == "gdelt"
+ assert result["mode"] == "artlist"
+ assert result["query"] == "border clash"
+ assert result["count"] == 1
+ article = result["articles"][0]
+ assert article["title"] == "Border clash reported"
+ assert article["url"] == "https://example.com/a1"
+ assert article["domain"] == "example.com"
+ assert article["sourcecountry"] == "France"
+ assert result.get("error") is None
+ assert result.get("degraded") is None
+
+
+async def test_fetch_gdelt_search_timeline_mode(fetcher: Fetcher) -> None:
+ timeline = [
+ {"series": "Volume Intensity", "data": [{"date": "20260830", "value": 1.2}]}
+ ]
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(
+ return_value=httpx.Response(200, json={"timeline": timeline})
+ )
+
+ result = await fetch_gdelt_search(fetcher, query="coup", mode="timelinevol")
+ assert result["mode"] == "timelinevol"
+ assert result["timeline"] == timeline
+ assert result["count"] == 1
+
+
+async def test_fetch_gdelt_search_timeline_degraded_shape(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Issue-#17 contract in timeline mode: a failed fetch keeps timeline
+ as its normal empty-list shape while flagging degradation."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+
+ respx.get(url__regex=r".*api\.gdeltproject\.org.*").mock(
+ return_value=httpx.Response(429, text="rate limited")
+ )
+
+ result = await fetch_gdelt_search(fetcher, query="coup", mode="timelinevol")
+ assert result["degraded"] is True
+ assert result["reason"] == "gdelt_fetch_failed"
+ assert result["timeline"] == []
+ assert result["articles"] is None
+ assert result["count"] == 0
+
+
+def test_truncate() -> None:
+ assert _truncate(None) == ""
+ assert _truncate("") == ""
+ assert _truncate("short") == "short"
+ assert _truncate("x" * 200) == "x" * 200 # exactly at the limit
+ assert _truncate("x" * 201) == "x" * 200 + "..."
+
+
+def test_parse_published_fallbacks() -> None:
+ import time as time_mod
+
+ parsed = _parse_published({"published_parsed": time_mod.gmtime(1700000000)})
+ assert parsed is not None and parsed.endswith("Z")
+
+ updated = _parse_published({"updated_parsed": time_mod.gmtime(1700000000)})
+ assert updated is not None and updated.endswith("Z")
+
+ assert _parse_published({"published": "raw"}) == "raw"
+ assert _parse_published({"updated": "raw2"}) == "raw2"
+ assert _parse_published({}) is None
diff --git a/src/world_intel_mcp/tests/test_sources_prediction.py b/src/world_intel_mcp/tests/test_sources_prediction.py
new file mode 100644
index 0000000..79f1de6
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_prediction.py
@@ -0,0 +1,152 @@
+"""Tests for sources/prediction.py — respx-mocked Polymarket Gamma API.
+
+Gaps / not covered: real Gamma API schema drift; the module's documented
+"empty results on upstream failure" contract carries no degraded marker,
+which is asserted as-is (see the api-down test).
+"""
+
+import asyncio as asyncio_mod
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources.prediction import (
+ _classify_sentiment,
+ _parse_outcome_prices,
+ _safe_float,
+ fetch_prediction_markets,
+)
+
+_MARKETS = [
+ {
+ "question": "Will X happen by 2027?",
+ "outcomePrices": "[0.9, 0.1]",
+ "volume24hr": "1000.5",
+ "volume": "50000",
+ "liquidity": "200",
+ "category": "politics",
+ "slug": "will-x",
+ },
+ {
+ "question": "Coin flip?",
+ "outcomePrices": "[0.5, 0.5]",
+ "volume24hr": 2000,
+ "volume": 9000,
+ "liquidity": 100,
+ "category": "fun",
+ "slug": "",
+ },
+ # Unparseable outcomePrices -> skipped entirely.
+ {"question": "Broken", "outcomePrices": "notjson", "volume24hr": 99999},
+ {
+ "question": "Will Y collapse?",
+ "outcomePrices": "[0.05, 0.95]",
+ "volume24hr": 1,
+ "volume": 10,
+ "liquidity": 5,
+ "category": "econ",
+ "slug": "will-y",
+ },
+ "garbage-non-dict-entry",
+]
+
+
+async def test_fetch_prediction_markets_parses_and_sorts(fetcher: Fetcher) -> None:
+ route = respx.get(url__regex=r".*gamma-api\.polymarket\.com/markets.*").mock(
+ return_value=httpx.Response(200, json=_MARKETS)
+ )
+
+ result = await fetch_prediction_markets(fetcher, limit=20)
+
+ assert result["source"] == "polymarket"
+ # Broken and non-dict entries skipped.
+ assert result["count"] == 3
+ # Sorted by 24h volume descending: 2000, 1000.5, 1.
+ assert [m["volume_24h"] for m in result["markets"]] == [2000.0, 1000.5, 1.0]
+
+ top = result["markets"][0]
+ assert top["question"] == "Coin flip?"
+ assert top["yes_probability"] == 0.5
+ assert top["sentiment"] == "uncertain"
+ assert top["url"] == "" # empty slug -> no URL fabricated
+
+ second = result["markets"][1]
+ assert second["yes_probability"] == 0.9
+ assert second["sentiment"] == "strong_yes"
+ assert second["url"] == "https://polymarket.com/event/will-x"
+ assert second["total_volume"] == 50000.0
+ assert second["liquidity"] == 200.0
+ assert second["category"] == "politics"
+
+ assert result["markets"][2]["sentiment"] == "strong_no"
+
+ # Query contract sent to the API.
+ params = route.calls.last.request.url.params
+ assert params["active"] == "true"
+ assert params["closed"] == "false"
+ assert params["limit"] == "20"
+
+
+async def test_fetch_prediction_markets_api_down(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Upstream failure returns the documented empty shape. Observation
+ (flagged in review, not fixed): there is no degraded/error marker, so
+ an outage is shape-identical to a market lull."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+
+ respx.get(url__regex=r".*gamma-api\.polymarket\.com.*").mock(
+ return_value=httpx.Response(500)
+ )
+
+ result = await fetch_prediction_markets(fetcher)
+ assert result["markets"] == []
+ assert result["count"] == 0
+ assert result["source"] == "polymarket"
+
+
+async def test_fetch_prediction_markets_non_list_response(fetcher: Fetcher) -> None:
+ respx.get(url__regex=r".*gamma-api\.polymarket\.com.*").mock(
+ return_value=httpx.Response(200, json={"unexpected": "dict"})
+ )
+
+ result = await fetch_prediction_markets(fetcher)
+ assert result["markets"] == []
+ assert result["count"] == 0
+
+
+def test_parse_outcome_prices() -> None:
+ assert _parse_outcome_prices(None) is None
+ assert _parse_outcome_prices("notjson") is None
+ assert _parse_outcome_prices("[]") is None
+ assert _parse_outcome_prices("{}") is None
+ assert _parse_outcome_prices("[0.7, 0.3]") == 0.7
+ assert _parse_outcome_prices('["0.25", "0.75"]') == 0.25
+
+
+def test_classify_sentiment_boundaries() -> None:
+ assert _classify_sentiment(0.86) == "strong_yes"
+ assert _classify_sentiment(0.85) == "leaning_yes" # boundary is strict >
+ assert _classify_sentiment(0.66) == "leaning_yes"
+ assert _classify_sentiment(0.5) == "uncertain"
+ assert _classify_sentiment(0.34) == "leaning_no"
+ assert _classify_sentiment(0.14) == "strong_no"
+
+
+def test_safe_float() -> None:
+ assert _safe_float(None) == 0.0
+ assert _safe_float("1.5") == 1.5
+ assert _safe_float("x") == 0.0
+ assert _safe_float(3) == 3.0
diff --git a/src/world_intel_mcp/tests/test_sources_service_status.py b/src/world_intel_mcp/tests/test_sources_service_status.py
new file mode 100644
index 0000000..9015620
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_sources_service_status.py
@@ -0,0 +1,198 @@
+"""Tests for sources/service_status.py — respx-mocked provider RSS feeds.
+
+Gaps / not covered: real feed schema drift per provider; feedparser's
+timezone handling of published_parsed (asserted for shape, not exact
+instant, because time.mktime interprets the tuple in local time).
+"""
+
+import asyncio as asyncio_mod
+import time as time_mod
+
+import httpx
+import pytest
+import respx
+
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources.service_status import (
+ _STATUS_FEEDS,
+ _classify_severity,
+ _parse_published,
+ fetch_service_status,
+)
+
+# Three items: critical (major outage), info (maintenance), medium
+# (investigating). Active per provider = 2 (critical + medium).
+_RSS = """<?xml version="1.0" encoding="UTF-8"?>
+<rss version="2.0"><channel><title>Status</title>
+<item>
+ <title>Major outage: API errors in us-east-1</title>
+ <link>https://status.example/1</link>
+ <pubDate>Mon, 31 Aug 2026 14:00:00 GMT</pubDate>
+ <description>Widespread API failures.</description>
+</item>
+<item>
+ <title>Scheduled maintenance window</title>
+ <link>https://status.example/2</link>
+ <pubDate>Sun, 30 Aug 2026 10:00:00 GMT</pubDate>
+ <description>Planned maintenance.</description>
+</item>
+<item>
+ <title>Investigating connectivity issues</title>
+ <link>https://status.example/3</link>
+ <pubDate>Sat, 29 Aug 2026 08:00:00 GMT</pubDate>
+ <description>We are looking into reports.</description>
+</item>
+</channel></rss>"""
+
+_FEED_PATTERNS = {
+ "AWS": r".*status\.aws\.amazon\.com.*",
+ "Azure": r".*azurestatuscdn\.azureedge\.net.*",
+ "GCP": r".*status\.cloud\.google\.com.*",
+ "Cloudflare": r".*cloudflarestatus\.com.*",
+ "GitHub": r".*githubstatus\.com.*",
+}
+
+
+def _mock_all_feeds() -> None:
+ for pattern in _FEED_PATTERNS.values():
+ respx.get(url__regex=pattern).mock(return_value=httpx.Response(200, text=_RSS))
+
+
+async def test_fetch_service_status_all_providers(fetcher: Fetcher) -> None:
+ _mock_all_feeds()
+
+ result = await fetch_service_status(fetcher)
+
+ assert result["source"] == "service-status"
+ assert result["count"] == 15 # 3 items x 5 providers
+ assert result["by_provider"] == {
+ "AWS": 3,
+ "Azure": 3,
+ "GCP": 3,
+ "Cloudflare": 3,
+ "GitHub": 3,
+ }
+ assert sorted(result["providers_checked"]) == sorted(
+ f["provider"] for f in _STATUS_FEEDS
+ )
+ # critical + medium are active; info is not: 2 per provider.
+ assert result["active_incidents"] == 10
+
+ # Field contract on one incident, values derived from the RSS.
+ incident = next(
+ i
+ for i in result["incidents"]
+ if i["provider"] == "GitHub" and "Major outage" in i["title"]
+ )
+ assert incident["severity"] == "critical"
+ assert incident["link"] == "https://status.example/1"
+ assert incident["summary"] == "Widespread API failures."
+ assert incident["published"] is not None
+
+ # Sorted by published descending: newest (Aug 31) first.
+ assert "Major outage" in result["incidents"][0]["title"]
+
+
+async def test_fetch_service_status_provider_filter(fetcher: Fetcher) -> None:
+ # Only the GitHub feed is mocked; any other request would error under
+ # respx, so a green run proves the filter fetches exactly one feed.
+ respx.get(url__regex=_FEED_PATTERNS["GitHub"]).mock(
+ return_value=httpx.Response(200, text=_RSS)
+ )
+
+ result = await fetch_service_status(fetcher, provider="github")
+ assert result["providers_checked"] == ["GitHub"]
+ assert result["count"] == 3
+ assert set(result["by_provider"]) == {"GitHub"}
+
+
+async def test_fetch_service_status_unknown_provider(fetcher: Fetcher) -> None:
+ result = await fetch_service_status(fetcher, provider="nonexistent-cloud")
+ assert "Unknown provider" in result["error"]
+ assert result["incidents"] == []
+ assert result["count"] == 0
+
+
+async def test_fetch_service_status_one_feed_down(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A failing feed contributes zero incidents while others still report.
+ Observation (flagged in review, not fixed): the response does not say
+ WHICH provider's feed failed — a dead AWS feed is shape-identical to a
+ healthy AWS with no incidents."""
+
+ async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+
+ for provider, pattern in _FEED_PATTERNS.items():
+ if provider == "AWS":
+ respx.get(url__regex=pattern).mock(return_value=httpx.Response(500))
+ else:
+ respx.get(url__regex=pattern).mock(
+ return_value=httpx.Response(200, text=_RSS)
+ )
+
+ result = await fetch_service_status(fetcher)
+ assert result["count"] == 12 # 3 x 4 surviving providers
+ assert "AWS" not in result["by_provider"]
+ assert "AWS" in result["providers_checked"] # still claimed as checked
+
+
+async def test_resolved_incident_with_severity_words_counts_active(
+ fetcher: Fetcher,
+) -> None:
+ """Suspected bug (documented, not fixed): _SEVERITY_KEYWORDS is scanned
+ in insertion order and "major"/"outage" precede "resolved", so a
+ 'Resolved: Major outage' post-mortem classifies as critical and inflates
+ active_incidents."""
+ rss = """<?xml version="1.0"?>
+ <rss version="2.0"><channel><title>S</title>
+ <item><title>Resolved: Major outage restored</title>
+ <link>https://status.example/9</link>
+ <description>All clear.</description></item>
+ </channel></rss>"""
+
+ respx.get(url__regex=_FEED_PATTERNS["GitHub"]).mock(
+ return_value=httpx.Response(200, text=rss)
+ )
+
+ result = await fetch_service_status(fetcher, provider="github")
+ assert result["incidents"][0]["severity"] == "critical" # current behavior
+ assert result["active_incidents"] == 1 # inflated
+
+
+def test_classify_severity() -> None:
+ assert _classify_severity("Major outage", "") == "critical"
+ assert _classify_severity("Service disruption", "") == "high"
+ assert _classify_severity("Degraded performance", "") == "high"
+ assert _classify_severity("Partial impairment", "") == "medium"
+ assert _classify_severity("Investigating reports", "") == "medium"
+ assert _classify_severity("Resolved", "") == "resolved"
+ assert _classify_severity("Monitoring recovery", "") == "low"
+ assert _classify_severity("Scheduled maintenance", "") == "info"
+ assert _classify_severity("Something else entirely", "") == "unknown"
+ # Keyword can live in the summary, not just the title.
+ assert _classify_severity("Update", "elevated error rates observed") == "high"
+
+
+def test_parse_published() -> None:
+ entry = {"published_parsed": time_mod.gmtime(1700000000)}
+ parsed = _parse_published(entry)
+ assert parsed is not None
+ assert parsed.endswith("Z") # ISO-8601 UTC shape
+
+ # Fallback to the raw string fields when no parsed tuple exists.
+ assert _parse_published({"published": "raw-date"}) == "raw-date"
+ assert _parse_published({"updated": "other-date"}) == "other-date"
+ assert _parse_published({}) is None
diff --git a/src/world_intel_mcp/tests/test_spikes.py b/src/world_intel_mcp/tests/test_spikes.py
new file mode 100644
index 0000000..4019ae9
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_spikes.py
@@ -0,0 +1,127 @@
+"""Tests for analysis/spikes.py — Welford keyword spike detection.
+
+The detector persists baselines in SQLite; every test uses a tmp_path
+database (never the real ~/.cache file). Expected z-scores are hand-computed
+from Welford's recurrence: for observations [10, 20, 30, 20] the running
+state is n=4, mean=20, M2=200, so variance=50 and stddev=sqrt(50)=7.0711.
+"""
+
+from pathlib import Path
+
+import pytest
+
+from world_intel_mcp.analysis import spikes as spikes_mod
+from world_intel_mcp.analysis.spikes import KeywordSpikeDetector, fetch_keyword_spikes
+from world_intel_mcp.sources import news
+
+
+def detector(tmp_path: Path) -> KeywordSpikeDetector:
+ return KeywordSpikeDetector(db_path=str(tmp_path / "spikes.db"))
+
+
+def _feed(detector: KeywordSpikeDetector, keyword: str, values: list[int]) -> None:
+ for v in values:
+ detector.detect_spikes({keyword: v})
+
+
+def test_no_spikes_during_warmup(detector: KeywordSpikeDetector) -> None:
+ # Fewer than 3 baseline observations: even a huge count is not a spike.
+ assert detector.detect_spikes({"war": 500}) == []
+ assert detector.detect_spikes({"war": 500}) == []
+ assert detector.detect_spikes({"war": 500}) == []
+
+
+def test_ratio_spike_on_flat_baseline(detector: KeywordSpikeDetector) -> None:
+ _feed(detector, "gaza", [10, 10, 10]) # zero variance baseline
+ result = detector.detect_spikes({"gaza": 40})
+ assert len(result) == 1
+ spike = result[0]
+ assert spike["keyword"] == "gaza"
+ assert spike["detection"] == "ratio"
+ assert spike["z_score"] is None
+ assert spike["ratio"] == 4.0
+ assert spike["baseline_mean"] == 10.0
+ assert spike["current_count"] == 40
+
+
+def test_no_ratio_spike_below_threshold(detector: KeywordSpikeDetector) -> None:
+ """Load-bearing pair with the test above: 2.5x on a flat baseline is
+ NOT a spike (the ratio path requires > 3.0)."""
+ _feed(detector, "gaza", [10, 10, 10])
+ assert detector.detect_spikes({"gaza": 25}) == []
+
+
+def test_z_score_spike_flags_surge_not_noise(detector: KeywordSpikeDetector) -> None:
+ for v in [10, 20, 30, 20]:
+ detector.detect_spikes({"surging": v, "steady": v})
+ result = detector.detect_spikes({"surging": 40, "steady": 25})
+ # surging: z = (40-20)/7.0711 = 2.83 >= 2.0 -> spike.
+ # steady: z = (25-20)/7.0711 = 0.71 -> silence.
+ assert [s["keyword"] for s in result] == ["surging"]
+ spike = result[0]
+ assert spike["detection"] == "z_score"
+ assert spike["z_score"] == 2.83
+ assert spike["stddev"] == 7.07
+ assert spike["baseline_mean"] == 20.0
+ assert spike["ratio"] == 2.0
+
+
+def test_baseline_absorbs_the_spike(detector: KeywordSpikeDetector) -> None:
+ """A sustained plateau stops alarming: the spike observation is folded
+ into the baseline, so the same count again is no longer anomalous."""
+ _feed(detector, "gaza", [10, 10, 10])
+ assert len(detector.detect_spikes({"gaza": 40})) == 1
+ # Baseline is now [10,10,10,40]: mean 17.5, stddev ~12.99 -> z ~1.73.
+ assert detector.detect_spikes({"gaza": 40}) == []
+
+
+def test_spikes_sorted_by_magnitude_descending(detector: KeywordSpikeDetector) -> None:
+ for v in [10, 20, 30, 20]:
+ detector.detect_spikes({"big": v, "small": v})
+ result = detector.detect_spikes({"big": 100, "small": 40})
+ assert [s["keyword"] for s in result] == ["big", "small"]
+ assert result[0]["z_score"] > result[1]["z_score"]
+
+
+def test_baselines_persist_across_instances(tmp_path: Path) -> None:
+ db = str(tmp_path / "persist.db")
+ first = KeywordSpikeDetector(db_path=db)
+ _feed(first, "coup", [10, 10, 10])
+
+ second = KeywordSpikeDetector(db_path=db)
+ result = second.detect_spikes({"coup": 40})
+ assert len(result) == 1 # baseline survived the restart
+ assert result[0]["baseline_mean"] == 10.0
+
+
+async def test_fetch_keyword_spikes_composes_news_sources(
+ fetcher, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _fake_trending(fetcher, min_count=3):
+ return {"keywords": [{"keyword": "gaza", "count": 30}]}
+
+ async def _fake_feed(fetcher, limit=100, category=None):
+ return {
+ "items": [
+ {"title": "CVE-2026-1111 exploited in the wild", "summary": ""},
+ {"title": "Volt Typhoon activity reported", "summary": ""},
+ ]
+ }
+
+ monkeypatch.setattr(news, "fetch_trending_keywords", _fake_trending)
+ monkeypatch.setattr(news, "fetch_news_feed", _fake_feed)
+ # Point the module singleton at a throwaway database.
+ monkeypatch.setattr(
+ spikes_mod, "_detector", KeywordSpikeDetector(db_path=str(tmp_path / "kw.db"))
+ )
+
+ result = await fetch_keyword_spikes(fetcher, min_count=3, z_threshold=2.0)
+ assert result["keywords_analyzed"] == 1
+ assert result["spikes"] == [] # first observation ever: warm-up
+ assert result["cve_mentions"] == ["CVE-2026-1111"]
+ assert result["apt_mentions"] == ["volt typhoon"] # lowercased
+ assert result["cve_count"] == 1
+ assert result["apt_count"] == 1
+ assert result["z_threshold"] == 2.0
+ assert result["source"] == "keyword-spike-detector"
diff --git a/src/world_intel_mcp/tests/test_surge.py b/src/world_intel_mcp/tests/test_surge.py
new file mode 100644
index 0000000..1d9379d
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_surge.py
@@ -0,0 +1,106 @@
+"""Tests for analysis/surge.py — military surge detection over baselines.
+
+Baselines come from the module's SENSITIVE_REGIONS table (e.g. persian_gulf
+United States: 15, red_sea United States: 3, baltic_sea Russia: 3), and the
+middle_east theater maps to persian_gulf + red_sea, european to
+baltic_sea + black_sea.
+"""
+
+import pytest
+
+from world_intel_mcp.analysis.surge import detect_surges
+
+
+def test_empty_theater_data_yields_no_surges() -> None:
+ assert detect_surges({}) == []
+
+
+def test_surge_detected_in_mapped_regions_sorted_by_ratio() -> None:
+ theater = {"middle_east": {"count": 60, "countries": ["United States"]}}
+ surges = detect_surges(theater)
+ assert [s["region"] for s in surges] == ["red_sea", "persian_gulf"]
+ red_sea = surges[0]
+ assert red_sea["country"] == "United States"
+ assert red_sea["current"] == 60
+ assert red_sea["baseline"] == 3
+ assert red_sea["surge_ratio"] == 20.0
+ assert red_sea["severity"] == "critical"
+ assert surges[1]["surge_ratio"] == 4.0 # 60 / persian_gulf baseline 15
+
+
+def test_at_baseline_is_quiet_above_threshold_reported() -> None:
+ """Load-bearing pair in one dataset: 15 aircraft is exactly the
+ persian_gulf US baseline (ratio 1.0, silent) while the same count is a
+ 5x surge against the red_sea baseline of 3."""
+ theater = {"middle_east": {"count": 15, "countries": ["United States"]}}
+ surges = detect_surges(theater)
+ assert [s["region"] for s in surges] == ["red_sea"]
+ assert surges[0]["surge_ratio"] == 5.0
+
+
+ "count,expected_severity",
+ [
+ (5, "watch"), # 5/3 = 1.67
+ (6, "elevated"), # 6/3 = 2.0
+ (9, "critical"), # 9/3 = 3.0
+ ],
+)
+def test_severity_ladder_for_baltic_russia(count: int, expected_severity: str) -> None:
+ theater = {"european": {"count": count, "countries": ["Russia"]}}
+ surges = detect_surges(theater)
+ baltic = next(s for s in surges if s["region"] == "baltic_sea")
+ assert baltic["country"] == "Russia"
+ assert baltic["severity"] == expected_severity
+
+
+def test_count_distributed_across_theater_countries() -> None:
+ # 40 aircraft over 2 countries -> 20 each. US 20/15 = 1.33 stays
+ # quiet; Iran 20/5 = 4.0 is critical.
+ theater = {"middle_east": {"count": 40, "countries": ["United States", "Iran"]}}
+ surges = detect_surges(theater)
+ gulf = [s for s in surges if s["region"] == "persian_gulf"]
+ assert [s["country"] for s in gulf] == ["Iran"]
+ assert gulf[0]["current"] == 20
+ assert gulf[0]["severity"] == "critical"
+
+
+def test_country_without_baseline_is_ignored() -> None:
+ # France has no baseline in any european-mapped region.
+ theater = {"european": {"count": 30, "countries": ["France"]}}
+ assert detect_surges(theater) == []
+
+
+def test_theater_with_no_countries_is_skipped() -> None:
+ theater = {"middle_east": {"count": 100, "countries": []}}
+ assert detect_surges(theater) == []
+
+
+def test_temporal_anomaly_boosts_watch_to_elevated() -> None:
+ theater = {"european": {"count": 5, "countries": ["Russia"]}} # 1.67 = watch
+ surges = detect_surges(
+ theater,
+ temporal_baselines={"baltic_sea": {"z_score": 2.5, "multiplier": 1.8}},
+ )
+ baltic = next(s for s in surges if s["region"] == "baltic_sea")
+ assert baltic["severity"] == "elevated"
+ assert baltic["temporal_anomaly"] == {"z_score": 2.5, "multiplier": 1.8}
+
+
+def test_temporal_anomaly_boosts_elevated_to_critical() -> None:
+ theater = {"european": {"count": 6, "countries": ["Russia"]}} # 2.0 = elevated
+ surges = detect_surges(theater, temporal_baselines={"baltic_sea": {"z_score": 3.1}})
+ baltic = next(s for s in surges if s["region"] == "baltic_sea")
+ assert baltic["severity"] == "critical"
+
+
+def test_weak_temporal_signal_does_not_boost() -> None:
+ theater = {"european": {"count": 5, "countries": ["Russia"]}}
+ surges = detect_surges(
+ theater,
+ # z_score must be strictly greater than 2.0 to boost.
+ temporal_baselines={"baltic_sea": {"z_score": 2.0, "multiplier": 1.1}},
+ )
+ baltic = next(s for s in surges if s["region"] == "baltic_sea")
+ assert baltic["severity"] == "watch"
+ assert "temporal_anomaly" not in baltic
diff --git a/src/world_intel_mcp/tests/test_world_brief.py b/src/world_intel_mcp/tests/test_world_brief.py
new file mode 100644
index 0000000..7061e6f
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_world_brief.py
@@ -0,0 +1,190 @@
+"""Tests for analysis/world_brief.py — structured daily intelligence summary.
+
+fetch_world_brief composes two analysis functions and three source/analysis
+fetchers; tests mock all five at their module boundaries (pattern from
+test_aoi.py / test_daily_digest.py).
+"""
+
+from datetime import datetime, timezone
+
+import pytest
+
+from world_intel_mcp.analysis import clustering, posture, spikes
+from world_intel_mcp.analysis.world_brief import fetch_world_brief
+from world_intel_mcp.sources import intelligence
+
+
+def _make_fake(payload: dict):
+ async def _fake(fetcher, *args, **kwargs):
+ return payload
+
+ return _fake
+
+
+_POSTURE = {
+ "composite_score": 48.3,
+ "risk_level": "ELEVATED",
+ "domain_scores": {
+ "military": {"score": 32.0, "level": "GUARDED", "signals": []},
+ "political": {"score": 80.0, "level": "CRITICAL", "signals": []},
+ },
+ "top_threats": [
+ {"domain": "political", "signal": f"threat {i}", "domain_score": 80.0}
+ for i in range(7)
+ ],
+}
+
+_FOCAL = {
+ "focal_points": [
+ {
+ "entity": f"entity-{i}",
+ "entity_type": "country",
+ "signal_count": 3,
+ "domains": ["conflict"],
+ }
+ for i in range(10)
+ ]
+}
+
+_CLUSTERS = {
+ "clusters": [
+ {
+ "keywords": ["kyiv", "strikes", "missile", "grid", "energy", "russia"],
+ "article_count": 4,
+ "sources": ["BBC", "Reuters", "AP", "AFP"],
+ "items": [{"title": "Headline one"}],
+ }
+ ]
+}
+
+_ANOMALIES = {
+ "anomalies": [
+ {
+ "key": "conflict:UKR",
+ "z_score": 3.1,
+ "current_value": 50,
+ "baseline_mean": 20,
+ "description": "conflict events well above baseline",
+ }
+ ]
+}
+
+_SPIKES = {
+ "spikes": [{"keyword": f"kw{i}", "z_score": 3.0} for i in range(12)],
+ "spike_count": 12,
+ "cve_mentions": ["CVE-2026-1111"],
+ "apt_mentions": ["lazarus"],
+}
+
+
+def _patch_all(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(posture, "fetch_strategic_posture", _make_fake(_POSTURE))
+ monkeypatch.setattr(intelligence, "fetch_focal_points", _make_fake(_FOCAL))
+ monkeypatch.setattr(clustering, "fetch_news_clusters", _make_fake(_CLUSTERS))
+ monkeypatch.setattr(
+ intelligence, "fetch_temporal_anomalies", _make_fake(_ANOMALIES)
+ )
+ monkeypatch.setattr(spikes, "fetch_keyword_spikes", _make_fake(_SPIKES))
+
+
+async def test_world_brief_assembles_all_sections(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_all(monkeypatch)
+ result = await fetch_world_brief(fetcher)
+
+ assert result["date"] == datetime.now(timezone.utc).strftime("%Y-%m-%d")
+ assert result["source"] == "world-intelligence-brief"
+
+ overview = result["risk_overview"]
+ assert overview["composite_score"] == 48.3
+ assert overview["risk_level"] == "ELEVATED"
+ assert overview["domain_summary"]["political"] == {
+ "score": 80.0,
+ "level": "CRITICAL",
+ }
+
+ # Caps: 8 focal areas of 10, 5 threats of 7, 8 spikes of 12.
+ assert result["focal_area_count"] == 8
+ assert result["focal_areas"][0]["entity"] == "entity-0"
+ assert len(result["top_threats"]) == 5
+ assert len(result["trending"]["spikes"]) == 8
+ assert result["trending"]["spike_count"] == 12
+ assert result["trending"]["cve_mentions"] == ["CVE-2026-1111"]
+ assert result["trending"]["apt_mentions"] == ["lazarus"]
+
+ assert result["top_story_count"] == 1
+ story = result["top_stories"][0]
+ assert story["topic_keywords"] == ["kyiv", "strikes", "missile", "grid", "energy"]
+ assert story["sources"] == ["BBC", "Reuters", "AP"]
+ assert story["headline"] == "Headline one"
+
+ assert result["anomaly_count"] == 1
+ assert result["anomalies"][0]["metric"] == "conflict:UKR"
+ assert result["anomalies"][0]["z_score"] == 3.1
+
+
+async def test_world_brief_survives_posture_failure(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """One broken section must degrade to defaults, not sink the brief."""
+ _patch_all(monkeypatch)
+
+ async def _broken(fetcher, *args, **kwargs):
+ raise RuntimeError("posture upstream down")
+
+ monkeypatch.setattr(posture, "fetch_strategic_posture", _broken)
+ result = await fetch_world_brief(fetcher)
+
+ assert result["risk_overview"]["composite_score"] == 0
+ assert result["risk_overview"]["risk_level"] == "UNKNOWN"
+ assert result["risk_overview"]["domain_summary"] == {}
+ assert result["top_threats"] == []
+ # The other sections still populate.
+ assert result["focal_area_count"] == 8
+ assert result["top_story_count"] == 1
+
+
+async def test_world_brief_all_sources_empty(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ for mod, name in [
+ (posture, "fetch_strategic_posture"),
+ (intelligence, "fetch_focal_points"),
+ (clustering, "fetch_news_clusters"),
+ (intelligence, "fetch_temporal_anomalies"),
+ (spikes, "fetch_keyword_spikes"),
+ ]:
+ monkeypatch.setattr(mod, name, _make_fake({}))
+
+ result = await fetch_world_brief(fetcher)
+ assert result["focal_area_count"] == 0
+ assert result["top_story_count"] == 0
+ assert result["anomaly_count"] == 0
+ assert result["trending"]["spikes"] == []
+
+
+async def test_top_stories_count_from_real_clustering_shape(
+ fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Regression: fetch_news_clusters emits the member count as "size",
+ and world_brief read only "article_count", so every real brief
+ reported 0 articles per story (the silent-zero class). The brief
+ must propagate the count from the shape clustering actually emits."""
+ _patch_all(monkeypatch)
+ real_shape = {
+ "clusters": [
+ {
+ "headline": "Ceasefire talks resume",
+ "size": 7,
+ "keywords": ["ceasefire", "talks"],
+ "sources": ["Reuters"],
+ "items": [{"title": "Ceasefire talks resume", "source": "Reuters"}],
+ }
+ ],
+ "cluster_count": 1,
+ }
+ monkeypatch.setattr(clustering, "fetch_news_clusters", _make_fake(real_shape))
+ result = await fetch_world_brief(fetcher)
+ assert result["top_stories"][0]["article_count"] == 7