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
Geofence hardening + change detection: antimeridian bboxes, segment distance, intel_aoi_update, intel_aoi_changes (+2 = 122 tools)
Phoenix Agent (Marcs-Mac-Studio)b12aa1989cb7
diff --git a/src/world_intel_mcp/analysis/aoi.py b/src/world_intel_mcp/analysis/aoi.pyindex f5f96d1..051c5cc 100644--- a/src/world_intel_mcp/analysis/aoi.py+++ b/src/world_intel_mcp/analysis/aoi.py@@ -31,6 +31,7 @@ tested 188-line module untouched by this change.from __future__ import annotationsimport asyncio+import jsonimport loggingimport mathimport sqlite3@@ -73,27 +74,101 @@ def haversine_km(lat1: float, lon1: float, lat2: float, lon2: float) -> float:return _EARTH_RADIUS_KM * 2 * math.asin(math.sqrt(min(1.0, a)))-def bbox_from_radius_km(lat: float, lon: float, radius_km: float) -> str:- """Derive a ``lamin,lomin,lamax,lomax`` bounding box (the format- ``sources/military.py``'s ``fetch_military_flights(bbox=...)`` takes)- that fully contains a circle of ``radius_km`` around (lat, lon).+def _lat_band(lat: float, radius_km: float) -> tuple[float, float]:+ dlat = radius_km / _KM_PER_DEGREE_LAT+ return max(-90.0, lat - dlat), min(90.0, lat + dlat)- Longitude degrees shrink toward the poles; the cosine factor is- clamped so a near-polar AOI gets a wide-but-finite box instead of a- division blowup. This is a bounding rectangle, not the circle itself;- callers that need the exact radius still haversine-filter the- candidates it returns (see ``filter_by_radius``), the same way++def _lon_halfwidth_deg(lat: float, radius_km: float) -> float:+ """Half-width in longitude degrees of a circle of ``radius_km`` at+ ``lat``. Longitude degrees shrink toward the poles; the cosine factor+ is clamped so a near-polar AOI gets a wide-but-finite width instead+ of a division blowup."""+ cos_lat = max(math.cos(math.radians(lat)), 0.01)+ return radius_km / (_KM_PER_DEGREE_LAT * cos_lat)+++def bboxes_from_radius_km(lat: float, lon: float, radius_km: float) -> list[str]:+ """Derive ``lamin,lomin,lamax,lomax`` bounding boxes (the format+ ``sources/military.py``'s ``fetch_military_flights(bbox=...)`` takes)+ that together fully contain a circle of ``radius_km`` around+ (lat, lon).++ Normally one box. When the circle crosses the antimeridian the+ single-box clamp used before v0.4 silently cut off everything on the+ far side of the dateline (a Bering Strait or Fiji AOI lost half its+ coverage); such circles now split into two boxes, one ending at+ +180 and one starting at -180. A circle whose longitude half-width+ reaches 180 degrees rings the pole and gets one full-longitude box.++ These are bounding rectangles, not the circle itself; callers that+ need the exact radius still haversine-filter the candidates they get+ back (see ``filter_by_radius``), the same way``analysis/convergence.py``'s grid cells are a coarse pre-filter, notthe final answer."""- dlat = radius_km / _KM_PER_DEGREE_LAT- cos_lat = max(math.cos(math.radians(lat)), 0.01)- dlon = radius_km / (_KM_PER_DEGREE_LAT * cos_lat)- lamin = max(-90.0, lat - dlat)- lamax = min(90.0, lat + dlat)- lomin = max(-180.0, lon - dlon)- lomax = min(180.0, lon + dlon)- return f"{lamin:.4f},{lomin:.4f},{lamax:.4f},{lomax:.4f}"+ lamin, lamax = _lat_band(lat, radius_km)+ dlon = _lon_halfwidth_deg(lat, radius_km)++ def _box(lomin: float, lomax: float) -> str:+ return f"{lamin:.4f},{lomin:.4f},{lamax:.4f},{lomax:.4f}"++ if dlon >= 180.0:+ return [_box(-180.0, 180.0)]+ lomin = lon - dlon+ lomax = lon + dlon+ if lomin < -180.0:+ return [_box(-180.0, lomax), _box(lomin + 360.0, 180.0)]+ if lomax > 180.0:+ return [_box(lomin, 180.0), _box(-180.0, lomax - 360.0)]+ return [_box(lomin, lomax)]+++def _bearing_rad(lat1: float, lon1: float, lat2: float, lon2: float) -> float:+ """Initial great-circle bearing from point 1 to point 2, in radians."""+ phi1, phi2 = math.radians(lat1), math.radians(lat2)+ dlon = math.radians(lon2 - lon1)+ y = math.sin(dlon) * math.cos(phi2)+ x = math.cos(phi1) * math.sin(phi2) - math.sin(phi1) * math.cos(phi2) * math.cos(+ dlon+ )+ return math.atan2(y, x)+++def segment_distance_km(+ plat: float,+ plon: float,+ alat: float,+ alon: float,+ blat: float,+ blon: float,+) -> float:+ """Distance from point P to the great-circle SEGMENT A-B, in km.++ Cross-track distance where the closest point of the great circle+ falls within the segment; distance to the nearer endpoint where it+ falls beyond either end. The endpoint clamp is what makes this a+ segment distance: a point far past B on the same great circle is+ near the *line* but not near the *pipeline*."""+ d_ab = haversine_km(alat, alon, blat, blon) / _EARTH_RADIUS_KM+ d_ap_km = haversine_km(plat, plon, alat, alon)+ if d_ab < 1e-9:+ return d_ap_km+ d_ap = d_ap_km / _EARTH_RADIUS_KM+ theta_ap = _bearing_rad(alat, alon, plat, plon)+ theta_ab = _bearing_rad(alat, alon, blat, blon)+ if math.cos(theta_ap - theta_ab) < 0:+ # Closest point of the great circle lies behind A.+ return d_ap_km+ xt = math.asin(max(-1.0, min(1.0, math.sin(d_ap) * math.sin(theta_ap - theta_ab))))+ cos_xt = math.cos(xt)+ if abs(cos_xt) < 1e-12:+ return abs(xt) * _EARTH_RADIUS_KM+ at = math.acos(max(-1.0, min(1.0, math.cos(d_ap) / cos_xt)))+ if at > d_ab:+ # Closest point of the great circle lies beyond B.+ return haversine_km(plat, plon, blat, blon)+ return abs(xt) * _EARTH_RADIUS_KMdef _distance_or_none(@@ -198,6 +273,15 @@ class AOIStore:)""")+ self._conn.execute(+ """+ CREATE TABLE IF NOT EXISTS aoi_snapshots (+ name_key TEXT PRIMARY KEY,+ taken_at REAL NOT NULL,+ snapshot TEXT NOT NULL+ )+ """+ )self._conn.commit()@staticmethod@@ -255,12 +339,92 @@ class AOIStore:return [self._row_to_dict(r) for r in rows]def delete(self, name: str) -> bool:- cur = self._conn.execute(- "DELETE FROM aois WHERE name_key = ?", (self._key(name),)- )+ key = self._key(name)+ cur = self._conn.execute("DELETE FROM aois WHERE name_key = ?", (key,))+ self._conn.execute("DELETE FROM aoi_snapshots WHERE name_key = ?", (key,))self._conn.commit()return cur.rowcount > 0+ def update(+ self,+ name: str,+ *,+ new_name: str | None = None,+ lat: float | None = None,+ lon: float | None = None,+ radius_km: float | None = None,+ ) -> dict[str, Any]:+ """Apply the given field changes to an existing AOI and return the+ updated row. A rename migrates the AOI's change snapshot with it;+ validation, collision checks, and the geometry-change snapshot+ drop are the caller's job (see ``update_aoi``). Raises ``KeyError``+ if the AOI does not exist."""+ existing = self.get(name)+ if existing is None:+ raise KeyError(name)+ old_key = self._key(name)+ merged_name = new_name.strip() if new_name is not None else existing["name"]+ merged = {+ "name": merged_name,+ "lat": lat if lat is not None else existing["lat"],+ "lon": lon if lon is not None else existing["lon"],+ "radius_km": radius_km if radius_km is not None else existing["radius_km"],+ "created_at": existing["created_at"],+ }+ new_key = self._key(merged_name)+ self._conn.execute(+ "UPDATE aois SET name_key = ?, name = ?, lat = ?, lon = ?, radius_km = ? "+ "WHERE name_key = ?",+ (+ new_key,+ merged["name"],+ merged["lat"],+ merged["lon"],+ merged["radius_km"],+ old_key,+ ),+ )+ if new_key != old_key:+ self._conn.execute(+ "UPDATE aoi_snapshots SET name_key = ? WHERE name_key = ?",+ (new_key, old_key),+ )+ self._conn.commit()+ return merged++ # -- Change-detection snapshots -----------------------------------++ def get_snapshot(self, name: str) -> dict[str, Any] | None:+ """The last saved change-detection snapshot for an AOI:+ ``{"taken_at": epoch, "domains": {domain: {item_key: summary}}}``,+ or ``None`` if no sweep has been recorded."""+ row = self._conn.execute(+ "SELECT taken_at, snapshot FROM aoi_snapshots WHERE name_key = ?",+ (self._key(name),),+ ).fetchone()+ if row is None:+ return None+ taken_at, snapshot_json = row+ try:+ domains = json.loads(snapshot_json)+ except (TypeError, ValueError):+ return None+ return {"taken_at": taken_at, "domains": domains}++ def save_snapshot(self, name: str, domains: dict[str, dict[str, str]]) -> None:+ self._conn.execute(+ "INSERT OR REPLACE INTO aoi_snapshots (name_key, taken_at, snapshot) "+ "VALUES (?, ?, ?)",+ (self._key(name), time.time(), json.dumps(domains)),+ )+ self._conn.commit()++ def delete_snapshot(self, name: str) -> None:+ self._conn.execute(+ "DELETE FROM aoi_snapshots WHERE name_key = ?", (self._key(name),)+ )+ self._conn.commit()+def close(self) -> None:self._conn.close()@@ -307,6 +471,74 @@ def delete_aoi(store: AOIStore, name: Any) -> dict:}+def update_aoi(+ store: AOIStore,+ name: Any,+ new_name: Any = None,+ lat: Any = None,+ lon: Any = None,+ radius_km: Any = None,+) -> dict:+ """Change any subset of an existing AOI's name, center, or radius.+ A rename keeps the change-detection snapshot; a geometry change+ (center or radius) drops it, because the old snapshot described a+ different piece of the planet and diffing against it would+ manufacture fake enter/leave events."""+ if not isinstance(name, str) or not name.strip():+ return {"error": "name must be a non-empty string."}+ existing = store.get(name)+ if existing is None:+ return {+ "error": f"AOI '{name}' not found. Use intel_aoi_list to see defined areas."+ }+ if new_name is None and lat is None and lon is None and radius_km is None:+ return {+ "error": "Nothing to update: provide at least one of "+ "new_name, lat, lon, radius_km."+ }++ merged_name = new_name if new_name is not None else existing["name"]+ merged_lat = lat if lat is not None else existing["lat"]+ merged_lon = lon if lon is not None else existing["lon"]+ merged_radius = radius_km if radius_km is not None else existing["radius_km"]+ error = validate_aoi_params(merged_name, merged_lat, merged_lon, merged_radius)+ if error:+ return {"error": error}++ if new_name is not None:+ new_key = AOIStore._key(new_name)+ if new_key != AOIStore._key(name):+ collision = store.get(new_name)+ if collision is not None:+ return {+ "error": f"AOI '{new_name.strip()}' already exists.",+ "existing": collision,+ }++ geometry_changed = any(+ value is not None and float(value) != existing[field]+ for field, value in (("lat", lat), ("lon", lon), ("radius_km", radius_km))+ )++ updated = store.update(+ name,+ new_name=str(merged_name),+ lat=float(merged_lat),+ lon=float(merged_lon),+ radius_km=float(merged_radius),+ )+ if geometry_changed:+ store.delete_snapshot(updated["name"])++ return {+ "aoi": updated,+ "previous": existing,+ "snapshot_dropped": geometry_changed,+ "source": "aoi-update",+ "timestamp": _utc_now_iso(),+ }++# ---------------------------------------------------------------------------# Nearby static infrastructure: pure, no I/O, config datasets only# ---------------------------------------------------------------------------@@ -374,23 +606,55 @@ def nearby_spaceports(lat: float, lon: float, radius_km: float) -> list[dict]:)+def _segment_distance_or_none(+ lat: float,+ lon: float,+ lat1: Any,+ lon1: Any,+ lat2: Any,+ lon2: Any,+) -> float | None:+ try:+ if None in (lat1, lon1, lat2, lon2):+ return None+ return segment_distance_km(+ lat, lon, float(lat1), float(lon1), float(lat2), float(lon2)+ )+ except (TypeError, ValueError):+ return None++def nearby_pipelines(lat: float, lon: float, radius_km: float) -> list[dict]:- """Pipelines are line features; proximity is approximated from each- pipeline's two published endpoints (``lat_start``/``lon_start``,- ``lat_end``/``lon_end``); the config dataset carries no intermediate- waypoints. A pipeline that passes through the AOI without either- endpoint nearby is missed by this approximation; documented here+ """Pipelines are line features. Proximity is the great-circle-segment+ distance between the AOI center and the span from+ (``lat_start``, ``lon_start``) to (``lat_end``, ``lon_end``), so a+ pipeline whose midspan crosses the AOI is detected even when both+ endpoints are far away (endpoint-only proximity missed that case+ before v0.4). Still an approximation: the config dataset carries no+ intermediate waypoints, so a pipeline that bends far off the+ endpoint-to-endpoint great circle can be misjudged; documented hererather than silently wrong."""from ..config.geospatial import PIPELINESout = []for p in PIPELINES:- d_start = _distance_or_none(lat, lon, p.get("lat_start"), p.get("lon_start"))- d_end = _distance_or_none(lat, lon, p.get("lat_end"), p.get("lon_end"))- candidates = [d for d in (d_start, d_end) if d is not None]- if not candidates:- continue- dist = min(candidates)+ dist = _segment_distance_or_none(+ lat,+ lon,+ p.get("lat_start"),+ p.get("lon_start"),+ p.get("lat_end"),+ p.get("lon_end"),+ )+ if dist is None:+ d_start = _distance_or_none(+ lat, lon, p.get("lat_start"), p.get("lon_start")+ )+ d_end = _distance_or_none(lat, lon, p.get("lat_end"), p.get("lon_end"))+ candidates = [d for d in (d_start, d_end) if d is not None]+ if not candidates:+ continue+ dist = min(candidates)if dist <= radius_km:out.append({@@ -406,19 +670,38 @@ def nearby_pipelines(lat: float, lon: float, radius_km: float) -> list[dict]:def nearby_cables(lat: float, lon: float, radius_km: float) -> list[dict]:- """Cables are multi-point routes; proximity is the closest published- landing point, not the undersea path between landing points."""+ """Cables are multi-point routes. Proximity is the minimum+ great-circle-segment distance over consecutive published landing+ points, so a cable whose run passes the AOI between landings is+ detected (landing-point-only proximity missed that case before+ v0.4). The nearest published landing point is still reported for+ context. Real cable paths deviate from great circles; the segment is+ an approximation of the run, not its surveyed route."""from ..config.cables import UNDERSEA_CABLESout = []for cable in UNDERSEA_CABLES:- best_dist: float | None = None+ points = [+ (lp.get("lat"), lp.get("lon"), lp.get("name"))+ for lp in cable.get("landing_points", [])+ ]++ best_landing_dist: float | None = Nonebest_landing: str | None = None- for lp in cable.get("landing_points", []):- dist = _distance_or_none(lat, lon, lp.get("lat"), lp.get("lon"))+ for plat, plon, pname in points:+ dist = _distance_or_none(lat, lon, plat, plon)+ if dist is not None and (+ best_landing_dist is None or dist < best_landing_dist+ ):+ best_landing_dist = dist+ best_landing = pname++ best_dist = best_landing_dist+ for (alat, alon, _), (blat, blon, _) in zip(points, points[1:]):+ dist = _segment_distance_or_none(lat, lon, alat, alon, blat, blon)if dist is not None and (best_dist is None or dist < best_dist):best_dist = dist- best_landing = lp.get("name")+if best_dist is not None and best_dist <= radius_km:out.append({@@ -472,19 +755,25 @@ def _overlapping_wildfire_regions(``fetch_wildfires`` exposes only these 9 continental regions, so anAOI is "region-mappable" whenever its box intersects at least one ofthem: true for all populated land; an AOI in open ocean far from any- region is the honest gap."""+ region is the honest gap. Uses the same antimeridian-aware boxes as+ the rest of the module, so an AOI just east of the dateline still+ maps into the oceania box that ends at lon 180."""from ..sources.wildfire import REGIONS- dlat = radius_km / _KM_PER_DEGREE_LAT- cos_lat = max(math.cos(math.radians(lat)), 0.01)- dlon = radius_km / (_KM_PER_DEGREE_LAT * cos_lat)- a_west, a_south, a_east, a_north = lon - dlon, lat - dlat, lon + dlon, lat + dlat-overlapping = []- for region_name, bbox in REGIONS.items():- west, south, east, north = (float(x) for x in bbox.split(","))- if a_west <= east and a_east >= west and a_south <= north and a_north >= south:- overlapping.append(region_name)+ for aoi_box in bboxes_from_radius_km(lat, lon, radius_km):+ a_south, a_west, a_north, a_east = (float(x) for x in aoi_box.split(","))+ for region_name, bbox in REGIONS.items():+ if region_name in overlapping:+ continue+ west, south, east, north = (float(x) for x in bbox.split(","))+ if (+ a_west <= east+ and a_east >= west+ and a_south <= north+ and a_north >= south+ ):+ overlapping.append(region_name)return overlapping@@ -521,6 +810,122 @@ async def _fetch_wildfires_for_aoi(fetcher, wildfire_regions: list[str]) -> dictreturn {"clusters": clusters}+async def _fetch_military_merged(fetcher, bboxes: list[str]) -> dict:+ """Fetch military flights for each bounding box (two when the AOI+ crosses the antimeridian) and merge, deduplicating by icao24 /+ callsign — the same aircraft can appear in both boxes' data because+ the adsb.lol path returns a global list regardless of bbox. Reports+ an error only when every box failed; a partial failure is surfaced+ via ``partial_errors`` so the caller can name the gap honestly+ instead of presenting half-coverage as full."""+ from ..sources import military++ results = await asyncio.gather(+ *[+ _safe_fetch(+ military.fetch_military_flights(fetcher, bbox=b), "military_flights"+ )+ for b in bboxes+ ]+ )+ aircraft: list[dict] = []+ errors: list[str] = []+ seen: set[str] = set()+ any_ok = False+ for res in results:+ if not isinstance(res, dict):+ continue+ if res.get("error"):+ errors.append(str(res["error"]))+ continue+ any_ok = True+ for ac in res.get("aircraft", []):+ key = ac.get("icao24") or ac.get("callsign")+ if key is not None:+ if key in seen:+ continue+ seen.add(key)+ aircraft.append(ac)+ if not any_ok:+ return {+ "error": "; ".join(sorted(set(errors))) or "military flights fetch failed"+ }+ out: dict[str, Any] = {"aircraft": aircraft}+ if errors:+ out["partial_errors"] = sorted(set(errors))+ return out+++async def _gather_scoped_domains(+ fetcher, lat: float, lon: float, radius_km: float, aoi_name: str+) -> dict[str, dict]:+ """Fetch all six dynamic domains in parallel and scope each to the+ AOI. The single shared scoping path for ``fetch_aoi_brief`` and+ ``fetch_aoi_changes``, so the two tools can never disagree about+ what is inside the fence.++ Per domain: ``{"items": [...]}`` (radius-filtered, annotated with+ ``distance_km``, nearest first) or ``{"error": msg}``. Military may+ additionally carry ``partial_errors`` (antimeridian AOIs query two+ boxes; one can fail alone). News items are the raw articles —+ scoped by AOI-name mention, not geography."""+ from ..sources import aviation, conflict, news, seismology++ bboxes = bboxes_from_radius_km(lat, lon, radius_km)+ wildfire_regions = _overlapping_wildfire_regions(lat, lon, radius_km)++ (+ eq_result,+ mil_result,+ conflict_result,+ wildfire_result,+ aviation_result,+ news_result,+ ) = await asyncio.gather(+ _safe_fetch(seismology.fetch_earthquakes(fetcher, hours=72), "earthquakes"),+ _fetch_military_merged(fetcher, bboxes),+ _safe_fetch(conflict.fetch_acled_events(fetcher, days=7), "acled_events"),+ _safe_fetch(_fetch_wildfires_for_aoi(fetcher, wildfire_regions), "wildfires"),+ _safe_fetch(aviation.fetch_domestic_flights(fetcher), "domestic_flights"),+ _safe_fetch(+ news.fetch_gdelt_search(fetcher, query=aoi_name, mode="artlist", limit=10),+ "news",+ ),+ )++ scoped: dict[str, dict] = {}++ def _scope(+ result: Any, list_key: str, domain: str, lat_key: str, lon_key: str+ ) -> None:+ if isinstance(result, dict) and result.get("error"):+ scoped[domain] = {"error": str(result["error"])}+ return+ items = result.get(list_key, []) if isinstance(result, dict) else []+ entry: dict[str, Any] = {+ "items": filter_by_radius(items, lat, lon, radius_km, lat_key, lon_key)+ }+ if isinstance(result, dict) and result.get("partial_errors"):+ entry["partial_errors"] = result["partial_errors"]+ scoped[domain] = entry++ _scope(eq_result, "earthquakes", "earthquakes", "latitude", "longitude")+ _scope(mil_result, "aircraft", "military_flights", "latitude", "longitude")+ _scope(conflict_result, "events", "conflict_events", "latitude", "longitude")+ _scope(wildfire_result, "clusters", "wildfires", "lat", "lon")+ _scope(aviation_result, "sampled", "aviation", "lat", "lon")++ if isinstance(news_result, dict) and news_result.get("error"):+ scoped["news"] = {"error": str(news_result["error"])}+ else:+ scoped["news"] = {+ "items": (+ news_result.get("articles", []) if isinstance(news_result, dict) else []+ )+ }+ return scoped++# ---------------------------------------------------------------------------# intel_aoi_brief# ---------------------------------------------------------------------------@@ -543,33 +948,10 @@ async def fetch_aoi_brief(fetcher, store: AOIStore, name: Any) -> dict:"error": f"AOI '{name}' not found. Use intel_aoi_list to see defined areas."}- from ..sources import aviation, conflict, military, news, seismology-lat, lon, radius_km = aoi["lat"], aoi["lon"], aoi["radius_km"]aoi_name = aoi["name"]- bbox = bbox_from_radius_km(lat, lon, radius_km)- wildfire_regions = _overlapping_wildfire_regions(lat, lon, radius_km)- (- eq_result,- mil_result,- conflict_result,- wildfire_result,- aviation_result,- news_result,- ) = await asyncio.gather(- _safe_fetch(seismology.fetch_earthquakes(fetcher, hours=72), "earthquakes"),- _safe_fetch(- military.fetch_military_flights(fetcher, bbox=bbox), "military_flights"- ),- _safe_fetch(conflict.fetch_acled_events(fetcher, days=7), "acled_events"),- _safe_fetch(_fetch_wildfires_for_aoi(fetcher, wildfire_regions), "wildfires"),- _safe_fetch(aviation.fetch_domestic_flights(fetcher), "domestic_flights"),- _safe_fetch(- news.fetch_gdelt_search(fetcher, query=aoi_name, mode="artlist", limit=10),- "news",- ),- )+ scoped = await _gather_scoped_domains(fetcher, lat, lon, radius_km, aoi_name)sources: list[dict] = []citations: dict[str, list[int]] = {}@@ -581,16 +963,11 @@ async def fetch_aoi_brief(fetcher, store: AOIStore, name: Any) -> dict:sections.setdefault(domain, []).append(text)# Earthquakes ------------------------------------------------------- if isinstance(eq_result, dict) and eq_result.get("error"):- data_gaps.append(f"Earthquakes: {eq_result['error']}")+ if scoped["earthquakes"].get("error"):+ data_gaps.append(f"Earthquakes: {scoped['earthquakes']['error']}")counts["earthquakes"] = 0else:- eq_events = (- eq_result.get("earthquakes", []) if isinstance(eq_result, dict) else []- )- eq_in_range = filter_by_radius(- eq_events, lat, lon, radius_km, "latitude", "longitude"- )+ eq_in_range = scoped["earthquakes"]["items"]counts["earthquakes"] = len(eq_in_range)for eq in eq_in_range:n = _add_source(@@ -608,16 +985,13 @@ async def fetch_aoi_brief(fetcher, store: AOIStore, name: Any) -> dict:)# Military flights ---------------------------------------------------- if isinstance(mil_result, dict) and mil_result.get("error"):- data_gaps.append(f"Military flights: {mil_result['error']}")+ if scoped["military_flights"].get("error"):+ data_gaps.append(f"Military flights: {scoped['military_flights']['error']}")counts["military_flights"] = 0else:- mil_aircraft = (- mil_result.get("aircraft", []) if isinstance(mil_result, dict) else []- )- mil_in_range = filter_by_radius(- mil_aircraft, lat, lon, radius_km, "latitude", "longitude"- )+ mil_in_range = scoped["military_flights"]["items"]+ for partial in scoped["military_flights"].get("partial_errors", []):+ data_gaps.append(f"Military flights: partial coverage: {partial}")counts["military_flights"] = len(mil_in_range)if mil_in_range:n = _add_source(@@ -634,18 +1008,11 @@ async def fetch_aoi_brief(fetcher, store: AOIStore, name: Any) -> dict:)# Conflict (ACLED) ----------------------------------------------------- if isinstance(conflict_result, dict) and conflict_result.get("error"):- data_gaps.append(f"Conflict events: {conflict_result['error']}")+ if scoped["conflict_events"].get("error"):+ data_gaps.append(f"Conflict events: {scoped['conflict_events']['error']}")counts["conflict_events"] = 0else:- conflict_events = (- conflict_result.get("events", [])- if isinstance(conflict_result, dict)- else []- )- conflict_in_range = filter_by_radius(- conflict_events, lat, lon, radius_km, "latitude", "longitude"- )+ conflict_in_range = scoped["conflict_events"]["items"]counts["conflict_events"] = len(conflict_in_range)for ev in conflict_in_range[:10]:loc = (@@ -668,16 +1035,11 @@ async def fetch_aoi_brief(fetcher, store: AOIStore, name: Any) -> dict:)# Wildfires ------------------------------------------------------------- if isinstance(wildfire_result, dict) and wildfire_result.get("error"):- data_gaps.append(f"Wildfires: {wildfire_result['error']}")+ if scoped["wildfires"].get("error"):+ data_gaps.append(f"Wildfires: {scoped['wildfires']['error']}")counts["wildfires"] = 0else:- clusters = (- wildfire_result.get("clusters", [])- if isinstance(wildfire_result, dict)- else []- )- fire_in_range = filter_by_radius(clusters, lat, lon, radius_km, "lat", "lon")+ fire_in_range = scoped["wildfires"]["items"]counts["wildfires"] = len(fire_in_range)for fc in fire_in_range:n = _add_source(@@ -692,16 +1054,11 @@ async def fetch_aoi_brief(fetcher, store: AOIStore, name: Any) -> dict:)# Aviation (sampled) ---------------------------------------------------- if isinstance(aviation_result, dict) and aviation_result.get("error"):- data_gaps.append(f"Aviation: {aviation_result['error']}")+ if scoped["aviation"].get("error"):+ data_gaps.append(f"Aviation: {scoped['aviation']['error']}")counts["aviation"] = 0else:- sampled = (- aviation_result.get("sampled", [])- if isinstance(aviation_result, dict)- else []- )- aviation_in_range = filter_by_radius(sampled, lat, lon, radius_km, "lat", "lon")+ aviation_in_range = scoped["aviation"]["items"]counts["aviation"] = len(aviation_in_range)if aviation_in_range:n = _add_source(@@ -717,14 +1074,12 @@ async def fetch_aoi_brief(fetcher, store: AOIStore, name: Any) -> dict:)# News headline mentions ------------------------------------------------ if isinstance(news_result, dict) and news_result.get("error"):- data_gaps.append(f"News: {news_result['error']}")+ if scoped["news"].get("error"):+ data_gaps.append(f"News: {scoped['news']['error']}")counts["news"] = 0articles: list = []else:- articles = (- news_result.get("articles", []) if isinstance(news_result, dict) else []- )+ articles = scoped["news"]["items"]counts["news"] = len(articles)for art in articles[:10]:title = art.get("title")@@ -811,17 +1166,14 @@ async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:}from ..sources import conflict as conflict_mod- from ..sources import military as mil_modlat, lon, radius_km = aoi["lat"], aoi["lon"], aoi["radius_km"]aoi_name = aoi["name"]- bbox = bbox_from_radius_km(lat, lon, radius_km)+ bboxes = bboxes_from_radius_km(lat, lon, radius_km)acled_result, mil_result = await asyncio.gather(_safe_fetch(conflict_mod.fetch_acled_events(fetcher, days=7), "acled_events"),- _safe_fetch(- mil_mod.fetch_military_flights(fetcher, bbox=bbox), "military_flights"- ),+ _fetch_military_merged(fetcher, bboxes),)data_gaps: list[str] = []@@ -848,6 +1200,10 @@ async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:if isinstance(mil_result, dict) and mil_result.get("error"):data_gaps.append(f"Military flights: {mil_result['error']}")else:+ for partial in (+ mil_result.get("partial_errors", []) if isinstance(mil_result, dict) else []+ ):+ data_gaps.append(f"Military flights: partial coverage: {partial}")aircraft = filter_by_radius(mil_result.get("aircraft", []) if isinstance(mil_result, dict) else [],lat,@@ -882,3 +1238,147 @@ async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:"timestamp": _utc_now_iso(),**scored,}+++# ---------------------------------------------------------------------------+# intel_aoi_changes: geofence change detection+# ---------------------------------------------------------------------------++# How each diffable domain identifies an item across sweeps and summarizes+# it for the report. Aviation is deliberately absent: the 1-in-10 global+# sample is pure churn between sweeps, and diffing it would manufacture+# fake enter/leave events every run. Static infrastructure is absent+# because it cannot change between sweeps.+_CHANGE_DOMAINS: dict[str, tuple[Any, Any]] = {+ "earthquakes": (+ lambda i: str(+ i.get("id")+ or f"eq:{i.get('magnitude')}@{i.get('latitude')},{i.get('longitude')}"+ ),+ lambda i: f"M{i.get('magnitude')} {i.get('place') or 'unknown location'} "+ f"({i.get('distance_km')} km)",+ ),+ "military_flights": (+ lambda i: str(i.get("icao24") or i.get("callsign") or "unknown"),+ lambda i: f"{i.get('callsign') or i.get('icao24')} "+ f"({i.get('origin_country') or 'unknown origin'}, {i.get('distance_km')} km)",+ ),+ "conflict_events": (+ lambda i: f"{i.get('event_date')}|{i.get('event_type')}|"+ f"{i.get('location') or i.get('admin1') or i.get('country')}",+ lambda i: f"{i.get('event_type') or 'conflict event'}, "+ f"{i.get('location') or i.get('admin1') or i.get('country') or 'unspecified'} "+ f"({i.get('distance_km')} km)",+ ),+ "wildfires": (+ lambda i: f"fire:{round(float(i.get('lat', 0.0)), 2)},"+ f"{round(float(i.get('lon', 0.0)), 2)}",+ lambda i: f"{i.get('fire_count')} fire detections ({i.get('distance_km')} km)",+ ),+ "news": (+ lambda i: str(i.get("url") or i.get("title") or "untitled"),+ lambda i: str(i.get("title") or i.get("url") or "untitled"),+ ),+}++_CHANGE_GAP_LABELS = {+ "earthquakes": "Earthquakes",+ "military_flights": "Military flights",+ "conflict_events": "Conflict events",+ "wildfires": "Wildfires",+ "news": "News",+}+++async def fetch_aoi_changes(fetcher, store: AOIStore, name: Any) -> dict:+ """What entered or left a user-defined AOI since the last sweep: the+ geofence alerting primitive. Runs the same scoped gather as+ ``fetch_aoi_brief``, diffs each diffable domain against the AOI's+ stored snapshot, then saves the new snapshot.++ Honesty invariants: the first sweep is a ``baseline`` (nothing is+ claimed to have entered or left); a domain whose fetch failed goes to+ ``data_gaps``, is excluded from ``changes`` (a failed fetch must+ never read as "everything left the area"), and keeps its previous+ snapshot slice so the next successful sweep diffs against the last+ real observation."""+ if not isinstance(name, str) or not name.strip():+ return {"error": "name must be a non-empty string."}++ aoi = store.get(name)+ if aoi is None:+ return {+ "error": f"AOI '{name}' not found. Use intel_aoi_list to see defined areas."+ }++ lat, lon, radius_km = aoi["lat"], aoi["lon"], aoi["radius_km"]+ aoi_name = aoi["name"]++ scoped = await _gather_scoped_domains(fetcher, lat, lon, radius_km, aoi_name)++ previous = store.get_snapshot(aoi_name)+ prev_domains: dict[str, dict[str, str]] = previous["domains"] if previous else {}+ baseline = previous is None++ changes: dict[str, dict[str, Any]] = {}+ data_gaps: list[str] = []+ counts: dict[str, int] = {}+ next_domains: dict[str, dict[str, str]] = {}++ for domain, (key_fn, summary_fn) in _CHANGE_DOMAINS.items():+ result = scoped.get(domain, {})+ label = _CHANGE_GAP_LABELS[domain]+ if result.get("error"):+ data_gaps.append(f"{label}: {result['error']}")+ # Keep the last real observation for the next successful diff.+ if domain in prev_domains:+ next_domains[domain] = prev_domains[domain]+ continue+ for partial in result.get("partial_errors", []):+ data_gaps.append(f"{label}: partial coverage: {partial}")++ current: dict[str, str] = {}+ for item in result.get("items", []):+ try:+ current[key_fn(item)] = summary_fn(item)+ except (TypeError, ValueError):+ continue+ counts[domain] = len(current)+ next_domains[domain] = current++ if baseline or domain not in prev_domains:+ changes[domain] = {+ "new": [],+ "departed": [],+ "unchanged": len(current),+ "baseline": True,+ }+ continue++ prev_items = prev_domains[domain]+ new_keys = [k for k in current if k not in prev_items]+ departed_keys = [k for k in prev_items if k not in current]+ changes[domain] = {+ "new": [{"key": k, "summary": current[k]} for k in new_keys],+ "departed": [{"key": k, "summary": prev_items[k]} for k in departed_keys],+ "unchanged": len(current) - len(new_keys),+ }++ store.save_snapshot(aoi_name, next_domains)++ return {+ "aoi": {"name": aoi_name, "lat": lat, "lon": lon, "radius_km": radius_km},+ "baseline": baseline,+ "previous_taken_at": (+ datetime.fromtimestamp(previous["taken_at"], tz=timezone.utc).strftime(+ "%Y-%m-%dT%H:%M:%SZ"+ )+ if previous+ else None+ ),+ "changes": changes,+ "counts": counts,+ "data_gaps": data_gaps,+ "source": "aoi-changes",+ "timestamp": _utc_now_iso(),+ }diff --git a/src/world_intel_mcp/server.py b/src/world_intel_mcp/server.pyindex dd45acd..f2ba7d0 100644--- a/src/world_intel_mcp/server.py+++ b/src/world_intel_mcp/server.py@@ -49,6 +49,14 @@ Phase 22: intel_situation_brief (+1 = 120 tools). The cited situation brief (#15reachable directly over MCP, not only through the dashboard: a boundedserver-side gather of ~8-10 domains feeds the existing, unmodifiedfetch_situation_brief() (#18).+Phase 23: Geofence hardening + change detection (+2 = 122 tools). AOI bounding boxes+ split at the antimeridian instead of clamping (military fetches merge per-box+ with icao24 dedup; one-box failures surface as partial-coverage data_gaps);+ pipelines and undersea cables match on great-circle segment distance, not+ endpoints only. intel_aoi_update renames/resizes an AOI in place;+ intel_aoi_changes diffs each sweep against a stored per-AOI snapshot to+ report what entered and left the fence, with an explicit baseline first run+ and failed domains excluded from the diff rather than read as departures."""import asyncio@@ -1822,6 +1830,44 @@ TOOLS: list[Tool] = ["required": ["name"],},),+ Tool(+ name="intel_aoi_update",+ description="Update a user-defined AOI in place: rename it and/or change its center or radius, without losing its identity. Required: name. Optional: new_name, lat, lon, radius_km (same validation as intel_aoi_define; at least one must be provided). A rename keeps the AOI's change-detection history; changing center or radius drops it, because the old baseline described a different area.",+ inputSchema={+ "type": "object",+ "properties": {+ "name": {"type": "string", "description": "Current AOI name"},+ "new_name": {+ "type": "string",+ "description": "New name (case-insensitive, must not collide)",+ },+ "lat": {+ "type": "number",+ "description": "New center latitude, -90..90",+ },+ "lon": {+ "type": "number",+ "description": "New center longitude, -180..180",+ },+ "radius_km": {+ "type": "number",+ "description": "New radius in kilometers, 1..2000",+ },+ },+ "required": ["name"],+ },+ ),+ Tool(+ name="intel_aoi_changes",+ description="What entered or left a user-defined AOI since the last sweep: geofence change detection over earthquakes, military flights, ACLED conflict events, wildfire clusters, and news mentions. The first call establishes a baseline (nothing is claimed to have entered or left); subsequent calls report new, departed, and unchanged items per domain. A domain whose fetch failed is reported in data_gaps and excluded from the diff (a failed fetch never reads as 'everything left'), keeping its last real observation for the next successful sweep. Sampled aviation is excluded by design: a 1-in-10 sample churns every sweep. Required: name (must already be defined via intel_aoi_define).",+ inputSchema={+ "type": "object",+ "properties": {+ "name": {"type": "string", "description": "AOI name"},+ },+ "required": ["name"],+ },+ ),# --- Situation Brief (1 tool) ---Tool(name="intel_situation_brief",@@ -2541,6 +2587,19 @@ async def _dispatch(name: str, arguments: dict[str, Any]) -> Any:return aoi.list_aois(_aoi_store)case "intel_aoi_delete":return aoi.delete_aoi(_aoi_store, name=arguments.get("name"))+ case "intel_aoi_update":+ return aoi.update_aoi(+ _aoi_store,+ name=arguments.get("name"),+ new_name=arguments.get("new_name"),+ lat=arguments.get("lat"),+ lon=arguments.get("lon"),+ radius_km=arguments.get("radius_km"),+ )+ case "intel_aoi_changes":+ return await aoi.fetch_aoi_changes(+ fetcher, _aoi_store, name=arguments.get("name")+ )case "intel_aoi_brief":return await aoi.fetch_aoi_brief(fetcher, _aoi_store, name=arguments.get("name")diff --git a/src/world_intel_mcp/tests/test_aoi.py b/src/world_intel_mcp/tests/test_aoi.pyindex d209385..72bf186 100644--- a/src/world_intel_mcp/tests/test_aoi.py+++ b/src/world_intel_mcp/tests/test_aoi.py@@ -61,9 +61,9 @@ def test_haversine_km_known_pair() -> None:assert dist == pytest.approx(3936, rel=0.01)-def test_bbox_from_radius_km_widens_at_low_latitude_and_narrows_near_pole() -> None:- equator_box = aoi.bbox_from_radius_km(0.0, 0.0, 100.0)- polar_box = aoi.bbox_from_radius_km(85.0, 0.0, 100.0)+def test_bboxes_widen_at_high_latitude() -> None:+ equator_box = aoi.bboxes_from_radius_km(0.0, 0.0, 100.0)[0]+ polar_box = aoi.bboxes_from_radius_km(85.0, 0.0, 100.0)[0]eq_lomin, eq_lomax = (float(equator_box.split(",")[1]),float(equator_box.split(",")[3]),@@ -73,11 +73,11 @@ def test_bbox_from_radius_km_widens_at_low_latitude_and_narrows_near_pole() -> Nassert (pl_lomax - pl_lomin) > (eq_lomax - eq_lomin)-def test_bbox_from_radius_km_clamps_to_valid_ranges() -> None:- box = aoi.bbox_from_radius_km(89.5, 179.5, 2000.0)- lamin, lomin, lamax, lomax = (float(x) for x in box.split(","))- assert -90.0 <= lamin <= lamax <= 90.0- assert -180.0 <= lomin <= lomax <= 180.0+def test_bboxes_stay_within_valid_ranges() -> None:+ for box in aoi.bboxes_from_radius_km(89.5, 179.5, 2000.0):+ lamin, lomin, lamax, lomax = (float(x) for x in box.split(","))+ assert -90.0 <= lamin <= lamax <= 90.0+ assert -180.0 <= lomin <= lomax <= 180.0def test_filter_by_radius_includes_near_excludes_far() -> None:@@ -636,3 +636,722 @@ def test_aoi_store_instantiated_from_cache_db_path() -> None:WORLD_INTEL_CACHE_DB or the tempdir fallback)."""text = _SERVER_PY.read_text()assert "_aoi_store = aoi.AOIStore(cache.db_path)" in text+++# ---------------------------------------------------------------------------+# Antimeridian-aware bounding boxes (v0.4 geofence hardening)+# ---------------------------------------------------------------------------+++def test_bboxes_single_box_away_from_dateline() -> None:+ boxes = aoi.bboxes_from_radius_km(_PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ assert len(boxes) == 1+ lamin, lomin, lamax, lomax = (float(x) for x in boxes[0].split(","))+ assert lamin < _PGH_LAT < lamax+ assert lomin < _PGH_LON < lomax+++def test_bboxes_split_when_circle_crosses_dateline_eastward() -> None:+ """An AOI at lon 179.5 with a 200 km radius extends past +180; the+ old single-box clamp silently cut off everything on the far side of+ the dateline. Two boxes must now cover both sides."""+ boxes = aoi.bboxes_from_radius_km(52.0, 179.5, 200.0)+ assert len(boxes) == 2+ parsed = [tuple(float(x) for x in b.split(",")) for b in boxes]+ for lamin, lomin, lamax, lomax in parsed:+ assert -180.0 <= lomin <= lomax <= 180.0+ assert -90.0 <= lamin <= lamax <= 90.0+ # One box ends at +180, the other starts at -180.+ assert any(lomax == 180.0 for _, _, _, lomax in parsed)+ assert any(lomin == -180.0 for _, lomin, _, _ in parsed)+ # A point just across the dateline (~35 km away) is inside some box.+ assert any(+ lomin <= -179.9 <= lomax and lamin <= 52.0 <= lamax+ for lamin, lomin, lamax, lomax in parsed+ )+++def test_bboxes_split_when_circle_crosses_dateline_westward() -> None:+ boxes = aoi.bboxes_from_radius_km(-17.7, -179.5, 300.0)+ assert len(boxes) == 2+ parsed = [tuple(float(x) for x in b.split(",")) for b in boxes]+ # A point just west of the dateline (Fiji side) is inside some box.+ assert any(+ lomin <= 179.9 <= lomax and lamin <= -17.7 <= lamax+ for lamin, lomin, lamax, lomax in parsed+ )+++def test_bboxes_full_longitude_band_near_pole() -> None:+ """When the longitude half-width reaches 180 degrees the circle rings+ the pole; one full-longitude box, not two overlapping ones."""+ boxes = aoi.bboxes_from_radius_km(89.0, 10.0, 1500.0)+ assert len(boxes) == 1+ _, lomin, _, lomax = (float(x) for x in boxes[0].split(","))+ assert lomin == -180.0+ assert lomax == 180.0+++def test_overlapping_wildfire_regions_across_dateline() -> None:+ """An AOI just EAST of the dateline near Fiji reaches across into the+ oceania FIRMS box (which ends at lon 180). The old clamped math found+ no overlap and reported a false 'no FIRMS coverage' gap."""+ regions = aoi._overlapping_wildfire_regions(-17.7, -179.5, 300.0)+ assert "oceania" in regions+++# ---------------------------------------------------------------------------+# Great-circle segment distance (pipelines and cables as lines, not points)+# ---------------------------------------------------------------------------+++def test_segment_distance_abeam_midpoint() -> None:+ # 1 degree of latitude abeam an equatorial segment: ~111.19 km.+ d = aoi.segment_distance_km(1.0, 0.0, 0.0, -1.0, 0.0, 1.0)+ assert d == pytest.approx(111.19, rel=0.01)+++def test_segment_distance_clamps_beyond_end() -> None:+ """A point past the far endpoint on the same great circle is NOT at+ distance 0 (the infinite-great-circle answer); it is at the distance+ to the endpoint."""+ d = aoi.segment_distance_km(0.0, 20.0, 0.0, 0.0, 0.0, 10.0)+ assert d == pytest.approx(aoi.haversine_km(0.0, 20.0, 0.0, 10.0), rel=1e-6)+ assert d > 1000+++def test_segment_distance_clamps_before_start() -> None:+ d = aoi.segment_distance_km(0.0, -10.0, 0.0, 0.0, 0.0, 10.0)+ assert d == pytest.approx(aoi.haversine_km(0.0, -10.0, 0.0, 0.0), rel=1e-6)+++def test_segment_distance_degenerate_segment() -> None:+ d = aoi.segment_distance_km(1.0, 1.0, 40.0, -80.0, 40.0, -80.0)+ assert d == pytest.approx(aoi.haversine_km(1.0, 1.0, 40.0, -80.0), rel=1e-6)+++def test_segment_distance_across_dateline() -> None:+ d = aoi.segment_distance_km(1.0, 180.0, 0.0, 179.0, 0.0, -179.0)+ assert d == pytest.approx(111.19, rel=0.01)+++def test_nearby_pipelines_detects_midspan_crossing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The load-bearing improvement: a pipeline whose midspan passes+ through the AOI but whose endpoints are both far away was invisible+ to the old endpoint-only proximity check."""+ from world_intel_mcp.config import geospatial as geo_cfg++ monkeypatch.setattr(+ geo_cfg,+ "PIPELINES",+ [+ {+ "name": "Test Midspan Line",+ "route": "A-B",+ "type": "oil",+ "status": "operational",+ "lat_start": 0.0,+ "lon_start": -5.0,+ "lat_end": 0.0,+ "lon_end": 5.0,+ }+ ],+ )+ # AOI center 0.5 deg (~55.6 km) abeam the midspan; endpoints ~558 km away.+ result = aoi.nearby_pipelines(0.5, 0.0, 100.0)+ names = [p["name"] for p in result]+ assert "Test Midspan Line" in names+ assert result[0]["distance_km"] == pytest.approx(55.6, rel=0.02)+++def test_nearby_cables_detects_midspan_crossing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from world_intel_mcp.config import cables as cables_cfg++ monkeypatch.setattr(+ cables_cfg,+ "UNDERSEA_CABLES",+ [+ {+ "name": "Test Midspan Cable",+ "status": "active",+ "landing_points": [+ {"name": "West End", "lat": 0.0, "lon": -5.0},+ {"name": "East End", "lat": 0.0, "lon": 5.0},+ ],+ }+ ],+ )+ result = aoi.nearby_cables(0.5, 0.0, 100.0)+ assert any(c["name"] == "Test Midspan Cable" for c in result)+ assert result[0]["distance_km"] == pytest.approx(55.6, rel=0.02)+ # The nearest published landing point is still reported for context.+ assert result[0]["nearest_landing_point"] in {"West End", "East End"}+++def test_nearby_pipelines_still_finds_endpoint_proximity() -> None:+ # TAPS endpoint at Valdez must keep matching (regression guard).+ result = aoi.nearby_pipelines(61.13, -146.35, 5.0)+ assert "Trans-Alaska (TAPS)" in [p["name"] for p in result]+++# ---------------------------------------------------------------------------+# AOIStore.update / update_aoi tool+# ---------------------------------------------------------------------------+++def test_update_aoi_radius_only(store: AOIStore) -> None:+ aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ result = aoi.update_aoi(store, "Pittsburgh", radius_km=120.0)+ assert "error" not in result+ assert result["aoi"]["radius_km"] == 120.0+ assert result["aoi"]["lat"] == _PGH_LAT+ assert result["previous"]["radius_km"] == _PGH_RADIUS_KM+ assert store.get("Pittsburgh")["radius_km"] == 120.0+++def test_update_aoi_rename(store: AOIStore) -> None:+ aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ result = aoi.update_aoi(store, "Pittsburgh", new_name="Steel City")+ assert "error" not in result+ assert store.get("Pittsburgh") is None+ assert store.get("Steel City")["lat"] == _PGH_LAT+++def test_update_aoi_rename_collision_rejected(store: AOIStore) -> None:+ aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ aoi.define_aoi(store, "Austin", 30.27, -97.74, 40.0)+ result = aoi.update_aoi(store, "Pittsburgh", new_name="austin")+ assert "error" in result+ assert store.get("Pittsburgh") is not None+++def test_update_aoi_case_change_rename_of_itself_allowed(store: AOIStore) -> None:+ aoi.define_aoi(store, "pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ result = aoi.update_aoi(store, "pittsburgh", new_name="Pittsburgh")+ assert "error" not in result+ assert store.get("Pittsburgh")["name"] == "Pittsburgh"+++def test_update_aoi_not_found(store: AOIStore) -> None:+ assert "error" in aoi.update_aoi(store, "Nowhere", radius_km=10.0)+++def test_update_aoi_no_fields_is_an_error(store: AOIStore) -> None:+ aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ assert "error" in aoi.update_aoi(store, "Pittsburgh")+++def test_update_aoi_invalid_merged_params_rejected(store: AOIStore) -> None:+ aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ result = aoi.update_aoi(store, "Pittsburgh", lat=95.0)+ assert "error" in result+ assert store.get("Pittsburgh")["lat"] == _PGH_LAT+++# ---------------------------------------------------------------------------+# fetch_aoi_changes: geofence change detection (enter/leave since last check)+# ---------------------------------------------------------------------------+++async def test_aoi_changes_first_run_is_baseline(+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_all_domains(monkeypatch)+ result = await aoi.fetch_aoi_changes(+ fetcher, aoi_store_with_pittsburgh, "Pittsburgh"+ )+ assert result["baseline"] is True+ # A baseline run must not claim anything entered or left.+ for domain_changes in result["changes"].values():+ assert domain_changes["new"] == []+ assert domain_changes["departed"] == []+++async def test_aoi_changes_detects_new_and_departed(+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_all_domains(monkeypatch)+ await aoi.fetch_aoi_changes(fetcher, aoi_store_with_pittsburgh, "Pittsburgh")++ # Second sweep: quake near1 is gone, near2 appeared; military unchanged.+ async def _second_earthquakes(fetcher, **kwargs):+ return {+ "earthquakes": [+ {+ "id": "near2",+ "magnitude": 4.1,+ "place": "near Pittsburgh again",+ "time": "2026-08-16T02:00:00Z",+ "latitude": _NEAR_LAT,+ "longitude": _NEAR_LON,+ "url": "https://earthquake.usgs.gov/near2",+ }+ ],+ "count": 1,+ "source": "usgs",+ }++ monkeypatch.setattr(seismology, "fetch_earthquakes", _second_earthquakes)+ result = await aoi.fetch_aoi_changes(+ fetcher, aoi_store_with_pittsburgh, "Pittsburgh"+ )++ assert result["baseline"] is False+ eq = result["changes"]["earthquakes"]+ assert [i["key"] for i in eq["new"]] == ["near2"]+ assert [i["key"] for i in eq["departed"]] == ["near1"]+ mil = result["changes"]["military_flights"]+ assert mil["new"] == []+ assert mil["departed"] == []+ assert mil["unchanged"] == 1+++async def test_aoi_changes_error_domain_reports_gap_not_departures(+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The honesty invariant: a failed fetch must never read as 'everything+ left the area'. The domain goes to data_gaps, its diff is skipped, and+ its baseline slice survives for the next successful run."""+ _patch_all_domains(monkeypatch)+ await aoi.fetch_aoi_changes(fetcher, aoi_store_with_pittsburgh, "Pittsburgh")++ async def _broken_earthquakes(fetcher, **kwargs):+ return {"error": "USGS unavailable"}++ monkeypatch.setattr(seismology, "fetch_earthquakes", _broken_earthquakes)+ result = await aoi.fetch_aoi_changes(+ fetcher, aoi_store_with_pittsburgh, "Pittsburgh"+ )+ assert any("Earthquakes" in gap for gap in result["data_gaps"])+ assert "earthquakes" not in result["changes"]++ # Recovery run: the original quake is still there; nothing new or+ # departed versus the PRE-ERROR baseline.+ monkeypatch.setattr(seismology, "fetch_earthquakes", _fake_earthquakes)+ result = await aoi.fetch_aoi_changes(+ fetcher, aoi_store_with_pittsburgh, "Pittsburgh"+ )+ eq = result["changes"]["earthquakes"]+ assert eq["new"] == []+ assert eq["departed"] == []+ assert eq["unchanged"] == 1+++async def test_aoi_changes_aviation_excluded_from_diff(+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The 1-in-10 aviation sample is pure churn between sweeps; diffing+ it would manufacture fake enter/leave events every run."""+ _patch_all_domains(monkeypatch)+ result = await aoi.fetch_aoi_changes(+ fetcher, aoi_store_with_pittsburgh, "Pittsburgh"+ )+ assert "aviation" not in result["changes"]+++async def test_aoi_changes_not_found(fetcher, store: AOIStore) -> None:+ result = await aoi.fetch_aoi_changes(fetcher, store, "Nowhere")+ assert "error" in result+++def test_geometry_update_drops_snapshot(store: AOIStore) -> None:+ """Moving or resizing an AOI invalidates its change baseline: the old+ snapshot described a different piece of the planet."""+ aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ store.save_snapshot("Pittsburgh", {"earthquakes": {"near1": "M3.2"}})+ aoi.update_aoi(store, "Pittsburgh", radius_km=500.0)+ assert store.get_snapshot("Pittsburgh") is None+++def test_rename_migrates_snapshot(store: AOIStore) -> None:+ aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ store.save_snapshot("Pittsburgh", {"earthquakes": {"near1": "M3.2"}})+ aoi.update_aoi(store, "Pittsburgh", new_name="Steel City")+ snap = store.get_snapshot("Steel City")+ assert snap is not None+ assert snap["domains"]["earthquakes"] == {"near1": "M3.2"}+++def test_delete_aoi_also_deletes_snapshot(store: AOIStore) -> None:+ aoi.define_aoi(store, "Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ store.save_snapshot("Pittsburgh", {"earthquakes": {"near1": "M3.2"}})+ store.delete("Pittsburgh")+ assert store.get_snapshot("Pittsburgh") is None+++# ---------------------------------------------------------------------------+# New tool registration parity+# ---------------------------------------------------------------------------+++ "tool_name,fn_name",+ [+ ("intel_aoi_update", "aoi.update_aoi"),+ ("intel_aoi_changes", "aoi.fetch_aoi_changes"),+ ],+)+def test_new_aoi_tools_registered_and_dispatched(tool_name: str, fn_name: str) -> None:+ text = _SERVER_PY.read_text()+ assert f'name="{tool_name}"' in text+ dispatch_idx = text.index(f'case "{tool_name}":')+ dispatch_body = text[dispatch_idx : dispatch_idx + 300]+ assert fn_name in dispatch_body+++# ---------------------------------------------------------------------------+# Coverage completion for the v0.4 geofence edges. Deliberately NOT hit,+# as defensive guards unreachable through the public paths that wrap them:+# the non-dict continue in _fetch_military_merged (its inputs pass through+# _safe_fetch, which always yields a dict).+# ---------------------------------------------------------------------------+++def test_segment_distance_perpendicular_pole() -> None:+ # P at the pole, equatorial segment: cross-track is exactly 90 deg,+ # cos(xt) ~ 0, exercising the polar guard; distance is a quarter+ # circumference (~10,007 km).+ d = aoi.segment_distance_km(90.0, 0.0, 0.0, -10.0, 0.0, 10.0)+ assert d == pytest.approx(10007, rel=0.01)+++def test_store_update_missing_aoi_raises() -> None:+ import tempfile as _tf++ s = AOIStore(Path(_tf.mkdtemp()) / "kx.db")+ try:+ with pytest.raises(KeyError):+ s.update("Nowhere", radius_km=10.0)+ finally:+ s.close()+++def test_get_snapshot_with_corrupt_json_returns_none(store: AOIStore) -> None:+ store.define("Pittsburgh", _PGH_LAT, _PGH_LON, _PGH_RADIUS_KM)+ store._conn.execute(+ "INSERT OR REPLACE INTO aoi_snapshots (name_key, taken_at, snapshot) "+ "VALUES ('pittsburgh', 0, 'not json')"+ )+ store._conn.commit()+ assert store.get_snapshot("Pittsburgh") is None++[email protected]("bad_name", [123, "", " ", None])+def test_name_validation_across_tools(bad_name, store: AOIStore, fetcher) -> None:+ assert "error" in aoi.delete_aoi(store, bad_name)+ assert "error" in aoi.update_aoi(store, bad_name, radius_km=10.0)++[email protected]("bad_name", [123, " "])+async def test_name_validation_async_tools(bad_name, store: AOIStore, fetcher) -> None:+ assert "error" in await aoi.fetch_aoi_brief(fetcher, store, bad_name)+ assert "error" in await aoi.fetch_aoi_escalation(fetcher, store, bad_name)+ assert "error" in await aoi.fetch_aoi_changes(fetcher, store, bad_name)+++def test_nearby_pipelines_endpoint_fallback_on_partial_coords(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A pipeline missing one endpoint's coordinates can't be treated as+ a segment; it falls back to whichever endpoint is placeable."""+ from world_intel_mcp.config import geospatial as geo_cfg++ monkeypatch.setattr(+ geo_cfg,+ "PIPELINES",+ [+ {+ "name": "Half-Mapped Line",+ "lat_start": None,+ "lon_start": None,+ "lat_end": 0.0,+ "lon_end": 0.0,+ },+ {"name": "Unmappable Line"},+ ],+ )+ result = aoi.nearby_pipelines(0.2, 0.0, 100.0)+ names = [p["name"] for p in result]+ assert "Half-Mapped Line" in names+ assert "Unmappable Line" not in names+++def test_nearby_cables_skips_unplaceable_landing_points(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from world_intel_mcp.config import cables as cables_cfg++ monkeypatch.setattr(+ cables_cfg,+ "UNDERSEA_CABLES",+ [+ {+ "name": "Patchy Cable",+ "status": "active",+ "landing_points": [+ {"name": "Ghost", "lat": None, "lon": None},+ {"name": "Bad", "lat": "not-a-number", "lon": "x"},+ {"name": "Real", "lat": 0.0, "lon": 0.0},+ ],+ }+ ],+ )+ result = aoi.nearby_cables(0.2, 0.0, 100.0)+ assert result[0]["name"] == "Patchy Cable"+ assert result[0]["nearest_landing_point"] == "Real"+++def test_wildfire_region_dedup_when_both_boxes_overlap_one_region(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """No real FIRMS region spans the dateline today; patch one that does+ so the both-boxes-same-region dedup guard is exercised."""+ from world_intel_mcp.sources import wildfire++ monkeypatch.setattr(wildfire, "REGIONS", {"global": "-180,-90,180,90"})+ regions = aoi._overlapping_wildfire_regions(52.0, 179.9, 300.0)+ assert regions == ["global"]+++async def test_wildfires_for_aoi_all_regions_error_and_non_dict(+ fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ calls = {"n": 0}++ async def _flaky_wildfires(fetcher, region=None):+ calls["n"] += 1+ if calls["n"] == 1:+ return "not-a-dict"+ return {"error": f"FIRMS down for {region}"}++ monkeypatch.setattr(wildfire, "fetch_wildfires", _flaky_wildfires)+ result = await aoi._fetch_wildfires_for_aoi(+ fetcher, ["north_america", "europe", "africa"]+ )+ assert "FIRMS down" in result["error"]+++async def test_safe_fetch_catches_raising_coroutine(fetcher) -> None:+ async def _boom():+ raise RuntimeError("upstream exploded")++ result = await aoi._safe_fetch(_boom(), "boom")+ assert result == {"error": "upstream exploded"}+++async def test_brief_data_gaps_for_eq_military_aviation_and_titleless_news(+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_all_domains(monkeypatch)++ async def _err(fetcher, **kwargs):+ return {"error": "backend down"}++ async def _titleless_gdelt(fetcher, **kwargs):+ return {"articles": [{"url": "https://x.example/1", "title": ""}], "count": 1}++ monkeypatch.setattr(seismology, "fetch_earthquakes", _err)+ monkeypatch.setattr(military, "fetch_military_flights", _err)+ monkeypatch.setattr(aviation, "fetch_domestic_flights", _err)+ monkeypatch.setattr(news, "fetch_gdelt_search", _titleless_gdelt)++ result = await aoi.fetch_aoi_brief(fetcher, aoi_store_with_pittsburgh, "Pittsburgh")+ gaps = " | ".join(result["data_gaps"])+ assert "Earthquakes" in gaps+ assert "Military flights" in gaps+ assert "Aviation" in gaps+ # The titleless article is counted but produces no citation line.+ assert result["counts"]["news"] == 1+ assert not any(s["domain"] == "news" for s in result["sources"])+++def dateline_store(tmp_path: Path) -> AOIStore:+ s = AOIStore(tmp_path / "dateline.db")+ # Two bounding boxes (crosses lon 180).+ s.define("Bering", 52.0, 179.8, 200.0)+ yield s+ s.close()+++def _per_bbox_military(fail_boxes: set[int]):+ """Fake military fetch that errors for chosen box indexes and+ returns one duplicated + one unique aircraft otherwise."""+ seen: list[str] = []++ async def _fake(fetcher, bbox=None):+ seen.append(bbox)+ idx = len(seen) - 1+ if idx in fail_boxes:+ return {"error": f"box {idx} upstream down"}+ return {+ "aircraft": [+ {+ "icao24": "dup001",+ "callsign": "RCH777",+ "origin_country": "United States",+ "latitude": 52.0,+ "longitude": 179.9,+ },+ {+ "icao24": f"uniq{idx}",+ "callsign": f"RCH{idx}",+ "origin_country": "United States",+ "latitude": 52.0,+ "longitude": -179.95,+ },+ ]+ }++ _fake.seen = seen+ return _fake+++async def test_dateline_brief_merges_boxes_and_dedupes(+ fetcher, dateline_store: AOIStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_all_domains(monkeypatch)+ fake = _per_bbox_military(fail_boxes=set())+ monkeypatch.setattr(military, "fetch_military_flights", fake)++ result = await aoi.fetch_aoi_brief(fetcher, dateline_store, "Bering")++ assert len(fake.seen) == 2, "a dateline AOI must query both boxes"+ # dup001 counted once, uniq0 and uniq1 both in range: 3 aircraft.+ assert result["counts"]["military_flights"] == 3+++async def test_dateline_brief_partial_coverage_gap(+ fetcher, dateline_store: AOIStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_all_domains(monkeypatch)+ monkeypatch.setattr(+ military, "fetch_military_flights", _per_bbox_military(fail_boxes={1})+ )++ result = await aoi.fetch_aoi_brief(fetcher, dateline_store, "Bering")++ assert any("partial coverage" in g for g in result["data_gaps"])+ # The surviving box still contributes aircraft.+ assert result["counts"]["military_flights"] == 2+++async def test_dateline_escalation_partial_coverage_and_battle_count(+ fetcher, dateline_store: AOIStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def _battle_acled(fetcher, **kwargs):+ return {+ "events": [+ {+ "event_type": "Battles",+ "location": "Near Bering",+ "event_date": "2026-08-31",+ "latitude": 52.0,+ "longitude": 179.9,+ "fatalities": 3,+ }+ ]+ }++ monkeypatch.setattr(conflict, "fetch_acled_events", _battle_acled)+ monkeypatch.setattr(+ military, "fetch_military_flights", _per_bbox_military(fail_boxes={0})+ )++ result = await aoi.fetch_aoi_escalation(fetcher, dateline_store, "Bering")++ assert any("partial coverage" in g for g in result["data_gaps"])+ # One battle with 3 fatalities: conflict component = 1*0.5 + 3*0.1.+ assert result["components"]["conflict"] == pytest.approx(0.8)+++async def test_dateline_changes_partial_coverage(+ fetcher, dateline_store: AOIStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_all_domains(monkeypatch)+ monkeypatch.setattr(+ military, "fetch_military_flights", _per_bbox_military(fail_boxes={1})+ )++ result = await aoi.fetch_aoi_changes(fetcher, dateline_store, "Bering")++ assert any("partial coverage" in g for g in result["data_gaps"])+ # No FIRMS region reaches this stretch of the Bering; the honest gap.+ assert any("Wildfires" in g for g in result["data_gaps"])+ assert "wildfires" not in result["changes"]+++async def test_changes_drops_unkeyable_item_keeps_placeable(+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ """An item whose key function raises (unparseable coordinates in a+ wildfire cluster that slipped past the radius filter's own guard)+ is dropped from the diff, not allowed to poison the sweep."""+ _patch_all_domains(monkeypatch)++ real_filter = aoi.filter_by_radius++ def _leaky_filter(+ items, lat, lon, radius_km, lat_key="latitude", lon_key="longitude"+ ):+ kept = real_filter(items, lat, lon, radius_km, lat_key, lon_key)+ # Simulate a malformed item surviving into the scoped list.+ leak = [i for i in items if i.get("fire_count") == 99]+ return kept + leak++ async def _wildfires_with_bad_cluster(fetcher, region=None):+ return {+ "fires_by_region": {+ region: {+ "top_clusters": [+ {"lat": _NEAR_LAT, "lon": _NEAR_LON, "fire_count": 2},+ {"lat": "bad", "lon": None, "fire_count": 99},+ ]+ }+ }+ }++ monkeypatch.setattr(wildfire, "fetch_wildfires", _wildfires_with_bad_cluster)+ monkeypatch.setattr(aoi, "filter_by_radius", _leaky_filter)++ result = await aoi.fetch_aoi_changes(+ fetcher, aoi_store_with_pittsburgh, "Pittsburgh"+ )++ # The malformed cluster is dropped by the key function guard; only+ # the placeable one is counted.+ assert result["counts"]["wildfires"] == 1+++async def test_escalation_reports_gap_when_acled_fails(+ fetcher, aoi_store_with_pittsburgh: AOIStore, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def _broken_acled(fetcher, **kwargs):+ return {"error": "ACLED down"}++ monkeypatch.setattr(conflict, "fetch_acled_events", _broken_acled)+ monkeypatch.setattr(military, "fetch_military_flights", _fake_military)++ result = await aoi.fetch_aoi_escalation(+ fetcher, aoi_store_with_pittsburgh, "Pittsburgh"+ )+ assert any("Conflict events" in g for g in result["data_gaps"])