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
CLI honesty: 33 commands stop rendering outages as healthy empty states; Rich markup escaped per-site
Phoenix Agent (Marcs-Mac-Studio)7237ad7c9be6
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.pyindex 2638e9a..791aef3 100644--- a/src/world_intel_mcp/cli.py+++ b/src/world_intel_mcp/cli.py@@ -11,6 +11,7 @@ from typing import Anyimport clickfrom rich.console import Console+from rich.markup import escapefrom rich.table import Tablefrom rich.panel import Panelfrom rich import box@@ -76,6 +77,25 @@ def _print_json(data: dict) -> None:console.print_json(json.dumps(data, default=str))+def _bail_on_error(ctx: click.Context, data: dict) -> bool:+ """True when the command should stop rendering.++ In --json-output mode the raw dict (error included) is printed+ unchanged. In table mode an upstream {"error": ...} is printed in red+ so an outage is never shape-identical to a quiet world ("0+ earthquakes", "No market data available"). Degraded-but-partial+ payloads carry no top-level "error" key and fall through to normal+ rendering.+ """+ if ctx.obj.get("json"):+ _print_json(data)+ return True+ if "error" in data:+ console.print(f"[red]Error:[/red] {escape(str(data['error']))}")+ return True+ return False++# ---------------------------------------------------------------------------# Root group# ---------------------------------------------------------------------------@@ -104,8 +124,7 @@ def markets_cmd(ctx: click.Context, symbols: tuple[str, ...]) -> None:sym_list = list(symbols) if symbols else Nonedata = _run(markets.fetch_market_quotes(f, symbols=sym_list))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnquotes = data.get("quotes", [])@@ -140,8 +159,7 @@ def crypto(ctx: click.Context, limit: int) -> None:f = _get_fetcher()data = _run(markets.fetch_crypto_quotes(f, limit=limit))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returncoins = data.get("coins", [])@@ -177,8 +195,7 @@ def macro(ctx: click.Context) -> None:f = _get_fetcher()data = _run(markets.fetch_macro_signals(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnsignals = data.get("signals", {})@@ -365,8 +382,7 @@ def earthquakes(ctx: click.Context, min_mag: float, hours: int) -> None:f = _get_fetcher()data = _run(seismology.fetch_earthquakes(f, min_magnitude=min_mag, hours=hours))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnquakes = data.get("earthquakes", [])@@ -482,8 +498,7 @@ def flights(ctx: click.Context, bbox: str | None) -> None:f = _get_fetcher()data = _run(military.fetch_military_flights(f, bbox=bbox))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnaircraft = data.get("aircraft", [])@@ -514,8 +529,7 @@ def posture(ctx: click.Context) -> None:f = _get_fetcher()data = _run(military.fetch_theater_posture(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnconsole.print(@@ -554,8 +568,7 @@ def outages(ctx: click.Context) -> None:f = _get_fetcher()data = _run(infrastructure.fetch_internet_outages(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnconsole.print(@@ -567,7 +580,8 @@ def outages(ctx: click.Context) -> None:ongoing = "[red]ONGOING[/red]" if o.get("is_ongoing") else ""countries = ", ".join(o.get("countries", [])[:5]) if o.get("countries") else ""console.print(- f" {o.get('start', '')[:16]} {countries} {o.get('description', '')[:80]} {ongoing}"+ f" {o.get('start', '')[:16]} {escape(countries)} "+ f"{escape(o.get('description', '')[:80])} {ongoing}")@@ -578,8 +592,7 @@ def cables(ctx: click.Context) -> None:f = _get_fetcher()data = _run(infrastructure.fetch_cable_health(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnstatus_labels = {@@ -619,8 +632,7 @@ def warnings(ctx: click.Context, navarea: str | None) -> None:f = _get_fetcher()data = _run(maritime.fetch_nav_warnings(f, navarea=navarea))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnconsole.print(f"[bold]{data.get('count', 0)} active warnings[/bold]\n")@@ -633,8 +645,9 @@ def warnings(ctx: click.Context, navarea: str | None) -> None:console.print()for w in data.get("warnings", [])[:20]:+ area = escape(f"[{w.get('navarea', '?')}]")console.print(- f" [{w.get('navarea', '?')}] {w.get('id', '')} {w.get('text', '')[:100]}"+ f" {area} {escape(w.get('id', ''))} {escape(w.get('text', '')[:100])}")@@ -650,13 +663,21 @@ def climate_cmd(ctx: click.Context) -> None:f = _get_fetcher()data = _run(climate.fetch_climate_anomalies(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnzones = data.get("zones", {})sig = data.get("significant_anomalies", [])+ # Degraded-but-partial: some zones failed but the rest are usable.+ # Render the data AND a visible warning naming what is missing.+ unavailable = data.get("unavailable_zones", [])+ if unavailable:+ console.print(+ f"[yellow]Warning:[/yellow] {len(unavailable)} zones unavailable "+ f"(Open-Meteo): {escape(', '.join(unavailable))}\n"+ )+table = Table(title="Climate Anomalies", box=box.SIMPLE_HEAVY)table.add_column("Zone", style="bold")table.add_column("Temp Anomaly", justify="right")@@ -722,8 +743,7 @@ def news_cmd(ctx: click.Context, category: str | None, limit: int) -> None:f = _get_fetcher()data = _run(news.fetch_news_feed(f, category=category, limit=limit))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnitems = data.get("items", [])@@ -736,11 +756,15 @@ def news_cmd(ctx: click.Context, category: str | None, limit: int) -> None:)for item in items:- cat = item.get("category", "")- title = item.get("title", "")- feed = item.get("feed_name", "")+ # Remote values are escaped so the category label renders+ # literally instead of parsing as a markup tag, and bracketed+ # sequences inside feed titles can't drop text or raise+ # MarkupError.+ cat = escape(f"[{item.get('category', '')}]")+ title = escape(item.get("title", ""))+ feed = escape(item.get("feed_name", ""))pub = (item.get("published") or "")[:16]- console.print(f" [{cat}] [bold]{title}[/bold]")+ console.print(f" {cat} [bold]{title}[/bold]")console.print(f" {feed} — {pub}")@@ -752,8 +776,7 @@ def trending(ctx: click.Context, min_count: int) -> None:f = _get_fetcher()data = _run(news.fetch_trending_keywords(f, min_count=min_count))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnkeywords = data.get("keywords", [])@@ -783,15 +806,14 @@ def gdelt(ctx: click.Context, query: str, mode: str, limit: int) -> None:f = _get_fetcher()data = _run(news.fetch_gdelt_search(f, query=query, mode=mode, limit=limit))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnif mode == "artlist":articles = data.get("articles", [])console.print(f"[bold]{len(articles)} articles[/bold] for '{query}'\n")for a in articles[:20]:- title = a.get("title", "")[:80]+ title = escape(a.get("title", "")[:80])domain = a.get("domain", "")console.print(f" [bold]{title}[/bold] ({domain})")else:@@ -812,8 +834,7 @@ def predictions(ctx: click.Context, limit: int) -> None:f = _get_fetcher()data = _run(prediction.fetch_prediction_markets(f, limit=limit))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnmkts = data.get("markets", [])@@ -856,8 +877,7 @@ def displacement_cmd(ctx: click.Context, year: int | None) -> None:f = _get_fetcher()data = _run(displacement.fetch_displacement_summary(f, year=year))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returntotals = data.get("global_totals", {})@@ -893,8 +913,7 @@ def delays(ctx: click.Context) -> None:f = _get_fetcher()data = _run(aviation.fetch_airport_delays(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returndelayed = data.get("delayed", [])@@ -939,8 +958,7 @@ def threats(ctx: click.Context, limit: int) -> None:f = _get_fetcher()data = _run(cyber.fetch_cyber_threats(f, limit=limit))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnby_sev = data.get("by_severity", {})@@ -994,8 +1012,7 @@ def brief(ctx: click.Context, country_code: str) -> None:f = _get_fetcher()data = _run(intelligence.fetch_country_brief(f, country_code=country_code))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnllm_tag = (@@ -1004,7 +1021,9 @@ def brief(ctx: click.Context, country_code: str) -> None:else "[yellow]data-only[/yellow]")console.print(f"[bold]Intelligence Brief: {country_code}[/bold] ({llm_tag})\n")- console.print(data.get("brief", "No brief available."))+ # LLM-generated free text: escape so bracketed sequences render+ # instead of parsing as markup.+ console.print(escape(str(data.get("brief", "No brief available."))))d = data.get("data", {})if d.get("gdp") or d.get("recent_events"):@@ -1073,7 +1092,7 @@ def dossier(ctx: click.Context, country: str) -> None:news = data.get("news", {})console.print(f"[blue]News:[/blue] {news.get('mention_count', 0)} recent mentions")for art in news.get("mentions", [])[:3]:- console.print(f" - {art.get('title', 'N/A')[:80]}")+ console.print(f" - {escape(art.get('title', 'N/A')[:80])}")# Securitysec = data.get("security", {})@@ -1231,8 +1250,7 @@ def central_banks_cmd(ctx: click.Context) -> None:f = _get_fetcher()data = _run(fetch_central_bank_rates(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnfred_tag = (@@ -1273,8 +1291,7 @@ def shipping_cmd(ctx: click.Context) -> None:f = _get_fetcher()data = _run(shipping.fetch_shipping_index(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnconsole.print(@@ -1310,8 +1327,7 @@ def social_cmd(ctx: click.Context) -> None:f = _get_fetcher()data = _run(social.fetch_social_signals(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnmetrics = data.get("velocity_metrics", {})@@ -1323,7 +1339,7 @@ def social_cmd(ctx: click.Context) -> None:for post in data.get("top_posts", [])[:15]:score = post.get("score", 0)style = "bold" if score >= 1000 else ""- title = post.get("title", "")[:80]+ title = escape(post.get("title", "")[:80])console.print(f" [{style}]{score:>5}[/{style}] {title}"if style@@ -1338,8 +1354,7 @@ def disease_cmd(ctx: click.Context) -> None:f = _get_fetcher()data = _run(health.fetch_disease_outbreaks(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnconsole.print(@@ -1349,8 +1364,8 @@ def disease_cmd(ctx: click.Context) -> None:for item in data.get("items", [])[:20]:hc = "[red]HC[/red] " if item.get("is_high_concern") else " "- title = item.get("title", "")[:80]- feed = item.get("feed_name", "")+ title = escape(item.get("title", "")[:80])+ feed = escape(item.get("feed_name", ""))console.print(f" {hc}{title} [dim]({feed})[/dim]")@@ -1362,8 +1377,7 @@ def elections_cmd(ctx: click.Context, country: str | None) -> None:f = _get_fetcher()data = _run(elections.fetch_election_calendar(f, country=country))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returntable = Table(title="Election Calendar", box=box.SIMPLE_HEAVY)@@ -1400,8 +1414,7 @@ def nuclear_cmd(ctx: click.Context, hours: int) -> None:f = _get_fetcher()data = _run(nuclear.fetch_nuclear_monitor(f, hours=hours))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnconsole.print(@@ -1424,8 +1437,7 @@ def space_cmd(ctx: click.Context) -> None:f = _get_fetcher()data = _run(space_weather.fetch_space_weather(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returntable = Table(title="Space Weather", box=box.SIMPLE_HEAVY)@@ -1454,8 +1466,7 @@ def sanctions_cmd(ctx: click.Context, query: str, country: str | None) -> None:f = _get_fetcher()data = _run(sanctions.fetch_sanctions_search(f, query=query, country=country))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnconsole.print(@@ -1464,10 +1475,10 @@ def sanctions_cmd(ctx: click.Context, query: str, country: str | None) -> None:)for m in data.get("matches", [])[:20]:- etype = m.get("entity_type", "")- name = m.get("name", "")- programs = ", ".join(m.get("programs", [])[:3])- console.print(f" [{etype}] [bold]{name}[/bold] ({programs})")+ etype = escape(f"[{m.get('entity_type', '')}]")+ name = escape(m.get("name", ""))+ programs = escape(", ".join(m.get("programs", [])[:3]))+ console.print(f" {etype} [bold]{name}[/bold] ({programs})")@main.command(name="ai-watch")@@ -1477,15 +1488,14 @@ def ai_watch_cmd(ctx: click.Context) -> None:f = _get_fetcher()data = _run(ai_watch.fetch_ai_watch(f))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnconsole.print(f"[bold]AI Watch[/bold] — {data.get('total_items', 0)} items\n")for item in data.get("items", [])[:20]:- title = item.get("title", "")[:80]- src = item.get("source", "")- console.print(f" [{src}] {title}")+ title = escape(item.get("title", "")[:80])+ src = escape(f"[{item.get('source', '')}]")+ console.print(f" {src} {title}")# ---------------------------------------------------------------------------@@ -1504,7 +1514,7 @@ def fleet_cmd(ctx: click.Context) -> None:_print_json(data)return- console.print(f"[bold]{data.get('report_title', 'Fleet Report')}[/bold]\n")+ console.print(f"[bold]{escape(data.get('report_title', 'Fleet Report'))}[/bold]\n")totals = data.get("force_totals", {})if totals.get("battle_force"):@@ -1549,13 +1559,12 @@ def hn_cmd(ctx: click.Context, limit: int) -> None:f = _get_fetcher()data = _run(fetch_hacker_news(f, limit=limit))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnfor s in data.get("stories", []):score = s.get("score", 0)- title = s.get("title", "")[:80]+ title = escape(s.get("title", "")[:80])console.print(f" {score:>5} {title}")@@ -1567,16 +1576,15 @@ def gh_trending_cmd(ctx: click.Context, limit: int) -> None:f = _get_fetcher()data = _run(fetch_trending_repos(f, limit=limit))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnfor r in data.get("repos", []):stars = r.get("stars", 0)- name = r.get("name", "")- lang = r.get("language") or ""- desc = (r.get("description") or "")[:60]- console.print(f" {stars:>6} [bold]{name}[/bold] [{lang}] {desc}")+ name = escape(r.get("name", ""))+ lang = escape(f"[{r.get('language') or ''}]")+ desc = escape((r.get("description") or "")[:60])+ console.print(f" {stars:>6} [bold]{name}[/bold] {lang} {desc}")@main.command(name="arxiv")@@ -1588,13 +1596,12 @@ def arxiv_cmd(ctx: click.Context, query: str, limit: int) -> None:f = _get_fetcher()data = _run(fetch_arxiv_papers(f, query=query, limit=limit))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnfor p in data.get("papers", []):- title = p.get("title", "")[:80]- authors = ", ".join(p.get("authors", [])[:3])+ title = escape(p.get("title", "")[:80])+ authors = escape(", ".join(p.get("authors", [])[:3]))console.print(f" [bold]{title}[/bold]")console.print(f" {authors}")@@ -1607,8 +1614,7 @@ def spending_cmd(ctx: click.Context, limit: int) -> None:f = _get_fetcher()data = _run(fetch_usa_spending(f, limit=limit))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returntable = Table(title="Federal Agencies by Budget", box=box.SIMPLE_HEAVY)@@ -1638,8 +1644,7 @@ def bases_cmd(ctx: click.Context, operator: str | None, country: str | None) ->"""Military bases worldwide (70 bases)."""data = _run(geospatial.fetch_military_bases(operator=operator, country=country))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnconsole.print(@@ -1673,8 +1678,7 @@ def exchanges_cmd(ctx: click.Context, tier: str | None, country: str | None) ->"""Global stock exchanges (82 exchanges)."""data = _run(geospatial.fetch_stock_exchanges(tier=tier, country=country))- if ctx.obj.get("json"):- _print_json(data)+ if _bail_on_error(ctx, data):returnconsole.print(@@ -1959,9 +1963,12 @@ def report()if "error" in result:- console.print(f"[red]Error:[/red] {result['error']}")+ console.print(f"[red]Error:[/red] {escape(str(result['error']))}")if "fallback" in result:- console.print(f"[yellow]{result['fallback']}[/yellow]")+ # escape keeps the literal "[pdf]" in the install hint from+ # being eaten as a markup tag — the printed command must be+ # runnable verbatim.+ console.print(f"[yellow]{escape(str(result['fallback']))}[/yellow]")returnconsole.print(diff --git a/src/world_intel_mcp/tests/test_cli.py b/src/world_intel_mcp/tests/test_cli.pyindex d5b7eb3..fb65f39 100644--- a/src/world_intel_mcp/tests/test_cli.py+++ b/src/world_intel_mcp/tests/test_cli.py@@ -5,27 +5,26 @@ test_world_brief.py pattern), so no network happens; assertions check thatrendered Rich output contains values derived from the fakes and that CLIoptions reach the fetch functions with the right names.-Three cli.py bugs are pinned (not fixed) by characterization tests below,-marked BUG in comments:--1. Error swallowing: many commands only branch on ``ctx.obj["json"]`` and- never check ``"error" in data``, so an upstream {"error": ...} renders- as a healthy-looking empty table ("0 earthquakes", "No market data- available") with the actual error message discarded. Commands that DO- surface errors (energy, fred, fires, conflicts, dossier, btc, fleet,- traffic, ...) print the JSON error. See the *_error_dict tests.--2. Rich markup swallowing: several commands interpolate data into- ``[...]`` brackets (news category, sanctions entity_type, ai-watch- source), and the report command's own remediation hint contains a- literal ``[pdf]``. Lowercase bracketed values parse as Rich markup- tags and are silently dropped from output — the label the line exists- to show never renders, and the install hint prints as- ``pip install -e '.'``. (Uppercase values like "[IV]" or "[Rust]" fail- Rich's tag regex and survive as literal text.) This is also a- markup-injection surface: bracketed sequences inside remote data- (news titles, etc.) are interpreted as markup. See the- *_markup_swallowed tests and test_report_error_with_fallback_hint.+Two former cli.py bug classes are now covered by honest-contract tests+(they were pinned here as characterization tests until fixed):++1. Error surfacing: every data command bails via ``cli._bail_on_error``,+ so an upstream {"error": ...} prints the error text in red instead of+ rendering as a healthy-looking empty table ("0 earthquakes", "No+ market data available"). In --json-output mode the raw dict (error+ included) is printed unchanged. An outage must never be+ shape-identical to a quiet world. See the *_error_dict tests and the+ parametrized test_error_dict_reaches_table_output sweep.++2. Rich markup escaping: values interpolated into ``[...]`` label+ constructs (news category, sanctions entity_type, ai-watch source,+ gh-trending language) and remote free text (titles, descriptions,+ feed names, the report command's literal ``[pdf]`` install hint) are+ escaped with rich.markup.escape, so lowercase bracketed labels render+ literally instead of parsing as markup tags, and bracketed sequences+ inside remote data neither vanish nor raise MarkupError. See the+ *_label_renders tests, test_report_error_with_fallback_hint, and+ test_news_bracketed_remote_title_survives."""import pytest@@ -176,17 +175,31 @@ def test_markets_json_flag_prints_raw_json(monkeypatch: pytest.MonkeyPatch) -> Nassert '"change_pct"' in result.output-def test_markets_error_dict_swallowed(monkeypatch: pytest.MonkeyPatch) -> None:- # BUG: markets never checks "error" in data. An upstream failure- # renders as the healthy-looking empty state and the error text is- # discarded. Pinned, not fixed (fix belongs in cli.py).+def test_markets_error_dict_is_surfaced(monkeypatch: pytest.MonkeyPatch) -> None:+ # An upstream failure must print the error text, not the+ # healthy-looking empty state.monkeypatch.setattr(cli.markets, "fetch_market_quotes", _fake({"error": "yahoo down"}))result = _invoke("markets")assert result.exit_code == 0- assert "No market data available" in result.output- assert "yahoo down" not in result.output+ assert "yahoo down" in result.output+ assert "No market data available" not in result.output+++def test_markets_error_dict_json_mode_passes_raw_dict(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # --json-output stays machine-honest: the raw dict, error included,+ # with no separate error rendering.+ monkeypatch.setattr(+ cli.markets, "fetch_market_quotes", _fake({"error": "yahoo down"})+ )+ result = _invoke("--json-output", "markets")+ assert result.exit_code == 0+ assert '"error"' in result.output+ assert '"yahoo down"' in result.output+ assert "Error:" not in result.outputdef test_crypto_renders_and_passes_limit(monkeypatch: pytest.MonkeyPatch) -> None:@@ -442,17 +455,16 @@ def test_earthquakes_passes_options_and_renders_rows(assert "Nevada" in result.output-def test_earthquakes_error_dict_swallowed(monkeypatch: pytest.MonkeyPatch) -> None:- # BUG: earthquakes never checks "error" in data. A USGS failure renders- # as "0 earthquakes" over an empty table — indistinguishable from a- # genuinely quiet day. Pinned, not fixed.+def test_earthquakes_error_dict_is_surfaced(monkeypatch: pytest.MonkeyPatch) -> None:+ # A USGS failure must print the error text — never "0 earthquakes"+ # over an empty table, indistinguishable from a genuinely quiet day.monkeypatch.setattr(cli.seismology, "fetch_earthquakes", _fake({"error": "USGS unreachable"}))result = _invoke("earthquakes")assert result.exit_code == 0- assert "0 earthquakes" in result.output- assert "USGS unreachable" not in result.output+ assert "USGS unreachable" in result.output+ assert "0 earthquakes" not in result.outputdef test_fires_renders_regions_and_skips_zero_counts(@@ -520,6 +532,32 @@ def test_climate_renders_anomalies_and_sig_flag(assert "+0.5C" in result.output+def test_climate_degraded_partial_renders_data_and_warning(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Partial degradation (some zones failed, no top-level "error") must+ # render the usable zones AND a visible warning naming the failed+ # ones — not bail, and not silently show a shrunken table.+ payload = {+ "zones": {+ "arctic": {+ "name": "Arctic",+ "temp_anomaly_c": 4.2,+ "precip_anomaly_pct": -10.0,+ },+ },+ "significant_anomalies": [],+ "unavailable_zones": ["sahel", "amazon"],+ "degraded": True,+ }+ monkeypatch.setattr(cli.climate, "fetch_climate_anomalies", _fake(payload))+ result = _invoke("climate")+ assert result.exit_code == 0+ assert "Arctic" in result.output+ assert "Warning" in result.output+ assert "sahel, amazon" in result.output++# ---------------------------------------------------------------------------# Conflict / Military# ---------------------------------------------------------------------------@@ -705,7 +743,7 @@ def test_warnings_passes_navarea_and_renders_groups(# ----------------------------------------------------------------------------def test_news_passes_options_and_category_label_markup_swallowed(+def test_news_passes_options_and_category_label_renders(monkeypatch: pytest.MonkeyPatch,) -> None:calls: list = []@@ -729,10 +767,36 @@ def test_news_passes_options_and_category_label_markup_swallowed(assert "Summit convened on maritime security" in result.outputassert "BBC World" in result.outputassert "2026-08-31T10:00" in result.output- # BUG: the per-item category label is printed as "[geopolitics]", which- # Rich parses as an (unknown, lowercase) markup tag and silently drops —- # the item's category never reaches the user. Pinned, not fixed.- assert "geopolitics" not in result.output+ # The per-item category label must render literally; before the+ # escape fix Rich parsed "[geopolitics]" as an unknown lowercase+ # markup tag and silently dropped it.+ assert "[geopolitics]" in result.output+++def test_news_bracketed_remote_title_survives(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # Remote data is a markup-injection surface: "[/]" inside a feed+ # title is a Rich closing tag that used to unbalance the [bold]+ # wrapper and raise MarkupError, crashing the command. Escaped, the+ # title must render verbatim and the command must exit 0.+ payload = {+ "count": 1,+ "categories_fetched": ["security"],+ "items": [+ {+ "category": "security",+ "title": "Ceasefire [/] holds in region",+ "feed_name": "Feed [with] brackets",+ "published": "2026-08-31T10:00:00Z",+ }+ ],+ }+ monkeypatch.setattr(cli.news, "fetch_news_feed", _fake(payload))+ result = _invoke("news")+ assert result.exit_code == 0+ assert "Ceasefire [/] holds in region" in result.output+ assert "Feed [with] brackets" in result.outputdef test_news_rejects_invalid_category() -> None:@@ -847,6 +911,28 @@ def test_displacement_passes_year_and_renders_totals(assert "13,000,000" in result.output+def test_displacement_outage_shape_bails_not_zero_totals(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ # UNHCR's honest outage shape carries "error" alongside a zeroed+ # structure. The CLI must surface the error, never render+ # "Grand total: 0" as if there were zero displaced persons worldwide.+ payload = {+ "error": "UNHCR API unavailable (no live or cached data)",+ "degraded": True,+ "reason": "unhcr_fetch_failed",+ "by_origin": [],+ "global_totals": {"grand_total": 0},+ "year": 2025,+ "count": 0,+ }+ monkeypatch.setattr(cli.displacement, "fetch_displacement_summary", _fake(payload))+ result = _invoke("displacement")+ assert result.exit_code == 0+ assert "UNHCR API unavailable" in result.output+ assert "Grand total: 0" not in result.output++def test_delays_all_clear_message(monkeypatch: pytest.MonkeyPatch) -> None:payload = {"delayed_count": 0, "total_checked": 30, "delayed": []}monkeypatch.setattr(cli.aviation, "fetch_airport_delays", _fake(payload))@@ -1159,7 +1245,7 @@ def test_space_renders_metrics_and_skips_missing(assert "Bz" not in result.output # None metrics are omitted-def test_sanctions_passes_query_and_entity_type_markup_swallowed(+def test_sanctions_passes_query_and_entity_type_label_renders(monkeypatch: pytest.MonkeyPatch,) -> None:calls: list = []@@ -1183,12 +1269,12 @@ def test_sanctions_passes_query_and_entity_type_markup_swallowed(assert "12000 total" in result.outputassert "WAGNER GROUP" in result.outputassert "RUSSIA-EO14024" in result.output- # BUG: "[org]" is parsed as Rich markup and silently dropped — the- # entity type never renders. Pinned, not fixed.- assert "org" not in result.output+ # The entity-type label must render literally; before the escape fix+ # Rich parsed "[org]" as a markup tag and silently dropped it.+ assert "[org]" in result.output-def test_ai_watch_source_label_markup_swallowed(+def test_ai_watch_source_label_renders(monkeypatch: pytest.MonkeyPatch,) -> None:payload = {@@ -1200,9 +1286,9 @@ def test_ai_watch_source_label_markup_swallowed(assert result.exit_code == 0assert "2 items" in result.outputassert "New frontier model released" in result.output- # BUG: "[arxiv]" is parsed as Rich markup and silently dropped — the- # per-item source label never renders. Pinned, not fixed.- assert "arxiv" not in result.output+ # The per-item source label must render literally; before the escape+ # fix Rich parsed "[arxiv]" as a markup tag and silently dropped it.+ assert "[arxiv]" in result.output# ---------------------------------------------------------------------------@@ -1273,13 +1359,32 @@ def test_gh_trending_renders_repos(monkeypatch: pytest.MonkeyPatch) -> None:assert result.exit_code == 0assert "3200" in result.outputassert "acme/widget" in result.output- # "[Rust]" survives only because it starts uppercase and so fails- # Rich's markup-tag regex; a lowercase language would be swallowed- # like the news category (see BUG note in module docstring).+ # The language label is escaped, so it renders literally regardless+ # of case (an unescaped lowercase language used to be swallowed as a+ # markup tag; "[Rust]" only survived by failing Rich's tag regex).assert "[Rust]" in result.outputassert "A widget framework" in result.output+def test_gh_trending_lowercase_language_label_renders(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ payload = {+ "repos": [+ {+ "stars": 900,+ "name": "acme/gadget",+ "language": "zig",+ "description": "A gadget toolkit",+ }+ ]+ }+ monkeypatch.setattr(cli, "fetch_trending_repos", _fake(payload))+ result = _invoke("gh-trending")+ assert result.exit_code == 0+ assert "[zig]" in result.output++def test_arxiv_passes_query_and_renders_papers(monkeypatch: pytest.MonkeyPatch,) -> None:@@ -1586,9 +1691,68 @@ def test_report_error_with_fallback_hint(monkeypatch: pytest.MonkeyPatch) -> Nonassert result.exit_code == 0assert "Error:" in result.outputassert "WeasyPrint not installed" in result.output- # BUG: the fallback hint's literal "[pdf]" is parsed as a Rich markup- # tag and silently dropped, so the user is told to run- # `pip install -e '.'` — which would NOT install the pdf extra.- # Pinned, not fixed.- assert "pip install -e '.'" in result.output- assert "[pdf]" not in result.output+ # The fallback hint must print the runnable command verbatim; before+ # the escape fix Rich ate the literal "[pdf]" as a markup tag and the+ # printed command would NOT have installed the pdf extra.+ assert "pip install -e '.[pdf]'" in result.output+++# ---------------------------------------------------------------------------+# Error-surfacing sweep: every data command converted to _bail_on_error+# ---------------------------------------------------------------------------++# (cli args, module holding the fetch fn, fetch fn attribute name). One row+# per command that used to branch only on ctx.obj["json"] and rendered an+# upstream {"error": ...} as a healthy empty state.+_ERROR_SWEEP = [+ (("markets",), cli.markets, "fetch_market_quotes"),+ (("crypto",), cli.markets, "fetch_crypto_quotes"),+ (("macro",), cli.markets, "fetch_macro_signals"),+ (("earthquakes",), cli.seismology, "fetch_earthquakes"),+ (("flights",), cli.military, "fetch_military_flights"),+ (("posture",), cli.military, "fetch_theater_posture"),+ (("outages",), cli.infrastructure, "fetch_internet_outages"),+ (("cables",), cli.infrastructure, "fetch_cable_health"),+ (("warnings",), cli.maritime, "fetch_nav_warnings"),+ (("climate",), cli.climate, "fetch_climate_anomalies"),+ (("news",), cli.news, "fetch_news_feed"),+ (("trending",), cli.news, "fetch_trending_keywords"),+ (("gdelt",), cli.news, "fetch_gdelt_search"),+ (("predictions",), cli.prediction, "fetch_prediction_markets"),+ (("displacement",), cli.displacement, "fetch_displacement_summary"),+ (("delays",), cli.aviation, "fetch_airport_delays"),+ (("threats",), cli.cyber, "fetch_cyber_threats"),+ (("brief",), cli.intelligence, "fetch_country_brief"),+ (("central-banks",), cli, "fetch_central_bank_rates"),+ (("shipping",), cli.shipping, "fetch_shipping_index"),+ (("social",), cli.social, "fetch_social_signals"),+ (("disease",), cli.health, "fetch_disease_outbreaks"),+ (("elections",), cli.elections, "fetch_election_calendar"),+ (("nuclear",), cli.nuclear, "fetch_nuclear_monitor"),+ (("space",), cli.space_weather, "fetch_space_weather"),+ (("sanctions", "Wagner"), cli.sanctions, "fetch_sanctions_search"),+ (("ai-watch",), cli.ai_watch, "fetch_ai_watch"),+ (("hn",), cli, "fetch_hacker_news"),+ (("gh-trending",), cli, "fetch_trending_repos"),+ (("arxiv",), cli, "fetch_arxiv_papers"),+ (("spending",), cli, "fetch_usa_spending"),+ (("bases",), cli.geospatial, "fetch_military_bases"),+ (("exchanges",), cli.geospatial, "fetch_stock_exchanges"),+]+++ ("args", "module", "attr"),+ _ERROR_SWEEP,+ ids=[" ".join(row[0]) for row in _ERROR_SWEEP],+)+def test_error_dict_reaches_table_output(+ args: tuple[str, ...],+ module: object,+ attr: str,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(module, attr, _fake({"error": "upstream exploded"}))+ result = _invoke(*args)+ assert result.exit_code == 0+ assert "upstream exploded" in result.output