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
Dashboard AOI layer: draw geofences with last-sweep counts
Phoenix Agent (Marcs-Mac-Studio)e632395a3f0a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e1f1ffd..2d1bffe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,20 @@## Unreleased+### Added+- Dashboard AOI layer: a toggleable "AOI Geofences" Leaflet layer draws+ every defined area (circle, polygon, corridor) from the shared store,+ with a tooltip and detail panel showing what the last collector sweep+ counted inside it. Backed by a new `/api/aois` endpoint that reads+ the stored change snapshot and never gathers live, so drawing a shape+ costs nothing upstream. An AOI that has never been swept says so+ (`last_sweep: null`) instead of showing zeros; a broken store is a 503+ with the reason, never an empty map that reads as "no areas defined".+ Verified in headless Chromium: 2 shapes rendered, the 50 km circle at+ 50,000 m, no console errors. First endpoint tests for the dashboard+ (Starlette TestClient); a real SQLite thread-affinity error surfaced+ during them and was fixed by opening the store per request.+### Changed- AOI news is now scoped by where the area IS, not what it is named.Every other AOI domain was filtered geometrically; news alone was adiff --git a/CLAUDE.md b/CLAUDE.mdindex 3a1ed11..8edea33 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -61,7 +61,7 @@ collector.py (daemon) ──┘**Reports** (`reports.py`): PDF/HTML intelligence report generator. Collects 18 domains in parallel, renders styled HTML, converts to PDF via WeasyPrint. Optional dependency: `pip install -e ".[pdf]"`.-**Dashboard** (`dashboard/`): Self-contained Starlette app with a single `index.html` template (no frontend build step). SSE endpoint streams all domains in parallel via `asyncio.gather()`, refreshes every 30 seconds. Loads `.env` from project root on startup.+**Dashboard** (`dashboard/`): Self-contained Starlette app with a single `index.html` template (no frontend build step). SSE endpoint streams all domains in parallel via `asyncio.gather()`, refreshes every 30 seconds. Loads `.env` from project root on startup. `/api/aois` feeds the AOI geofence layer from the shared AOI store: it opens a fresh `AOIStore` per request (`_open_aoi_store`) because SQLite connections are thread-bound and the handler may run on a different thread than a cached store's creator; it reads stored sweep snapshots and never gathers live. Endpoint tests use Starlette's `TestClient` without the context manager so lifespan (default-path `Cache`) never runs.## Adding a New Tooldiff --git a/README.md b/README.mdindex 3bedea3..b92f7f8 100644--- a/README.md+++ b/README.md@@ -120,7 +120,7 @@ intel report -o brief.pdf # custom output pathintel report -s markets,cyber,earthquakes # select sections```-Map-first ops center: Leaflet map with toggle-able layers (quakes, military, conflict, fires, convergence, nuclear, infrastructure), 47 live SSE feeds, HUD bar, glassmorphic panels, per-source circuit breaker health.+Map-first ops center: Leaflet map with toggle-able layers (quakes, military, conflict, fires, convergence, nuclear, infrastructure, your AOI geofences with last-sweep counts), 47 live SSE feeds, HUD bar, glassmorphic panels, per-source circuit breaker health.### CLIdiff --git a/ROADMAP.md b/ROADMAP.mdindex a58ebe9..46912fe 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -533,7 +533,7 @@ Ordered by value; numbers are proposals, not commitments.| Escalation news + convergence components | `intel_aoi_escalation` reports null for news/convergence; wire GDELT name-mention counts and the existing convergence grid | :yellow_circle: || Geo-scoped news | AOI centre reverse-geocoded via OSM Nominatim (`sources/geocode.py`); GDELT searched for the settlement + county, e.g. `("Pittsburgh" OR "Allegheny County")`. Brief reports `news_scoping`; name-mention fallback is disclosed as a data gap. GDELT GEO 2.0 API was tried first and is 404 (both path variants, measured), so per-article coordinates are not available; the curated 105-city set could not do this either (nearest to Pittsburgh: Toronto, ~360 km) | :white_check_mark: Shipped (unreleased) || CLI parity | `intel aoi` group with all 9 subcommands, shared store semantics, live-smoked | :white_check_mark: Shipped in 0.8.0 |-| Dashboard AOI layer | Draw defined AOIs on the Leaflet map; show per-AOI counts | :red_circle: |+| Dashboard AOI layer | `/api/aois` + a toggleable "AOI Geofences" Leaflet layer: circles, polygons, and corridors drawn from the store, tooltip/detail with what the last collector sweep counted inside each. Reads the stored snapshot, never gathers live (a never-swept AOI says so instead of showing zeros; a broken store is a 503, not an empty map). Verified in headless Chromium: 2 shapes rendered, 50 km circle at 50,000 m, no console errors | :white_check_mark: Shipped (unreleased) || Scheduled AOI sweeps | `aoi_digest` is a collector source (`fetch_aoi_sweep`, 240 s budget): every daemon cycle advances all AOI snapshots, so `--daemon` + the launchd wrapper IS the schedule. Change digests land in the collector log and vector store | :white_check_mark: Shipped in 0.9.0 || AOI change notifications | `WORLD_INTEL_AOI_WEBHOOK` (+ `_FORMAT=json\|text`): the sweep POSTs non-quiet digests; quiet sweeps and dead sinks are honest `notification` records, never silent or fatal. Live-verified against a local sink. Email is out of scope (bring a webhook bridge) | :white_check_mark: Shipped in 0.9.0 |diff --git a/src/world_intel_mcp/dashboard/app.py b/src/world_intel_mcp/dashboard/app.pyindex f89f16f..d81be81 100644--- a/src/world_intel_mcp/dashboard/app.py+++ b/src/world_intel_mcp/dashboard/app.py@@ -19,6 +19,7 @@ from starlette.applications import Starlettefrom starlette.responses import HTMLResponse, JSONResponse, StreamingResponsefrom starlette.routing import Route+from world_intel_mcp.analysis.aoi import AOIStorefrom world_intel_mcp.cache import Cachefrom world_intel_mcp.circuit_breaker import CircuitBreakerfrom world_intel_mcp.fetcher import Fetcher@@ -101,6 +102,20 @@ def _ensure_fetcher() -> Fetcher:return _fetcher+def _open_aoi_store() -> AOIStore:+ """Open the AOI store on the same cache database the MCP server and+ CLI write geofences to, so the map shows exactly the areas a user+ defined over MCP.++ Opened per request and closed by the caller, never cached: SQLite+ connections are bound to the thread that created them, and a+ module-level store built on one thread and read from another (the+ test client's portal thread; any ``to_thread`` path) raises. A+ fresh connection per read is cheap and thread-safe by construction,+ the same pattern ``analysis.aoi.fetch_aoi_sweep`` uses."""+ return AOIStore(_ensure_fetcher().cache.db_path)++# ---------------------------------------------------------------------------# Data fetching# ---------------------------------------------------------------------------@@ -325,53 +340,84 @@ async def api_stream(request):"macro_signals": lambda: markets.fetch_macro_signals(fetcher),"sector_heatmap": lambda: markets.fetch_sector_heatmap(fetcher),"earthquakes": lambda: seismology.fetch_earthquakes(fetcher),- "military_flights": lambda: military.fetch_military_flights(fetcher),+ "military_flights": lambda: military.fetch_military_flights(+ fetcher+ ),"cyber_threats": lambda: cyber.fetch_cyber_threats(fetcher),"news_feed": lambda: news.fetch_news_feed(fetcher),"trending_keywords": lambda: news.fetch_trending_keywords(fetcher),"nav_warnings": lambda: maritime.fetch_nav_warnings(fetcher),- "internet_outages": lambda: infrastructure.fetch_internet_outages(fetcher),+ "internet_outages": lambda: infrastructure.fetch_internet_outages(+ fetcher+ ),"cable_health": lambda: infrastructure.fetch_cable_health(fetcher),"wildfires": lambda: wildfire.fetch_wildfires(fetcher),- "prediction_markets": lambda: prediction.fetch_prediction_markets(fetcher),+ "prediction_markets": lambda: prediction.fetch_prediction_markets(+ fetcher+ ),"airport_delays": lambda: aviation.fetch_airport_delays(fetcher),- "climate_anomalies": lambda: climate.fetch_climate_anomalies(fetcher),+ "climate_anomalies": lambda: climate.fetch_climate_anomalies(+ fetcher+ ),"energy_prices": lambda: economic.fetch_energy_prices(fetcher),"gas_prices": lambda: economic.fetch_gas_prices(fetcher),- "residential_natgas": lambda: economic.fetch_residential_natgas_prices(fetcher),- "electricity_rates": lambda: economic.fetch_electricity_rates(fetcher),- "stablecoin_status": lambda: markets.fetch_stablecoin_status(fetcher),+ "residential_natgas": lambda: economic.fetch_residential_natgas_prices(+ fetcher+ ),+ "electricity_rates": lambda: economic.fetch_electricity_rates(+ fetcher+ ),+ "stablecoin_status": lambda: markets.fetch_stablecoin_status(+ fetcher+ ),"etf_flows": lambda: markets.fetch_etf_flows(fetcher),"acled_events": lambda: conflict.fetch_acled_events(fetcher),"ucdp_events": lambda: conflict.fetch_ucdp_events(fetcher),- "displacement": lambda: displacement.fetch_displacement_summary(fetcher),+ "displacement": lambda: displacement.fetch_displacement_summary(+ fetcher+ ),"risk_scores": lambda: intelligence.fetch_risk_scores(fetcher),- "signal_convergence": lambda: intelligence.fetch_signal_convergence(fetcher),+ "signal_convergence": lambda: intelligence.fetch_signal_convergence(+ fetcher+ ),"space_weather": lambda: space_weather.fetch_space_weather(fetcher),"ai_watch": lambda: ai_watch.fetch_ai_watch(fetcher),- "disease_outbreaks": lambda: health.fetch_disease_outbreaks(fetcher),- "election_calendar": lambda: elections.fetch_election_calendar(fetcher),+ "disease_outbreaks": lambda: health.fetch_disease_outbreaks(+ fetcher+ ),+ "election_calendar": lambda: elections.fetch_election_calendar(+ fetcher+ ),"shipping_index": lambda: shipping.fetch_shipping_index(fetcher),"social_signals": lambda: social.fetch_social_signals(fetcher),"nuclear_monitor": lambda: nuclear.fetch_nuclear_monitor(fetcher),"alert_digest": lambda: fetch_alert_digest(fetcher),"weekly_trends": lambda: fetch_weekly_trends(fetcher),- "service_status": lambda: service_status.fetch_service_status(fetcher),+ "service_status": lambda: service_status.fetch_service_status(+ fetcher+ ),"strategic_posture": lambda: fetch_strategic_posture(fetcher),"fleet_report": lambda: fetch_fleet_report(fetcher),"usni_fleet": lambda: fetch_usni_fleet(fetcher),"population_exposure": lambda: fetch_population_exposure(fetcher),- "domestic_flights": lambda: aviation.fetch_domestic_flights(fetcher),+ "domestic_flights": lambda: aviation.fetch_domestic_flights(+ fetcher+ ),"traffic_flow": lambda: traffic.fetch_traffic_flow(fetcher),- "traffic_incidents": lambda: traffic.fetch_traffic_incidents(fetcher),+ "traffic_incidents": lambda: traffic.fetch_traffic_incidents(+ fetcher+ ),"webcams": lambda: webcams.fetch_webcams(fetcher),"btc_technicals": lambda: markets.fetch_btc_technicals(fetcher),"central_bank_rates": lambda: fetch_central_bank_rates(fetcher),}_SLOW = {- "news_feed", "trending_keywords", "alert_digest",- "weekly_trends", "strategic_posture",+ "news_feed",+ "trending_keywords",+ "alert_digest",+ "weekly_trends",+ "strategic_posture",}results_q: asyncio.Queue = asyncio.Queue()@@ -396,12 +442,19 @@ async def api_stream(request):# Yield each result as it arriveswhile completed < total:try:- name, data = await asyncio.wait_for(results_q.get(), timeout=120)+ name, data = await asyncio.wait_for(+ results_q.get(), timeout=120+ )except asyncio.TimeoutError:breakcompleted += 1payload = json.dumps(- {"_progressive": True, "_done": completed, "_total": total, name: data},+ {+ "_progressive": True,+ "_done": completed,+ "_total": total,+ name: data,+ },default=str,)yield f"data: {payload}\n\n"@@ -485,6 +538,49 @@ async def api_static(request):)+async def api_aois(request):+ """User-defined AOI geofences for the map layer, each with what the+ last collector sweep counted inside it.++ Reads the stored change snapshot rather than gathering live: drawing+ a shape must never cost the 60-90 s of upstream fetches a brief+ does. An AOI that has never been swept reports ``last_sweep: null``+ rather than a row of zeros, and a broken store is a 503 with the+ reason, never an empty list that reads as "no areas defined".+ """+ cors = {"Access-Control-Allow-Origin": "*"}+ try:+ store = _open_aoi_store()+ try:+ aois = []+ for row in store.list_all():+ snap = store.get_snapshot(row["name"])+ last_sweep = None+ if snap is not None:+ counts = {+ domain: len(items or {})+ for domain, items in (snap.get("domains") or {}).items()+ }+ last_sweep = {+ "taken_at": snap.get("taken_at"),+ "counts": counts,+ "total": sum(counts.values()),+ }+ aois.append({**row, "last_sweep": last_sweep})+ finally:+ store.close()+ except Exception as exc:+ logger.warning("AOI layer unavailable: %s", exc)+ return JSONResponse(+ {"error": f"AOI store unavailable: {exc}", "aois": [], "count": 0},+ status_code=503,+ headers=cors,+ )+ return JSONResponse(+ {"aois": aois, "count": len(aois), "source": "aoi-store"}, headers=cors+ )++async def api_health(request):"""Health check."""return JSONResponse({"status": "ok"})@@ -638,6 +734,7 @@ app = Starlette(Route("/api/overview", api_overview),Route("/api/stream", api_stream),Route("/api/static", api_static),+ Route("/api/aois", api_aois),Route("/api/health", api_health),Route("/api/report/pdf", api_report_pdf),Route("/sse/vector-analytics", sse_vector_analytics),diff --git a/src/world_intel_mcp/dashboard/index.html b/src/world_intel_mcp/dashboard/index.htmlindex 00da0ac..fc1377d 100644--- a/src/world_intel_mcp/dashboard/index.html+++ b/src/world_intel_mcp/dashboard/index.html@@ -742,6 +742,12 @@ a { color: var(--accent); text-decoration: none; }<span class="layer-count" id="cntNews">—</span><div class="toggle on" style="--lc:var(--accent)"><div class="knob"></div></div></div>+ <div class="layer-row" data-layer="aoi">+ <span class="layer-dot" style="background:#ff7f50"></span>+ <span class="layer-label">AOI Geofences</span>+ <span class="layer-count" id="cntAoi">—</span>+ <div class="toggle on" style="--lc:#ff7f50"><div class="knob"></div></div>+ </div><div style="border-top:1px solid rgba(255,255,255,0.08);margin-top:4px;padding-top:6px"><div style="font-size:0.55rem;letter-spacing:1px;color:rgba(255,255,255,0.35);margin-bottom:4px">REGION</div><div id="regionPresets" style="display:flex;flex-wrap:wrap;gap:2px">@@ -829,7 +835,7 @@ function _withinTimeWindow(ts) { if (!ts) return true; var age = Date.now() - nevar latestData = null;var map = null;var mapLayers = {};-var layerState = { quakes: true, military: true, conflict: true, fires: true, convergence: true, nuclear: true, infra: true, exposure: true, airtraffic: true, traffic: true, navwarnings: true, webcams: true, climate: true, news: true };+var layerState = { quakes: true, military: true, conflict: true, fires: true, convergence: true, nuclear: true, infra: true, exposure: true, airtraffic: true, traffic: true, navwarnings: true, webcams: true, climate: true, news: true, aoi: true };// Restore saved layer toggles from localStoragetry { var _saved = JSON.parse(localStorage.getItem('phoenix-layers')); if (_saved) { for (var _k in _saved) { if (layerState.hasOwnProperty(_k)) layerState[_k] = _saved[_k]; } } } catch(e) {}var drawerOpen = false;@@ -926,6 +932,7 @@ function initMap() {mapLayers.webcams = L.layerGroup().addTo(map);mapLayers.climate = L.layerGroup().addTo(map);mapLayers.news = L.markerClusterGroup(clusterOpts(null, 35)).addTo(map);+ mapLayers.aoi = L.layerGroup().addTo(map);}// ════════════ LAYER TOGGLES ════════════@@ -951,8 +958,8 @@ $('#drawerToggle').addEventListener('click', function() {});// ════════════ DETAIL MODAL ════════════-var COLORS = { earthquake: 'var(--red)', military: 'var(--blue)', conflict: 'var(--amber)', fire: 'var(--gold)', convergence: 'var(--purple)', nuclear: 'var(--green)', military_base: 'var(--teal)', port: 'var(--blue)', nuclear_facility: 'var(--gold)', pipeline: 'var(--purple)', exposure: '#e040fb', waterway: 'var(--accent)', cable: 'var(--blue)', airtraffic: '#00c8ff', traffic_city: '#e0e0e0', navwarn: '#ffc832', webcam: '#909090' };-var LABELS = { earthquake: 'EARTHQUAKE', military: 'MILITARY AIRCRAFT', conflict: 'CONFLICT EVENT', fire: 'WILDFIRE CLUSTER', convergence: 'SIGNAL CONVERGENCE', nuclear: 'NUCLEAR MONITOR', military_base: 'MILITARY BASE', port: 'STRATEGIC PORT', nuclear_facility: 'NUCLEAR FACILITY', pipeline: 'PIPELINE', exposure: 'POPULATION EXPOSURE', waterway: 'STRATEGIC WATERWAY', cable: 'CABLE CORRIDOR', airtraffic: 'AIRCRAFT', traffic_city: 'TRAFFIC CONGESTION', navwarn: 'NAVIGATION WARNING', webcam: 'WEBCAM' };+var COLORS = { earthquake: 'var(--red)', military: 'var(--blue)', conflict: 'var(--amber)', fire: 'var(--gold)', convergence: 'var(--purple)', nuclear: 'var(--green)', military_base: 'var(--teal)', port: 'var(--blue)', nuclear_facility: 'var(--gold)', pipeline: 'var(--purple)', exposure: '#e040fb', waterway: 'var(--accent)', cable: 'var(--blue)', airtraffic: '#00c8ff', traffic_city: '#e0e0e0', navwarn: '#ffc832', webcam: '#909090', aoi: '#ff7f50' };+var LABELS = { earthquake: 'EARTHQUAKE', military: 'MILITARY AIRCRAFT', conflict: 'CONFLICT EVENT', fire: 'WILDFIRE CLUSTER', convergence: 'SIGNAL CONVERGENCE', nuclear: 'NUCLEAR MONITOR', military_base: 'MILITARY BASE', port: 'STRATEGIC PORT', nuclear_facility: 'NUCLEAR FACILITY', pipeline: 'PIPELINE', exposure: 'POPULATION EXPOSURE', waterway: 'STRATEGIC WATERWAY', cable: 'CABLE CORRIDOR', airtraffic: 'AIRCRAFT', traffic_city: 'TRAFFIC CONGESTION', navwarn: 'NAVIGATION WARNING', webcam: 'WEBCAM', aoi: 'AOI GEOFENCE' };function showDetail(type, d) {var title = '', subtitle = '', fields = [], link = '';@@ -1324,6 +1331,18 @@ function showDrawerDetail(id) {['Issued', d.dtg || d.date || '\u2014'],['Text', d.text || d.description || '\u2014']];+ } else if (type === 'aoi') {+ title = d.name || 'AOI';+ var ak = d.kind || 'circle';+ subtitle = ak.toUpperCase() + (ak === 'circle' ? ' • ' + d.radius_km + ' km radius' : ak === 'corridor' && d.geometry ? ' • ' + d.geometry.width_km + ' km wide' : '');+ var ls = d.last_sweep;+ fields = [+ ['Name', d.name || '—'],+ ['Shape', ak],+ ['Center', (d.lat != null ? d.lat.toFixed(3) : '—') + ', ' + (d.lon != null ? d.lon.toFixed(3) : '—')],+ ['Last sweep', ls ? ago(ls.taken_at * 1000) + ' ago (' + ls.total + ' items)' : 'never — run intel-collector --sources aoi', ls ? '' : 'high']+ ];+ if (ls) { Object.keys(ls.counts).sort().forEach(function(k) { fields.push([k.replace(/_/g, ' '), String(ls.counts[k])]); }); }} else if (type === 'pipeline') {title = d.name || 'Pipeline';subtitle = d.route || '';@@ -1510,7 +1529,7 @@ function _toggleHelp() {document.body.appendChild(_helpOverlay);}-var _layerKeys = ['quakes','military','conflict','fires','convergence','nuclear','infra','exposure','airtraffic','news'];+var _layerKeys = ['quakes','military','conflict','fires','convergence','nuclear','infra','exposure','airtraffic','news','aoi'];function _toggleLayerByIndex(idx) {var key = _layerKeys[idx];if (!key || !mapLayers[key]) return;@@ -3205,6 +3224,38 @@ function performSearch(q) {setTimeout(function() { $('#searchInput').style.borderColor = ''; }, 2000);}+// User AOI geofences: shapes from the store, counts from the last collector sweep.+// Never gathers live per AOI (that costs 60-90 s each); a never-swept AOI says so.+function updateMapAois(data) {+ mapLayers.aoi.clearLayers();+ var cnt = $('#cntAoi');+ if (!data || data.error) { cnt.textContent = '!'; cnt.title = (data && data.error) || 'AOI fetch failed'; return; }+ var aois = data.aois || [];+ aois.forEach(function(a) {+ var opts = { color: '#ff7f50', weight: 2, opacity: 0.9, fillColor: '#ff7f50', fillOpacity: 0.08, className: 'aoi-shape' };+ var shape;+ if (a.kind === 'polygon' && a.geometry && a.geometry.vertices) {+ shape = L.polygon(a.geometry.vertices, opts);+ } else if (a.kind === 'corridor' && a.geometry && a.geometry.waypoints) {+ // Width is stated in the tooltip/detail; a polyline cannot draw it honestly at every zoom.+ shape = L.polyline(a.geometry.waypoints, { color: '#ff7f50', weight: 3, opacity: 0.9, dashArray: '8 6', className: 'aoi-shape' });+ } else {+ shape = L.circle([a.lat, a.lon], Object.assign({ radius: (a.radius_km || 0) * 1000 }, opts));+ }+ var ls = a.last_sweep;+ var sweep = ls ? ls.total + ' items, swept ' + ago(ls.taken_at * 1000) + ' ago' : 'never swept';+ shape.bindTooltip(esc(a.name) + '<br><span style="opacity:0.7">' + esc(a.kind || 'circle') + ' • ' + esc(sweep) + '</span>', { className: 'mk-tip', sticky: true });+ shape.on('click', function() { showDetail('aoi', a); });+ shape.addTo(mapLayers.aoi);+ });+ cnt.textContent = aois.length;+ cnt.title = '';+}+fetch('/api/aois')+ .then(function(r) { return r.json(); })+ .then(function(data) { try { updateMapAois(data); } catch(e) { console.warn('aoi layer failed:', e); } })+ .catch(function(e) { console.warn('aoi fetch failed:', e); var c = $('#cntAoi'); c.textContent = '!'; c.title = String(e); });+// Load static geospatial data immediately (bases, ports, nuclear facilities).fetch('/api/static').then(function(r) { return r.json(); })diff --git a/src/world_intel_mcp/tests/test_dashboard_aois.py b/src/world_intel_mcp/tests/test_dashboard_aois.pynew file mode 100644index 0000000..3c696fa--- /dev/null+++ b/src/world_intel_mcp/tests/test_dashboard_aois.py@@ -0,0 +1,113 @@+"""Tests for the dashboard's /api/aois endpoint (Phase 23: dashboard AOI layer).++The map draws user-defined geofences from this endpoint and shows, per+area, what the last collector sweep counted inside it. Counts come from+the stored change snapshot, not a live multi-domain gather: the+dashboard boots instantly and never spends 60-90 s of upstream fetches+per AOI just to draw a shape.++First endpoint tests for the dashboard; the prior test_dashboard.py+covered only argument parsing. Uses Starlette's TestClient without the+context manager so lifespan (default-path Cache, vector store) never+runs.++Gaps / not covered: the Leaflet rendering itself (index.html JS) has no+automated test; it is verified by loading the dashboard live.+"""++from pathlib import Path++import pytest+from starlette.testclient import TestClient++from world_intel_mcp.analysis import aoi+from world_intel_mcp.analysis.aoi import AOIStore+from world_intel_mcp.dashboard import app as dashboard_app++_PGH_LAT, _PGH_LON = 40.4406, -79.9959+++def store(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AOIStore:+ """The test's own handle for defining AOIs. The endpoint is patched+ to open a FRESH store on the same file per request, exactly as+ production does: SQLite connections are thread-bound, and the test+ client serves requests on a different thread from this fixture."""+ db_path = tmp_path / "dash_aoi.db"+ s = AOIStore(db_path)+ monkeypatch.setattr(dashboard_app, "_open_aoi_store", lambda: AOIStore(db_path))+ yield s+ s.close()+++def client() -> TestClient:+ return TestClient(dashboard_app.app)+++def test_api_aois_empty(client: TestClient, store: AOIStore) -> None:+ r = client.get("/api/aois")+ assert r.status_code == 200+ body = r.json()+ assert body["aois"] == []+ assert body["count"] == 0+ assert "error" not in body+ assert r.headers.get("access-control-allow-origin") == "*"+++def test_api_aois_lists_geometry_and_last_sweep(+ client: TestClient, store: AOIStore+) -> None:+ aoi.define_aoi(store, "Home", _PGH_LAT, _PGH_LON, 50.0)+ aoi.define_polygon_aoi(+ store,+ "PGH Square",+ [(40.3, -80.1), (40.3, -79.9), (40.6, -79.9), (40.6, -80.1)],+ )+ aoi.define_corridor_aoi(+ store, "I-79", [(40.2, -80.2), (40.5, -80.0), (40.8, -79.9)], 20.0+ )+ store.save_snapshot(+ "Home",+ {"earthquakes": {"eq1": "M4.9", "eq2": "M5.1"}, "news": {}},+ )++ r = client.get("/api/aois")+ assert r.status_code == 200+ body = r.json()+ assert body["count"] == 3+ by_name = {a["name"]: a for a in body["aois"]}++ home = by_name["Home"]+ assert home["kind"] == "circle"+ assert home["lat"] == _PGH_LAT and home["lon"] == _PGH_LON+ assert home["radius_km"] == 50.0+ assert home["last_sweep"]["taken_at"] > 0+ assert home["last_sweep"]["counts"] == {"earthquakes": 2, "news": 0}+ assert home["last_sweep"]["total"] == 2++ square = by_name["PGH Square"]+ assert square["kind"] == "polygon"+ assert len(square["geometry"]["vertices"]) == 4+ assert square["last_sweep"] is None # never swept: say so, don't fake zeros++ corridor = by_name["I-79"]+ assert corridor["kind"] == "corridor"+ assert corridor["geometry"]["width_km"] == 20.0+ assert len(corridor["geometry"]["waypoints"]) == 3+++def test_api_aois_store_failure_is_honest(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A broken store must not render as 'no AOIs defined'."""++ def _boom():+ raise RuntimeError("disk on fire")++ monkeypatch.setattr(dashboard_app, "_open_aoi_store", _boom)+ r = client.get("/api/aois")+ assert r.status_code == 503+ body = r.json()+ assert "disk on fire" in body["error"]+ assert body["aois"] == [] and body["count"] == 0