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: place naval warnings, mark outages and a frozen feed

Phoenix Agent (mac-studio)63791933ffb6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6311734..e032647 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,59 @@
# Changelog
+## Unreleased
+
+### Fixed: vessel snapshot waterway matching
+- `intel_vessel_snapshot` counted every NGA warning at all nine waterways,
+ so three naval-keyword warnings anywhere on Earth marked Panama and
+ Hormuz critical alike. On the live feed of 2026-10-17 the old code marked
+ all nine `critical` from 8 such warnings, none within 300 km of any of
+ them. A warning now counts only at waterways within 300 km of a position
+ it states (degrees-minutes or degrees-minutes-seconds). A warning that
+ states no position counts by NAVAREA only when its area code names a
+ single NAVAREA (4 is NAVAREA IV, 12 is NAVAREA XII, which of the nine
+ contain only the Panama Canal). HYDROLANT, HYDROPAC and HYDROARC each
+ span several NAVAREAs, so a positionless naval warning in those series,
+ or one whose only stated position is malformed, is listed in
+ `unplaced_naval_warnings` and named in `data_gaps`. The response states
+ the rule in `matching_rule`.
+- Each waterway emits `total_nearby` (warnings of any topic credited to
+ it, which the old code computed and dropped), split by how they matched
+ in `nearby_by_match` and `naval_by_match`; `warning_details` entries
+ carry `match`, `distance_km` and `issue_date`.
+- With NGA down every waterway read `clear`. It now reads `unknown`, and
+ the response carries `error`, `degraded` and `reason`.
+
+### Fixed: navigational warnings
+- An NGA outage returned `warnings: []` with no marker, the same shape as a
+ sea with no active warnings. It now carries `error`, `degraded`,
+ `reason` (`nga_msi_fetch_failed`) and `data_gaps`. A payload with no
+ warnings list is `nga_msi_unexpected_payload`; a stale cache serve is
+ degraded and says how old the copy is.
+- The NGA MSI API holds no warning issued after 10 May 2024 (measured
+ 2026-10-17: `msgYear=2025` with `status=all` and `msgYear=2026` return
+ none, `msgYear=2024` with `status=all` ends on 10 May, and
+ `/current-warnings` and `/inforce` list the same 2024 state), yet
+ responses read as current. `intel_nav_warnings` now reports
+ `newest_issue_date` and `newest_issue_age_days`; past `stale_after_days`
+ (14, twice the slowest series' longest gap between issues in 2024) the
+ response is degraded with the age in `data_gaps`. The vessel snapshot and
+ fleet report pass this on.
+- `area_codes` maps the codes the API sends in `navArea` (4, 12, A, P, C;
+ never the Roman numerals) to the NAVAREAs, with each code's source in
+ `sources/maritime.py`.
+
+### Fixed: fleet report
+- `intel_fleet_report` turned a failed component into `{}`, so with all
+ three down it read `LOW_ACTIVITY` with no marker. A component that raises
+ or reports an error is now named in `unavailable_components` and
+ `data_gaps` and the report is degraded; with all three down it also
+ carries `error` and `reason` (`fleet_components_unavailable`). Component
+ `data_gaps` are passed on.
+
+### Tests
+- Failing-first regression tests for all three, built on live NGA records
+ captured 2026-10-17.
+
## 0.11.0 - 2026-10-12
Cross-border migration (MCP tools, CLI, collector and a dashboard
diff --git a/ROADMAP.md b/ROADMAP.md
index 4f03400..815ed53 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -598,10 +598,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 | :red_circle: |
+| 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 it states, or, when it states none, by single-NAVAREA area code (4, 12); the rule is in `matching_rule`, naval warnings no rule can place are in `unplaced_naval_warnings`; `total_nearby` emitted; an NGA outage reads `unknown`, not `clear` |
| 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 | silent degradation | :red_circle: |
+| 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 | silent degradation | :yellow_circle: `maritime.py` and `fleet.py` fixed (Unreleased): outages carry `error`/`degraded`/`reason` and `data_gaps`, failed fleet components are named in `unavailable_components`, and nav warnings flag a feed whose newest warning is over 14 days old (NGA's API holds nothing issued after 10 May 2024, measured 2026-10-17). `prediction.py` and `news.py` are not covered by this change |
| 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) |
| Remote data inside Rich TABLE cells was not markup-escaped | `cli.py` | output corruption | :white_check_mark: Fixed in 0.6.0 (`_cell` Text-wrapping convention, 11 injection tests; error styles unified across all 53 commands) |
diff --git a/src/world_intel_mcp/sources/fleet.py b/src/world_intel_mcp/sources/fleet.py
index ff2de16..73cc96c 100644
--- a/src/world_intel_mcp/sources/fleet.py
+++ b/src/world_intel_mcp/sources/fleet.py
@@ -15,11 +15,32 @@ logger = logging.getLogger("world-intel-mcp.sources.fleet")
async def _safe(coro, label: str) -> dict:
+ """Await one report component; a raise or a non-dict result comes back
+ as an error dict (error / degraded / reason), never as an empty one.
+
+ This used to return {}, which made a component that raised read exactly
+ like one that found nothing: with all three down, the report scored
+ LOW_ACTIVITY with no sign that it had no data.
+ """
try:
- return await coro
+ result = await coro
except Exception as exc:
logger.warning("Fleet report: %s failed: %s", label, exc)
- return {}
+ return {
+ "error": f"{type(exc).__name__}: {exc}"[:200],
+ "degraded": True,
+ "reason": "component_raised",
+ }
+ if not isinstance(result, dict):
+ logger.warning(
+ "Fleet report: %s returned %s, not a dict", label, type(result).__name__
+ )
+ return {
+ "error": f"returned {type(result).__name__}, not a dict",
+ "degraded": True,
+ "reason": "component_bad_shape",
+ }
+ return result
def _fleet_readiness(theaters: dict, waterways: list, surges: list) -> tuple[str, int]:
@@ -66,6 +87,12 @@ async def fetch_fleet_report(fetcher) -> dict:
- Vessel snapshot (9 strategic waterways, naval status)
- Military surge detections (anomalous foreign aircraft concentration)
- Naval bases (filtered from static dataset)
+
+ A component that raised or reported an error is named in
+ unavailable_components and data_gaps, and the report is degraded; the
+ readiness score is then computed without it. With all three down the
+ report carries error / reason, so an outage never reads as
+ LOW_ACTIVITY. data_gaps also carries each component's own gaps.
"""
from . import intelligence, military, geospatial
@@ -83,6 +110,25 @@ async def fetch_fleet_report(fetcher) -> dict:
naval_bases = await geospatial.fetch_military_bases(base_type="naval_base")
naval_base_count = naval_bases.get("count", 0)
+ components = {
+ "military_surge": surge_data,
+ "theater_posture": posture_data,
+ "vessel_snapshot": vessel_data,
+ }
+ unavailable = [name for name, data in components.items() if data.get("error")]
+ data_gaps: list[str] = []
+ for name, data in components.items():
+ if data.get("error"):
+ data_gaps.append(
+ f"{name}: unavailable ({data['error']}); readiness_score is "
+ "computed without it"
+ )
+ continue
+ gaps = data.get("data_gaps") or []
+ data_gaps.extend(f"{name}: {gap}" for gap in gaps)
+ if data.get("degraded") and not gaps:
+ data_gaps.append(f"{name}: degraded")
+
# Extract key data
theaters = posture_data.get("theaters", {})
if not isinstance(theaters, dict):
@@ -133,7 +179,7 @@ async def fetch_fleet_report(fetcher) -> dict:
}
)
- return {
+ response = {
"readiness_level": readiness_level,
"readiness_score": readiness_score,
"theater_summary": theater_summary,
@@ -146,6 +192,20 @@ async def fetch_fleet_report(fetcher) -> dict:
"total_tracked_aircraft": sum(
t.get("count", 0) for t in theaters.values() if isinstance(t, dict)
),
+ "data_gaps": data_gaps,
"source": "fleet-activity-report",
"timestamp": datetime.now(timezone.utc).isoformat(),
}
+ if unavailable:
+ # The zeroed fields above stay for consumers that read them;
+ # these say which inputs they lack.
+ response["unavailable_components"] = unavailable
+ response["degraded"] = True
+ if len(unavailable) == len(components):
+ response["error"] = "All fleet report components unavailable: " + ", ".join(
+ unavailable
+ )
+ response["reason"] = "fleet_components_unavailable"
+ elif any(data.get("degraded") for data in components.values()):
+ response["degraded"] = True
+ return response
diff --git a/src/world_intel_mcp/sources/intelligence.py b/src/world_intel_mcp/sources/intelligence.py
index 4263e7d..a7a4834 100644
--- a/src/world_intel_mcp/sources/intelligence.py
+++ b/src/world_intel_mcp/sources/intelligence.py
@@ -1542,13 +1542,54 @@ _NAVAL_KEYWORDS = re.compile(
re.IGNORECASE,
)
+# A warning concerns a waterway when a position stated in its text lies
+# within this distance of the waterway's reference point in
+# STRATEGIC_WATERWAYS. 300 km is a chosen radius, not a measured boundary:
+# it spans each canal end to end and a strait's approaches, but one point
+# models the long GIUK Gap and Strait of Malacca only near that point.
+_WATERWAY_PROXIMITY_KM = 300.0
+
+# NAVAREAs a waterway lies in, used only for warnings that state no
+# position. Only areas the NGA feed emits as single-NAVAREA codes can place
+# such a warning (code 4 is NAVAREA IV, code 12 is NAVAREA XII; see
+# maritime.NGA_AREA_CODES), and of the nine waterways only the Panama Canal
+# lies in either. NGA's own limits (IHO WWNWS13/3/2/IV-XII, 27 July 2021)
+# run the IV/XII boundary across the isthmus between 09-08-41N 078-44-03W
+# and 08-21-53N 081-39-33W, so the canal's Caribbean end is in IV and its
+# Pacific end in XII. IV lies west of 035W in the Atlantic and XII between
+# the Americas and the date line, so the other eight waterways are in
+# neither.
+_WATERWAY_NAVAREAS: dict[str, tuple[str, ...]] = {
+ "Panama Canal": ("IV", "XII"),
+}
+
+_VESSEL_MATCHING_RULE = (
+ "A warning is credited to a waterway when any position stated in its "
+ "text lies within proximity_km of the waterway's reference point. A "
+ "warning that states no position is credited by NAVAREA only when its "
+ "area code names a single NAVAREA (4 is NAVAREA IV, 12 is NAVAREA XII) "
+ "that contains the waterway (waterway_navareas). HYDROLANT (A), HYDROPAC "
+ "(P) and HYDROARC (C) each span several NAVAREAs (area_codes), so a "
+ "positionless warning in those series is credited to no waterway, nor "
+ "is one whose only stated positions are malformed; naval ones are "
+ "listed in unplaced_naval_warnings. status counts the naval-keyword "
+ "warnings credited to the waterway; total_nearby counts credited "
+ "warnings of any topic, split by match in nearby_by_match."
+)
+
async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:
"""Naval activity snapshot at strategic waterways using NGA warnings.
- Uses NGA MSI (existing fetch_nav_warnings) filtered for naval/vessel
- keywords near STRATEGIC_WATERWAYS from config.
- Scores each waterway: clear/advisory/elevated/critical.
+ Uses NGA MSI (maritime.fetch_nav_warnings) filtered for naval/vessel
+ keywords. Each warning is credited only to the STRATEGIC_WATERWAYS it
+ concerns: a stated position within _WATERWAY_PROXIMITY_KM, or, for a
+ warning that states no position, a single-NAVAREA area code that
+ contains the waterway. The response states the rule (matching_rule).
+ Before 2026-10-17 every warning counted at all nine waterways, so three
+ naval warnings anywhere on Earth marked Panama and Hormuz critical alike.
+ Scores each waterway: clear/advisory/elevated/critical, or unknown when
+ the warning feed itself is unavailable.
Note: Real-time AIS requires paid API. This uses NGA MSI as a
free proxy for naval activity indicators.
@@ -1557,44 +1598,101 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:
fetcher: Shared HTTP fetcher with caching and circuit breaking.
Returns:
- Dict with waterways list, source, and timestamp.
+ Dict with waterways list (each with total_nearby, the warnings of
+ any topic credited to it, and how each was matched), the matching
+ rule, naval warnings no rule could place, the feed's newest issue
+ date, data_gaps, source, and timestamp.
"""
now = datetime.now(timezone.utc)
from . import maritime
nav_data = await maritime.fetch_nav_warnings(fetcher)
- all_warnings = nav_data.get("warnings", [])
+ all_warnings = nav_data.get("warnings", []) or []
+ feed_error = nav_data.get("error")
- waterways: list[dict] = []
+ credited: dict[str, dict] = {
+ ww["name"]: {"naval": [], "nearby": {"proximity": 0, "navarea": 0}}
+ for ww in STRATEGIC_WATERWAYS
+ }
+ unplaced_naval: list[dict] = []
+ naval_total = 0
+ truncated = 0
+
+ for warning in all_warnings:
+ text = warning.get("text") or ""
+ is_naval = bool(_NAVAL_KEYWORDS.search(text))
+ naval_total += is_naval
+ if len(text) > maritime._MAX_TEXT_LENGTH and text.endswith("..."):
+ truncated += 1
+ positions = maritime.extract_positions(text)
+
+ matches: list[tuple[str, str, float | None]] = []
+ if positions:
+ for ww in STRATEGIC_WATERWAYS:
+ distance = min(
+ _haversine_km(ww["lat"], ww["lon"], lat, lon)
+ for lat, lon in positions
+ )
+ if distance <= _WATERWAY_PROXIMITY_KM:
+ matches.append((ww["name"], "proximity", round(distance, 1)))
+ else:
+ area = maritime.NGA_AREA_CODES.get(str(warning.get("navarea") or "").upper())
+ unplaced_reason = None
+ if maritime.mentions_position(text):
+ # Its only stated positions are malformed; crediting it by
+ # NAVAREA would place it at a waterway it does not concern.
+ unplaced_reason = "position_unreadable"
+ elif area is None:
+ unplaced_reason = "unknown_area_code"
+ elif not area["single_navarea"]:
+ unplaced_reason = "multi_navarea_series"
+ else:
+ navarea = area["navareas"][0]
+ for ww in STRATEGIC_WATERWAYS:
+ if navarea in _WATERWAY_NAVAREAS.get(ww["name"], ()):
+ matches.append((ww["name"], "navarea", None))
+ if unplaced_reason and is_naval:
+ unplaced_naval.append(
+ {
+ "id": warning.get("id"),
+ "navarea": warning.get("navarea"),
+ "series": area["series"] if area else None,
+ "issue_date": warning.get("issue_date"),
+ "reason": unplaced_reason,
+ "text_snippet": text[:200],
+ }
+ )
- for ww in STRATEGIC_WATERWAYS:
- ww_lat = ww["lat"]
- ww_lon = ww["lon"]
-
- naval_warnings: list[dict] = []
- total_nearby = 0
-
- for warning in all_warnings:
- text = warning.get("text", "")
- # Simple proximity: check if warning text mentions coordinates
- # near the waterway (NGA warnings have lat/lon in text parsed elsewhere)
- # Use navarea as rough filter and keyword matching
- if _NAVAL_KEYWORDS.search(text):
- naval_warnings.append(
+ for name, basis, distance in matches:
+ entry = credited[name]
+ entry["nearby"][basis] += 1
+ if is_naval:
+ entry["naval"].append(
{
"id": warning.get("id"),
"text_snippet": text[:200],
"navarea": warning.get("navarea"),
+ "issue_date": warning.get("issue_date"),
+ "match": basis,
+ "distance_km": distance,
}
)
- # Count all warnings in the general vicinity (any topic)
- total_nearby += 1
+ waterways: list[dict] = []
+ for ww in STRATEGIC_WATERWAYS:
+ entry = credited[ww["name"]]
+ # Nearest stated positions first, then NAVAREA-only matches.
+ naval_warnings = sorted(
+ entry["naval"],
+ key=lambda d: (d["match"] != "proximity", d["distance_km"] or 0.0),
+ )
naval_count = len(naval_warnings)
- if naval_count >= 3:
+ if feed_error:
+ status = "unknown"
+ elif naval_count >= 3:
status = "critical"
elif naval_count >= 2:
status = "elevated"
@@ -1606,22 +1704,64 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:
waterways.append(
{
"name": ww["name"],
- "lat": ww_lat,
- "lon": ww_lon,
+ "lat": ww["lat"],
+ "lon": ww["lon"],
"throughput": ww.get("throughput"),
"naval_warnings": naval_count,
"status": status,
"warning_details": naval_warnings[:5],
+ "total_nearby": sum(entry["nearby"].values()),
+ "nearby_by_match": dict(entry["nearby"]),
+ "naval_by_match": {
+ basis: sum(1 for d in naval_warnings if d["match"] == basis)
+ for basis in ("proximity", "navarea")
+ },
}
)
- return {
+ 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 unplaced_naval:
+ data_gaps.append(
+ f"{len(unplaced_naval)} naval warning(s) state no readable position "
+ "and no single-NAVAREA area code, so no waterway is credited with "
+ "them (unplaced_naval_warnings): "
+ + ", ".join(f"{w['id']} ({w['reason']})" for w in unplaced_naval)
+ )
+ if truncated:
+ data_gaps.append(
+ f"{truncated} warning text(s) were cut at {maritime._MAX_TEXT_LENGTH} "
+ "characters; positions after the cut are not read"
+ )
+
+ response = {
"waterways": waterways,
"count": len(waterways),
"total_nav_warnings": len(all_warnings),
+ "total_naval_warnings": naval_total,
+ "unplaced_naval_warnings": unplaced_naval,
+ "matching_rule": {
+ "proximity_km": _WATERWAY_PROXIMITY_KM,
+ "rule": _VESSEL_MATCHING_RULE,
+ "waterway_navareas": {k: list(v) for k, v in _WATERWAY_NAVAREAS.items()},
+ "area_codes": maritime.area_codes_view(),
+ },
+ "newest_issue_date": nav_data.get("newest_issue_date"),
+ "newest_issue_age_days": nav_data.get("newest_issue_age_days"),
+ "stale_after_days": nav_data.get("stale_after_days"),
+ "data_gaps": data_gaps,
"source": "nga-msi-vessel-snapshot",
"timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
}
+ if feed_error:
+ # Every waterway used to read "clear" when NGA was down.
+ 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"):
+ response["degraded"] = True
+ return response
# ---------------------------------------------------------------------------
diff --git a/src/world_intel_mcp/sources/maritime.py b/src/world_intel_mcp/sources/maritime.py
index 106e0f5..2b99091 100644
--- a/src/world_intel_mcp/sources/maritime.py
+++ b/src/world_intel_mcp/sources/maritime.py
@@ -38,6 +38,71 @@ NAVAREAS = {
"XVI": "Peru (E Pacific)",
}
+# Area codes the NGA MSI API puts in each warning's navArea field, mapped to
+# the NAVAREAS keys above. The API never sends the Roman numerals: each of
+# the 386 active warnings in a 2026-10-17 capture carried one of these five
+# codes, the set the API's own GET /api/publications/broadcast-warn/navareas
+# lists ({"NAVAREA IV": "4", "HYDROLANT": "A", "NAVAREA XII": "12",
+# "HYDROPAC": "P", "HYDROARC": "C"}). Where each code's areas come from:
+# 4, 12 that endpoint names them NAVAREA IV and NAVAREA XII: one area
+# each, so single_navarea is True.
+# A, P, C NGA's HYDROLANT, HYDROPAC and HYDROARC series, which rebroadcast
+# other coordinators' warnings (Federal Register 2018-10215: the
+# Atlantic edition carries HYDROLANT, the Pacific edition
+# HYDROPAC, and HYDROARC covers the Arctic the other two leave
+# out). A series lists a NAVAREA when at least one of its warnings
+# names that NAVAREA's coordinator in its authority field, in the
+# 2026-10-17 capture or in the 3,480 warnings of msgYear=2024
+# status=all (e.g. HYDROPAC "NAVAREA IX 483/22" on a PERSIAN GULF
+# warning, HYDROLANT "NAVAREA III 118/22" on a BLACK SEA one).
+# IV and XII are NGA's own areas, whose warnings name no
+# coordinator; they sit under A and P because those series carry
+# GULF OF MEXICO and CARIBBEAN, and EASTERN NORTH PACIFIC,
+# warnings. Most HYDROARC coordinators are the Arctic NAVAREAs
+# XVII-XXI, which NAVAREAS does not define (unlisted_navareas).
+# NAVAREAS labels XIII "Russia (Arctic)", but the feed carries
+# NAVAREA XIII warnings for the Sea of Okhotsk and the Sea of
+# Japan under HYDROPAC, so XIII sits under P.
+NGA_AREA_CODES: dict[str, dict] = {
+ "4": {
+ "series": "NAVAREA IV",
+ "navareas": ("IV",),
+ "unlisted_navareas": (),
+ "single_navarea": True,
+ },
+ "12": {
+ "series": "NAVAREA XII",
+ "navareas": ("XII",),
+ "unlisted_navareas": (),
+ "single_navarea": True,
+ },
+ "A": {
+ "series": "HYDROLANT",
+ "navareas": ("I", "II", "III", "IV", "V", "VI", "VII", "XV"),
+ "unlisted_navareas": (),
+ "single_navarea": False,
+ },
+ "P": {
+ "series": "HYDROPAC",
+ "navareas": ("VII", "VIII", "IX", "X", "XI", "XII", "XIII", "XIV", "XV", "XVI"),
+ "unlisted_navareas": (),
+ "single_navarea": False,
+ },
+ "C": {
+ "series": "HYDROARC",
+ "navareas": ("I",),
+ "unlisted_navareas": ("XVII", "XVIII", "XIX", "XX", "XXI"),
+ "single_navarea": False,
+ },
+}
+
+# A response whose newest active warning is older than this is flagged as
+# stale. Measured on the live API (msgYear=2024, status=all: 3,480 warnings
+# issued 1 Jan to 10 May 2024): consecutive issues were never more than 0.42
+# days apart across all series, or more than 7.0 days apart within one series
+# (HYDROARC, the slowest), so 14 days is twice the slowest series' worst gap.
+STALE_AFTER_DAYS = 14
+
_MAX_TEXT_LENGTH = 500
@@ -45,10 +110,6 @@ _MAX_TEXT_LENGTH = 500
# Helpers
# ---------------------------------------------------------------------------
-def _utc_now_iso() -> str:
- return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
-
-
def _is_active(warning: dict) -> bool:
"""Return True if the warning has no cancelDate (i.e. still active)."""
cancel = warning.get("cancelDate")
@@ -78,6 +139,121 @@ def _extract_coords(text: str) -> tuple[float | None, float | None]:
return round(lat, 4), round(lon, 4)
+# Degrees-minutes-seconds positions ('20-03-44N 072-58-02W'), which NGA uses
+# in some light and buoy warnings. _COORD_RE never matches them: it needs a
+# hemisphere letter straight after the minutes.
+_COORD_DMS_RE = re.compile(
+ r"(\d{1,3})-(\d{1,2})-(\d{1,2}(?:\.\d+)?)\s*([NS])\s+"
+ r"(\d{1,3})-(\d{1,2})-(\d{1,2}(?:\.\d+)?)\s*([EW])",
+)
+
+
+def extract_positions(text: str) -> list[tuple[float, float]]:
+ """Every lat/lon position stated in NGA warning text, in text order.
+
+ Reads degrees-minutes ('22-16.65N 097-44.48W') and
+ degrees-minutes-seconds ('20-03-44N 072-58-02W'). A pair with minutes
+ or seconds of 60 or more, a latitude past 90 or a longitude past 180 is
+ skipped as malformed rather than guessed at.
+ """
+ found: list[tuple[int, float, float]] = []
+ for m in _COORD_RE.finditer(text):
+ lat_min, lon_min = float(m.group(2)), float(m.group(5))
+ if lat_min >= 60 or lon_min >= 60:
+ continue
+ lat = int(m.group(1)) + lat_min / 60
+ lon = int(m.group(4)) + lon_min / 60
+ found.append(
+ (m.start(), -lat if m.group(3) == "S" else lat, -lon if m.group(6) == "W" else lon)
+ )
+ for m in _COORD_DMS_RE.finditer(text):
+ lat_m, lat_s = int(m.group(2)), float(m.group(3))
+ lon_m, lon_s = int(m.group(6)), float(m.group(7))
+ if max(lat_m, lat_s, lon_m, lon_s) >= 60:
+ continue
+ lat = int(m.group(1)) + lat_m / 60 + lat_s / 3600
+ lon = int(m.group(5)) + lon_m / 60 + lon_s / 3600
+ found.append(
+ (m.start(), -lat if m.group(4) == "S" else lat, -lon if m.group(8) == "W" else lon)
+ )
+ found.sort()
+ return [
+ (round(lat, 4), round(lon, 4))
+ for _, lat, lon in found
+ if abs(lat) <= 90 and abs(lon) <= 180
+ ]
+
+
+def mentions_position(text: str) -> bool:
+ """True when the text holds a lat/lon pair in either notation, readable
+ or not, so a warning whose only stated position is malformed (a live
+ 2023 HYDROPAC text gives '10-52.0N 154-84.0W') is not mistaken for one
+ that states no position at all."""
+ return bool(_COORD_RE.search(text) or _COORD_DMS_RE.search(text))
+
+
+_ISSUE_DATE_RE = re.compile(r"^(\d{2})(\d{2})(\d{2})Z\s+([A-Z]{3})\s+(\d{4})$")
+_MONTHS = {
+ "JAN": 1, "FEB": 2, "MAR": 3, "APR": 4, "MAY": 5, "JUN": 6,
+ "JUL": 7, "AUG": 8, "SEP": 9, "OCT": 10, "NOV": 11, "DEC": 12,
+}
+
+
+def _parse_issue_date(value: object) -> datetime | None:
+ """Parse an NGA issue date ('101515Z MAY 2024': day, hour, minute,
+ Zulu, month, year) or an ISO 8601 string. None when unparseable.
+
+ The month table is fixed English, not strptime's locale-dependent %b.
+ """
+ if not isinstance(value, str) or not value.strip():
+ return None
+ m = _ISSUE_DATE_RE.match(value.strip().upper())
+ if m:
+ day, hour, minute, month_name, year = m.groups()
+ month = _MONTHS.get(month_name)
+ if month is None:
+ return None
+ try:
+ return datetime(
+ int(year), month, int(day), int(hour), int(minute), tzinfo=timezone.utc
+ )
+ except ValueError:
+ return None
+ try:
+ parsed = datetime.fromisoformat(value.strip().replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if parsed.tzinfo is None:
+ parsed = parsed.replace(tzinfo=timezone.utc)
+ return parsed.astimezone(timezone.utc)
+
+
+def _freshness(warnings: list[dict], now: datetime) -> tuple[str | None, float | None]:
+ """(newest issue date as ISO 8601, its age in days) over the warnings
+ whose issue date parses; (None, None) when none does."""
+ dates = [
+ d for d in (_parse_issue_date(w.get("issue_date")) for w in warnings) if d
+ ]
+ if not dates:
+ return None, None
+ newest = max(dates)
+ age_days = (now - newest).total_seconds() / 86400
+ return newest.strftime("%Y-%m-%dT%H:%M:%SZ"), round(age_days, 1)
+
+
+def area_codes_view() -> dict[str, dict]:
+ """NGA_AREA_CODES as plain JSON (lists, not tuples) for responses."""
+ return {
+ code: {
+ "series": entry["series"],
+ "navareas": list(entry["navareas"]),
+ "unlisted_navareas": list(entry["unlisted_navareas"]),
+ "single_navarea": entry["single_navarea"],
+ }
+ for code, entry in NGA_AREA_CODES.items()
+ }
+
+
def _parse_warning(warning: dict) -> dict:
"""Extract structured fields from a single NGA broadcast warning."""
msg_year = warning.get("msgYear", "")
@@ -123,7 +299,12 @@ async def fetch_nav_warnings(
Returns:
Dict with warnings list, count, per-navarea breakdown, NAVAREA
- definitions, source, and timestamp.
+ definitions, the NGA area-code table (area_codes), the newest
+ warning's issue date and age in days, data_gaps, source, and
+ timestamp. A failed fetch or an unrecognized payload carries
+ error / degraded / reason, so an outage never reads as a quiet sea;
+ a response whose newest warning is older than STALE_AFTER_DAYS is
+ degraded, with the age named in data_gaps.
"""
cache_label = navarea.upper() if navarea else "all"
cache_key = f"maritime:warnings:{cache_label}"
@@ -135,28 +316,74 @@ async def fetch_nav_warnings(
cache_ttl=3600,
)
- now_iso = _utc_now_iso()
+ now = datetime.now(timezone.utc)
+ response: dict = {
+ "warnings": [],
+ "count": 0,
+ "by_navarea": {},
+ "navareas": NAVAREAS,
+ "area_codes": area_codes_view(),
+ "newest_issue_date": None,
+ "newest_issue_age_days": None,
+ "stale_after_days": STALE_AFTER_DAYS,
+ "data_gaps": [],
+ "source": "nga-msi",
+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
+ }
if data is None:
logger.warning("NGA MSI API returned no data")
- return {
- "warnings": [],
- "count": 0,
- "by_navarea": {},
- "navareas": NAVAREAS,
- "source": "nga-msi",
- "timestamp": now_iso,
- }
+ # Honest outage shape. Without these markers this return was
+ # shape-identical to a sea with no active warnings (the
+ # silent-degradation class). The zeroed fields stay for consumers
+ # that read them directly; error / degraded / reason say NGA is
+ # down, and cli.py's bail path, the dashboard and the collector all
+ # key on "error".
+ response.update(
+ error="NGA MSI API unavailable (no live or cached data)",
+ degraded=True,
+ reason="nga_msi_fetch_failed",
+ )
+ response["data_gaps"].append(
+ "NGA MSI broadcast warnings unavailable (no live or cached data): "
+ "zero warnings here means unknown, not a quiet sea"
+ )
+ return response
# The API returns either a list directly or a dict with a data key
+ raw_warnings: object = None
if isinstance(data, list):
raw_warnings = data
elif isinstance(data, dict):
- raw_warnings = data.get("broadcast-warn", data.get("data", []))
+ raw_warnings = data.get("broadcast-warn", data.get("data"))
if isinstance(raw_warnings, dict):
raw_warnings = [raw_warnings]
- else:
- raw_warnings = []
+ if not isinstance(raw_warnings, list):
+ # A payload with no warnings list used to read as zero warnings.
+ if isinstance(data, dict):
+ shape = f"keys: {sorted(str(k) for k in data)[:5]}"
+ else:
+ shape = f"type: {type(data).__name__}"
+ logger.warning("NGA MSI payload had no warnings list (%s)", shape)
+ response.update(
+ error=f"NGA MSI returned an unrecognized payload ({shape})",
+ degraded=True,
+ reason="nga_msi_unexpected_payload",
+ )
+ response["data_gaps"].append(
+ "NGA MSI payload carried no 'broadcast-warn' or 'data' list, so the "
+ "active warnings are unknown"
+ )
+ return response
+
+ if isinstance(data, dict) and data.get("_stale"):
+ # The fetcher fell back to its last cached copy after a failed
+ # fetch; say so instead of passing old data off as a fresh read.
+ response["degraded"] = True
+ response["data_gaps"].append(
+ "NGA MSI fetch failed; serving a cached copy "
+ f"{data.get('_stale_age_seconds')} s old"
+ )
# Filter to active warnings only
active_raw = [w for w in raw_warnings if _is_active(w)]
@@ -184,11 +411,28 @@ async def fetch_nav_warnings(
na = w.get("navarea", "UNKNOWN")
by_navarea[na] = by_navarea.get(na, 0) + 1
- return {
- "warnings": warnings,
- "count": len(warnings),
- "by_navarea": by_navarea,
- "navareas": NAVAREAS,
- "source": "nga-msi",
- "timestamp": now_iso,
- }
+ newest, age_days = _freshness(warnings, now)
+ response.update(
+ warnings=warnings,
+ count=len(warnings),
+ by_navarea=by_navarea,
+ newest_issue_date=newest,
+ newest_issue_age_days=age_days,
+ )
+ if warnings and newest is None:
+ response["degraded"] = True
+ response["data_gaps"].append(
+ "no warning carries a parseable issue date, so how current this "
+ "list is cannot be checked"
+ )
+ elif age_days is not None and age_days > STALE_AFTER_DAYS:
+ # Measured 2026-10-17: the live API's newest warning was issued
+ # 10 May 2024 and it holds none from 2025 or 2026 (status=all),
+ # yet this response looked current. Name the age instead.
+ response["degraded"] = True
+ response["data_gaps"].append(
+ f"newest active warning was issued {newest}, {age_days:.0f} days "
+ f"ago, past the {STALE_AFTER_DAYS}-day staleness threshold: these "
+ "are historical warnings, not current conditions"
+ )
+ return response
diff --git a/src/world_intel_mcp/tests/test_sources_fleet.py b/src/world_intel_mcp/tests/test_sources_fleet.py
index c475250..248299c 100644
--- a/src/world_intel_mcp/tests/test_sources_fleet.py
+++ b/src/world_intel_mcp/tests/test_sources_fleet.py
@@ -3,15 +3,23 @@ the sibling-module boundary (fleet imports them inside the function, so
patching the module attributes intercepts the real calls).
Gaps / not covered: the real intelligence/military component functions are
-not exercised here (they have their own tests); naval-base static data is
-asserted only as non-empty, not for content.
+not exercised here (they have their own tests), except the vessel snapshot
+in the NGA-outage test, which runs the real snapshot against a mocked NGA
+500; naval-base static data is asserted only as non-empty, not for content;
+theater posture and military surge never report an error themselves (an
+OpenSky outage reads as zero aircraft there), so only a raise marks them
+unavailable.
"""
+import asyncio as asyncio_mod
+
+import httpx
import pytest
+import respx
from world_intel_mcp.fetcher import Fetcher
from world_intel_mcp.sources import intelligence, military
-from world_intel_mcp.sources.fleet import _fleet_readiness, fetch_fleet_report
+from world_intel_mcp.sources.fleet import _fleet_readiness, _safe, fetch_fleet_report
def test_fleet_readiness_low_activity() -> None:
@@ -166,3 +174,174 @@ async def test_waterway_warning_count_from_real_vessel_snapshot_shape(
ww = result["waterway_summary"][0]
assert ww["name"] == "Strait of Hormuz"
assert ww["warning_count"] == 3
+
+
+_COMPONENTS = ("military_surge", "theater_posture", "vessel_snapshot")
+
+
+async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+
+async def test_fetch_fleet_report_all_components_down_is_an_error(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Regression (silent-empty class): with every component raising,
+ _safe returned {} for each and the report read LOW_ACTIVITY with no
+ marker. The zeroed structure stays; error / reason /
+ unavailable_components / data_gaps say the report has no inputs."""
+
+ async def _boom(f) -> dict:
+ raise RuntimeError("component down")
+
+ monkeypatch.setattr(military, "fetch_theater_posture", _boom)
+ monkeypatch.setattr(intelligence, "fetch_vessel_snapshot", _boom)
+ monkeypatch.setattr(intelligence, "fetch_military_surge", _boom)
+
+ result = await fetch_fleet_report(fetcher)
+
+ assert result["error"] == (
+ "All fleet report components unavailable: "
+ "military_surge, theater_posture, vessel_snapshot"
+ )
+ assert result["reason"] == "fleet_components_unavailable"
+ assert result["degraded"] is True
+ assert result["unavailable_components"] == list(_COMPONENTS)
+ assert result["data_gaps"] == [
+ f"{name}: unavailable (RuntimeError: component down); "
+ "readiness_score is computed without it"
+ for name in _COMPONENTS
+ ]
+ assert result["readiness_level"] == "LOW_ACTIVITY"
+ assert result["readiness_score"] == 0
+
+
+async def test_fetch_fleet_report_partial_failure_is_named_not_fatal(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ async def _boom(f) -> dict:
+ raise TimeoutError("opensky timed out")
+
+ async def _vessels(f) -> dict:
+ return {
+ "waterways": [
+ {"name": "Strait of Hormuz", "status": "critical", "naval_warnings": 3}
+ ]
+ }
+
+ async def _surges(f) -> dict:
+ return {
+ "surges": [
+ {"region": "persian_gulf", "aircraft_count": 9, "baseline": 3, "ratio": 3.0}
+ ]
+ }
+
+ monkeypatch.setattr(military, "fetch_theater_posture", _boom)
+ monkeypatch.setattr(intelligence, "fetch_vessel_snapshot", _vessels)
+ monkeypatch.setattr(intelligence, "fetch_military_surge", _surges)
+
+ result = await fetch_fleet_report(fetcher)
+
+ assert "error" not in result
+ assert result["degraded"] is True
+ assert result["unavailable_components"] == ["theater_posture"]
+ assert result["data_gaps"] == [
+ "theater_posture: unavailable (TimeoutError: opensky timed out); "
+ "readiness_score is computed without it"
+ ]
+ # Critical waterway 30 + one surge 15; no aircraft term without posture.
+ assert result["readiness_score"] == 45
+ assert result["readiness_level"] == "ELEVATED_ACTIVITY"
+
+
+async def test_fetch_fleet_report_names_an_nga_outage_from_the_real_snapshot(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Through the real vessel snapshot: with NGA down the snapshot is an
+ error, so the report lists it unavailable instead of scoring nine
+ 'clear' waterways as calm."""
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(return_value=httpx.Response(500))
+
+ async def _posture(f) -> dict:
+ return {"theaters": {"european": {"count": 4, "top_types": []}}}
+
+ async def _surges(f) -> dict:
+ return {"surges": []}
+
+ monkeypatch.setattr(military, "fetch_theater_posture", _posture)
+ monkeypatch.setattr(intelligence, "fetch_military_surge", _surges)
+
+ result = await fetch_fleet_report(fetcher)
+
+ assert "error" not in result
+ assert result["degraded"] is True
+ assert result["unavailable_components"] == ["vessel_snapshot"]
+ assert result["data_gaps"] == [
+ "vessel_snapshot: unavailable (NGA navigational warnings unavailable: "
+ "NGA MSI API unavailable (no live or cached data)); readiness_score is "
+ "computed without it"
+ ]
+ assert result["waterway_count"] == 9
+ assert {ww["status"] for ww in result["waterway_summary"]} == {"unknown"}
+ # 4 aircraft -> 2; 'unknown' waterways add nothing.
+ assert result["readiness_score"] == 2
+
+
+async def test_fetch_fleet_report_carries_component_data_gaps(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ stale = (
+ "NGA feed: newest active warning was issued 2024-05-10T15:15:00Z, 890 "
+ "days ago, past the 14-day staleness threshold: these are historical "
+ "warnings, not current conditions"
+ )
+
+ async def _vessels(f) -> dict:
+ return {
+ "waterways": [{"name": "Suez Canal", "status": "clear", "naval_warnings": 0}],
+ "degraded": True,
+ "data_gaps": [stale],
+ }
+
+ async def _posture(f) -> dict:
+ return {"theaters": {}}
+
+ async def _surges(f) -> dict:
+ return {"surges": [], "degraded": True}
+
+ monkeypatch.setattr(military, "fetch_theater_posture", _posture)
+ monkeypatch.setattr(intelligence, "fetch_vessel_snapshot", _vessels)
+ monkeypatch.setattr(intelligence, "fetch_military_surge", _surges)
+
+ result = await fetch_fleet_report(fetcher)
+
+ assert "error" not in result
+ assert "unavailable_components" not in result
+ assert result["degraded"] is True
+ assert result["data_gaps"] == ["military_surge: degraded", f"vessel_snapshot: {stale}"]
+
+
+async def test_safe_turns_raises_and_bad_shapes_into_error_dicts() -> None:
+ async def _raises() -> dict:
+ raise ValueError("bad payload")
+
+ async def _returns_list() -> list:
+ return ["not", "a", "dict"]
+
+ assert await _safe(_raises(), "vessel_snapshot") == {
+ "error": "ValueError: bad payload",
+ "degraded": True,
+ "reason": "component_raised",
+ }
+ assert await _safe(_returns_list(), "vessel_snapshot") == {
+ "error": "returned list, not a dict",
+ "degraded": True,
+ "reason": "component_bad_shape",
+ }
diff --git a/src/world_intel_mcp/tests/test_sources_intelligence.py b/src/world_intel_mcp/tests/test_sources_intelligence.py
index de275c1..cd06df9 100644
--- a/src/world_intel_mcp/tests/test_sources_intelligence.py
+++ b/src/world_intel_mcp/tests/test_sources_intelligence.py
@@ -18,9 +18,14 @@ TemporalBaseline anomaly-firing path (needs 10+ historical observations —
only the recording path is exercised here); exact CII arithmetic
(instability tests assert raw_data pass-through and the UCDP floor, not
the weighted-sum internals, which belong to analysis/instability.py).
+Vessel snapshot: the 300 km radius is a chosen value, tested at its
+consequences (which waterways a warning reaches), not validated against
+real chokepoint geometry; positions past the 500-character text cut are
+not read (none in the 2026-10-17 capture changed a waterway's credits).
"""
-from datetime import datetime, timezone
+import asyncio as asyncio_mod
+from datetime import datetime, timedelta, timezone
import httpx
import pytest
@@ -879,6 +884,333 @@ async def test_fetch_vessel_snapshot_clear(
assert all(ww["naval_warnings"] == 0 for ww in result["waterways"])
+# Verbatim live records from GET
+# https://msi.nga.mil/api/publications/broadcast-warn?output=json, captured
+# 2026-10-17T16:43:08Z. Distances are to the STRATEGIC_WATERWAYS reference
+# points, cross-checked with the spherical law of cosines.
+def _nga_record(year, number, area, subregion, text, issued, authority) -> dict:
+ return {
+ "msgYear": year, "msgNumber": number, "navArea": area,
+ "subregion": subregion, "text": text, "status": "A",
+ "issueDate": issued, "authority": authority, "cancelDate": None,
+ "cancelNavArea": None, "cancelMsgYear": None, "cancelMsgNumber": None,
+ "number": number, "year": year, "area": area,
+ }
+
+
+_NGA_LIVE = [
+ # 68.5 km from the Strait of Hormuz.
+ _nga_record(
+ 2022, 3371, "P", "62",
+ "PERSIAN GULF.\nU.A.E.\nDNC 10.\nODAS BUOYS, Q Y, ESTABLISHED IN:\n"
+ "A. 25-59.00N 056-02.40E.\nB. 25-52.22N 055-51.20E.\n",
+ "251705Z NOV 2022", "NAVAREA IX 483/22 251524Z NOV 22.",
+ ),
+ # 40.8 km from the Panama Canal.
+ _nga_record(
+ 2024, 15, "4", "26",
+ "WESTERN CARIBBEAN SEA.\nPANAMA.\nCHART 26060.\n"
+ "BUOY NO1 09-25.09N 079-49.50W DESTROYED.\n",
+ "041210Z JAN 2024", "PANAMA MARITIME AUTHORITY 0/24 040926Z JAN 24.",
+ ),
+ # 53.7 km from the Panama Canal.
+ _nga_record(
+ 2022, 978, "12", "21",
+ "GULF OF PANAMA.\nPANAMA.\nCHART 26060.\n"
+ "DANGEROUS WRECK REPORTED IN 08-50.68N 079-15.18W.\n",
+ "231758Z DEC 2022", "PANAMA MARITIME AUTHORITY 0/22 231731Z DEC 22.",
+ ),
+ # Nearest of its five positions: 274.7 km from the Taiwan Strait.
+ _nga_record(
+ 2024, 1561, "P", "94",
+ "PHILIPPINE SEA.\nTAIWAN.\nDNC 23.\n"
+ "CABLE OPERATIONS 100900Z MAY UNTIL FURTHER NOTICE\n"
+ "BY CABLESHIP PETER FABER IN AREA BOUND BY\n"
+ "24-51.27N 122-05.38E, 24-50.57N 122-03.14E,\n"
+ "24-48.00N 122-03.97E, 24-48.13N 122-06.33E,\n"
+ "24-48.52N 122-06.30E.\nWIDE BERTH REQUESTED.\n",
+ "100559Z MAY 2024", "NAVAREA XI 223/24 100544Z MAY 24.",
+ ),
+ # Naval keyword (ORDNANCE); 988.6 km from Gibraltar, the nearest waterway.
+ _nga_record(
+ 2023, 1435, "A", "37",
+ "BAY OF BISCAY.\nFRANCE.\nDNC 08.\nUNEXPLODED ORDNANCE IN 44-23.00N 001-46.00W.\n",
+ "261350Z JUN 2023", "AVURNAV BREST 206/23 261335Z JUN 23.",
+ ),
+ # Naval keyword (EXERCISE); states no position, and HYDROLANT spans
+ # several NAVAREAs.
+ _nga_record(
+ 2022, 789, "A", "55",
+ "BLACK SEA.\nDNC 10.\nMINES ADRIFT REPORTED IN NORTHWESTERN, WESTERN\n"
+ "AND SOUTHWESTERN BLACK SEA. VESSELS IN VICINITY\n"
+ "ARE ADVISED TO EXERCISE EXTREME CAUTION.\n",
+ "181218Z MAR 2022", "NAVAREA III 118/22 181124Z MAR 22.",
+ ),
+ # States no position; NAVAREA XII contains the canal's Pacific end.
+ _nga_record(
+ 2023, 249, "12", "83",
+ "EASTERN NORTH PACIFIC.\nCANCEL NAVAREA XII 243/23 AND THIS MSG,\n"
+ "SEARCH SUSPENDED.\n",
+ "280353Z APR 2023", "JRCC HONOLULU 0/23 280342Z APR 23.",
+ ),
+ # Its only position, 154-84.0W, is malformed (84 minutes): no NAVAREA
+ # credit either, since it does state a place (south of Hawaii).
+ _nga_record(
+ 2023, 243, "12", "83",
+ "EASTERN NORTH PACIFIC.\nMAN OVERBOARD IN VICINITY 10-52.0N 154-84.0W\n"
+ "500 NAUTICAL MILES SOUTH OF BIG ISLAND HAWAII\n"
+ "AT 260903Z APR, PERSON DRESSED IN GREEN SHORTS\n"
+ "AND WHITE HOODIE. VESSELS IN VICINITY REQUESTED\n"
+ "TO KEEP A SHARP LOOKOUT, ASSIST IF POSSIBLE.\n"
+ "REPORTS TO JRCC HONOLULU,\nTELEX: 392401,\nPHONE: 808 535 3333,\n"
+ "FAX: 808 535 3338,\nE-MAIL: [email protected].\n",
+ "261142Z APR 2023", "JRCC HONOLULU 0/23 261128Z APR 23.",
+ ),
+ # Position in degrees-minutes-seconds, 1325.2 km from the Panama Canal.
+ _nga_record(
+ 2022, 219, "12", "21",
+ "EASTERN NORTH PACIFIC.\nGUATEMALA.\nBUOY 13-55-18N 090-47-53W TEMPORARILY REMOVED.\n",
+ "062141Z APR 2022", "GUATEMALA 1/22 062127Z APR 22.",
+ ),
+]
+
+_WATERWAY_NAMES = [
+ "Strait of Hormuz", "Strait of Malacca", "Suez Canal", "Panama Canal",
+ "Bab-el-Mandeb", "Taiwan Strait", "Strait of Gibraltar", "GIUK Gap",
+ "Bosphorus",
+]
+
+
+async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+
+async def test_fetch_vessel_snapshot_credits_only_the_waterways_a_live_warning_concerns(
+ fetcher: Fetcher,
+) -> None:
+ """Regression: every warning used to count at all nine waterways, and
+ total_nearby was computed but never emitted. On these live records the
+ old code marked every waterway 'elevated' (two naval-keyword warnings,
+ one in the Bay of Biscay, one in the Black Sea)."""
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(
+ return_value=httpx.Response(200, json={"broadcast-warn": _NGA_LIVE})
+ )
+
+ result = await intelligence.fetch_vessel_snapshot(fetcher)
+ by_name = {ww["name"]: ww for ww in result["waterways"]}
+
+ assert list(by_name) == _WATERWAY_NAMES
+ assert result["total_nav_warnings"] == 9
+
+ # Neither naval-keyword warning is near a waterway.
+ for ww in result["waterways"]:
+ assert ww["naval_warnings"] == 0
+ assert ww["status"] == "clear"
+ assert ww["warning_details"] == []
+ assert ww["naval_by_match"] == {"proximity": 0, "navarea": 0}
+ assert result["total_naval_warnings"] == 2
+
+ assert {name: ww["total_nearby"] for name, ww in by_name.items()} == {
+ "Strait of Hormuz": 1, "Strait of Malacca": 0, "Suez Canal": 0,
+ "Panama Canal": 3, "Bab-el-Mandeb": 0, "Taiwan Strait": 1,
+ "Strait of Gibraltar": 0, "GIUK Gap": 0, "Bosphorus": 0,
+ }
+ # Two by stated position, one (the positionless cancellation) by NAVAREA.
+ assert by_name["Panama Canal"]["nearby_by_match"] == {"proximity": 2, "navarea": 1}
+ assert by_name["Strait of Hormuz"]["nearby_by_match"] == {"proximity": 1, "navarea": 0}
+
+ assert result["unplaced_naval_warnings"] == [
+ {
+ "id": "2022-789",
+ "navarea": "A",
+ "series": "HYDROLANT",
+ "issue_date": "181218Z MAR 2022",
+ "reason": "multi_navarea_series",
+ "text_snippet": _NGA_LIVE[5]["text"][:200],
+ }
+ ]
+
+ rule = result["matching_rule"]
+ assert rule["proximity_km"] == 300.0
+ assert rule["waterway_navareas"] == {"Panama Canal": ["IV", "XII"]}
+ assert rule["area_codes"] == maritime.area_codes_view()
+ assert "proximity_km" in rule["rule"]
+
+ # The newest of these was issued 10 May 2024: flagged, not passed off
+ # as current.
+ assert result["newest_issue_date"] == "2024-05-10T05:59:00Z"
+ assert result["degraded"] is True
+ assert "error" not in result
+ assert result["data_gaps"][0].startswith(
+ "NGA feed: newest active warning was issued 2024-05-10T05:59:00Z, "
+ )
+ assert result["data_gaps"][1:] == [
+ "1 naval warning(s) state no readable position and no single-NAVAREA "
+ "area code, so no waterway is credited with them "
+ "(unplaced_naval_warnings): 2022-789 (multi_navarea_series)"
+ ]
+
+
+async def test_fetch_vessel_snapshot_naval_status_counts_only_nearby_warnings(
+ fetcher: Fetcher,
+) -> None:
+ """Constructed in the live record shape (texts are not real warnings,
+ issue dates are two hours old): three naval warnings near Hormuz, one
+ near Bab-el-Mandeb, one positionless NAVAREA IV warning, one whose only
+ position is malformed."""
+ issued = datetime.now(timezone.utc) - timedelta(hours=2)
+ month = "JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC".split()[issued.month - 1]
+ stamp = f"{issued:%d%H%M}Z {month} {issued.year}"
+ records = [
+ # 11.4 km from Hormuz (nearer of two positions).
+ _nga_record(
+ 2026, 901, "P", "62",
+ "PERSIAN GULF.\nIRAN.\nDNC 10.\nNAVAL EXERCISES IN AREA BOUND BY\n"
+ "26-30.00N 056-10.00E, 26-40.00N 056-30.00E.\n",
+ stamp, "NAVAREA IX 1/26",
+ ),
+ # 140.6 km from Hormuz.
+ _nga_record(
+ 2026, 902, "P", "63",
+ "GULF OF OMAN.\nIRAN.\nDNC 10.\nLIVE FIRING 25-30.00N 057-00.00E.\n",
+ stamp, "NAVAREA IX 2/26",
+ ),
+ # 98.0 km from Hormuz.
+ _nga_record(
+ 2026, 903, "P", "62",
+ "PERSIAN GULF.\nU.A.E.\nDNC 10.\nSUBMARINE OPERATIONS IN VICINITY "
+ "26-00.00N 055-30.00E.\n",
+ stamp, "NAVAREA IX 3/26",
+ ),
+ # 9.6 km from Bab-el-Mandeb.
+ _nga_record(
+ 2026, 904, "P", "62",
+ "RED SEA.\nYEMEN.\nDNC 10.\nWARSHIP OPERATIONS 12-40.00N 043-20.00E.\n",
+ stamp, "NAVAREA IX 4/26",
+ ),
+ # No position, single-NAVAREA code 4: credited to Panama by NAVAREA.
+ _nga_record(
+ 2026, 905, "4", "24",
+ "WESTERN NORTH ATLANTIC.\nNAVAL OPERATIONS IN PROGRESS.\n",
+ stamp, "NAVSAFETY 5/26",
+ ),
+ # Malformed position (84 minutes): credited nowhere.
+ _nga_record(
+ 2026, 906, "12", "83",
+ "EASTERN NORTH PACIFIC.\nGUNNERY FIRING EXERCISE IN 10-52.0N 154-84.0W.\n",
+ stamp, "NAVSAFETY 6/26",
+ ),
+ ]
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(
+ return_value=httpx.Response(200, json={"broadcast-warn": records})
+ )
+
+ result = await intelligence.fetch_vessel_snapshot(fetcher)
+ by_name = {ww["name"]: ww for ww in result["waterways"]}
+
+ hormuz = by_name["Strait of Hormuz"]
+ assert hormuz["naval_warnings"] == 3
+ assert hormuz["status"] == "critical"
+ assert hormuz["naval_by_match"] == {"proximity": 3, "navarea": 0}
+ assert [(d["id"], d["match"], d["distance_km"]) for d in hormuz["warning_details"]] == [
+ ("2026-901", "proximity", 11.4),
+ ("2026-903", "proximity", 98.0),
+ ("2026-902", "proximity", 140.6),
+ ]
+ assert by_name["Bab-el-Mandeb"]["status"] == "advisory"
+ assert by_name["Bab-el-Mandeb"]["warning_details"][0]["distance_km"] == 9.6
+
+ panama = by_name["Panama Canal"]
+ assert panama["status"] == "advisory"
+ assert panama["naval_by_match"] == {"proximity": 0, "navarea": 1}
+ assert panama["warning_details"][0]["id"] == "2026-905"
+ assert panama["warning_details"][0]["match"] == "navarea"
+ assert panama["warning_details"][0]["distance_km"] is None
+
+ others = set(_WATERWAY_NAMES) - {"Strait of Hormuz", "Bab-el-Mandeb", "Panama Canal"}
+ assert {by_name[name]["status"] for name in others} == {"clear"}
+
+ assert [(w["id"], w["reason"], w["series"]) for w in result["unplaced_naval_warnings"]] == [
+ ("2026-906", "position_unreadable", "NAVAREA XII")
+ ]
+ assert result["total_naval_warnings"] == 6
+ assert result["newest_issue_age_days"] == pytest.approx(2 / 24, abs=0.1)
+ assert "degraded" not in result
+
+
+async def test_fetch_vessel_snapshot_nga_outage_reads_unknown_not_clear(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Regression (silent-empty class): with NGA down every waterway read
+ 'clear', a calm-seas verdict drawn from no data."""
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(return_value=httpx.Response(500))
+
+ result = await intelligence.fetch_vessel_snapshot(fetcher)
+
+ assert [ww["status"] for ww in result["waterways"]] == ["unknown"] * 9
+ assert all(ww["naval_warnings"] == 0 for ww in result["waterways"])
+ assert all(ww["total_nearby"] == 0 for ww in result["waterways"])
+ assert result["error"] == (
+ "NGA navigational warnings unavailable: "
+ "NGA MSI API unavailable (no live or cached data)"
+ )
+ assert result["degraded"] is True
+ assert result["reason"] == "nga_msi_fetch_failed"
+ assert result["data_gaps"] == [
+ "NGA feed: NGA MSI broadcast warnings unavailable (no live or cached "
+ "data): zero warnings here means unknown, not a quiet sea"
+ ]
+
+
+async def test_fetch_vessel_snapshot_roman_numeral_navarea_is_not_an_nga_code(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The live API never sends Roman numerals in navArea, so a warning
+ that carries one and states no position is placed nowhere, and said
+ so, instead of counting everywhere."""
+ warnings = [
+ {"id": "2026-1", "text": "NAVAL EXERCISES IN AREA", "navarea": "IV"},
+ {"id": "2026-2", "text": "SUBMARINE OPERATIONS", "navarea": "XI"},
+ {"id": "2026-3", "text": "LIVE FIRING IN PROGRESS", "navarea": "IX"},
+ {"id": "2026-4", "text": "BUOY UNLIT", "navarea": "IV"},
+ {"id": "2026-5", "text": "X" * 500 + "...", "navarea": "A"},
+ ]
+ monkeypatch.setattr(
+ maritime, "fetch_nav_warnings", _async_return({"warnings": warnings})
+ )
+
+ result = await intelligence.fetch_vessel_snapshot(fetcher)
+
+ assert all(ww["naval_warnings"] == 0 for ww in result["waterways"])
+ assert all(ww["status"] == "clear" for ww in result["waterways"])
+ assert all(ww["total_nearby"] == 0 for ww in result["waterways"])
+ assert result["total_naval_warnings"] == 3
+ assert [
+ (w["id"], w["reason"], w["series"]) for w in result["unplaced_naval_warnings"]
+ ] == [
+ ("2026-1", "unknown_area_code", None),
+ ("2026-2", "unknown_area_code", None),
+ ("2026-3", "unknown_area_code", None),
+ ]
+ assert result["data_gaps"] == [
+ "3 naval warning(s) state no readable position and no single-NAVAREA "
+ "area code, so no waterway is credited with them "
+ "(unplaced_naval_warnings): 2026-1 (unknown_area_code), "
+ "2026-2 (unknown_area_code), 2026-3 (unknown_area_code)",
+ "1 warning text(s) were cut at 500 characters; positions after the "
+ "cut are not read",
+ ]
+ assert "degraded" not in result
+
+
# ---------------------------------------------------------------------------
# Function 12: fetch_cascade_analysis
# ---------------------------------------------------------------------------
diff --git a/src/world_intel_mcp/tests/test_sources_maritime.py b/src/world_intel_mcp/tests/test_sources_maritime.py
index 8207f39..8d35dd9 100644
--- a/src/world_intel_mcp/tests/test_sources_maritime.py
+++ b/src/world_intel_mcp/tests/test_sources_maritime.py
@@ -1,17 +1,30 @@
"""Tests for sources/maritime.py — respx-mocked NGA MSI broadcast warnings.
+The _LIVE_* records further down are verbatim from the live API
+(GET https://msi.nga.mil/api/publications/broadcast-warn?output=json,
+captured 2026-10-17T16:43:08Z: 386 active warnings, the newest issued
+10 May 2024). The live API sends navArea as an area code ("4", "12", "A",
+"P", "C"), never a Roman numeral, and issueDate as "DDHHMMZ MON YYYY".
+
Gaps / not covered: live NGA payload variants beyond the three shapes the
-module handles (list, dict-with-key, single dict); coordinate strings with
-seconds notation (the regex only handles degrees-minutes).
+module handles (list, dict-with-key, single dict); seconds notation in the
+per-warning lat/lon fields (_extract_coords still reads degrees-minutes
+only; extract_positions reads both); the 14-day staleness threshold is
+derived from 2024 issue gaps only (the live API holds nothing newer); a
+stale cache serve of a list payload, which cannot carry the fetcher's
+_stale marker.
"""
import asyncio as asyncio_mod
+import re
+from datetime import datetime, timedelta, timezone
import httpx
import pytest
import respx
from world_intel_mcp.fetcher import Fetcher
+from world_intel_mcp.sources import maritime as maritime_mod
from world_intel_mcp.sources.maritime import (
NAVAREAS,
_extract_coords,
@@ -168,3 +181,344 @@ def test_is_active_and_parse_warning() -> None:
# Missing msgYear/msgNumber leaves id as None.
assert _parse_warning({"text": "x"})["id"] is None
+
+
+# ---------------------------------------------------------------------------
+# Data honesty: outage markers, frozen-feed staleness, NGA area codes
+# ---------------------------------------------------------------------------
+
+# Verbatim live records (see the module docstring for the capture).
+_LIVE_P_PERSIAN_GULF = {
+ "msgYear": 2022, "msgNumber": 3371, "navArea": "P", "subregion": "62",
+ "text": (
+ "PERSIAN GULF.\nU.A.E.\nDNC 10.\nODAS BUOYS, Q Y, ESTABLISHED IN:\n"
+ "A. 25-59.00N 056-02.40E.\nB. 25-52.22N 055-51.20E.\n"
+ ),
+ "status": "A", "issueDate": "251705Z NOV 2022",
+ "authority": "NAVAREA IX 483/22 251524Z NOV 22.", "cancelDate": None,
+ "cancelNavArea": None, "cancelMsgYear": None, "cancelMsgNumber": None,
+ "number": 3371, "year": 2022, "area": "P",
+}
+_LIVE_A_BLACK_SEA_MINES = {
+ "msgYear": 2022, "msgNumber": 789, "navArea": "A", "subregion": "55",
+ "text": (
+ "BLACK SEA.\nDNC 10.\nMINES ADRIFT REPORTED IN NORTHWESTERN, WESTERN\n"
+ "AND SOUTHWESTERN BLACK SEA. VESSELS IN VICINITY\n"
+ "ARE ADVISED TO EXERCISE EXTREME CAUTION.\n"
+ ),
+ "status": "A", "issueDate": "181218Z MAR 2022",
+ "authority": "NAVAREA III 118/22 181124Z MAR 22.", "cancelDate": None,
+ "cancelNavArea": None, "cancelMsgYear": None, "cancelMsgNumber": None,
+ "number": 789, "year": 2022, "area": "A",
+}
+_LIVE_P_TAIWAN_CABLE = {
+ "msgYear": 2024, "msgNumber": 1561, "navArea": "P", "subregion": "94",
+ "text": (
+ "PHILIPPINE SEA.\nTAIWAN.\nDNC 23.\n"
+ "CABLE OPERATIONS 100900Z MAY UNTIL FURTHER NOTICE\n"
+ "BY CABLESHIP PETER FABER IN AREA BOUND BY\n"
+ "24-51.27N 122-05.38E, 24-50.57N 122-03.14E,\n"
+ "24-48.00N 122-03.97E, 24-48.13N 122-06.33E,\n"
+ "24-48.52N 122-06.30E.\nWIDE BERTH REQUESTED.\n"
+ ),
+ "status": "A", "issueDate": "100559Z MAY 2024",
+ "authority": "NAVAREA XI 223/24 100544Z MAY 24.", "cancelDate": None,
+ "cancelNavArea": None, "cancelMsgYear": None, "cancelMsgNumber": None,
+ "number": 1561, "year": 2024, "area": "P",
+}
+# The newest active warning in the capture.
+_LIVE_P_BASS_STRAIT_NEWEST = {
+ "msgYear": 2024, "msgNumber": 1571, "navArea": "P", "subregion": "75",
+ "text": (
+ "BASS STRAIT.\nAUSTRALIA.\nDNC 05.\n1. UNDERWATER OPERATIONS IN PROGRESS\n"
+ " UNTIL FURTHER NOTICE BY M/V INVESTIGATOR\n IN AREA BOUND BY\n"
+ " 37-57.00S 148-13.00E, 38-54.00S 148-13.00E,\n"
+ " 38-54.00S 149-03.00E, 37-57.00S 149-03.00E.\n"
+ " ONE MILE BERTH REQUESTED.\n2. CANCEL HYDROLANT 1564/24.\n"
+ ),
+ "status": "A", "issueDate": "101515Z MAY 2024",
+ "authority": "AUSCOAST 154/24 101452Z MAY 24.", "cancelDate": None,
+ "cancelNavArea": None, "cancelMsgYear": None, "cancelMsgNumber": None,
+ "number": 1571, "year": 2024, "area": "P",
+}
+_LIVE_4_HAITI_DMS = {
+ "msgYear": 2021, "msgNumber": 1157, "navArea": "4", "subregion": "26",
+ "text": (
+ "WESTERN NORTH ATLANTIC.\nHAITI.\nCHART 26141.\n"
+ "ILE DE LA TORTUE W. POINT LIGHT\n20-03-44N 072-58-02W UNLIT.\n"
+ ),
+ "status": "A", "issueDate": "281021Z DEC 2021",
+ "authority": "HAITI 5/21 280205Z DEC 21.", "cancelDate": None,
+ "cancelNavArea": None, "cancelMsgYear": None, "cancelMsgNumber": None,
+ "number": 1157, "year": 2021, "area": "4",
+}
+# GET https://msi.nga.mil/api/publications/broadcast-warn/navareas, same day.
+_LIVE_NAVAREAS_ENDPOINT = {
+ "NAVAREA IV": "4", "HYDROLANT": "A", "NAVAREA XII": "12",
+ "HYDROPAC": "P", "HYDROARC": "C",
+}
+
+_MONTHS = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN",
+ "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]
+
+
+def _nga_issue_date(dt: datetime) -> str:
+ """Format a datetime the way the live API writes issueDate."""
+ return f"{dt:%d%H%M}Z {_MONTHS[dt.month - 1]} {dt.year}"
+
+
+def _days_since(dt: datetime) -> float:
+ return (datetime.now(timezone.utc) - dt).total_seconds() / 86400
+
+
+async def _no_sleep(*args, **kwargs) -> None:
+ return None
+
+
+async def test_fetch_nav_warnings_outage_is_marked_not_quiet(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Regression (silent-empty class): an NGA outage returned warnings=[]
+ with no marker, shape-identical to a sea with no active warnings. The
+ zeroed fields stay; error / degraded / reason / data_gaps say why."""
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(return_value=httpx.Response(500))
+
+ result = await fetch_nav_warnings(fetcher)
+
+ assert result["error"] == "NGA MSI API unavailable (no live or cached data)"
+ assert result["degraded"] is True
+ assert result["reason"] == "nga_msi_fetch_failed"
+ assert result["data_gaps"] == [
+ "NGA MSI broadcast warnings unavailable (no live or cached data): "
+ "zero warnings here means unknown, not a quiet sea"
+ ]
+ assert result["warnings"] == []
+ assert result["count"] == 0
+ assert result["newest_issue_date"] is None
+
+
+async def test_fetch_nav_warnings_unrecognized_payload_is_an_error(
+ fetcher: Fetcher,
+) -> None:
+ """A 200 whose JSON holds no warnings list used to read as zero
+ warnings; an empty list is a real (if unlikely) answer and stays one."""
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(
+ return_value=httpx.Response(200, json={"message": "Service Unavailable"})
+ )
+
+ result = await fetch_nav_warnings(fetcher)
+
+ assert result["error"] == "NGA MSI returned an unrecognized payload (keys: ['message'])"
+ assert result["degraded"] is True
+ assert result["reason"] == "nga_msi_unexpected_payload"
+ assert result["count"] == 0
+ assert len(result["data_gaps"]) == 1
+
+
+async def test_fetch_nav_warnings_empty_list_is_not_an_outage(fetcher: Fetcher) -> None:
+ # The live API answers msgYear=2026 with exactly this.
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(
+ return_value=httpx.Response(200, json={"broadcast-warn": []})
+ )
+
+ result = await fetch_nav_warnings(fetcher)
+
+ assert "error" not in result
+ assert "degraded" not in result
+ assert result["count"] == 0
+ assert result["data_gaps"] == []
+ assert result["newest_issue_date"] is None
+ assert result["newest_issue_age_days"] is None
+
+
+async def test_fetch_nav_warnings_stale_cache_serve_is_degraded(
+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A failed fetch answered from the expired cache is named as such."""
+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)
+ fresh = datetime.now(timezone.utc) - timedelta(hours=2)
+ record = dict(_LIVE_P_PERSIAN_GULF, issueDate=_nga_issue_date(fresh))
+ fetcher.cache.set(
+ "maritime:warnings:all", {"broadcast-warn": [record]}, ttl_seconds=-10
+ )
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(return_value=httpx.Response(500))
+
+ result = await fetch_nav_warnings(fetcher)
+
+ assert "error" not in result
+ assert result["degraded"] is True
+ assert result["count"] == 1
+ assert result["warnings"][0]["id"] == "2022-3371"
+ assert len(result["data_gaps"]) == 1
+ assert re.fullmatch(
+ r"NGA MSI fetch failed; serving a cached copy \d+(\.\d+)? s old",
+ result["data_gaps"][0],
+ )
+
+
+async def test_fetch_nav_warnings_frozen_feed_names_its_age(fetcher: Fetcher) -> None:
+ """Measured 2026-10-17: the live API's newest active warning was issued
+ 10 May 2024, yet the response carried nothing to say so. Live-shaped
+ records: the age of the newest issue date is reported and, past
+ STALE_AFTER_DAYS, flagged in data_gaps."""
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "broadcast-warn": [
+ _LIVE_P_PERSIAN_GULF,
+ _LIVE_A_BLACK_SEA_MINES,
+ _LIVE_P_BASS_STRAIT_NEWEST,
+ _LIVE_P_TAIWAN_CABLE,
+ ]
+ },
+ )
+ )
+
+ result = await fetch_nav_warnings(fetcher)
+
+ expected_age = _days_since(datetime(2024, 5, 10, 15, 15, tzinfo=timezone.utc))
+ assert result["newest_issue_date"] == "2024-05-10T15:15:00Z"
+ assert result["newest_issue_age_days"] == pytest.approx(expected_age, abs=0.1)
+ assert result["stale_after_days"] == 14
+ assert result["degraded"] is True
+ assert "error" not in result
+ age_text = f"{result['newest_issue_age_days']:.0f}"
+ assert result["data_gaps"] == [
+ f"newest active warning was issued 2024-05-10T15:15:00Z, {age_text} days "
+ "ago, past the 14-day staleness threshold: these are historical "
+ "warnings, not current conditions"
+ ]
+ # The live area codes pass through as the API sends them.
+ assert result["by_navarea"] == {"P": 3, "A": 1}
+ assert result["area_codes"] == maritime_mod.area_codes_view()
+
+
+async def test_fetch_nav_warnings_fresh_feed_is_not_flagged(fetcher: Fetcher) -> None:
+ issued = datetime.now(timezone.utc).replace(second=0, microsecond=0) - timedelta(hours=2)
+ record = dict(_LIVE_P_PERSIAN_GULF, issueDate=_nga_issue_date(issued))
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(
+ return_value=httpx.Response(200, json={"broadcast-warn": [record]})
+ )
+
+ result = await fetch_nav_warnings(fetcher)
+
+ assert result["newest_issue_date"] == issued.strftime("%Y-%m-%dT%H:%M:%SZ")
+ assert result["newest_issue_age_days"] == pytest.approx(_days_since(issued), abs=0.1)
+ assert result["data_gaps"] == []
+ assert "degraded" not in result
+
+
+async def test_fetch_nav_warnings_unparseable_dates_are_flagged(fetcher: Fetcher) -> None:
+ records = [
+ dict(_LIVE_P_PERSIAN_GULF, issueDate=None),
+ dict(_LIVE_P_TAIWAN_CABLE, issueDate="SOMETIME IN MAY"),
+ ]
+ respx.get(url__regex=r".*msi\.nga\.mil.*").mock(
+ return_value=httpx.Response(200, json={"broadcast-warn": records})
+ )
+
+ result = await fetch_nav_warnings(fetcher)
+
+ assert result["count"] == 2
+ assert result["newest_issue_date"] is None
+ assert result["degraded"] is True
+ assert result["data_gaps"] == [
+ "no warning carries a parseable issue date, so how current this list "
+ "is cannot be checked"
+ ]
+
+
+def test_parse_issue_date() -> None:
+ parse = maritime_mod._parse_issue_date
+ assert parse("101515Z MAY 2024") == datetime(2024, 5, 10, 15, 15, tzinfo=timezone.utc)
+ assert parse("281021z dec 2021") == datetime(2021, 12, 28, 10, 21, tzinfo=timezone.utc)
+ # The older fixtures above use ISO dates; those still parse, as UTC.
+ assert parse("2026-08-30") == datetime(2026, 8, 30, tzinfo=timezone.utc)
+ assert parse("2026-08-30T12:00:00+02:00") == datetime(
+ 2026, 8, 30, 10, 0, tzinfo=timezone.utc
+ )
+ assert parse("321515Z MAY 2024") is None # day 32
+ assert parse("101515Z MAI 2024") is None # not an English month
+ assert parse("SOMETIME IN MAY") is None
+ assert parse("") is None
+ assert parse(None) is None
+
+
+def test_extract_positions_reads_dm_and_dms_in_text_order() -> None:
+ assert maritime_mod.extract_positions(_LIVE_P_TAIWAN_CABLE["text"]) == [
+ (24.8545, 122.0897),
+ (24.8428, 122.0523),
+ (24.8, 122.0662),
+ (24.8022, 122.1055),
+ (24.8087, 122.105),
+ ]
+ # 20 + 3/60 + 44/3600 = 20.0622 N; 72 + 58/60 + 2/3600 = 72.9672 W.
+ assert maritime_mod.extract_positions(_LIVE_4_HAITI_DMS["text"]) == [
+ (20.0622, -72.9672)
+ ]
+ assert _extract_coords(_LIVE_4_HAITI_DMS["text"]) == (None, None)
+ assert maritime_mod.extract_positions(
+ "A. 05-30.0S 120-15.0E. B. 13-55-18N 090-47-53W."
+ ) == [(-5.5, 120.25), (13.9217, -90.7981)]
+ # Live HYDROPAC 2023-243 gives '154-84.0W': 84 minutes is malformed.
+ assert maritime_mod.extract_positions("IN VICINITY 10-52.0N 154-84.0W") == []
+ assert maritime_mod.extract_positions("95-00.0N 010-00.0E") == []
+ assert maritime_mod.extract_positions(_LIVE_A_BLACK_SEA_MINES["text"]) == []
+
+
+def test_mentions_position_sees_malformed_pairs() -> None:
+ assert maritime_mod.mentions_position("IN VICINITY 10-52.0N 154-84.0W") is True
+ assert maritime_mod.mentions_position(_LIVE_4_HAITI_DMS["text"]) is True
+ assert maritime_mod.mentions_position(_LIVE_P_TAIWAN_CABLE["text"]) is True
+ assert maritime_mod.mentions_position(_LIVE_A_BLACK_SEA_MINES["text"]) is False
+
+
+def test_nga_area_codes_cover_the_live_code_table() -> None:
+ codes = maritime_mod.NGA_AREA_CODES
+ # Exactly the codes the live navareas endpoint lists, under its names.
+ assert set(codes) == set(_LIVE_NAVAREAS_ENDPOINT.values())
+ for series, code in _LIVE_NAVAREAS_ENDPOINT.items():
+ assert codes[code]["series"] == series
+
+ assert codes["4"]["navareas"] == ("IV",)
+ assert codes["12"]["navareas"] == ("XII",)
+ assert [c for c in codes if codes[c]["single_navarea"]] == ["4", "12"]
+ assert codes["C"]["unlisted_navareas"] == ("XVII", "XVIII", "XIX", "XX", "XXI")
+
+ listed: set[str] = set()
+ for entry in codes.values():
+ assert set(entry["navareas"]) <= set(NAVAREAS)
+ assert not set(entry["unlisted_navareas"]) & set(NAVAREAS)
+ listed |= set(entry["navareas"])
+ assert listed == set(NAVAREAS)
+
+ # The coordinator a live warning names in its authority field belongs
+ # to an area its code maps to.
+ for record in (_LIVE_P_PERSIAN_GULF, _LIVE_A_BLACK_SEA_MINES, _LIVE_P_TAIWAN_CABLE):
+ area = re.match(r"NAVAREA ([IVX]+) ", record["authority"]).group(1)
+ entry = codes[record["navArea"]]
+ assert area in entry["navareas"] + entry["unlisted_navareas"]
+
+ view = maritime_mod.area_codes_view()
+ assert view["A"] == {
+ "series": "HYDROLANT",
+ "navareas": ["I", "II", "III", "IV", "V", "VI", "VII", "XV"],
+ "unlisted_navareas": [],
+ "single_navarea": False,
+ }