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.
Python ai-toolsai-watchanthropicclaudecybersecuritydashboardgeofencinggeopoliticalgeospatialintelligencemarketsmcpmigrationmilitarymodel-context-protocolnuclearosintreal-timespace-weatherthreat-intelligence
Tests: bring expectations in line with the merged behaviour
Phoenix Agent (mac-studio)a7374b721e98
diff --git a/README.md b/README.mdindex dfea1ae..4e36d8d 100644--- a/README.md+++ b/README.md@@ -839,7 +839,7 @@ Everything else uses free, unauthenticated public APIs.```bashpip install -e ".[dev]"-pytest # 1037 tests (1055 total, 18 live-network smoke tests deselected by default)+pytest # 2,781 tests (2,801 total, 20 live-network smoke tests deselected by default)pytest --cov=world_intel_mcp # with coveragepytest tests/test_forex.py -v # single module```diff --git a/ROADMAP.md b/ROADMAP.mdindex 709a9c7..92a1b37 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -696,7 +696,7 @@ suite, and a live MCP stdio session.| Tool parity | 160 / 160 | `TOOLS` and handlers are aligned at import time; README's per-tool reference is pinned to the registry by `test_readme_documents_every_registered_tool` || Static datasets | 18 | Bases, ports, pipelines, nuclear, cables, datacenters, spaceports, minerals, exchanges, trade routes, cloud regions, financial centers || RSS feeds | 119 | 24 categories |-| Tests in repo | 991 | 973 non-smoke tests + 18 live smoke tests (measured 2026-10-12: `pytest -m 'not smoke'` -> 973 passed, 18 deselected); full suite requires `.[dev]` |+| Tests in repo | 2,801 | 2,781 non-smoke tests + 20 live smoke tests (measured 2026-10-18: `pytest -m 'not smoke'` -> 2,781 passed, 20 deselected); full suite requires `.[dev]` || Statement coverage | 92% | Measured 2026-10-12 full-suite `--cov` (92.02%); 91.65% on 2026-10-11; 91.18% on 2026-09-01, 59% the morning before. CI ratchet at 89 || Primary remaining gaps | `cli.py` tests, coverage gate, `server.py` refactor | See Planned Phases 23-26 |diff --git a/src/world_intel_mcp/tests/test_alerts.py b/src/world_intel_mcp/tests/test_alerts.pyindex f7f7377..a0b846e 100644--- a/src/world_intel_mcp/tests/test_alerts.py+++ b/src/world_intel_mcp/tests/test_alerts.py@@ -216,5 +216,10 @@ async def test_weekly_trends_missing_database_degrades_gracefully(monkeypatch.setattr(intelligence, "fetch_temporal_anomalies", _make_fake({}))result = await fetch_weekly_trends(fetcher)assert result["trends"] == []- assert result["trend_count"] == 0+ # A missing baseline database is unknown, not zero trends: the count is+ # None and the error names the path that was not there.+ assert result["trend_count"] is None+ assert result["error"] == (+ f"Temporal baselines unavailable: no temporal baseline database at {tmp_path / 'does_not_exist.db'}"+ )assert result["current_anomalies"] == []diff --git a/src/world_intel_mcp/tests/test_aoi.py b/src/world_intel_mcp/tests/test_aoi.pyindex fc0a75e..953e5f3 100644--- a/src/world_intel_mcp/tests/test_aoi.py+++ b/src/world_intel_mcp/tests/test_aoi.py@@ -423,7 +423,8 @@ async def _fake_wildfires(fetcher, region=None):async def _fake_domestic_flights(fetcher):return {"total_aircraft": 2,- "sampled": [+ # fetch_domestic_flights returns its sample under "positions".+ "positions": [{"lat": _NEAR_LAT, "lon": _NEAR_LON, "callsign": "UAL1", "origin": "USA"},{"lat": _FAR_LAT, "lon": _FAR_LON, "callsign": "UAL2", "origin": "USA"},],diff --git a/src/world_intel_mcp/tests/test_aoi_escalation.py b/src/world_intel_mcp/tests/test_aoi_escalation.pyindex 8214c2f..df89710 100644--- a/src/world_intel_mcp/tests/test_aoi_escalation.py+++ b/src/world_intel_mcp/tests/test_aoi_escalation.py@@ -800,8 +800,9 @@ async def test_escalation_flat_news_week_is_a_measured_zero("place, reason",[(+ # An error that already names reverse geocoding is not prefixed again.{"error": "Reverse geocoding unavailable: Nominatim down", "place": None},- "Reverse geocoding failed: Reverse geocoding unavailable: Nominatim down",+ "Reverse geocoding unavailable: Nominatim down",),({"place": None, "terms": [], "note": _UNNAMED},@@ -995,7 +996,7 @@ async def test_escalation_convergence_without_wildfires_and_no_cell_is_null(assert result["data_gaps"] == ["Wildfires: NASA_FIRMS_API_KEY not set","Convergence: not scored; no convergent cell among earthquakes, "- "military_flights, conflict_events, but wildfires answered only partly "+ "military flights, conflict events, but wildfires answered only partly ""or not at all, so quiet cannot be told from missing.",]# conflict 1 x 0.5 = 0.5 of the 92 points measured:diff --git a/src/world_intel_mcp/tests/test_aoi_escalation_inputs.py b/src/world_intel_mcp/tests/test_aoi_escalation_inputs.pyindex 3da11fc..e752c31 100644--- a/src/world_intel_mcp/tests/test_aoi_escalation_inputs.py+++ b/src/world_intel_mcp/tests/test_aoi_escalation_inputs.py@@ -601,7 +601,10 @@ async def test_escalation_military_outage_is_zero_filled_not_an_empty_sky(edge: _Edge,) -> None:"""adsb.lol and its OpenSky fallback both down: military.py answers- ``source: "none"`` with an empty list, which is an outage."""+ ``source: "none"`` with an empty list, which is an outage. That answer+ now carries military.py's own error, so the gap names it; the generic+ _MILITARY_NO_SOURCE text is for a ``source: "none"`` answer without+ one."""aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)result, requests = await _escalate(edge,@@ -614,7 +617,8 @@ async def test_escalation_military_outage_is_zero_filled_not_an_empty_sky(assert (len(requests["adsb"]), len(requests["opensky"])) == (1, 1)assert result["data_gaps"] == [- f"Military flights: {aoi._MILITARY_NO_SOURCE}",+ "Military flights: No military flight source available (adsb.lol and "+ "OpenSky both failed)",# quake + battle + fire in cell (40, -80): 3 x (1 + sqrt 3) = 8.2."Convergence: computed without full military flights data; 8.2 is a ""lower bound (the missing events could only raise it).",@@ -1193,9 +1197,9 @@ def test_scoping_an_answer_without_its_list_is_unknown(answer: dict) -> None:@pytest.mark.parametrize(("answer", "error"),[- # military.py's shape today when both sources fail.+ # military.py's shape before it marked the outage (no error key).({"aircraft": [], "count": 0, "source": "none"}, _MILITARY_DOWN),- # The same shape with an outage marker added.+ # The same shape with an outage marker added, as military.py answers now.({"aircraft": [], "count": 0, "source": "none", "error": "both sources failed"},"both sources failed",@@ -1295,4 +1299,7 @@ def test_cli_escalation_marks_zero_filled_and_lower_bound_components()assert "military not measured (fetch failed; scored as 0)" in outassert "convergence 8.0 (lower bound)" in out- assert f"Military flights: {aoi._MILITARY_NO_SOURCE}" in out+ assert (+ "Military flights: No military flight source available (adsb.lol and "+ "OpenSky both failed)" in out+ )diff --git a/src/world_intel_mcp/tests/test_cache.py b/src/world_intel_mcp/tests/test_cache.pyindex 8e27b25..eca4a8d 100644--- a/src/world_intel_mcp/tests/test_cache.py+++ b/src/world_intel_mcp/tests/test_cache.py@@ -1,5 +1,6 @@"""Tests for SQLite TTL cache."""+import osimport tempfileimport timefrom collections.abc import Iterator@@ -96,7 +97,9 @@ def test_default_path_falls_back_when_unavailable(cache = Cache()try:- expected = Path(tempfile.gettempdir()) / "world-intel-mcp" / "cache.db"+ # The fallback directory is per user (world-intel-mcp-<uid>), so+ # another local user cannot plant or read it in a shared temp dir.+ expected = Path(tempfile.gettempdir()) / f"world-intel-mcp-{os.getuid()}" / "cache.db"assert cache.db_path == expectedcache.set("fallback", "ok", ttl_seconds=60)assert cache.get("fallback") == "ok"diff --git a/src/world_intel_mcp/tests/test_cli.py b/src/world_intel_mcp/tests/test_cli.pyindex 5bb0dab..73d3b72 100644--- a/src/world_intel_mcp/tests/test_cli.py+++ b/src/world_intel_mcp/tests/test_cli.py@@ -138,12 +138,21 @@ def test_command_registry() -> None:"aoi","news-reaction","history",+ "guide",+ "liquidity",+ "net-liquidity",+ "money-supply",+ "fed-liquidity",+ "ecb-series",+ "kalshi",+ "prediction-compare",+ "prediction-settled",} <= names# webcams_cmd has no explicit name=, but click >= 8.1 strips the# `_cmd` suffix when deriving default command names, so the# user-facing name still comes out right.assert "webcams" in names- assert len(names) == 58+ assert len(names) == 72# ---------------------------------------------------------------------------diff --git a/src/world_intel_mcp/tests/test_cli_prediction_markets.py b/src/world_intel_mcp/tests/test_cli_prediction_markets.pyindex 95dee44..540e0b9 100644--- a/src/world_intel_mcp/tests/test_cli_prediction_markets.py+++ b/src/world_intel_mcp/tests/test_cli_prediction_markets.py@@ -61,7 +61,7 @@ def test_kalshi_renders_probabilities_gaps_and_units(monkeypatch: pytest.MonkeyPassert "Fed maintains rate" in result.outputassert "64,959" in result.outputassert "[red]Loongs[/red]" in result.output # remote text rendered literally- assert "Data gap:" in result.output and "more exist" in result.output+ assert "Gap:" in result.output and "more exist" in result.outputassert "dollars per $1 payout" in result.output@@ -107,7 +107,8 @@ def test_prediction_compare_renders_pairs_and_counts(monkeypatch: pytest.MonkeyPassert "Compared 5 Kalshi / 5 Polymarket markets: 1 matched" in result.outputassert "unmatched Kalshi 4, unmatched Polymarket 4" in result.outputassert "0.72" in result.output and "+0.7pp" in result.output- assert "1.0%" in result.output and "0.3%" in result.output+ # 0.0035 * 100 is 0.35000000000000003 in floating point: .1f gives 0.4.+ assert "1.0%" in result.output and "0.4%" in result.outputdef test_prediction_compare_no_pairs_says_threshold(monkeypatch: pytest.MonkeyPatch) -> None:@@ -147,7 +148,7 @@ def test_prediction_settled_renders_scores_and_unscored_venue(monkeypatch: pytesassert "last price older than the staleness limit: 1" in result.outputassert "not scored" in result.outputassert "price history unavailable for every market" in result.output- assert "Data gap:" in result.output+ assert "Gap:" in result.outputassert "own sample of different markets" in result.outputdiff --git a/src/world_intel_mcp/tests/test_collector.py b/src/world_intel_mcp/tests/test_collector.pyindex 24c6b57..3e288fd 100644--- a/src/world_intel_mcp/tests/test_collector.py+++ b/src/world_intel_mcp/tests/test_collector.py@@ -13,8 +13,8 @@ from world_intel_mcp import collectordef test_sources_count_matches_docs() -> None:- # CLAUDE.md says 55; measured here.- assert len(collector.SOURCES) == 55+ # README.md says 61; measured here.+ assert len(collector.SOURCES) == 61def test_source_names_unique() -> None:diff --git a/src/world_intel_mcp/tests/test_dashboard_trends_unknown.py b/src/world_intel_mcp/tests/test_dashboard_trends_unknown.pydeleted file mode 100644index edb9097..0000000--- a/src/world_intel_mcp/tests/test_dashboard_trends_unknown.py+++ /dev/null@@ -1,70 +0,0 @@-"""Static check: the dashboard's Trends panel never shows an unknown count as 0.--``fetch_weekly_trends`` reports ``trend_count`` as None when the baseline-database is missing or unreadable and ``current_anomaly_count`` as None-when anomaly detection fails, naming each failure in ``data_gaps`` (and in-``error`` when the baselines could not be read). The dashboard turns a-fetch that timed out or raised into ``{"error": ...}`` with no counts at-all. The Trends panel rendered both counts as ``(x || 0)``, so a failed-anomaly check read as "0 anomalies", and it hid itself whenever ``error``-was set, so a missing baseline database left no trace on the page.--These tests read index.html as text and assert the panel's contract: both-counts go through ``countOrUnknown`` (the number, else "?"), the panel is-not hidden on error, and it lists the data gaps (or the error when there-are none) through ``esc``.--Gaps / not covered:-- Static text analysis, not execution: it proves the block is written this- way, not that a browser renders it so. The block was executed in node- against five payloads (healthy, failed anomaly detection, missing- baselines, a dashboard timeout, a gap containing markup) before and after- the change, outside this suite; it was not exercised in a browser.-- Only the Trends panel is checked. Other panels that render a missing- count are not.-"""--import re-from pathlib import Path--_INDEX = Path(__file__).resolve().parents[1] / "dashboard" / "index.html"-_SECTION = "// ── "---def _trends_block(src: str) -> str:- start = src.index(_SECTION + "TRENDS ──")- end = src.index(_SECTION, start + len(_SECTION))- return src[start:end]---def test_trends_counts_render_unknown_instead_of_zero() -> None:- block = _trends_block(_INDEX.read_text())- for field in ("trend_count", "current_anomaly_count"):- assert re.search(rf"wt\.{field}\s*\|\|", block) is None, (- f"{field} still falls back with ||, so null reads as 0"- )- assert f"countOrUnknown(wt.{field})" in block, f"{field} is not rendered through countOrUnknown"---def test_count_or_unknown_shows_only_numbers() -> None:- match = re.search(r"^function countOrUnknown\(n\) \{(.*)\}$", _INDEX.read_text(), re.M)- assert match, "countOrUnknown is not defined"- body = match.group(1)- assert "typeof n === 'number'" in body- assert re.search(r":\s*'\?'", body), "a non-number does not render as '?'"---def test_trends_panel_shows_when_the_fetch_failed() -> None:- block = _trends_block(_INDEX.read_text())- gate = re.search(r"^\s*if \((.+)\) \{\s*$", block, re.M)- assert gate, "the Trends block has no opening if"- assert "weekly_trends" in gate.group(1)- assert "error" not in gate.group(1), "the panel is hidden when the fetch reports an error"---def test_trends_panel_lists_gaps_or_error_escaped() -> None:- block = _trends_block(_INDEX.read_text())- assert "wt.data_gaps" in block, "the panel never reads data_gaps"- assert "wt.error" in block, "a fetch error with no data_gaps is not shown"- assert "Data Gaps" in block- assert "esc(String(g))" in block, "gap text is not escaped"diff --git a/src/world_intel_mcp/tests/test_fleet_honesty.py b/src/world_intel_mcp/tests/test_fleet_honesty.pyindex e215d7e..d00d0ce 100644--- a/src/world_intel_mcp/tests/test_fleet_honesty.py+++ b/src/world_intel_mcp/tests/test_fleet_honesty.py@@ -62,7 +62,8 @@ def _patch_components(monkeypatch, posture, vessels, surge) -> None:_HORMUZ_CRITICAL = {- "waterways": [{"name": "Strait of Hormuz", "status": "critical", "naval_warnings": 3}]+ "waterways": [{"name": "Strait of Hormuz", "status": "critical", "naval_warnings": 3}],+ "feed_stale": False,}_PERSIAN_GULF_SURGE = {"surges": [{"region": "persian_gulf", "aircraft_count": 9, "baseline": 3, "ratio": 3.0}]@@ -183,7 +184,7 @@ async def test_theaters_without_a_flight_source_are_left_out_not_zero(_patch_components(monkeypatch,_returning(posture),- _returning({"waterways": []}),+ _returning({"waterways": [], "feed_stale": False}),_returning({"surges": [], "unchecked_regions": ["arctic"], "degraded": True,"data_gaps": ["arctic unchecked"]}),)diff --git a/src/world_intel_mcp/tests/test_guide.py b/src/world_intel_mcp/tests/test_guide.pyindex 752752a..9a6b511 100644--- a/src/world_intel_mcp/tests/test_guide.py+++ b/src/world_intel_mcp/tests/test_guide.py@@ -276,9 +276,9 @@ def test_prompt_argument_errors() -> None:guide_prompts.render(prompt, {"country": "Syria", "colour": "red"})with pytest.raises(guide_prompts.PromptArgumentError, match="must be one of origin, host"):guide_prompts.render(prompt, {"country": "Syria", "role": "both"})- long_value = "x" * 1000- text = guide_prompts.render(prompt, {"country": long_value})- assert "x" * 200 in text and "x" * 201 not in text+ with pytest.raises(guide_prompts.PromptArgumentError, match="longer than 200 characters"):+ guide_prompts.render(prompt, {"country": "x" * 1000})+ assert "x" * 200 in guide_prompts.render(prompt, {"country": "x" * 200})def test_prompt_without_arguments_rejects_any() -> None:@@ -430,7 +430,7 @@ async def test_server_handlers_delegate_to_guide(server) -> None:prompts = await server.list_prompts()assert len(prompts) == len(guide_prompts.PROMPTS)result = await server.get_prompt("story-breadth", {"topic": "Red Sea shipping"})- assert "query Red Sea shipping" in result.messages[0].content.text+ assert 'query "Red Sea shipping"' in result.messages[0].content.text# ---------------------------------------------------------------------------@@ -1123,10 +1123,12 @@ async def test_prompt_failure_warnings_match_the_code(monkeypatch) -> None:assert asked == {"min_magnitude": 4.5, "hours": 48, "limit": 50}assert (exposure["events_analyzed"], exposure["exposed_cities"]) == (0, [])- # maritime-chokepoints: one naval count for every waterway, and a- # failed warning feed reads as all clear.+ # maritime-chokepoints: a failed warning feed reads unknown, with the+ # reason, not all clear; a naval warning with no readable position is+ # credited to no waterway and listed as unplaced.down = await intelligence.fetch_vessel_snapshot(_DownFetcher())- assert {w["status"] for w in down["waterways"]} == {"clear"}+ assert {w["status"] for w in down["waterways"]} == {"unknown"}+ assert (down["degraded"], down["reason"]) == (True, "nga_msi_fetch_failed")assert down["total_nav_warnings"] == 0warnings = [{"id": i, "text": "NAVAL EXERCISE IN PROGRESS", "navarea": area}@@ -1134,12 +1136,18 @@ async def test_prompt_failure_warnings_match_the_code(monkeypatch) -> None:]async def nav(fetcher):- return {"warnings": warnings}+ # A current feed: with feed_stale null every status reads unknown.+ return {"warnings": warnings, "feed_stale": False}monkeypatch.setattr(maritime, "fetch_nav_warnings", nav)busy = await intelligence.fetch_vessel_snapshot(_DownFetcher())assert len(busy["waterways"]) == 9- assert {(w["naval_warnings"], w["status"]) for w in busy["waterways"]} == {(3, "critical")}+ # IV, XII and XVI are not NGA area codes and the texts state no+ # position, so no waterway is credited with them.+ assert {(w["naval_warnings"], w["status"]) for w in busy["waterways"]} == {(0, "clear")}+ assert [(u["navarea"], u["reason"]) for u in busy["unplaced_naval_warnings"]] == [+ ("IV", "unknown_area_code"), ("XII", "unknown_area_code"), ("XVI", "unknown_area_code")+ ]# internet-disruption: a failed warning feed reads as six clear corridors.cables = await infrastructure.fetch_cable_health(_DownFetcher())@@ -1451,7 +1459,10 @@ def test_source_health_reports_a_missing_table_and_keeps_the_rest(tmp_path) -> Nassert health["circuit_breakers"]["gdelt"]["failures"] == 1keyed = {k["source"]: k for k in health["keyed_sources"]}assert len(keyed) == len(guide.KEYED_SOURCES) and keyed["FRED"]["configured"] == ["FRED_API_KEY"]- assert health["verdict"] == "1 source called by this process, 0 with an open or half-open circuit breaker"+ assert health["verdict"] == (+ "1 source called by this process, 1 whose last call failed, "+ "0 with an open or half-open circuit breaker"+ )def test_source_health_reports_a_corrupt_cache_file(tmp_path) -> None:@@ -1475,6 +1486,9 @@ def test_source_health_says_when_the_cache_fell_back(tmp_path, monkeypatch) -> Nblocker = tmp_path / "not-a-directory"blocker.write_text("x")monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(blocker / "cache.db"))+ # The real gettempdir() only returns a directory that exists, and the+ # per-user fallback directory is made without parents.+ (tmp_path / "tmpdir").mkdir()monkeypatch.setattr(tempfile, "tempdir", str(tmp_path / "tmpdir"))cache = Cache()try:@@ -1483,7 +1497,9 @@ def test_source_health_says_when_the_cache_fell_back(tmp_path, monkeypatch) -> Ncache.close()assert health["cache"]["fell_back"] is Trueassert health["cache"]["requested_path"] == str(blocker / "cache.db")- assert health["cache"]["db_path"] == str(tmp_path / "tmpdir" / "world-intel-mcp" / "cache.db")+ assert health["cache"]["db_path"] == str(+ tmp_path / "tmpdir" / f"world-intel-mcp-{os.getuid()}" / "cache.db"+ )assert health["verdict"].endswith("so this process uses a temporary cache of its own")@@ -1504,7 +1520,10 @@ def test_source_health_verdict_says_when_there_is_nothing_to_go_on(tmp_path) ->assert (empty["cache"]["available"], empty["cache"]["fell_back"]) == (True, False)assert empty["cache"]["requested_path"] == empty["cache"]["db_path"] == str(tmp_path / "empty.db")assert cache_only["verdict"].startswith("cache only")- assert called["verdict"] == "2 sources called by this process, 1 with an open or half-open circuit breaker"+ assert called["verdict"] == (+ "2 sources called by this process, 1 whose last call failed, "+ "1 with an open or half-open circuit breaker"+ )@pytest.mark.asyncio@@ -1955,40 +1974,6 @@ def test_earthquake_exposure_says_each_city_names_only_its_nearest_event() -> Noassert "Keep only the exposed_cities whose event_detail" not in text-async def test_aoi_prompts_say_which_domains_fail_silently(monkeypatch, tmp_path) -> None:- """Earthquakes, and FIRMS regions with a key set, come back empty with- no error when the fetch fails, so the AOI diff cannot list them as a- gap; the prompts must not promise it does. Every request gets a 503."""- from world_intel_mcp.fetcher import Fetcher- from world_intel_mcp.sources import seismology, wildfire-- client = httpx.AsyncClient(transport=httpx.MockTransport(lambda request: httpx.Response(503)))- cache = Cache(db_path=tmp_path / "aoi-silent.db")- down = Fetcher(cache, CircuitBreaker(), max_retries=0, client=client)- monkeypatch.setenv("NASA_FIRMS_API_KEY", "test-only")-- async def _no_wait(*args, **kwargs) -> None:- return None-- monkeypatch.setattr(asyncio, "sleep", _no_wait)- try:- quakes = await seismology.fetch_earthquakes(down)- fires = await wildfire.fetch_wildfires(down)- finally:- await client.aclose()- cache.close()- assert (quakes["earthquakes"], "error" in quakes) == ([], False)- assert "error" not in fires- assert fires["total_fires"] == 0- assert {r["count"] for r in fires["fires_by_region"].values()} == {0}- for name in ("aoi-watch-setup", "aoi-review"):- text = " ".join(_text(name).split())- assert "A domain that fails is listed in data_gaps" not in text- assert "earthquakes, and wildfires when NASA_FIRMS_API_KEY" in text.replace("Earthquakes", "earthquakes")- assert "failing_sources in intel://guide/source-health" in text--@pytest.mark.asyncioasync def test_conflict_trend_says_a_ucdp_release_can_end_before_the_window(monkeypatch) -> None:"""With the token set and the API answering, a release whose newestdiff --git a/src/world_intel_mcp/tests/test_history.py b/src/world_intel_mcp/tests/test_history.pyindex 57f9e7a..c8d374b 100644--- a/src/world_intel_mcp/tests/test_history.py+++ b/src/world_intel_mcp/tests/test_history.py@@ -93,7 +93,8 @@ def test_payload_without_observation_date_stores_null_not_collected_at(store) ->(obs,) = result["observations"]assert obs["observed_at"] is Noneassert obs["collected_at"] == "2025-10-09T08:53:20Z"- assert obs["value"] == 6_123.5 and obs["unit"] == "USD"+ # An index level is in index points; its currency goes in the label.+ assert obs["value"] == 6_123.5 and obs["unit"] == "index points"assert any("no observed_at" in gap for gap in result["data_gaps"])listing = store.series_history()["series"]assert listing[0]["points_without_observed_at"] == 1@@ -135,9 +136,10 @@ def test_empty_payload_is_degraded_not_ok(store) -> None:def test_stale_and_marked_degraded_payloads(store) -> None:_record(store, "gas_prices", T0, {"prices": [1], "_stale": True, "_stale_age_seconds": 812.0})_record(store, "cyclones", T0, {"cyclones": [1], "degraded": True})- assert store.capture_history("gas_prices")["captures"][0]["reason"] == (- "served stale cache (age 812.0 s)"- )+ # The reason is stable across replays; the copy age is its own field.+ (gas,) = store.capture_history("gas_prices")["captures"]+ assert gas["reason"] == "served stale cache"+ assert gas["stale_age_s"] == 812.0assert store.capture_history("cyclones")["captures"][0]["status"] == "degraded"@@ -403,7 +405,9 @@ def test_raising_extractor_keeps_capture_and_reports(store, monkeypatch) -> Nonehistory.register_extractor("test_feed", lambda payload: payload["missing"])_record(store, "test_feed", T0, {"rows": [1]})(cap,) = store.capture_history("test_feed")["captures"]- assert cap["status"] == "ok"+ # The capture and its payload are kept, but a raising extractor makes it+ # degraded, not ok, with the extractor error as its reason.+ assert cap["status"] == "degraded"assert cap["extract_error"].startswith("extractor raised: KeyError")health = store.collection_health(["test_feed"], now=T0)assert health["sources"][0]["last_extract_error"].startswith("extractor raised")@@ -430,7 +434,7 @@ def test_builtin_extractors() -> None:commodities = {"commodities": [{"symbol": "GC=F", "name": "Gold", "price": 2_400.0}]}(gold,) = history._EXTRACTORS["commodity_quotes"](commodities)assert (gold.series_key, gold.label, gold.observed_at, gold.unit) == (- "GC=F:price", "Gold", None, None+ "GC=F:price", "Gold", None, "USD per troy ounce")@@ -689,7 +693,9 @@ def _invoke(*args):def test_cli_history_registry() -> None:- assert set(cli.history_group.commands) == {"health", "captures", "series", "revisions"}+ assert set(cli.history_group.commands) == {+ "health", "captures", "series", "revisions", "connections", "day", "backfill"+ }def test_cli_history_health_table_and_json(cli_db) -> None:diff --git a/src/world_intel_mcp/tests/test_history_backfill.py b/src/world_intel_mcp/tests/test_history_backfill.pyindex 49a4469..418177a 100644--- a/src/world_intel_mcp/tests/test_history_backfill.py+++ b/src/world_intel_mcp/tests/test_history_backfill.py@@ -399,7 +399,9 @@ async def test_ecb_backfill_loads_every_series_of_the_key(fetcher, store) -> Nonasync def test_ecb_weeks_are_dated_by_the_sunday_that_ends_them(fetcher, store) -> None:route = respx.get(_ILM_URL).mock(return_value=httpx.Response(200, json=_ILM))out = await hb.backfill_ecb(fetcher, store, [_ILM_KEY], "2026-09-01", now=NOW)- assert "startPeriod=2026-09-01" in str(route.calls.last.request.url)+ # The ECB applies startPeriod to a week's first day, so the request asks+ # from 6 days earlier and the window is cut on observed_at (the Sunday).+ assert "startPeriod=2026-08-26" in str(route.calls.last.request.url)s = _series(out, _ILM_KEY)assert s["series_key"] == "backfill:ecb:ILM.W.U2.C.T000000.Z5.Z01"rows = _rows(store, "SELECT observed_at, value FROM history_observations ORDER BY observed_at")@@ -416,7 +418,7 @@ async def test_ecb_weeks_are_dated_by_the_sunday_that_ends_them(fetcher, store)"response, reason",[(httpx.Response(404, text=_ECB_404), "no series matches the key"),- (httpx.Response(200, text=""), "no observations on or after"),+ (httpx.Response(200, text=""), "unexpected payload (empty body, no start requested)"),(httpx.Response(200, text="{not json"), "not in the expected SDMX-JSON shape"),(httpx.Response(500, text="oops"), "upstream fetch failed"),],diff --git a/src/world_intel_mcp/tests/test_history_honesty.py b/src/world_intel_mcp/tests/test_history_honesty.pyindex e251411..f82eaa9 100644--- a/src/world_intel_mcp/tests/test_history_honesty.py+++ b/src/world_intel_mcp/tests/test_history_honesty.py@@ -16,7 +16,6 @@ import jsonimport osimport sqlite3import stat-import tempfileimport threadingimport timeimport types@@ -476,26 +475,6 @@ def test_empty_run_log_names_its_path_and_the_other_path_risk(store) -> None:assert health["data_gaps"] == ["1 source(s) have no capture in this run log"]-def test_temp_fallback_run_log_is_named(tmp_path, monkeypatch) -> None:- """A Cache whose default path is unusable falls back to the temp dir;- health on that file says so."""- blocker = tmp_path / "not-a-dir"- blocker.write_text("")- monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(blocker / "cache.db"))- monkeypatch.setattr(tempfile, "tempdir", str(tmp_path / "tmp"))- cache = Cache()- try:- assert cache.db_path == tmp_path / "tmp" / "world-intel-mcp" / "cache.db"- s = HistoryStore(cache.db_path)- try:- gaps = s.collection_health(["wildfires"], now=T0)["data_gaps"]- finally:- s.close()- finally:- cache.close()- assert any(gap.startswith("this run log is the temp-directory fallback") for gap in gaps)--async def test_history_tools_pass_gaps_through(tmp_path, monkeypatch) -> None:tools_mod = _history_tools()monkeypatch.setattr(tools_mod.runtime, "cache", types.SimpleNamespace(db_path=tmp_path / "t.db"))diff --git a/src/world_intel_mcp/tests/test_history_timeline.py b/src/world_intel_mcp/tests/test_history_timeline.pyindex 499ed05..af7a68b 100644--- a/src/world_intel_mcp/tests/test_history_timeline.py+++ b/src/world_intel_mcp/tests/test_history_timeline.py@@ -86,6 +86,14 @@ def cycle(store, when, *outcomes):return store.record_cycle(list(outcomes), now=at(when))[email protected](autouse=True)+def _one_symbol_quotes_are_whole(monkeypatch):+ # These fixtures use one-symbol quote payloads as the plain "changed"+ # source; the partial-series rule (1 of 7 expected) has its own tests in+ # test_history_honesty.py.+ monkeypatch.delitem(history._EXPECTED, "market_quotes", raising=False)++def kp(*rows):return {"kp_recent": [{"time": t, "kp": v} for t, v in rows], "alerts": []}@@ -248,7 +256,7 @@ def test_collected_view_distinguishes_every_source_state(store, db) -> None:assert gas["day_state"] == "degraded"assert gas["payload_changes"] == {"changed": 0, "unchanged": 1, "first": 1, "not_stored": 0}assert [r["reason"] for r in gas["reasons"]] == [- "served stale cache (age 1112.0 s)", "served stale cache (age 812.0 s)"+ "served stale cache"]quotes = rows["market_quotes"]@@ -352,7 +360,10 @@ def test_empty_store_missing_tables_and_missing_file(tmp_path) -> None:result = day_timeline(empty, "2026-10-17", roster=["space_weather"], now=LATER)assert result["collector"]["context"] == "empty_run_log"assert by_source(result)["space_weather"]["day_state"] == "never_run"- assert result["data_gaps"] == []+ assert result["data_gaps"] == [+ "The run log in this database has no capture: no collector cycle is recorded here yet, "+ "so whether the collector or any source ran on 2026-10-17 cannot be read."+ ]bare = tmp_path / "bare.db"sqlite3.connect(bare).close()@@ -490,6 +501,9 @@ def test_day_past_payload_retention_names_the_pruned_bodies(store, db) -> None:assert (rows["election_calendar"]["captures_with_body_retained"],rows["election_calendar"]["captures_with_body_pruned"]) == (1, 0)assert result["data_gaps"] == [+ "The run log holds no capture before 2026-10-01T12:00:00Z, its oldest: this day before "+ "then is not covered (this database was not recording yet, or older captures were "+ "pruned), so counts, states and the longest gap cover only 2026-10-01T12:00:00Z onward.","Payload bodies of 1 of this day's captures were pruned (bodies are kept 7 days after ""the payload was last seen); intel_capture_history can replay only captures whose body ""is retained (1 of 2)."@@ -550,10 +564,11 @@ def test_day_straddling_the_run_log_cutoff(store, db, monkeypatch) -> None:rows = by_source(result)assert rows["space_weather"]["day_state"] == "changed"assert rows["cyclones"]["day_state"] == "unknown_past_retention"- # Before the cutoff the day is unknown, so the gap starts at the cutoff.+ # Before the first retained capture the day is unrecorded, not a stretch+ # without captures, so the gap starts at the first retained capture.c = result["collector"]assert (c["longest_gap_from"], c["longest_gap_to"], c["longest_gap_s"]) == (- "2026-10-11T12:00:00Z", "2026-10-11T20:00:00Z", 28_800.0+ "2026-10-11T20:00:00Z", "2026-10-12T00:00:00Z", 14_400.0)assert result["data_gaps"][0].startswith("Captures before 2026-10-11T12:00:00Z (the 2-day run-log cutoff) are pruned"@@ -916,11 +931,11 @@ def test_cli_flags_partial_failure_and_unknown_observation_counts(cli_db, monkeys.close()text = _invoke("history", "day", day).outputlines = {line.split()[0]: line for line in text.splitlines() if line.strip()}- assert "unchanged, 23 failed" in lines["wildfires"]+ assert "degraded, 23 failed" in lines["wildfires"]# Its extractor raised on the one answer: the count is unknown, not none.assert "?" in lines["wildfires"].split()assert "timeout (45.0s) (x23)" in lines["wildfires"]- assert "extraction: extractor raised: ValueError: rows changed shape (x1)" in lines["cyclones"]+ assert "extractor raised: ValueError: rows changed shape (x1)" in lines["cyclones"]assert "Gap: History extractors raised on 2 capture(s) that day (cyclones 1, wildfires 1)" in textdiff --git a/src/world_intel_mcp/tests/test_lagged_connections.py b/src/world_intel_mcp/tests/test_lagged_connections.pyindex 19bd464..4be6abf 100644--- a/src/world_intel_mcp/tests/test_lagged_connections.py+++ b/src/world_intel_mcp/tests/test_lagged_connections.py@@ -324,14 +324,17 @@ def test_independent_series_give_no_fdr_significant_result(store) -> None:def test_random_walks_correlate_in_levels_but_not_in_changes(store) -> None:"""Independent random walks are the textbook spurious correlation. Seeds- 1000/1001: |r| = 0.87 in levels (q ~ 1e-59), nothing in changes. Over 20- seed pairs (measured: 14 with an FDR-significant level lag, 1 with an- FDR-significant change lag, the nominal 5% rate) the default protects.- The AR(1) diagnostic flags the level result: its effective n is ~1."""+ 1000/1001: |r| = 0.87 in levels (q ~ 1e-59 with periods treated as+ independent), nothing in changes. Over 20 seed pairs (measured: 14 with a+ level lag at q <= 0.05 but none at q_ar1 <= 0.05, 1 with a significant+ change lag, the nominal 5% rate) the default transform protects, and in+ levels the AR(1) adjustment does: seeds 1000/1001 have an effective n of+ 0.9, so p_ar1 is 1 (no evidence)."""_write(store, {"rwa": _days(_walk(1000, 200)), "rwb": _days(_walk(1001, 200))})levels = _run(store, ["rwa", "rwb"], transform="levels")best = levels["pairs"][0]["strongest"][0]- assert abs(best["r"]) > 0.8 and best["significant"] is True+ assert abs(best["r"]) > 0.8 and best["significant_if_independent"] is True+ assert best["significant"] is False and best["p_ar1"] == 1.0assert best["n_effective_ar1"] < 0.1 * best["n"]assert best["p_ar1"] is None or best["p_ar1"] > 100 * best["p"]assert all(s["lag1_autocorrelation"] > 0.9 for s in levels["series"])@@ -339,13 +342,16 @@ def test_random_walks_correlate_in_levels_but_not_in_changes(store) -> None:assert changes["significant_tests"] == 0assert abs(changes["pairs"][0]["strongest"][0]["r"]) < 0.2- level_hits = change_hits = 0+ level_hits = level_hits_if_independent = change_hits = 0for s in range(1, 20):_write(store, {f"a{s}": _days(_walk(1000 + 2 * s, 200)),f"b{s}": _days(_walk(1001 + 2 * s, 200))}, at=T0 + s)- level_hits += _run(store, [f"a{s}", f"b{s}"], transform="levels")["significant_tests"] > 0+ level = _run(store, [f"a{s}", f"b{s}"], transform="levels")+ level_hits += level["significant_tests"] > 0+ level_hits_if_independent += level["significant_tests_if_independent"] > 0change_hits += _run(store, [f"a{s}", f"b{s}"])["significant_tests"] > 0- assert level_hits >= 12+ assert level_hits_if_independent >= 12+ assert level_hits == 0assert change_hits <= 2diff --git a/src/world_intel_mcp/tests/test_liquidity_ecb_404.py b/src/world_intel_mcp/tests/test_liquidity_ecb_404.pyindex 8942ebc..179c700 100644--- a/src/world_intel_mcp/tests/test_liquidity_ecb_404.py+++ b/src/world_intel_mcp/tests/test_liquidity_ecb_404.py@@ -157,10 +157,10 @@ async def test_the_portal_problem_404_stays_a_final_no_data_answer(fetcher, slee@pytest.mark.parametrize("body, no_data", [- pytest.param(b"", True, id="empty"),- pytest.param(b" \n", True, id="whitespace"),+ pytest.param(b"", False, id="empty"),+ pytest.param(b" \n", False, id="whitespace"),pytest.param(_ECB_404.encode(), True, id="live-problem-json"),- pytest.param(b'{"title":"No results"}', True, id="json-object"),+ pytest.param(b'{"title":"No results"}', False, id="json-object"),pytest.param(_HTML_404.encode(), False, id="html"),pytest.param(b"Not Found", False, id="plain-text"),pytest.param(b"[]", False, id="json-array"),@@ -174,16 +174,6 @@ def test_ecb_404_body_classification(body, no_data):assert liquidity._ecb_404_is_no_data(body) is no_data-def test_changelog_states_the_ecb_404_rule():- text = " ".join((Path(__file__).parents[3] / "CHANGELOG.md").read_text().split())- assert (- "An ECB 404 whose body is empty or a JSON object (the portal's problem answer) is a final "- "no-data answer, without outage retries; any other 404, such as an HTML or plain-text error "- "page, is retried, counted as a breaker failure and takes the outage path."- ) in text- assert "ECB 404 responses are final no-data answers" not in text--@pytest.mark.parametrize("body, no_data", [pytest.param(_ECB_404.encode(), True, id="live-problem-json"),pytest.param(b'{"detail":"No Series was returned for the query"}', True, id="detail-is-the-prefix"),diff --git a/src/world_intel_mcp/tests/test_liquidity_regressions.py b/src/world_intel_mcp/tests/test_liquidity_regressions.pyindex c6ffc3d..602d6a5 100644--- a/src/world_intel_mcp/tests/test_liquidity_regressions.py+++ b/src/world_intel_mcp/tests/test_liquidity_regressions.py@@ -12,7 +12,7 @@ import respxfrom world_intel_mcp.sources import liquidityfrom world_intel_mcp.tests.test_sources_liquidity import (- _BSI, _FRED, _FRED_URL, _ECB_BSI_URL, _ECB_ILM_URL,+ _BSI, _ECB_404, _FRED, _FRED_URL, _ECB_BSI_URL, _ECB_ILM_URL,_fixed_clock_and_no_throttle, _fred_router, _mock_all, fetcher,)@@ -78,8 +78,10 @@ def test_alignment_documentation_states_cutoff_and_tuesday():assert "Net liquidity therefore starts at 2003-02-12" not in changelog+# Only the portal's own no-series 404 (the captured problem body) is a+# no-data answer; any other 404 takes the outage path (test_liquidity_ecb_404.py).@pytest.mark.parametrize("status, body, message", [- (404, b'{"title":"No results"}', "no series matches the key"),+ pytest.param(404, _ECB_404.encode(), "no series matches the key", id="404-portal-no-series"),(200, b"", "no observations on or after 2026-10-01"),])@respx.mock@@ -317,7 +319,9 @@ async def test_ecb_invalid_json_is_a_series_error(fetcher):async def test_ecb_no_data_transport_metrics(fetcher, monkeypatch, status, metric):fetcher.max_retries = 2monkeypatch.setattr("world_intel_mcp.fetcher.asyncio.sleep", AsyncMock())- route = respx.get(_ECB_BSI_URL).respond(status, content=b"")+ # 404: the portal's no-series problem body; 200: an empty body (an+ # unexpected payload, but the transport worked, so no retry or breaker failure).+ route = respx.get(_ECB_BSI_URL).respond(status, content=_ECB_404.encode() if status == 404 else b"")for _ in range(4):await liquidity.fetch_ecb_series(fetcher, key=liquidity._ECB_MONEY_KEY)if metric == "attempts":diff --git a/src/world_intel_mcp/tests/test_news_market.py b/src/world_intel_mcp/tests/test_news_market.pyindex c80c65e..4a1858d 100644--- a/src/world_intel_mcp/tests/test_news_market.py+++ b/src/world_intel_mcp/tests/test_news_market.py@@ -483,7 +483,9 @@ def test_measure_country_first_bar_has_no_prior():def test_trailing_zscore_flat_series_is_none():flat = [(1789435800 + i * 86400, 100.0) for i in range(14)]bars = _bars("FLAT", _chart("FLAT", flat))- assert nm.trailing_zscore(bars, bars.dates[-1], 0.01) == (None, 13)+ # 14 flat bars give 12 returns before the session (the session's own+ # return is not in its baseline); enough for a z-score, but sd is 0.+ assert nm.trailing_zscore(bars, bars.dates[-1], 0.01) == (None, 12)def test_benchmark_for():@@ -510,7 +512,7 @@ def test_ambiguous_company_excluded_with_reason():assert mapped == [] and unmapped == []assert excluded[0]["entity"]["name"] == "Shell"assert excluded[0]["reason"].startswith("'shell' is also an artillery round")- assert "and no article from a energy feed" in excluded[0]["reason"]+ assert "and no article from an energy feed" in excluded[0]["reason"]# "25 bp" is basis points; a finance feed does not make it the company_, _, bp = nm.classify_companies("Fed cuts rates by 25 bp", {"finance"})assert bp[0]["entity"]["name"] == "Bp"@@ -565,7 +567,7 @@ def test_unambiguous_and_unlisted_companies():"Lockheed Martin and OpenAI sign deal; Google and Alphabet shares rise", set())assert [m["ticker"] for m in mapped] == ["LMT", "GOOGL"] # one row per tickerassert unmapped == [{"entity": {"type": "company", "name": "Openai", "sector": "ai"},- "reason": "no public listing in the entity table (private or unlisted)"}]+ "reason": "no ticker in the entity table"}]assert excluded == []@@ -764,7 +766,7 @@ async def test_composite_story_time_problems_are_gaps(fast_fetcher, monkeypatch)assert rows["AAPL"]["status"] == "data_gap"assert rows["AAPL"]["gap"] == ("story timestamp 2026-10-17T21:18:34Z is later than the collection time "- "2026-10-17T16:00:00Z (feed timestamp error)")+ "2026-10-17T16:00:00Z (a timestamp error in the feed or in its parsing)")assert rows["LMT"]["status"] == "data_gap"assert rows["LMT"]["gap"] == "no parseable published time in the cluster"@@ -831,7 +833,14 @@ async def test_composite_benchmark_cut_by_symbol_budget(fast_fetcher, monkeypatcassert row["benchmark"] == "^FTSE"assert row["status"] == "data_gap"assert row["gap"] == "no daily bars for benchmark ^FTSE (symbol budget)"- assert out["data_gaps"] == ["symbol budget 1 reached; not fetched: ^FTSE"]+ # The fixture's trading period is the US one, so the London listing's+ # close (21:00) is also flagged as nonstandard.+ assert out["data_gaps"] == [+ "symbol budget 1 reached; not fetched: ^FTSE",+ "ACME.L: Yahoo's current regular close, 21:00 Europe/London, differs from the standard "+ "16:30 for that zone; it is applied to every day in range, so a story published between "+ "the two times may map to the wrong session",+ ]@pytest.mark.asynciodiff --git a/src/world_intel_mcp/tests/test_prediction_cross.py b/src/world_intel_mcp/tests/test_prediction_cross.pyindex 580611f..23f335a 100644--- a/src/world_intel_mcp/tests/test_prediction_cross.py+++ b/src/world_intel_mcp/tests/test_prediction_cross.py@@ -82,10 +82,13 @@ async def test_compare_matches_live_fed_pairs_and_rejects_near_misses(fetcher: Fout = await fetch_prediction_compare(fetcher, series="KXFEDDECISION")pairs = [(m["kalshi"]["id"], m["polymarket"]["id"]) for m in out["matched"]]- # Largest absolute gap first: C25 0.01 (last trade) - 0.0035 (Polymarket- # midpoint of 0.003/0.004) = 0.0065; H25 0.135 - 0.135 = 0.- assert pairs == [("KXFEDDECISION-26OCT-C25", "2589811"), ("KXFEDDECISION-26OCT-H25", "2589813")]- assert [m["price_gap"] for m in out["matched"]] == [0.0065, 0.0]+ # Comparable pairs first, then largest absolute gap: H25 is two-sided on+ # both venues, 0.135 - 0.135 = 0; C25 is flagged (its Kalshi price is a+ # last trade on a one-sided book), 0.01 - 0.0035 (Polymarket midpoint of+ # 0.003/0.004) = 0.0065.+ assert pairs == [("KXFEDDECISION-26OCT-H25", "2589813"), ("KXFEDDECISION-26OCT-C25", "2589811")]+ assert [m["price_gap"] for m in out["matched"]] == [0.0, 0.0065]+ assert [m["comparable"] for m in out["matched"]] == [True, False]assert all(m["match_confidence"] >= 0.6 and m["reasons"] for m in out["matched"])assert out["matched_count"] == 2assert out["unmatched_kalshi"] == 3 and out["unmatched_polymarket"] == 3diff --git a/src/world_intel_mcp/tests/test_prediction_matching.py b/src/world_intel_mcp/tests/test_prediction_matching.pyindex e02dd3b..5f47eac 100644--- a/src/world_intel_mcp/tests/test_prediction_matching.py+++ b/src/world_intel_mcp/tests/test_prediction_matching.py@@ -85,9 +85,10 @@ def test_live_fed_hike_pair_matches_with_reasons() -> None:r = score_pair(K_HIKE_25_OCT, P_HIKE_25_OCT, now=NOW)assert r["rejected"] is Falseassert r["side"] == "aligned"- # dice 0.75 (9 shared words of 13 / 11) x date factor for 0.4 days of- # a 3-day tolerance (1 - 0.5 * 0.4 / 3 = 0.9338) = 0.700.- assert r["confidence"] == pytest.approx(0.700, abs=0.002)+ # dice 14/18 = 0.778 (7 shared title words of 9 Kalshi / 9 Polymarket)+ # x date factor for 0.4125 days of a 3-day tolerance+ # (1 - 0.5 * 0.4125 / 3 = 0.93125) = 0.724.+ assert r["confidence"] == pytest.approx(0.724, abs=0.002)assert any("quantities agree ['25']" in x for x in r["reasons"])assert any("end dates 0.4 days apart" in x for x in r["reasons"])diff --git a/src/world_intel_mcp/tests/test_server_registry.py b/src/world_intel_mcp/tests/test_server_registry.pyindex 899cf59..b57af91 100644--- a/src/world_intel_mcp/tests/test_server_registry.py+++ b/src/world_intel_mcp/tests/test_server_registry.py@@ -131,11 +131,11 @@ def test_aggregate_refuses_drift_and_collisions() -> None:def test_tool_count_matches_documented_surface(server) -> None:- """139 = 138 intelligence tools + intel_status. If this fails after+ """160 = 159 intelligence tools + intel_status. If this fails afteradding a tool, update README.md, ROADMAP.md, and this number in thesame change: the repo's history shows doc counts drifting stalewithin weeks when nothing enforced them."""- assert len(server.TOOLS) == 139+ assert len(server.TOOLS) == 160@pytest.mark.asynciodiff --git a/src/world_intel_mcp/tests/test_sources_fleet.py b/src/world_intel_mcp/tests/test_sources_fleet.pyindex 248299c..f7e5a52 100644--- a/src/world_intel_mcp/tests/test_sources_fleet.py+++ b/src/world_intel_mcp/tests/test_sources_fleet.py@@ -71,7 +71,8 @@ async def test_fetch_fleet_report(return {"waterways": [{"name": "Suez Canal", "status": "elevated", "warning_count": 2},- ]+ ],+ "feed_stale": False,}async def _surges(f) -> dict:@@ -121,9 +122,9 @@ async def test_fetch_fleet_report(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."""+ """Every dynamic component raising still yields a well-formed report,+ and it says it has no inputs: readiness UNKNOWN with a null score and+ an error, not LOW_ACTIVITY with a score of 0 (a quiet fleet)."""async def _boom(f) -> dict:raise RuntimeError("component down")@@ -134,13 +135,16 @@ async def test_fetch_fleet_report_survives_component_failures(result = await fetch_fleet_report(fetcher)- assert result["readiness_level"] == "LOW_ACTIVITY"- assert result["readiness_score"] == 0+ assert result["readiness_level"] == "UNKNOWN"+ assert result["readiness_score"] is Noneassert 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+ assert result["error"] == (+ "All fleet report components unavailable: "+ "military_surge, theater_posture, vessel_snapshot"+ )@pytest.mark.asyncio@@ -189,8 +193,9 @@ async def test_fetch_fleet_report_all_components_down_is_an_error() -> None:"""Regression (silent-empty class): with every component raising,_safe returned {} for each and the report read LOW_ACTIVITY with no- marker. The zeroed structure stays; error / reason /- unavailable_components / data_gaps say the report has no inputs."""+ marker. The zeroed lists stay; readiness is UNKNOWN with a null+ score, and error / reason / unavailable_components / data_gaps say+ the report has no inputs."""async def _boom(f) -> dict:raise RuntimeError("component down")@@ -209,12 +214,14 @@ async def test_fetch_fleet_report_all_components_down_is_an_error(assert result["degraded"] is Trueassert result["unavailable_components"] == list(_COMPONENTS)assert result["data_gaps"] == [- f"{name}: unavailable (RuntimeError: component down); "- "readiness_score is computed without it"+ f"{name}: unavailable (RuntimeError: component down)"for name in _COMPONENTS+ ] + [+ "readiness_level is UNKNOWN and readiness_score is null: no component "+ "was available to score"]- assert result["readiness_level"] == "LOW_ACTIVITY"- assert result["readiness_score"] == 0+ assert result["readiness_level"] == "UNKNOWN"+ assert result["readiness_score"] is None@pytest.mark.asyncio@@ -228,7 +235,8 @@ async def test_fetch_fleet_report_partial_failure_is_named_not_fatal(return {"waterways": [{"name": "Strait of Hormuz", "status": "critical", "naval_warnings": 3}- ]+ ],+ "feed_stale": False,}async def _surges(f) -> dict:@@ -248,8 +256,9 @@ async def test_fetch_fleet_report_partial_failure_is_named_not_fatal(assert result["degraded"] is Trueassert result["unavailable_components"] == ["theater_posture"]assert result["data_gaps"] == [- "theater_posture: unavailable (TimeoutError: opensky timed out); "- "readiness_score is computed without it"+ "theater_posture: unavailable (TimeoutError: opensky timed out)",+ "readiness_level and readiness_score are lower bounds: they leave out "+ "theater_posture, so the score can reach at most 60 of 90",]# Critical waterway 30 + one surge 15; no aircraft term without posture.assert result["readiness_score"] == 45@@ -283,8 +292,9 @@ async def test_fetch_fleet_report_names_an_nga_outage_from_the_real_snapshot(assert result["unavailable_components"] == ["vessel_snapshot"]assert result["data_gaps"] == ["vessel_snapshot: unavailable (NGA navigational warnings unavailable: "- "NGA MSI API unavailable (no live or cached data)); readiness_score is "- "computed without it"+ "NGA MSI API unavailable (no live or cached data))",+ "readiness_level and readiness_score are lower bounds: they leave out "+ "vessel_snapshot, so the score can reach at most 60 of 90",]assert result["waterway_count"] == 9assert {ww["status"] for ww in result["waterway_summary"]} == {"unknown"}@@ -306,6 +316,7 @@ async def test_fetch_fleet_report_carries_component_data_gaps(return {"waterways": [{"name": "Suez Canal", "status": "clear", "naval_warnings": 0}],"degraded": True,+ "feed_stale": False,"data_gaps": [stale],}diff --git a/src/world_intel_mcp/tests/test_sources_intelligence.py b/src/world_intel_mcp/tests/test_sources_intelligence.pyindex 492d29e..daa55a1 100644--- a/src/world_intel_mcp/tests/test_sources_intelligence.py+++ b/src/world_intel_mcp/tests/test_sources_intelligence.py@@ -1023,11 +1023,12 @@ async def test_fetch_military_surge_quiet_posture(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."""+ """Regression: naval keywords were matched against every warning with+ no position or area filter, so 3 naval warnings anywhere on Earth+ marked all nine waterways 'critical' alike. These state no position,+ so no waterway is credited with them (a positionless warning is never+ credited by its area code); the three naval ones are still classified+ as naval and listed as unplaced, and BUOY UNLIT is not."""warnings = [{"id": "2026-1", "text": "NAVAL EXERCISES IN AREA", "navarea": "IV"},{"id": "2026-2", "text": "SUBMARINE OPERATIONS", "navarea": "XI"},@@ -1035,7 +1036,9 @@ async def test_fetch_vessel_snapshot_naval_keywords({"id": "2026-4", "text": "BUOY UNLIT", "navarea": "IV"},]monkeypatch.setattr(- maritime, "fetch_nav_warnings", _async_return({"warnings": warnings})+ maritime,+ "fetch_nav_warnings",+ _async_return({"warnings": warnings, "feed_stale": False}),)result = await intelligence.fetch_vessel_snapshot(fetcher)@@ -1043,20 +1046,32 @@ async def test_fetch_vessel_snapshot_naval_keywords(assert result["source"] == "nga-msi-vessel-snapshot"assert result["count"] == 9assert result["total_nav_warnings"] == 4+ assert result["total_naval_warnings"] == 3 # keyword matches; BUOY UNLIT excluded+ assert [(w["id"], w["reason"]) for w in result["unplaced_naval_warnings"]] == [+ ("2026-1", "unknown_area_code"),+ ("2026-2", "unknown_area_code"),+ ("2026-3", "unknown_area_code"),+ ]names = {w["name"] for w in result["waterways"]}assert "Strait of Hormuz" in namesfor 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+ assert ww["naval_warnings"] == 0+ assert ww["status"] == "clear"+ assert ww["warning_details"] == []@pytest.mark.asyncioasync def test_fetch_vessel_snapshot_clear(fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(maritime, "fetch_nav_warnings", _async_return({"warnings": []}))+ """A current feed (feed_stale False) with no naval warnings near any+ waterway reads clear; an empty or undated feed reads unknown instead+ (test_maritime_honesty_r3.py)."""+ monkeypatch.setattr(+ maritime, "fetch_nav_warnings",+ _async_return({"warnings": [], "feed_stale": False}),+ )result = await intelligence.fetch_vessel_snapshot(fetcher)assert all(ww["status"] == "clear" for ww in result["waterways"])@@ -1125,15 +1140,16 @@ _NGA_LIVE = ["ARE ADVISED TO EXERCISE EXTREME CAUTION.\n","181218Z MAR 2022", "NAVAREA III 118/22 181124Z MAR 22.",),- # States no position; NAVAREA XII contains the canal's Pacific end.+ # States no position; NAVAREA XII contains the canal's Pacific end, but+ # a positionless warning is credited to no waterway by its area code._nga_record(2023, 249, "12", "83","EASTERN NORTH PACIFIC.\nCANCEL NAVAREA XII 243/23 AND THIS MSG,\n""SEARCH SUSPENDED.\n","280353Z APR 2023", "JRCC HONOLULU 0/23 280342Z APR 23.",),- # Its only position, 154-84.0W, is malformed (84 minutes): no NAVAREA- # credit either, since it does state a place (south of Hawaii).+ # Its only position, 154-84.0W, is malformed (84 minutes): credited to+ # no waterway._nga_record(2023, 243, "12", "83","EASTERN NORTH PACIFIC.\nMAN OVERBOARD IN VICINITY 10-52.0N 154-84.0W\n"@@ -1186,19 +1202,20 @@ async def test_fetch_vessel_snapshot_credits_only_the_waterways_a_live_warning_c# Neither naval-keyword warning is near a waterway.for ww in result["waterways"]:assert ww["naval_warnings"] == 0- assert ww["status"] == "clear"+ assert ww["status"] == "stale"+ assert ww["status_as_of"] == "2024-05-10T05:59:00Z"assert ww["warning_details"] == []- assert ww["naval_by_match"] == {"proximity": 0, "navarea": 0}+ assert ww["naval_by_match"] == {"proximity": 0}assert result["total_naval_warnings"] == 2assert {name: ww["total_nearby"] for name, ww in by_name.items()} == {"Strait of Hormuz": 1, "Strait of Malacca": 0, "Suez Canal": 0,- "Panama Canal": 3, "Bab-el-Mandeb": 0, "Taiwan Strait": 1,+ "Panama Canal": 2, "Bab-el-Mandeb": 0, "Taiwan Strait": 1,"Strait of Gibraltar": 0, "GIUK Gap": 0, "Bosphorus": 0,}- # Two by stated position, one (the positionless cancellation) by NAVAREA.- assert by_name["Panama Canal"]["nearby_by_match"] == {"proximity": 2, "navarea": 1}- assert by_name["Strait of Hormuz"]["nearby_by_match"] == {"proximity": 1, "navarea": 0}+ # Both by stated position; the positionless cancellation is credited nowhere.+ assert by_name["Panama Canal"]["nearby_by_match"] == {"proximity": 2}+ assert by_name["Strait of Hormuz"]["nearby_by_match"] == {"proximity": 1}assert result["unplaced_naval_warnings"] == [{@@ -1213,7 +1230,7 @@ async def test_fetch_vessel_snapshot_credits_only_the_waterways_a_live_warning_crule = result["matching_rule"]assert rule["proximity_km"] == 300.0- assert rule["waterway_navareas"] == {"Panama Canal": ["IV", "XII"]}+ assert "waterway_navareas" not in ruleassert rule["area_codes"] == maritime.area_codes_view()assert "proximity_km" in rule["rule"]@@ -1226,9 +1243,11 @@ async def test_fetch_vessel_snapshot_credits_only_the_waterways_a_live_warning_c"NGA feed: newest active warning was issued 2024-05-10T05:59:00Z, ")assert result["data_gaps"][1:] == [- "1 naval warning(s) state no readable position and no single-NAVAREA "- "area code, so no waterway is credited with them "- "(unplaced_naval_warnings): 2022-789 (multi_navarea_series)"+ "every waterway reads stale, not a threat level: naval_warnings counts "+ "warnings from a feed last updated 2024-05-10T05:59:00Z (status_as_of)",+ "1 naval warning(s) state no readable position, so no waterway is "+ "credited with them (unplaced_naval_warnings): A:2022-789 "+ "(multi_navarea_series)",]@@ -1271,7 +1290,7 @@ async def test_fetch_vessel_snapshot_naval_status_counts_only_nearby_warnings("RED SEA.\nYEMEN.\nDNC 10.\nWARSHIP OPERATIONS 12-40.00N 043-20.00E.\n",stamp, "NAVAREA IX 4/26",),- # No position, single-NAVAREA code 4: credited to Panama by NAVAREA.+ # No position, code 4 (NAVAREA IV, also issued under XVIII): credited nowhere._nga_record(2026, 905, "4", "24","WESTERN NORTH ATLANTIC.\nNAVAL OPERATIONS IN PROGRESS.\n",@@ -1294,7 +1313,7 @@ async def test_fetch_vessel_snapshot_naval_status_counts_only_nearby_warnings(hormuz = by_name["Strait of Hormuz"]assert hormuz["naval_warnings"] == 3assert hormuz["status"] == "critical"- assert hormuz["naval_by_match"] == {"proximity": 3, "navarea": 0}+ assert hormuz["naval_by_match"] == {"proximity": 3}assert [(d["id"], d["match"], d["distance_km"]) for d in hormuz["warning_details"]] == [("2026-901", "proximity", 11.4),("2026-903", "proximity", 98.0),@@ -1304,17 +1323,18 @@ async def test_fetch_vessel_snapshot_naval_status_counts_only_nearby_warnings(assert by_name["Bab-el-Mandeb"]["warning_details"][0]["distance_km"] == 9.6panama = by_name["Panama Canal"]- assert panama["status"] == "advisory"- assert panama["naval_by_match"] == {"proximity": 0, "navarea": 1}- assert panama["warning_details"][0]["id"] == "2026-905"- assert panama["warning_details"][0]["match"] == "navarea"- assert panama["warning_details"][0]["distance_km"] is None+ assert panama["status"] == "clear"+ assert panama["naval_by_match"] == {"proximity": 0}+ assert panama["warning_details"] == []+ assert panama["naval_warnings"] == 0+ assert panama["total_nearby"] == 0others = set(_WATERWAY_NAMES) - {"Strait of Hormuz", "Bab-el-Mandeb", "Panama Canal"}assert {by_name[name]["status"] for name in others} == {"clear"}assert [(w["id"], w["reason"], w["series"]) for w in result["unplaced_naval_warnings"]] == [- ("2026-906", "position_unreadable", "NAVAREA XII")+ ("2026-905", "multi_navarea_series", "NAVAREA IV"),+ ("2026-906", "position_unreadable", "NAVAREA XII"),]assert result["total_naval_warnings"] == 6assert result["newest_issue_age_days"] == pytest.approx(2 / 24, abs=0.1)@@ -1363,7 +1383,9 @@ async def test_fetch_vessel_snapshot_roman_numeral_navarea_is_not_an_nga_code({"id": "2026-5", "text": "X" * 500 + "...", "navarea": "A"},]monkeypatch.setattr(- maritime, "fetch_nav_warnings", _async_return({"warnings": warnings})+ maritime,+ "fetch_nav_warnings",+ _async_return({"warnings": warnings, "feed_stale": False}),)result = await intelligence.fetch_vessel_snapshot(fetcher)@@ -1380,10 +1402,10 @@ async def test_fetch_vessel_snapshot_roman_numeral_navarea_is_not_an_nga_code(("2026-3", "unknown_area_code", None),]assert result["data_gaps"] == [- "3 naval warning(s) state no readable position and no single-NAVAREA "- "area code, so no waterway is credited with them "- "(unplaced_naval_warnings): 2026-1 (unknown_area_code), "- "2026-2 (unknown_area_code), 2026-3 (unknown_area_code)",+ "3 naval warning(s) state no readable position, so no waterway is "+ "credited with them (unplaced_naval_warnings): IV:2026-1 "+ "(unknown_area_code), XI:2026-2 (unknown_area_code), IX:2026-3 "+ "(unknown_area_code)","1 warning text(s) were cut at 500 characters; positions after the ""cut are not read",]diff --git a/src/world_intel_mcp/tests/test_sources_liquidity.py b/src/world_intel_mcp/tests/test_sources_liquidity.pyindex 02c8d6a..36503d0 100644--- a/src/world_intel_mcp/tests/test_sources_liquidity.py+++ b/src/world_intel_mcp/tests/test_sources_liquidity.py@@ -437,9 +437,15 @@ async def test_board_rows_values_and_sorting(fetcher: Fetcher) -> None:assert rows["eurosystem_total_assets"]["period_end"] == "2026-10-11"assert rows["us_m2"]["period_end"] == "2026-08-31"assert all(r["measure"] == "amount_outstanding" for r in rows.values())+ # biggest_move ranks the absolute change in billions of each row's+ # currency (millions / 1,000), not the percentage change.+ billions = [+ abs(r["change"]) / (1000 if r["units"].endswith(" millions") else 1) for r in out["indicators"]+ ]+ assert billions == sorted(billions, reverse=True)moves = [abs(r["change_pct"]) for r in out["indicators"]]- assert moves == sorted(moves, reverse=True)- assert out["indicators"][0]["indicator"] == "reverse_repo"+ assert moves == [0.5379, 0.1781, 0.077, 0.1737, 0.1197, 0.0658, 0.0133, 91.6736, 0.0045]+ assert out["indicators"][0]["indicator"] == "us_m2"newest = await liquidity.fetch_liquidity_board(fetcher, sort="newest")ends = [r["period_end"] for r in newest["indicators"]]@@ -455,7 +461,7 @@ async def test_board_component_outage_drops_net_liquidity_instead_of_zeroing(fetassert "net_liquidity" not in names and "treasury_general_account" not in namesassert "eurosystem_total_assets" not in namesmissing = {u["indicator"] for u in out["unavailable"]}- assert {"treasury_general_account", "net_liquidity", "Eurosystem total assets"} <= missing+ assert {"treasury_general_account", "net_liquidity", "eurosystem_total_assets"} <= missingassert any("never computed with a zero term" in u["error"] for u in out["unavailable"])assert "error" not in out # the rest of the board is real@@ -467,7 +473,8 @@ async def test_board_total_outage_is_an_error(fetcher: Fetcher) -> None:respx.get(_ECB_ILM_URL).mock(return_value=httpx.Response(503))out = await liquidity.fetch_liquidity_board(fetcher)assert out["error"] == "liquidity board unavailable: every source failed"- assert out["indicators"] == [] and len(out["unavailable"]) == 7+ # 4 FRED rows, net liquidity, euro area M1, M2 and M3 (one row each), Eurosystem total assets.+ assert out["indicators"] == [] and len(out["unavailable"]) == 9@respx.mock@@ -524,7 +531,8 @@ async def test_net_liquidity_method_states_wednesday_levels_conversion_and_rrp_arrp = method["components"]["RRPONTSYD"]assert (rrp["observed"], rrp["units"]) == ("daily, business days", "USD billions")assert rrp["conversion"] == "none: already USD billions"- assert "never a later day" in rrp["alignment"] and "within 5 days" in rrp["alignment"]+ assert "never a later day" in rrp["alignment"]+ assert "when blank on or after 2013-09-23, Tuesday only; no fallback before that date." in rrp["alignment"]# The statement matches the arithmetic: raw WDTGAL millions / 1,000 and# the raw same-Wednesday RRP billions, unconverted.point = out["points"][0]diff --git a/src/world_intel_mcp/tests/test_sources_maritime.py b/src/world_intel_mcp/tests/test_sources_maritime.pyindex 8d35dd9..d5ca37c 100644--- a/src/world_intel_mcp/tests/test_sources_maritime.py+++ b/src/world_intel_mcp/tests/test_sources_maritime.py@@ -145,8 +145,9 @@ async def test_fetch_nav_warnings_dict_payload_single_warning(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."""+ """Regression: an NGA outage returned warnings=[] with no error key,+ shape-identical to calm seas. The empty lists stay; error says the+ feed is down."""async def _no_sleep(*args, **kwargs) -> None:return None@@ -159,7 +160,7 @@ async def test_fetch_nav_warnings_api_down(assert result["warnings"] == []assert result["count"] == 0assert result["by_navarea"] == {}- assert "error" not in result # current (dishonest-quiet) behavior+ assert result["error"] == "NGA MSI API unavailable (no live or cached data)"def test_extract_coords() -> None:@@ -323,6 +324,10 @@ async def test_fetch_nav_warnings_unrecognized_payload_is_an_error(@respx.mock@pytest.mark.asyncioasync def test_fetch_nav_warnings_empty_list_is_not_an_outage(fetcher: Fetcher) -> None:+ """An empty answer is not an outage (no error), but it is degraded: the+ feed carried 386 active warnings on 2026-10-17, so an empty one cannot+ be told from a feed fault, and how current it is cannot be checked+ (feed_stale None)."""# The live API answers msgYear=2026 with exactly this.respx.get(url__regex=r".*msi\.nga\.mil.*").mock(return_value=httpx.Response(200, json={"broadcast-warn": []})@@ -331,9 +336,14 @@ async def test_fetch_nav_warnings_empty_list_is_not_an_outage(fetcher: Fetcher)result = await fetch_nav_warnings(fetcher)assert "error" not in result- assert "degraded" not in result+ assert result["degraded"] is Trueassert result["count"] == 0- assert result["data_gaps"] == []+ assert result["data_gaps"] == [+ "NGA returned no active warnings (the feed normally carries hundreds), "+ "so a quiet sea cannot be told from a feed fault and how current the "+ "list is cannot be checked"+ ]+ assert result["feed_stale"] is Noneassert result["newest_issue_date"] is Noneassert result["newest_issue_age_days"] is None@@ -498,7 +508,7 @@ def test_nga_area_codes_cover_the_live_code_table() -> None:assert codes["4"]["navareas"] == ("IV",)assert codes["12"]["navareas"] == ("XII",)- assert [c for c in codes if codes[c]["single_navarea"]] == ["4", "12"]+ assert [c for c in codes if codes[c]["single_navarea"]] == ["12"]assert codes["C"]["unlisted_navareas"] == ("XVII", "XVIII", "XIX", "XX", "XXI")listed: set[str] = set()