Skip to content

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.

fix(aoi): escalation reads outages, stale copies and capped samples as missing

Phoenix Agent (mac-studio)44cbfba923a9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a08f2cd..335fa4d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,39 +5,87 @@
### Added: AOI escalation news and convergence components
- `intel_aoi_escalation` now scores the news and convergence components it
used to report as null (ROADMAP Phase 23).
-- News: the rise in the area's share of all GDELT coverage over the last 7
- days against the 7 days before, for the reverse-geocoded settlement and
- county (the query the AOI brief already uses, sent as `timelinevolraw`).
- Expected articles = prior share x current GDELT volume; change_pct =
- 100 x (current - expected) / max(expected, 20); component =
- min(20, 0.2 x max(0, change_pct)). Shares rather than raw counts because
- GDELT's own intake has multi-day outages (measured 2026-10-17 for
- Pittsburgh: no data for 16 of 85 days), which raw counts would read as a
- surge on recovery; a comparison where one week monitored under half the
- other's volume is refused as a data gap. An area that cannot be
- geocoded is not scored, rather than searched by the AOI's name.
+- News: the change in the area's share of all GDELT coverage, the 7 days
+ ending with GDELT's current daily step (still filling;
+ `current_step_elapsed` says how far) against the 7 days before, for the
+ reverse-geocoded settlement and county at the AOI's centre (the query
+ the AOI brief already uses, sent as `timelinevolraw`). Expected articles
+ = prior share x current GDELT volume; change_pct = 100 x (current -
+ expected) / max(expected, 20); component = min(20, 0.2 x max(0,
+ change_pct)). Shares rather than raw counts because GDELT's own intake
+ has multi-day outages (measured 2026-10-17 for Pittsburgh: no data for
+ 16 of 85 days), which raw counts would read as a surge on recovery; a
+ comparison where one week monitored under half the other's volume is
+ refused as a data gap. An area that cannot be geocoded is not scored,
+ rather than searched by the AOI's name. An AOI reaching more than 50 km
+ from its centre, or a polygon or corridor whose centre cannot be
+ placed, gets a data gap saying the query covers only the centre's place.
- Convergence: `analysis/convergence.py`, unmodified, over the
earthquakes, military flights, ACLED events and wildfires inside the
AOI's exact shape (circle, polygon or corridor, through the same
- `filter_by_aoi` scoping as the brief). With an input missing, a
- convergent cell is reported as a lower bound; no cell at all is null,
- because quiet cannot be told from missing.
+ `filter_by_aoi` scoping as the brief). The 1-degree grid is laid at four
+ half-degree offsets and the strongest cell is used, so a cluster
+ spanning under half a degree in latitude and in longitude is never
+ split on a degree line (one spanning 0.5 to 1 degree still can be).
+ With an input failed or partial, a convergent cell is reported as a
+ lower bound; no cell at all is null, because quiet cannot be told from
+ missing.
+- An input that did not answer counts as missing, never as quiet: a USGS
+ or FIRMS outage, a military answer from neither adsb.lol nor OpenSky
+ (`source: "none"`), and an expired cached copy served in place of a
+ fresh answer (USGS, ACLED, GDELT, FIRMS), which is refused with the
+ copy's age named in `data_gaps`. A global sample that reached its cap
+ (USGS newest 50, ACLED 100 worldwide, FIRMS 20 largest clusters per
+ region) counts as partial coverage.
- New response keys; existing keys keep their meaning. `computed_from`
- names the components the score was computed from, and
+ names the components the score was computed from,
`zero_filled_components` the ones among them that are a 0 only because
the military or ACLED fetch failed (`score_hotspot` takes no null for
- those, unchanged); `news_signal` (query, both windows' counts and
- shares, change), `news_scoping` and `convergence_signal` (cells, events
- per domain, inputs used, failed or partial) carry the working. A failed
- news or convergence input makes that component null in `components`,
- listed in `unavailable_components` and explained in `data_gaps`, never
- a 0.
+ those, unchanged), and `lower_bound_components` the ones partial data
+ can only have understated. An AOI has no curated baseline, so the score
+ tops out at 80; `score_ceiling` is the highest score reachable with the
+ components this call measured (a zero-filled one held at 0) and
+ `score_method` the formula.
+ `news_signal` (query, fetch time, both windows' counts and shares,
+ change), `news_scoping` and `convergence_signal` (cells, grid offset,
+ events per domain, inputs used, failed or partial, each domain's window
+ and fetch time) carry the working. A failed news or convergence input
+ makes that component null in `components`, listed in
+ `unavailable_components` and explained in `data_gaps`, never a 0.
+
+### Fixed
+- `fetch_earthquakes` and `fetch_wildfires` mark a failed fetch (`error`,
+ `degraded`, `reason`; per region for FIRMS, with `failed_regions` and,
+ when other regions answered, `partial_errors`) instead of answering a
+ well-formed empty. Their list keys stay, so callers that do not check
+ still iterate an empty list.
+- `fetch_earthquakes`, `fetch_wildfires` (per region), `fetch_acled_events`
+ and `fetch_gdelt_search` keep the fetcher's `_stale` /
+ `_stale_age_seconds` marks on an expired cached copy and report
+ `fetched_at`, when upstream answered: a cached answer reports its
+ original fetch, not the time it was served.
+- `fetch_gdelt_search`'s cache key holds a digest of every request
+ parameter. The old key reduced a non-Latin query to underscores, so
+ "Київ" and "Суми" shared one entry and one AOI was scored on the other's
+ timeline. The USGS and ACLED keys now hold the result limit, so a short
+ answer cached for one caller is not served to another as complete.
+- The FIRMS docstring states what the request asks for: a day range of 2
+ (FIRMS's two most recent days), not the last 24 hours.
+- A reverse-geocoding failure no longer repeats its prefix ("Reverse
+ geocoding failed: Reverse geocoding unavailable: ...").
### Changed
- The escalation also fetches earthquakes and wildfires (convergence
inputs) and one GDELT timeline, in parallel with ACLED and military
flights; their failures are named in `data_gaps`. The brief, the change
- sweep and the escalation now share one AOI scoping helper.
+ sweep and the escalation now share one AOI scoping helper, which reads
+ an answer without its list (an unrecognized shape) as unknown rather
+ than as an empty area, and names a failed FIRMS region next to answered
+ ones. The brief's aviation section reads a `sampled` list the
+ domestic-flights source does not return, so it now reports that as a
+ data gap where it used to show 0 aircraft.
+- `intel aoi escalation` prints a zero-filled component as not measured,
+ marks lower bounds, and shows the score ceiling and `computed_from`.
- `test_aoi.py` stubs every network-bound source by default: its older
escalation tests stub only ACLED and military flights and would
otherwise reach Nominatim, GDELT, USGS and FIRMS live.
diff --git a/README.md b/README.md
index 026624e..d49308e 100644
--- a/README.md
+++ b/README.md
@@ -571,17 +571,26 @@ instead of silently omitting it.
`intel_aoi_escalation` runs the same baseline/military/conflict/social-
unrest scoring engine that powers `intel_hotspot_escalation` for the 22
built-in hotspots, but scoped to your AOI's own radius instead of a fixed
-2-degree window. It also scores the two components the built-ins leave
-null. News is the rise in the area's share of all GDELT coverage over the
-last 7 days against the 7 before, for the reverse-geocoded place (the
-same query the brief uses), so a swing or outage in what GDELT ingests is
-not read as a news surge. Convergence runs the multi-domain convergence
-grid over the earthquakes, military flights, ACLED events and wildfires
-inside the AOI's exact shape. If either one's inputs fail, it comes back
-null with the reason in `data_gaps`, never as a 0, and `computed_from`
-names the components the score was computed from
-(`zero_filled_components` flags any that are a 0 only because the
-military or ACLED fetch failed).
+2-degree window. An AOI has no curated baseline, so that component is 0
+and the score tops out at 80; `score_ceiling` gives this call's ceiling,
+lower when a component is missing or zero-filled. It also scores the two
+components the built-ins leave null. News is the change in the area's
+share of all GDELT coverage, the 7 days ending with GDELT's current
+(still filling) daily step against the 7 before, for the reverse-geocoded
+settlement and county at the AOI's centre (the same query the brief
+uses), so a swing or outage in what GDELT ingests is not read as a news
+surge; only a rise scores. Convergence runs the multi-domain convergence
+grid, laid at four half-degree offsets so a compact cluster on a degree
+line is not split, over the earthquakes, military flights, ACLED events
+and wildfires inside the AOI's exact shape. A source that did not answer,
+or answered only with an expired cached copy, counts as missing, never as
+quiet, and a global sample that hit its cap counts as partial. If either
+component's inputs fail, it comes back null with the reason in
+`data_gaps`, never as a 0, and `computed_from` names the components the
+score was computed from (`zero_filled_components` flags any that are a 0
+only because the military or ACLED fetch failed, and
+`lower_bound_components` any that partial data can only have
+understated).
AOIs persist in a dedicated table inside the same SQLite cache database
the server already uses (`~/.cache/world-intel-mcp/cache.db` by default,
diff --git a/ROADMAP.md b/ROADMAP.md
index 1c802ab..59e09f1 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -564,7 +564,7 @@ Ordered by value; numbers are proposals, not commitments.
| Polygon AOIs | 3-64 vertex shapes, dateline-aware, exact membership across brief/changes/escalation; DB migrates in place | :white_check_mark: Shipped in 0.5.0 (`intel_aoi_define_polygon`) |
| Corridor AOIs | Waypoint route + width; distances measured to the route | :white_check_mark: Shipped in 0.5.0 (`intel_aoi_define_corridor`) |
| AOI groups / watchlists | `intel_aoi_digest` sweeps all (or named) AOIs in one call, advancing snapshots | :white_check_mark: Shipped in 0.8.0 |
-| Escalation news + convergence components | `intel_aoi_escalation` reported null for news/convergence. News is now the rise in the geocoded place's share of all GDELT coverage, the last 7 days against the 7 before (`timelinevolraw` for the brief's settlement + county query), not name-mention counts: GDELT's own intake has multi-day outages (measured 2026-10-17 for Pittsburgh: no data for 16 of 85 days), which raw counts would read as a surge on recovery, so windows with uneven intake are refused as a data gap. Convergence runs `analysis/convergence.py` over the earthquakes, military flights, ACLED events and wildfires inside the AOI's exact shape. A failed news or convergence input makes that component null plus a `data_gaps` entry, never a 0; `computed_from` names the components behind the score | :white_check_mark: Shipped (Unreleased) |
+| Escalation news + convergence components | `intel_aoi_escalation` reported null for news/convergence. News is now the change in the geocoded place's share of all GDELT coverage, the 7 days ending with GDELT's current (still filling) daily step against the 7 before (`timelinevolraw` for the brief's settlement + county query), not name-mention counts: GDELT's own intake has multi-day outages (measured 2026-10-17 for Pittsburgh: no data for 16 of 85 days), which raw counts would read as a surge on recovery, so windows with uneven intake are refused as a data gap. Convergence runs `analysis/convergence.py` over the earthquakes, military flights, ACLED events and wildfires inside the AOI's exact shape, on four half-degree-offset grids. Outages and expired cached copies count as missing and capped global samples as partial; a failed news or convergence input makes that component null plus a `data_gaps` entry, never a 0; `computed_from` names the components behind the score | :white_check_mark: Shipped (Unreleased) |
| 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 in 0.10.0 |
| 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 | `/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 in 0.10.0 |
diff --git a/src/world_intel_mcp/analysis/aoi.py b/src/world_intel_mcp/analysis/aoi.py
index 77e8624..0ebe17b 100644
--- a/src/world_intel_mcp/analysis/aoi.py
+++ b/src/world_intel_mcp/analysis/aoi.py
@@ -1122,7 +1122,47 @@ async def _safe_fetch(coro, label: str) -> dict:
return {"error": str(exc)}
-async def _fetch_wildfires_for_aoi(fetcher, wildfire_regions: list[str]) -> dict:
+def _age_text(seconds: float) -> str:
+ if seconds < 3600:
+ return f"{seconds / 60:.0f} min"
+ if seconds < 2 * 86400:
+ return f"{seconds / 3600:.1f} h"
+ return f"{seconds / 86400:.1f} days"
+
+
+def _stale_copy_reason(subject: str, result: dict) -> str:
+ """Why an expired cached copy is not used: names the copy's age and
+ write time as this server's, never as the upstream's data gap."""
+ age = result.get("_stale_age_seconds")
+ age_text = _age_text(float(age)) if isinstance(age, (int, float)) else "an unknown time"
+ when = f" (at {result['fetched_at']})" if result.get("fetched_at") else ""
+ return (
+ f"no fresh {subject} (the request failed or its circuit breaker is "
+ f"open); the only copy on hand is one this server cached {age_text} "
+ f"ago{when}, so it is not scored as current"
+ )
+
+
+def _refuse_stale_copy(result: Any, subject: str) -> Any:
+ """An escalation input that is the fetcher's expired fallback copy
+ (``_stale``) becomes an outage that names the copy's age, so a days-old
+ answer never scores as current conditions."""
+ if isinstance(result, dict) and result.get("_stale"):
+ return {"error": _stale_copy_reason(subject, result), "stale_copy": True}
+ return result
+
+
+async def _fetch_wildfires_for_aoi(
+ fetcher, wildfire_regions: list[str], refuse_stale: bool = False
+) -> dict:
+ """FIRMS fire clusters from every continental region the AOI overlaps,
+ merged as ``{"clusters": [...]}``. ``error`` when no region answered
+ with a cluster and at least one failed (quiet cannot be told from
+ missing); a failed region next to answered ones is named in
+ ``partial_errors``. ``truncated_regions`` lists regions whose answer
+ kept only its largest clusters; ``fetched_at`` is the oldest answered
+ region's fetch time. With ``refuse_stale`` (the escalation score), a
+ region answered only by an expired cached copy counts as failed."""
from ..sources import wildfire
if not wildfire_regions:
@@ -1133,17 +1173,63 @@ async def _fetch_wildfires_for_aoi(fetcher, wildfire_regions: list[str]) -> dict
)
clusters: list[dict] = []
errors: list[str] = []
- for res in results:
+ truncated: list[dict] = []
+ fetched: list[str] = []
+ for region, res in zip(wildfire_regions, results):
if not isinstance(res, dict):
+ errors.append(f"the NASA FIRMS answer for {region} was not a dict")
continue
- if res.get("error"):
- errors.append(res["error"])
+ by_region = res.get("fires_by_region")
+ has_regions = isinstance(by_region, dict) and bool(by_region)
+ # A failed region names itself inside fires_by_region; the top-level
+ # error ("every requested region") is used only when none does.
+ if res.get("error") and not has_regions:
+ errors.append(str(res["error"]))
+ continue
+ if not has_regions:
+ errors.append(f"the NASA FIRMS answer for {region} carried no regions")
continue
- for region_data in res.get("fires_by_region", {}).values():
- clusters.extend(region_data.get("top_clusters", []))
+ for name, region_data in by_region.items():
+ if isinstance(region_data, dict) and region_data.get("error"):
+ errors.append(str(region_data["error"]))
+ continue
+ top = region_data.get("top_clusters") if isinstance(region_data, dict) else None
+ if not isinstance(top, list):
+ errors.append(f"the NASA FIRMS answer for {name} carried no cluster list")
+ continue
+ if refuse_stale and region_data.get("_stale"):
+ errors.append(
+ _stale_copy_reason(f"NASA FIRMS answer for {name}", region_data)
+ )
+ continue
+ clusters.extend(top)
+ total = region_data.get("cluster_count")
+ if isinstance(total, int) and not isinstance(total, bool):
+ cut = total > len(top)
+ else:
+ cut = len(top) >= wildfire.TOP_CLUSTERS_PER_REGION
+ if cut:
+ truncated.append(
+ {"region": name, "listed": len(top), "clusters": total}
+ )
+ if region_data.get("fetched_at"):
+ fetched.append(str(region_data["fetched_at"]))
if not clusters and errors:
return {"error": "; ".join(sorted(set(errors)))}
- return {"clusters": clusters}
+ out: dict[str, Any] = {"clusters": clusters}
+ if errors:
+ out["partial_errors"] = sorted(set(errors))
+ if truncated:
+ out["truncated_regions"] = truncated
+ if fetched:
+ out["fetched_at"] = min(fetched)
+ return out
+
+
+_MILITARY_NO_SOURCE = (
+ "no military flight source answered (adsb.lol failed or returned no "
+ "aircraft, and the OpenSky fallback failed)"
+)
async def _fetch_military_merged(fetcher, bboxes: list[str]) -> dict:
@@ -1153,7 +1239,10 @@ async def _fetch_military_merged(fetcher, bboxes: list[str]) -> dict:
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."""
+ instead of presenting half-coverage as full. A box whose answer is
+ ``source: "none"`` (adsb.lol gave no aircraft and the OpenSky
+ fallback failed), with or without an ``error`` key, failed: that
+ shape is an outage, not an empty sky."""
from ..sources import military
results = await asyncio.gather(
@@ -1174,8 +1263,14 @@ async def _fetch_military_merged(fetcher, bboxes: list[str]) -> dict:
if res.get("error"):
errors.append(str(res["error"]))
continue
+ if res.get("source") == "none":
+ errors.append(_MILITARY_NO_SOURCE)
+ continue
+ if not isinstance(res.get("aircraft"), list):
+ errors.append("the military flights answer carried no aircraft list")
+ continue
any_ok = True
- for ac in res.get("aircraft", []):
+ for ac in res["aircraft"]:
key = ac.get("icao24") or ac.get("callsign")
if key is not None:
if key in seen:
@@ -1218,10 +1313,15 @@ async def _aoi_news_query(fetcher, aoi_row: dict) -> tuple[str, dict]:
)
if isinstance(place_ctx, dict) and place_ctx.get("error"):
+ error = str(place_ctx["error"])
return aoi_name, {
"basis": "aoi_name",
"query": aoi_name,
- "reason": f"Reverse geocoding failed: {place_ctx['error']}",
+ "reason": (
+ error
+ if error.lower().startswith("reverse geocoding")
+ else f"Reverse geocoding failed: {error}"
+ ),
}
terms = place_ctx.get("terms") or [] if isinstance(place_ctx, dict) else []
@@ -1264,7 +1364,16 @@ def _scope_to_aoi(
fence."""
if isinstance(result, dict) and result.get("error"):
return {"error": str(result["error"])}
- items = result.get(list_key, []) if isinstance(result, dict) else []
+ items = result.get(list_key) if isinstance(result, dict) else None
+ if not isinstance(items, list):
+ # An unrecognized answer (``_safe_fetch`` turns a non-dict into {})
+ # says nothing about the area: unknown, not an empty fence.
+ return {
+ "error": (
+ f"the answer carried no {list_key} list, so what is inside "
+ "the area is unknown"
+ )
+ }
entry: dict[str, Any] = {"items": filter_by_aoi(items, aoi_row, lat_key, lon_key)}
if isinstance(result, dict) and result.get("partial_errors"):
entry["partial_errors"] = result["partial_errors"]
@@ -1455,6 +1564,8 @@ async def fetch_aoi_brief(fetcher, store: AOIStore, name: Any) -> dict:
counts["wildfires"] = 0
else:
fire_in_range = scoped["wildfires"]["items"]
+ for partial in scoped["wildfires"].get("partial_errors", []):
+ data_gaps.append(f"Wildfires: partial coverage: {partial}")
counts["wildfires"] = len(fire_in_range)
for fc in fire_in_range:
n = _add_source(
@@ -1634,18 +1745,36 @@ _NEWS_MIN_INTAKE_RATIO = 0.5
NEWS_METHOD = (
"GDELT DOC timelinevolraw for the geocoded place query (see "
- "news_scoping). Current window: the 7 days ending with GDELT's current "
- "time step, which may be partly filled; prior window: the 7 days before "
- "it. Share = matching articles / all articles GDELT monitored in the "
- "window. expected_articles = prior share x current monitored volume; "
- "change_pct = 100 x (current articles - expected) / max(expected, 20); "
- "news component = min(20, 0.2 x max(0, change_pct)), so a doubled share "
- "scores the full 20 (once 20 or more articles were expected) and a flat "
- "or falling one scores 0. Not scored when "
- "either window monitored under half the other's volume (GDELT ingestion "
- "gaps)."
+ "news_scoping): the settlement and county at the AOI's centre, so "
+ "coverage of other places inside a large area is not counted. Current "
+ "window: the 7 days ending with GDELT's current time step (a UTC day at "
+ "GDELT's default daily resolution), which is still filling: "
+ "current_step_elapsed is the fraction of it that has passed; a share is "
+ "unaffected by how much of the day GDELT has ingested so far, but any "
+ "time-of-day mix in a partial day is not measured. Prior window: the 7 "
+ "days before it. Share = matching articles / all articles GDELT "
+ "monitored in the window. expected_articles = prior share x current "
+ "monitored volume; change_pct = 100 x (current articles - expected) / "
+ "max(expected, 20); news component = min(20, 0.2 x max(0, change_pct)), "
+ "so a doubled share scores the full 20 (once 20 or more articles were "
+ "expected) and a flat or falling one scores 0. Not scored when either "
+ "window monitored under half the other's volume (GDELT ingestion gaps), "
+ "or when the only timeline on hand is an expired cached copy."
)
+# News is scoped to the settlement and county at the AOI's centre. Above
+# this bounding radius that place describes only part of the area, and
+# data_gaps says so. A judgment threshold (the README's worked example is
+# a 50 km circle around Pittsburgh), not a measured one.
+_NEWS_SCOPE_RADIUS_KM = 50.0
+
+# The escalation's global event feeds and the caps that make even a full
+# answer a sample: a list that reaches its cap is marked partial coverage.
+_QUAKE_WINDOW_HOURS = 72
+_QUAKE_SAMPLE_LIMIT = 50
+_ACLED_WINDOW_DAYS = 7
+_ACLED_SAMPLE_LIMIT = 100
+
# Convergence component: the geolocated domains whose in-fence events
# feed analysis/convergence.py, with their coordinate keys. Aviation is
# left out (a 1-in-10 sample of ordinary civil traffic is not a risk
@@ -1660,15 +1789,76 @@ _CONVERGENCE_GRID_DEGREES = 1.0
_CONVERGENCE_MIN_DOMAINS = 2
_CONVERGENCE_MIN_EVENTS = 3
+# The 1-degree grid laid four ways, shifted by half a cell in latitude,
+# longitude or both, as (lat, lon) offsets in degrees. A fixed grid splits
+# a compact cluster that straddles a degree line (the README's Pittsburgh
+# centre is 0.0041 degrees from -80). Any cluster spanning under half a
+# cell on both axes lies inside one cell of at least one of these grids
+# (z3-checked); the unshifted grid comes first so it wins ties.
+_CONVERGENCE_GRID_OFFSETS: tuple[tuple[float, float], ...] = (
+ (0.0, 0.0),
+ (0.0, 0.5),
+ (0.5, 0.0),
+ (0.5, 0.5),
+)
+
+# Names for the convergence domains in data_gaps prose.
+_CONVERGENCE_LABELS = {
+ "earthquakes": "earthquakes",
+ "military_flights": "military flights",
+ "conflict_events": "conflict events",
+ "wildfires": "wildfires",
+}
+
+# What each convergence domain covers: they share no common window.
+_CONVERGENCE_WINDOWS = {
+ "earthquakes": (
+ f"USGS M4.5+ quakes in the {_QUAKE_WINDOW_HOURS} h before the fetch, "
+ f"worldwide, newest first, at most {_QUAKE_SAMPLE_LIMIT}"
+ ),
+ "military_flights": (
+ "a live ADS-B snapshot (adsb.lol, OpenSky as fallback); the source "
+ "does not report when it fetched, so its fetched_at is null"
+ ),
+ "conflict_events": (
+ f"ACLED events dated in the {_ACLED_WINDOW_DAYS} days before the "
+ "fetch (by event date; ACLED publishes with a reporting lag), "
+ f"worldwide, at most {_ACLED_SAMPLE_LIMIT}"
+ ),
+ "wildfires": (
+ "NASA FIRMS VIIRS SNPP NRT detections for a day range of 2 (FIRMS's "
+ "two most recent days, not a rolling 24 h), the 20 largest "
+ "0.5-degree clusters per continental region"
+ ),
+}
+
CONVERGENCE_METHOD = (
"analysis/convergence.py detect_convergence over the events inside the "
"AOI's exact shape (filter_by_aoi) from earthquakes, military flights, "
"ACLED conflict events and wildfires: 1-degree grid, a cell converges "
"with events from at least 2 of those domains and at least 3 events, "
- "cell score = domains x (1 + sqrt(events)). Input = the strongest cell; "
- "convergence component = min(8, 2 x score), so any convergent cell "
- "(smallest possible score 5.46) earns the full 8. A cell's lat/lon is "
- "its grid-cell centre, which can lie outside a small AOI."
+ "cell score = domains x (1 + sqrt(events)). The grid is laid four ways, "
+ "shifted 0 or 0.5 degrees in latitude and in longitude (grid_offset_deg "
+ "names the one used; ties keep the unshifted grid), and input = the "
+ "strongest cell of any of them, so a cluster spanning under 0.5 degrees "
+ "in both latitude and longitude is never split; one spanning 0.5 to 1 "
+ "degree still can be. Convergence component = min(8, 2 x score), so any "
+ "convergent cell (smallest possible score 5.46) earns the full 8. A "
+ "cell's lat/lon is its grid-cell centre, which can lie outside a small "
+ "AOI. The four domains cover different windows (windows) and were "
+ "fetched at different times (fetched_at)."
+)
+
+SCORE_METHOD = (
+ "score_hotspot (analysis/escalation.py): capped components baseline 20, "
+ "news 20, military 20, conflict 20, social unrest 12 and convergence 8, "
+ "summed and renormalized to 0-100 over computed_from. An AOI has no "
+ "curated baseline, so baseline is a structural 0: the score can reach "
+ "80 when every component is measured (75 without news, 78.3 without "
+ "convergence, 72.2 without either); score_ceiling is this call's, with "
+ "any zero-filled component held at 0. "
+ "zero_filled_components are 0 only because their fetch failed; "
+ "lower_bound_components could only rise with the data that is missing."
)
@@ -1783,6 +1973,9 @@ def news_coverage_trend(timeline: Any, now: datetime | None = None) -> dict:
"window_days": NEWS_WINDOW_DAYS,
"step_seconds": int(step_s),
"latest_step": _iso(last),
+ # The step containing `now` is still filling: how far into it we are.
+ "current_step_start": _iso(current_step),
+ "current_step_elapsed": round((now - current_step) / step, 3),
"current_window": cur,
"prior_window": pri,
"method": NEWS_METHOD,
@@ -1820,21 +2013,68 @@ def news_coverage_trend(timeline: Any, now: datetime | None = None) -> dict:
return out
-def aoi_convergence(scoped: dict[str, dict]) -> dict:
+def _finite(value: Any) -> float | None:
+ try:
+ number = float(value)
+ except (TypeError, ValueError):
+ return None
+ return number if math.isfinite(number) else None
+
+
+def _grid_events(
+ events: list[dict], dlat: float, dlon: float, ref_lon: float | None
+) -> list[dict]:
+ """``events`` moved by (dlat, dlon) degrees, which shifts the grid
+ ``detect_convergence`` lays by the opposite amount. With ``ref_lon``
+ (the AOI's centre), a longitude more than 180 degrees from it is first
+ moved by exactly 360 so a cluster straddling the antimeridian stays
+ contiguous. Events without usable coordinates keep None, which
+ ``detect_convergence`` skips."""
+ moved = []
+ for event in events:
+ lat, lon = _finite(event["lat"]), _finite(event["lon"])
+ if lat is None or lon is None:
+ moved.append({**event, "lat": None, "lon": None})
+ continue
+ if ref_lon is not None:
+ if lon - ref_lon > 180.0:
+ lon -= 360.0
+ elif lon - ref_lon < -180.0:
+ lon += 360.0
+ moved.append({**event, "lat": lat + dlat, "lon": lon + dlon})
+ return moved
+
+
+def _wrap_lon(lon: float) -> float:
+ if lon > 180.0:
+ return lon - 360.0
+ if lon < -180.0:
+ return lon + 360.0
+ return lon
+
+
+def aoi_convergence(scoped: dict[str, dict], ref_lon: float | None = None) -> dict:
"""Multi-domain convergence inside an AOI: ``detect_convergence``
(``analysis/convergence.py``, unmodified) over the in-fence events of
the four geolocated domains in ``_CONVERGENCE_DOMAINS``. ``scoped``
maps each domain to its ``_scope_to_aoi`` result, so the events are
already filtered to the AOI's exact shape (circle, polygon or
- corridor).
+ corridor). The grid is laid at each of ``_CONVERGENCE_GRID_OFFSETS``
+ and the grid holding the strongest cell is reported (``cells``,
+ ``convergent_cells``, ``grid_offset_deg``); cell centres are given in
+ ordinary coordinates. ``ref_lon`` (the AOI's centre longitude) keeps
+ an antimeridian-straddling cluster in one piece.
``score`` is the strongest convergent cell's score, the escalation
- input. It is a measured 0.0 only when every input domain answered in
- full. With a domain failed or partial, a positive score is reported
+ input. It is reported as a measured 0.0 only when no input domain
+ reported a failure or partial coverage; it cannot see gaps the
+ sources do not report, which is why ``fetch_aoi_escalation`` marks
+ samples cut at their caps as partial and refuses expired cached
+ copies. With a domain failed or partial, a positive score is reported
with ``lower_bound`` true (with uniform weights a cell scores
domains x (1 + sqrt(events)), so the missing events could only raise
- it), and no convergent cell yields ``score`` None plus ``error``,
- because quiet cannot be told from missing.
+ it, on every grid), and no convergent cell yields ``score`` None plus
+ ``error``, because quiet cannot be told from missing.
"""
events: list[dict] = []
events_by_domain: dict[str, int] = {}
@@ -1855,18 +2095,33 @@ def aoi_convergence(scoped: dict[str, dict]) -> dict:
for item in result["items"]
)
- cells = detect_convergence(
- events,
- resolution=_CONVERGENCE_GRID_DEGREES,
- min_types=_CONVERGENCE_MIN_DOMAINS,
- min_total=_CONVERGENCE_MIN_EVENTS,
- )
+ best: tuple[float, tuple[float, float], list[dict]] | None = None
+ for dlat, dlon in _CONVERGENCE_GRID_OFFSETS:
+ grid_cells = detect_convergence(
+ _grid_events(events, dlat, dlon, ref_lon),
+ resolution=_CONVERGENCE_GRID_DEGREES,
+ min_types=_CONVERGENCE_MIN_DOMAINS,
+ min_total=_CONVERGENCE_MIN_EVENTS,
+ )
+ top = grid_cells[0]["convergence_score"] if grid_cells else 0.0
+ if best is None or top > best[0]:
+ best = (top, (dlat, dlon), grid_cells)
+ _, (dlat, dlon), grid_cells = best
+ cells = [
+ {
+ **cell,
+ "lat": round(cell["lat"] - dlat, 2),
+ "lon": round(_wrap_lon(cell["lon"] - dlon), 2),
+ }
+ for cell in grid_cells
+ ]
incomplete = failed + partial
out: dict[str, Any] = {
"score": None,
"lower_bound": False,
"convergent_cells": len(cells),
"cells": cells[:5],
+ "grid_offset_deg": {"lat": dlat, "lon": dlon},
"events_by_domain": events_by_domain,
"inputs_used": used,
"inputs_failed": failed,
@@ -1922,7 +2177,95 @@ async def _aoi_news_timeline(fetcher, aoi_row: dict) -> tuple[dict, dict]:
news.fetch_gdelt_search(fetcher, query=query, mode="timelinevolraw"),
"news_timeline",
)
- return result, scoping
+ return _refuse_stale_copy(result, "GDELT answer"), scoping
+
+
+def _news_scope_gap(aoi_row: dict, scoping: dict) -> str | None:
+ """The news-scope limit as a data gap where it bites: the query names
+ only the settlement and county at the AOI's centre, which cover a
+ large area only in part, and a shape whose centre cannot be placed
+ (a corridor or strait polygon centred at sea) gets no news score at
+ all, even where it covers named places."""
+ radius_km = float(aoi_row.get("radius_km") or 0.0)
+ kind = aoi_row.get("kind", "circle")
+ if scoping.get("basis") == "geocoded":
+ if radius_km <= _NEWS_SCOPE_RADIUS_KM:
+ return None
+ place = ", ".join(
+ str(part) for part in (scoping.get("place"), scoping.get("county")) if part
+ )
+ return (
+ f"News: scoped to {place or 'the place at the centre'}, the place at "
+ f"the AOI's centre; the area reaches {radius_km:.0f} km from its "
+ "centre, so coverage of other places inside it is not counted."
+ )
+ if kind != "circle" or radius_km > _NEWS_SCOPE_RADIUS_KM:
+ return (
+ "News: the query is built from the place at the AOI's centre "
+ f"only, so a {kind} whose centre cannot be placed gets no news "
+ "score even where it covers named places."
+ )
+ return None
+
+
+def _mark_capped_samples(
+ scoped: dict[str, dict], eq_result: Any, acled_result: Any, wildfire_result: Any
+) -> None:
+ """Name as partial coverage every escalation input whose global answer
+ reached its cap: its in-fence count is then a floor, not a
+ measurement, and convergence over it a lower bound. None of these
+ sources takes the AOI's box: USGS and ACLED are queried worldwide and
+ FIRMS by continental region."""
+
+ def _partial(domain: str, text: str) -> None:
+ entry = scoped[domain]
+ if "items" in entry:
+ entry["partial_errors"] = [*entry.get("partial_errors", []), text]
+
+ quakes = eq_result.get("earthquakes") if isinstance(eq_result, dict) else None
+ if isinstance(quakes, list) and len(quakes) >= _QUAKE_SAMPLE_LIMIT:
+ times = sorted(
+ str(q["time"]) for q in quakes if isinstance(q, dict) and q.get("time")
+ )
+ since = f"only quakes since {times[0]} are in" if times else "the oldest are cut"
+ _partial(
+ "earthquakes",
+ f"USGS answered with its cap of {_QUAKE_SAMPLE_LIMIT} M4.5+ quakes "
+ f"worldwide, newest first, so {since}; earlier ones in the "
+ f"{_QUAKE_WINDOW_HOURS} h window are missing",
+ )
+ events = acled_result.get("events") if isinstance(acled_result, dict) else None
+ if isinstance(events, list) and len(events) >= _ACLED_SAMPLE_LIMIT:
+ _partial(
+ "conflict_events",
+ f"ACLED answered with its cap of {_ACLED_SAMPLE_LIMIT} events "
+ f"worldwide for {_ACLED_WINDOW_DAYS} days, so in-area events "
+ "outside that sample are missing",
+ )
+ cut_regions = (
+ wildfire_result.get("truncated_regions", [])
+ if isinstance(wildfire_result, dict)
+ else []
+ )
+ for cut in cut_regions:
+ total = cut.get("clusters")
+ of = f" of {total}" if isinstance(total, int) else ""
+ _partial(
+ "wildfires",
+ f"NASA FIRMS listed only the {cut.get('listed')} largest{of} fire "
+ f"clusters for {cut.get('region')}, so smaller in-area clusters "
+ "can be missing",
+ )
+
+
+def _domain_names(domains: list[str]) -> str:
+ return ", ".join(_CONVERGENCE_LABELS.get(d, d) for d in domains)
+
+
+def _fetched_at(result: Any) -> str | None:
+ if isinstance(result, dict) and not result.get("error"):
+ return result.get("fetched_at")
+ return None
async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:
@@ -1938,6 +2281,13 @@ async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:
is ``analysis/convergence.py`` run over the in-fence earthquakes,
military flights, conflict events and wildfires (``aoi_convergence``).
+ An outage is never read as quiet: a source that did not answer
+ (USGS, a FIRMS region, both military sources, ACLED, GDELT), or that
+ answered only with an expired cached copy, counts as failed, the
+ copy's age named in ``data_gaps``. A global sample that reached its
+ cap (USGS newest 50, ACLED 100, FIRMS 20 largest clusters per region)
+ counts as partial coverage.
+
When the news or convergence inputs fail, that component is
``None`` in ``components``, listed in ``unavailable_components`` and
explained in ``data_gaps``, never a 0; ``computed_from`` names the
@@ -1945,9 +2295,14 @@ async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:
failure is named in ``data_gaps`` but still enters the score as 0,
because ``score_hotspot`` takes no null for those components;
``zero_filled_components`` lists which of ``computed_from`` that
- happened to, so a reader can tell those zeros from measured quiet.
- ``news_signal`` and ``convergence_signal`` carry the working for
- both new components."""
+ happened to, so a reader can tell those zeros from measured quiet,
+ and ``lower_bound_components`` the components partial data can only
+ have understated. ``score_ceiling`` is the highest score reachable
+ with the components measured, a zero-filled one held at 0 (an AOI's
+ baseline is a structural 0, ``score_method``). ``news_signal`` and
+ ``convergence_signal`` carry the working for both new components,
+ with each input's ``fetched_at`` and, for convergence, each domain's
+ ``windows``."""
if not isinstance(name, str) or not name.strip():
return {"error": "name must be a non-empty string."}
@@ -1972,12 +2327,30 @@ async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:
wildfire_result,
(news_result, news_scoping),
) = await asyncio.gather(
- _safe_fetch(conflict_mod.fetch_acled_events(fetcher, days=7), "acled_events"),
+ _safe_fetch(
+ conflict_mod.fetch_acled_events(
+ fetcher, days=_ACLED_WINDOW_DAYS, limit=_ACLED_SAMPLE_LIMIT
+ ),
+ "acled_events",
+ ),
_fetch_military_merged(fetcher, bboxes),
- _safe_fetch(seismology.fetch_earthquakes(fetcher, hours=72), "earthquakes"),
- _safe_fetch(_fetch_wildfires_for_aoi(fetcher, wildfire_regions), "wildfires"),
+ _safe_fetch(
+ seismology.fetch_earthquakes(
+ fetcher, hours=_QUAKE_WINDOW_HOURS, limit=_QUAKE_SAMPLE_LIMIT
+ ),
+ "earthquakes",
+ ),
+ _safe_fetch(
+ _fetch_wildfires_for_aoi(fetcher, wildfire_regions, refuse_stale=True),
+ "wildfires",
+ ),
_aoi_news_timeline(fetcher, aoi),
)
+ # "How hot is this area right now" must not be built from an expired
+ # copy: refused, with its age named (the news timeline and FIRMS
+ # regions are refused where they are fetched).
+ acled_result = _refuse_stale_copy(acled_result, "ACLED answer")
+ eq_result = _refuse_stale_copy(eq_result, "USGS answer")
scoped = {
"earthquakes": _scope_to_aoi(
eq_result, "earthquakes", aoi, "latitude", "longitude"
@@ -1990,12 +2363,15 @@ async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:
),
"wildfires": _scope_to_aoi(wildfire_result, "clusters", aoi, "lat", "lon"),
}
+ _mark_capped_samples(scoped, eq_result, acled_result, wildfire_result)
data_gaps: list[str] = []
conflict_count = fatalities = protests = 0
if scoped["conflict_events"].get("error"):
data_gaps.append(f"Conflict events: {scoped['conflict_events']['error']}")
else:
+ for partial in scoped["conflict_events"].get("partial_errors", []):
+ data_gaps.append(f"Conflict events: partial coverage: {partial}")
for ev in scoped["conflict_events"]["items"]:
if "protest" in (ev.get("event_type") or "").lower():
protests += 1
@@ -2014,17 +2390,33 @@ async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:
for domain, label in (("earthquakes", "Earthquakes"), ("wildfires", "Wildfires")):
if scoped[domain].get("error"):
data_gaps.append(f"{label}: {scoped[domain]['error']}")
+ for partial in scoped[domain].get("partial_errors", []):
+ data_gaps.append(f"{label}: partial coverage: {partial}")
- convergence = aoi_convergence(scoped)
+ convergence = aoi_convergence(scoped, ref_lon=lon)
+ incomplete = convergence["inputs_failed"] + convergence["inputs_partial"]
if convergence.get("error"):
- data_gaps.append(f"Convergence: not scored; {convergence['error']}.")
+ reason = (
+ f"no convergent cell among {_domain_names(convergence['inputs_used'])}, "
+ f"but {_domain_names(incomplete)} answered only partly or not at "
+ "all, so quiet cannot be told from missing"
+ if convergence["inputs_used"]
+ else convergence["error"]
+ )
+ data_gaps.append(f"Convergence: not scored; {reason}.")
elif convergence["lower_bound"]:
- incomplete = convergence["inputs_failed"] + convergence["inputs_partial"]
data_gaps.append(
- f"Convergence: computed without full {', '.join(incomplete)} data; "
+ f"Convergence: computed without full {_domain_names(incomplete)} data; "
f"{convergence['score']} is a lower bound (the missing events could "
"only raise it)."
)
+ convergence["windows"] = dict(_CONVERGENCE_WINDOWS)
+ convergence["fetched_at"] = {
+ "earthquakes": _fetched_at(eq_result),
+ "military_flights": _fetched_at(mil_result),
+ "conflict_events": _fetched_at(acled_result),
+ "wildfires": _fetched_at(wildfire_result),
+ }
if news_result.get("error"):
trend: dict[str, Any] = {"error": str(news_result["error"])}
@@ -2033,12 +2425,16 @@ async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:
news_signal = {
"query": news_scoping.get("query"),
"basis": news_scoping.get("basis"),
+ "fetched_at": _fetched_at(news_result),
**trend,
}
if news_signal.get("error"):
data_gaps.append(f"News: {news_signal['error']}.")
elif news_signal.get("note"):
data_gaps.append(f"News: {news_signal['note']}")
+ scope_gap = _news_scope_gap(aoi, news_scoping)
+ if scope_gap:
+ data_gaps.append(scope_gap)
hotspot_config = {
"lat": lat,
@@ -2055,6 +2451,21 @@ async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:
fatalities=fatalities,
protests=protests,
)
+ # The same scorer with every measured component at its cap: what this
+ # call could have reached (an AOI's baseline is always 0; a zero-filled
+ # component stays at 0).
+ unavailable = scored["unavailable_components"]
+ military_failed = bool(scoped["military_flights"].get("error"))
+ conflict_failed = bool(scoped["conflict_events"].get("error"))
+ score_ceiling = score_hotspot(
+ hotspot_config,
+ news_mentions=None if "news" in unavailable else 10**6,
+ military_count=0 if military_failed else 10**6,
+ conflict_events=0 if conflict_failed else 10**6,
+ convergence_score=None if "convergence" in unavailable else 10**6,
+ fatalities=0,
+ protests=0 if conflict_failed else 10**6,
+ )["score"]
return {
"aoi": {
@@ -2073,13 +2484,24 @@ async def fetch_aoi_escalation(fetcher, store: AOIStore, name: Any) -> dict:
comp for comp, points in scored["components"].items() if points is not None
],
"zero_filled_components": (
- (["military"] if scoped["military_flights"].get("error") else [])
+ (["military"] if military_failed else [])
+ + (["conflict", "social_unrest"] if conflict_failed else [])
+ ),
+ "lower_bound_components": (
+ (["military"] if scoped["military_flights"].get("partial_errors") else [])
+ (
["conflict", "social_unrest"]
- if scoped["conflict_events"].get("error")
+ if scoped["conflict_events"].get("partial_errors")
+ else []
+ )
+ + (
+ ["convergence"]
+ if convergence["score"] is not None and convergence["lower_bound"]
else []
)
),
+ "score_ceiling": score_ceiling,
+ "score_method": SCORE_METHOD,
"news_scoping": news_scoping,
"news_signal": news_signal,
"convergence_signal": convergence,
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index af3204c..f31e597 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -2541,16 +2541,36 @@ def aoi_escalation(ctx: click.Context, name: str) -> None:
)
console.print(
f"[bold]{escape(str(a.get('name', name)))}[/bold] escalation: "
- f"{data.get('score', 0)}/100 ({level_str}, "
+ f"{data.get('score', 0)} on a 0-100 scale ({level_str}, "
f"trend {escape(str(data.get('trend_signal', '')))})"
)
+ if data.get("score_ceiling") is not None:
+ console.print(
+ f"[dim]Highest score reachable with the components measured: "
+ f"{data['score_ceiling']} (an AOI has no curated baseline)[/dim]"
+ )
+ if data.get("computed_from"):
+ console.print(
+ "[dim]Computed from: "
+ f"{escape(', '.join(str(c) for c in data['computed_from']))}[/dim]"
+ )
+ # A zero-filled component is a 0 only because its fetch failed; a
+ # lower bound could only rise with the data that is missing.
+ zero_filled = set(data.get("zero_filled_components") or [])
+ lower_bound = set(data.get("lower_bound_components") or [])
table = Table(title="Components", box=box.SIMPLE_HEAVY)
table.add_column("Component", style="bold")
table.add_column("Points", justify="right")
for comp, points in data.get("components", {}).items():
if points is None:
table.add_row(_cell(comp), "[dim]not measured[/dim]")
+ elif comp in zero_filled:
+ table.add_row(
+ _cell(comp), "[yellow]not measured (fetch failed; scored as 0)[/yellow]"
+ )
+ elif comp in lower_bound:
+ table.add_row(_cell(comp), f"{points:.1f} (lower bound)")
else:
table.add_row(_cell(comp), f"{points:.1f}")
console.print(table)
diff --git a/src/world_intel_mcp/sources/conflict.py b/src/world_intel_mcp/sources/conflict.py
index 17d283c..87c6124 100644
--- a/src/world_intel_mcp/sources/conflict.py
+++ b/src/world_intel_mcp/sources/conflict.py
@@ -13,6 +13,7 @@ from datetime import datetime, timezone, timedelta
import httpx
from ..fetcher import Fetcher
+from .freshness import json_answer_freshness
logger = logging.getLogger("world-intel-mcp.sources.conflict")
@@ -153,7 +154,10 @@ async def fetch_acled_events(
limit: Maximum number of results.
Returns:
- Dict with events list, count, query params, source, and timestamp.
+ Dict with events list, count, query params, source, timestamp and
+ ``fetched_at`` (when ACLED answered; earlier than ``timestamp`` for
+ a cached answer). An expired cached copy served because ACLED did
+ not answer carries ``_stale`` and ``_stale_age_seconds``.
"""
now = datetime.now(timezone.utc)
@@ -169,10 +173,13 @@ async def fetch_acled_events(
params["country"] = country
cache_country = country or "global"
+ # The limit is part of the key: a 15-event answer cached for one
+ # caller must not be served to another that asked for 100.
+ cache_key = f"conflict:acled:{cache_country}:{days}:{limit}"
data = await acled_query(
fetcher,
params,
- cache_key=f"conflict:acled:{cache_country}:{days}",
+ cache_key=cache_key,
cache_ttl=900,
)
if data is None:
@@ -239,6 +246,7 @@ async def fetch_acled_events(
"query": {"country": country, "days": days},
"source": "acled",
"timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ **json_answer_freshness(fetcher, cache_key, data),
}
diff --git a/src/world_intel_mcp/sources/freshness.py b/src/world_intel_mcp/sources/freshness.py
new file mode 100644
index 0000000..36968c5
--- /dev/null
+++ b/src/world_intel_mcp/sources/freshness.py
@@ -0,0 +1,67 @@
+"""When a source's answer was really fetched, and whether it is an expired copy.
+
+The fetcher answers from its cache while an entry is live, and when a
+live fetch fails (or the source's circuit is open) it serves the expired
+entry instead, marking a dict answer with ``_stale`` and
+``_stale_age_seconds``. A source wrapper that rebuilds the answer drops
+both marks unless it carries them, and its own ``timestamp`` is the time
+it assembled the reply, not when upstream answered. Anything that scores
+current conditions needs both facts, so these helpers recover them from
+the cache entry the answer came from.
+"""
+
+import time
+from datetime import datetime, timezone
+
+from ..fetcher import Fetcher
+
+
+def _utc(epoch: float) -> str:
+ return datetime.fromtimestamp(epoch, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _cache_entry(fetcher: Fetcher, cache_key: str) -> tuple[object, float] | None:
+ """``(value, written_at)`` of the cache entry under ``cache_key``, live
+ or expired, or None when there is none."""
+ meta = fetcher.cache.get_stale_meta(cache_key)
+ if meta is None or not isinstance(meta[1], (int, float)):
+ return None
+ return meta[0], float(meta[1])
+
+
+def json_answer_freshness(fetcher: Fetcher, cache_key: str, data: object) -> dict:
+ """``fetched_at`` for an answer ``fetcher.get_json`` returned under
+ ``cache_key``, plus the fetcher's ``_stale`` / ``_stale_age_seconds``
+ when the answer was its expired copy.
+
+ ``fetched_at`` is when this server received the answer from upstream:
+ the cache entry's write time, so a cached answer reports its original
+ fetch, not the moment it was served. With no entry (the cache write
+ failed) the answer was just fetched."""
+ now = time.time()
+ if isinstance(data, dict) and data.get("_stale"):
+ age = data.get("_stale_age_seconds")
+ age = float(age) if isinstance(age, (int, float)) else 0.0
+ return {
+ "fetched_at": _utc(now - age),
+ "_stale": True,
+ "_stale_age_seconds": round(age, 1),
+ }
+ entry = _cache_entry(fetcher, cache_key)
+ return {"fetched_at": _utc(entry[1] if entry is not None else now)}
+
+
+def text_answer_freshness(fetcher: Fetcher, cache_key: str, text: str) -> dict:
+ """``json_answer_freshness`` for ``fetcher.get_text``, which cannot mark
+ a stale ``str``: an answer equal to an expired cache entry is that
+ expired copy."""
+ now = time.time()
+ entry = _cache_entry(fetcher, cache_key)
+ if entry is None or entry[0] != text:
+ return {"fetched_at": _utc(now)}
+ written_at = entry[1]
+ out: dict = {"fetched_at": _utc(written_at)}
+ if fetcher.cache.get(cache_key) is None:
+ out["_stale"] = True
+ out["_stale_age_seconds"] = round(max(0.0, now - written_at), 1)
+ return out
diff --git a/src/world_intel_mcp/sources/news.py b/src/world_intel_mcp/sources/news.py
index 7c11078..d5e22f8 100644
--- a/src/world_intel_mcp/sources/news.py
+++ b/src/world_intel_mcp/sources/news.py
@@ -6,12 +6,15 @@ search via the GDELT 2.0 Doc API. No API keys required.
"""
import asyncio
+import hashlib
+import json
import logging
import re
import string
from datetime import datetime, timezone
from ..fetcher import Fetcher
+from .freshness import json_answer_freshness
try:
import feedparser
@@ -729,6 +732,20 @@ async def fetch_trending_keywords(
# ---------------------------------------------------------------------------
+def _gdelt_cache_key(params: dict) -> str:
+ """Cache key for one GDELT request: a readable prefix plus a digest of
+ every request parameter. The prefix alone (the query reduced to ASCII
+ letters, digits, ``_`` and ``-``, cut to 64 characters) maps different
+ non-Latin queries to one string ("Київ" and "Суми" both become
+ ``______``) and leaves out ``maxrecords``, so one search was answered
+ from another's cache entry."""
+ safe_query = re.sub(r"[^a-zA-Z0-9_-]", "_", str(params["query"]))[:64]
+ digest = hashlib.sha256(
+ json.dumps(params, sort_keys=True, ensure_ascii=False).encode("utf-8")
+ ).hexdigest()[:16]
+ return f"news:gdelt:{safe_query}:{params['mode']}:{digest}"
+
+
async def fetch_gdelt_search(
fetcher: Fetcher,
query: str = "conflict",
@@ -748,7 +765,10 @@ async def fetch_gdelt_search(
Returns:
Dict with articles/timeline data, count, query info, source,
- and timestamp.
+ timestamp and ``fetched_at`` (when GDELT answered; earlier than
+ ``timestamp`` for a cached answer). An expired cached copy served
+ because GDELT did not answer carries ``_stale`` and
+ ``_stale_age_seconds``.
"""
now = datetime.now(timezone.utc)
@@ -759,11 +779,11 @@ async def fetch_gdelt_search(
"format": "json",
}
- safe_query = re.sub(r"[^a-zA-Z0-9_-]", "_", query)[:64]
+ cache_key = _gdelt_cache_key(params)
data = await fetcher.get_json(
_GDELT_DOC_URL,
source="gdelt",
- cache_key=f"news:gdelt:{safe_query}:{mode}",
+ cache_key=cache_key,
cache_ttl=600,
params=params,
timeout=GDELT_TIMEOUT,
@@ -812,6 +832,7 @@ async def fetch_gdelt_search(
"mode": mode,
"source": "gdelt",
"timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ **json_answer_freshness(fetcher, cache_key, data),
}
# timelinevol mode — return timeline data as-is
@@ -823,4 +844,5 @@ async def fetch_gdelt_search(
"mode": mode,
"source": "gdelt",
"timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ **json_answer_freshness(fetcher, cache_key, data),
}
diff --git a/src/world_intel_mcp/sources/seismology.py b/src/world_intel_mcp/sources/seismology.py
index d0aa545..c31663d 100644
--- a/src/world_intel_mcp/sources/seismology.py
+++ b/src/world_intel_mcp/sources/seismology.py
@@ -8,6 +8,7 @@ import logging
from datetime import datetime, timezone, timedelta
from ..fetcher import Fetcher
+from .freshness import json_answer_freshness
logger = logging.getLogger("world-intel-mcp.sources.seismology")
@@ -29,7 +30,13 @@ async def fetch_earthquakes(
limit: Maximum number of results.
Returns:
- Dict with earthquakes list, count, query params, source, and timestamp.
+ Dict with earthquakes list, count, query params, source, timestamp
+ and ``fetched_at`` (when USGS answered; earlier than ``timestamp``
+ for a cached answer). An expired cached copy served because USGS
+ did not answer carries ``_stale`` and ``_stale_age_seconds``. A
+ failed fetch with no copy is ``error`` / ``degraded`` /
+ ``reason: "usgs_fetch_failed"`` with the list keys kept empty, so
+ it never reads as a quiet planet.
"""
now = datetime.now(timezone.utc)
starttime = (now - timedelta(hours=hours)).strftime("%Y-%m-%dT%H:%M:%S")
@@ -42,17 +49,28 @@ async def fetch_earthquakes(
"starttime": starttime,
}
+ # The limit is part of the key: a 5-quake answer cached for one caller
+ # must not be served to another that asked for 50 and then reads the
+ # short list as complete.
+ cache_key = f"seismology:quakes:{min_magnitude}:{hours}:{limit}"
data = await fetcher.get_json(
url=_USGS_ENDPOINT,
source="usgs",
- cache_key=f"seismology:quakes:{min_magnitude}:{hours}",
+ cache_key=cache_key,
cache_ttl=300,
params=params,
)
if data is None:
logger.warning("USGS API returned no data")
+ # A failed fetch must not be byte-identical to a quiet planet, the
+ # same contract ACLED and GDELT follow. earthquakes/count keep their
+ # normal empty shape so callers that don't check "error" or
+ # "degraded" still iterate an empty list.
return {
+ "error": "USGS earthquake fetch failed (API error, timeout, or malformed response)",
+ "degraded": True,
+ "reason": "usgs_fetch_failed",
"earthquakes": [],
"count": 0,
"query": {"min_magnitude": min_magnitude, "hours": hours},
@@ -95,4 +113,5 @@ async def fetch_earthquakes(
"query": {"min_magnitude": min_magnitude, "hours": hours},
"source": "usgs",
"timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ **json_answer_freshness(fetcher, cache_key, data),
}
diff --git a/src/world_intel_mcp/sources/wildfire.py b/src/world_intel_mcp/sources/wildfire.py
index 432849c..ef20ad1 100644
--- a/src/world_intel_mcp/sources/wildfire.py
+++ b/src/world_intel_mcp/sources/wildfire.py
@@ -11,6 +11,7 @@ import os
from datetime import datetime, timezone
from ..fetcher import Fetcher
+from .freshness import text_answer_freshness
logger = logging.getLogger("world-intel-mcp.sources.wildfire")
@@ -33,6 +34,11 @@ REGIONS = {
"oceania": "105,-50,180,-5",
}
+# How many 0.5-degree clusters each region's answer lists (the largest by
+# fire count). A region's ``cluster_count`` says how many there were, so a
+# caller can tell when smaller clusters were cut.
+TOP_CLUSTERS_PER_REGION = 20
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -106,8 +112,9 @@ def _parse_fires_csv(csv_text: str) -> list[dict]:
return fires
-def _cluster_fires(fires: list[dict], top_n: int = 20) -> list[dict]:
- """Group fires by a 0.5-degree grid and return the top N clusters by count."""
+def _cluster_fires(fires: list[dict], top_n: int | None = TOP_CLUSTERS_PER_REGION) -> list[dict]:
+ """Group fires by a 0.5-degree grid and return the top N clusters by
+ count (every cluster when ``top_n`` is None)."""
grid: dict[tuple[float, float], list[dict]] = {}
for fire in fires:
@@ -145,7 +152,11 @@ async def fetch_wildfires(
region: str | None = None,
api_key: str | None = None,
) -> dict:
- """Fetch active wildfire data from NASA FIRMS (VIIRS SNPP NRT, last 24h).
+ """Fetch active wildfire data from NASA FIRMS (VIIRS SNPP NRT).
+
+ Each region is one FIRMS area request with a day range of 2 (the
+ trailing ``/2`` in the URL), which asks FIRMS for its two most recent
+ days of detections, not a rolling 24 hours.
Args:
fetcher: Shared HTTP fetcher with caching and circuit breaking.
@@ -153,7 +164,18 @@ async def fetch_wildfires(
api_key: NASA FIRMS API key. Falls back to NASA_FIRMS_API_KEY env var.
Returns:
- Dict with fires_by_region, total_fires, source, and timestamp.
+ Dict with fires_by_region, total_fires, source, and timestamp. Each
+ answered region has ``count``, ``top_clusters`` (the
+ ``TOP_CLUSTERS_PER_REGION`` largest), ``cluster_count`` and
+ ``fetched_at`` (when FIRMS answered), plus ``_stale`` /
+ ``_stale_age_seconds`` when it is an expired cached copy served
+ because FIRMS did not answer. A region FIRMS did not answer (and no
+ copy exists) keeps ``count`` 0 and empty ``top_clusters`` but
+ carries ``error``, and the result is ``degraded`` with
+ ``reason: "firms_fetch_failed"`` and ``failed_regions``: ``error``
+ when every requested region failed, else ``partial_errors``. Any
+ expired copy also marks the result ``_stale`` with
+ ``stale_regions``.
"""
key = api_key or os.environ.get("NASA_FIRMS_API_KEY")
if not key:
@@ -169,23 +191,26 @@ async def fetch_wildfires(
else:
regions_to_fetch = dict(REGIONS)
- async def _fetch_region(region_name: str, bbox: str) -> tuple[str, list[dict] | None]:
- """Fetch fires for a single region, return (name, fires_list_or_None)."""
+ async def _fetch_region(
+ region_name: str, bbox: str
+ ) -> tuple[str, list[dict] | None, dict]:
+ """Fetch fires for a single region: (name, fires or None, freshness)."""
url = f"{_FIRMS_BASE_URL}/{key}/VIIRS_SNPP_NRT/{bbox}/2"
+ cache_key = f"wildfire:csv:{region_name}"
csv_text = await fetcher.get_text(
url=url,
source="nasa-firms",
- cache_key=f"wildfire:csv:{region_name}",
+ cache_key=cache_key,
cache_ttl=1800,
)
if csv_text is None:
logger.warning("FIRMS returned no data for region %s", region_name)
- return (region_name, None)
+ return (region_name, None, {})
fires = _parse_fires_csv(csv_text)
- return (region_name, fires)
+ return (region_name, fires, text_answer_freshness(fetcher, cache_key, csv_text))
# Fetch all requested regions in parallel
tasks = [
@@ -197,36 +222,65 @@ async def fetch_wildfires(
# Assemble response
fires_by_region: dict[str, dict] = {}
total_fires = 0
+ failed: list[str] = []
+ stale: list[str] = []
+ stale_ages: list[float] = []
- for region_name, fires in results:
+ for region_name, fires, freshness in results:
if fires is None:
- fires_by_region[region_name] = {"count": 0, "top_clusters": []}
+ # A region FIRMS did not answer must not read as a region with
+ # no fires: same contract as ACLED, GDELT and USGS. The empty
+ # count/top_clusters keep old callers iterating.
+ failed.append(region_name)
+ fires_by_region[region_name] = {
+ "count": 0,
+ "top_clusters": [],
+ "error": (
+ f"NASA FIRMS gave no answer for {region_name} (API error, "
+ "timeout, or open circuit) and no cached copy exists"
+ ),
+ }
continue
count = len(fires)
total_fires += count
- top_clusters = _cluster_fires(fires)
+ clusters = _cluster_fires(fires, top_n=None)
fires_by_region[region_name] = {
"count": count,
- "top_clusters": top_clusters,
+ "top_clusters": clusters[:TOP_CLUSTERS_PER_REGION],
+ "cluster_count": len(clusters),
+ **freshness,
}
+ if freshness.get("_stale"):
+ stale.append(region_name)
+ stale_ages.append(freshness["_stale_age_seconds"])
- cache_label = region if region is not None else "global"
- # Store assembled result in cache under the composite key
- fetcher.cache.set(
- f"wildfire:fires:{cache_label}",
- {
- "fires_by_region": fires_by_region,
- "total_fires": total_fires,
- "source": "nasa-firms",
- "timestamp": _utc_now_iso(),
- },
- 1800,
- )
-
- return {
+ result: dict = {
"fires_by_region": fires_by_region,
"total_fires": total_fires,
"source": "nasa-firms",
"timestamp": _utc_now_iso(),
}
+ if failed:
+ result["degraded"] = True
+ result["reason"] = "firms_fetch_failed"
+ result["failed_regions"] = sorted(failed)
+ if len(failed) == len(results):
+ result["error"] = (
+ "NASA FIRMS fetch failed for every requested region (API error, "
+ "timeout, or open circuit; no cached copy)"
+ )
+ else:
+ result["partial_errors"] = [
+ fires_by_region[name]["error"] for name in sorted(failed)
+ ]
+ if stale:
+ result["_stale"] = True
+ result["_stale_age_seconds"] = max(stale_ages)
+ result["stale_regions"] = sorted(stale)
+
+ cache_label = region if region is not None else "global"
+ # Store assembled result in cache under the composite key
+ fetcher.cache.set(f"wildfire:fires:{cache_label}", result, 1800)
+
+ return result
diff --git a/src/world_intel_mcp/tests/test_aoi_escalation_inputs.py b/src/world_intel_mcp/tests/test_aoi_escalation_inputs.py
new file mode 100644
index 0000000..3da11fc
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_aoi_escalation_inputs.py
@@ -0,0 +1,1298 @@
+"""Escalation inputs that must never read as quiet: real outages, expired
+cached copies, global samples cut at their caps, cache entries shared by
+different queries, and compact clusters split by the convergence grid.
+
+Every test that names an upstream drives the real source functions
+(geocode, news, seismology, military, wildfire, and ACLED's events fetch
+with only its OAuth bearer stubbed) through the real Fetcher and Cache,
+with each upstream answered by respx; nothing reaches a live API
+(``assert_all_mocked``). An expired copy is made the way it happens in
+production: one call caches a real answer, the entry is aged past its TTL
+in the cache database, and the next call finds the upstream down.
+
+Each expected number is worked by hand in a comment next to its
+assertion. The news trend's clock is pinned to ``_NOW``; cache ages use
+the real clock.
+"""
+
+import asyncio
+import functools
+import re
+import sqlite3
+import time
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+import httpx
+import pytest
+import respx
+from click.testing import CliRunner
+
+import world_intel_mcp.fetcher as fetcher_mod
+from world_intel_mcp import cli
+from world_intel_mcp.analysis import aoi
+from world_intel_mcp.analysis.aoi import AOIStore
+from world_intel_mcp.cache import Cache
+from world_intel_mcp.circuit_breaker import CircuitBreaker
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources import conflict, military, news, seismology, wildfire
+
+# Pittsburgh, the README worked example: a 50 km circle.
+_PGH = (40.4406, -79.9959, 50.0)
+# ~6.6 km from the centre; unshifted grid cell (40, -80). A FIRMS fire
+# here clusters to (40.5, -80.0), the same cell.
+_IN = (40.5, -79.9)
+
+# News trend clock: the current window is Oct 11-17 (Oct 17 is 0.75
+# elapsed), the prior window Oct 4-10.
+_NOW = datetime(2026, 10, 17, 18, 0, tzinfo=timezone.utc)
+_DAY0 = datetime(2026, 10, 4, tzinfo=timezone.utc)
+
+_UTC = "%Y-%m-%dT%H:%M:%SZ"
+
+_NOMINATIM_PGH = {
+ "osm_type": "relation",
+ "osm_id": 188553,
+ "name": "Pittsburgh",
+ "display_name": "Pittsburgh, Allegheny County, Pennsylvania, United States",
+ "address": {
+ "city": "Pittsburgh",
+ "county": "Allegheny County",
+ "state": "Pennsylvania",
+ "country": "United States",
+ "country_code": "us",
+ },
+}
+# Nominatim's own answer for a point it cannot name (open water).
+_NOMINATIM_UNNAMED = {"error": "Unable to geocode"}
+
+_URLS = {
+ "nominatim": r"^https://nominatim\.openstreetmap\.org/reverse",
+ "gdelt": r"^https://api\.gdeltproject\.org/api/v2/doc/doc",
+ "usgs": r"^https://earthquake\.usgs\.gov/",
+ "adsb": r"^https://api\.adsb\.lol/",
+ "opensky": r"^https://opensky-network\.org/",
+ "firms": r"^https://firms\.modaps\.eosdis\.nasa\.gov/",
+ "acled": r"^https://acleddata\.com/api/acled/read",
+}
+
+_USGS_DOWN = "USGS earthquake fetch failed (API error, timeout, or malformed response)"
+_FIRMS_ALL_DOWN = (
+ "NASA FIRMS fetch failed for every requested region (API error, timeout, "
+ "or open circuit; no cached copy)"
+)
+_GEOCODER_DOWN = (
+ "Reverse geocoding unavailable: the Nominatim request failed (rate limit, "
+ "upstream error, or network). See fetcher logs for the specific failure."
+)
+_MILITARY_DOWN = (
+ "no military flight source answered (adsb.lol failed or returned no "
+ "aircraft, and the OpenSky fallback failed)"
+)
+
+
+def _firms_region_down(region: str) -> str:
+ return (
+ f"NASA FIRMS gave no answer for {region} (API error, timeout, or open "
+ "circuit) and no cached copy exists"
+ )
+
+
+def _stale_pattern(subject: str, age: str) -> str:
+ return (
+ rf"no fresh {subject} \(the request failed or its circuit breaker is "
+ rf"open\); the only copy on hand is one this server cached {age} ago "
+ r"\(at (\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ)\), so it is not scored as current"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Upstream answers
+# ---------------------------------------------------------------------------
+
+
+def _timeline(prior: list[tuple[int, int]], current: list[tuple[int, int]]) -> dict:
+ """A GDELT DOC body: daily (matching, monitored) article counts for
+ Oct 4-10 then Oct 11-17. It also carries an empty article list, so the
+ same body answers the brief's artlist query."""
+ points = [
+ {
+ "date": (_DAY0 + timedelta(days=i)).strftime("%Y%m%dT%H%M%SZ"),
+ "value": value,
+ "norm": norm,
+ }
+ for i, (value, norm) in enumerate(prior + current)
+ ]
+ return {"timeline": [{"series": "Article Count", "data": points}], "articles": []}
+
+
+_FLAT = _timeline([(10, 1000)] * 7, [(10, 1000)] * 7) # change 0.0
+_RISING = _timeline([(10, 1000)] * 7, [(15, 1000)] * 7) # change +50.0
+
+
+def _usgs(points: list[tuple[float, float]], newest_ms: int | None = None) -> dict:
+ """USGS GeoJSON, newest first, one minute apart."""
+ newest_ms = newest_ms or int(time.time() * 1000) - 3_600_000
+ return {
+ "type": "FeatureCollection",
+ "features": [
+ {
+ "id": f"q{i}",
+ "properties": {
+ "mag": 4.7,
+ "place": f"quake {i}",
+ "time": newest_ms - i * 60_000,
+ },
+ "geometry": {"coordinates": [lon, lat, 10.0]},
+ }
+ for i, (lat, lon) in enumerate(points)
+ ],
+ }
+
+
+def _adsb(points: list[tuple[float, float]]) -> dict:
+ return {
+ "ac": [
+ {"hex": f"ae{i:04x}", "flight": f"RCH{i}", "lat": lat, "lon": lon,
+ "alt_baro": 20000}
+ for i, (lat, lon) in enumerate(points)
+ ]
+ }
+
+
+def _firms(points: list[tuple[float, float]]) -> str:
+ header = "latitude,longitude,bright_ti4,confidence,frp,acq_date,acq_time,daynight,satellite"
+ rows = [f"{lat},{lon},330.0,n,12.0,2026-10-17,0600,D,N" for lat, lon in points]
+ return "\n".join([header, *rows]) + "\n"
+
+
+def _acled(points: list[tuple[float, float]]) -> dict:
+ """ACLED read API body; it sends coordinates and fatalities as strings."""
+ return {
+ "status": 200,
+ "success": True,
+ "count": len(points),
+ "data": [
+ {
+ "event_id_cnty": f"T{i}",
+ "event_date": "2026-10-16",
+ "event_type": "Battles",
+ "latitude": str(lat),
+ "longitude": str(lon),
+ "fatalities": "0",
+ "location": f"site {i}",
+ "country": "Testland",
+ }
+ for i, (lat, lon) in enumerate(points)
+ ],
+ }
+
+
+def _response(spec) -> httpx.Response:
+ if isinstance(spec, int):
+ return httpx.Response(spec, text="upstream error")
+ if isinstance(spec, str):
+ return httpx.Response(200, text=spec)
+ return httpx.Response(200, json=spec)
+
+
+def _routes(router: respx.MockRouter, **specs) -> dict:
+ """One route per upstream. A spec is a JSON body, a CSV string, an
+ HTTP status, or a callable side effect. By default every upstream
+ answers and nothing is in the area: Nominatim names Pittsburgh, GDELT
+ is flat, adsb.lol is empty and OpenSky (its fallback) answers empty."""
+ answers = {
+ "nominatim": _NOMINATIM_PGH,
+ "gdelt": _FLAT,
+ "usgs": _usgs([]),
+ "adsb": _adsb([]),
+ "opensky": {"time": 0, "states": []},
+ "firms": _firms([]),
+ "acled": _acled([]),
+ }
+ assert set(specs) <= set(answers), set(specs) - set(answers)
+ answers.update(specs)
+ routes = {}
+ for name, pattern in _URLS.items():
+ route = router.get(url__regex=pattern)
+ spec = answers[name]
+ if callable(spec):
+ route.mock(side_effect=spec)
+ else:
+ route.mock(return_value=_response(spec))
+ routes[name] = route
+ return routes
+
+
+# ---------------------------------------------------------------------------
+# Environment
+# ---------------------------------------------------------------------------
+
+
+class _Edge:
+ """A real Cache, Fetcher (no retries) and AOIStore in a temp dir."""
+
+ def __init__(self, tmp_path: Path) -> None:
+ self.db = tmp_path / "cache.db"
+ self.cache = Cache(db_path=self.db)
+ self.fetcher = Fetcher(
+ cache=self.cache,
+ breaker=CircuitBreaker(),
+ default_timeout=5.0,
+ max_retries=0,
+ )
+ self.store = AOIStore(tmp_path / "aoi.db")
+
+ async def aclose(self) -> None:
+ await self.fetcher.close()
+ self.store.close()
+ self.cache.close()
+
+
+def _hermetic(monkeypatch: pytest.MonkeyPatch) -> None:
+ """No rate-limit sleeps, a FIRMS key, an ACLED bearer without the
+ OAuth exchange, and the news trend's clock pinned to ``_NOW``."""
+
+ async def _acled_bearer() -> str:
+ return "respx-bearer"
+
+ monkeypatch.setattr(fetcher_mod, "_SOURCE_RATE_LIMITS", {})
+ monkeypatch.setenv("NASA_FIRMS_API_KEY", "respx-firms")
+ monkeypatch.delenv("OPENSKY_CLIENT_ID", raising=False)
+ monkeypatch.delenv("OPENSKY_CLIENT_SECRET", raising=False)
+ monkeypatch.setattr(conflict, "_acled_get_token", _acled_bearer)
+ monkeypatch.setattr(
+ aoi, "news_coverage_trend", functools.partial(aoi.news_coverage_trend, now=_NOW)
+ )
+
+
+async def edge(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ _hermetic(monkeypatch)
+ env = _Edge(tmp_path)
+ yield env
+ await env.aclose()
+
+
+async def _escalate(env: _Edge, name: str = "Pittsburgh", **specs) -> tuple[dict, dict]:
+ """``fetch_aoi_escalation`` behind ``_routes``; returns the result and
+ each upstream's requests."""
+ with respx.mock(assert_all_mocked=True, assert_all_called=False) as router:
+ routes = _routes(router, **specs)
+ result = await aoi.fetch_aoi_escalation(env.fetcher, env.store, name)
+ requests = {k: [c.request for c in r.calls] for k, r in routes.items()}
+ return result, requests
+
+
+def _age_entry(db: Path, prefix: str, age_s: float, *, expire: bool) -> float:
+ """Move the one cache entry whose key starts with ``prefix`` back by
+ ``age_s`` seconds (and past its TTL when ``expire``); returns its new
+ write time."""
+ written = time.time() - age_s
+ conn = sqlite3.connect(db)
+ try:
+ if expire:
+ cur = conn.execute(
+ "UPDATE cache SET created_at = ?, expires_at = ? "
+ "WHERE substr(key, 1, length(?)) = ?",
+ (written, time.time() - 1.0, prefix, prefix),
+ )
+ else:
+ cur = conn.execute(
+ "UPDATE cache SET created_at = ? WHERE substr(key, 1, length(?)) = ?",
+ (written, prefix, prefix),
+ )
+ conn.commit()
+ assert cur.rowcount == 1, f"{cur.rowcount} cache entries start with {prefix!r}"
+ finally:
+ conn.close()
+ return written
+
+
+def _epoch(stamp: str) -> float:
+ return datetime.strptime(stamp, _UTC).replace(tzinfo=timezone.utc).timestamp()
+
+
+def _iso(epoch: float) -> str:
+ return datetime.fromtimestamp(epoch, tz=timezone.utc).strftime(_UTC)
+
+
+# ---------------------------------------------------------------------------
+# Sources: an outage carries an error, never the shape of a quiet answer
+# ---------------------------------------------------------------------------
+
+
+async def test_usgs_outage_is_an_error_not_a_quiet_planet(edge: _Edge) -> None:
+ with respx.mock(assert_all_mocked=True) as router:
+ router.get(url__regex=_URLS["usgs"]).mock(return_value=httpx.Response(503))
+ result = await seismology.fetch_earthquakes(edge.fetcher, hours=72)
+
+ assert result["error"] == _USGS_DOWN
+ assert result["degraded"] is True
+ assert result["reason"] == "usgs_fetch_failed"
+ # The list keys keep their shape so callers that only iterate still run.
+ assert result["earthquakes"] == []
+ assert result["count"] == 0
+
+
+async def test_firms_region_outage_is_named_not_an_empty_region(edge: _Edge) -> None:
+ with respx.mock(assert_all_mocked=True) as router:
+ router.get(url__regex=_URLS["firms"]).mock(return_value=httpx.Response(503))
+ result = await wildfire.fetch_wildfires(edge.fetcher, region="north_america")
+
+ assert result["fires_by_region"]["north_america"] == {
+ "count": 0,
+ "top_clusters": [],
+ "error": _firms_region_down("north_america"),
+ }
+ assert result["error"] == _FIRMS_ALL_DOWN
+ assert result["degraded"] is True
+ assert result["reason"] == "firms_fetch_failed"
+ assert result["failed_regions"] == ["north_america"]
+ assert result["total_fires"] == 0
+
+
+async def test_firms_failed_region_among_answered_ones_is_partial(edge: _Edge) -> None:
+ def _by_region(request: httpx.Request) -> httpx.Response:
+ if "/-25,35,45,72/" in request.url.path: # europe
+ return httpx.Response(503)
+ return httpx.Response(200, text=_firms([(10.0, 10.0)]))
+
+ with respx.mock(assert_all_mocked=True) as router:
+ route = router.get(url__regex=_URLS["firms"]).mock(side_effect=_by_region)
+ result = await wildfire.fetch_wildfires(edge.fetcher)
+
+ assert route.call_count == 9
+ assert "error" not in result
+ assert result["degraded"] is True
+ assert result["failed_regions"] == ["europe"]
+ assert result["partial_errors"] == [_firms_region_down("europe")]
+ assert result["fires_by_region"]["europe"]["error"] == _firms_region_down("europe")
+ answered = {k: v for k, v in result["fires_by_region"].items() if k != "europe"}
+ assert len(answered) == 8
+ for region in answered.values():
+ assert "error" not in region
+ assert (region["count"], region["cluster_count"]) == (1, 1)
+ assert len(region["top_clusters"]) == 1
+ assert result["total_fires"] == 8
+
+
+async def test_firms_answer_says_how_many_clusters_it_cut(edge: _Edge) -> None:
+ # 3 fires in one 0.5-degree cell plus 24 single fires in 24 others:
+ # 25 clusters, of which the 20 largest are listed.
+ fires = [_IN] * 3 + [(60.0, -140.0 + i) for i in range(24)]
+ with respx.mock(assert_all_mocked=True) as router:
+ router.get(url__regex=_URLS["firms"]).mock(
+ return_value=httpx.Response(200, text=_firms(fires))
+ )
+ result = await wildfire.fetch_wildfires(edge.fetcher, region="north_america")
+
+ region = result["fires_by_region"]["north_america"]
+ assert region["count"] == 27
+ assert region["cluster_count"] == 25
+ assert len(region["top_clusters"]) == wildfire.TOP_CLUSTERS_PER_REGION == 20
+ assert region["top_clusters"][0] == {
+ "lat": 40.5, "lon": -80.0, "fire_count": 3, "max_frp": 12.0,
+ }
+
+
+# ---------------------------------------------------------------------------
+# Sources: when upstream answered, and whether the answer is an expired copy
+# ---------------------------------------------------------------------------
+
+
+async def test_a_cached_answer_reports_when_upstream_answered(edge: _Edge) -> None:
+ with respx.mock(assert_all_mocked=True) as router:
+ route = router.get(url__regex=_URLS["usgs"]).mock(
+ return_value=httpx.Response(200, json=_usgs([_IN]))
+ )
+ before = int(time.time())
+ fresh = await seismology.fetch_earthquakes(edge.fetcher, hours=72)
+ written = _age_entry(edge.db, "seismology:", 120.0, expire=False)
+ cached = await seismology.fetch_earthquakes(edge.fetcher, hours=72)
+
+ assert before <= _epoch(fresh["fetched_at"]) <= time.time()
+ # The second answer came from the live cache entry: its fetched_at is
+ # when USGS answered, 2 minutes before it was served.
+ assert route.call_count == 1
+ assert cached["fetched_at"] == _iso(written)
+ assert "_stale" not in cached
+
+
+async def test_usgs_expired_copy_is_marked_stale(edge: _Edge) -> None:
+ with respx.mock(assert_all_mocked=True) as router:
+ route = router.get(url__regex=_URLS["usgs"])
+ route.mock(return_value=httpx.Response(200, json=_usgs([_IN])))
+ await seismology.fetch_earthquakes(edge.fetcher, hours=72)
+ written = _age_entry(edge.db, "seismology:", 7200.0, expire=True)
+ route.mock(return_value=httpx.Response(503))
+ result = await seismology.fetch_earthquakes(edge.fetcher, hours=72)
+
+ assert route.call_count == 2
+ assert result["count"] == 1
+ assert result["_stale"] is True
+ assert 7200.0 <= result["_stale_age_seconds"] < 7260.0
+ assert abs(_epoch(result["fetched_at"]) - written) <= 2.0
+
+
[email protected]("mode", ["artlist", "timelinevolraw"])
+async def test_gdelt_expired_copy_is_marked_stale(edge: _Edge, mode: str) -> None:
+ with respx.mock(assert_all_mocked=True) as router:
+ route = router.get(url__regex=_URLS["gdelt"])
+ route.mock(return_value=httpx.Response(200, json=_RISING))
+ await news.fetch_gdelt_search(edge.fetcher, query="Pittsburgh", mode=mode)
+ written = _age_entry(edge.db, "news:gdelt:", 72000.0, expire=True)
+ route.mock(return_value=httpx.Response(429, text="limit"))
+ result = await news.fetch_gdelt_search(edge.fetcher, query="Pittsburgh", mode=mode)
+
+ assert route.call_count == 2
+ assert result["_stale"] is True
+ assert 72000.0 <= result["_stale_age_seconds"] < 72060.0
+ assert abs(_epoch(result["fetched_at"]) - written) <= 2.0
+
+
+async def test_firms_expired_copy_is_marked_stale(edge: _Edge) -> None:
+ with respx.mock(assert_all_mocked=True) as router:
+ route = router.get(url__regex=_URLS["firms"])
+ route.mock(return_value=httpx.Response(200, text=_firms([_IN])))
+ await wildfire.fetch_wildfires(edge.fetcher, region="north_america")
+ written = _age_entry(edge.db, "wildfire:csv:", 10800.0, expire=True)
+ route.mock(return_value=httpx.Response(503))
+ result = await wildfire.fetch_wildfires(edge.fetcher, region="north_america")
+
+ assert route.call_count == 2
+ region = result["fires_by_region"]["north_america"]
+ assert region["count"] == 1
+ assert region["_stale"] is True
+ assert 10800.0 <= region["_stale_age_seconds"] < 10860.0
+ assert region["fetched_at"] == _iso(written)
+ assert result["_stale"] is True
+ assert result["stale_regions"] == ["north_america"]
+ assert "error" not in result
+
+
+# ---------------------------------------------------------------------------
+# Sources: one cache entry per distinct request
+# ---------------------------------------------------------------------------
+
+
+async def test_gdelt_queries_that_reduce_to_one_ascii_string_get_their_own_answers(
+ edge: _Edge,
+) -> None:
+ """'"Київ"' and '"Суми"' both reduce to the ASCII string '______'."""
+
+ def _by_query(request: httpx.Request) -> httpx.Response:
+ query = request.url.params["query"]
+ return httpx.Response(
+ 200, json={"articles": [{"title": f"about {query}", "url": "https://example.org/a"}]}
+ )
+
+ with respx.mock(assert_all_mocked=True) as router:
+ route = router.get(url__regex=_URLS["gdelt"]).mock(side_effect=_by_query)
+ kyiv = await news.fetch_gdelt_search(edge.fetcher, query='"Київ"', mode="artlist")
+ sumy = await news.fetch_gdelt_search(edge.fetcher, query='"Суми"', mode="artlist")
+
+ assert route.call_count == 2
+ assert [a["title"] for a in kyiv["articles"]] == ['about "Київ"']
+ assert [a["title"] for a in sumy["articles"]] == ['about "Суми"']
+
+
+async def test_gdelt_answers_for_different_limits_do_not_share_a_cache_entry(
+ edge: _Edge,
+) -> None:
+ def _by_limit(request: httpx.Request) -> httpx.Response:
+ n = int(request.url.params["maxrecords"])
+ return httpx.Response(
+ 200, json={"articles": [{"title": f"t{i}", "url": f"https://example.org/{i}"}
+ for i in range(n)]}
+ )
+
+ with respx.mock(assert_all_mocked=True) as router:
+ route = router.get(url__regex=_URLS["gdelt"]).mock(side_effect=_by_limit)
+ ten = await news.fetch_gdelt_search(edge.fetcher, query="Pittsburgh", limit=10)
+ fifty = await news.fetch_gdelt_search(edge.fetcher, query="Pittsburgh", limit=50)
+
+ assert route.call_count == 2
+ assert (ten["count"], fifty["count"]) == (10, 50)
+
+
+async def test_usgs_answers_for_different_limits_do_not_share_a_cache_entry(
+ edge: _Edge,
+) -> None:
+ """A short list cached for one caller must not reach a caller that
+ asked for 50 and reads a list under its cap as complete."""
+
+ def _by_limit(request: httpx.Request) -> httpx.Response:
+ n = int(request.url.params["limit"])
+ return httpx.Response(200, json=_usgs([(-20.0 - i * 0.1, -70.0) for i in range(n)]))
+
+ with respx.mock(assert_all_mocked=True) as router:
+ route = router.get(url__regex=_URLS["usgs"]).mock(side_effect=_by_limit)
+ short = await seismology.fetch_earthquakes(edge.fetcher, hours=72, limit=5)
+ full = await seismology.fetch_earthquakes(edge.fetcher, hours=72, limit=50)
+
+ assert route.call_count == 2
+ assert (short["count"], full["count"]) == (5, 50)
+
+
+async def test_acled_answers_for_different_limits_do_not_share_a_cache_entry(
+ edge: _Edge,
+) -> None:
+ def _by_limit(request: httpx.Request) -> httpx.Response:
+ n = int(request.url.params["limit"])
+ return httpx.Response(200, json=_acled([(0.1 * i, 30.0) for i in range(n)]))
+
+ with respx.mock(assert_all_mocked=True) as router:
+ route = router.get(url__regex=_URLS["acled"]).mock(side_effect=_by_limit)
+ short = await conflict.fetch_acled_events(edge.fetcher, days=7, limit=15)
+ full = await conflict.fetch_acled_events(edge.fetcher, days=7, limit=100)
+
+ assert route.call_count == 2
+ assert (short["count"], full["count"]) == (15, 100)
+
+
+# ---------------------------------------------------------------------------
+# Escalation: a real outage is a gap, never a measured quiet
+# ---------------------------------------------------------------------------
+
+
+async def test_escalation_usgs_outage_is_a_gap_and_blocks_a_quiet_convergence(
+ edge: _Edge,
+) -> None:
+ """An aircraft and a battle in one cell: 2 events, under the 3 a cell
+ needs, so with earthquakes missing quiet cannot be told from missing."""
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ result, requests = await _escalate(
+ edge, usgs=503, adsb=_adsb([_IN]), acled=_acled([_IN])
+ )
+
+ assert len(requests["usgs"]) == 1
+ assert result["data_gaps"] == [
+ f"Earthquakes: {_USGS_DOWN}",
+ "Convergence: not scored; no convergent cell among military flights, "
+ "conflict events, wildfires, but earthquakes answered only partly or "
+ "not at all, so quiet cannot be told from missing.",
+ ]
+ assert result["convergence_signal"]["inputs_failed"] == ["earthquakes"]
+ assert result["components"]["convergence"] is None
+ assert result["zero_filled_components"] == []
+ # military 1.0 + conflict 0.5 = 1.5 of the 92 points measured: 1.63.
+ assert result["score"] == 1.6
+ # baseline 0 + news 20 + military 20 + conflict 20 + unrest 12 = 72 of
+ # 92: 78.26.
+ assert result["score_ceiling"] == 78.3
+
+
+async def test_escalation_military_outage_is_zero_filled_not_an_empty_sky(
+ edge: _Edge,
+) -> None:
+ """adsb.lol and its OpenSky fallback both down: military.py answers
+ ``source: "none"`` with an empty list, which is an outage."""
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ result, requests = await _escalate(
+ edge,
+ adsb=503,
+ opensky=503,
+ usgs=_usgs([_IN]),
+ acled=_acled([_IN]),
+ firms=_firms([_IN]),
+ )
+
+ assert (len(requests["adsb"]), len(requests["opensky"])) == (1, 1)
+ assert result["data_gaps"] == [
+ f"Military flights: {aoi._MILITARY_NO_SOURCE}",
+ # quake + battle + fire in cell (40, -80): 3 x (1 + sqrt 3) = 8.2.
+ "Convergence: computed without full military flights data; 8.2 is a "
+ "lower bound (the missing events could only raise it).",
+ ]
+ assert aoi._MILITARY_NO_SOURCE == (
+ "no military flight source answered (adsb.lol failed or returned no "
+ "aircraft, and the OpenSky fallback failed)"
+ )
+ assert result["zero_filled_components"] == ["military"]
+ assert result["lower_bound_components"] == ["convergence"]
+ assert result["convergence_signal"]["inputs_failed"] == ["military_flights"]
+ # The ceiling holds the zero-filled military component at 0:
+ # news 20 + conflict 20 + unrest 12 + convergence 8 = 60 of 100.
+ assert result["score_ceiling"] == 60.0
+
+
+async def test_escalation_firms_outage_is_a_gap_not_a_fireless_area(
+ edge: _Edge,
+) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ result, requests = await _escalate(
+ edge, firms=503, usgs=_usgs([_IN]), adsb=_adsb([_IN]), acled=_acled([_IN])
+ )
+
+ assert len(requests["firms"]) == 1
+ assert result["data_gaps"] == [
+ f"Wildfires: {_firms_region_down('north_america')}",
+ "Convergence: computed without full wildfires data; 8.2 is a lower "
+ "bound (the missing events could only raise it).",
+ ]
+ assert result["convergence_signal"]["inputs_failed"] == ["wildfires"]
+ assert result["lower_bound_components"] == ["convergence"]
+
+
+async def test_escalation_names_a_failed_firms_region_next_to_an_answered_one(
+ edge: _Edge,
+) -> None:
+ """A circle at 15.2 N straddles FIRMS's north_america box (from 15 N)
+ and south_america box (to 15 N). south_america is down; the fire
+ north_america lists is still counted, and the gap is named."""
+ aoi.define_aoi(edge.store, "Border", 15.2, -80.0, 50.0)
+
+ def _by_region(request: httpx.Request) -> httpx.Response:
+ if "/-85,-60,-30,15/" in request.url.path: # south_america
+ return httpx.Response(503)
+ return httpx.Response(200, text=_firms([(15.2, -80.0)]))
+
+ result, requests = await _escalate(edge, "Border", firms=_by_region)
+
+ assert len(requests["firms"]) == 2
+ assert (
+ f"Wildfires: partial coverage: {_firms_region_down('south_america')}"
+ in result["data_gaps"]
+ )
+ signal = result["convergence_signal"]
+ assert signal["events_by_domain"]["wildfires"] == 1
+ assert signal["inputs_partial"] == ["wildfires"]
+
+
+async def test_brief_names_a_failed_firms_region_next_to_an_answered_one(
+ edge: _Edge,
+) -> None:
+ aoi.define_aoi(edge.store, "Border", 15.2, -80.0, 50.0)
+
+ def _by_region(request: httpx.Request) -> httpx.Response:
+ if "/-85,-60,-30,15/" in request.url.path: # south_america
+ return httpx.Response(503)
+ return httpx.Response(200, text=_firms([(15.2, -80.0)]))
+
+ with respx.mock(assert_all_mocked=True, assert_all_called=False) as router:
+ _routes(router, firms=_by_region)
+ brief = await aoi.fetch_aoi_brief(edge.fetcher, edge.store, "Border")
+
+ assert brief["counts"]["wildfires"] == 1
+ assert (
+ f"Wildfires: partial coverage: {_firms_region_down('south_america')}"
+ in brief["data_gaps"]
+ )
+
+
+# ---------------------------------------------------------------------------
+# Escalation: an expired cached copy is refused, with its age named
+# ---------------------------------------------------------------------------
+
+
+async def test_escalation_refuses_an_expired_usgs_copy(edge: _Edge) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ events = {"usgs": _usgs([_IN]), "adsb": _adsb([_IN]), "acled": _acled([_IN])}
+ first, _ = await _escalate(edge, **events)
+ # Fresh: quake + aircraft + battle in one cell, 8.2, component 8.0.
+ assert first["components"]["convergence"] == 8.0
+
+ written = _age_entry(edge.db, "seismology:", 2 * 86400, expire=True)
+ second, requests = await _escalate(edge, **{**events, "usgs": 503})
+
+ assert len(requests["usgs"]) == 1
+ gap = re.fullmatch(
+ "Earthquakes: " + _stale_pattern("USGS answer", r"2\.0 days"),
+ second["data_gaps"][0],
+ )
+ assert gap, second["data_gaps"]
+ assert abs(_epoch(gap.group(1)) - written) <= 2.0
+ assert second["data_gaps"][1:] == [
+ "Convergence: not scored; no convergent cell among military flights, "
+ "conflict events, wildfires, but earthquakes answered only partly or "
+ "not at all, so quiet cannot be told from missing.",
+ ]
+ assert second["components"]["convergence"] is None
+ assert second["convergence_signal"]["fetched_at"]["earthquakes"] is None
+
+
+async def test_escalation_refuses_an_expired_gdelt_copy_without_blaming_gdelt(
+ edge: _Edge,
+) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ first, _ = await _escalate(edge, gdelt=_RISING)
+ # Fresh: +50% share, news = 0.2 x 50 = 10.0.
+ assert first["components"]["news"] == 10.0
+
+ written = _age_entry(edge.db, "news:gdelt:", 20 * 3600, expire=True)
+ second, requests = await _escalate(edge, gdelt=429)
+
+ assert len(requests["gdelt"]) == 1
+ assert second["components"]["news"] is None
+ assert second["news_signal"]["fetched_at"] is None
+ assert len(second["data_gaps"]) == 1
+ gap = re.fullmatch(
+ "News: " + _stale_pattern("GDELT answer", r"20\.0 h") + r"\.",
+ second["data_gaps"][0],
+ )
+ assert gap, second["data_gaps"]
+ assert abs(_epoch(gap.group(1)) - written) <= 2.0
+ # The copy is ours; nothing says GDELT itself had no data.
+ assert "GDELT returned" not in second["data_gaps"][0]
+ assert "GDELT has no data" not in second["data_gaps"][0]
+
+
+async def test_escalation_refuses_an_expired_firms_copy(edge: _Edge) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ events = {"usgs": _usgs([_IN]), "acled": _acled([_IN]), "firms": _firms([_IN])}
+ first, _ = await _escalate(edge, **events)
+ assert first["components"]["convergence"] == 8.0
+
+ written = _age_entry(edge.db, "wildfire:csv:", 3 * 3600, expire=True)
+ second, requests = await _escalate(edge, **{**events, "firms": 503})
+
+ assert len(requests["firms"]) == 1
+ gap = re.fullmatch(
+ "Wildfires: " + _stale_pattern("NASA FIRMS answer for north_america", r"3\.0 h"),
+ second["data_gaps"][0],
+ )
+ assert gap, second["data_gaps"]
+ assert abs(_epoch(gap.group(1)) - written) <= 2.0
+ assert second["components"]["convergence"] is None
+ assert second["convergence_signal"]["inputs_failed"] == ["wildfires"]
+
+
+async def test_escalation_refuses_an_expired_acled_copy(edge: _Edge) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ events = {"usgs": _usgs([_IN]), "adsb": _adsb([_IN]), "acled": _acled([_IN])}
+ first, _ = await _escalate(edge, **events)
+ assert first["components"]["conflict"] == 0.5
+
+ _age_entry(edge.db, "conflict:acled:", 2 * 86400, expire=True)
+ second, requests = await _escalate(edge, **{**events, "acled": 503})
+
+ assert len(requests["acled"]) == 1
+ assert re.fullmatch(
+ "Conflict events: " + _stale_pattern("ACLED answer", r"2\.0 days"),
+ second["data_gaps"][0],
+ ), second["data_gaps"]
+ assert second["zero_filled_components"] == ["conflict", "social_unrest"]
+ assert second["components"]["conflict"] == 0.0
+ assert second["components"]["convergence"] is None
+
+
+# ---------------------------------------------------------------------------
+# Escalation: each AOI's news is its own
+# ---------------------------------------------------------------------------
+
+
+async def test_escalation_news_for_two_non_latin_places_is_not_shared(
+ edge: _Edge,
+) -> None:
+ aoi.define_aoi(edge.store, "Kyiv", 50.4501, 30.5234, 30.0)
+ aoi.define_aoi(edge.store, "Sumy", 50.9077, 34.7981, 30.0)
+
+ def _place(request: httpx.Request) -> httpx.Response:
+ city = "Київ" if float(request.url.params["lat"]) < 50.7 else "Суми"
+ return httpx.Response(200, json={"display_name": city, "address": {"city": city}})
+
+ bodies = {
+ '"Київ"': _timeline([(10, 1000)] * 7, [(10, 1000)] * 7),
+ '"Суми"': _timeline([(10, 1000)] * 7, [(30, 1000)] * 7),
+ }
+
+ def _gdelt(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(200, json=bodies[request.url.params["query"]])
+
+ kyiv, _ = await _escalate(edge, "Kyiv", nominatim=_place, gdelt=_gdelt)
+ sumy, requests = await _escalate(edge, "Sumy", nominatim=_place, gdelt=_gdelt)
+
+ # Sumy's timeline was fetched, not served from Kyiv's cache entry.
+ assert [r.url.params["query"] for r in requests["gdelt"]] == ['"Суми"']
+ assert kyiv["news_signal"]["change_pct"] == 0.0
+ assert sumy["news_signal"]["query"] == '"Суми"'
+ # expected 70 of 7,000 x 7,000 = 70; change = 100 x (210 - 70) / 70 = 200.
+ assert sumy["news_signal"]["change_pct"] == 200.0
+ assert sumy["components"]["news"] == 20.0
+
+
+# ---------------------------------------------------------------------------
+# Escalation: a global sample cut at its cap is partial coverage
+# ---------------------------------------------------------------------------
+
+
+async def test_escalation_usgs_answer_at_its_cap_is_partial(edge: _Edge) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ newest_ms = int(time.time() * 1000) - 3_600_000
+ quakes = _usgs([_IN] + [(-20.0 - i * 0.5, -70.0) for i in range(49)], newest_ms)
+ oldest = _iso((newest_ms - 49 * 60_000) / 1000)
+
+ result, requests = await _escalate(
+ edge, usgs=quakes, adsb=_adsb([_IN]), acled=_acled([_IN])
+ )
+
+ assert requests["usgs"][-1].url.params["limit"] == "50"
+ assert result["data_gaps"] == [
+ "Earthquakes: partial coverage: USGS answered with its cap of 50 M4.5+ "
+ f"quakes worldwide, newest first, so only quakes since {oldest} are in; "
+ "earlier ones in the 72 h window are missing",
+ "Convergence: computed without full earthquakes data; 8.2 is a lower "
+ "bound (the missing events could only raise it).",
+ ]
+ assert result["convergence_signal"]["inputs_partial"] == ["earthquakes"]
+ assert result["lower_bound_components"] == ["convergence"]
+
+
+async def test_escalation_acled_answer_at_its_cap_is_partial(edge: _Edge) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ battles = _acled([_IN] + [(0.5 * i, 30.0) for i in range(99)])
+
+ result, requests = await _escalate(edge, acled=battles)
+
+ assert requests["acled"][-1].url.params["limit"] == "100"
+ assert result["data_gaps"] == [
+ "Conflict events: partial coverage: ACLED answered with its cap of 100 "
+ "events worldwide for 7 days, so in-area events outside that sample "
+ "are missing",
+ "Convergence: not scored; no convergent cell among earthquakes, "
+ "military flights, conflict events, wildfires, but conflict events "
+ "answered only partly or not at all, so quiet cannot be told from "
+ "missing.",
+ ]
+ assert result["lower_bound_components"] == ["conflict", "social_unrest"]
+ assert result["components"]["conflict"] == 0.5
+
+
+async def test_escalation_firms_region_cut_at_its_cap_is_partial(edge: _Edge) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ fires = [_IN] * 3 + [(60.0, -140.0 + i) for i in range(24)]
+
+ result, _ = await _escalate(edge, firms=_firms(fires))
+
+ assert result["data_gaps"] == [
+ "Wildfires: partial coverage: NASA FIRMS listed only the 20 largest of "
+ "25 fire clusters for north_america, so smaller in-area clusters can "
+ "be missing",
+ "Convergence: not scored; no convergent cell among earthquakes, "
+ "military flights, conflict events, wildfires, but wildfires answered "
+ "only partly or not at all, so quiet cannot be told from missing.",
+ ]
+ assert result["convergence_signal"]["events_by_domain"]["wildfires"] == 1
+
+
+# ---------------------------------------------------------------------------
+# Escalation: per-domain windows and fetch times
+# ---------------------------------------------------------------------------
+
+
+async def test_escalation_names_each_inputs_window_and_fetch_time(edge: _Edge) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ before = int(time.time())
+ result, requests = await _escalate(
+ edge,
+ usgs=_usgs([_IN]),
+ adsb=_adsb([_IN]),
+ acled=_acled([_IN]),
+ firms=_firms([_IN]),
+ )
+ after = time.time()
+
+ signal = result["convergence_signal"]
+ domains = {"earthquakes", "military_flights", "conflict_events", "wildfires"}
+ assert set(signal["windows"]) == set(signal["fetched_at"]) == domains
+ for domain in ("earthquakes", "conflict_events", "wildfires"):
+ assert before <= _epoch(signal["fetched_at"][domain]) <= after
+ # military.py does not report when it fetched; null, and the window says so.
+ assert signal["fetched_at"]["military_flights"] is None
+ assert "fetched_at is null" in signal["windows"]["military_flights"]
+ assert before <= _epoch(result["news_signal"]["fetched_at"]) <= after
+ # The window text states the day range the FIRMS request really asks for.
+ assert requests["firms"][-1].url.path.endswith("/2")
+ assert "day range of 2" in signal["windows"]["wildfires"]
+ assert "72 h" in signal["windows"]["earthquakes"]
+ assert "7 days" in signal["windows"]["conflict_events"]
+
+
+def test_news_trend_states_how_far_into_its_current_step_it_is() -> None:
+ trend = aoi.news_coverage_trend(_FLAT["timeline"], now=_NOW)
+
+ assert trend["current_step_start"] == "2026-10-17T00:00:00Z"
+ assert trend["current_step_elapsed"] == 0.75 # 18 of 24 hours
+
+
+# ---------------------------------------------------------------------------
+# Escalation: the convergence grid does not split a compact cluster
+# ---------------------------------------------------------------------------
+
+
+def _scoped(quakes=(), aircraft=(), battles=(), fires=()) -> dict:
+ return {
+ "earthquakes": {"items": [{"latitude": a, "longitude": o} for a, o in quakes]},
+ "military_flights": {
+ "items": [{"latitude": a, "longitude": o} for a, o in aircraft]
+ },
+ "conflict_events": {"items": [{"latitude": a, "longitude": o} for a, o in battles]},
+ "wildfires": {"items": [{"lat": a, "lon": o} for a, o in fires]},
+ }
+
+
+async def test_escalation_cluster_straddling_a_degree_line_converges(
+ edge: _Edge,
+) -> None:
+ """Three domains within 2.6 km, astride lon -80 (Pittsburgh's centre
+ is 0.0041 degrees east of it). The unshifted grid puts the quake in
+ cell -81 and the other two in -80; the grid shifted half a degree in
+ longitude holds all three."""
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ result, _ = await _escalate(
+ edge,
+ usgs=_usgs([(40.5, -80.01)]),
+ adsb=_adsb([(40.5, -79.99)]),
+ acled=_acled([(40.5, -79.98)]),
+ )
+
+ signal = result["convergence_signal"]
+ assert signal["grid_offset_deg"] == {"lat": 0.0, "lon": 0.5}
+ assert signal["cells"][0]["event_count"] == 3
+ assert (signal["cells"][0]["lat"], signal["cells"][0]["lon"]) == (40.5, -80.0)
+ # 3 domains x (1 + sqrt 3) = 8.2; component min(8, 16.4) = 8.0.
+ assert signal["score"] == 8.2
+ assert result["components"]["convergence"] == 8.0
+ assert result["data_gaps"] == []
+
+
+async def test_escalation_cluster_straddling_the_antimeridian_converges(
+ edge: _Edge,
+) -> None:
+ aoi.define_aoi(edge.store, "Dateline", -16.5, 179.9, 50.0)
+ result, _ = await _escalate(
+ edge,
+ "Dateline",
+ usgs=_usgs([(-16.5, 179.95)]),
+ adsb=_adsb([(-16.5, -179.95)]),
+ acled=_acled([(-16.5, 179.9)]),
+ )
+
+ signal = result["convergence_signal"]
+ assert signal["events_by_domain"] == {
+ "earthquakes": 1, "military_flights": 1, "conflict_events": 1, "wildfires": 0,
+ }
+ assert signal["cells"][0]["event_count"] == 3
+ assert (signal["cells"][0]["lat"], signal["cells"][0]["lon"]) == (-16.5, 180.0)
+ assert result["components"]["convergence"] == 8.0
+
+
+def test_convergence_cluster_astride_a_grid_corner_converges() -> None:
+ # Astride lat 41 and lon -80: only the grid shifted on both axes holds
+ # all three; its cell centre is (41.0, -80.0).
+ result = aoi.aoi_convergence(
+ _scoped(quakes=[(40.99, -80.01)], aircraft=[(41.01, -79.99)], battles=[(41.0, -80.0)])
+ )
+
+ assert result["grid_offset_deg"] == {"lat": 0.5, "lon": 0.5}
+ assert result["score"] == 8.2
+ assert (result["cells"][0]["lat"], result["cells"][0]["lon"]) == (41.0, -80.0)
+ assert result["lower_bound"] is False
+
+
+def test_convergence_cluster_spanning_over_half_a_degree_can_still_split() -> None:
+ """The stated limit: a 0.6-degree span (lon -80.55 to -79.95) is split
+ on the unshifted grid (-81 | -80) and on the shifted one (-81 | -80
+ after +0.5), so no cell holds 3 events."""
+ result = aoi.aoi_convergence(
+ _scoped(quakes=[(40.5, -80.55)], aircraft=[(40.5, -80.05)], battles=[(40.5, -79.95)])
+ )
+
+ assert result["convergent_cells"] == 0
+ assert result["score"] == 0.0
+
+
+# ---------------------------------------------------------------------------
+# Escalation: the news scope is named where it bites
+# ---------------------------------------------------------------------------
+
+
+async def test_escalation_names_the_news_scope_of_a_large_area(edge: _Edge) -> None:
+ aoi.define_aoi(edge.store, "Western PA", 40.4406, -79.9959, 200.0)
+ result, _ = await _escalate(edge, "Western PA")
+
+ assert result["data_gaps"] == [
+ "News: scoped to Pittsburgh, Allegheny County, the place at the AOI's "
+ "centre; the area reaches 200 km from its centre, so coverage of other "
+ "places inside it is not counted."
+ ]
+
+
+async def test_escalation_names_why_a_shape_centred_at_sea_has_no_news(
+ edge: _Edge,
+) -> None:
+ aoi.define_polygon_aoi(
+ edge.store, "Strait", [[26.0, 56.0], [26.0, 57.0], [27.0, 57.0], [27.0, 56.0]]
+ )
+ result, requests = await _escalate(edge, "Strait", nominatim=_NOMINATIM_UNNAMED)
+
+ assert requests["gdelt"] == []
+ assert result["components"]["news"] is None
+ assert result["data_gaps"][-1] == (
+ "News: the query is built from the place at the AOI's centre only, so a "
+ "polygon whose centre cannot be placed gets no news score even where it "
+ "covers named places."
+ )
+
+
+async def test_escalation_geocoder_outage_reason_is_not_prefixed_twice(
+ edge: _Edge,
+) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ result, requests = await _escalate(edge, nominatim=503)
+
+ assert len(requests["nominatim"]) == 1
+ assert result["news_scoping"] == {
+ "basis": "unavailable",
+ "query": None,
+ "reason": _GEOCODER_DOWN,
+ }
+ assert result["data_gaps"] == [
+ f"News: not scored: the area could not be placed ({_GEOCODER_DOWN}), and "
+ "counting mentions of the AOI's own name would not measure coverage of "
+ "the area."
+ ]
+
+
+# ---------------------------------------------------------------------------
+# Escalation: what the score can reach, and the news gate's edges
+# ---------------------------------------------------------------------------
+
+
+ ("specs", "ceiling"),
+ [
+ # Everything measured: 80 of 100 (the baseline is a structural 0).
+ ({}, 80.0),
+ # News unplaced: 60 of 80.
+ ({"nominatim": _NOMINATIM_UNNAMED}, 75.0),
+ # News unplaced and convergence unscored (USGS down, no cell): 52 of 72.
+ ({"nominatim": _NOMINATIM_UNNAMED, "usgs": 503}, 72.2),
+ # ACLED down: conflict and unrest zero-filled, convergence unscored:
+ # news 20 + military 20 = 40 of 92.
+ ({"acled": 503}, 43.5),
+ ],
+)
+async def test_escalation_score_ceiling(edge: _Edge, specs: dict, ceiling: float) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ result, _ = await _escalate(edge, **specs)
+
+ assert result["score_ceiling"] == ceiling
+ assert "baseline is a structural 0" in result["score_method"]
+
+
+ ("current_norm", "news"),
+ [
+ # 2,100 monitored against 7,000: 0.3 of the other window, refused.
+ (300, None),
+ # 3,500 against 7,000: exactly half, compared (flat share: 0.0).
+ (500, 0.0),
+ ],
+)
+async def test_escalation_news_intake_gate_boundary(
+ edge: _Edge, current_norm: int, news: float | None
+) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ share_kept = [(current_norm // 100, current_norm)] * 7
+ result, _ = await _escalate(edge, gdelt=_timeline([(10, 1000)] * 7, share_kept))
+
+ assert result["components"]["news"] == news
+
+
+async def test_escalation_news_with_no_monitored_volume_is_a_gap_not_a_crash(
+ edge: _Edge,
+) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ result, _ = await _escalate(edge, gdelt=_timeline([(0, 0)] * 7, [(0, 0)] * 7))
+
+ assert result["components"]["news"] is None
+ assert result["data_gaps"] == [
+ "News: GDELT intake too uneven to compare: it monitored 0 articles in "
+ "the prior 7 days (7 of 7 steps with data) and 0 in the latest 7 (7 of "
+ "7), so a comparison would measure GDELT's ingestion gaps, not the news."
+ ]
+
+
+async def test_escalation_falling_news_share_scores_zero_not_negative(
+ edge: _Edge,
+) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ falling = _timeline([(20, 1000)] * 7, [(10, 1000)] * 7)
+ result, _ = await _escalate(edge, gdelt=falling)
+
+ # expected 140; change = 100 x (70 - 140) / 140 = -50.0.
+ assert result["news_signal"]["change_pct"] == -50.0
+ assert result["components"]["news"] == 0.0
+
+
+async def test_escalation_one_domain_alone_is_not_convergence(edge: _Edge) -> None:
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ result, _ = await _escalate(edge, adsb=_adsb([_IN, _IN, _IN]))
+
+ assert result["components"]["military"] == 3.0
+ # 3 aircraft in one cell are 1 domain, under the 2 a cell needs.
+ assert result["convergence_signal"]["convergent_cells"] == 0
+ assert result["components"]["convergence"] == 0.0
+
+
+# ---------------------------------------------------------------------------
+# Scoping helpers: an unrecognized answer is unknown, not empty
+# ---------------------------------------------------------------------------
+
+_PGH_ROW = {"name": "Pittsburgh", "lat": 40.4406, "lon": -79.9959, "radius_km": 50.0,
+ "kind": "circle"}
+
+
[email protected]("answer", [{}, {"count": 0, "source": "usgs"}])
+def test_scoping_an_answer_without_its_list_is_unknown(answer: dict) -> None:
+ assert aoi._scope_to_aoi(answer, "earthquakes", _PGH_ROW, "latitude", "longitude") == {
+ "error": "the answer carried no earthquakes list, so what is inside the area "
+ "is unknown"
+ }
+
+
+ ("answer", "error"),
+ [
+ # military.py's shape today when both sources fail.
+ ({"aircraft": [], "count": 0, "source": "none"}, _MILITARY_DOWN),
+ # The same shape with an outage marker added.
+ (
+ {"aircraft": [], "count": 0, "source": "none", "error": "both sources failed"},
+ "both sources failed",
+ ),
+ ({"count": 0, "source": "adsb.lol"}, "the military flights answer carried no aircraft list"),
+ ],
+)
+async def test_military_answer_without_a_source_or_list_is_an_outage(
+ edge: _Edge, monkeypatch: pytest.MonkeyPatch, answer: dict, error: str
+) -> None:
+ async def _answer(fetcher, bbox=None) -> dict:
+ return dict(answer)
+
+ monkeypatch.setattr(military, "fetch_military_flights", _answer)
+ result = await aoi._fetch_military_merged(edge.fetcher, ["39.9,-80.6,41.0,-79.4"])
+
+ assert result == {"error": error}
+
+
+async def test_changes_skip_an_in_fence_item_whose_key_cannot_be_built(
+ edge: _Edge, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A wildfire cluster whose lat is not a number reaches the diff (the
+ scoping is patched to let it through): it is skipped, not a crash."""
+ aoi.define_aoi(edge.store, "Pittsburgh", *_PGH)
+ real_filter = aoi.filter_by_aoi
+
+ def _leaky_filter(items, aoi_row, lat_key="latitude", lon_key="longitude"):
+ kept = real_filter(items, aoi_row, lat_key, lon_key)
+ if any("fire_count" in item for item in items):
+ kept.append({"lat": "unplaceable", "lon": -79.9, "fire_count": 1,
+ "distance_km": 0.0})
+ return kept
+
+ monkeypatch.setattr(aoi, "filter_by_aoi", _leaky_filter)
+ with respx.mock(assert_all_mocked=True, assert_all_called=False) as router:
+ _routes(router, firms=_firms([_IN]))
+ result = await aoi.fetch_aoi_changes(edge.fetcher, edge.store, "Pittsburgh")
+
+ assert result["baseline"] is True
+ assert result["counts"]["wildfires"] == 1
+
+
+# ---------------------------------------------------------------------------
+# CLI: a zero-filled component is not a measured 0
+# ---------------------------------------------------------------------------
+
+
+def test_cli_escalation_marks_zero_filled_and_lower_bound_components(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The CLI renders a real escalation result: both military sources
+ down (zero-filled) and USGS at its cap (convergence a lower bound)."""
+ _hermetic(monkeypatch)
+
+ async def _measure() -> dict:
+ env = _Edge(tmp_path)
+ try:
+ aoi.define_aoi(env.store, "Pittsburgh", *_PGH)
+ quakes = _usgs([_IN] + [(-20.0 - i * 0.5, -70.0) for i in range(49)])
+ result, _ = await _escalate(
+ env,
+ adsb=503,
+ opensky=503,
+ usgs=quakes,
+ acled=_acled([_IN]),
+ firms=_firms([_IN]),
+ )
+ return result
+ finally:
+ await env.aclose()
+
+ result = asyncio.run(_measure())
+ assert result["zero_filled_components"] == ["military"]
+ assert result["lower_bound_components"] == ["convergence"]
+
+ async def _canned(*args, **kwargs) -> dict:
+ return result
+
+ monkeypatch.setattr(cli.aoi_analysis, "fetch_aoi_escalation", _canned)
+ run = CliRunner().invoke(
+ cli.main, ["aoi", "escalation", "Pittsburgh"], catch_exceptions=False
+ )
+ out = " ".join(run.output.split())
+
+ assert run.exit_code == 0
+ # conflict 0.5 + convergence 8.0 = 8.5 of 100.
+ assert "Pittsburgh escalation: 8.5 on a 0-100 scale" in out
+ assert (
+ "Highest score reachable with the components measured: 60.0 (an AOI has "
+ "no curated baseline)" in out
+ )
+ assert (
+ "Computed from: baseline, news, military, conflict, social_unrest, "
+ "convergence" in out
+ )
+ assert "military not measured (fetch failed; scored as 0)" in out
+ assert "convergence 8.0 (lower bound)" in out
+ assert f"Military flights: {aoi._MILITARY_NO_SOURCE}" in out
diff --git a/src/world_intel_mcp/tools/aoi.py b/src/world_intel_mcp/tools/aoi.py
index ddd55d8..afe7e20 100644
--- a/src/world_intel_mcp/tools/aoi.py
+++ b/src/world_intel_mcp/tools/aoi.py
@@ -77,7 +77,7 @@ TOOLS: list[Tool] = [
),
Tool(
name="intel_aoi_escalation",
- description="Run the hotspot escalation scoring (baseline, news, military, conflict, social-unrest and convergence components; 0-100) on a user-defined AOI instead of only the 22 built-in intel hotspots. News: the rise in the area's share of GDELT coverage, the last 7 days against the 7 before, for the reverse-geocoded place (news_signal shows the counts). Convergence: multi-domain convergence of the earthquakes, military flights, ACLED events and wildfires inside the AOI's exact shape (circle, polygon or corridor; convergence_signal shows the cells). If the news or convergence inputs fail, that component is null and explained in data_gaps, never a 0; computed_from lists the components the score was computed from, and zero_filled_components any of those that are a 0 only because the military or ACLED fetch failed. Required: name (must already be defined via intel_aoi_define).",
+ description="Run the hotspot escalation scoring (baseline, news, military, conflict, social-unrest and convergence components; 0-100) on a user-defined AOI instead of only the 22 built-in intel hotspots. An AOI has no curated baseline, so baseline is 0 and the score tops out at 80 (score_ceiling gives this call's ceiling). News: the change in the area's share of GDELT coverage, the 7 days ending with GDELT's current daily step (still filling) against the 7 days before, for the settlement and county at the AOI's centre; only a rise scores, and weeks with uneven GDELT intake are not compared (news_signal shows the counts). Convergence: multi-domain convergence of the earthquakes, military flights, ACLED events and wildfires inside the AOI's exact shape (circle, polygon or corridor; convergence_signal shows the cells, each domain's window and fetch time). A source that did not answer, or answered only with an expired cached copy, counts as missing, never as quiet. If the news or convergence inputs fail, that component is null and explained in data_gaps, never a 0; computed_from lists the components the score was computed from, zero_filled_components any of those that are a 0 only because the military or ACLED fetch failed, and lower_bound_components any that partial data (a capped global sample, a failed region) can only have understated. Required: name (must already be defined via intel_aoi_define).",
inputSchema={
"type": "object",
"properties": {