160-tool MCP server for real-time global intelligence from free public APIs: markets, liquidity, prediction markets, SEC filings, conflict, military, aircraft-cohort early warning, migration and border flows, cyber, climate, news and more. Dated observation history, 29 research prompts, cited briefs, geofences, SSE dashboard. MIT, no paid API keys.
Python ai-toolsai-watchanthropicclaudecybersecuritydashboardgeofencinggeopoliticalgeospatialintelligencemarketsmcpmigrationmilitarymodel-context-protocolnuclearosintreal-timespace-weatherthreat-intelligence
Add aircraft-cohort early-warning tools (approach inspired by kylemcdonald/ews)
Phoenix Agent (mac-studio)82f32d140000
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4c40d67..4fa5fcb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,54 @@# Changelog+## Unreleased++Aircraft-cohort early warning, approach inspired by+[kylemcdonald/ews](https://github.com/kylemcdonald/ews) (independent+implementation; no ews code used).++### Added+- `intel_jet_cohort_snapshot`: live airborne snapshot of the business-jet+ cohort (69 ICAO type designators in one adsb.lol `/v2/type` request) or+ the military cohort (`/v2/mil`), with per-type counts and PIA/LADD+ flags. Each call learns cohort membership into a `jet_cohort` table in+ the cache DB. The collector gains `bizjet_cohort` and `military_cohort`+ so the cohort keeps learning 24/7 (collector sources 51 -> 53).+- `intel_jet_activity_anomaly`: peak concurrent airborne cohort aircraft+ in a UTC half-hour, from adsb.lol `globe_history` heatmaps, against the+ same slot on 2-8 prior same-weekday dates; dates within a day of a US+ federal holiday are swapped for earlier weeks. Robust z with a counting+ noise floor; a second z on the cohort's share of all tracked aircraft+ guards against feeder-coverage swings, and the level (1-5) uses the+ smaller. Deficits (z <= -3) are flagged too.+- `intel_jet_excess_origins`: takeoff/landing inference (ground/air+ transitions plus low climbs/descents at coverage edges), density+ clustering of endpoints across the current and baseline windows, and a+ departure/arrival anchor, regional, diffuse or no-excess label, with+ optional distance to a reference point.+- `Fetcher.get_bytes` (binary fetch with rate floor, retries, breaker;+ 404 reported distinctly) and an on-disk LRU for heatmaps+ (`WORLD_INTEL_HEATMAP_CACHE_MB`, default 1024).++### Data honesty+- Cohort selection bias is gated: only members first seen+ `min_learning_lead_hours` (default 24) before the window count. A fresh+ install answers `warming_up`. A negative lead is allowed for a first+ look but marks the result degraded and suppresses the alert level and+ pattern label (bypassing the gate measured 1,002 vs a 206 baseline+ median on 2026-10-11, i.e. pure selection artefact).+- Missing, unpublished or low-coverage heatmaps are listed in+ `data_gaps`; fewer than 3 usable baseline windows is+ `insufficient_baseline`, never a zero-excess "normal".++### Not ported from ews+- FAA / global registry cohort importers: the FAA ReleasableAircraft.zip+ answers 403 to non-browser clients, and the ADS-B Exchange database and+ `globe_history` are under JETNET terms (robots.txt disallows+ `/globe_history/`), so the cohort is learned from adsb.lol instead.+- Year-long backfill, learned holiday profiles and annual ratios,+ non-ICAO (`~hex`) activity stores, and the paid SMS/email/Telegram+ alerting stack.+## 0.10.0 - 2026-09-02Geofences become visible and their news becomes geographic: thediff --git a/CLAUDE.md b/CLAUDE.mdindex 8edea33..d9ea0e4 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co## What This Is-World Intelligence MCP Server: 128 tools across 30+ domains providing real-time global intelligence from free public APIs. Serves four interfaces: MCP stdio (for Claude Code/Cursor), a live Starlette dashboard with SSE, a Click CLI with Rich output, and a collector daemon for 24/7 vector store population. Python 3.11+, built with hatchling.+World Intelligence MCP Server: 135 tools across 30+ domains providing real-time global intelligence from free public APIs. Serves four interfaces: MCP stdio (for Claude Code/Cursor), a live Starlette dashboard with SSE, a Click CLI with Rich output, and a collector daemon for 24/7 vector store population. Python 3.11+, built with hatchling.## Commands@@ -47,7 +47,7 @@ collector.py (daemon) ──┘- `CircuitBreaker`: Per-source tracking. 3 consecutive failures trips the breaker for 5 minutes. Each RSS feed gets its own breaker (`rss:bbc_world`).- `Cache`: SQLite WAL-mode TTL cache. `get()` returns live data, `get_stale()` returns expired data for fallback.-**Tool registry** (`tools/*.py` + `runtime.py`, Phase 26): server.py is a thin shell; the 128 tools live in 12 domain modules under `tools/`, each exporting `TOOLS` (list of Tool definitions) and `HANDLERS` (tool name -> `async def h(arguments)`). Shared infrastructure (cache, circuit breaker, AOI store, vector store, fetcher) is constructed once in `runtime.py`; handlers reach it as `runtime.fetcher` etc. `tools/aggregate()` enforces TOOLS/HANDLERS parity and cross-module name uniqueness at import time — a drifted registry refuses to start.+**Tool registry** (`tools/*.py` + `runtime.py`, Phase 26): server.py is a thin shell; the 135 tools live in 12 domain modules under `tools/`, each exporting `TOOLS` (list of Tool definitions) and `HANDLERS` (tool name -> `async def h(arguments)`). Shared infrastructure (cache, circuit breaker, AOI store, vector store, fetcher) is constructed once in `runtime.py`; handlers reach it as `runtime.fetcher` etc. `tools/aggregate()` enforces TOOLS/HANDLERS parity and cross-module name uniqueness at import time — a drifted registry refuses to start.**Source modules** (`sources/*.py`): Each module exports `async def fetch_*(fetcher: Fetcher, **kwargs) -> dict`. Pure data fetching — no MCP awareness. 30+ modules covering markets, seismology, military, cyber, health, tech, environmental, etc.@@ -57,7 +57,7 @@ collector.py (daemon) ──┘**Vector store** (`vector_store.py`): Optional Qdrant + FastEmbed (BAAI/bge-small-en-v1.5, 384-dim ONNX). Async background worker queue (`asyncio.Queue` + `asyncio.to_thread()`) for non-blocking storage. Fetcher auto-stores on fresh HTTP fetches. 65+ source name → category mappings for filtered search.-**Collector** (`collector.py`): Standalone daemon for 24/7 vector store population. 51 sources organized by domain, with `--daemon`, `--interval`, `--sources` CLI args. Dynamic import via `_import_fetch_fn()`. Per-source timeout overrides in `SOURCE_TIMEOUTS` (the `aoi_digest` sweep gets 240 s; everything else the flat 45 s). Entry point: `intel-collector`.+**Collector** (`collector.py`): Standalone daemon for 24/7 vector store population. 53 sources organized by domain, with `--daemon`, `--interval`, `--sources` CLI args. Dynamic import via `_import_fetch_fn()`. Per-source timeout overrides in `SOURCE_TIMEOUTS` (the `aoi_digest` sweep gets 240 s; everything else the flat 45 s). Entry point: `intel-collector`.**Reports** (`reports.py`): PDF/HTML intelligence report generator. Collects 18 domains in parallel, renders styled HTML, converts to PDF via WeasyPrint. Optional dependency: `pip install -e ".[pdf]"`.@@ -76,6 +76,7 @@ collector.py (daemon) ──┘- **Source name string**: The `source` parameter in `fetcher.get_json()` identifies the API for circuit breaking and rate limiting. Must match entries in `_SOURCE_RATE_LIMITS` if rate-limited (e.g., `"yahoo-finance"`, `"coingecko"`, `"adsblol"`, `"nominatim"`).- **GDELT needs its own timeout**: `api.gdeltproject.org` TCP-connects instantly but its TLS handshake runs 17-20 s and sometimes longer (measured 2026-09-02), and the Fetcher's 15 s default counts TLS inside connect. Every GDELT `get_json` call must pass `timeout=GDELT_TIMEOUT` (from `sources/news.py`, 45 s) or it silently fails and serves stale cache.- **AOI news is geographic** (`sources/geocode.py`): AOI briefs reverse-geocode the area centre with OSM Nominatim and search GDELT for the settlement/county, never the AOI's name. Nominatim policy: 1 req/s (`_SOURCE_RATE_LIMITS`), identifying User-Agent with contact URL, results cached 30 days. Tests must stub `geocode.fetch_place_context` (the shared `_patch_all_domains` helper in `test_aoi.py` does) — a suite that hits Nominatim live gets rate-limited within seconds.+- **Heatmap tools** (`sources/jet_cohort.py`, `analysis/jet_activity.py`): adsb.lol heatmaps are binary (~14 MB); fetch them with `fetcher.get_bytes` (source `adsblol-history`, 2 s floor) and the on-disk `HeatmapDiskCache`, never the SQLite TTL cache. Tests build synthetic heatmaps with the encoder in `tests/test_jet_activity.py` and zero the rate floor via monkeypatch.- **Tool dispatch**: `server.py` uses Python `match/case` to route tool names to source functions. Tool names follow `intel_*` convention.- **All source functions take `fetcher` as first arg** — never construct your own httpx client.- **Tests strip proxy env vars** automatically via `conftest.py` fixture (prevents SOCKS proxy interference). The conftest also resets global fetcher rate-limit locks between tests to avoid cross-event-loop binding.diff --git a/README.md b/README.mdindex f56b101..eed48a4 100644--- a/README.md+++ b/README.md@@ -6,7 +6,7 @@[](https://python.org)[](LICENSE)-Real-time global intelligence across **30+ domains** with **132 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.+Real-time global intelligence across **30+ domains** with **135 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.Built for AI agents that need world awareness: market conditions, geopolitical risk, military posture, supply chain disruptions, cyber threats, and more — all queryable via the Model Context Protocol. The vector store enables natural language queries like *"military activity near Taiwan"* or *"cyber threats targeting healthcare"* across all historical data.@@ -33,7 +33,7 @@ Built for AI agents that need world awareness: market conditions, geopolitical r| **Military & Defense** | 6 | adsb.lol, OpenSky, hexdb.io, surge detection, theater posture, aircraft batch || **Infrastructure** | 5 | Cloudflare Radar, submarine cables, cascade analysis, cloud status, RIPEstat BGP/RPKI || **Maritime** | 2 | NGA navigation warnings, vessel snapshots |-| **Aviation** | 2 | FAA airport delays, domestic flight snapshot |+| **Aviation** | 5 | FAA airport delays, domestic flight snapshot, business-jet/military cohort early warning (adsb.lol live + globe_history heatmaps) || **News & Media** | 3 | 119 RSS feeds (4-tier), GDELT, trending keywords || **Intelligence Analysis** | 8 | Signal convergence, focal points, instability index, risk scores, escalation || **NLP Intelligence** | 4 | Entity extraction, event classification, news clustering, keyword spikes |@@ -64,7 +64,7 @@ Built for AI agents that need world awareness: market conditions, geopolitical r| **Tropical Cyclones** | 2 | NHC (Atlantic, E/C Pacific) + JTWC (NW Pacific, N Indian, S Hemisphere) || **Situation Brief** | 1 | Cited situational awareness brief over MCP: bounded server-side overview synthesized via local Ollama, with a mechanically-cited fallback |-**Total: 132 tools** across 30+ intelligence domains.+**Total: 135 tools** across 30+ intelligence domains.---@@ -334,11 +334,36 @@ collector.py (daemon) ─┘|------|-------------|| `intel_displacement_summary` | UNHCR refugee/IDP statistics |-### Aviation (2)+### Aviation (5)| Tool | Description ||------|-------------|| `intel_airport_delays` | FAA airport delay status || `intel_aviation_domestic` | Global air traffic snapshot from OpenSky |+| `intel_jet_cohort_snapshot` | Live airborne business-jet (ICAO type designators) or military cohort from adsb.lol; learns cohort membership as a side effect |+| `intel_jet_activity_anomaly` | Peak concurrent airborne cohort aircraft in a UTC half-hour vs the same slot on prior same-weekday dates (holiday-adjacent dates swapped out); robust z, alert level 1-5, deficit flag |+| `intel_jet_excess_origins` | Infers takeoffs/landings from heatmap tracks, density-clusters endpoints, and reports clusters above their baseline median: departure/arrival anchor, regional, or diffuse |++**Cohort early warning.** The three `intel_jet_*` tools watch a cohort of aircraft+(business jets by ICAO type designator, or military) for activity that departs+from its calendar baseline, and locate where an excess came from. Data:+adsb.lol's live API and its public half-hour `globe_history` heatmaps (readsb+format, ODbL 1.0, no key). Heatmaps are ~14 MB each and immutable once+published, so they are cached on disk next to the cache DB+(`WORLD_INTEL_HEATMAP_CACHE_MB`, default 1024) and fetched at most one at a+time with a 2 s floor. The cohort is *learned* from live snapshots (run+`intel_jet_cohort_snapshot` or the collector daemon, which now includes+`bizjet_cohort` and `military_cohort`); the analyses only use members first+seen `min_learning_lead_hours` (default 24) before the window, because a+cohort learned during a window inflates that window (measured: 1,002 vs a+206 baseline median when the gate is bypassed). Until the cohort has that+lead, the tools answer `warming_up`. The baseline is a handful of+same-weekday slots fetched on demand, not a year-long backfill, so there+are no learned holiday profiles or annual ratios.++Approach inspired by [kylemcdonald/ews](https://github.com/kylemcdonald/ews)+(Early Warning System: business-jet cohorts against calendar baselines, and+the excess-origin detector). This is an independent implementation over a+different, openly licensed data source; no ews code is used.### Cyber Threats (1)| Tool | Description |diff --git a/ROADMAP.md b/ROADMAP.mdindex 84504e1..2994345 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -2,7 +2,7 @@**Benchmark**: [koala73/worldmonitor](https://github.com/koala73/worldmonitor)**Updated**: 2026-09-02 (v0.10.0)-**Current tools**: 132 (131 intel + 1 status)+**Current tools**: 135 (134 intel + 1 status)---diff --git a/src/world_intel_mcp/analysis/jet_activity.py b/src/world_intel_mcp/analysis/jet_activity.pynew file mode 100644index 0000000..198ff9d--- /dev/null+++ b/src/world_intel_mcp/analysis/jet_activity.py@@ -0,0 +1,838 @@+"""Cohort air-activity early warning: anomaly vs calendar baseline, and+where an excess came from.++Two analyses over adsb.lol half-hour heatmaps (see+``sources/jet_cohort.py`` for the data path and format):++``fetch_cohort_activity``+ Peak concurrent airborne cohort aircraft in one half-hour slot,+ compared with the same UTC slot on prior same-weekday dates+ (``baseline_weeks``, US federal holiday-adjacent dates swapped for+ earlier weeks). Robust z = (current - median) / scale, with scale+ floored by counting noise. A second z on the cohort's share of all+ tracked aircraft guards against feeder-network coverage swings;+ the alert level uses the smaller of the two.++``fetch_excess_origins``+ Infers takeoffs and landings of cohort aircraft in a window and the+ same window on prior weeks, clusters the endpoints by density+ (default 12-mile radius), and reports clusters whose current count+ exceeds the baseline median: the airport (group) an excess departed+ from or converged on, labelled anchor / regional / diffuse.++Honest limits, surfaced in every result: the baseline is a handful of+same-weekday slots fetched now (no year-long history, no learned+holiday profiles); the cohort is learned from live snapshots and only+members first seen ``min_learning_lead_hours`` before the window are+used, so a fresh install reports ``warming_up`` until it has history.++Approach (business-jet cohorts vs calendar baselines; endpoint+clustering of excess departures) inspired by kylemcdonald/ews; this+implementation is independent.++Gaps / not covered:+- The holiday rule is binary exclusion of +/-1 day around US federal+ holidays; non-US holidays and multi-day events are not modelled.+- Thresholds (alarm_sigma, cluster shares) are chosen defaults, not+ calibrated against labelled events.+"""++from __future__ import annotations++import math+import statistics+import time+from collections import Counter+from datetime import date, datetime, timedelta, timezone+from typing import Any+from zoneinfo import ZoneInfo++from ..fetcher import Fetcher+from ..sources import jet_cohort as jc++_EASTERN = ZoneInfo("America/New_York")+MIN_COHORT = 25+MIN_BASELINE = 3+MIN_COVERAGE = 0.8+MAX_ORIGIN_FILES = 12+EARTH_RADIUS_MI = 3958.8+SELECTION_BIAS_NOTE = (+ "cohort selection bias: min_learning_lead_hours < 0 admits members first "+ "seen after the window started, which inflates the current window"+)+++# ---------------------------------------------------------------------------+# Calendar+# ---------------------------------------------------------------------------++def _nth_weekday(year: int, month: int, weekday: int, n: int) -> date:+ first = date(year, month, 1)+ offset = (weekday - first.weekday()) % 7+ return first + timedelta(days=offset + 7 * (n - 1))+++def _last_weekday(year: int, month: int, weekday: int) -> date:+ nxt = date(year + (month == 12), month % 12 + 1, 1)+ last = nxt - timedelta(days=1)+ return last - timedelta(days=(last.weekday() - weekday) % 7)+++def us_federal_holidays(year: int) -> dict[date, str]:+ """US federal holidays (5 U.S.C. 6103) for ``year``, plus the weekday+ each fixed-date holiday is observed on when it falls on a weekend."""+ fixed = {+ date(year, 1, 1): "New Year's Day",+ date(year, 6, 19): "Juneteenth",+ date(year, 7, 4): "Independence Day",+ date(year, 11, 11): "Veterans Day",+ date(year, 12, 25): "Christmas Day",+ }+ out: dict[date, str] = dict(fixed)+ for d, name in fixed.items():+ if d.weekday() == 5:+ out[d - timedelta(days=1)] = f"{name} (observed)"+ elif d.weekday() == 6:+ out[d + timedelta(days=1)] = f"{name} (observed)"+ out[_nth_weekday(year, 1, 0, 3)] = "Martin Luther King Jr. Day"+ out[_nth_weekday(year, 2, 0, 3)] = "Washington's Birthday"+ out[_last_weekday(year, 5, 0)] = "Memorial Day"+ out[_nth_weekday(year, 9, 0, 1)] = "Labor Day"+ out[_nth_weekday(year, 10, 0, 2)] = "Columbus Day"+ out[_nth_weekday(year, 11, 3, 4)] = "Thanksgiving Day"+ return out+++def holiday_near(day: date, window_days: int = 1) -> str | None:+ """Name of a US federal holiday within +/- ``window_days`` of ``day``."""+ for delta in range(-window_days, window_days + 1):+ d = day + timedelta(days=delta)+ name = us_federal_holidays(d.year).get(d)+ if name:+ return name+ return None+++def _local_day(start: datetime) -> date:+ return start.astimezone(_EASTERN).date()+++def baseline_starts(+ target: datetime, weeks: int, max_extra: int = 2+) -> tuple[list[datetime], list[dict[str, str]]]:+ """Same UTC slot on prior same-weekday dates, skipping holiday-adjacent+ dates (replaced by earlier weeks, at most ``max_extra`` extra)."""+ chosen: list[datetime] = []+ skipped: list[dict[str, str]] = []+ k = 1+ while len(chosen) < weeks and k <= weeks + max_extra:+ cand = target - timedelta(weeks=k)+ hol = holiday_near(_local_day(cand))+ if hol:+ skipped.append({"date": cand.date().isoformat(), "reason": f"near {hol}"})+ else:+ chosen.append(cand)+ k += 1+ return chosen, skipped+++# ---------------------------------------------------------------------------+# Activity metrics+# ---------------------------------------------------------------------------++def _is_airborne(fix: tuple) -> bool:+ return not fix[4] and (fix[5] is None or fix[5] >= 80.0)+++def _is_groundish(fix: tuple) -> bool:+ return fix[4] or (fix[5] is not None and fix[5] < 40.0)+++def concurrent_profile(slot: jc.SlotData, hold_seconds: float = 120.0) -> dict[str, Any]:+ """Peak / mean concurrent airborne aircraft across the slot's slices.++ An aircraft counts as airborne at time t when its latest fix at or+ before t is airborne and no older than ``hold_seconds`` (readsb only+ writes a fix when the trace advances, so single slices undercount).+ """+ events: list[tuple[float, int]] = []+ unique_airborne = 0+ for track in slot.tracks.values():+ intervals: list[list[float]] = []+ for i, fix in enumerate(track):+ if not _is_airborne(fix):+ continue+ end = fix[0] + hold_seconds+ if i + 1 < len(track):+ end = min(end, track[i + 1][0]) if not _is_airborne(track[i + 1]) else end+ if intervals and fix[0] <= intervals[-1][1]:+ intervals[-1][1] = max(intervals[-1][1], end)+ else:+ intervals.append([fix[0], end])+ if intervals:+ unique_airborne += 1+ for a, b in intervals:+ events.append((a, 1))+ events.append((b, -1))+ events.sort(key=lambda e: (e[0], e[1]))+ counts: list[int] = []+ level = 0+ j = 0+ for t in sorted(slot.slice_times):+ while j < len(events) and events[j][0] <= t:+ level += events[j][1]+ j += 1+ counts.append(level)+ return {+ "peak_concurrent": max(counts) if counts else 0,+ "mean_concurrent": round(sum(counts) / len(counts), 1) if counts else 0.0,+ "unique_airborne": unique_airborne,+ "all_tracked_aircraft": slot.total_aircraft,+ "coverage": round(slot.coverage, 3),+ }+++def robust_score(current: float, baseline: list[float], alarm_sigma: float = 5.0) -> dict[str, Any]:+ """Robust z of ``current`` against ``baseline`` with a counting-noise floor."""+ center = statistics.median(baseline)+ mad = statistics.median([abs(b - center) for b in baseline])+ floor = max(math.sqrt(max(center, 0.0)), 0.03 * abs(center), 1.0)+ scale = max(1.4826 * mad, floor)+ z = (current - center) / scale+ return {+ "baseline_median": round(center, 3),+ "baseline_values": [round(b, 4) for b in baseline],+ "scale": round(scale, 3),+ "z": round(z, 2),+ }+++def alert_level(z: float, alarm_sigma: float) -> tuple[int, str]:+ """1..5 from the positive z; deficits are reported separately."""+ if z >= alarm_sigma:+ return 5, "alarm"+ if z >= 4.0:+ return 4, "high"+ if z >= 3.0:+ return 3, "elevated"+ if z >= 2.0:+ return 2, "watch"+ return 1, "normal"+++def _slot_label(start: datetime) -> str:+ return start.strftime("%Y-%m-%dT%H:%MZ")+++def _parse_slot(value: str) -> datetime:+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return jc.slot_start(dt)+++# ---------------------------------------------------------------------------+# Tool 1: activity anomaly+# ---------------------------------------------------------------------------++async def fetch_cohort_activity(+ fetcher: Fetcher,+ cohort: str = "bizjet",+ region: str | None = None,+ baseline_weeks: int = 4,+ slot: str | None = None,+ alarm_sigma: float = 5.0,+ min_learning_lead_hours: float = 24.0,+ store: jc.CohortStore | None = None,+ disk: jc.HeatmapDiskCache | None = None,+ now: datetime | None = None,+) -> dict[str, Any]:+ """Cohort concurrent-activity anomaly vs a same-weekday baseline."""+ now = now or datetime.now(timezone.utc)+ base = {"cohort": cohort, "source": "adsb.lol globe_history heatmaps", "license": "ODbL-1.0"}+ if cohort not in jc.COHORTS:+ return {**base, "error": f"cohort must be one of {list(jc.COHORTS)}"}+ if not 2 <= int(baseline_weeks) <= 8:+ return {**base, "error": "baseline_weeks must be between 2 and 8"}+ if alarm_sigma <= 2.0:+ return {**base, "error": "alarm_sigma must be greater than 2"}+ if not -168.0 <= min_learning_lead_hours <= 168.0:+ return {**base, "error": "min_learning_lead_hours must be between -168 and 168"}+ try:+ region_name, bbox = jc.resolve_region(region)+ target = _parse_slot(slot) if slot else None+ except ValueError as exc:+ return {**base, "error": str(exc)}+ if target is not None and target > jc.slot_start(now) - timedelta(minutes=30):+ return {**base, "error": "slot must be a completed half-hour in the past"}++ earliest = target or (jc.slot_start(now) - timedelta(minutes=90))+ learned_before = earliest.timestamp() - min_learning_lead_hours * 3600.0+ own_store = store is None+ store = store or jc.default_store(fetcher)+ try:+ members = store.members(cohort, learned_before=learned_before)+ stats = store.stats(cohort)+ finally:+ if own_store:+ store.close()+ base.update({"region": region_name, "bbox": list(bbox) if bbox else None})+ cohort_info = {+ **stats,+ "eligible_members": len(members),+ "min_learning_lead_hours": min_learning_lead_hours,+ }+ if len(members) < MIN_COHORT:+ return {+ **base,+ "status": "warming_up",+ "cohort_store": cohort_info,+ "message": (+ f"Only {len(members)} cohort members were learned at least "+ f"{min_learning_lead_hours:g} h before the window (need {MIN_COHORT}). "+ "Run intel_jet_cohort_snapshot periodically (or the collector "+ "daemon) to learn the cohort; a cohort learned during the window "+ "would bias the count upward."+ ),+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }++ wanted = set(members)+ disk = disk or jc.default_disk_cache(fetcher)+ if target is None:+ current = await jc.latest_published_slot(fetcher, wanted, bbox, disk, now=now)+ else:+ current = await jc.fetch_slot(fetcher, target, wanted, bbox, disk)+ if current.status != "ok" or current.data is None:+ return {+ **base,+ "status": "error",+ "error": f"current slot {_slot_label(current.start)} unavailable: "+ f"{current.error or current.status}",+ "cohort_store": cohort_info,+ }++ cur_metrics = concurrent_profile(current.data)+ starts, skipped = baseline_starts(current.start, int(baseline_weeks))+ windows: list[dict[str, Any]] = []+ data_gaps: list[str] = []+ for start in starts:+ res = await jc.fetch_slot(fetcher, start, wanted, bbox, disk)+ if res.status != "ok" or res.data is None:+ data_gaps.append(f"baseline {_slot_label(start)}: {res.error or res.status}")+ continue+ m = concurrent_profile(res.data)+ if m["coverage"] < MIN_COVERAGE:+ data_gaps.append(+ f"baseline {_slot_label(start)}: coverage {m['coverage']} < {MIN_COVERAGE}, excluded"+ )+ continue+ windows.append({"slot": _slot_label(start), "cached": res.cached, **m})++ result: dict[str, Any] = {+ **base,+ "window": {"slot": _slot_label(current.start), "cached": current.cached, **cur_metrics},+ "baseline_windows": windows,+ "baseline_skipped_holidays": skipped,+ "current_near_holiday": holiday_near(_local_day(current.start)),+ "cohort_store": cohort_info,+ "data_gaps": data_gaps,+ "method": (+ "peak concurrent airborne cohort aircraft (120 s hold) in one UTC "+ "half-hour slot vs the same slot on prior same-weekday dates; robust "+ "z = (x - median) / max(1.4826*MAD, sqrt(median), 3% of median, 1); "+ "level uses min(z on count, z on share of all tracked aircraft)"+ ),+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }+ if cur_metrics["coverage"] < MIN_COVERAGE:+ data_gaps.append(f"current slot coverage {cur_metrics['coverage']} < {MIN_COVERAGE}")+ if min_learning_lead_hours < 0:+ data_gaps.append(SELECTION_BIAS_NOTE)+ if len(windows) < MIN_BASELINE:+ result["status"] = "insufficient_baseline"+ result["message"] = f"{len(windows)} usable baseline windows (need {MIN_BASELINE})"+ return result++ count_score = robust_score(+ cur_metrics["peak_concurrent"], [w["peak_concurrent"] for w in windows], alarm_sigma+ )+ share = cur_metrics["peak_concurrent"] / max(cur_metrics["all_tracked_aircraft"], 1)+ share_base = [w["peak_concurrent"] / max(w["all_tracked_aircraft"], 1) for w in windows]+ share_med = statistics.median(share_base)+ share_mad = statistics.median([abs(s - share_med) for s in share_base])+ # Same noise floor as the count, expressed in share units.+ count_floor = max(math.sqrt(max(count_score["baseline_median"], 0.0)), 1.0)+ share_floor = share_med * count_floor / max(count_score["baseline_median"], 1.0)+ share_scale = max(1.4826 * share_mad, share_floor, 1e-9)+ share_z = round((share - share_med) / share_scale, 2)++ z_used = min(count_score["z"], share_z)+ level, label = alert_level(z_used, alarm_sigma)+ if min_learning_lead_hours < 0:+ # A biased cohort must not raise (or clear) an alarm.+ level, label = None, "suppressed: selection-biased cohort"+ result.update(+ {+ "status": "degraded" if data_gaps else "ok",+ "score": {+ "count": count_score,+ "share_of_all_traffic": {+ "current": round(share, 5),+ "baseline_median": round(share_med, 5),+ "z": share_z,+ },+ "z_used": z_used,+ "excess_aircraft": round(+ cur_metrics["peak_concurrent"] - count_score["baseline_median"], 1+ ),+ },+ "alert_level": level,+ "alert": label,+ "alarm_sigma": alarm_sigma,+ "deficit": (z_used <= -3.0) if level is not None else None,+ }+ )+ return result+++# ---------------------------------------------------------------------------+# Endpoint inference and clustering+# ---------------------------------------------------------------------------++def _climbs(seg: list[tuple], i: int, horizon: float = 600.0, min_ft: int = 1500) -> bool:+ base = seg[i][3]+ if base is None:+ return False+ alts = [f[3] for f in seg[i + 1:] if f[0] - seg[i][0] <= horizon and f[3] is not None]+ return bool(alts) and max(alts) - base >= min_ft+++def _descends(seg: list[tuple], i: int, horizon: float = 600.0, min_ft: int = 1500) -> bool:+ base = seg[i][3]+ if base is None:+ return False+ alts = [f[3] for f in seg[:i] if seg[i][0] - f[0] <= horizon and f[3] is not None]+ return bool(alts) and max(alts) - base >= min_ft+++def infer_endpoints(+ track: list[tuple],+ window_start: float,+ window_end: float,+ gap_seconds: float = 1200.0,+ edge_seconds: float = 120.0,+ low_ft: int = 10_000,+) -> list[tuple[str, tuple, str]]:+ """Takeoff / landing events ``(kind, fix, reason)`` for one aircraft.++ Direct evidence: a ground (or < 40 kt) fix followed within 10 min by an+ airborne (>= 80 kt) fix, or the reverse. Coverage-edge evidence: a+ track segment that begins (ends) inside the window below ``low_ft``+ and climbs (descends) >= 1500 ft within 10 min, i.e. the aircraft rose+ into (sank out of) receiver coverage near an airport.+ """+ if not track:+ return []+ segments: list[list[tuple]] = [[track[0]]]+ for fix in track[1:]:+ if fix[0] - segments[-1][-1][0] > gap_seconds:+ segments.append([fix])+ else:+ segments[-1].append(fix)++ events: list[tuple[str, tuple, str]] = []+ for si, seg in enumerate(segments):+ for a, b in zip(seg, seg[1:]):+ if b[0] - a[0] > 600.0:+ continue+ if _is_groundish(a) and _is_airborne(b):+ events.append(("takeoff", a, "ground_to_air"))+ elif _is_airborne(a) and _is_groundish(b):+ events.append(("landing", b, "air_to_ground"))+ first, last = seg[0], seg[-1]+ starts_inside = si > 0 or first[0] - window_start > edge_seconds+ if (+ starts_inside+ and _is_airborne(first)+ and first[3] is not None+ and first[3] <= low_ft+ and _climbs(seg, 0)+ ):+ events.append(("takeoff", first, "appeared_climbing"))+ ends_inside = si < len(segments) - 1 or window_end - last[0] > edge_seconds+ if (+ ends_inside+ and _is_airborne(last)+ and last[3] is not None+ and last[3] <= low_ft+ and _descends(seg, len(seg) - 1)+ ):+ events.append(("landing", last, "vanished_descending"))++ events.sort(key=lambda e: e[1][0])+ deduped: list[tuple[str, tuple, str]] = []+ last_time: dict[str, float] = {}+ for kind, fix, reason in events:+ if fix[0] - last_time.get(kind, -1e18) < 600.0:+ continue+ last_time[kind] = fix[0]+ deduped.append((kind, fix, reason))+ return deduped+++def haversine_mi(lat1: float, lon1: float, lat2: float, lon2: float) -> float:+ p1, p2 = math.radians(lat1), math.radians(lat2)+ dphi = p2 - p1+ dl = math.radians(lon2 - lon1)+ h = math.sin(dphi / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(dl / 2) ** 2+ return 2 * EARTH_RADIUS_MI * math.asin(min(1.0, math.sqrt(h)))+++def density_clusters(+ points: list[dict[str, Any]], radius_mi: float, min_points: int+) -> list[int]:+ """DBSCAN labels (-1 = noise) using a 3-D grid on the sphere so the+ neighbour search is distortion-free at any latitude."""+ cell = radius_mi+ xyz: list[tuple[float, float, float]] = []+ grid: dict[tuple[int, int, int], list[int]] = {}+ for idx, p in enumerate(points):+ la, lo = math.radians(p["lat"]), math.radians(p["lon"])+ v = (+ EARTH_RADIUS_MI * math.cos(la) * math.cos(lo),+ EARTH_RADIUS_MI * math.cos(la) * math.sin(lo),+ EARTH_RADIUS_MI * math.sin(la),+ )+ xyz.append(v)+ grid.setdefault(tuple(int(math.floor(c / cell)) for c in v), []).append(idx)++ def neighbours(i: int) -> list[int]:+ cx, cy, cz = (int(math.floor(c / cell)) for c in xyz[i])+ out = []+ for dx in (-1, 0, 1):+ for dy in (-1, 0, 1):+ for dz in (-1, 0, 1):+ for j in grid.get((cx + dx, cy + dy, cz + dz), ()):+ if haversine_mi(points[i]["lat"], points[i]["lon"], points[j]["lat"], points[j]["lon"]) <= radius_mi:+ out.append(j)+ return out++ labels = [None] * len(points) # type: list[int | None]+ cluster_id = -1+ for i in range(len(points)):+ if labels[i] is not None:+ continue+ nb = neighbours(i)+ if len(nb) < min_points:+ labels[i] = -1+ continue+ cluster_id += 1+ labels[i] = cluster_id+ queue = [j for j in nb if j != i]+ while queue:+ j = queue.pop()+ if labels[j] == -1:+ labels[j] = cluster_id+ if labels[j] is not None:+ continue+ labels[j] = cluster_id+ nb_j = neighbours(j)+ if len(nb_j) >= min_points:+ queue.extend(k for k in nb_j if labels[k] is None or labels[k] == -1)+ return [lab if lab is not None else -1 for lab in labels]+++def summarize_clusters(+ points: list[dict[str, Any]],+ n_baseline: int,+ radius_mi: float,+ min_points: int,+ ref: tuple[float, float] | None = None,+ top: int = 8,+) -> dict[str, Any]:+ """Per-cluster current vs baseline-median counts for one event kind."""+ labels = density_clusters(points, radius_mi, min_points)+ groups: dict[int, list[dict[str, Any]]] = {}+ for p, lab in zip(points, labels):+ if lab >= 0:+ groups.setdefault(lab, []).append(p)++ clusters = []+ for items in groups.values():+ cur = [p for p in items if p["window"] == 0]+ base_counts = [sum(1 for p in items if p["window"] == w) for w in range(1, n_baseline + 1)]+ med = statistics.median(base_counts) if base_counts else 0.0+ centre_src = cur or items+ clat = sum(p["lat"] for p in centre_src) / len(centre_src)+ clon = sum(p["lon"] for p in centre_src) / len(centre_src)+ delta = len(cur) - med+ entry = {+ "center": {"lat": round(clat, 4), "lon": round(clon, 4)},+ "current": len(cur),+ "baseline_counts": base_counts,+ "baseline_median": med,+ "delta": delta,+ "unique_aircraft_current": len({p["hex"] for p in cur}),+ "radius_mi": round(max(haversine_mi(clat, clon, p["lat"], p["lon"]) for p in items), 1),+ "evidence": dict(Counter(p["reason"] for p in cur)),+ "significant": delta >= max(3.0, 2.0 * math.sqrt(max(med, 1.0))),+ }+ if ref is not None:+ entry["distance_to_reference_mi"] = round(haversine_mi(ref[0], ref[1], clat, clon), 1)+ clusters.append(entry)++ positive = sorted((c for c in clusters if c["delta"] > 0), key=lambda c: (-c["delta"], -c["current"]))+ pos_total = sum(c["delta"] for c in positive)+ for c in positive:+ c["share_of_excess"] = round(c["delta"] / pos_total, 3) if pos_total else 0.0+ current_total = sum(1 for p in points if p["window"] == 0)+ base_totals = [sum(1 for p in points if p["window"] == w) for w in range(1, n_baseline + 1)]+ return {+ "current_events": current_total,+ "baseline_events": base_totals,+ "baseline_median_events": statistics.median(base_totals) if base_totals else 0,+ "positive_excess_total": pos_total,+ "clusters_total": len(clusters),+ "top_excess_clusters": positive[:top],+ }+++def classify_excess(takeoffs: dict[str, Any], landings: dict[str, Any]) -> dict[str, str]:+ """Label the spatial shape of the excess from the top cluster shares."""++ def top(summary: dict[str, Any]) -> tuple[float, float, bool]:+ clusters = summary["top_excess_clusters"]+ if not clusters:+ return 0.0, 0.0, False+ c = clusters[0]+ return c["share_of_excess"], c["delta"], c["significant"]++ t_share, t_delta, t_sig = top(takeoffs)+ l_share, l_delta, l_sig = top(landings)+ dep_first = t_share * t_delta >= l_share * l_delta+ ordered = [("departure", t_share, t_sig), ("arrival", l_share, l_sig)]+ if not dep_first:+ ordered.reverse()+ for phase, share, sig in ordered:+ if sig and share >= 0.25:+ return {+ "pattern": f"{phase}_anchor",+ "explanation": (+ f"One endpoint cluster holds {share:.0%} of the excess {phase}s: "+ f"consistent with a specific airport or airport group "+ f"{'emptying out' if phase == 'departure' else 'drawing traffic in'}."+ ),+ }+ for phase, share, sig in ordered:+ if sig and share >= 0.12:+ return {+ "pattern": f"regional_{phase}_concentration",+ "explanation": (+ f"The strongest {phase} cluster holds {share:.0%} of the excess: a "+ "leading region, but too spread out to name one airport."+ ),+ }+ if takeoffs["positive_excess_total"] > 0 or landings["positive_excess_total"] > 0:+ return {+ "pattern": "diffuse",+ "explanation": "Excess endpoints are spread across many clusters with no "+ "significant concentration (broad redistribution, not one origin).",+ }+ return {"pattern": "no_excess", "explanation": "No cluster exceeds its baseline median."}+++# ---------------------------------------------------------------------------+# Tool 2: excess origins+# ---------------------------------------------------------------------------++async def _window_tracks(+ fetcher: Fetcher,+ start: datetime,+ slots: int,+ wanted: set[int],+ bbox: tuple[float, float, float, float] | None,+ disk: jc.HeatmapDiskCache,+) -> tuple[dict[int, list[tuple]], list[str], int]:+ tracks: dict[int, list[tuple]] = {}+ gaps: list[str] = []+ ok = 0+ for i in range(slots):+ s = start + timedelta(minutes=30 * i)+ res = await jc.fetch_slot(fetcher, s, wanted, bbox, disk)+ if res.status != "ok" or res.data is None:+ gaps.append(f"{_slot_label(s)}: {res.error or res.status}")+ continue+ ok += 1+ for addr, tr in res.data.tracks.items():+ tracks.setdefault(addr, []).extend(tr)+ for tr in tracks.values():+ tr.sort(key=lambda f: f[0])+ return tracks, gaps, ok+++async def fetch_excess_origins(+ fetcher: Fetcher,+ cohort: str = "bizjet",+ region: str | None = None,+ start: str | None = None,+ slots: int = 2,+ baseline_weeks: int = 3,+ ref_lat: float | None = None,+ ref_lon: float | None = None,+ cluster_radius_mi: float = 12.0,+ min_cluster_points: int = 3,+ min_learning_lead_hours: float = 24.0,+ store: jc.CohortStore | None = None,+ disk: jc.HeatmapDiskCache | None = None,+ now: datetime | None = None,+) -> dict[str, Any]:+ """Where did excess cohort departures/arrivals in a window come from?"""+ now = now or datetime.now(timezone.utc)+ base = {"cohort": cohort, "source": "adsb.lol globe_history heatmaps", "license": "ODbL-1.0"}+ if cohort not in jc.COHORTS:+ return {**base, "error": f"cohort must be one of {list(jc.COHORTS)}"}+ slots, baseline_weeks = int(slots), int(baseline_weeks)+ if not 1 <= slots <= 4:+ return {**base, "error": "slots must be between 1 and 4 (half-hours)"}+ if not 1 <= baseline_weeks <= 4:+ return {**base, "error": "baseline_weeks must be between 1 and 4"}+ if slots * (1 + baseline_weeks) > MAX_ORIGIN_FILES:+ return {+ **base,+ "error": f"slots x (1 + baseline_weeks) must be <= {MAX_ORIGIN_FILES} "+ "heatmap files (~14 MB each) per call",+ }+ if not 1.0 <= cluster_radius_mi <= 50.0:+ return {**base, "error": "cluster_radius_mi must be between 1 and 50"}+ if not -168.0 <= min_learning_lead_hours <= 168.0:+ return {**base, "error": "min_learning_lead_hours must be between -168 and 168"}+ if (ref_lat is None) != (ref_lon is None):+ return {**base, "error": "ref_lat and ref_lon must be given together"}+ try:+ region_name, bbox = jc.resolve_region(region)+ window_start = _parse_slot(start) if start else None+ except ValueError as exc:+ return {**base, "error": str(exc)}++ latest_complete = jc.slot_start(now) - timedelta(minutes=30)+ if window_start is not None and window_start + timedelta(minutes=30 * (slots - 1)) > latest_complete:+ return {**base, "error": "window must end at a completed half-hour in the past"}++ earliest = window_start or (latest_complete - timedelta(minutes=30 * (slots + 1)))+ learned_before = earliest.timestamp() - min_learning_lead_hours * 3600.0+ own_store = store is None+ store = store or jc.default_store(fetcher)+ try:+ members = store.members(cohort, learned_before=learned_before)+ stats = store.stats(cohort)+ finally:+ if own_store:+ store.close()+ base.update({"region": region_name, "bbox": list(bbox) if bbox else None})+ cohort_info = {**stats, "eligible_members": len(members), "min_learning_lead_hours": min_learning_lead_hours}+ if len(members) < MIN_COHORT:+ return {+ **base,+ "status": "warming_up",+ "cohort_store": cohort_info,+ "message": f"Only {len(members)} cohort members learned >= "+ f"{min_learning_lead_hours:g} h before the window (need {MIN_COHORT}); "+ "run intel_jet_cohort_snapshot periodically first.",+ }+ wanted = set(members)+ disk = disk or jc.default_disk_cache(fetcher)++ if window_start is None:+ latest = await jc.latest_published_slot(fetcher, wanted, bbox, disk, now=now)+ if latest.status != "ok":+ return {**base, "status": "error", "error": f"no recent heatmap published: {latest.error or latest.status}"}+ window_start = latest.start - timedelta(minutes=30 * (slots - 1))++ starts = [window_start]+ baseline, skipped = baseline_starts(window_start, baseline_weeks)+ starts.extend(baseline)++ takeoff_pts: list[dict[str, Any]] = []+ landing_pts: list[dict[str, Any]] = []+ data_gaps: list[str] = []+ windows_meta = []+ usable_baselines = 0+ for w_index, ws in enumerate(starts):+ tracks, gaps, ok = await _window_tracks(fetcher, ws, slots, wanted, bbox, disk)+ data_gaps.extend(gaps)+ if ok < slots:+ if w_index == 0:+ return {+ **base,+ "status": "error",+ "error": "current window incomplete: " + "; ".join(gaps),+ "cohort_store": cohort_info,+ }+ continue # an incomplete baseline window would bias the median low+ label = 0 if w_index == 0 else usable_baselines + 1+ if w_index > 0:+ usable_baselines += 1+ t0 = ws.timestamp()+ t1 = t0 + 1800.0 * slots+ n_t = n_l = 0+ for addr, tr in tracks.items():+ for kind, fix, reason in infer_endpoints(tr, t0, t1):+ pt = {"lat": fix[1], "lon": fix[2], "window": label, "hex": addr, "reason": reason}+ if kind == "takeoff":+ takeoff_pts.append(pt)+ n_t += 1+ else:+ landing_pts.append(pt)+ n_l += 1+ windows_meta.append(+ {"start": _slot_label(ws), "role": "current" if w_index == 0 else "baseline", "takeoffs": n_t, "landings": n_l, "aircraft_tracked": len(tracks)}+ )++ if usable_baselines == 0:+ return {+ **base,+ "status": "insufficient_baseline",+ "windows": windows_meta,+ "data_gaps": data_gaps,+ "cohort_store": cohort_info,+ }+ if min_learning_lead_hours < 0:+ data_gaps.append(SELECTION_BIAS_NOTE)+ ref = (ref_lat, ref_lon) if ref_lat is not None else None+ take = summarize_clusters(takeoff_pts, usable_baselines, cluster_radius_mi, min_cluster_points, ref)+ land = summarize_clusters(landing_pts, usable_baselines, cluster_radius_mi, min_cluster_points, ref)+ return {+ **base,+ "status": "degraded" if data_gaps else "ok",+ "window": {+ "start": _slot_label(window_start),+ "end": _slot_label(window_start + timedelta(minutes=30 * slots)),+ "near_holiday": holiday_near(_local_day(window_start)),+ },+ "windows": windows_meta,+ "baseline_skipped_holidays": skipped,+ "classification": (+ classify_excess(take, land)+ if min_learning_lead_hours >= 0+ else {+ "pattern": "suppressed",+ "explanation": "Selection-biased cohort (members learned after the "+ "window): cluster deltas are shown but not classified.",+ }+ ),+ "takeoffs": take,+ "landings": land,+ "cluster_radius_mi": cluster_radius_mi,+ "min_cluster_points": min_cluster_points,+ "reference": {"lat": ref_lat, "lon": ref_lon} if ref else None,+ "cohort_store": cohort_info,+ "data_gaps": data_gaps,+ "method": (+ "takeoffs/landings inferred from ground<->air transitions and from "+ "low-altitude climbs/descents at coverage edges; endpoints from the "+ "current and baseline windows density-clustered together; each "+ "cluster's current count compared with its baseline median"+ ),+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(now.timestamp())),+ }diff --git a/src/world_intel_mcp/collector.py b/src/world_intel_mcp/collector.pyindex 9d12970..4259dbd 100644--- a/src/world_intel_mcp/collector.py+++ b/src/world_intel_mcp/collector.py@@ -77,9 +77,13 @@ SOURCES = [("trending_keywords", "sources.news", "fetch_trending_keywords", {}),# Prediction (1)("prediction_markets", "sources.prediction", "fetch_prediction_markets", {}),- # Aviation (2)+ # Aviation (4)("airport_delays", "sources.aviation", "fetch_airport_delays", {}),("domestic_flights", "sources.aviation", "fetch_domestic_flights", {}),+ # Aircraft cohorts (2): each run learns cohort members that the+ # intel_jet_activity_anomaly / intel_jet_excess_origins tools need.+ ("bizjet_cohort", "sources.jet_cohort", "fetch_cohort_snapshot", {"cohort": "bizjet"}),+ ("military_cohort", "sources.jet_cohort", "fetch_cohort_snapshot", {"cohort": "military"}),# Cyber (1)("cyber_threats", "sources.cyber", "fetch_cyber_threats", {}),# Space (2)@@ -154,7 +158,7 @@ DOMAIN_GROUPS = {"climate": ["climate_anomalies"],"news": ["news_feed", "trending_keywords"],"prediction": ["prediction_markets"],- "aviation": ["airport_delays", "domestic_flights"],+ "aviation": ["airport_delays", "domestic_flights", "bizjet_cohort", "military_cohort"],"cyber": ["cyber_threats"],"space": ["space_weather", "launch_schedule"],"ai": ["ai_watch"],diff --git a/src/world_intel_mcp/fetcher.py b/src/world_intel_mcp/fetcher.pyindex c31ed1e..5b3afad 100644--- a/src/world_intel_mcp/fetcher.py+++ b/src/world_intel_mcp/fetcher.py@@ -8,6 +8,7 @@ response is returned (marked with _stale=True) so dashboards never go blank.import asyncioimport loggingimport time+from dataclasses import dataclassfrom typing import Anyimport httpx@@ -40,7 +41,29 @@ _SOURCE_RATE_LIMITS: dict[str, float] = {"acled": 2.0, # API key based"nga": 2.0, # govt API"sec-edgar": 1.0, # SEC EDGAR — be polite+ # adsb.lol globe_history heatmaps are ~14 MB each; one at a time,+ # spaced, so a cold baseline never bursts the community server.+ "adsblol-history": 2.0,}+++@dataclass(frozen=True)+class BinaryResult:+ """Outcome of :meth:`Fetcher.get_bytes`.++ ``status`` is the final HTTP status (None when no response arrived),+ ``content`` the body on 2xx, ``error`` a short reason otherwise. A+ 404 is reported as ``status=404`` with no error so callers can tell+ "not published (yet)" apart from "the fetch failed".+ """++ status: int | None+ content: bytes | None+ error: str | None = None++ @property+ def ok(self) -> bool:+ return self.content is not None_source_locks: dict[str, asyncio.Lock] = {}_source_last_call: dict[str, float] = {}@@ -247,6 +270,58 @@ class Fetcher:"""Fetch XML content (returns raw text for feedparser/ET parsing)."""return await self.get_text(url, source, cache_key, cache_ttl, timeout=timeout)+ async def get_bytes(+ self,+ url: str,+ source: str,+ headers: dict[str, str] | None = None,+ timeout: float | None = None,+ max_bytes: int = 256 * 1024 * 1024,+ ) -> BinaryResult:+ """Fetch a binary body with rate limiting, retries and circuit breaking.++ Not cached here: binary payloads (multi-MB) do not belong in the+ SQLite TTL cache, so callers own any on-disk caching. A 404 is a+ definitive answer (not retried, not a breaker failure). A body+ larger than ``max_bytes`` is refused rather than buffered.+ """+ if not self.breaker.is_available(source):+ return BinaryResult(None, None, f"circuit open for {source}")++ await self._source_throttle(source)+ client = await self._get_client()+ last_error = "unknown error"+ last_status: int | None = None++ for attempt in range(self.max_retries + 1):+ try:+ resp = await client.get(+ url, headers=headers, timeout=timeout or self.default_timeout+ )+ last_status = resp.status_code+ if resp.status_code == 404:+ self.breaker.record_success(source)+ return BinaryResult(404, None, None)+ resp.raise_for_status()+ body = resp.content+ if len(body) > max_bytes:+ self.breaker.record_success(source)+ return BinaryResult(+ resp.status_code,+ None,+ f"body of {len(body)} bytes exceeds cap {max_bytes}",+ )+ self.breaker.record_success(source)+ return BinaryResult(resp.status_code, body, None)+ except (httpx.HTTPStatusError, httpx.RequestError) as exc:+ last_error = f"{type(exc).__name__}: {exc}"+ if attempt < self.max_retries:+ await asyncio.sleep(min(2**attempt, 30))++ self.breaker.record_failure(source)+ logger.warning("Binary fetch failed for %s: %s (url=%s)", source, last_error, url)+ return BinaryResult(last_status, None, last_error)+def _stale_fallback(self, cache_key: str, source: str) -> Any | None:"""Return stale (expired) cached data as last-known-good fallback.diff --git a/src/world_intel_mcp/sources/jet_cohort.py b/src/world_intel_mcp/sources/jet_cohort.pynew file mode 100644index 0000000..0a51237--- /dev/null+++ b/src/world_intel_mcp/sources/jet_cohort.py@@ -0,0 +1,585 @@+"""Aircraft cohorts and historical ADS-B activity from adsb.lol.++Two data paths, both from adsb.lol (free, no key; data licensed ODbL 1.0+per the API's own OpenAPI description):++* **Live cohort snapshots** via ``api.adsb.lol/v2/type/{T1,T2,...}`` (one+ request covers every business-jet ICAO type designator) and+ ``/v2/mil``. Each snapshot also *learns* the cohort: every ICAO address+ seen is upserted into a ``jet_cohort`` table with first/last-seen+ times, so the historical analyses have a hex set to filter on.+* **Half-hour heatmaps** at ``adsb.lol/globe_history/YYYY/MM/DD/heatmap/+ NN.bin.ttf`` (slot NN = UTC half-hour 00..47). These are readsb's+ heatmap files: ~14 MB gzip, 10-second slices of every tracked+ aircraft's position. The binary layout is readsb's documented fixed+ ``struct heatEntry`` (globe_index.h/.c): little-endian+ ``int32 addr, int32 lat*1e6, int32 lon*1e6, int16 alt/25ft,+ int16 gs*10``; a slice starts with a marker entry whose addr is+ 0x0E7F7C9D and whose lat/lon carry the slice epoch-ms high/low words;+ entries with lat bit 30 set are callsign/squawk info records.+ Altitude -123 means on ground, -124 unknown; gs -1 invalid. Bits+ 27-31 of addr carry the address type; bit 24 marks non-ICAO.++Heatmaps for past slots are immutable once written, so downloaded files+are kept in an on-disk LRU next to the cache database+(``WORLD_INTEL_HEATMAP_CACHE_MB``, default 1024) and never re-fetched.++Why a learned cohort rather than a registry import: the public registry+paths that would give a complete hex->type map are either bot-blocked+for scripts (FAA ReleasableAircraft.zip answers 403 to non-browser+clients) or licensed restrictively (ADS-B Exchange / JETNET terms;+``globe.adsbexchange.com/robots.txt`` disallows ``/globe_history/``).+The adsb.lol type endpoint is open, so the cohort is learned from it.+Consequence callers must respect: a cohort learned *during* a window is+biased toward aircraft airborne in that window. The analyses therefore+only use members first seen a configurable lead time before the window.++Approach (business-jet cohort vs calendar baseline) inspired by+kylemcdonald/ews; implementation is independent.+"""++from __future__ import annotations++import asyncio+import gzip+import logging+import os+import sqlite3+import struct+import time+from dataclasses import dataclass, field+from datetime import datetime, timedelta, timezone+from pathlib import Path+from typing import Any++from ..fetcher import Fetcher++logger = logging.getLogger("world-intel-mcp.sources.jet_cohort")++# ---------------------------------------------------------------------------+# Constants+# ---------------------------------------------------------------------------++ADSBLOL_API = "https://api.adsb.lol/v2"+HEATMAP_URL = "https://adsb.lol/globe_history/{y:04d}/{m:02d}/{d:02d}/heatmap/{slot:02d}.bin.ttf"+HEATMAP_SOURCE = "adsblol-history"+USER_AGENT = "world-intel-mcp (+https://github.com/marc-shade/world-intel-mcp)"++# ICAO Doc 8643 type designators for business jets. Unknown designators+# simply match nothing on the type endpoint, so the list errs inclusive.+BIZJET_TYPES: tuple[str, ...] = (+ # Gulfstream+ "GLF2", "GLF3", "GLF4", "GLF5", "GLF6", "GA5C", "GA6C", "GA7C", "GA8C",+ "G150", "G280", "GALX", "ASTR",+ # Bombardier+ "GLEX", "GL5T", "GL7T", "CL30", "CL35", "CL60",+ "LJ31", "LJ35", "LJ40", "LJ45", "LJ55", "LJ60", "LJ70", "LJ75",+ # Dassault+ "FA10", "FA20", "FA50", "F2TH", "F900", "FA7X", "FA8X", "FA6X",+ # Cessna / Textron+ "C500", "C501", "C510", "C525", "C25A", "C25B", "C25C", "C25M",+ "C550", "C551", "C55B", "C560", "C56X", "C650", "C680", "C68A",+ "C700", "C750",+ # Embraer+ "E50P", "E55P", "E545", "E550", "E35L",+ # Hawker / Beechcraft+ "H25A", "H25B", "H25C", "HA4T", "PRM1", "BE40",+ # Others+ "HDJT", "PC24", "SF50", "EA50", "WW24",+)++COHORTS = ("bizjet", "military")++# readsb JSON ``dbFlags`` bitfield (readsb README-json): 1 military,+# 2 interesting, 4 PIA (privacy ICAO address), 8 FAA LADD.+DBFLAG_MILITARY = 1+DBFLAG_PIA = 4+DBFLAG_LADD = 8++# Region presets as (lat_min, lon_min, lat_max, lon_max).+REGIONS: dict[str, tuple[float, float, float, float] | None] = {+ "global": None,+ "conus": (24.0, -126.0, 50.0, -66.0),+ "north_america": (15.0, -170.0, 72.0, -50.0),+ "europe": (35.0, -25.0, 72.0, 45.0),+ "middle_east": (12.0, 25.0, 42.0, 65.0),+ "east_asia": (15.0, 95.0, 55.0, 155.0),+}++SLICE_MARKER = 0x0E7F7C9D+_INFO_BIT = 1 << 30+_NON_ICAO_BIT = 1 << 24+_ADDR_MASK = 0x1FFFFFF+_ALT_GROUND = -123+_ALT_UNKNOWN = -124+_GS_INVALID = -1+_ENTRY = struct.Struct("<iiihh")++# Thinning: keep a fix if this many seconds passed since the last kept+# fix for that aircraft, or if its ground/air state or altitude band+# changed. Bounds memory at <= 60 fixes per aircraft per half hour.+_THIN_SECONDS = 30.0+_THIN_ALT_FT = 500+++# ---------------------------------------------------------------------------+# Region parsing+# ---------------------------------------------------------------------------++def resolve_region(region: str | None) -> tuple[str, tuple[float, float, float, float] | None]:+ """Map a preset name or "lamin,lomin,lamax,lomax" to a bbox.++ Raises ValueError on an unknown preset or malformed/inverted bbox.+ """+ if region is None or region == "":+ return "global", None+ key = region.strip().lower()+ if key in REGIONS:+ return key, REGIONS[key]+ parts = [p.strip() for p in region.split(",")]+ if len(parts) != 4:+ raise ValueError(+ f"region must be one of {sorted(REGIONS)} or 'lamin,lomin,lamax,lomax'"+ )+ lat_min, lon_min, lat_max, lon_max = (float(p) for p in parts)+ if not (-90 <= lat_min < lat_max <= 90 and -180 <= lon_min < lon_max <= 180):+ raise ValueError("bbox must satisfy -90<=lamin<lamax<=90 and -180<=lomin<lomax<=180")+ return "bbox", (lat_min, lon_min, lat_max, lon_max)+++# ---------------------------------------------------------------------------+# Cohort store+# ---------------------------------------------------------------------------++class CohortStore:+ """Learned aircraft cohorts, in a ``jet_cohort`` table of the cache DB."""++ def __init__(self, db_path: Path | str):+ self.db_path = Path(db_path)+ self.db_path.parent.mkdir(parents=True, exist_ok=True)+ self._conn = sqlite3.connect(str(self.db_path), timeout=10)+ self._conn.execute("PRAGMA journal_mode=WAL")+ self._conn.execute("PRAGMA busy_timeout=5000")+ self._conn.execute(+ """+ CREATE TABLE IF NOT EXISTS jet_cohort (+ cohort TEXT NOT NULL,+ hex TEXT NOT NULL,+ type TEXT,+ registration TEXT,+ db_flags INTEGER NOT NULL DEFAULT 0,+ first_seen REAL NOT NULL,+ last_seen REAL NOT NULL,+ PRIMARY KEY (cohort, hex)+ )+ """+ )+ self._conn.commit()++ def close(self) -> None:+ self._conn.close()++ def upsert(self, cohort: str, aircraft: list[dict[str, Any]], seen_at: float) -> int:+ """Record sightings; returns how many hexes were new to the cohort."""+ before = self.count(cohort)+ rows = [+ (+ cohort,+ a["hex"],+ a.get("type"),+ a.get("registration"),+ int(a.get("db_flags") or 0),+ seen_at,+ seen_at,+ )+ for a in aircraft+ ]+ self._conn.executemany(+ """+ INSERT INTO jet_cohort+ (cohort, hex, type, registration, db_flags, first_seen, last_seen)+ VALUES (?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(cohort, hex) DO UPDATE SET+ type = COALESCE(excluded.type, jet_cohort.type),+ registration = COALESCE(excluded.registration, jet_cohort.registration),+ db_flags = excluded.db_flags,+ last_seen = MAX(jet_cohort.last_seen, excluded.last_seen),+ first_seen = MIN(jet_cohort.first_seen, excluded.first_seen)+ """,+ rows,+ )+ self._conn.commit()+ return self.count(cohort) - before++ def count(self, cohort: str) -> int:+ row = self._conn.execute(+ "SELECT COUNT(*) FROM jet_cohort WHERE cohort = ?", (cohort,)+ ).fetchone()+ return int(row[0])++ def members(self, cohort: str, learned_before: float | None = None) -> dict[int, dict[str, Any]]:+ """Return {addr_int: {hex, type, registration, db_flags}} for a cohort,+ optionally only members first seen strictly before ``learned_before``."""+ if learned_before is None:+ cur = self._conn.execute(+ "SELECT hex, type, registration, db_flags FROM jet_cohort WHERE cohort = ?",+ (cohort,),+ )+ else:+ cur = self._conn.execute(+ "SELECT hex, type, registration, db_flags FROM jet_cohort "+ "WHERE cohort = ? AND first_seen < ?",+ (cohort, learned_before),+ )+ out: dict[int, dict[str, Any]] = {}+ for hex_, type_, reg, flags in cur.fetchall():+ try:+ out[int(hex_, 16)] = {+ "hex": hex_,+ "type": type_,+ "registration": reg,+ "db_flags": flags,+ }+ except ValueError:+ continue+ return out++ def stats(self, cohort: str) -> dict[str, Any]:+ row = self._conn.execute(+ "SELECT COUNT(*), MIN(first_seen), MAX(last_seen) FROM jet_cohort WHERE cohort = ?",+ (cohort,),+ ).fetchone()+ n, first, last = row+ return {+ "members": int(n),+ "learning_started": _iso(first) if first else None,+ "last_sighting": _iso(last) if last else None,+ }+++def default_store(fetcher: Fetcher) -> CohortStore:+ return CohortStore(fetcher.cache.db_path)+++# ---------------------------------------------------------------------------+# Live snapshot (learns the cohort)+# ---------------------------------------------------------------------------++def _iso(ts: float) -> str:+ return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _normalize_live_aircraft(ac: dict[str, Any]) -> dict[str, Any] | None:+ hex_ = str(ac.get("hex") or "").strip().lower()+ if len(hex_) != 6 or hex_.startswith("~"):+ return None # non-ICAO (TIS-B track files etc.) cannot be cohort members+ try:+ int(hex_, 16)+ except ValueError:+ return None+ alt = ac.get("alt_baro")+ on_ground = alt == "ground"+ return {+ "hex": hex_,+ "type": (ac.get("t") or None),+ "registration": (ac.get("r") or None),+ "callsign": (ac.get("flight") or "").strip() or None,+ "db_flags": int(ac.get("dbFlags") or 0),+ "lat": ac.get("lat"),+ "lon": ac.get("lon"),+ "alt_ft": None if on_ground or not isinstance(alt, (int, float)) else alt,+ "on_ground": on_ground,+ "gs_kt": ac.get("gs"),+ }+++def _in_bbox(lat: Any, lon: Any, bbox: tuple[float, float, float, float] | None) -> bool:+ if bbox is None:+ return True+ if lat is None or lon is None:+ return False+ return bbox[0] <= lat <= bbox[2] and bbox[1] <= lon <= bbox[3]+++async def fetch_cohort_snapshot(+ fetcher: Fetcher,+ cohort: str = "bizjet",+ region: str | None = None,+ store: CohortStore | None = None,+) -> dict[str, Any]:+ """Live airborne snapshot of a cohort, and cohort learning as a side effect.++ Every ICAO address in the global response is recorded in the cohort+ store (regardless of ``region``, which only filters the summary).+ """+ if cohort not in COHORTS:+ return {"error": f"cohort must be one of {list(COHORTS)}", "source": "adsb.lol"}+ try:+ region_name, bbox = resolve_region(region)+ except ValueError as exc:+ return {"error": str(exc), "source": "adsb.lol"}++ if cohort == "bizjet":+ url = f"{ADSBLOL_API}/type/{','.join(BIZJET_TYPES)}"+ cache_key = "jet_cohort:live:bizjet"+ else:+ url = f"{ADSBLOL_API}/mil"+ cache_key = "military:adsblol:mil" # shared with intel_military_flights++ data = await fetcher.get_json(+ url,+ source="adsblol",+ cache_key=cache_key,+ cache_ttl=300,+ headers={"User-Agent": USER_AGENT},+ timeout=30.0,+ )+ now = time.time()+ if not isinstance(data, dict) or not isinstance(data.get("ac"), list):+ return {+ "cohort": cohort,+ "error": "adsb.lol live endpoint unavailable",+ "source": "adsb.lol",+ "timestamp": _iso(now),+ }++ aircraft = [a for a in (_normalize_live_aircraft(x) for x in data["ac"]) if a]+ own_store = store is None+ store = store or default_store(fetcher)+ try:+ new_members = store.upsert(cohort, aircraft, now)+ stats = store.stats(cohort)+ finally:+ if own_store:+ store.close()++ in_region = [a for a in aircraft if _in_bbox(a["lat"], a["lon"], bbox)]+ airborne = [a for a in in_region if not a["on_ground"]]+ by_type: dict[str, int] = {}+ for a in airborne:+ by_type[a["type"] or "unknown"] = by_type.get(a["type"] or "unknown", 0) + 1+ pia = sum(1 for a in airborne if a["db_flags"] & DBFLAG_PIA)+ ladd = sum(1 for a in airborne if a["db_flags"] & DBFLAG_LADD)++ result: dict[str, Any] = {+ "cohort": cohort,+ "region": region_name,+ "bbox": list(bbox) if bbox else None,+ "airborne": len(airborne),+ "on_ground": len(in_region) - len(airborne),+ "by_type": dict(sorted(by_type.items(), key=lambda kv: -kv[1])[:25]),+ "privacy_flags": {"pia": pia, "ladd": ladd},+ "cohort_store": {**stats, "new_members_this_snapshot": new_members},+ "aircraft": [+ {k: a[k] for k in ("hex", "type", "registration", "callsign", "lat", "lon", "alt_ft", "gs_kt")}+ for a in airborne[:200]+ ],+ "source": "adsb.lol",+ "license": "ODbL-1.0",+ "timestamp": _iso(now),+ }+ if cohort == "bizjet":+ result["type_designators_queried"] = len(BIZJET_TYPES)+ if data.get("_stale"):+ result["stale"] = True+ result["stale_age_seconds"] = data.get("_stale_age_seconds")+ return result+++# ---------------------------------------------------------------------------+# Heatmap slots+# ---------------------------------------------------------------------------++def slot_start(ts: datetime) -> datetime:+ """Floor a UTC datetime to its half-hour slot start."""+ ts = ts.astimezone(timezone.utc)+ return ts.replace(minute=0 if ts.minute < 30 else 30, second=0, microsecond=0)+++def slot_index(start: datetime) -> int:+ return start.hour * 2 + (1 if start.minute >= 30 else 0)+++def heatmap_url(start: datetime) -> str:+ return HEATMAP_URL.format(y=start.year, m=start.month, d=start.day, slot=slot_index(start))+++@dataclass+class SlotData:+ """Parsed, cohort-filtered contents of one half-hour heatmap."""++ start: datetime+ slice_times: list[float]+ tracks: dict[int, list[tuple[float, float, float, int | None, bool, float | None]]] = field(+ default_factory=dict+ )+ total_aircraft: int = 0 # every address with a position in the file (any cohort)++ @property+ def coverage(self) -> float:+ """Fraction of the expected 180 ten-second slices present."""+ return min(1.0, len(self.slice_times) / 180.0)+++def parse_heatmap(+ blob: bytes,+ wanted: set[int] | None,+ bbox: tuple[float, float, float, float] | None = None,+) -> tuple[list[float], dict[int, list[tuple]], int]:+ """Decode a readsb heatmap body (gzip or raw).++ Returns ``(slice_epoch_seconds, tracks, total_addresses)`` where+ ``tracks[addr]`` is a time-ordered, thinned list of+ ``(ts, lat, lon, alt_ft|None, on_ground, gs_kt|None)`` for addresses+ in ``wanted`` (all ICAO addresses if None) inside ``bbox``.++ Raises ValueError for a truncated body or one with no slice markers.+ """+ if blob[:2] == b"\x1f\x8b":+ blob = gzip.decompress(blob)+ if len(blob) % _ENTRY.size:+ raise ValueError(f"heatmap body length {len(blob)} is not a multiple of 16")++ slices: list[float] = []+ tracks: dict[int, list[tuple]] = {}+ seen_all: set[int] = set()+ current_ts: float | None = None+ if bbox is not None:+ lat_lo, lon_lo, lat_hi, lon_hi = (int(v * 1_000_000) for v in bbox)++ for addr_raw, lat_i, lon_i, alt, gs in _ENTRY.iter_unpack(blob):+ if addr_raw == SLICE_MARKER:+ epoch_ms = ((lat_i & 0xFFFFFFFF) << 32) | (lon_i & 0xFFFFFFFF)+ current_ts = epoch_ms / 1000.0+ slices.append(current_ts)+ continue+ if current_ts is None or lat_i & _INFO_BIT:+ continue # leading slice index, or a callsign/squawk record+ addr = addr_raw & _ADDR_MASK+ if addr & _NON_ICAO_BIT:+ continue+ seen_all.add(addr)+ if wanted is not None and addr not in wanted:+ continue+ if bbox is not None and not (lat_lo <= lat_i <= lat_hi and lon_lo <= lon_i <= lon_hi):+ continue+ on_ground = alt == _ALT_GROUND+ alt_ft = None if alt in (_ALT_GROUND, _ALT_UNKNOWN) else alt * 25+ gs_kt = None if gs == _GS_INVALID else gs / 10.0+ fix = (current_ts, lat_i / 1e6, lon_i / 1e6, alt_ft, on_ground, gs_kt)+ track = tracks.get(addr)+ if track is None:+ tracks[addr] = [fix]+ continue+ last = track[-1]+ if (+ current_ts - last[0] >= _THIN_SECONDS+ or on_ground != last[4]+ or (alt_ft is not None and (last[3] is None or abs(alt_ft - last[3]) >= _THIN_ALT_FT))+ ):+ track.append(fix)++ if not slices:+ raise ValueError("heatmap body contains no slice markers")+ return slices, tracks, len(seen_all)+++class HeatmapDiskCache:+ """On-disk LRU of raw heatmap bodies (immutable once published)."""++ def __init__(self, root: Path, cap_bytes: int):+ self.root = Path(root)+ self.cap_bytes = cap_bytes++ def path_for(self, start: datetime) -> Path:+ return self.root / f"{start:%Y}" / f"{start:%m}" / f"{start:%d}" / f"{slot_index(start):02d}.bin.gz"++ def get(self, start: datetime) -> bytes | None:+ p = self.path_for(start)+ if not p.exists():+ return None+ os.utime(p) # LRU recency+ return p.read_bytes()++ def put(self, start: datetime, body: bytes) -> None:+ p = self.path_for(start)+ p.parent.mkdir(parents=True, exist_ok=True)+ if body[:2] != b"\x1f\x8b":+ body = gzip.compress(body, compresslevel=6)+ tmp = p.with_suffix(".tmp")+ tmp.write_bytes(body)+ tmp.replace(p)+ self.evict()++ def evict(self) -> None:+ files = sorted(self.root.rglob("*.bin.gz"), key=lambda f: f.stat().st_mtime)+ total = sum(f.stat().st_size for f in files)+ while files and total > self.cap_bytes:+ victim = files.pop(0)+ total -= victim.stat().st_size+ victim.unlink(missing_ok=True)+++def default_disk_cache(fetcher: Fetcher) -> HeatmapDiskCache:+ cap_mb = float(os.environ.get("WORLD_INTEL_HEATMAP_CACHE_MB", "1024"))+ root = Path(fetcher.cache.db_path).parent / "heatmaps" / "adsblol"+ return HeatmapDiskCache(root, int(cap_mb * 1024 * 1024))+++@dataclass+class SlotFetch:+ start: datetime+ data: SlotData | None+ status: str # "ok" | "not_published" | "error"+ error: str | None = None+ cached: bool = False+++async def fetch_slot(+ fetcher: Fetcher,+ start: datetime,+ wanted: set[int] | None,+ bbox: tuple[float, float, float, float] | None,+ disk: HeatmapDiskCache,+) -> SlotFetch:+ """Fetch (disk cache first) and parse one half-hour heatmap slot."""+ body = disk.get(start)+ cached = body is not None+ if body is None:+ res = await fetcher.get_bytes(+ heatmap_url(start),+ source=HEATMAP_SOURCE,+ headers={"User-Agent": USER_AGENT},+ timeout=120.0,+ )+ if res.status == 404:+ return SlotFetch(start, None, "not_published")+ if not res.ok:+ return SlotFetch(start, None, "error", res.error or f"HTTP {res.status}")+ body = res.content+ try:+ slices, tracks, total = await asyncio.to_thread(parse_heatmap, body, wanted, bbox)+ except (ValueError, OSError, EOFError) as exc:+ return SlotFetch(start, None, "error", f"unparseable heatmap: {exc}", cached)+ if not cached:+ await asyncio.to_thread(disk.put, start, body)+ return SlotFetch(start, SlotData(start, slices, tracks, total), "ok", None, cached)+++async def latest_published_slot(+ fetcher: Fetcher,+ wanted: set[int] | None,+ bbox: tuple[float, float, float, float] | None,+ disk: HeatmapDiskCache,+ now: datetime | None = None,+) -> SlotFetch:+ """Most recent completed slot that adsb.lol has published (tries 3 back)."""+ now = now or datetime.now(timezone.utc)+ candidate = slot_start(now) - timedelta(minutes=30)+ last = await fetch_slot(fetcher, candidate, wanted, bbox, disk)+ for _ in range(2):+ if last.status != "not_published":+ return last+ candidate -= timedelta(minutes=30)+ last = await fetch_slot(fetcher, candidate, wanted, bbox, disk)+ return lastdiff --git a/src/world_intel_mcp/tests/test_collector.py b/src/world_intel_mcp/tests/test_collector.pyindex b7d7391..4ab1df2 100644--- a/src/world_intel_mcp/tests/test_collector.py+++ b/src/world_intel_mcp/tests/test_collector.py@@ -13,8 +13,8 @@ from world_intel_mcp import collectordef test_sources_count_matches_docs() -> None:- # CLAUDE.md says 51; measured here.- assert len(collector.SOURCES) == 51+ # CLAUDE.md says 53; measured here.+ assert len(collector.SOURCES) == 53def test_source_names_unique() -> None:diff --git a/src/world_intel_mcp/tests/test_jet_activity.py b/src/world_intel_mcp/tests/test_jet_activity.pynew file mode 100644index 0000000..21dfcb8--- /dev/null+++ b/src/world_intel_mcp/tests/test_jet_activity.py@@ -0,0 +1,540 @@+"""Tests for the aircraft-cohort early-warning tools.++Heatmaps here are synthetic files written by a test-side encoder of+readsb's fixed heatEntry layout; network calls are mocked with respx.+"""++from __future__ import annotations++import gzip+import struct+from datetime import date, datetime, timedelta, timezone++import httpx+import pytest+import respx++import world_intel_mcp.fetcher as fetcher_mod+from world_intel_mcp.analysis import jet_activity as ja+from world_intel_mcp.sources import jet_cohort as jc++# ---------------------------------------------------------------------------+# Synthetic heatmap encoder+# ---------------------------------------------------------------------------++_E = struct.Struct("<iiihh")+++def _s32(v: int) -> int:+ v &= 0xFFFFFFFF+ return v - (1 << 32) if v >= 1 << 31 else v+++def encode_heatmap(start: datetime, slices: list[list[tuple]], gz: bool = True) -> bytes:+ """slices[i] = entries (addr, lat, lon, alt_units, gs_units) at start+10*i s.+ alt_units: feet/25, -123 ground, -124 unknown. gs_units: kt*10, -1 invalid.+ An entry ("info", addr) emits a callsign/squawk record."""+ base_ms = int(start.timestamp() * 1000)+ out = bytearray()+ for i in range(len(slices)): # leading index records (ignored by readers)+ out += _E.pack(i, 0, 0, 0, 0)+ for i, entries in enumerate(slices):+ ms = base_ms + 10_000 * i+ out += _E.pack(jc.SLICE_MARKER, _s32(ms >> 32), _s32(ms & 0xFFFFFFFF), 10, 0)+ for e in entries:+ if e[0] == "info":+ out += _E.pack(e[1], (1 << 30) | 1200, _s32(int.from_bytes(b"TEST", "little")), 0, 0)+ continue+ addr, lat, lon, alt, gs = e+ out += _E.pack(addr, int(round(lat * 1e6)), int(round(lon * 1e6)), alt, gs)+ raw = bytes(out)+ return gzip.compress(raw) if gz else raw+++def airborne(addr: int, lat=40.0, lon=-75.0, ft=30000, kt=450.0):+ return (addr, lat, lon, ft // 25, int(kt * 10))+++def ground(addr: int, lat=40.0, lon=-75.0, kt=5.0):+ return (addr, lat, lon, -123, int(kt * 10))+++def slot_file(start: datetime, airborne_addrs: list[int], others: list[int] = (), n_slices: int = 180):+ """Every listed aircraft airborne in every slice; ``others`` appear once."""+ slices = []+ for i in range(n_slices):+ entries = [airborne(a) for a in airborne_addrs]+ if i == 0:+ entries += [airborne(o, ft=35000) for o in others]+ slices.append(entries)+ return encode_heatmap(start, slices)+++# ---------------------------------------------------------------------------+# Parser+# ---------------------------------------------------------------------------++T0 = datetime(2026, 10, 14, 11, 30, tzinfo=timezone.utc)+++def test_parse_heatmap_decodes_fields_and_skips_non_position_records():+ blob = encode_heatmap(+ T0,+ [+ [+ airborne(0xA00001, lat=33.5, lon=-112.25, ft=10000, kt=250.0),+ ground(0xA00002, lat=33.4, lon=-112.0, kt=12.5),+ ("info", 0xA00001),+ (0xA00003 | (1 << 24), 33.0, -112.0, 400, 2000), # non-ICAO+ (0xA00004 | (5 << 27), 34.0, -111.0, -124, -1), # MLAT, unknown alt/gs+ ]+ ],+ )+ slices, tracks, total = jc.parse_heatmap(blob, wanted=None)+ assert slices == [T0.timestamp()]+ assert total == 3 # non-ICAO address excluded+ ts, lat, lon, alt, on_ground, gs = tracks[0xA00001][0]+ assert (lat, lon, alt, on_ground, gs) == (33.5, -112.25, 10000, False, 250.0)+ assert tracks[0xA00002][0][3:] == (None, True, 12.5)+ assert tracks[0xA00004][0][3:] == (None, False, None) # address-type bits masked+ assert 0xA00003 not in tracks and (0xA00003 | (1 << 24)) not in tracks+++def test_parse_heatmap_filters_by_wanted_and_bbox_and_accepts_raw():+ blob = encode_heatmap(+ T0,+ [[airborne(1, lat=40, lon=-75), airborne(2, lat=40, lon=-75), airborne(3, lat=10, lon=10)]],+ gz=False,+ )+ _, tracks, total = jc.parse_heatmap(blob, wanted={1, 3}, bbox=(24, -126, 50, -66))+ assert set(tracks) == {1}+ assert total == 3+++def test_parse_heatmap_rejects_truncated_and_markerless_bodies():+ blob = encode_heatmap(T0, [[airborne(1)]], gz=False)+ with pytest.raises(ValueError, match="multiple of 16"):+ jc.parse_heatmap(blob[:-3], wanted=None)+ with pytest.raises(ValueError, match="no slice markers"):+ jc.parse_heatmap(_E.pack(1, 2, 3, 4, 5) * 4, wanted=None)+++def test_parse_heatmap_thins_but_keeps_state_changes():+ slices = [[airborne(1, ft=30000)] for _ in range(12)] # 120 s steady cruise+ slices.append([ground(1)]) # state change must survive thinning+ _, tracks, _ = jc.parse_heatmap(encode_heatmap(T0, slices), wanted=None)+ times = [f[0] - T0.timestamp() for f in tracks[1]]+ assert times == [0.0, 30.0, 60.0, 90.0, 120.0]+ assert tracks[1][-1][4] is True+++# ---------------------------------------------------------------------------+# Metrics and scoring+# ---------------------------------------------------------------------------++def _slot(tracks, n=180):+ t = T0.timestamp()+ return jc.SlotData(T0, [t + 10 * i for i in range(n)], tracks, total_aircraft=len(tracks))+++def test_concurrent_profile_counts_overlap_hold_and_ground():+ t = T0.timestamp()+ air = lambda s: (t + s, 40.0, -75.0, 30000, False, 450.0) # noqa: E731+ gnd = lambda s: (t + s, 40.0, -75.0, None, True, 5.0) # noqa: E731+ tracks = {+ 1: [air(0), air(30), air(60)], # present 0..180 (hold 120 after 60)+ 2: [air(40), gnd(70)], # present 40..70 only+ 3: [gnd(0), gnd(30)], # never airborne+ 4: [air(1000)], # present 1000..1120+ }+ prof = ja.concurrent_profile(_slot(tracks))+ assert prof["peak_concurrent"] == 2+ assert prof["unique_airborne"] == 3+ # One fix counts for the hold window (slices 0..110 s), not beyond it.+ held = ja.concurrent_profile(_slot({1: [air(0)]}), hold_seconds=120)+ assert held["peak_concurrent"] == 1+ assert ja.concurrent_profile(_slot({1: [air(0)]}), hold_seconds=0)["peak_concurrent"] == 0+ late = ja.concurrent_profile(_slot({1: [air(-200)]}), hold_seconds=120)+ assert late["peak_concurrent"] == 0+++def test_robust_score_floor_and_levels():+ s = ja.robust_score(130, [100, 100, 100, 100])+ assert s["baseline_median"] == 100+ assert s["scale"] == 10.0 # MAD 0 -> sqrt(100) floor+ assert s["z"] == 3.0+ assert ja.alert_level(3.0, 5.0) == (3, "elevated")+ assert ja.alert_level(5.0, 5.0) == (5, "alarm")+ assert ja.alert_level(4.2, 6.0) == (4, "high")+ assert ja.alert_level(1.9, 5.0) == (1, "normal")+ wide = ja.robust_score(130, [60, 100, 140, 100])+ assert wide["scale"] == pytest.approx(1.4826 * 20, abs=1e-3)+++# ---------------------------------------------------------------------------+# Calendar+# ---------------------------------------------------------------------------++def test_us_federal_holidays_2026():+ h = ja.us_federal_holidays(2026)+ assert h[date(2026, 1, 19)] == "Martin Luther King Jr. Day"+ assert h[date(2026, 5, 25)] == "Memorial Day"+ assert h[date(2026, 7, 3)] == "Independence Day (observed)"+ assert h[date(2026, 9, 7)] == "Labor Day"+ assert h[date(2026, 10, 12)] == "Columbus Day"+ assert h[date(2026, 11, 26)] == "Thanksgiving Day"+ assert ja.holiday_near(date(2026, 11, 27)) == "Thanksgiving Day"+ assert ja.holiday_near(date(2026, 11, 20)) is None+++def test_baseline_starts_skips_holiday_weeks():+ target = datetime(2026, 10, 5, 15, 30, tzinfo=timezone.utc)+ starts, skipped = ja.baseline_starts(target, 4)+ assert [s.date().isoformat() for s in starts] == [+ "2026-09-28", "2026-09-21", "2026-09-14", "2026-08-31",+ ]+ assert skipped == [{"date": "2026-09-07", "reason": "near Labor Day"}]+++# ---------------------------------------------------------------------------+# Endpoint inference and clustering+# ---------------------------------------------------------------------------++def _fx(s, ft, on_ground=False, kt=300.0, lat=40.0, lon=-75.0):+ return (T0.timestamp() + s, lat, lon, ft, on_ground, kt)+++W0, W1 = T0.timestamp(), T0.timestamp() + 3600+++def test_infer_takeoff_and_landing_from_ground_transitions():+ track = [_fx(300, None, True, 10.0), _fx(330, 1500), _fx(360, 4000)]+ assert [(k, r) for k, _, r in ja.infer_endpoints(track, W0, W1)] == [("takeoff", "ground_to_air")]+ track = [_fx(300, 2000), _fx(330, None, True, 60.0), _fx(360, None, True, 10.0)]+ events = ja.infer_endpoints(track, W0, W1)+ assert [(k, r) for k, _, r in events] == [("landing", "air_to_ground")]+ assert events[0][1][0] == W0 + 330+++def test_infer_coverage_edge_events_respect_window_edges():+ climb = [_fx(600, 3000), _fx(660, 4500), _fx(720, 6000)]+ assert [r for _, _, r in ja.infer_endpoints(climb, W0, W1)] == ["appeared_climbing"]+ at_edge = [_fx(30, 3000), _fx(90, 4500), _fx(150, 6000)]+ assert ja.infer_endpoints(at_edge, W0, W1) == []+ cruise = [_fx(600, 35000), _fx(660, 37000)]+ assert ja.infer_endpoints(cruise, W0, W1) == []+ descent = [_fx(1000, 8000), _fx(1060, 6000), _fx(1120, 4000)]+ assert [r for _, _, r in ja.infer_endpoints(descent, W0, W1)] == ["vanished_descending"]+++def test_infer_dedupes_repeat_events_within_ten_minutes():+ track = [+ _fx(100, None, True, 5.0), _fx(130, 1000),+ _fx(160, None, True, 5.0), _fx(190, 1000), # jitter, same takeoff+ ]+ kinds = [k for k, _, _ in ja.infer_endpoints(track, W0, W1)]+ assert kinds.count("takeoff") == 1+++def _pts(lat, lon, n, window, spread=0.02):+ return [+ {"lat": lat + spread * (i % 3), "lon": lon + spread * (i // 3 % 3), "window": window, "hex": 1000 + i, "reason": "ground_to_air"}+ for i in range(n)+ ]+++def test_density_clusters_groups_and_noise():+ pts = _pts(40.0, -75.0, 5, 0) + _pts(41.5, -73.0, 4, 0) + [{"lat": 10.0, "lon": 10.0}]+ labels = ja.density_clusters(pts, radius_mi=12, min_points=3)+ assert len(set(labels[:5])) == 1 and labels[0] >= 0+ assert len(set(labels[5:9])) == 1 and labels[5] not in (labels[0], -1)+ assert labels[9] == -1+++def test_density_clusters_work_across_antimeridian():+ pts = [{"lat": 0.0, "lon": 179.95}, {"lat": 0.0, "lon": -179.95}, {"lat": 0.05, "lon": 179.99}]+ assert len(set(ja.density_clusters(pts, radius_mi=12, min_points=3))) == 1+++def test_summarize_and_classify_departure_anchor():+ take = (+ _pts(33.37, -81.96, 30, 0) # big current departure cluster+ + _pts(33.37, -81.96, 2, 1) + _pts(33.37, -81.96, 1, 2)+ + _pts(26.1, -80.2, 6, 0) + _pts(26.1, -80.2, 5, 1) + _pts(26.1, -80.2, 6, 2)+ )+ summary = ja.summarize_clusters(take, n_baseline=2, radius_mi=12, min_points=3, ref=(33.47, -82.02))+ top = summary["top_excess_clusters"][0]+ assert top["current"] == 30 and top["baseline_median"] == 1.5 and top["significant"]+ assert top["distance_to_reference_mi"] < 10+ land = ja.summarize_clusters([], 2, 12, 3)+ cls = ja.classify_excess(summary, land)+ assert cls["pattern"] == "departure_anchor"+++def test_classify_diffuse_and_no_excess():+ diffuse = []+ for k in range(10):+ diffuse += _pts(30 + 2 * k, -100 + 3 * k, 4, 0) + _pts(30 + 2 * k, -100 + 3 * k, 3, 1)+ s = ja.summarize_clusters(diffuse, 1, 12, 3)+ empty = ja.summarize_clusters([], 1, 12, 3)+ assert ja.classify_excess(s, empty)["pattern"] == "diffuse"+ assert ja.classify_excess(empty, empty)["pattern"] == "no_excess"+++# ---------------------------------------------------------------------------+# Cohort store, disk cache, fetcher binary path+# ---------------------------------------------------------------------------++def test_cohort_store_upsert_and_learning_gate(tmp_path):+ store = jc.CohortStore(tmp_path / "c.db")+ assert store.upsert("bizjet", [{"hex": "a1b2c3", "type": "GLF6"}], 100.0) == 1+ assert store.upsert("bizjet", [{"hex": "a1b2c3", "type": None}, {"hex": "000001"}], 200.0) == 1+ assert set(store.members("bizjet")) == {0xA1B2C3, 1}+ assert set(store.members("bizjet", learned_before=150.0)) == {0xA1B2C3}+ assert store.members("bizjet")[0xA1B2C3]["type"] == "GLF6" # not erased by a null+ assert store.members("military") == {}+ stats = store.stats("bizjet")+ assert stats["members"] == 2 and stats["learning_started"] == "1970-01-01T00:01:40Z"+ store.close()+++def test_heatmap_disk_cache_evicts_oldest(tmp_path):+ disk = jc.HeatmapDiskCache(tmp_path, cap_bytes=2500)+ a, b = T0, T0 + timedelta(minutes=30)+ disk.put(a, b"\x1f\x8b" + b"x" * 1200)+ disk.put(b, b"\x1f\x8b" + b"y" * 1200)+ assert disk.get(a) is not None and disk.get(b) is not None+ disk.put(b + timedelta(minutes=30), b"\x1f\x8b" + b"z" * 1200)+ remaining = sorted(p.name for p in tmp_path.rglob("*.bin.gz"))+ assert len(remaining) == 2+++def test_resolve_region():+ assert jc.resolve_region(None) == ("global", None)+ assert jc.resolve_region("CONUS")[1] == (24.0, -126.0, 50.0, -66.0)+ assert jc.resolve_region("10,20,30,40") == ("bbox", (10.0, 20.0, 30.0, 40.0))+ for bad in ("mars", "1,2,3", "30,20,10,40"):+ with pytest.raises(ValueError):+ jc.resolve_region(bad)+++async def test_get_bytes_404_error_and_cap(fetcher):+ respx.get("https://x.test/missing").mock(return_value=httpx.Response(404))+ respx.get("https://x.test/boom").mock(return_value=httpx.Response(500))+ respx.get("https://x.test/big").mock(return_value=httpx.Response(200, content=b"0" * 50))+ r = await fetcher.get_bytes("https://x.test/missing", source="t1")+ assert r.status == 404 and r.content is None and r.error is None+ assert fetcher.breaker.is_available("t1")+ fetcher.max_retries = 0+ r = await fetcher.get_bytes("https://x.test/boom", source="t2")+ assert not r.ok and "500" in r.error+ r = await fetcher.get_bytes("https://x.test/big", source="t3", max_bytes=10)+ assert not r.ok and "exceeds cap" in r.error+++# ---------------------------------------------------------------------------+# Live-snapshot source (mocked)+# ---------------------------------------------------------------------------++_LIVE = {+ "ac": [+ {"hex": "a18d83", "t": "GLF6", "r": "N2C", "dbFlags": 8, "lat": 40.0, "lon": -100.0, "alt_baro": 43000, "gs": 480, "flight": "N2C "},+ {"hex": "a00002", "t": "C68A", "r": "N2", "dbFlags": 0, "lat": 48.0, "lon": 2.0, "alt_baro": 30000, "gs": 420},+ {"hex": "a00003", "t": "E55P", "dbFlags": 4, "lat": 41.0, "lon": -90.0, "alt_baro": "ground", "gs": 3},+ {"hex": "~2a0001", "t": "E55P", "lat": 41.0, "lon": -90.0, "alt_baro": 20000},+ ]+}+++async def test_cohort_snapshot_learns_globally_and_summarizes_region(fetcher, tmp_path):+ route = respx.get(url__regex=r"https://api\.adsb\.lol/v2/type/GLF2,.*").mock(+ return_value=httpx.Response(200, json=_LIVE)+ )+ store = jc.CohortStore(tmp_path / "s.db")+ r = await jc.fetch_cohort_snapshot(fetcher, "bizjet", region="conus", store=store)+ assert route.called+ assert r["airborne"] == 1 and r["on_ground"] == 1+ assert r["by_type"] == {"GLF6": 1}+ assert r["privacy_flags"] == {"pia": 0, "ladd": 1}+ assert r["cohort_store"]["members"] == 3 # Paris jet learned, non-ICAO not+ assert set(store.members("bizjet")) == {0xA18D83, 0xA00002, 0xA00003}+ store.close()+++async def test_cohort_snapshot_upstream_failure_is_an_error_not_zero(fetcher, tmp_path):+ fetcher.max_retries = 0+ respx.get(url__regex=r"https://api\.adsb\.lol/v2/mil.*").mock(return_value=httpx.Response(503))+ store = jc.CohortStore(tmp_path / "m.db")+ r = await jc.fetch_cohort_snapshot(fetcher, "military", store=store)+ store.close()+ assert "error" in r and "airborne" not in r+ assert (await jc.fetch_cohort_snapshot(fetcher, "boats"))["error"].startswith("cohort must be")+++# ---------------------------------------------------------------------------+# End-to-end analyses over mocked heatmaps+# ---------------------------------------------------------------------------++NOW = datetime(2026, 10, 14, 12, 10, tzinfo=timezone.utc) # Wednesday+CUR = datetime(2026, 10, 14, 11, 30, tzinfo=timezone.utc)+COHORT = list(range(0xA00000, 0xA00000 + 100))+OTHERS = list(range(0x400000, 0x400000 + 300))+++def no_floor(monkeypatch):+ monkeypatch.setitem(fetcher_mod._SOURCE_RATE_LIMITS, jc.HEATMAP_SOURCE, 0.0)+++def learned_store(tmp_path):+ store = jc.CohortStore(tmp_path / "cohort.db")+ store.upsert("bizjet", [{"hex": f"{a:06x}"} for a in COHORT], NOW.timestamp() - 10 * 86400)+ yield store+ store.close()+++def _mock_slot(start, body=None, status=200):+ return respx.get(jc.heatmap_url(start)).mock(+ return_value=httpx.Response(status, content=body or b"")+ )+++async def test_activity_alarm_on_synthetic_surge_then_disk_cache(fetcher, learned_store, no_floor, tmp_path):+ routes = [_mock_slot(CUR, slot_file(CUR, COHORT[:100], OTHERS))]+ for k, n in zip(range(1, 5), (50, 52, 48, 51)):+ s = CUR - timedelta(weeks=k)+ routes.append(_mock_slot(s, slot_file(s, COHORT[:n], OTHERS)))+ disk = jc.HeatmapDiskCache(tmp_path / "hm", 10**9)+ r = await ja.fetch_cohort_activity(fetcher, store=learned_store, disk=disk, now=NOW)+ assert r["status"] == "ok", r+ assert r["window"]["slot"] == "2026-10-14T11:30Z"+ assert r["window"]["peak_concurrent"] == 100+ assert [w["peak_concurrent"] for w in r["baseline_windows"]] == [50, 52, 48, 51]+ assert r["score"]["count"]["baseline_median"] == 50.5+ assert r["alert_level"] == 5 and r["alert"] == "alarm" and r["deficit"] is False+ assert all(route.call_count == 1 for route in routes)+ again = await ja.fetch_cohort_activity(fetcher, store=learned_store, disk=disk, now=NOW)+ assert all(route.call_count == 1 for route in routes) # served from disk+ assert again["window"]["cached"] is True and again["alert_level"] == 5+++async def test_activity_normal_and_deficit(fetcher, learned_store, no_floor, tmp_path):+ for k, n in zip(range(0, 5), (12, 50, 52, 48, 51)):+ s = CUR - timedelta(weeks=k)+ _mock_slot(s, slot_file(s, COHORT[:n], OTHERS))+ r = await ja.fetch_cohort_activity(+ fetcher, store=learned_store, disk=jc.HeatmapDiskCache(tmp_path / "hm", 10**9), now=NOW+ )+ assert r["alert_level"] == 1 and r["deficit"] is True+++async def test_activity_degrades_honestly(fetcher, learned_store, no_floor, tmp_path):+ fetcher.max_retries = 0+ disk = jc.HeatmapDiskCache(tmp_path / "hm", 10**9)+ _mock_slot(CUR, slot_file(CUR, COHORT[:60], OTHERS))+ _mock_slot(CUR - timedelta(weeks=1), slot_file(CUR - timedelta(weeks=1), COHORT[:50], OTHERS))+ _mock_slot(CUR - timedelta(weeks=2), status=404)+ _mock_slot(CUR - timedelta(weeks=3), status=500)+ s4 = CUR - timedelta(weeks=4)+ _mock_slot(s4, slot_file(s4, COHORT[:50], OTHERS, n_slices=60)) # 1/3 coverage+ r = await ja.fetch_cohort_activity(fetcher, store=learned_store, disk=disk, now=NOW)+ assert r["status"] == "insufficient_baseline"+ assert "alert_level" not in r+ assert len(r["data_gaps"]) == 3 and any("coverage" in g for g in r["data_gaps"])+++async def test_activity_current_slot_missing_is_error(fetcher, learned_store, no_floor, tmp_path):+ for k in range(0, 3):+ _mock_slot(CUR - timedelta(minutes=30 * k), status=404)+ r = await ja.fetch_cohort_activity(+ fetcher, store=learned_store, disk=jc.HeatmapDiskCache(tmp_path / "hm", 10**9), now=NOW+ )+ assert r["status"] == "error" and "unavailable" in r["error"]+++async def test_activity_warming_up_and_validation(fetcher, tmp_path):+ store = jc.CohortStore(tmp_path / "fresh.db")+ store.upsert("bizjet", [{"hex": f"{a:06x}"} for a in COHORT], NOW.timestamp() - 3600)+ r = await ja.fetch_cohort_activity(fetcher, store=store, now=NOW)+ assert r["status"] == "warming_up" and r["cohort_store"]["eligible_members"] == 0+ assert "error" in await ja.fetch_cohort_activity(fetcher, baseline_weeks=1, store=store, now=NOW)+ assert "error" in await ja.fetch_cohort_activity(fetcher, slot="2026-10-14T12:00Z", store=store, now=NOW)+ assert "error" in await ja.fetch_cohort_activity(fetcher, region="nowhere", store=store, now=NOW)+ store.close()+++async def test_activity_biased_cohort_suppresses_alert(fetcher, no_floor, tmp_path):+ store = jc.CohortStore(tmp_path / "fresh.db")+ store.upsert("bizjet", [{"hex": f"{a:06x}"} for a in COHORT], NOW.timestamp() - 60)+ for k, n in zip(range(0, 5), (90, 50, 52, 48, 51)):+ s = CUR - timedelta(weeks=k)+ _mock_slot(s, slot_file(s, COHORT[:n], OTHERS))+ r = await ja.fetch_cohort_activity(+ fetcher, store=store, min_learning_lead_hours=-24,+ disk=jc.HeatmapDiskCache(tmp_path / "hm", 10**9), now=NOW,+ )+ assert r["status"] == "degraded"+ assert r["alert_level"] is None and r["alert"].startswith("suppressed")+ assert any("selection bias" in g for g in r["data_gaps"])+ store.close()+++def _departure_slot(start, n_departing, base_lat=33.37, base_lon=-81.96):+ """n aircraft sit on the ground then take off mid-slot near one airport."""+ slices = []+ for i in range(180):+ entries = []+ for j in range(n_departing):+ a = COHORT[j]+ lat, lon = base_lat + 0.01 * (j % 5), base_lon + 0.01 * (j // 5 % 5)+ if i < 60:+ entries.append(ground(a, lat, lon, kt=8.0))+ else:+ entries.append(airborne(a, lat, lon, ft=2000 + 100 * (i - 60), kt=180.0))+ slices.append(entries)+ return encode_heatmap(start, slices)+++async def test_excess_origins_finds_departure_anchor(fetcher, learned_store, no_floor, tmp_path):+ _mock_slot(CUR, _departure_slot(CUR, 25))+ for k in (1, 2):+ s = CUR - timedelta(weeks=k)+ _mock_slot(s, _departure_slot(s, 2))+ r = await ja.fetch_excess_origins(+ fetcher, slots=1, baseline_weeks=2, ref_lat=33.47, ref_lon=-82.02,+ store=learned_store, disk=jc.HeatmapDiskCache(tmp_path / "hm", 10**9), now=NOW,+ )+ assert r["status"] == "ok", r+ assert r["classification"]["pattern"] == "departure_anchor"+ top = r["takeoffs"]["top_excess_clusters"][0]+ assert top["current"] == 25 and top["baseline_median"] == 2 and top["delta"] == 23+ assert top["evidence"] == {"ground_to_air": 25}+ assert top["distance_to_reference_mi"] < 15+ assert [w["takeoffs"] for w in r["windows"]] == [25, 2, 2]+++async def test_excess_origins_bounds_and_incomplete_current(fetcher, learned_store, no_floor, tmp_path):+ disk = jc.HeatmapDiskCache(tmp_path / "hm", 10**9)+ r = await ja.fetch_excess_origins(fetcher, slots=4, baseline_weeks=3, store=learned_store, now=NOW)+ assert "<= 12" in r["error"]+ r = await ja.fetch_excess_origins(fetcher, ref_lat=1.0, store=learned_store, now=NOW)+ assert "together" in r["error"]+ fetcher.max_retries = 0+ start = CUR - timedelta(minutes=30)+ _mock_slot(start, _departure_slot(start, 3))+ _mock_slot(CUR, status=500)+ r = await ja.fetch_excess_origins(+ fetcher, start=start.isoformat(), slots=2, store=learned_store, disk=disk, now=NOW+ )+ assert r["status"] == "error" and "incomplete" in r["error"]diff --git a/src/world_intel_mcp/tests/test_server_registry.py b/src/world_intel_mcp/tests/test_server_registry.pyindex c0720f3..22c2c70 100644--- a/src/world_intel_mcp/tests/test_server_registry.py+++ b/src/world_intel_mcp/tests/test_server_registry.py@@ -123,11 +123,11 @@ def test_aggregate_refuses_drift_and_collisions() -> None:def test_tool_count_matches_documented_surface(server) -> None:- """132 = 131 intelligence tools + intel_status. If this fails after+ """135 = 134 intelligence tools + intel_status. If this fails afteradding a tool, update README.md, ROADMAP.md, and this number in thesame change: the repo's history shows doc counts drifting stalewithin weeks when nothing enforced them."""- assert len(server.TOOLS) == 132+ assert len(server.TOOLS) == 135@pytest.mark.asynciodiff --git a/src/world_intel_mcp/tools/infrastructure.py b/src/world_intel_mcp/tools/infrastructure.pyindex 3b61394..6a3ae6a 100644--- a/src/world_intel_mcp/tools/infrastructure.py+++ b/src/world_intel_mcp/tools/infrastructure.py@@ -13,6 +13,7 @@ from typing import Anyfrom mcp.types import Toolfrom .. import runtime+from ..sources.jet_cohort import BIZJET_TYPESfrom ..sources import (infrastructure,maritime,@@ -124,6 +125,71 @@ TOOLS: list[Tool] = ["required": ["resource"],},),+ # --- Aircraft cohort early warning (3 tools; approach inspired by kylemcdonald/ews) ---+ Tool(+ name="intel_jet_cohort_snapshot",+ description=f"Live airborne snapshot of a tracked aircraft cohort from adsb.lol (free, no key, ODbL): business jets ({len(BIZJET_TYPES)} ICAO type designators, one request) or military. "+ "Counts by type, PIA/LADD privacy flags, positions. Each call also learns the cohort (hex addresses persisted locally) that intel_jet_activity_anomaly and intel_jet_excess_origins filter on; run it periodically to build the cohort.",+ inputSchema={+ "type": "object",+ "properties": {+ "cohort": {"type": "string", "enum": ["bizjet", "military"], "default": "bizjet"},+ "region": {+ "type": "string",+ "description": "global, conus, north_america, europe, middle_east, east_asia, or 'lamin,lomin,lamax,lomax' (filters the summary only; learning is global)",+ "default": "global",+ },+ },+ },+ ),+ Tool(+ name="intel_jet_activity_anomaly",+ description="Early-warning check: peak concurrent airborne cohort aircraft (business jets or military) in the latest published UTC half-hour (or a given slot) vs the same slot on prior same-weekday dates, from adsb.lol globe_history heatmaps. US federal holiday-adjacent baseline dates are swapped for earlier weeks. Returns robust z-score, alert level 1-5 (normal/watch/elevated/high/alarm), deficit flag, and data gaps. Needs a learned cohort (see intel_jet_cohort_snapshot); downloads ~14 MB per uncached slot, cached on disk.",+ inputSchema={+ "type": "object",+ "properties": {+ "cohort": {"type": "string", "enum": ["bizjet", "military"], "default": "bizjet"},+ "region": {+ "type": "string",+ "description": "global, conus, north_america, europe, middle_east, east_asia, or 'lamin,lomin,lamax,lomax'",+ "default": "global",+ },+ "slot": {+ "type": "string",+ "description": "UTC ISO datetime inside the half-hour to score (default: latest published)",+ },+ "baseline_weeks": {"type": "integer", "minimum": 2, "maximum": 8, "default": 4},+ "alarm_sigma": {"type": "number", "default": 5.0, "description": "z at which level 5 (alarm) fires"},+ "min_learning_lead_hours": {+ "type": "number",+ "default": 24,+ "description": "Only use cohort members first seen this long before the window (avoids selection bias). Negative values admit later-learned members for a first look; the result is then marked degraded with a selection-bias data gap.",+ },+ },+ },+ ),+ Tool(+ name="intel_jet_excess_origins",+ description="Where did an excess of cohort departures/arrivals come from? Infers takeoffs and landings from adsb.lol heatmap tracks for a 0.5-2 h window and the same window on prior weeks, density-clusters the endpoints (default 12-mile radius), and reports clusters above their baseline median with a pattern label: departure_anchor, arrival_anchor, regional concentration, diffuse, or no_excess. Optional reference point gives distance-to-event. At most 12 heatmap files (~14 MB each, cached) per call.",+ inputSchema={+ "type": "object",+ "properties": {+ "cohort": {"type": "string", "enum": ["bizjet", "military"], "default": "bizjet"},+ "region": {"type": "string", "default": "global", "description": "Region preset or 'lamin,lomin,lamax,lomax'"},+ "start": {"type": "string", "description": "UTC ISO start of the window (default: ends at the latest published slot)"},+ "slots": {"type": "integer", "minimum": 1, "maximum": 4, "default": 2, "description": "Window length in half-hours"},+ "baseline_weeks": {"type": "integer", "minimum": 1, "maximum": 4, "default": 3},+ "ref_lat": {"type": "number", "description": "Optional event latitude for distance reporting"},+ "ref_lon": {"type": "number", "description": "Optional event longitude for distance reporting"},+ "cluster_radius_mi": {"type": "number", "default": 12, "minimum": 1, "maximum": 50},+ "min_learning_lead_hours": {+ "type": "number",+ "default": 24,+ "description": "Only use cohort members first seen this long before the window; negative admits later-learned members (marked as a selection-bias data gap)",+ },+ },+ },+ ),]@@ -190,6 +256,47 @@ async def _bgp_status(arguments: dict[str, Any]) -> Any:)+async def _jet_cohort_snapshot(arguments: dict[str, Any]) -> Any:+ from ..sources.jet_cohort import fetch_cohort_snapshot++ return await fetch_cohort_snapshot(+ runtime.fetcher,+ cohort=arguments.get("cohort", "bizjet"),+ region=arguments.get("region"),+ )+++async def _jet_activity_anomaly(arguments: dict[str, Any]) -> Any:+ from ..analysis.jet_activity import fetch_cohort_activity++ return await fetch_cohort_activity(+ runtime.fetcher,+ cohort=arguments.get("cohort", "bizjet"),+ region=arguments.get("region"),+ baseline_weeks=arguments.get("baseline_weeks", 4),+ slot=arguments.get("slot"),+ alarm_sigma=float(arguments.get("alarm_sigma", 5.0)),+ min_learning_lead_hours=float(arguments.get("min_learning_lead_hours", 24)),+ )+++async def _jet_excess_origins(arguments: dict[str, Any]) -> Any:+ from ..analysis.jet_activity import fetch_excess_origins++ return await fetch_excess_origins(+ runtime.fetcher,+ cohort=arguments.get("cohort", "bizjet"),+ region=arguments.get("region"),+ start=arguments.get("start"),+ slots=arguments.get("slots", 2),+ baseline_weeks=arguments.get("baseline_weeks", 3),+ ref_lat=arguments.get("ref_lat"),+ ref_lon=arguments.get("ref_lon"),+ cluster_radius_mi=float(arguments.get("cluster_radius_mi", 12)),+ min_learning_lead_hours=float(arguments.get("min_learning_lead_hours", 24)),+ )++HANDLERS = {"intel_internet_outages": _internet_outages,"intel_cable_health": _cable_health,@@ -200,5 +307,9 @@ HANDLERS = {"intel_traffic_incidents": _traffic_incidents,"intel_webcams": _webcams,"intel_shipping_index": _shipping_index,- "intel_service_status": _service_status, "intel_bgp_status": _bgp_status,+ "intel_service_status": _service_status,+ "intel_bgp_status": _bgp_status,+ "intel_jet_cohort_snapshot": _jet_cohort_snapshot,+ "intel_jet_activity_anomaly": _jet_activity_anomaly,+ "intel_jet_excess_origins": _jet_excess_origins,}