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
Implements #15: cited situation briefs + intel_daily_digest
Phoenix Agent (Marcs-Mac-Studio)4c52d5ca91e4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a17d515..a59fdcb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,36 @@# Changelog+## Unreleased++### Added+- Situation briefs now cite their sources. `fetch_situation_brief` builds a+ numbered `sources` list while walking the overview data: domain, a short+ description or headline, a URL when the upstream item carries one, and a+ timestamp when available, covering every metric that contributes to the+ brief. The Ollama prompt is instructed to cite claims inline as `[n]`+ using only that list; the structured fallback brief cites mechanically,+ since it is assembled per-metric. The response gains `sources` and+ `cited`: `cited` is true only when the returned text actually contains a+ `[n]` matching a real source number, so a brief where the model ignored+ the citation instruction (or invented an out-of-range number) is+ distinguishable from one that genuinely cited its sources. A metric with+ no traceable upstream item is reported without a citation rather than+ pointing at something that isn't really there (#15).+- `intel_daily_digest`: a cited markdown morning brief composing top+ current events by domain, recent headlines, and, when the optional+ vector store is installed, recent activity trends and a 24-hour+ timeline. Every listed item carries a source reference. When the vector+ store isn't available, the Trends and Timeline sections say so via+ `data_gaps` instead of rendering as an empty, falsely-quiet section+ (#15).++### Fixed+- `_extract_metrics` (situation brief) read the earthquake event list under+ the key `events`, but `fetch_earthquakes` returns it under `earthquakes`,+ so the lookup always missed and `max_magnitude` was silently 0 in every+ brief ever generated. Found while wiring earthquake citations off the+ same field.+## 0.2.0 - 2026-08-16The honesty release. A full review of the data paths found five ways thediff --git a/CLAUDE.md b/CLAUDE.mdindex a0ec566..18c0c30 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co## What This Is-World Intelligence MCP Server — 113 tools across 30+ domains providing real-time global intelligence from free public APIs. Serves four interfaces: MCP stdio (for Claude Code/Cursor), a live Starlette dashboard with SSE, a Click CLI with Rich output, and a collector daemon for 24/7 vector store population. Python 3.11+, built with hatchling.+World Intelligence MCP Server: 114 tools across 30+ domains providing real-time global intelligence from free public APIs. Serves four interfaces: MCP stdio (for Claude Code/Cursor), a live Starlette dashboard with SSE, a Click CLI with Rich output, and a collector daemon for 24/7 vector store population. Python 3.11+, built with hatchling.## Commandsdiff --git a/README.md b/README.mdindex 2ada27c..1869acd 100644--- a/README.md+++ b/README.md@@ -6,7 +6,7 @@[](https://python.org)[](LICENSE)-Real-time global intelligence across **30+ domains** with **113 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs — no paid subscriptions required.+Real-time global intelligence across **30+ domains** with **114 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.Built for AI agents that need world awareness: market conditions, geopolitical risk, military posture, supply chain disruptions, cyber threats, and more — all queryable via the Model Context Protocol. The vector store enables natural language queries like *"military activity near Taiwan"* or *"cyber threats targeting healthcare"* across all historical data.@@ -56,8 +56,9 @@ Built for AI agents that need world awareness: market conditions, geopolitical r| **Vector Search** | 5 | Qdrant semantic search, similarity, timeline, stats || **Cross-Domain Analytics** | 3 | Correlation, domain summary, trend detection || **Reports** | 1 | PDF/HTML multi-domain intelligence reports |+| **Daily Digest** | 1 | Cited markdown morning brief: top events, headlines, trends, and timeline |-**Total: 113 tools** across 30+ intelligence domains.+**Total: 114 tools** across 30+ intelligence domains.---diff --git a/ROADMAP.md b/ROADMAP.mdindex d69aea1..5217bff 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -2,7 +2,7 @@**Benchmark**: [koala73/worldmonitor](https://github.com/koala73/worldmonitor)**Updated**: 2026-06-04-**Current tools**: 113 (112 intel + 1 status)+**Current tools**: 114 (113 intel + 1 status)---@@ -20,7 +20,7 @@| Area | Finding | Status | Action ||------|---------|--------|--------|-| MCP tool parity | 113 tools declared in `TOOLS`; 113 routed in `_dispatch()` | :white_check_mark: | Keep as an invariant |+| MCP tool parity | 114 tools declared in `TOOLS`; 114 routed in `_dispatch()` | :white_check_mark: | Keep as an invariant || Optional vector runtime | Missing `qdrant-client` / `fastembed` previously surfaced as runtime failures | :white_check_mark: Fixed | Vector features now degrade cleanly and report availability || Base-environment test run | `pytest -q` fails collection without dev extras because `respx` is not installed | :yellow_circle: | Run `pip install -e ".[dev]"` before full-suite validation || Core verification | 226 non-smoke tests pass with dev extras installed | :white_check_mark: | Full default `pytest` run |@@ -430,17 +430,31 @@ Added PDF/HTML intelligence report generation over the existing multi-domain datAdded retail fuel, residential natural gas, and electricity-rate tools to round out consumer energy monitoring alongside existing EIA crude, gas, FRED, and World Bank economic signals.+### Phase 19: Cited Situation Briefs + Daily Digest (+1 = 114 tools)+`intel_daily_digest`++The situation brief (used by the dashboard, not itself a separate tool) now+builds a numbered `sources` list while walking the overview data, and+carries an honest `cited` flag: true only when the returned text actually+references a real source number, so a brief where the model ignored the+citation instruction is distinguishable from one that didn't. The new+`intel_daily_digest` tool composes a cited markdown morning brief from+current events across several domains plus, when the optional vector+store is installed, recent trend detection and a timeline, degrading via+`data_gaps` rather than an empty section when the vector store isn't+available.+---## Summary| Category | Current | Notes ||----------|---------|-------|-| Total MCP tools | 113 | 112 intelligence tools + `intel_status` |-| Tool parity | 113 / 113 | `TOOLS` and `_dispatch()` are aligned |+| Total MCP tools | 114 | 113 intelligence tools + `intel_status` |+| Tool parity | 114 / 114 | `TOOLS` and `_dispatch()` are aligned || 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 | 244 | 226 non-smoke tests + 18 live smoke tests; full suite requires `.[dev]` || Primary remaining gap | Architecture | `server.py` monolith remains the main refactor target |-**Bottom line**: 113 tools across 30+ domains, with the roadmap now aligned to the live MCP registry. The main remaining gaps are full-environment test bootstrapping (`.[dev]`) and continued modularization of the monolithic `server.py` tool registry/dispatcher.+**Bottom line**: 114 tools across 30+ domains, with the roadmap now aligned to the live MCP registry. The main remaining gaps are full-environment test bootstrapping (`.[dev]`) and continued modularization of the monolithic `server.py` tool registry/dispatcher.diff --git a/src/world_intel_mcp/analysis/daily_digest.py b/src/world_intel_mcp/analysis/daily_digest.pynew file mode 100644index 0000000..7ba50de--- /dev/null+++ b/src/world_intel_mcp/analysis/daily_digest.py@@ -0,0 +1,278 @@+"""Daily intelligence digest: a cited markdown morning brief.++Composes a numbered-source markdown digest from current-event data across+several intelligence domains, plus (when the optional vector store is+installed) recent trend detection and a chronological timeline drawn from+accumulated history.++Follows the same citation discipline as the situation brief+(analysis/situation.py): every listed event carries a `[n]` reference into+a numbered `sources` list, and `cited` is only true when the markdown+actually contains a real one. When the vector store is unavailable, the+Trends and Timeline sections say so explicitly via `data_gaps` rather than+rendering empty sections that would read as a quiet day.+"""++from __future__ import annotations++import asyncio+import logging+from datetime import datetime, timezone++from .situation import _add_source, _cite, _has_valid_citation++logger = logging.getLogger("world-intel-mcp.analysis.daily_digest")++# Overview key -> (friendly label, domain used in _extract_metrics' sources)+_CURRENT_EVENT_DOMAINS = {+ "earthquakes": "Earthquakes",+ "military_flights": "Military aircraft",+ "wildfires": "Wildfires",+ "cyber_threats": "Cyber threats",+ "disease_outbreaks": "Disease outbreaks",+ "news_feed": "News",+ "space_weather": "Space weather",+ "domestic_flights": "Air traffic",+ "traffic_flow": "Traffic",+}+++async def _safe_fetch(coro, label: str) -> dict:+ try:+ result = await coro+ return result if isinstance(result, dict) else {}+ except Exception as exc:+ logger.warning("Daily digest: %s failed: %s", label, exc)+ return {"error": str(exc)}+++async def _fetch_current_events(fetcher) -> tuple[dict, list[str]]:+ """Fetch the same current-event domains the situation brief consumes.++ Returns a mini overview dict shaped like `_fetch_overview()`'s output+ (for reuse of `_extract_metrics`), plus a list of honest data_gaps for+ any domain that errored or returned nothing usable.+ """+ from ..sources import (+ seismology,+ military,+ conflict,+ wildfire,+ cyber,+ health,+ news,+ space_weather,+ aviation,+ traffic,+ )++ (+ earthquakes,+ military_flights,+ acled_events,+ ucdp_events,+ wildfires,+ cyber_threats,+ disease_outbreaks,+ news_feed,+ space_weather_data,+ domestic_flights,+ traffic_flow,+ ) = await asyncio.gather(+ _safe_fetch(seismology.fetch_earthquakes(fetcher), "earthquakes"),+ _safe_fetch(military.fetch_military_flights(fetcher), "military_flights"),+ _safe_fetch(conflict.fetch_acled_events(fetcher), "acled_events"),+ _safe_fetch(conflict.fetch_ucdp_events(fetcher), "ucdp_events"),+ _safe_fetch(wildfire.fetch_wildfires(fetcher), "wildfires"),+ _safe_fetch(cyber.fetch_cyber_threats(fetcher), "cyber_threats"),+ _safe_fetch(health.fetch_disease_outbreaks(fetcher), "disease_outbreaks"),+ _safe_fetch(news.fetch_news_feed(fetcher), "news_feed"),+ _safe_fetch(space_weather.fetch_space_weather(fetcher), "space_weather"),+ _safe_fetch(aviation.fetch_domestic_flights(fetcher), "domestic_flights"),+ _safe_fetch(traffic.fetch_traffic_flow(fetcher), "traffic_flow"),+ )++ mini_overview = {+ "earthquakes": earthquakes,+ "military_flights": military_flights,+ "acled_events": acled_events,+ "ucdp_events": ucdp_events,+ "wildfires": wildfires,+ "cyber_threats": cyber_threats,+ "disease_outbreaks": disease_outbreaks,+ "news_feed": news_feed,+ "space_weather": space_weather_data,+ "domestic_flights": domestic_flights,+ "traffic_flow": traffic_flow,+ }++ domain_gaps: list[str] = []+ for key, label in _CURRENT_EVENT_DOMAINS.items():+ payload = mini_overview.get(key)+ if not isinstance(payload, dict) or payload.get("error"):+ reason = (+ payload.get("error")+ if isinstance(payload, dict)+ else "no data returned"+ )+ domain_gaps.append(f"{label}: {reason or 'unavailable'}")++ # Conflict is a fallback pair (ACLED, then UCDP): only a gap if both failed.+ acled_ok = isinstance(acled_events, dict) and not acled_events.get("error")+ ucdp_ok = isinstance(ucdp_events, dict) and not ucdp_events.get("error")+ if not acled_ok and not ucdp_ok:+ acled_reason = (+ acled_events.get("error") if isinstance(acled_events, dict) else "no data"+ )+ domain_gaps.append(f"Conflict events: {acled_reason or 'unavailable'}")++ return mini_overview, domain_gaps+++def _render_events_and_headlines(sources: list[dict]) -> tuple[list[str], list[str]]:+ """Split the sources produced so far into 'current event' bullets and+ 'headline' bullets, each carrying its own [n]."""+ events_md = []+ headlines_md = []+ for s in sources:+ if s["domain"] == "news":+ url_suffix = f" ({s['url']})" if s.get("url") else ""+ headlines_md.append(f"- [{s['n']}] {s['description']}{url_suffix}")+ else:+ label = s["domain"].replace("_", " ").title()+ events_md.append(f"- **{label}** [{s['n']}]: {s['description']}")+ return events_md, headlines_md+++async def fetch_daily_digest(fetcher, vector_store=None) -> dict:+ """Compose a cited markdown morning brief.++ Args:+ fetcher: Shared HTTP fetcher with caching and circuit breaking.+ vector_store: Optional VectorStore instance. When None (Qdrant /+ FastEmbed not installed, or the caller has none configured),+ the Trends and Timeline sections are honestly omitted via+ `data_gaps` instead of rendered empty.++ Returns:+ Dict with `markdown`, `sources`, `cited`, `data_gaps`,+ `vector_store_available`, `source`, and `timestamp`.+ """+ from .situation import _extract_metrics++ now = datetime.now(timezone.utc)+ data_gaps: list[str] = []++ mini_overview, domain_gaps = await _fetch_current_events(fetcher)+ data_gaps.extend(domain_gaps)++ _metrics, sources, _citations = _extract_metrics(mini_overview)+ events_md, headlines_md = _render_events_and_headlines(sources)++ vector_store_available = vector_store is not None+ trend_result: dict = {}+ timeline_result: dict = {}++ if vector_store_available:+ trend_result, timeline_result = await asyncio.gather(+ _safe_fetch(+ vector_store.trend_detection(recent_hours=6.0, baseline_hours=48.0),+ "trend_detection",+ ),+ _safe_fetch(vector_store.timeline(hours=24.0, limit=15), "timeline"),+ )+ else:+ data_gaps.append("vector store unavailable: trends and timeline omitted")++ # --- Trends section -----------------------------------------------+ if not vector_store_available:+ trends_section = "_Omitted: vector store unavailable._"+ elif trend_result.get("error"):+ data_gaps.append(f"trend detection unavailable: {trend_result['error']}")+ trends_section = f"_Unavailable: {trend_result['error']}._"+ elif not trend_result.get("trends"):+ trends_section = "_No trend data accumulated yet._"+ else:+ notable = [t for t in trend_result["trends"] if t.get("trend") != "NORMAL"]+ if not notable:+ trends_section = (+ "_No significant trend shifts in the last 6h vs. 48h baseline._"+ )+ else:+ lines = []+ for t in notable[:8]:+ n = _add_source(+ sources,+ "trends",+ f"{t['category']}: {t['trend']} ({t['change_pct']:+.1f}% vs. 48h baseline, "+ f"{t['recent_count']} recent / {t['baseline_count']} baseline)",+ )+ _cite(_citations, "trends", n)+ lines.append(+ f"- **{t['category']}** [{n}]: {t['trend']} "+ f"({t['change_pct']:+.1f}% vs. baseline)"+ )+ trends_section = "\n".join(lines)++ # --- Timeline section ------------------------------------------------+ if not vector_store_available:+ timeline_section = "_Omitted: vector store unavailable._"+ elif timeline_result.get("error"):+ data_gaps.append(f"timeline unavailable: {timeline_result['error']}")+ timeline_section = f"_Unavailable: {timeline_result['error']}._"+ elif not timeline_result.get("entries"):+ timeline_section = "_No timeline entries in the last 24h._"+ else:+ lines = []+ for entry in timeline_result["entries"][:10]:+ desc = (entry.get("text") or f"{entry.get('category', 'update')}").strip()[+ :200+ ]+ n = _add_source(+ sources,+ "timeline",+ desc,+ timestamp=entry.get("datetime"),+ )+ _cite(_citations, "timeline", n)+ lines.append(f"- [{n}] ({entry.get('category', 'unknown')}) {desc[:160]}")+ timeline_section = "\n".join(lines)++ # --- Compose markdown --------------------------------------------------+ md_parts = [f"# Daily Intelligence Digest ({now.strftime('%Y-%m-%d')})", ""]++ md_parts.append("## Top Events by Domain")+ md_parts.append(+ "\n".join(events_md) if events_md else "_No current-event data available._"+ )+ md_parts.append("")++ if headlines_md:+ md_parts.append("## Headlines")+ md_parts.append("\n".join(headlines_md))+ md_parts.append("")++ md_parts.append("## Trends (6h vs. 48h baseline)")+ md_parts.append(trends_section)+ md_parts.append("")++ md_parts.append("## Timeline (last 24h)")+ md_parts.append(timeline_section)++ if data_gaps:+ md_parts.append("")+ md_parts.append("## Data Gaps")+ md_parts.extend(f"- {gap}" for gap in data_gaps)++ markdown = "\n".join(md_parts)+ cited = _has_valid_citation(markdown, len(sources))++ return {+ "markdown": markdown,+ "sources": sources,+ "cited": cited,+ "data_gaps": data_gaps,+ "vector_store_available": vector_store_available,+ "source": "daily-digest",+ "timestamp": now.isoformat(),+ }diff --git a/src/world_intel_mcp/analysis/situation.py b/src/world_intel_mcp/analysis/situation.pyindex 814c14b..6a17975 100644--- a/src/world_intel_mcp/analysis/situation.py+++ b/src/world_intel_mcp/analysis/situation.py@@ -3,70 +3,325 @@Generates a real-time intelligence brief from all dashboard datausing a local Ollama LLM. Falls back to a structured metrics summarywhen the LLM is unavailable.++Every brief carries a numbered ``sources`` list built from the same+overview data it summarizes, and a ``cited`` flag that is only true when+the returned text actually contains at least one ``[n]`` reference to a+real entry in that list. A metric with no traceable upstream item is+reported without a citation rather than pointing at something that+isn't really there."""import loggingimport os+import refrom datetime import datetime, timezoneimport httpxlogger = logging.getLogger("world-intel-mcp.analysis.situation")+_CITATION_RE = re.compile(r"\[(\d+)\]")++# Overview key -> short citable domain label. Kept distinct from the+# dict key so labels stay stable even when the underlying key varies+# (conflict data comes from whichever of acled/conflict_zones/ucdp is+# actually populated).+_CONFLICT_FEED_LABELS = {+ "acled_events": "ACLED",+ "conflict_zones": "hotspot fallback",+ "ucdp_events": "UCDP",+}+def _utc_now_iso() -> str:return datetime.now(timezone.utc).isoformat()-def _extract_metrics(data: dict) -> dict:- """Pull key numbers from the full overview data."""+def _add_source(+ sources: list[dict],+ domain: str,+ description: str,+ url: str | None = None,+ timestamp: str | None = None,+) -> int:+ """Append a numbered, traceable source and return its citation number."""+ n = len(sources) + 1+ entry: dict = {"n": n, "domain": domain, "description": description}+ if url:+ entry["url"] = url+ if timestamp:+ entry["timestamp"] = timestamp+ sources.append(entry)+ return n+++def _cite(citations: dict[str, list[int]], key: str, n: int) -> None:+ citations.setdefault(key, []).append(n)+++def _citation_suffix(citations: dict[str, list[int]], *keys: str) -> str:+ """Format the trailing ``[n][n]`` markers for a fallback-brief line+ from the metric keys it reports on. Empty when none of those keys+ produced a source: an uncited line is the honest outcome, not a+ bug, for a metric with nothing traceable behind it."""+ ns: list[int] = []+ for key in keys:+ for n in citations.get(key, []):+ if n not in ns:+ ns.append(n)+ ns.sort()+ return "".join(f"[{n}]" for n in ns)+++def _has_valid_citation(text: str, source_count: int) -> bool:+ """True only if `text` contains at least one [n] whose n is a real+ source number. A hallucinated or out-of-range [n] does not count:+ that is the model ignoring the citation instruction, not honoring it."""+ if source_count <= 0:+ return False+ for match in _CITATION_RE.finditer(text):+ n = int(match.group(1))+ if 1 <= n <= source_count:+ return True+ return False+++def _extract_metrics(data: dict) -> tuple[dict, list[dict], dict[str, list[int]]]:+ """Pull key numbers from the full overview data.++ Alongside the metrics dict, builds a numbered `sources` list and a+ `citations` map (metric key -> source numbers) covering every metric+ that has an identifiable upstream item behind it. Metrics computed+ from missing, errored, or empty domain data get no source entry and+ no citation.+ """+ sources: list[dict] = []+ citations: dict[str, list[int]] = {}+eq = data.get("earthquakes", {})quakes = eq.get("count", 0) if isinstance(eq, dict) else 0- eq_events = eq.get("events", []) if isinstance(eq, dict) else []- max_mag = max((e.get("magnitude", 0) for e in eq_events), default=0) if eq_events else 0+ # fetch_earthquakes() returns the event list under "earthquakes", not+ # "events": the latter key was never populated, so max_magnitude (and,+ # without this fix, every earthquake citation) was silently dead code.+ eq_events = eq.get("earthquakes", []) if isinstance(eq, dict) else []+ max_mag = (+ max((e.get("magnitude", 0) for e in eq_events), default=0) if eq_events else 0+ )+ if eq_events:+ top_quake = max(eq_events, key=lambda e: e.get("magnitude") or 0)+ n = _add_source(+ sources,+ "earthquakes",+ f"M{top_quake.get('magnitude')} earthquake, {top_quake.get('place') or 'unknown location'}",+ url=top_quake.get("url"),+ timestamp=top_quake.get("time"),+ )+ _cite(citations, "earthquakes", n)mil = data.get("military_flights", {})mil_count = mil.get("count", 0) if isinstance(mil, dict) else 0-- conflict_src = data.get("acled_events") or data.get("conflict_zones") or data.get("ucdp_events") or {}- conflict_count = conflict_src.get("count", 0) if isinstance(conflict_src, dict) else 0+ if isinstance(mil, dict) and mil and not mil.get("error"):+ n = _add_source(+ sources,+ "military",+ f"{mil_count} military aircraft currently tracked",+ timestamp=mil.get("timestamp"),+ )+ _cite(citations, "military_aircraft", n)++ conflict_domain = None+ for key in ("acled_events", "conflict_zones", "ucdp_events"):+ if data.get(key):+ conflict_domain = key+ break+ conflict_src = data.get(conflict_domain, {}) if conflict_domain else {}+ conflict_count = (+ conflict_src.get("count", 0) if isinstance(conflict_src, dict) else 0+ )+ if (+ conflict_domain+ and isinstance(conflict_src, dict)+ and not conflict_src.get("error")+ ):+ conflict_events = conflict_src.get("events", [])+ feed_label = _CONFLICT_FEED_LABELS.get(conflict_domain, conflict_domain)+ if conflict_events:+ top_event = conflict_events[0]+ loc = (+ top_event.get("location")+ or top_event.get("admin1")+ or top_event.get("country")+ or "unspecified location"+ )+ event_type = top_event.get("event_type") or "conflict event"+ n = _add_source(+ sources,+ "conflict",+ f"{event_type}, {loc} ({feed_label})",+ timestamp=top_event.get("event_date"),+ )+ _cite(citations, "conflicts", n)+ elif conflict_count:+ n = _add_source(+ sources,+ "conflict",+ f"{conflict_count} conflict events tracked ({feed_label})",+ )+ _cite(citations, "conflicts", n)fires = data.get("wildfires", {})fire_regions = fires.get("fires_by_region", {}) if isinstance(fires, dict) else {}fire_clusters = sum(- len(r.get("top_clusters", [])) for r in fire_regions.values() if isinstance(r, dict)+ len(r.get("top_clusters", []))+ for r in fire_regions.values()+ if isinstance(r, dict))+ if fire_regions:+ top_region, top_count = max(+ (+ (name, len(r.get("top_clusters", [])) if isinstance(r, dict) else 0)+ for name, r in fire_regions.items()+ ),+ key=lambda pair: pair[1],+ default=(None, 0),+ )+ if top_region and top_count:+ n = _add_source(+ sources,+ "wildfires",+ f"{top_count} active fire clusters in {top_region}",+ )+ _cite(citations, "fire_clusters", n)cyber = data.get("cyber_threats", {})- cyber_count = len(cyber.get("threats", [])) if isinstance(cyber, dict) else 0+ cyber_threats_list = cyber.get("threats", []) if isinstance(cyber, dict) else []+ cyber_count = len(cyber_threats_list)+ if cyber_threats_list:+ top_threat = cyber_threats_list[0]+ threat_label = (+ top_threat.get("threat") or top_threat.get("type") or "cyber threat"+ )+ indicator = top_threat.get("indicator") or ""+ severity = top_threat.get("severity") or "unknown"+ label = f"{threat_label}, {indicator}" if indicator else threat_label+ desc = f"{label} ({severity} severity)"+ n = _add_source(+ sources,+ "cyber",+ desc,+ timestamp=top_threat.get("first_seen") or None,+ )+ _cite(citations, "cyber_threats", n)posture = data.get("strategic_posture", {})- posture_score = posture.get("composite_score", 0) if isinstance(posture, dict) else 0- risk_level = posture.get("risk_level", "unknown") if isinstance(posture, dict) else "unknown"+ posture_score = (+ posture.get("composite_score", 0) if isinstance(posture, dict) else 0+ )+ risk_level = (+ posture.get("risk_level", "unknown") if isinstance(posture, dict) else "unknown"+ )+ if isinstance(posture, dict) and posture and not posture.get("error"):+ n = _add_source(+ sources,+ "posture",+ f"Composite risk score {posture_score}/100 ({risk_level})",+ timestamp=posture.get("timestamp"),+ )+ _cite(citations, "posture", n)alerts = data.get("alert_digest", {})alert_count = alerts.get("alert_count", 0) if isinstance(alerts, dict) else 0+ if isinstance(alerts, dict) and alerts and not alerts.get("error"):+ alert_items = alerts.get("alerts") or []+ if alert_items:+ top_alert = alert_items[0]+ desc = top_alert.get("message") or f"{alert_count} active alerts"+ n = _add_source(sources, "alerts", desc, timestamp=alerts.get("timestamp"))+ _cite(citations, "alerts", n)+ elif alert_count:+ n = _add_source(+ sources,+ "alerts",+ f"{alert_count} active alerts across monitored domains",+ timestamp=alerts.get("timestamp"),+ )+ _cite(citations, "alerts", n)space = data.get("space_weather", {})kp = space.get("current_kp", 0) if isinstance(space, dict) else 0+ if isinstance(space, dict) and space.get("current_kp") is not None:+ n = _add_source(+ sources,+ "space_weather",+ f"Kp index {round(kp, 1)}",+ timestamp=space.get("timestamp"),+ )+ _cite(citations, "kp_index", n)health = data.get("disease_outbreaks", {})outbreaks = health.get("high_concern_count", 0) if isinstance(health, dict) else 0+ if isinstance(health, dict) and health and not health.get("error"):+ high_concern_items = [+ item+ for item in (health.get("items") or [])+ if isinstance(item, dict) and item.get("is_high_concern")+ ]+ if high_concern_items:+ top = high_concern_items[0]+ n = _add_source(+ sources,+ "health",+ top.get("title") or "disease outbreak alert",+ url=top.get("link"),+ timestamp=top.get("published"),+ )+ _cite(citations, "outbreaks", n)news = data.get("news_feed", {})headlines = []if isinstance(news, dict):for item in (news.get("items") or news.get("articles") or [])[:5]:if isinstance(item, dict):- headlines.append(item.get("title", ""))+ title = item.get("title", "")+ headlines.append(title)+ if title:+ n = _add_source(+ sources,+ "news",+ title,+ url=item.get("link") or item.get("url"),+ timestamp=item.get("published"),+ )+ _cite(citations, "headlines", n)domestic = data.get("domestic_flights", {})- total_aircraft = domestic.get("total_aircraft", 0) if isinstance(domestic, dict) else 0+ total_aircraft = (+ domestic.get("total_aircraft", 0) if isinstance(domestic, dict) else 0+ )+ if isinstance(domestic, dict) and domestic and not domestic.get("error"):+ n = _add_source(+ sources,+ "aviation",+ f"{total_aircraft} aircraft airborne globally",+ timestamp=domestic.get("timestamp"),+ )+ _cite(citations, "total_aircraft", n)traffic = data.get("traffic_flow", {})- avg_congestion = traffic.get("global_avg_congestion", 0) if isinstance(traffic, dict) else 0-- return {+ avg_congestion = (+ traffic.get("global_avg_congestion", 0) if isinstance(traffic, dict) else 0+ )+ if isinstance(traffic, dict) and traffic and not traffic.get("error"):+ n = _add_source(+ sources,+ "traffic",+ f"{avg_congestion}% average city congestion",+ timestamp=traffic.get("timestamp"),+ )+ _cite(citations, "avg_congestion", n)++ metrics = {"earthquakes": quakes,"max_magnitude": round(max_mag, 1),"military_aircraft": mil_count,@@ -82,44 +337,64 @@ def _extract_metrics(data: dict) -> dict:"avg_congestion": avg_congestion,"top_headlines": headlines,}+ return metrics, sources, citations-def _build_prompt(m: dict) -> str:- """Build an LLM prompt from extracted metrics."""- headline_block = "\n".join(f" - {h}" for h in m["top_headlines"]) if m["top_headlines"] else " (no headlines available)"+def _build_prompt(m: dict, sources: list[dict]) -> str:+ """Build an LLM prompt from extracted metrics and the source list."""+ headline_block = (+ "\n".join(f" - {h}" for h in m["top_headlines"])+ if m["top_headlines"]+ else " (no headlines available)"+ )+ source_block = (+ "\n".join(f" [{s['n']}] ({s['domain']}) {s['description']}" for s in sources)+ if sources+ else " (no numbered sources available, do not invent citation numbers)"+ )return f"""You are a senior intelligence analyst. Generate a concise 3-paragraph situational awareness brief based on these real-time metrics:-THREAT POSTURE: Score {m['posture_score']}/100 ({m['risk_level']}), {m['alerts']} active alerts-MILITARY: {m['military_aircraft']} tracked aircraft-CONFLICT: {m['conflicts']} active events-SEISMIC: {m['earthquakes']} earthquakes (max M{m['max_magnitude']})-FIRES: {m['fire_clusters']} active fire clusters-CYBER: {m['cyber_threats']} tracked IOCs-SPACE WEATHER: Kp {m['kp_index']}-HEALTH: {m['outbreaks']} high-concern outbreaks-AIR TRAFFIC: {m['total_aircraft']} aircraft airborne-TRAFFIC: {m['avg_congestion']}% avg city congestion+THREAT POSTURE: Score {m["posture_score"]}/100 ({m["risk_level"]}), {m["alerts"]} active alerts+MILITARY: {m["military_aircraft"]} tracked aircraft+CONFLICT: {m["conflicts"]} active events+SEISMIC: {m["earthquakes"]} earthquakes (max M{m["max_magnitude"]})+FIRES: {m["fire_clusters"]} active fire clusters+CYBER: {m["cyber_threats"]} tracked IOCs+SPACE WEATHER: Kp {m["kp_index"]}+HEALTH: {m["outbreaks"]} high-concern outbreaks+AIR TRAFFIC: {m["total_aircraft"]} aircraft airborne+TRAFFIC: {m["avg_congestion"]}% avg city congestionTOP HEADLINES:{headline_block}+NUMBERED SOURCES (cite claims inline as [n], using ONLY the numbers below; never invent a source or cite a number that is not listed here):+{source_block}+Write exactly 3 paragraphs:1. Overall threat assessment and most significant developments2. Regional hotspots and emerging patterns3. Recommended watch items for the next 12 hours-Be specific, cite numbers. No preamble."""+Be specific, cite numbers. Cite every factual claim inline as [n] referencing the source list above. No preamble."""-def _fallback_brief(m: dict) -> str:- """Generate a structured summary without LLM."""+def _fallback_brief(m: dict, citations: dict[str, list[int]]) -> str:+ """Generate a structured summary without LLM, cited mechanically:+ each line is assembled per-metric, so it carries exactly the+ citations backing the numbers on that line, no more and no less."""lines = [- f"THREAT POSTURE: {m['risk_level'].upper()} (score {m['posture_score']}/100) with {m['alerts']} active alerts.",- f"MILITARY: {m['military_aircraft']} aircraft tracked. CONFLICT: {m['conflicts']} active events.",- f"SEISMIC: {m['earthquakes']} earthquakes (max M{m['max_magnitude']}). FIRES: {m['fire_clusters']} clusters.",- f"CYBER: {m['cyber_threats']} IOCs. HEALTH: {m['outbreaks']} high-concern outbreaks.",- f"SPACE: Kp {m['kp_index']}. AIR TRAFFIC: {m['total_aircraft']} airborne. CONGESTION: {m['avg_congestion']}%.",+ f"THREAT POSTURE: {m['risk_level'].upper()} (score {m['posture_score']}/100) with {m['alerts']} active alerts."+ f"{_citation_suffix(citations, 'posture', 'alerts')}",+ f"MILITARY: {m['military_aircraft']} aircraft tracked. CONFLICT: {m['conflicts']} active events."+ f"{_citation_suffix(citations, 'military_aircraft', 'conflicts')}",+ f"SEISMIC: {m['earthquakes']} earthquakes (max M{m['max_magnitude']}). FIRES: {m['fire_clusters']} clusters."+ f"{_citation_suffix(citations, 'earthquakes', 'fire_clusters')}",+ f"CYBER: {m['cyber_threats']} IOCs. HEALTH: {m['outbreaks']} high-concern outbreaks."+ f"{_citation_suffix(citations, 'cyber_threats', 'outbreaks')}",+ f"SPACE: Kp {m['kp_index']}. AIR TRAFFIC: {m['total_aircraft']} airborne. CONGESTION: {m['avg_congestion']}%."+ f"{_citation_suffix(citations, 'kp_index', 'total_aircraft', 'avg_congestion')}",]return "\n".join(lines)@@ -135,10 +410,13 @@ async def fetch_situation_brief(overview_data: dict) -> dict:overview_data: Full dashboard overview dict from _fetch_overview().Returns:- Dict with brief text, generation metadata, and key metrics.+ Dict with brief text, generation metadata, key metrics, a numbered+ `sources` list traceable back to overview_data, and a `cited` flag+ that is true only when the brief text actually references one of+ those sources."""- metrics = _extract_metrics(overview_data)- prompt = _build_prompt(metrics)+ metrics, sources, citations = _extract_metrics(overview_data)+ prompt = _build_prompt(metrics, sources)ollama_url = os.environ.get("OLLAMA_API_URL", "http://localhost:11434")model = os.environ.get("OLLAMA_MODEL", "llama3.2")@@ -168,13 +446,17 @@ async def fetch_situation_brief(overview_data: dict) -> dict:logger.debug("Ollama unavailable for situation brief: %s", exc)if not brief_text:- brief_text = _fallback_brief(metrics)+ brief_text = _fallback_brief(metrics, citations)++ cited = _has_valid_citation(brief_text, len(sources))return {"brief": brief_text,"ai_generated": ai_generated,"model": used_model,"metrics_snapshot": metrics,+ "sources": sources,+ "cited": cited,"source": "situation-brief","timestamp": _utc_now_iso(),}diff --git a/src/world_intel_mcp/server.py b/src/world_intel_mcp/server.pyindex 4e169e7..9a7af7a 100644--- a/src/world_intel_mcp/server.py+++ b/src/world_intel_mcp/server.py@@ -34,6 +34,10 @@ Phase 18: PDF/HTML intelligence reports (+1 = 110 tools). WeasyPrint-based multireport generation covering 18 intelligence domains in parallel.Phase 19: Consumer energy signals (+3 = 113 tools). Retail fuel, residential natural gas,and electricity rates round out consumer energy monitoring.+Phase 20: Cited situation briefs and intel_daily_digest (+1 = 114 tools). Situation briefs+ now carry a numbered sources list and an honest cited flag; the new digest tool+ composes a cited markdown morning brief, degrading via data_gaps when the vector+ store is unavailable."""import asyncio@@ -1731,6 +1735,12 @@ TOOLS: list[Tool] = [},},),+ # --- Daily Digest (1 tool) ---+ Tool(+ name="intel_daily_digest",+ description="Cited markdown morning brief: top current events by domain (earthquakes, military, conflict, wildfires, cyber, health, air/traffic), recent headlines, and, when the optional vector store is installed, recent activity trends and a 24h timeline. Every listed item carries a [n] citation into a numbered sources list. Degrades honestly via data_gaps when the vector store or a domain fetch is unavailable, instead of showing an empty section as a quiet day.",+ inputSchema={"type": "object", "properties": {}},+ ),# --- Reports (1 tool) ---Tool(name="intel_generate_report",@@ -2425,6 +2435,12 @@ async def _dispatch(name: str, arguments: dict[str, Any]) -> Any:baseline_hours=arguments.get("baseline_hours", 48.0),)+ # Daily Digest+ case "intel_daily_digest":+ from .analysis.daily_digest import fetch_daily_digest++ return await fetch_daily_digest(fetcher, vector_store=_vector_store)+# System# Reportscase "intel_generate_report":diff --git a/src/world_intel_mcp/tests/test_daily_digest.py b/src/world_intel_mcp/tests/test_daily_digest.pynew file mode 100644index 0000000..8ad42b1--- /dev/null+++ b/src/world_intel_mcp/tests/test_daily_digest.py@@ -0,0 +1,287 @@+"""Tests for analysis/daily_digest.py and the intel_daily_digest tool (issue #15).++Mocks at the source-function boundary (monkeypatch), matching the pattern+used in test_intelligence.py, since daily_digest composes existing+`sources/*.py` fetch functions rather than making HTTP calls itself.+"""++import re+from pathlib import Path++import pytest++from world_intel_mcp.analysis.daily_digest import fetch_daily_digest+from world_intel_mcp.sources import (+ aviation,+ conflict,+ cyber,+ health,+ military,+ news,+ seismology,+ space_weather,+ traffic,+ wildfire,+)++_SERVER_PY = Path(__file__).resolve().parents[1] / "server.py"+++class _FakeVectorStore:+ def __init__(self, trend_result: dict, timeline_result: dict) -> None:+ self._trend_result = trend_result+ self._timeline_result = timeline_result++ async def trend_detection(+ self, category=None, recent_hours=6.0, baseline_hours=48.0+ ) -> dict:+ return self._trend_result++ async def timeline(self, domain=None, category=None, hours=24.0, limit=50) -> dict:+ return self._timeline_result+++async def _fake_earthquakes(fetcher):+ return {+ "earthquakes": [+ {+ "id": "us1",+ "magnitude": 6.1,+ "place": "5km E of Nowhere",+ "time": "2026-08-16T01:00:00Z",+ "url": "https://earthquake.usgs.gov/us1",+ },+ ],+ "count": 1,+ "source": "usgs",+ }+++async def _fake_military(fetcher):+ return {+ "aircraft": [],+ "count": 4,+ "source": "adsb.lol",+ "timestamp": "2026-08-16T00:00:00Z",+ }+++async def _fake_acled(fetcher, **kwargs):+ return {+ "events": [+ {+ "event_type": "Battle",+ "location": "Somewhere",+ "event_date": "2026-08-15",+ }+ ],+ "count": 1,+ "source": "acled",+ }+++async def _fake_ucdp(fetcher, **kwargs):+ return {"events": [], "count": 0, "source": "ucdp"}+++async def _fake_wildfires(fetcher):+ return {+ "fires_by_region": {"california": {"count": 3, "top_clusters": [{}, {}, {}]}},+ "total_fires": 3,+ }+++async def _fake_cyber(fetcher):+ return {+ "threats": [+ {+ "type": "c2_ip",+ "indicator": "1.2.3.4",+ "threat": "Emotet",+ "severity": "critical",+ "first_seen": "2026-08-15",+ },+ ],+ "count": 1,+ }+++async def _fake_health(fetcher):+ return {+ "items": [+ {+ "title": "Outbreak of Z",+ "link": "https://who.int/z",+ "published": "2026-08-15",+ "is_high_concern": True,+ },+ ],+ "high_concern_count": 1,+ }+++async def _fake_news(fetcher):+ return {+ "items": [+ {+ "title": "Big headline",+ "link": "https://news.example/a",+ "published": "2026-08-16T00:00:00Z",+ },+ ],+ }+++async def _fake_space_weather(fetcher):+ return {"current_kp": 5.3, "timestamp": "2026-08-16T00:00:00Z"}+++async def _fake_domestic_flights(fetcher):+ return {"total_aircraft": 5000, "timestamp": "2026-08-16T00:00:00Z"}+++async def _fake_traffic_flow(fetcher):+ return {"global_avg_congestion": 33, "timestamp": "2026-08-16T00:00:00Z"}+++def _patch_all_domains(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(seismology, "fetch_earthquakes", _fake_earthquakes)+ monkeypatch.setattr(military, "fetch_military_flights", _fake_military)+ monkeypatch.setattr(conflict, "fetch_acled_events", _fake_acled)+ monkeypatch.setattr(conflict, "fetch_ucdp_events", _fake_ucdp)+ monkeypatch.setattr(wildfire, "fetch_wildfires", _fake_wildfires)+ monkeypatch.setattr(cyber, "fetch_cyber_threats", _fake_cyber)+ monkeypatch.setattr(health, "fetch_disease_outbreaks", _fake_health)+ monkeypatch.setattr(news, "fetch_news_feed", _fake_news)+ monkeypatch.setattr(space_weather, "fetch_space_weather", _fake_space_weather)+ monkeypatch.setattr(aviation, "fetch_domestic_flights", _fake_domestic_flights)+ monkeypatch.setattr(traffic, "fetch_traffic_flow", _fake_traffic_flow)+++async def test_digest_markdown_contains_citations_with_vector_store(+ fetcher, monkeypatch+) -> None:+ _patch_all_domains(monkeypatch)+ vs = _FakeVectorStore(+ trend_result={+ "trends": [+ {+ "category": "Conflict & Security",+ "recent_count": 10,+ "baseline_count": 2,+ "recent_rate_per_hr": 1.7,+ "baseline_rate_per_hr": 0.2,+ "change_pct": 750.0,+ "trend": "SURGE",+ },+ {+ "category": "Financial Markets",+ "recent_count": 4,+ "baseline_count": 4,+ "recent_rate_per_hr": 0.5,+ "baseline_rate_per_hr": 0.5,+ "change_pct": 0.0,+ "trend": "NORMAL",+ },+ ],+ "categories_analyzed": 2,+ "surges": 1,+ "drops": 0,+ },+ timeline_result={+ "entries": [+ {+ "domain": "acled",+ "category": "Conflict & Security",+ "text": "Battle reported near Somewhere",+ "datetime": "2026-08-16T00:10:00Z",+ "timestamp": 0,+ },+ ],+ "count": 1,+ "hours": 24,+ },+ )++ result = await fetch_daily_digest(fetcher, vector_store=vs)++ assert result["vector_store_available"] is True+ assert result["cited"] is True+ assert not any("vector store unavailable" in gap for gap in result["data_gaps"])++ md = result["markdown"]+ assert "## Trends" in md+ assert "SURGE" in md+ assert "NORMAL" not in md # only notable shifts are surfaced+ assert "## Timeline" in md+ assert "Battle reported near Somewhere" in md++ # Every [n] appearing in the markdown must be a real, existing source.+ found_ns = {int(n) for n in re.findall(r"\[(\d+)\]", md)}+ real_ns = {s["n"] for s in result["sources"]}+ assert found_ns, "expected at least one citation in the digest"+ assert found_ns <= real_ns, "digest cited a number with no matching source"+++async def test_digest_vector_degraded_path_returns_data_gaps(+ fetcher, monkeypatch+) -> None:+ """Primary tested path per the 0.2.0 conventions: no qdrant/fastembed+ installed means vector_store is None. The digest must say so honestly+ rather than rendering an empty Trends/Timeline section as a quiet day."""+ _patch_all_domains(monkeypatch)++ result = await fetch_daily_digest(fetcher, vector_store=None)++ assert result["vector_store_available"] is False+ assert (+ "vector store unavailable: trends and timeline omitted" in result["data_gaps"]+ )++ md = result["markdown"]+ assert (+ md.count("Omitted: vector store unavailable.") == 2+ ) # Trends + Timeline sections++ # Domain events still came through and are still cited; degradation+ # is scoped to the vector-store sections only.+ assert result["cited"] is True+ assert not any(s["domain"] in ("trends", "timeline") for s in result["sources"])+++async def test_digest_domain_failure_reports_gap_not_fabricated_event(+ fetcher, monkeypatch+) -> None:+ _patch_all_domains(monkeypatch)++ async def _broken_cyber(fetcher):+ return {"error": "CISA KEV unreachable"}++ monkeypatch.setattr(cyber, "fetch_cyber_threats", _broken_cyber)++ result = await fetch_daily_digest(fetcher, vector_store=None)++ assert any(+ "Cyber threats: CISA KEV unreachable" in gap for gap in result["data_gaps"]+ )+ assert not any(s["domain"] == "cyber" for s in result["sources"])+++def test_intel_daily_digest_registered_and_dispatched() -> None:+ """Structural parity check: the TOOLS/`_dispatch` 1:1 invariant this+ repo maintains (see ROADMAP.md 'MCP tool parity') must hold for the+ new tool. Reads server.py as text rather than importing the module,+ since importing `world_intel_mcp.server` has real side effects+ (opens a live Cache() at the default on-disk path) that no other+ test in this suite triggers."""+ text = _SERVER_PY.read_text()++ assert 'name="intel_daily_digest"' in text++ dispatch_idx = text.index('case "intel_daily_digest":')+ assert dispatch_idx > 0+ dispatch_body = text[dispatch_idx : dispatch_idx + 300]+ assert "fetch_daily_digest" in dispatch_bodydiff --git a/src/world_intel_mcp/tests/test_situation.py b/src/world_intel_mcp/tests/test_situation.pynew file mode 100644index 0000000..db75873--- /dev/null+++ b/src/world_intel_mcp/tests/test_situation.py@@ -0,0 +1,317 @@+"""Tests for analysis/situation.py: cited situation briefs (issue #15).++Uses respx to mock the Ollama endpoint, matching the network-edge-mocking+style used elsewhere in this suite (see test_sources.py, test_intelligence.py).+"""++import re++import httpx+import pytest+import respx++from world_intel_mcp.analysis.situation import _extract_metrics, fetch_situation_brief++_OLLAMA_GENERATE = "http://localhost:11434/api/generate"+++def _synthetic_overview() -> dict:+ """A synthetic overview shaped like the real per-domain fetch outputs+ (see the corresponding sources/*.py functions), covering every metric+ `_extract_metrics` reports on."""+ return {+ "earthquakes": {+ "earthquakes": [+ {+ "id": "us1",+ "magnitude": 4.1,+ "place": "10km SW of Testville",+ "time": "2026-08-16T01:00:00Z",+ "url": "https://earthquake.usgs.gov/us1",+ },+ {+ "id": "us2",+ "magnitude": 5.7,+ "place": "20km N of Sampleton",+ "time": "2026-08-16T02:00:00Z",+ "url": "https://earthquake.usgs.gov/us2",+ },+ ],+ "count": 2,+ "source": "usgs",+ },+ "military_flights": {+ "aircraft": [],+ "count": 3,+ "source": "adsb.lol",+ "timestamp": "2026-08-16T03:00:00Z",+ },+ "acled_events": {+ "events": [+ {+ "event_type": "Battle",+ "location": "Testcity",+ "country": "Testland",+ "event_date": "2026-08-15",+ },+ ],+ "count": 1,+ "source": "acled",+ },+ "wildfires": {+ "fires_by_region": {+ "california": {+ "count": 5,+ "top_clusters": [{"lat": 1, "lon": 2}, {"lat": 3, "lon": 4}],+ },+ },+ "total_fires": 5,+ },+ "cyber_threats": {+ "threats": [+ {+ "type": "c2_ip",+ "indicator": "1.2.3.4",+ "threat": "TrickBot",+ "severity": "critical",+ "first_seen": "2026-08-15",+ },+ ],+ "count": 1,+ },+ "strategic_posture": {+ "composite_score": 42,+ "risk_level": "moderate",+ "timestamp": "2026-08-16T03:00:00Z",+ },+ "alert_digest": {+ "alerts": [+ {+ "domain": "space",+ "priority": "high",+ "message": "Geomagnetic storm: Kp=6",+ },+ ],+ "alert_count": 1,+ "timestamp": "2026-08-16T03:00:00Z",+ },+ "space_weather": {"current_kp": 6.0, "timestamp": "2026-08-16T03:00:00Z"},+ "disease_outbreaks": {+ "items": [+ {+ "title": "Outbreak of X in Y",+ "link": "https://who.int/x",+ "published": "2026-08-15",+ "is_high_concern": True,+ },+ ],+ "high_concern_count": 1,+ },+ "news_feed": {+ "items": [+ {+ "title": "Headline One",+ "link": "https://news.example/1",+ "published": "2026-08-16T00:00:00Z",+ },+ {+ "title": "Headline Two",+ "link": "https://news.example/2",+ "published": "2026-08-16T00:30:00Z",+ },+ ],+ },+ "domestic_flights": {+ "total_aircraft": 1234,+ "timestamp": "2026-08-16T03:00:00Z",+ },+ "traffic_flow": {+ "global_avg_congestion": 27,+ "timestamp": "2026-08-16T03:00:00Z",+ },+ }+++# ---------------------------------------------------------------------------+# _extract_metrics: unit level, precise citation-map assertions+# ---------------------------------------------------------------------------+++def test_sources_populated_from_synthetic_overview() -> None:+ metrics, sources, citations = _extract_metrics(_synthetic_overview())++ assert len(sources) == 13 # 11 single-item domains + 2 news headlines+ # Numbered sequentially with no gaps or duplicates.+ assert [s["n"] for s in sources] == list(range(1, len(sources) + 1))++ domains = {s["domain"] for s in sources}+ assert domains == {+ "earthquakes",+ "military",+ "conflict",+ "wildfires",+ "cyber",+ "posture",+ "alerts",+ "space_weather",+ "health",+ "news",+ "aviation",+ "traffic",+ }++ eq_source = next(s for s in sources if s["domain"] == "earthquakes")+ assert (+ eq_source["url"] == "https://earthquake.usgs.gov/us2"+ ) # higher-magnitude quake+ assert "5.7" in eq_source["description"]+ assert eq_source["timestamp"] == "2026-08-16T02:00:00Z"++ news_sources = [s for s in sources if s["domain"] == "news"]+ assert len(news_sources) == 2+ assert news_sources[0]["url"] == "https://news.example/1"+ assert news_sources[0]["description"] == "Headline One"++ assert metrics["earthquakes"] == 2+ assert metrics["max_magnitude"] == 5.7+ assert citations["earthquakes"] == [eq_source["n"]]+ assert citations["headlines"] == [s["n"] for s in news_sources]+++def test_earthquake_count_without_events_produces_no_citation() -> None:+ """Issue #15: never fabricate a citation. A count with no underlying+ event list is not a traceable item, so it must not be cited even+ though the count itself is still reported."""+ overview = _synthetic_overview()+ overview["earthquakes"] = {"earthquakes": [], "count": 3, "source": "usgs"}++ metrics, sources, citations = _extract_metrics(overview)++ assert metrics["earthquakes"] == 3+ assert "earthquakes" not in citations+ assert not any(s["domain"] == "earthquakes" for s in sources)+++def test_errored_domain_produces_no_citation() -> None:+ """A domain that failed upstream (carries an `error` key) must not be+ cited even if some default count survives in the metrics dict."""+ overview = _synthetic_overview()+ overview["cyber_threats"] = {+ "error": "CISA KEV unreachable",+ "threats": [],+ "count": 0,+ }++ metrics, sources, citations = _extract_metrics(overview)++ assert "cyber_threats" not in citations+ assert not any(s["domain"] == "cyber" for s in sources)+++def test_empty_overview_produces_no_sources() -> None:+ metrics, sources, citations = _extract_metrics({})++ assert sources == []+ assert citations == {}+ assert metrics["earthquakes"] == 0+ assert metrics["risk_level"] == "unknown"+++# ---------------------------------------------------------------------------+# fetch_situation_brief: end to end, network edge mocked with respx+# ---------------------------------------------------------------------------+++async def test_fallback_brief_is_mechanically_cited() -> None:+ respx.post(_OLLAMA_GENERATE).mock(+ side_effect=httpx.ConnectError("no ollama in test env")+ )++ result = await fetch_situation_brief(_synthetic_overview())++ assert result["ai_generated"] is False+ assert result["model"] == "fallback"+ assert result["cited"] is True+ assert len(result["sources"]) == 13++ real_ns = {s["n"] for s in result["sources"]}+ found_ns = {int(n) for n in re.findall(r"\[(\d+)\]", result["brief"])}+ assert found_ns, "fallback brief carried no citations at all"+ assert found_ns <= real_ns, "fallback brief cited a number with no matching source"++ # Every line of the structured fallback is cited: it is assembled+ # per-metric and every metric here has a traceable source.+ for line in result["brief"].splitlines():+ assert re.search(r"\[\d+\]", line), f"fallback line not cited: {line!r}"+++async def test_cited_false_when_llm_ignores_citation_instructions() -> None:+ """The load-bearing honesty property: an LLM response that never+ references the source list must be reported as uncited, not silently+ trusted because the model *could* have cited something real."""+ respx.post(_OLLAMA_GENERATE).mock(+ return_value=httpx.Response(+ 200,+ json={"response": "Everything looks calm today, nothing much to report."},+ )+ )++ result = await fetch_situation_brief(_synthetic_overview())++ assert result["ai_generated"] is True+ assert result["sources"] # a real source list was offered to the model+ assert result["cited"] is False # but the model never used it+++async def test_cited_true_when_llm_uses_a_real_source_number() -> None:+ respx.post(_OLLAMA_GENERATE).mock(+ return_value=httpx.Response(+ 200,+ json={+ "response": "Seismic activity ticked up [1] while cyber indicators [5] held steady."+ },+ )+ )++ result = await fetch_situation_brief(_synthetic_overview())++ assert result["ai_generated"] is True+ assert result["cited"] is True+++async def test_out_of_range_citation_does_not_count_as_cited() -> None:+ """Citation numbers never exceed the sources list: a bracketed number+ that looks like a citation but doesn't match a real source must not+ be treated as the model honoring the citation instruction."""+ respx.post(_OLLAMA_GENERATE).mock(+ return_value=httpx.Response(+ 200,+ json={"response": "Everything is quiet [99], nothing to see [42]."},+ )+ )++ result = await fetch_situation_brief(_synthetic_overview())++ assert len(result["sources"]) == 13+ assert result["cited"] is False+++async def test_empty_overview_falls_back_uncited() -> None:+ respx.post(_OLLAMA_GENERATE).mock(+ side_effect=httpx.ConnectError("no ollama in test env")+ )++ result = await fetch_situation_brief({})++ assert result["sources"] == []+ assert result["cited"] is False