Skip to content

160-tool MCP server for real-time global intelligence from free public APIs: markets, liquidity, prediction markets, SEC filings, conflict, military, aircraft-cohort early warning, migration and border flows, cyber, climate, news and more. Dated observation history, 29 research prompts, cited briefs, geofences, SSE dashboard. MIT, no paid API keys.

Maritime and fleet honesty: third review round

Phoenix Agent (mac-studio)843bea5c52e2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f817103..2deb943 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -702,7 +702,12 @@ source here, and no proxy is substituted for any of these measures.
- With NGA down every waterway read `clear`. It now reads `unknown`, and
the response carries `error`, `degraded` and `reason`. With the feed past
its staleness threshold every waterway reads `stale` (its counts kept,
- dated by `status_as_of`) instead of a current threat level.
+ dated by `status_as_of`) instead of a current threat level. A feed whose
+ currency cannot be checked (`feed_stale` null: no parseable issue date,
+ or no active warnings) also reads `unknown`, degraded, with a data gap:
+ three undated warnings near Hormuz used to read `critical` with
+ `status_as_of` null. The fleet report leaves such a snapshot out of its
+ score (a lower bound) and the report prints an UNDATED note.
- Positions are read in degrees-minutes, degrees-minutes-seconds and the
two mixed, with whitespace, a comma or a slash between latitude and
longitude; a lone latitude or longitude (a band or a meridian) counts as
@@ -710,6 +715,12 @@ source here, and no proxy is substituted for any of these measures.
2026-10-17 (386 active, 3,480 from 2024) this loses none of the previous
parser's 21,780 positions and reads 34 more, in HYDROLANT 2024-473, 479
and 488.
+- A position match no longer starts right after a letter: '20-O3-44N'
+ (letter O for zero) used to read as 3.73N, about 1,800 km off; it now
+ reads as no position. On 3,643 distinct real warnings (2024 and the
+ live captures) this changes no position. A lone latitude or longitude
+ still counts as a stated position when a letter precedes it, so a
+ mistyped coordinate is unplaced as `position_unreadable`.
### Fixed: navigational warnings
- An NGA outage returned `warnings: []` with no marker, the same shape as a
@@ -744,6 +755,11 @@ source here, and no proxy is substituted for any of these measures.
never the Roman numerals) to the NAVAREAs, with each code's source in
`sources/maritime.py`. Code 4 also carries Canadian Arctic (NAVAREA
XVIII) warnings, so it is not a single NAVAREA.
+- NGA answering with no active warnings (an empty list, or only cancelled
+ ones) read as a quiet sea: count 0, no marker, every waterway `clear`.
+ The live feed held 386 active warnings on 2026-10-17, so the response is
+ now degraded with a data gap and `feed_stale` null, and the empty answer
+ is reused from the cache for at most 5 minutes instead of an hour.
### Fixed: fleet report and theater posture
- `intel_fleet_report` turned a failed component into `{}`, so with all
@@ -770,6 +786,27 @@ source here, and no proxy is substituted for any of these measures.
`intel_military_surge` turns a posture error into its own error and
skips regions whose theater had no source (`unchecked_regions`) instead
of recording zeros in their baselines.
+- On a warm cache those markers were bypassed: when adsb.lol failed, the
+ fetcher's expired copy (marked `_stale`) came back as current flights,
+ source `adsb.lol`, stamped now, and OpenSky was never tried. Measured
+ with a 3-day-old copy and both hosts returning 500: posture cached it as
+ complete, surge recorded it into its baselines as today's traffic, and
+ the fleet report scored it with no data gap. OpenSky is now tried live
+ before any copy is considered, and an expired copy from either source is
+ an outage (`error`, `degraded`, `reason`): its aircraft go under
+ `stale_copy` with their source, `as_of` and `age_seconds`, never under
+ `aircraft`. Posture names such theaters in `stale_theaters` and does not
+ cache, surge records nothing for them, and the fleet score is a lower
+ bound.
+- A malformed `bbox` (not four comma-separated numbers, a latitude outside
+ -90..90 or longitude outside -180..180, a minimum not below its maximum)
+ returned every military aircraft in the world as the box's, or raised a
+ bare `ValueError`. It now returns `error` with `reason` `invalid_bbox`
+ without fetching; the tool schema carries a pattern.
+- `intel posture` printed 0 for theaters no flight source answered, under
+ a total that looked complete, and no data gaps. Those theaters now read
+ `unknown`, the total says it covers only the theaters that answered, and
+ the gaps are printed.
### Fixed: report maritime section
- The PDF/HTML report read `vessels` and `snapshot` for its maritime
@@ -784,6 +821,12 @@ source here, and no proxy is substituted for any of these measures.
branch head and passes now, and five tests kill the mutants that survived
the first round (radius boundary, malformed DMS, notation order,
staleness boundary, two components down).
+- `test_maritime_honesty_r3.py` for the third round: 44 tests, 26 of which
+ fail on the previous head; the other 18 pin parser guards and controls
+ that no test held. Each of 26 source mutants (stale-copy handling, bbox
+ validation, the CLI posture table, undated and empty feeds, the
+ short reuse of an empty answer, both lookbehinds, longitude-only tokens,
+ decimal minutes followed by seconds) is killed by this file.
### Still open
- The dashboard's nav-warnings table and fleet panel do not yet read
@@ -794,6 +837,11 @@ source here, and no proxy is substituted for any of these measures.
- A naval warning that cannot be placed leaves every waterway's status
unchanged; it is named only in `unplaced_naval_warnings` and
`data_gaps`.
+- One malformed coordinate the parser does not anticipate can still raise
+ inside the NGA parse loop and fail the whole feed; there is no
+ per-record guard.
+- For up to 5 minutes after an upgrade a posture cached by the previous
+ code can still be served.
### Added: AOI escalation news and convergence components
- `intel_aoi_escalation` now scores the news and convergence components it
diff --git a/ROADMAP.md b/ROADMAP.md
index 2de0745..09cd417 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -654,10 +654,10 @@ fail-quietly bugs below were fixed in the same-day follow-up
| UNHCR outage returned all-zero global totals with no error/degraded key ("zero refugees worldwide") | `sources/displacement.py` | fail-reads-as-success | :white_check_mark: Fixed (#22) |
| A climate zone whose fetch failed was silently omitted; full outage yielded `{"zones": {}}` with no marker | `sources/climate.py` | silent degradation | :white_check_mark: Fixed (#23) |
| "Resolved: Major outage" classified as an active critical incident; a dead provider feed still listed as checked | `sources/service_status.py` | misclassification | :white_check_mark: Fixed (#24) |
-| Naval warnings apply to all 9 waterways identically (no proximity/NAVAREA filter); `total_nearby` computed but never emitted | `sources/intelligence.py` vessel snapshot | precision | :white_check_mark: Fixed (Unreleased): a warning counts only at waterways within 300 km of a position its full text states; one that states no readable position counts nowhere (crediting positionless NAVAREA IV and XII warnings to Panama was measured wrong 5 of 5 times on the live feed and rejected) and, if naval, is listed in `unplaced_naval_warnings` with a reason; the rule is in `matching_rule`; `total_nearby` emitted; an NGA outage reads `unknown` and a frozen feed `stale`, not `clear` or a current threat level. Open: an unplaced naval warning leaves waterway statuses unchanged and is named only in `data_gaps` |
+| Naval warnings apply to all 9 waterways identically (no proximity/NAVAREA filter); `total_nearby` computed but never emitted | `sources/intelligence.py` vessel snapshot | precision | :white_check_mark: Fixed (Unreleased): a warning counts only at waterways within 300 km of a position its full text states; one that states no readable position counts nowhere (crediting positionless NAVAREA IV and XII warnings to Panama was measured wrong 5 of 5 times on the live feed and rejected) and, if naval, is listed in `unplaced_naval_warnings` with a reason; the rule is in `matching_rule`; `total_nearby` emitted; an NGA outage reads `unknown` and a frozen feed `stale`, not `clear` or a current threat level; a feed whose currency cannot be checked (no parseable issue date, or no active warnings at all) reads `unknown` and the fleet leaves it out of its score; a position match cannot start right after a letter ('20-O3-44N' used to read 3.73N), which changed no position in 3,643 real warnings. Open: an unplaced naval warning leaves waterway statuses unchanged and is named only in `data_gaps` |
| Country/company/leader entity matching was substring-based ("usa" inside "thousand", "hamas" inside "Bahamas") | `analysis/entities.py` | false positives | :white_check_mark: Fixed in 0.5.0 (word-boundary alternations, measured faster) |
| Category keywords matched substrings ("airstrike" bumped severity via "strike"; "denied" fired "ied") | `analysis/classifier.py` | false positives | :white_check_mark: Fixed in 0.5.0 (boundary-anchored stems, per-keyword overrides) |
-| Silent-empty degradation without a marker on RSS/API failure | `sources/prediction.py` (documented as intended), `sources/maritime.py`, `sources/news.py` RSS path, `sources/fleet.py` `_safe` wrapper, `sources/military.py` military flights and theater posture | silent degradation | :yellow_circle: `sources/news.py` RSS path fixed 2026-10-17 (every call reports `feeds_attempted` / `feeds_ok` / `feeds_failed` / `feeds_stale`; no feed answering live is `error` + `degraded` + `reason: all_feeds_failed`, including the warm-cache case where failed feeds came back as expired copies and counted as healthy; failing-first regression tests). Since the 2026-10-17 review: fewer than half of the feeds answering live is `degraded` + `reason: partial_feeds_failed` with no error (measured that day: 95 of 119 answered, the rest permanent 404 / 403 / 410 plus one timeout), passed through by trending keywords, situations, top stories and the dossier; links are kept only when http(s) and titles are capped at 500 characters. `maritime.py`, `fleet.py`, military flights and theater posture fixed (Unreleased): outages carry `error`/`degraded`/`reason` and `data_gaps`; failed or stale fleet components are named in `unavailable_components`, and fleet readiness reads `UNKNOWN` with none available and is marked a lower bound with some missing; military flights with both sources down carries `error`/`degraded`/`reason` (no `data_gaps`) beside `source: "none"`; posture names the theaters no flight source answered for; nav warnings flag (`feed_stale`) a feed whose newest warning is over 14 days old (NGA's API holds nothing issued after 10 May 2024, measured 2026-10-17). `sources/prediction.py` fixed, unreleased: an outage or unexpected response adds `error` + `degraded`, an expired-cache serve adds `stale`; keys unchanged; regression tests written failing-first (3 failed on the old module). The fetcher's stale fallback marks only dict payloads, so other text and XML sources can serve expired copies unmarked Open: the dashboard and collector do not yet read the new markers; strategic posture and temporal anomalies still read a posture outage as zero activity |
+| Silent-empty degradation without a marker on RSS/API failure | `sources/prediction.py` (documented as intended), `sources/maritime.py`, `sources/news.py` RSS path, `sources/fleet.py` `_safe` wrapper, `sources/military.py` military flights and theater posture | silent degradation | :yellow_circle: `sources/news.py` RSS path fixed 2026-10-17 (every call reports `feeds_attempted` / `feeds_ok` / `feeds_failed` / `feeds_stale`; no feed answering live is `error` + `degraded` + `reason: all_feeds_failed`, including the warm-cache case where failed feeds came back as expired copies and counted as healthy; failing-first regression tests). Since the 2026-10-17 review: fewer than half of the feeds answering live is `degraded` + `reason: partial_feeds_failed` with no error (measured that day: 95 of 119 answered, the rest permanent 404 / 403 / 410 plus one timeout), passed through by trending keywords, situations, top stories and the dossier; links are kept only when http(s) and titles are capped at 500 characters. `maritime.py`, `fleet.py`, military flights and theater posture fixed (Unreleased): outages carry `error`/`degraded`/`reason` and `data_gaps`; failed or stale fleet components are named in `unavailable_components`, and fleet readiness reads `UNKNOWN` with none available and is marked a lower bound with some missing; military flights with no live source carries `error`/`degraded`/`reason` and `data_gaps` beside `source: "none"`, including the warm-cache case, where an expired adsb.lol or OpenSky copy used to come back as current flights (it now goes under `stale_copy` with its age, after OpenSky is tried live); posture names the theaters no flight source answered for (`stale_theaters` for those only a copy answered) and does not cache them; a malformed `bbox` is `invalid_bbox` instead of the whole world; `intel posture` prints those theaters as unknown with the gaps; an empty NGA answer is degraded, not a quiet sea; nav warnings flag (`feed_stale`) a feed whose newest warning is over 14 days old (NGA's API holds nothing issued after 10 May 2024, measured 2026-10-17). `sources/prediction.py` fixed, unreleased: an outage or unexpected response adds `error` + `degraded`, an expired-cache serve adds `stale`; keys unchanged; regression tests written failing-first (3 failed on the old module). The fetcher's stale fallback marks only dict payloads, so other text and XML sources can serve expired copies unmarked Open: the dashboard and collector do not yet read the new markers; strategic posture and temporal anomalies still read a posture outage as zero activity |
| Country dossier news was always empty with no marker, for every country: it asked the feed for `category="all"` (not a category, so `fetch_news_feed` answered with an error dict), read `articles` / `source` while the feed emits `items` / `feed_name`, and checked only its own `_error`, never the feed's `error`. Also, 28 of the 50 accepted codes have no headline keywords, so their search could never match | `analysis/dossier.py` news section | fail-reads-as-success | :white_check_mark: Fixed 2026-10-17, unreleased (reads every feed; a feed error or outage passes through as `error` / `degraded` / `reason` with `mention_count: null` and a data gap; failed and stale feeds named; keywordless countries report "mentions not searched"; `intel dossier` prints `News: not measured`; failing-first tests drive the real `fetch_news_feed` output). Since the 2026-10-17 review: headlines match on whole words (the substring test counted "Tirana" as Iran and "Indiana" as India), four compound names are removed first, and the section reports `matching_items`, `mention_count_capped`, `items_searched` and `searched_span` |
| 33 CLI commands rendered upstream errors as healthy empty states | `cli.py` | fail-reads-as-success | :white_check_mark: Fixed in 0.6.0 (shared bail-on-error path; 43 failing-first tests) |
| Rich markup swallowed lowercase bracketed values and let remote titles inject markup | `cli.py` | output corruption | :white_check_mark: Fixed in 0.6.0 (per-site escaping; injection test) |
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index 014649e..7f8d82d 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -566,10 +566,20 @@ def posture(ctx: click.Context) -> None:
if _bail_on_error(ctx, data):
return
- console.print(
- f"[bold]{data.get('total_military_aircraft', 0)} total military aircraft[/bold]\n"
- )
theaters = data.get("theaters", {})
+ # A theater no flight source answered for used to print 0, the reading
+ # of an empty sky, under a total that looked complete.
+ unknown = set(data.get("unavailable_theaters") or []) | {
+ name for name, info in theaters.items() if info.get("source") == "none"
+ }
+ total = data.get("total_military_aircraft", 0)
+ if unknown:
+ console.print(
+ f"[bold]{total} military aircraft in the theaters that answered[/bold] "
+ f"({len(theaters) - len(unknown)} of {len(theaters)}; the rest are unknown)\n"
+ )
+ else:
+ console.print(f"[bold]{total} total military aircraft[/bold]\n")
table = Table(title="Theater Posture", box=box.SIMPLE_HEAVY)
table.add_column("Theater", style="bold")
@@ -581,6 +591,8 @@ def posture(ctx: click.Context) -> None:
count = info.get("count", 0)
style = "red bold" if count >= 20 else "yellow" if count >= 5 else ""
count_str = f"[{style}]{count}[/{style}]" if style else str(count)
+ if name in unknown:
+ count_str = "[yellow]unknown[/yellow]"
table.add_row(
name.replace("_", " ").title(),
count_str,
@@ -588,6 +600,7 @@ def posture(ctx: click.Context) -> None:
_cell(", ".join(info.get("sample_callsigns", [])[:3])),
)
console.print(table)
+ _print_data_gaps(data)
# ---------------------------------------------------------------------------
diff --git a/src/world_intel_mcp/reports.py b/src/world_intel_mcp/reports.py
index 255385d..c03f6e5 100644
--- a/src/world_intel_mcp/reports.py
+++ b/src/world_intel_mcp/reports.py
@@ -431,6 +431,13 @@ def _render_maritime(data: dict) -> str:
f"last updated {_esc(data.get('newest_issue_date'))}: these statuses "
"describe that date, not today.</p>"
)
+ elif data.get("feed_stale") is not False:
+ # An undated or empty feed used to render its statuses as current.
+ html += (
+ '<p><span class="metric amber">UNDATED</span> How current the NGA '
+ "warning feed is cannot be checked, so these statuses are not "
+ "current threat levels.</p>"
+ )
ww_rows = []
for ww in waterways:
if not isinstance(ww, dict):
diff --git a/src/world_intel_mcp/sources/fleet.py b/src/world_intel_mcp/sources/fleet.py
index 41b56e9..dc66a31 100644
--- a/src/world_intel_mcp/sources/fleet.py
+++ b/src/world_intel_mcp/sources/fleet.py
@@ -91,7 +91,8 @@ async def fetch_fleet_report(fetcher) -> dict:
A component that raised or reported an error is named in
unavailable_components and data_gaps, and the report is degraded; so is
a vessel snapshot whose NGA feed is stale (feed_stale), since its
- warnings describe the feed's last update, not today. The readiness
+ warnings describe the feed's last update, not today, or whose currency
+ cannot be checked (feed_stale anything but False). The readiness
score leaves unavailable inputs out, which makes it a lower bound
(readiness_lower_bound True, with the reason in data_gaps); so does a
theater with no flight source (posture's unavailable_theaters) or a
@@ -138,6 +139,16 @@ async def fetch_fleet_report(fetcher) -> dict:
f"{data.get('stale_after_days')}-day threshold)"
)
continue
+ if name == "vessel_snapshot" and data.get("feed_stale") is not False:
+ # Only feed_stale False says the snapshot is current; None (no
+ # usable issue date, or an empty feed) used to score as today.
+ unavailable.append(name)
+ data_gaps.append(
+ f"{name}: how current its NGA feed is cannot be checked "
+ "(feed_stale null), so its waterway statuses are not scored"
+ )
+ data_gaps.extend(f"{name}: {gap}" for gap in data.get("data_gaps") or [])
+ continue
gaps = data.get("data_gaps") or []
data_gaps.extend(f"{name}: {gap}" for gap in gaps)
if data.get("degraded") and not gaps:
diff --git a/src/world_intel_mcp/sources/intelligence.py b/src/world_intel_mcp/sources/intelligence.py
index e440b8f..2dac444 100644
--- a/src/world_intel_mcp/sources/intelligence.py
+++ b/src/world_intel_mcp/sources/intelligence.py
@@ -1602,7 +1602,9 @@ _VESSEL_MATCHING_RULE = (
"Naval ones are listed in unplaced_naval_warnings with the reason. "
"status counts the naval-keyword warnings credited to the waterway; it "
"reads stale when the feed's newest warning is older than "
- "stale_after_days and unknown when the feed is unavailable. "
+ "stale_after_days and unknown when the feed is unavailable or how "
+ "current it is cannot be checked (feed_stale null: no usable issue "
+ "date, or no active warnings at all). "
"total_nearby counts credited warnings of any topic."
)
@@ -1620,7 +1622,8 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:
Scores each waterway: clear/advisory/elevated/critical; stale when the
feed's newest warning is past its staleness threshold (the counts then
describe the feed's last update, status_as_of, not today); unknown when
- the feed itself is unavailable.
+ the feed itself is unavailable or its currency cannot be checked
+ (feed_stale None: no usable issue date, or an empty feed).
Note: Real-time AIS requires paid API. This uses NGA MSI as a
free proxy for naval activity indicators.
@@ -1642,6 +1645,10 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:
all_warnings = nav_data.get("warnings", []) or []
feed_error = nav_data.get("error")
feed_stale = nav_data.get("feed_stale") is True
+ # Only feed_stale False says the feed is current. None (no usable issue
+ # date, or no active warnings) used to score as current: three undated
+ # warnings near Hormuz read "critical".
+ currency_unknown = not feed_error and nav_data.get("feed_stale") is None
credited: dict[str, dict] = {
ww["name"]: {"naval": [], "nearby": 0} for ww in STRATEGIC_WATERWAYS
@@ -1720,7 +1727,7 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:
naval_warnings = sorted(entry["naval"], key=lambda d: d["distance_km"])
naval_count = len(naval_warnings)
- if feed_error:
+ if feed_error or currency_unknown:
status = "unknown"
elif feed_stale:
# A frozen feed's warnings describe its last update, not today:
@@ -1754,6 +1761,12 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:
data_gaps = [f"NGA feed: {gap}" for gap in nav_data.get("data_gaps") or []]
if feed_error and not data_gaps:
data_gaps.append(f"NGA feed: {feed_error}")
+ if currency_unknown:
+ data_gaps.append(
+ "every waterway reads unknown, not a threat level: how current the "
+ "NGA feed is cannot be checked (feed_stale null), so naval_warnings "
+ "is not scored as today's activity"
+ )
if feed_stale and not feed_error:
data_gaps.append(
"every waterway reads stale, not a threat level: naval_warnings "
@@ -1798,7 +1811,7 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:
response["error"] = f"NGA navigational warnings unavailable: {feed_error}"
response["degraded"] = True
response["reason"] = nav_data.get("reason") or "nav_warnings_unavailable"
- elif nav_data.get("degraded"):
+ elif nav_data.get("degraded") or currency_unknown:
response["degraded"] = True
return response
diff --git a/src/world_intel_mcp/sources/maritime.py b/src/world_intel_mcp/sources/maritime.py
index a722d28..40e8f78 100644
--- a/src/world_intel_mcp/sources/maritime.py
+++ b/src/world_intel_mcp/sources/maritime.py
@@ -7,6 +7,7 @@ No API key required.
import logging
import re
+import time
from datetime import datetime, timedelta, timezone
from ..fetcher import Fetcher
@@ -151,16 +152,24 @@ def _extract_coords(text: str) -> tuple[float | None, float | None]:
# One coordinate: degrees-minutes ('22-16.65') or degrees-minutes-seconds
# ('20-03-44'). Latitude and longitude are read separately, so a mixed pair
-# ('20-03-44N 072-58.00W') parses as written. The lookbehind keeps a match
-# from starting inside a longer number: two separate patterns used to read
-# the '03-44N' of that mixed pair as latitude 3.73, about 1,800 km off.
+# ('20-03-44N 072-58.00W') parses as written: one pattern for the whole
+# lat/lon pair fixed that, where two separate patterns read the pair's
+# '03-44N' as latitude 3.73, about 1,800 km off. The lookbehinds below do
+# something else: they keep a match from starting inside a longer number
+# or word, so a malformed coordinate ('20-03-44-10N', '2O-03-44N' with a
+# letter O, '20-O3-44N', chart number '26060-03.5N') reads as no position
+# rather than a confident wrong one. _POSITION_RE's lookbehind also
+# excludes letters ('20-O3-44N' read as 3.73N); widening it changed no
+# position in 3,643 real warnings (2024 and live). _COORD_TOKEN_RE keeps
+# the digit-only one, so a mistyped coordinate still counts as a stated
+# position (unplaced as position_unreadable, not by its area code).
_COORD_PART = r"(\d{1,3})-(\d{1,2}(?:\.\d+)?)(?:-(\d{1,2}(?:\.\d+)?))?"
# A lat/lon pair. Latitude and longitude may be separated by whitespace, a
# comma or a slash: live HYDROLANT 2024-473, 479 and 488 write
# '60-17.40S, 050-16.80W', which a whitespace-only separator never read.
_POSITION_RE = re.compile(
- rf"(?<![\d.-]){_COORD_PART}\s*([NS])(?:\s*[,/]\s*|\s+){_COORD_PART}\s*([EW])"
+ rf"(?<![\w.-]){_COORD_PART}\s*([NS])(?:\s*[,/]\s*|\s+){_COORD_PART}\s*([EW])"
)
# Any single latitude or longitude ('24-30N', '080-00W', '65-07.80 S'),
@@ -366,6 +375,27 @@ def _parse_warning(warning: dict) -> dict:
# Public API
# ---------------------------------------------------------------------------
+# An empty answer is kept in the cache this long, not the hour a full feed
+# is, so a feed fault is not replayed for an hour after NGA recovers.
+_EMPTY_ANSWER_REUSE_SECONDS = 300
+
+
+def _expire_empty_answer(fetcher: Fetcher, cache_key: str) -> None:
+ """Drop a cached empty NGA answer once it is _EMPTY_ANSWER_REUSE_SECONDS
+ old, so the next call fetches again. The fetcher caches every answer for
+ the TTL it was given; this shortens that for an empty one without
+ restamping when it was fetched."""
+ cache = getattr(fetcher, "cache", None)
+ get_meta = getattr(cache, "get_stale_meta", None)
+ if get_meta is None:
+ return
+ meta = get_meta(cache_key)
+ if not isinstance(meta, tuple):
+ return
+ if time.time() - meta[1] >= _EMPTY_ANSWER_REUSE_SECONDS:
+ cache.delete(cache_key)
+
+
async def fetch_nav_warnings(
fetcher: Fetcher,
navarea: str | None = None,
@@ -391,7 +421,10 @@ async def fetch_nav_warnings(
the response is degraded, with the age named in data_gaps. The
freshness fields describe the whole active feed, before any navarea
filter. feed_stale is None when no usable issue date says how current
- the feed is.
+ the feed is, or when the active feed is empty; either way the
+ response is degraded, with the reason in data_gaps, and an empty
+ answer is reused from the cache for at most
+ _EMPTY_ANSWER_REUSE_SECONDS.
"""
cache_label = navarea.upper() if navarea else "all"
cache_key = f"maritime:warnings:{cache_label}"
@@ -533,7 +566,19 @@ async def fetch_nav_warnings(
f"{_FUTURE_TOLERANCE.days} day ahead, left out of the freshness check: "
+ ", ".join(f"{_warning_label(w)} ({w.get('issue_date')})" for w in future)
)
- if feed and newest is None:
+ if not feed:
+ # NGA answering 200 with no active warnings (or only cancelled ones)
+ # used to read as a quiet sea: count 0, no marker, every waterway
+ # clear. The feed carried 386 active warnings on 2026-10-17, so an
+ # empty one is more likely a fault than calm; feed_stale stays None.
+ response["degraded"] = True
+ response["data_gaps"].append(
+ "NGA returned no active warnings (the feed normally carries "
+ "hundreds), so a quiet sea cannot be told from a feed fault and how "
+ "current the list is cannot be checked"
+ )
+ _expire_empty_answer(fetcher, cache_key)
+ elif newest is None:
response["degraded"] = True
if future:
response["data_gaps"].append(
diff --git a/src/world_intel_mcp/sources/military.py b/src/world_intel_mcp/sources/military.py
index dcf81b0..5b6ffa4 100644
--- a/src/world_intel_mcp/sources/military.py
+++ b/src/world_intel_mcp/sources/military.py
@@ -144,7 +144,60 @@ def _extract_aircraft(state: list) -> dict:
# Public API
# ---------------------------------------------------------------------------
-async def _fetch_adsblol_military(fetcher: Fetcher) -> list[dict] | None:
+class _FlightRead:
+ """One source's military aircraft, with how old the copy is.
+
+ stale_age_seconds is None for a live answer. When the live fetch fails
+ the fetcher may hand back its last cached copy, marked _stale with
+ _stale_age_seconds; those markers used to be dropped here, so a copy
+ days old read as current flights.
+ """
+
+ __slots__ = ("aircraft", "stale_age_seconds")
+
+ def __init__(self, aircraft: list[dict], stale_age_seconds: float | None) -> None:
+ self.aircraft = aircraft
+ self.stale_age_seconds = stale_age_seconds
+
+
+def _stale_age(data: object) -> float | None:
+ if isinstance(data, dict) and data.get("_stale"):
+ age = data.get("_stale_age_seconds")
+ return float(age) if isinstance(age, (int, float)) else 0.0
+ return None
+
+
+def _parse_bbox(bbox: str) -> tuple[float, float, float, float] | None:
+ """lamin, lomin, lamax, lomax from "lamin,lomin,lamax,lomax", or None
+ when the box is malformed: not exactly four comma-separated finite
+ numbers, a latitude outside -90..90, a longitude outside -180..180, or
+ a minimum not below its maximum. A 3-part or semicolon-split box used
+ to skip the filter and return every aircraft in the world as the box's.
+ """
+ parts = bbox.split(",")
+ if len(parts) != 4:
+ return None
+ try:
+ la_min, lo_min, la_max, lo_max = (float(p) for p in parts)
+ except ValueError:
+ return None
+ # The chained comparisons are False for nan and inf too.
+ if not (-90 <= la_min < la_max <= 90 and -180 <= lo_min < lo_max <= 180):
+ return None
+ return la_min, lo_min, la_max, lo_max
+
+
+def _in_bbox(aircraft: list[dict], box: tuple[float, float, float, float]) -> list[dict]:
+ la_min, lo_min, la_max, lo_max = box
+ return [
+ a for a in aircraft
+ if a["latitude"] is not None and a["longitude"] is not None
+ and la_min <= a["latitude"] <= la_max
+ and lo_min <= a["longitude"] <= lo_max
+ ]
+
+
+async def _fetch_adsblol_military(fetcher: Fetcher) -> _FlightRead | None:
"""Fetch military aircraft from adsb.lol free API (pre-filtered)."""
data = await fetcher.get_json(
url=_ADSBLOL_MIL_URL,
@@ -176,24 +229,23 @@ async def _fetch_adsblol_military(fetcher: Fetcher) -> list[dict] | None:
"aircraft_type": ac.get("t"),
"registration": ac.get("r"),
})
- return aircraft
+ return _FlightRead(aircraft, _stale_age(data))
async def _fetch_opensky_military(
- fetcher: Fetcher, bbox: str | None = None,
-) -> list[dict] | None:
- """Fetch military aircraft from OpenSky (requires filtering)."""
+ fetcher: Fetcher, bbox: tuple[float, float, float, float] | None = None,
+) -> _FlightRead | None:
+ """Fetch military aircraft from OpenSky (requires filtering).
+
+ bbox is an already validated (lamin, lomin, lamax, lomax).
+ """
params: dict[str, str] = {}
if bbox is not None:
- parts = bbox.split(",")
- if len(parts) == 4:
- params["lamin"] = parts[0]
- params["lomin"] = parts[1]
- params["lamax"] = parts[2]
- params["lomax"] = parts[3]
+ for key, value in zip(("lamin", "lomin", "lamax", "lomax"), bbox):
+ params[key] = str(int(value)) if value.is_integer() else repr(value)
headers = _build_opensky_auth_headers()
- cache_label = bbox or "global"
+ cache_label = ",".join(params.values()) if params else "global"
data = await fetcher.get_json(
url=_OPENSKY_STATES_URL,
@@ -216,7 +268,7 @@ async def _fetch_opensky_military(
callsign = state[1] or ""
if _is_military_icao(icao24) or _is_military_callsign(callsign):
aircraft.append(_extract_aircraft(state))
- return aircraft
+ return _FlightRead(aircraft, _stale_age(data))
async def fetch_military_flights(
@@ -230,56 +282,78 @@ async def fetch_military_flights(
Args:
fetcher: Shared HTTP fetcher with caching and circuit breaking.
- bbox: Optional bounding box as "lamin,lomin,lamax,lomax" (OpenSky only).
+ bbox: Optional bounding box as "lamin,lomin,lamax,lomax": four
+ comma-separated numbers, latitudes -90..90 and longitudes
+ -180..180, each minimum below its maximum (a box crossing the
+ antimeridian is two boxes). Anything else returns error /
+ reason "invalid_bbox" without fetching.
Returns:
Dict with aircraft list, count, filter description, source, and timestamp.
- When neither source answers, source is "none" and the dict also carries
- error, degraded and reason: the count is unknown, not zero.
+ When neither source answers live, source is "none" and the dict also
+ carries error, degraded and reason: the count is unknown, not zero.
+ An expired cached copy is never returned as current flights: when
+ it is all that is left it goes under stale_copy, with its source,
+ as_of and age, and aircraft stays empty.
"""
+ box: tuple[float, float, float, float] | None = None
+ if bbox is not None:
+ box = _parse_bbox(bbox)
+ if box is None:
+ return {
+ "aircraft": [],
+ "count": 0,
+ "bbox": bbox,
+ "source": "none",
+ "timestamp": _utc_now_iso(),
+ "error": (
+ f"invalid bbox {bbox!r}: expected lamin,lomin,lamax,lomax as four "
+ "comma-separated numbers, latitudes -90..90, longitudes "
+ "-180..180, each minimum below its maximum (split a box that "
+ "crosses the antimeridian in two)"
+ ),
+ "reason": "invalid_bbox",
+ }
+
# Primary: adsb.lol (free, dedicated military endpoint, no filtering needed)
- aircraft = await _fetch_adsblol_military(fetcher)
- adsblol_failed = aircraft is None
- if aircraft is not None and len(aircraft) > 0:
+ adsblol = await _fetch_adsblol_military(fetcher)
+ adsblol_live = adsblol is not None and adsblol.stale_age_seconds is None
+ # A live answer with aircraft elsewhere but none in the box is a real zero.
+ adsblol_any = adsblol is not None and bool(adsblol.aircraft)
+ if adsblol is not None and box is not None:
# Apply bbox filter client-side if requested
- if bbox is not None:
- parts = bbox.split(",")
- if len(parts) == 4:
- la_min, lo_min, la_max, lo_max = map(float, parts)
- aircraft = [
- a for a in aircraft
- if a["latitude"] is not None and a["longitude"] is not None
- and la_min <= a["latitude"] <= la_max
- and lo_min <= a["longitude"] <= lo_max
- ]
+ adsblol.aircraft = _in_bbox(adsblol.aircraft, box)
+ if adsblol_live and adsblol_any:
return {
- "aircraft": aircraft,
- "count": len(aircraft),
+ "aircraft": adsblol.aircraft,
+ "count": len(adsblol.aircraft),
"military_filter": "adsblol_mil_endpoint",
"source": "adsb.lol",
"timestamp": _utc_now_iso(),
}
- # Fallback: OpenSky Network
+ # Fallback: OpenSky Network, tried live before any cached copy is
+ # considered.
logger.debug("adsb.lol unavailable, trying OpenSky")
- aircraft = await _fetch_opensky_military(fetcher, bbox)
- if aircraft is not None:
+ opensky = await _fetch_opensky_military(fetcher, box)
+ if opensky is not None and opensky.stale_age_seconds is None:
return {
- "aircraft": aircraft,
- "count": len(aircraft),
+ "aircraft": opensky.aircraft,
+ "count": len(opensky.aircraft),
"military_filter": "icao_prefix+callsign",
"source": "opensky",
"timestamp": _utc_now_iso(),
}
- # Neither source answered. This used to read as an empty sky (count 0,
- # told apart only by source "none"); the keys stay for the consumers
- # that read them, and error / degraded / reason mark the outage.
- if adsblol_failed:
- detail = "adsb.lol and OpenSky both failed"
- else:
+ # Neither source answered live. This used to read as an empty sky (count
+ # 0, told apart only by source "none"), and an expired cached copy used
+ # to come back as current flights stamped now; the keys stay for the
+ # consumers that read them, and error / degraded / reason mark the outage.
+ if adsblol_live:
detail = "adsb.lol returned no positioned aircraft and OpenSky failed"
- return {
+ else:
+ detail = "adsb.lol and OpenSky both failed"
+ response = {
"aircraft": [],
"count": 0,
"military_filter": "icao_prefix+callsign",
@@ -288,7 +362,41 @@ async def fetch_military_flights(
"error": f"No military flight source available ({detail})",
"degraded": True,
"reason": "military_flights_unavailable",
+ "data_gaps": [],
}
+ copies = [
+ (name, read) for name, read in (("adsb.lol", adsblol), ("opensky", opensky))
+ if read is not None and read.stale_age_seconds is not None
+ ]
+ if copies:
+ # Prefer a copy that holds aircraft; adsb.lol first.
+ name, read = next(((n, r) for n, r in copies if r.aircraft), copies[0])
+ age = read.stale_age_seconds
+ as_of = datetime.fromtimestamp(
+ datetime.now(timezone.utc).timestamp() - age, tz=timezone.utc
+ ).isoformat()
+ response["stale_copy"] = {
+ "source": name,
+ "aircraft": read.aircraft,
+ "count": len(read.aircraft),
+ "as_of": as_of,
+ "age_seconds": age,
+ }
+ response["stale_age_seconds"] = age
+ response["error"] = (
+ f"No live military flight source ({detail}); only an expired cached "
+ f"copy from {name}, {age:.0f} s old, remains (stale_copy)"
+ )
+ response["data_gaps"].append(
+ f"no live military flight source answered; the {len(read.aircraft)} "
+ f"aircraft in stale_copy are {name}'s cached copy as of {as_of} "
+ f"({age:.0f} s old), not current positions, and are not counted"
+ )
+ else:
+ response["data_gaps"].append(
+ "no military flight source answered: the aircraft count is unknown, not zero"
+ )
+ return response
async def fetch_theater_posture(fetcher: Fetcher) -> dict:
@@ -301,8 +409,11 @@ async def fetch_theater_posture(fetcher: Fetcher) -> dict:
source "none") has an unknown count, not zero: it is named in
unavailable_theaters and data_gaps and the response is degraded; with
every theater unavailable it carries error / reason. Its count stays 0
- for consumers that read the field directly. Only a complete posture is
- cached, so an outage is not replayed after the sources recover.
+ for consumers that read the field directly. A theater for which only an
+ expired cached copy answered is unavailable too, and is also named in
+ stale_theaters (its stale_copy_age_seconds gives the copy's age). Only a
+ complete, live posture is cached, so an outage is not replayed after the
+ sources recover.
Args:
fetcher: Shared HTTP fetcher with caching and circuit breaking.
@@ -328,14 +439,17 @@ async def fetch_theater_posture(fetcher: Fetcher) -> dict:
if ac.get("callsign"):
callsigns.append(ac["callsign"])
- return (name, {
+ summary = {
"count": len(aircraft_list),
"countries": sorted(countries),
"sample_callsigns": callsigns[:5],
"bbox": info["bbox"],
"description": info["desc"],
"source": result.get("source"),
- })
+ }
+ if result.get("stale_copy"):
+ summary["stale_copy_age_seconds"] = result["stale_copy"]["age_seconds"]
+ return (name, summary)
tasks = [
_fetch_theater(name, info) for name, info in THEATERS.items()
@@ -367,6 +481,16 @@ async def fetch_theater_posture(fetcher: Fetcher) -> dict:
f"{', '.join(unavailable)}: their counts are unknown, not zero, and "
"total_military_aircraft counts only the other theaters"
)
+ stale = [name for name in unavailable if "stale_copy_age_seconds" in theaters[name]]
+ if stale:
+ # An expired cached copy used to read as current flights, and a
+ # posture built from it was cached as complete.
+ oldest = max(theaters[name]["stale_copy_age_seconds"] for name in stale)
+ response["stale_theaters"] = stale
+ response["data_gaps"].append(
+ f"for {', '.join(stale)} only an expired cached copy answered "
+ f"(up to {oldest:.0f} s old); it is not counted as current flights"
+ )
if len(unavailable) == len(theaters):
response["error"] = (
"No military flight source available for any theater "
diff --git a/src/world_intel_mcp/tests/test_maritime_honesty_r3.py b/src/world_intel_mcp/tests/test_maritime_honesty_r3.py
new file mode 100644
index 0000000..bcda0c7
--- /dev/null
+++ b/src/world_intel_mcp/tests/test_maritime_honesty_r3.py
@@ -0,0 +1,656 @@
+"""Tests for the third maritime-honesty review (2026-10-17): expired
+cached flight copies (behavior F1, tests F1), the CLI posture table
+(behavior F2, tests F8), an undated NGA feed (behavior F3, tests F7), an
+empty NGA answer (behavior F4, tests F6), malformed bounding boxes
+(behavior F7), and the parser guards no test pinned (behavior F8, tests
+F2-F5).
+
+The flight tests run the real Fetcher and Cache against respx-mocked
+adsb.lol and OpenSky 500s, with an expired row seeded into the cache the
+way a long-running server holds one; NGA records are built in the live
+API's shape.
+
+Gaps / not covered: no live upstream call is made here; a timeout and the
+circuit-open branch reach the same stale fallback but only HTTP 500 is
+driven; consumers of military flights other than posture, surge, fleet
+and the CLI (AOI briefs, situation, daily digest, the dashboard and the
+collector) are not exercised; the MCP schema pattern for bbox is checked
+for what it accepts, not enforced by a running server.
+"""
+
+import asyncio as asyncio_mod
+import re
+import time
+from datetime import datetime, timedelta, timezone
+
+import httpx
+import pytest
+import respx
+from click.testing import CliRunner
+
+from world_intel_mcp import cli
+from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.reports import _render_maritime
+from world_intel_mcp.sources import intelligence, maritime, military
+from world_intel_mcp.sources.fleet import fetch_fleet_report
+from world_intel_mcp.tools import conflict
+
+_ADSBLOL = r".*api\.adsb\.lol.*"
+_OPENSKY = r".*opensky-network\.org.*"
+_NGA = r".*msi\.nga\.mil.*"
+_MONTHS = "JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC".split()
+_THREE_DAYS = 3 * 86400
+
+# RCH1 over Germany (inside the european box), RCH2 over the Gulf.
+_ADSBLOL_BODY = {
+ "ac": [
+ {"hex": "ae1234", "flight": "RCH1 ", "lat": 50.0, "lon": 10.0},
+ {"hex": "ae5678", "flight": "RCH2", "lat": 26.5, "lon": 56.2},
+ ]
+}
+
+
+def _opensky_state(icao24: str, callsign: str, lat: float, lon: float) -> list:
+ return [icao24, callsign, "United States", None, None, lon, lat, 9000.0,
+ False, 200.0, 90.0, None, None, None, "1234", False, 0]
+
+
+async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+
+def _returning(value):
+ async def _fake(*args, **kwargs):
+ return value
+
+ return _fake
+
+
+def _seed_expired(fetcher: Fetcher, key: str, value, age_seconds: float) -> None:
+ """A cache row written age_seconds ago with a 300 s TTL, long expired."""
+ fetcher.cache.set(key, value, 300)
+ created = time.time() - age_seconds
+ conn = fetcher.cache._get_conn()
+ conn.execute(
+ "UPDATE cache SET created_at = ?, expires_at = ? WHERE key = ?",
+ (created, created + 300, key),
+ )
+ conn.commit()
+
+
+def _stamp(when: datetime) -> str:
+ return f"{when:%d%H%M}Z {_MONTHS[when.month - 1]} {when.year}"
+
+
+def _record(number: int, area: str, text: str, issued: str, cancel=None) -> dict:
+ return {
+ "msgYear": 2026, "msgNumber": number, "navArea": area,
+ "subregion": "00", "text": text, "status": "A",
+ "issueDate": issued, "authority": "NAVSAFETY", "cancelDate": cancel,
+ }
+
+
+def _mock_nga(records: list[dict]):
+ return respx.get(url__regex=_NGA).mock(
+ return_value=httpx.Response(200, json={"broadcast-warn": records})
+ )
+
+
+def _hormuz_naval(issued: str) -> list[dict]:
+ # 26-34.00N 056-15.00E is about 10 km from the Hormuz reference point.
+ return [
+ _record(n, "P", "PERSIAN GULF.\nNAVAL EXERCISE IN AREA 26-34.00N 056-15.00E.\n", issued)
+ for n in (1, 2, 3)
+ ]
+
+
+def _by_name(result: dict) -> dict[str, dict]:
+ return {ww["name"]: ww for ww in result["waterways"]}
+
+
+# ---------------------------------------------------------------------------
+# F1: an expired cached flight copy is never current flights
+# ---------------------------------------------------------------------------
+
+
+async def test_expired_adsblol_copy_is_an_outage_not_current_flights(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Regression: with adsb.lol and OpenSky both down, a 3-day-old
+ adsb.lol copy came back as source adsb.lol, stamped now, with no error
+ or degraded flag, and OpenSky was never tried."""
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ _seed_expired(fetcher, "military:adsblol:mil", _ADSBLOL_BODY, _THREE_DAYS)
+ respx.get(url__regex=_ADSBLOL).mock(return_value=httpx.Response(500))
+ opensky = respx.get(url__regex=_OPENSKY).mock(return_value=httpx.Response(500))
+
+ result = await military.fetch_military_flights(fetcher)
+
+ assert result["source"] == "none"
+ assert result["aircraft"] == []
+ assert result["count"] == 0
+ assert result["degraded"] is True
+ assert result["reason"] == "military_flights_unavailable"
+ assert opensky.called
+ copy = result["stale_copy"]
+ assert copy["source"] == "adsb.lol"
+ assert [a["callsign"] for a in copy["aircraft"]] == ["RCH1", "RCH2"]
+ assert copy["count"] == 2
+ assert copy["age_seconds"] == pytest.approx(_THREE_DAYS, abs=60)
+ assert result["stale_age_seconds"] == copy["age_seconds"]
+ as_of = datetime.fromisoformat(copy["as_of"])
+ expected = datetime.now(timezone.utc) - timedelta(seconds=_THREE_DAYS)
+ assert abs((as_of - expected).total_seconds()) < 60
+ assert result["error"] == (
+ "No live military flight source (adsb.lol and OpenSky both failed); only "
+ f"an expired cached copy from adsb.lol, {copy['age_seconds']:.0f} s old, "
+ "remains (stale_copy)"
+ )
+ assert result["data_gaps"] == [
+ "no live military flight source answered; the 2 aircraft in stale_copy "
+ f"are adsb.lol's cached copy as of {copy['as_of']} "
+ f"({copy['age_seconds']:.0f} s old), not current positions, and are not counted"
+ ]
+
+
+async def test_expired_adsblol_copy_is_filtered_to_the_box(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ _seed_expired(fetcher, "military:adsblol:mil", _ADSBLOL_BODY, _THREE_DAYS)
+ respx.get(url__regex=_ADSBLOL).mock(return_value=httpx.Response(500))
+ respx.get(url__regex=_OPENSKY).mock(return_value=httpx.Response(500))
+
+ result = await military.fetch_military_flights(fetcher, bbox="35,-25,72,45")
+
+ assert result["count"] == 0
+ assert [a["callsign"] for a in result["stale_copy"]["aircraft"]] == ["RCH1"]
+
+
+async def test_live_opensky_is_tried_before_an_expired_adsblol_copy(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ _seed_expired(fetcher, "military:adsblol:mil", _ADSBLOL_BODY, _THREE_DAYS)
+ respx.get(url__regex=_ADSBLOL).mock(return_value=httpx.Response(500))
+ respx.get(url__regex=_OPENSKY).mock(
+ return_value=httpx.Response(
+ 200, json={"states": [_opensky_state("ae0009", "RCH9", 50.0, 10.0)]}
+ )
+ )
+
+ result = await military.fetch_military_flights(fetcher)
+
+ assert result["source"] == "opensky"
+ assert [a["callsign"] for a in result["aircraft"]] == ["RCH9"]
+ assert not {"error", "degraded", "reason", "stale_copy"} & set(result)
+
+
+async def test_expired_opensky_copy_is_an_outage_not_current_flights(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ _seed_expired(
+ fetcher,
+ "military:flights:global",
+ {"states": [_opensky_state("ae0009", "RCH9", 50.0, 10.0)]},
+ 3000,
+ )
+ respx.get(url__regex=_ADSBLOL).mock(return_value=httpx.Response(500))
+ respx.get(url__regex=_OPENSKY).mock(return_value=httpx.Response(500))
+
+ result = await military.fetch_military_flights(fetcher)
+
+ assert result["source"] == "none"
+ assert result["aircraft"] == []
+ assert result["stale_copy"]["source"] == "opensky"
+ assert result["stale_copy"]["count"] == 1
+ assert result["stale_copy"]["age_seconds"] == pytest.approx(3000, abs=60)
+ assert "only an expired cached copy from opensky" in result["error"]
+
+
+async def test_warm_cache_outage_reaches_posture_surge_and_fleet_as_an_outage(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, temporal_baseline
+) -> None:
+ """Regression (tests F1, HIGH): the 3-day-old copy was cached as a
+ complete posture, recorded into the surge baselines as today's
+ traffic, and scored as a firm fleet readiness with no data gap."""
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ monkeypatch.setattr(intelligence, "_temporal", temporal_baseline)
+ _seed_expired(fetcher, "military:adsblol:mil", _ADSBLOL_BODY, _THREE_DAYS)
+ respx.get(url__regex=_ADSBLOL).mock(return_value=httpx.Response(500))
+ respx.get(url__regex=_OPENSKY).mock(return_value=httpx.Response(500))
+ _mock_nga(_hormuz_naval(_stamp(datetime.now(timezone.utc) - timedelta(hours=2))))
+
+ posture = await military.fetch_theater_posture(fetcher)
+
+ assert posture["unavailable_theaters"] == list(military.THEATERS)
+ assert posture["stale_theaters"] == list(military.THEATERS)
+ assert posture["total_military_aircraft"] == 0
+ assert posture["error"].startswith("No military flight source available for any theater")
+ assert any(
+ gap.startswith(f"for {', '.join(military.THEATERS)} only an expired cached copy answered")
+ for gap in posture["data_gaps"]
+ )
+ assert all(
+ t["stale_copy_age_seconds"] == pytest.approx(_THREE_DAYS, abs=60)
+ for t in posture["theaters"].values()
+ )
+ assert fetcher.cache.get("military:posture") is None
+
+ surge = await intelligence.fetch_military_surge(fetcher)
+
+ assert surge["error"].startswith("Theater posture unavailable")
+ assert surge["regions_checked"] == 0
+ rows = temporal_baseline._get_conn().execute("SELECT key FROM baselines").fetchall()
+ assert rows == []
+
+ fleet = await fetch_fleet_report(fetcher)
+
+ assert fleet["unavailable_components"] == ["military_surge", "theater_posture"]
+ assert fleet["readiness_lower_bound"] is True
+ assert fleet["total_tracked_aircraft"] == 0
+ assert fleet["degraded"] is True
+ assert temporal_baseline._get_conn().execute("SELECT key FROM baselines").fetchall() == []
+
+
+async def test_posture_names_a_theater_answered_only_by_an_expired_copy(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _flights(fetcher, bbox=None):
+ name = next(n for n, info in military.THEATERS.items() if info["bbox"] == bbox)
+ if name == "arctic":
+ return {
+ "aircraft": [], "count": 0, "source": "none",
+ "error": "No live military flight source", "degraded": True,
+ "stale_copy": {"source": "adsb.lol", "aircraft": [], "count": 0,
+ "as_of": "2026-10-17T00:00:00+00:00", "age_seconds": 3000.0},
+ }
+ aircraft = [{"callsign": "RCH1", "origin_country": "United States"}] * (
+ 2 if name == "european" else 0
+ )
+ return {"aircraft": aircraft, "count": len(aircraft), "source": "opensky"}
+
+ monkeypatch.setattr(military, "fetch_military_flights", _flights)
+
+ result = await military.fetch_theater_posture(fetcher)
+
+ assert result["unavailable_theaters"] == ["arctic"]
+ assert result["stale_theaters"] == ["arctic"]
+ assert result["theaters"]["arctic"]["stale_copy_age_seconds"] == 3000.0
+ assert "stale_copy_age_seconds" not in result["theaters"]["european"]
+ assert result["total_military_aircraft"] == 2
+ assert result["data_gaps"] == [
+ "neither adsb.lol nor OpenSky returned military flights for arctic: their "
+ "counts are unknown, not zero, and total_military_aircraft counts only the "
+ "other theaters",
+ "for arctic only an expired cached copy answered (up to 3000 s old); it is "
+ "not counted as current flights",
+ ]
+ assert "error" not in result
+ assert fetcher.cache.get("military:posture") is None
+
+
+# ---------------------------------------------------------------------------
+# Behavior F7: a malformed bbox is an error, never the whole world
+# ---------------------------------------------------------------------------
+
+
+ "bbox",
+ [
+ "35,-25,72", # three parts: the filter used to be skipped
+ "35;-25;72;45", # semicolons
+ "35,-25,72,45,9", # five parts
+ "a,b,c,d", # used to raise a bare ValueError
+ "nan,-25,72,45",
+ "35,-25,inf,45",
+ "-91,-25,72,45", # latitude out of range
+ "35,-25,72,181", # longitude out of range
+ "72,-25,35,45", # lamin above lamax
+ "35,45,72,-25", # lomin above lomax (crosses the antimeridian)
+ "35,-25,35,45", # empty latitude span
+ ],
+)
+async def test_malformed_bbox_is_an_error_and_fetches_nothing(
+ fetcher: Fetcher, bbox: str
+) -> None:
+ adsblol = respx.get(url__regex=_ADSBLOL).mock(
+ return_value=httpx.Response(200, json=_ADSBLOL_BODY)
+ )
+ opensky = respx.get(url__regex=_OPENSKY).mock(return_value=httpx.Response(500))
+
+ result = await military.fetch_military_flights(fetcher, bbox=bbox)
+
+ assert result["reason"] == "invalid_bbox"
+ assert result["error"].startswith(f"invalid bbox {bbox!r}: expected lamin,lomin,lamax,lomax")
+ assert result["aircraft"] == []
+ assert result["source"] == "none"
+ assert not adsblol.called
+ assert not opensky.called
+
+
+async def test_bbox_with_spaces_and_decimals_is_read(fetcher: Fetcher, monkeypatch) -> None:
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ respx.get(url__regex=_ADSBLOL).mock(return_value=httpx.Response(500))
+ opensky = respx.get(url__regex=_OPENSKY).mock(
+ return_value=httpx.Response(200, json={"states": []})
+ )
+
+ result = await military.fetch_military_flights(fetcher, bbox=" 35.25, -25, 72, 45.5 ")
+
+ assert result["source"] == "opensky"
+ params = opensky.calls.last.request.url.params
+ assert (params["lamin"], params["lomin"], params["lamax"], params["lomax"]) == (
+ "35.25", "-25", "72", "45.5"
+ )
+
+
+def test_bbox_schema_pattern_matches_the_validator() -> None:
+ tool = next(t for t in conflict.TOOLS if t.name == "intel_military_flights")
+ pattern = re.compile(tool.inputSchema["properties"]["bbox"]["pattern"])
+ assert pattern.match("35,-25,72,45")
+ assert pattern.match("-10.5, 95, 55, 155")
+ for bad in ("35,-25,72", "35;-25;72;45", "a,b,c,d", "35,-25,72,45,9"):
+ assert not pattern.match(bad)
+
+
+# ---------------------------------------------------------------------------
+# Behavior F2 / tests F8: the CLI posture table never prints 0 for unknown
+# ---------------------------------------------------------------------------
+
+
+def test_cli_posture_prints_unknown_theaters_and_gaps(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "cli-cache.db"))
+ monkeypatch.setenv("COLUMNS", "200")
+ monkeypatch.setattr(cli, "_fetcher", None)
+
+ async def _flights(fetcher, bbox=None):
+ name = next(n for n, info in military.THEATERS.items() if info["bbox"] == bbox)
+ if name in {"arctic", "korean_peninsula"}:
+ return {"aircraft": [], "count": 0, "source": "none",
+ "error": "No military flight source available", "degraded": True}
+ aircraft = [{"callsign": "RCH1", "origin_country": "United States"}] * (
+ 3 if name == "european" else 0
+ )
+ return {"aircraft": aircraft, "count": len(aircraft), "source": "opensky"}
+
+ monkeypatch.setattr(military, "fetch_military_flights", _flights)
+
+ result = CliRunner().invoke(cli.main, ["posture"], catch_exceptions=False)
+
+ assert result.exit_code == 0
+ out = result.output
+ assert "3 military aircraft in the theaters that answered (3 of 5; the rest are unknown)" in out
+ assert "total military aircraft" not in out
+ assert re.search(r"Arctic\s+unknown", out)
+ assert re.search(r"Korean Peninsula\s+unknown", out)
+ assert not re.search(r"Arctic\s+0\b", out)
+ assert re.search(r"Middle East\s+0\b", out)
+ assert re.search(r"European\s+3\b", out)
+ assert "Gap: neither adsb.lol nor OpenSky returned military flights for arctic, " \
+ "korean_peninsula" in " ".join(out.split())
+
+
+def test_cli_posture_complete_prints_a_plain_total(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "cli-cache.db"))
+ monkeypatch.setenv("COLUMNS", "200")
+ monkeypatch.setattr(cli, "_fetcher", None)
+ monkeypatch.setattr(
+ military,
+ "fetch_military_flights",
+ _returning({"aircraft": [], "count": 0, "source": "opensky"}),
+ )
+
+ result = CliRunner().invoke(cli.main, ["posture"], catch_exceptions=False)
+
+ assert "0 total military aircraft" in result.output
+ assert "unknown" not in result.output
+ assert "Gap:" not in result.output
+
+
+# ---------------------------------------------------------------------------
+# Behavior F3 / tests F7: an undated feed is not scored as current
+# ---------------------------------------------------------------------------
+
+
+_UNKNOWN_CURRENCY_GAP = (
+ "every waterway reads unknown, not a threat level: how current the NGA "
+ "feed is cannot be checked (feed_stale null), so naval_warnings is not "
+ "scored as today's activity"
+)
+_HEALTHY_POSTURE = {"theaters": {"european": {"count": 4, "source": "opensky"}}}
+
+
+async def test_undated_feed_reads_unknown_not_critical(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Regression: three warnings near Hormuz with no parseable issue date
+ read "critical" with status_as_of null, and the fleet scored them as
+ current with readiness_lower_bound False."""
+ _mock_nga(_hormuz_naval("SOMETIME IN OCTOBER"))
+
+ snapshot = await intelligence.fetch_vessel_snapshot(fetcher)
+
+ hormuz = _by_name(snapshot)["Strait of Hormuz"]
+ assert hormuz["status"] == "unknown"
+ assert hormuz["naval_warnings"] == 3
+ assert hormuz["status_as_of"] is None
+ assert {ww["status"] for ww in snapshot["waterways"]} == {"unknown"}
+ assert snapshot["feed_stale"] is None
+ assert snapshot["degraded"] is True
+ assert _UNKNOWN_CURRENCY_GAP in snapshot["data_gaps"]
+ assert "error" not in snapshot
+
+ html = _render_maritime(snapshot)
+ assert "UNDATED" in html
+ assert "STALE" not in html
+
+ monkeypatch.setattr(military, "fetch_theater_posture", _returning(_HEALTHY_POSTURE))
+ monkeypatch.setattr(intelligence, "fetch_military_surge", _returning({"surges": []}))
+ fleet = await fetch_fleet_report(fetcher)
+
+ assert fleet["unavailable_components"] == ["vessel_snapshot"]
+ assert fleet["readiness_lower_bound"] is True
+ assert fleet["data_gaps"][0] == (
+ "vessel_snapshot: how current its NGA feed is cannot be checked "
+ "(feed_stale null), so its waterway statuses are not scored"
+ )
+ assert f"vessel_snapshot: {_UNKNOWN_CURRENCY_GAP}" in fleet["data_gaps"]
+
+
+async def test_current_feed_is_scored_by_the_fleet(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Control: a feed dated today keeps its threat levels and its score."""
+ _mock_nga(_hormuz_naval(_stamp(datetime.now(timezone.utc) - timedelta(hours=2))))
+
+ snapshot = await intelligence.fetch_vessel_snapshot(fetcher)
+
+ assert _by_name(snapshot)["Strait of Hormuz"]["status"] == "critical"
+ assert snapshot["feed_stale"] is False
+ assert "UNDATED" not in _render_maritime(snapshot)
+
+ monkeypatch.setattr(military, "fetch_theater_posture", _returning(_HEALTHY_POSTURE))
+ monkeypatch.setattr(intelligence, "fetch_military_surge", _returning({"surges": []}))
+ fleet = await fetch_fleet_report(fetcher)
+
+ assert "unavailable_components" not in fleet
+ assert fleet["readiness_lower_bound"] is False
+
+
+# ---------------------------------------------------------------------------
+# Behavior F4 / tests F6: an empty NGA answer is not a quiet sea
+# ---------------------------------------------------------------------------
+
+
+_EMPTY_GAP = (
+ "NGA returned no active warnings (the feed normally carries hundreds), so a "
+ "quiet sea cannot be told from a feed fault and how current the list is "
+ "cannot be checked"
+)
+
+
+ "records",
+ [[], [_record(9, "P", "BUOY UNLIT.\n", "011600Z MAY 2024", cancel="031600Z MAY 2024")]],
+ ids=["empty", "only_cancelled"],
+)
+async def test_empty_nga_answer_is_degraded_and_reads_unknown(
+ fetcher: Fetcher, records: list[dict]
+) -> None:
+ _mock_nga(records)
+
+ nav = await maritime.fetch_nav_warnings(fetcher)
+
+ assert nav["count"] == 0
+ assert nav["degraded"] is True
+ assert nav["feed_stale"] is None
+ assert nav["data_gaps"] == [_EMPTY_GAP]
+ assert "error" not in nav
+
+ snapshot = await intelligence.fetch_vessel_snapshot(fetcher)
+
+ assert {ww["status"] for ww in snapshot["waterways"]} == {"unknown"}
+ assert snapshot["degraded"] is True
+ assert snapshot["data_gaps"] == [f"NGA feed: {_EMPTY_GAP}", _UNKNOWN_CURRENCY_GAP]
+
+
+async def test_empty_nga_answer_is_reused_only_briefly(fetcher: Fetcher) -> None:
+ route = _mock_nga([])
+ key = "maritime:warnings:all"
+
+ await maritime.fetch_nav_warnings(fetcher)
+ assert route.call_count == 1
+ assert fetcher.cache.get(key) == {"broadcast-warn": []}
+
+ # Within the reuse window the cached answer is served again.
+ await maritime.fetch_nav_warnings(fetcher)
+ assert route.call_count == 1
+ assert fetcher.cache.get(key) == {"broadcast-warn": []}
+
+ # Past it (the row still has most of its hour), the row is dropped and
+ # the next call fetches again.
+ conn = fetcher.cache._get_conn()
+ conn.execute(
+ "UPDATE cache SET created_at = ? WHERE key = ?",
+ (time.time() - maritime._EMPTY_ANSWER_REUSE_SECONDS - 1, key),
+ )
+ conn.commit()
+ await maritime.fetch_nav_warnings(fetcher)
+ assert route.call_count == 1
+ assert fetcher.cache.get_stale_meta(key) is None
+ await maritime.fetch_nav_warnings(fetcher)
+ assert route.call_count == 2
+
+
+async def test_a_full_nga_answer_keeps_its_hour(fetcher: Fetcher) -> None:
+ route = _mock_nga(_hormuz_naval(_stamp(datetime.now(timezone.utc) - timedelta(hours=2))))
+ key = "maritime:warnings:all"
+ await maritime.fetch_nav_warnings(fetcher)
+ conn = fetcher.cache._get_conn()
+ conn.execute(
+ "UPDATE cache SET created_at = ? WHERE key = ?",
+ (time.time() - maritime._EMPTY_ANSWER_REUSE_SECONDS - 1, key),
+ )
+ conn.commit()
+
+ result = await maritime.fetch_nav_warnings(fetcher)
+
+ assert result["count"] == 3
+ assert fetcher.cache.get(key) is not None
+ assert route.call_count == 1
+
+
+# ---------------------------------------------------------------------------
+# Behavior F8 / tests F2-F5: parser guards
+# ---------------------------------------------------------------------------
+
+
+ "text",
+ [
+ "BUOY 20-03-44-10N 072-58.00W.", # four-part latitude (lookbehind)
+ "BUOY 20-03-44-5N 072-58.00W.", # four-part latitude (lookbehind)
+ "BUOY 2O-03-44N 072-58.00W.", # letter O for the degrees' zero
+ "BUOY 20-O3-44N 072-58.00W.", # letter O inside the minutes
+ "CHART 26060-03.5N 072-58.00W.", # starts inside a chart number
+ "BUOY 20-034-44N 072-58.00W.", # three-digit minutes
+ "BUOY 20-03.5-44N 072-58.00W.", # decimal minutes followed by seconds
+ "BUOY 20-03.5-10N 072-58.00W.", # decimal minutes followed by seconds
+ "X 10-15.25-30S 120-05-07E.", # decimal minutes followed by seconds
+ ],
+)
+def test_malformed_coordinates_read_as_no_position(text: str) -> None:
+ """A malformed coordinate used to be read as a confident position about
+ 1,800 km off (20-03-44-10N as 3.74N), or made the whole feed raise
+ (decimal minutes followed by seconds)."""
+ assert maritime.extract_positions(text) == []
+
+
+def test_well_formed_mixed_pair_still_reads() -> None:
+ assert maritime.extract_positions("BUOY 20-03-44N 072-58.00W.") == [(20.0622, -72.9667)]
+
+
+ "text",
+ ["SECTOR 1234-56N.", "CHART 26060-03N.", "LIGHT 1234-56E REPORTED."],
+)
+def test_a_number_inside_a_longer_number_is_not_a_coordinate(text: str) -> None:
+ assert not maritime.mentions_position(text)
+
+
+ "text",
+ [
+ "NAVAL OPERATIONS WEST OF 080-00W.",
+ # Live 4:2024-273's letter-O typo leaves only the longitude readable.
+ "CABLE OPERATIONS IN AREA BOUND BY 22-20.OON 069-39.00W.",
+ # Mistyped: no point is read, but a position is stated.
+ "BUOY 20-O3-44N.",
+ ],
+)
+def test_a_lone_or_mistyped_coordinate_counts_as_a_stated_position(text: str) -> None:
+ assert maritime.mentions_position(text)
+
+
+async def test_meridian_only_naval_warning_is_unplaced_as_unreadable(fetcher: Fetcher) -> None:
+ _mock_nga([
+ _record(
+ 7, "4", "CARIBBEAN SEA.\nNAVAL OPERATIONS WEST OF 080-00W.\n",
+ _stamp(datetime.now(timezone.utc) - timedelta(hours=2)),
+ )
+ ])
+
+ result = await intelligence.fetch_vessel_snapshot(fetcher)
+
+ assert [
+ (w["navarea"], w["id"], w["reason"]) for w in result["unplaced_naval_warnings"]
+ ] == [("4", "2026-7", "position_unreadable")]
diff --git a/src/world_intel_mcp/tools/conflict.py b/src/world_intel_mcp/tools/conflict.py
index 6e73c69..7f1b0bc 100644
--- a/src/world_intel_mcp/tools/conflict.py
+++ b/src/world_intel_mcp/tools/conflict.py
@@ -79,7 +79,14 @@ TOOLS: list[Tool] = [
"properties": {
"bbox": {
"type": "string",
- "description": "Bounding box: lamin,lomin,lamax,lomax",
+ "pattern": r"^\s*-?\d+(\.\d+)?\s*(,\s*-?\d+(\.\d+)?\s*){3}$",
+ "description": (
+ "Bounding box: lamin,lomin,lamax,lomax, four comma-separated "
+ "numbers with latitudes -90..90, longitudes -180..180 and each "
+ "minimum below its maximum (split a box that crosses the "
+ "antimeridian in two). Anything else returns error "
+ "invalid_bbox."
+ ),
},
},
},
diff --git a/src/world_intel_mcp/tools/intelligence.py b/src/world_intel_mcp/tools/intelligence.py
index 574599f..8aac98e 100644
--- a/src/world_intel_mcp/tools/intelligence.py
+++ b/src/world_intel_mcp/tools/intelligence.py
@@ -146,7 +146,7 @@ TOOLS: list[Tool] = [
),
Tool(
name="intel_vessel_snapshot",
- description="Naval activity snapshot at 9 strategic waterways (Hormuz, Malacca, Suez, etc.) from NGA navigational warnings. A warning counts at a waterway only when a position it states lies within 300 km; naval warnings with no readable position are listed as unplaced. Each waterway scored clear/advisory/elevated/critical, stale when the feed's newest warning is past the staleness threshold (status_as_of gives the feed's date), or unknown when the feed is down.",
+ description="Naval activity snapshot at 9 strategic waterways (Hormuz, Malacca, Suez, etc.) from NGA navigational warnings. A warning counts at a waterway only when a position it states lies within 300 km; naval warnings with no readable position are listed as unplaced. Each waterway scored clear/advisory/elevated/critical, stale when the feed's newest warning is past the staleness threshold (status_as_of gives the feed's date), or unknown when the feed is down, empty or carries no usable issue date (feed_stale null).",
inputSchema={"type": "object", "properties": {}},
),
Tool(