160-tool MCP server for real-time global intelligence from free public APIs: markets, liquidity, prediction markets, SEC filings, conflict, military, aircraft-cohort early warning, migration and border flows, cyber, climate, news and more. Dated observation history, 29 research prompts, cited briefs, geofences, SSE dashboard. MIT, no paid API keys.
Python ai-toolsai-watchanthropicclaudecybersecuritydashboardgeofencinggeopoliticalgeospatialintelligencemarketsmcpmigrationmilitarymodel-context-protocolnuclearosintreal-timespace-weatherthreat-intelligence
Maritime and fleet honesty: second review round
Phoenix Agent (mac-studio)e4f021602c7e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e032647..75024cd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,20 +8,32 @@Hormuz critical alike. On the live feed of 2026-10-17 the old code markedall nine `critical` from 8 such warnings, none within 300 km of any ofthem. 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`.+ its text states, read from the full text (positions past the+ 500-character cut used to be lost). A warning that states no readable+ position counts nowhere: its area code names at least a whole NAVAREA.+ Crediting such warnings to the Panama Canal by NAVAREA IV or XII was+ measured and rejected: on the same capture all 5 of those credits were+ wrong (Hawaii, California, "warnings in force" lists), and on the 3,480+ warnings of 2024 they were 200 of Panama's 203, none naming Panama.+ Naval warnings with no readable position are listed in+ `unplaced_naval_warnings` with a reason (`multi_navarea_series`,+ `navarea_too_broad`, `position_unreadable`, `unknown_area_code`) and+ named in `data_gaps` as `<area code>:<id>`, since one id can name+ warnings in two series. The rule is 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`.+ it, which the old code computed and dropped) and `status_as_of`;+ `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`.+ 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.+- 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+ a stated but unreadable position. On the 3,866 warnings captured+ 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.### Fixed: navigational warnings- An NGA outage returned `warnings: []` with no marker, the same shape as a@@ -34,25 +46,78 @@none, `msgYear=2024` with `status=all` ends on 10 May, and`/current-warnings` and `/inforce` list the same 2024 state), yetresponses 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.+ `newest_issue_date`, `newest_issue_age_days` and `feed_stale`; 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`. An+ issue date more than a day ahead is left out of the check and named in+ `data_gaps`: one "MAY 2042" among frozen 2024 warnings used to make the+ feed read current. The vessel snapshot and fleet report pass this on,+ and `intel warnings` prints a STALE line and the data gaps.+- The `navarea` filter compared the value with the API's `navArea` field,+ which only ever holds the codes 4, 12, A, P and C, so the documented+ Roman numerals matched nothing: `navarea="IV"` returned 0 of the 71+ code-4 warnings on the live feed, with no marker. It now takes the codes,+ their series names (`HYDROPAC`) and IV or XII for 4 or 12; a value no+ carried area matches (most NAVAREAs arrive inside the A, P and C series)+ returns `error` and `reason` `navarea_not_carried` with a `data_gaps`+ line naming the series that carry it, never a bare 0. The tool schema+ and the CLI `--navarea` help say the same. The freshness fields describe+ the whole active feed, before the filter, so an area with nothing in+ force on a frozen feed reads stale instead of an undated 0.- `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`.+ `sources/maritime.py`. Code 4 also carries Canadian Arctic (NAVAREA+ XVIII) warnings, so it is not a single NAVAREA.-### Fixed: fleet report+### Fixed: fleet report and theater posture- `intel_fleet_report` turned a failed component into `{}`, so with allthree down it read `LOW_ACTIVITY` with no marker. A component that raisesor 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.+ `data_gaps` and the report is degraded; so is a vessel snapshot whose NGA+ feed is stale, which is no longer scored. With all three unavailable the+ report carries `error` and `reason` (`fleet_components_unavailable`),+ `readiness_level` `UNKNOWN` and `readiness_score` null. With some+ missing, `readiness_lower_bound` is true and `data_gaps` says what the+ score leaves out and how high it can still reach (each component adds at+ most 30 of 90). Component `data_gaps` are passed on.+- `intel_military_flights` with adsb.lol and OpenSky both down returned+ zero aircraft, told apart from an empty sky only by `source: "none"`.+ Those keys stay, and the response now also carries `error`, `degraded`+ and `reason` (`military_flights_unavailable`).+- `intel_theater_posture` turned a theater that no flight source answered+ for (adsb.lol and OpenSky both failed) into zero aircraft, so a full+ outage read as an empty sky, and as `LOW_ACTIVITY` with no error in the+ fleet report. Each theater now names its `source`; unanswered ones are+ listed in `unavailable_theaters` and `data_gaps` and the response is+ degraded, with `error` and `reason` (`military_flights_unavailable`)+ when none answered. Only a complete posture is cached.+ `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.++### Fixed: report maritime section+- The PDF/HTML report read `vessels` and `snapshot` for its maritime+ section, keys the vessel snapshot never emits, so every report said "No+ maritime data". It now shows the nine waterways' statuses, a STALE note+ for a frozen feed, the outage error, and the first data gaps.### Tests-- Failing-first regression tests for all three, built on live NGA records- captured 2026-10-17.+- Failing-first regression tests built on live NGA records captured+ 2026-10-17, and `test_maritime_honesty.py` and `test_fleet_honesty.py`+ for the second review round: each finding test fails on the previous+ 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).++### Still open+- The dashboard's nav-warnings table and fleet panel do not yet read+ `feed_stale`, `stale`, `unknown`, `readiness_lower_bound` or `UNKNOWN`,+ and the collector counts error results as successful collections.+- Strategic posture and temporal anomalies still read a posture outage as+ zero activity; posture now marks it, but they do not check.+- A naval warning that cannot be placed leaves every waterway's status+ unchanged; it is named only in `unplaced_naval_warnings` and+ `data_gaps`.## 0.11.0 - 2026-10-12diff --git a/ROADMAP.md b/ROADMAP.mdindex 815ed53..dcdf2d0 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 | :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` |+| 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` || 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 | :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 |+| 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: `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). Open: `prediction.py` and `news.py` are not covered; the dashboard and collector do not yet read the new markers; strategic posture and temporal anomalies still read a posture outage as zero activity || 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/cli.py b/src/world_intel_mcp/cli.pyindex af3204c..b9e4d60 100644--- a/src/world_intel_mcp/cli.py+++ b/src/world_intel_mcp/cli.py@@ -654,7 +654,12 @@ def cables(ctx: click.Context) -> None:@main.command()[email protected]("--navarea", "-n", default=None, help="NAVAREA number (e.g., IV)")+ "--navarea",+ "-n",+ default=None,+ help="NGA area code: 4, 12, A, P or C (IV and XII are accepted for 4 and 12)",+)@click.pass_contextdef warnings(ctx: click.Context, navarea: str | None) -> None:"""Navigational warnings (NGA Maritime Safety)."""@@ -662,9 +667,21 @@ def warnings(ctx: click.Context, navarea: str | None) -> None:data = _run(maritime.fetch_nav_warnings(f, navarea=navarea))if _bail_on_error(ctx, data):+ if not ctx.obj.get("json"):+ _print_data_gaps(data)return+ if data.get("feed_stale"):+ # The live feed's newest warning dates from May 2024; without this+ # line the list read as current conditions.+ console.print(+ "[yellow bold]STALE:[/yellow bold] newest warning issued "+ f"{escape(str(data.get('newest_issue_date')))} "+ f"({data.get('newest_issue_age_days')} days ago; threshold "+ f"{data.get('stale_after_days')} days)"+ )console.print(f"[bold]{data.get('count', 0)} active warnings[/bold]\n")+ _print_data_gaps(data)by_area = data.get("by_navarea", {})if by_area:diff --git a/src/world_intel_mcp/reports.py b/src/world_intel_mcp/reports.pyindex 9ae3537..4d8c0a8 100644--- a/src/world_intel_mcp/reports.py+++ b/src/world_intel_mcp/reports.py@@ -401,8 +401,61 @@ def _render_health(data: dict) -> str:</table>"""+_WATERWAY_STATUS_CLASS = {+ "critical": "red",+ "elevated": "red",+ "advisory": "amber",+ "clear": "green",+}++def _render_maritime(data: dict) -> str:- """Render maritime overview."""+ """Render maritime overview: the vessel snapshot's waterway statuses.++ The maritime section is fetch_vessel_snapshot, which emits waterways.+ This used to read only vessels / snapshot, keys the snapshot never+ emits, so every report said "No maritime data". Those keys still+ render when present.+ """+ if data.get("error"):+ return (+ '<p class="no-data">Maritime data unavailable: '+ f"{_esc(str(data['error'])[:200])}</p>"+ )+ waterways = data.get("waterways")+ if isinstance(waterways, list) and waterways:+ html = ""+ if data.get("feed_stale"):+ html += (+ '<p><span class="metric amber">STALE</span> The NGA warning feed was '+ f"last updated {_esc(data.get('newest_issue_date'))}: these statuses "+ "describe that date, not today.</p>"+ )+ ww_rows = []+ for ww in waterways:+ if not isinstance(ww, dict):+ continue+ status = str(ww.get("status") or "unknown")+ cls = _WATERWAY_STATUS_CLASS.get(status, "")+ ww_rows.append(+ f"<tr><td>{_esc(ww.get('name', ''))}</td>"+ f'<td><span class="metric {cls}">{_esc(status)}</span></td>'+ f"<td>{_esc(ww.get('naval_warnings', 0))}</td>"+ f"<td>{_esc(ww.get('total_nearby', 0))}</td></tr>"+ )+ html += f"""+ <table>+ <tr><th>Waterway</th><th>Status</th><th>Naval warnings</th><th>All warnings nearby</th></tr>+ {"".join(ww_rows)}+ </table>"""+ gaps = data.get("data_gaps") or []+ if gaps:+ html += "<ul>" + "".join(f"<li>{_esc(str(g)[:300])}</li>" for g in gaps[:5])+ if len(gaps) > 5:+ html += f"<li>{len(gaps) - 5} more data gap(s) not shown</li>"+ html += "</ul>"+ return html+vessels = data.get("vessels") or data.get("snapshot", [])if not vessels:return '<p class="no-data">No maritime data</p>'diff --git a/src/world_intel_mcp/sources/fleet.py b/src/world_intel_mcp/sources/fleet.pyindex 73cc96c..41b56e9 100644--- a/src/world_intel_mcp/sources/fleet.py+++ b/src/world_intel_mcp/sources/fleet.py@@ -89,10 +89,16 @@ async def fetch_fleet_report(fetcher) -> dict:- 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.+ 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+ 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+ surge region left unchecked. With all three components unavailable the+ report carries error / reason, readiness_level "UNKNOWN" and+ readiness_score None, so an outage never reads as LOW_ACTIVITY.+ data_gaps also carries each available component's own gaps."""from . import intelligence, military, geospatial@@ -115,29 +121,72 @@ async def fetch_fleet_report(fetcher) -> dict:"theater_posture": posture_data,"vessel_snapshot": vessel_data,}- unavailable = [name for name, data in components.items() if data.get("error")]data_gaps: list[str] = []+ unavailable: list[str] = []for name, data in components.items():if data.get("error"):+ unavailable.append(name)+ data_gaps.append(f"{name}: unavailable ({data['error']})")+ continue+ if data.get("feed_stale") is True:+ # Three 2024 warnings near Hormuz used to score as a critical+ # waterway today.+ unavailable.append(name)data_gaps.append(- f"{name}: unavailable ({data['error']}); readiness_score is "- "computed without it"+ f"{name}: stale (its newest NGA warning was issued "+ f"{data.get('newest_issue_date')}, past the "+ f"{data.get('stale_after_days')}-day threshold)")continuegaps = 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")+ scored = [name for name in components if name not in unavailable]- # Extract key data- theaters = posture_data.get("theaters", {})+ # Extract key data. An unavailable component contributes nothing, and+ # neither does a theater no flight source answered for: its count of 0+ # means unknown.+ theaters = posture_data.get("theaters", {}) if "theater_posture" in scored else {}if not isinstance(theaters, dict):theaters = {}+ no_source = [t for t in posture_data.get("unavailable_theaters") or [] if t in theaters]+ theaters = {name: t for name, t in theaters.items() if name not in no_source}waterways = vessel_data.get("waterways", [])- surges = surge_data.get("surges", [])+ scored_waterways = waterways if "vessel_snapshot" in scored else []+ surges = surge_data.get("surges", []) if "military_surge" in scored else []+ unchecked = (+ (surge_data.get("unchecked_regions") or []) if "military_surge" in scored else []+ )# Compute fleet readiness- readiness_level, readiness_score = _fleet_readiness(theaters, waterways, surges)+ readiness_lower_bound: bool | None+ if not scored:+ readiness_level, readiness_score = "UNKNOWN", None+ readiness_lower_bound = None+ data_gaps.append(+ "readiness_level is UNKNOWN and readiness_score is null: no component "+ "was available to score"+ )+ else:+ readiness_level, readiness_score = _fleet_readiness(+ theaters, scored_waterways, surges+ )+ left_out = list(unavailable)+ if no_source:+ left_out.append(f"the aircraft of {', '.join(no_source)}")+ if unchecked:+ left_out.append(f"surges in {', '.join(unchecked)}")+ readiness_lower_bound = bool(left_out)+ if left_out:+ gap = (+ "readiness_level and readiness_score are lower bounds: they "+ f"leave out {'; '.join(left_out)}"+ )+ if unavailable:+ # Each component adds at most 30 (see _fleet_readiness).+ gap += f", so the score can reach at most {30 * len(scored)} of 90"+ data_gaps.append(gap)# Theater summary — theaters is {name: {count, countries, top_types, ...}}theater_summary = []@@ -182,6 +231,7 @@ async def fetch_fleet_report(fetcher) -> dict:response = {"readiness_level": readiness_level,"readiness_score": readiness_score,+ "readiness_lower_bound": readiness_lower_bound,"theater_summary": theater_summary,"theater_count": len(theater_summary),"waterway_summary": waterway_summary,@@ -196,16 +246,18 @@ async def fetch_fleet_report(fetcher) -> dict:"source": "fleet-activity-report","timestamp": datetime.now(timezone.utc).isoformat(),}+ if no_source:+ response["unavailable_theaters"] = no_sourceif unavailable:# The zeroed fields above stay for consumers that read them;# these say which inputs they lack.response["unavailable_components"] = unavailableresponse["degraded"] = True- if len(unavailable) == len(components):+ if not scored:response["error"] = "All fleet report components unavailable: " + ", ".join(unavailable)response["reason"] = "fleet_components_unavailable"- elif any(data.get("degraded") for data in components.values()):+ elif readiness_lower_bound or any(data.get("degraded") for data in components.values()):response["degraded"] = Truereturn responsediff --git a/src/world_intel_mcp/sources/intelligence.py b/src/world_intel_mcp/sources/intelligence.pyindex a7a4834..e440b8f 100644--- a/src/world_intel_mcp/sources/intelligence.py+++ b/src/world_intel_mcp/sources/intelligence.py@@ -1490,30 +1490,58 @@ async def fetch_military_surge(fetcher: Fetcher) -> dict:2. Build temporal baselines for each region3. Run analysis.surge.detect_surges()+ A theater that no military flight source answered for (posture's+ unavailable_theaters) has unknown traffic, not zero: its regions go+ unchecked and nothing is recorded in their baselines. With the posture+ itself unavailable the response is an error.+Args:fetcher: Shared HTTP fetcher with caching and circuit breaking.Returns:- Dict with surges list, regions checked, source, and timestamp.+ Dict with surges list, regions checked, data_gaps, source, and+ timestamp; unchecked_regions and degraded when some theaters had no+ source; error / degraded / reason when the posture is unavailable."""now = datetime.now(timezone.utc)from . import military as mil_mod+ from ..analysis.surge import _THEATER_REGION_MAPposture = await mil_mod.fetch_theater_posture(fetcher)+ if posture.get("error"):+ # An outage used to record a zero in every region's baseline and+ # report no surges, the reading of an empty sky.+ return {+ "surges": [],+ "surge_count": 0,+ "regions_checked": 0,+ "data_gaps": [+ f"theater posture unavailable ({posture['error']}): no region was "+ "checked and nothing was recorded in the surge baselines"+ ],+ "error": f"Theater posture unavailable: {posture['error']}",+ "degraded": True,+ "reason": posture.get("reason") or "theater_posture_unavailable",+ "source": "military-surge-detection",+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),+ }theater_data = posture.get("theaters", {})+ unavailable_theaters = set(posture.get("unavailable_theaters") or [])# Build temporal baselines for each regiontemporal_baselines: dict[str, dict] = {}+ unchecked: list[str] = []for region_name in SENSITIVE_REGIONS:- # Record total aircraft count in the region's matching theaters- total = 0- from ..analysis.surge import _THEATER_REGION_MAP-- for theater_name, mapped_regions in _THEATER_REGION_MAP.items():- if region_name in mapped_regions:- total += theater_data.get(theater_name, {}).get("count", 0)+ theaters = [+ name for name, regions in _THEATER_REGION_MAP.items() if region_name in regions+ ]+ if unavailable_theaters.intersection(theaters):+ unchecked.append(region_name)+ continue+ # Record total aircraft count in the region's matching theaters+ total = sum(theater_data.get(name, {}).get("count", 0) for name in theaters)result = _temporal.record_and_check("surge_aircraft", region_name, total)if result is not None:temporal_baselines[region_name] = {@@ -1523,13 +1551,23 @@ async def fetch_military_surge(fetcher: Fetcher) -> dict:surges = detect_surges(theater_data, temporal_baselines)- return {+ response = {"surges": surges,"surge_count": len(surges),- "regions_checked": len(SENSITIVE_REGIONS),+ "regions_checked": len(SENSITIVE_REGIONS) - len(unchecked),+ "data_gaps": [],"source": "military-surge-detection","timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),}+ if unchecked:+ response["unchecked_regions"] = unchecked+ response["degraded"] = True+ response["data_gaps"].append(+ "no military flight source answered for "+ f"{', '.join(sorted(unavailable_theaters))}, so {', '.join(unchecked)} "+ "went unchecked and nothing was recorded in their baselines"+ )+ return response# ---------------------------------------------------------------------------@@ -1549,32 +1587,23 @@ _NAVAL_KEYWORDS = re.compile(# 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"),-}-+# A warning that states no readable position is credited to no waterway,+# whatever its area code. Crediting one by NAVAREA (IV and XII both contain+# the Panama Canal) gave Panama warnings from Hawaii, California and+# Virginia: all 5 such credits in the 2026-10-17 capture were wrong, and+# none of the 200 among the 3,480 warnings of 2024 named Panama. Requiring+# the name would not fix it: 4:2024-468 names "PANAMA CITY", in Florida._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."+ "A warning is credited to a waterway only when a position stated in its "+ "text (read in full, before the 500-character cut) lies within "+ "proximity_km of the waterway's reference point. A warning that states "+ "no readable position is credited to no waterway: its area code names "+ "at least a whole NAVAREA (area_codes), far wider than proximity_km. "+ "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. "+ "total_nearby counts credited warnings of any topic.")@@ -1582,14 +1611,16 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:"""Naval activity snapshot at strategic waterways using NGA warnings.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).+ keywords. Each warning is credited only to the STRATEGIC_WATERWAYS+ within _WATERWAY_PROXIMITY_KM of a position it states; one that states+ no readable position is credited nowhere and, if naval, listed in+ unplaced_naval_warnings. The response states the rule (matching_rule).Before 2026-10-17 every warning counted at all nine waterways, so threenaval 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.+ 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.Note: Real-time AIS requires paid API. This uses NGA MSI as afree proxy for naval activity indicators.@@ -1599,9 +1630,9 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:Returns: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.+ any topic credited to it, and status_as_of), the matching rule,+ naval warnings no rule could place, the feed's newest issue date,+ feed_stale, data_gaps, source, and timestamp."""now = datetime.now(timezone.utc)@@ -1610,10 +1641,10 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:nav_data = await maritime.fetch_nav_warnings(fetcher)all_warnings = nav_data.get("warnings", []) or []feed_error = nav_data.get("error")+ feed_stale = nav_data.get("feed_stale") is Truecredited: dict[str, dict] = {- ww["name"]: {"naval": [], "nearby": {"proximity": 0, "navarea": 0}}- for ww in STRATEGIC_WATERWAYS+ ww["name"]: {"naval": [], "nearby": 0} for ww in STRATEGIC_WATERWAYS}unplaced_naval: list[dict] = []naval_total = 0@@ -1623,11 +1654,18 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict: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)+ if isinstance(warning.get("positions"), list):+ # fetch_nav_warnings read these from the full text, before the+ # 500-character cut that used to hide later positions.+ positions = [(p[0], p[1]) for p in warning["positions"]]+ states_position = bool(positions) or bool(warning.get("mentions_position"))+ else:+ positions = maritime.extract_positions(text)+ states_position = maritime.mentions_position(text)+ if len(text) > maritime._MAX_TEXT_LENGTH and text.endswith("..."):+ truncated += 1- matches: list[tuple[str, str, float | None]] = []+ matches: list[tuple[str, float]] = []if positions:for ww in STRATEGIC_WATERWAYS:distance = min(@@ -1635,38 +1673,33 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:for lat, lon in positions)if distance <= _WATERWAY_PROXIMITY_KM:- matches.append((ww["name"], "proximity", round(distance, 1)))- else:+ matches.append((ww["name"], round(distance, 1)))+ elif is_naval: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"+ if states_position:+ # Its only stated positions are malformed or not points.+ reason = "position_unreadable"elif area is None:- unplaced_reason = "unknown_area_code"- elif not area["single_navarea"]:- unplaced_reason = "multi_navarea_series"+ reason = "unknown_area_code"+ elif area["single_navarea"]:+ # One NAVAREA (XII) is still an ocean wide.+ reason = "navarea_too_broad"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],- }- )+ reason = "multi_navarea_series"+ 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": reason,+ "text_snippet": text[:200],+ }+ )- for name, basis, distance in matches:+ for name, distance in matches:entry = credited[name]- entry["nearby"][basis] += 1+ entry["nearby"] += 1if is_naval:entry["naval"].append({@@ -1674,7 +1707,7 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:"text_snippet": text[:200],"navarea": warning.get("navarea"),"issue_date": warning.get("issue_date"),- "match": basis,+ "match": "proximity","distance_km": distance,})@@ -1683,15 +1716,16 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> 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),- )+ # Nearest stated positions first.+ naval_warnings = sorted(entry["naval"], key=lambda d: d["distance_km"])naval_count = len(naval_warnings)if feed_error:status = "unknown"+ elif feed_stale:+ # A frozen feed's warnings describe its last update, not today:+ # three 2024 warnings near Hormuz used to read "critical".+ status = "stale"elif naval_count >= 3:status = "critical"elif naval_count >= 2:@@ -1709,25 +1743,30 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:"throughput": ww.get("throughput"),"naval_warnings": naval_count,"status": status,+ "status_as_of": nav_data.get("newest_issue_date"),"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")- },+ "total_nearby": entry["nearby"],+ "nearby_by_match": {"proximity": entry["nearby"]},+ "naval_by_match": {"proximity": naval_count},})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 feed_stale and not feed_error:+ data_gaps.append(+ "every waterway reads stale, not a threat level: naval_warnings "+ "counts warnings from a feed last updated "+ f"{nav_data.get('newest_issue_date')} (status_as_of)"+ )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)+ f"{len(unplaced_naval)} naval warning(s) state no readable position, "+ "so no waterway is credited with them (unplaced_naval_warnings): "+ + ", ".join(+ f"{maritime._warning_label(w)} ({w['reason']})" for w in unplaced_naval+ ))if truncated:data_gaps.append(@@ -1744,12 +1783,12 @@ async def fetch_vessel_snapshot(fetcher: Fetcher) -> dict:"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"),+ "feed_stale": nav_data.get("feed_stale"),"data_gaps": data_gaps,"source": "nga-msi-vessel-snapshot","timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),diff --git a/src/world_intel_mcp/sources/maritime.py b/src/world_intel_mcp/sources/maritime.pyindex 2b99091..a722d28 100644--- a/src/world_intel_mcp/sources/maritime.py+++ b/src/world_intel_mcp/sources/maritime.py@@ -7,7 +7,7 @@ No API key required.import loggingimport re-from datetime import datetime, timezone+from datetime import datetime, timedelta, timezonefrom ..fetcher import Fetcher@@ -44,8 +44,11 @@ NAVAREAS = {# 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.+# 4, 12 that endpoint names them NAVAREA IV and NAVAREA XII. 12 carries+# only XII (single_navarea True). 4 also carries Canadian Arctic+# warnings: live 4:2023-808 "HUDSON BAY. CANADA." names "NAVAREA+# XVIII 56/23" in its authority field (2026-10-17 capture), so+# XVIII is listed for it and single_navarea is False.# 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@@ -67,8 +70,8 @@ NGA_AREA_CODES: dict[str, dict] = {"4": {"series": "NAVAREA IV","navareas": ("IV",),- "unlisted_navareas": (),- "single_navarea": True,+ "unlisted_navareas": ("XVIII",),+ "single_navarea": False,},"12": {"series": "NAVAREA XII",@@ -103,6 +106,11 @@ NGA_AREA_CODES: dict[str, dict] = {# (HYDROARC, the slowest), so 14 days is twice the slowest series' worst gap.STALE_AFTER_DAYS = 14+# An issue date further ahead than this is a typo (one "MAY 2042" among+# 2024 warnings used to make a frozen feed read 5,684 days fresh), so it is+# left out of the freshness check and named in data_gaps.+_FUTURE_TOLERANCE = timedelta(days=1)+_MAX_TEXT_LENGTH = 500@@ -126,6 +134,8 @@ def _extract_coords(text: str) -> tuple[float | None, float | None]:"""Extract first lat/lon pair from NGA warning text.Parses formats like '22-16.65N 097-44.48W' into decimal degrees.+ Degrees-minutes only and unvalidated; _parse_warning takes its lat/lon+ from extract_positions instead."""m = _COORD_RE.search(text)if not m:@@ -139,57 +149,73 @@ 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])",+# 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.+_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])")+# Any single latitude or longitude ('24-30N', '080-00W', '65-07.80 S'),+# paired or not: a warning that gives its area as latitude bands or+# meridians does state a position, just not one point.+_COORD_TOKEN_RE = re.compile(+ r"(?<![\d.-])\d{1,3}-\d{1,2}(?:\.\d+)?(?:-\d{1,2}(?:\.\d+)?)?\s*[NSEW]\b"+)+++def _decimal_degrees(degrees: str, minutes: str, seconds: str | None) -> float | None:+ """Decimal degrees from NGA's degree, minute and optional second fields,+ or None when the fields are malformed: minutes or seconds of 60 or+ more, or decimal minutes followed by seconds."""+ if seconds is None:+ whole_minutes = float(minutes)+ if whole_minutes >= 60:+ return None+ return int(degrees) + whole_minutes / 60+ if "." in minutes or int(minutes) >= 60 or float(seconds) >= 60:+ return None+ return int(degrees) + int(minutes) / 60 + float(seconds) / 3600+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.+ Reads degrees-minutes ('22-16.65N 097-44.48W'),+ degrees-minutes-seconds ('20-03-44N 072-58-02W') and the two mixed,+ with whitespace, a comma or a slash between latitude and longitude. 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:+ positions: list[tuple[float, float]] = []+ for m in _POSITION_RE.finditer(text):+ lat = _decimal_degrees(m.group(1), m.group(2), m.group(3))+ lon = _decimal_degrees(m.group(5), m.group(6), m.group(7))+ if lat is None or lon is None or lat > 90 or lon > 180: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)+ positions.append(+ (+ round(-lat if m.group(4) == "S" else lat, 4),+ round(-lon if m.group(8) == "W" else lon, 4),+ ))- found.sort()- return [- (round(lat, 4), round(lon, 4))- for _, lat, lon in found- if abs(lat) <= 90 and abs(lon) <= 180- ]+ return positionsdef 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))+ """True when the text holds any latitude or longitude, readable or not,+ so a warning whose only stated position is malformed (a live 2023+ HYDROPAC text gives '10-52.0N 154-84.0W') or given as bands ('BETWEEN+ 24-30N AND 25-00N, WEST OF 080-00W') is not mistaken for one that+ states no position at all."""+ return bool(_COORD_TOKEN_RE.search(text))_ISSUE_DATE_RE = re.compile(r"^(\d{2})(\d{2})(\d{2})Z\s+([A-Z]{3})\s+(\d{4})$")@@ -228,17 +254,64 @@ def _parse_issue_date(value: object) -> datetime | None: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- ]+def _freshness(+ warnings: list[dict], now: datetime+) -> tuple[str | None, float | None, list[dict]]:+ """(newest issue date as ISO 8601, its age in days, future-dated+ warnings) over the warnings whose issue date parses. A date more than+ _FUTURE_TOLERANCE ahead of now is left out of the newest date and+ returned in the third item; (None, None, ...) when no date is usable."""+ dates: list[datetime] = []+ future: list[dict] = []+ for w in warnings:+ issued = _parse_issue_date(w.get("issue_date"))+ if issued is None:+ continue+ if issued - now > _FUTURE_TOLERANCE:+ future.append(w)+ else:+ dates.append(issued)if not dates:- return None, None+ return None, None, futurenewest = max(dates)age_days = (now - newest).total_seconds() / 86400- return newest.strftime("%Y-%m-%dT%H:%M:%SZ"), round(age_days, 1)+ return newest.strftime("%Y-%m-%dT%H:%M:%SZ"), round(age_days, 1), future+++def _warning_label(warning: dict) -> str:+ """'<area code>:<id>' for data_gaps text. The id alone is ambiguous:+ NGA numbers each series separately, so one YEAR-NUMBER can name two+ active warnings (live 2024-12 is both a NAVAREA IV and a HYDROPAC one)."""+ return f"{warning.get('navarea') or '?'}:{warning.get('id')}"+++# navarea filter values, mapped to the NGA area code each selects: the code+# itself, its series name from the navareas endpoint, and the Roman numeral+# of the two NAVAREAs that have a code of their own. The API sends only the+# codes, so the numerals the tool documented used to match nothing.+_NAVAREA_FILTER_CODES: dict[str, str] = {+ **{code: code for code in NGA_AREA_CODES},+ **{entry["series"]: code for code, entry in NGA_AREA_CODES.items()},+ "IV": "4",+ "XII": "12",+}+++def _navarea_not_carried(requested: str) -> str:+ """data_gaps text for a navarea filter value that selects no area code."""+ numeral = requested.removeprefix("NAVAREA ")+ carriers = [+ f"{code} ({entry['series']})"+ for code, entry in NGA_AREA_CODES.items()+ if numeral in entry["navareas"] + entry["unlisted_navareas"]+ ]+ if carriers:+ return (+ f"NAVAREA {numeral} has no area code of its own in the NGA feed: its "+ "warnings arrive inside series that also carry other NAVAREAs "+ f"({', '.join(carriers)}; see area_codes)"+ )+ return f"no NGA area code, series or NAVAREA is called {requested!r} (see area_codes)"def area_codes_view() -> dict[str, dict]:@@ -263,11 +336,15 @@ def _parse_warning(warning: dict) -> dict:cancel_date = warning.get("cancelDate")status = "cancelled" if cancel_date else "active"- text = warning.get("text", "") or ""+ full_text = warning.get("text", "") or ""+ # Positions come from the full text: reading them after the cut lost+ # any stated past character 500.+ positions = extract_positions(full_text)+ text = full_textif len(text) > _MAX_TEXT_LENGTH:text = text[:_MAX_TEXT_LENGTH] + "..."- lat, lon = _extract_coords(text)+ lat, lon = positions[0] if positions else (None, None)return {"id": warning_id,@@ -280,6 +357,8 @@ def _parse_warning(warning: dict) -> dict:"authority": warning.get("authority", "NGA"),"lat": lat,"lon": lon,+ "positions": [[p_lat, p_lon] for p_lat, p_lon in positions],+ "mentions_position": mentions_position(full_text),}@@ -295,16 +374,24 @@ async def fetch_nav_warnings(Args:fetcher: Shared HTTP fetcher with caching and circuit breaking.- navarea: Optional NAVAREA identifier (e.g. "IV", "XII") to filter by.+ navarea: Optional NGA area code to filter by ("4", "12", "A", "P",+ "C"), its series name ("HYDROPAC"), or "IV" / "XII" for codes 4+ and 12. A value that selects no area the feed carries returns+ error / reason "navarea_not_carried" and a data_gaps line,+ never a bare count of 0.Returns:- Dict with warnings list, count, per-navarea breakdown, NAVAREA- 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.+ Dict with warnings list (each with every position its full text+ states), count, per-navarea breakdown, NAVAREA definitions, the NGA+ area-code table (area_codes), the newest active warning's issue date+ and age in days, feed_stale, 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 feed whose newest+ active warning is older than STALE_AFTER_DAYS has feed_stale True and+ 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."""cache_label = navarea.upper() if navarea else "all"cache_key = f"maritime:warnings:{cache_label}"@@ -326,6 +413,7 @@ async def fetch_nav_warnings("newest_issue_date": None,"newest_issue_age_days": None,"stale_after_days": STALE_AFTER_DAYS,+ "feed_stale": None,"data_gaps": [],"source": "nga-msi","timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),@@ -385,19 +473,36 @@ async def fetch_nav_warnings(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)]+ # Parse the active warnings into structured format+ feed = [_parse_warning(w) for w in raw_warnings if _is_active(w)]+ warnings = feed# Filter by NAVAREA if specifiedif navarea is not None:- navarea_upper = navarea.upper()- active_raw = [- w for w in active_raw- if str(w.get("navArea", "")).upper() == navarea_upper+ requested = " ".join(navarea.upper().split())+ code = _NAVAREA_FILTER_CODES.get(requested)+ accepted = (+ {value for value, c in _NAVAREA_FILTER_CODES.items() if c == code}+ if code+ else {requested}+ )+ warnings = [+ w for w in feed+ if " ".join(str(w.get("navarea", "")).upper().split()) in accepted]-- # Parse each warning into structured format- warnings = [_parse_warning(w) for w in active_raw]+ response["navarea_filter"] = {"requested": navarea, "area_code": code}+ if code is None and not warnings:+ # "IV" used to return count 0 with no marker, which read as a+ # NAVAREA with no active warnings.+ response.update(+ error=(+ f"navarea {navarea!r} matches no area the NGA feed carries; "+ "filter by an area code (4, 12, A, P, C) or by IV or XII"+ ),+ reason="navarea_not_carried",+ )+ response["data_gaps"].append(_navarea_not_carried(requested))+ return response# Sort by issue date descending (most recent first)def _issue_sort_key(w: dict) -> str:@@ -411,7 +516,10 @@ async def fetch_nav_warnings(na = w.get("navarea", "UNKNOWN")by_navarea[na] = by_navarea.get(na, 0) + 1- newest, age_days = _freshness(warnings, now)+ # Freshness is the feed's, not the filtered slice's: a frozen feed is+ # frozen for every area, and an area with nothing in force used to come+ # back as a count of 0 dated by nothing.+ newest, age_days, future = _freshness(feed, now)response.update(warnings=warnings,count=len(warnings),@@ -419,20 +527,34 @@ async def fetch_nav_warnings(newest_issue_date=newest,newest_issue_age_days=age_days,)- if warnings and newest is None:- response["degraded"] = True+ if future:response["data_gaps"].append(- "no warning carries a parseable issue date, so how current this "- "list is cannot be checked"+ f"{len(future)} warning(s) carry an issue date more than "+ 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))- 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.+ if feed and newest is None: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"- )+ if future:+ response["data_gaps"].append(+ "no warning carries a usable issue date, so how current this "+ "list is cannot be checked"+ )+ else:+ 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:+ response["feed_stale"] = age_days > STALE_AFTER_DAYS+ if response["feed_stale"]:+ # 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 responsediff --git a/src/world_intel_mcp/sources/military.py b/src/world_intel_mcp/sources/military.pyindex 7cc9b0c..dcf81b0 100644--- a/src/world_intel_mcp/sources/military.py+++ b/src/world_intel_mcp/sources/military.py@@ -234,9 +234,12 @@ async def fetch_military_flights(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."""# Primary: adsb.lol (free, dedicated military endpoint, no filtering needed)aircraft = await _fetch_adsblol_military(fetcher)+ adsblol_failed = aircraft is Noneif aircraft is not None and len(aircraft) > 0:# Apply bbox filter client-side if requestedif bbox is not None:@@ -269,12 +272,22 @@ async def fetch_military_flights("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:+ detail = "adsb.lol returned no positioned aircraft and OpenSky failed"return {"aircraft": [],"count": 0,"military_filter": "icao_prefix+callsign","source": "none","timestamp": _utc_now_iso(),+ "error": f"No military flight source available ({detail})",+ "degraded": True,+ "reason": "military_flights_unavailable",}@@ -284,11 +297,19 @@ async def fetch_theater_posture(fetcher: Fetcher) -> dict:Calls fetch_military_flights for each theater in parallel and aggregatesthe results into a per-theater summary.+ A theater that no flight source answered for (fetch_military_flights+ 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.+Args:fetcher: Shared HTTP fetcher with caching and circuit breaking.Returns:- Dict with per-theater summaries, total count, source, and timestamp.+ Dict with per-theater summaries (each with the source that answered),+ total count, data_gaps, source, and timestamp."""# Check cache first to avoid redundant parallel fetches.cached = fetcher.cache.get("military:posture")@@ -313,6 +334,7 @@ async def fetch_theater_posture(fetcher: Fetcher) -> dict:"sample_callsigns": callsigns[:5],"bbox": info["bbox"],"description": info["desc"],+ "source": result.get("source"),})tasks = [@@ -329,10 +351,30 @@ async def fetch_theater_posture(fetcher: Fetcher) -> dict:response = {"theaters": theaters,"total_military_aircraft": total,+ "data_gaps": [],"source": "opensky","timestamp": _utc_now_iso(),}+ # An outage used to come back as zero aircraft in every theater, the+ # reading of an empty sky, and fleet readiness scored it LOW_ACTIVITY.+ unavailable = [name for name, summary in theaters.items() if summary["source"] == "none"]+ if unavailable:+ response["unavailable_theaters"] = unavailable+ response["degraded"] = True+ response["data_gaps"].append(+ "neither adsb.lol nor OpenSky returned military flights for "+ f"{', '.join(unavailable)}: their counts are unknown, not zero, and "+ "total_military_aircraft counts only the other theaters"+ )+ if len(unavailable) == len(theaters):+ response["error"] = (+ "No military flight source available for any theater "+ "(neither adsb.lol nor OpenSky returned military flights)"+ )+ response["reason"] = "military_flights_unavailable"+ return response+fetcher.cache.set("military:posture", response, 300)return responsediff --git a/src/world_intel_mcp/tests/test_fleet_honesty.py b/src/world_intel_mcp/tests/test_fleet_honesty.pynew file mode 100644index 0000000..438e42a--- /dev/null+++ b/src/world_intel_mcp/tests/test_fleet_honesty.py@@ -0,0 +1,494 @@+"""Tests for the second maritime-honesty review (2026-10-17), fleet side:+an outage never reads as LOW_ACTIVITY (M1), a frozen NGA feed is not+scored as current (M2), military flights, theater posture and surge+detection say when no flight source answered, and the two-components-down+mutant (F2) that+survived the first round.++Components are monkeypatched at the sibling-module boundary, except in+the all-upstream-outage test, which runs the real posture, surge and+snapshot code against respx-mocked NGA, adsb.lol and OpenSky 500s.++Gaps / not covered: no live upstream call is made here; a partial+OpenSky outage is driven through a faked fetch_military_flights, not+through rate limiting or a tripped circuit breaker; consumers of posture+other than surge and fleet (strategic posture, temporal anomalies, the+dashboard) are not exercised.+"""++import asyncio as asyncio_mod++import httpx+import pytest+import respx++from world_intel_mcp.analysis.temporal import TemporalBaseline+from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.sources import intelligence, military+from world_intel_mcp.sources.fleet import fetch_fleet_report++_UNKNOWN_LINE = (+ "readiness_level is UNKNOWN and readiness_score is null: no component "+ "was available to score"+)+_NO_FLIGHTS = (+ "No military flight source available for any theater "+ "(neither adsb.lol nor OpenSky returned military flights)"+)+++def _returning(value):+ async def _fake(*args, **kwargs):+ return value++ return _fake+++def _raising(exc: Exception):+ async def _fake(*args, **kwargs):+ raise exc++ return _fake+++async def _no_sleep(*args, **kwargs) -> None:+ return None+++def _patch_components(monkeypatch, posture, vessels, surge) -> None:+ monkeypatch.setattr(military, "fetch_theater_posture", posture)+ monkeypatch.setattr(intelligence, "fetch_vessel_snapshot", vessels)+ monkeypatch.setattr(intelligence, "fetch_military_surge", surge)+++_HORMUZ_CRITICAL = {+ "waterways": [{"name": "Strait of Hormuz", "status": "critical", "naval_warnings": 3}]+}+_PERSIAN_GULF_SURGE = {+ "surges": [{"region": "persian_gulf", "aircraft_count": 9, "baseline": 3, "ratio": 3.0}]+}+++# ---------------------------------------------------------------------------+# M1: fleet readiness with components down+# ---------------------------------------------------------------------------+++async def test_all_components_down_reads_unknown_not_low_activity(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Regression (M1): with every component down the report carried an+ error but still read LOW_ACTIVITY with score 0, the reading of a quiet+ fleet."""+ boom = _raising(RuntimeError("component down"))+ _patch_components(monkeypatch, boom, boom, boom)++ result = await fetch_fleet_report(fetcher)++ assert result["readiness_level"] == "UNKNOWN"+ assert result["readiness_score"] is None+ assert result["readiness_lower_bound"] is None+ assert result["error"] == (+ "All fleet report components unavailable: "+ "military_surge, theater_posture, vessel_snapshot"+ )+ assert result["reason"] == "fleet_components_unavailable"+ assert result["data_gaps"] == [+ f"{name}: unavailable (RuntimeError: component down)"+ for name in ("military_surge", "theater_posture", "vessel_snapshot")+ ] + [_UNKNOWN_LINE]+++async def test_one_component_down_makes_the_level_a_lower_bound(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Regression (M1): with posture down the score lost its aircraft term+ (at most 60 of 90, so HIGH_ACTIVITY was out of reach) and nothing said+ the level could only be higher."""+ _patch_components(+ monkeypatch,+ _raising(TimeoutError("opensky timed out")),+ _returning(_HORMUZ_CRITICAL),+ _returning(_PERSIAN_GULF_SURGE),+ )++ result = await fetch_fleet_report(fetcher)++ assert result["readiness_score"] == 45+ assert result["readiness_level"] == "ELEVATED_ACTIVITY"+ assert result["readiness_lower_bound"] is True+ assert result["unavailable_components"] == ["theater_posture"]+ assert result["data_gaps"] == [+ "theater_posture: unavailable (TimeoutError: opensky timed out)",+ "readiness_level and readiness_score are lower bounds: they leave out "+ "theater_posture, so the score can reach at most 60 of 90",+ ]+ assert "error" not in result+++async def test_a_complete_report_is_not_a_lower_bound(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ _patch_components(+ monkeypatch,+ _returning({"theaters": {"european": {"count": 4}}}),+ _returning(_HORMUZ_CRITICAL),+ _returning(_PERSIAN_GULF_SURGE),+ )++ result = await fetch_fleet_report(fetcher)++ assert result["readiness_score"] == 47+ assert result["readiness_lower_bound"] is False+ assert result["data_gaps"] == []+ assert "degraded" not in result+++async def test_two_components_down_is_degraded_not_an_error(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Mutant F2 (error set at 2 of 3 components down) survived: no test+ took exactly two components down."""+ boom = _raising(RuntimeError("component down"))+ _patch_components(monkeypatch, boom, _returning(_HORMUZ_CRITICAL), boom)++ result = await fetch_fleet_report(fetcher)++ assert "error" not in result+ assert "reason" not in result+ assert result["degraded"] is True+ assert result["unavailable_components"] == ["military_surge", "theater_posture"]+ assert result["waterway_summary"] == [+ {"name": "Strait of Hormuz", "status": "critical", "warning_count": 3}+ ]+++async def test_theaters_without_a_flight_source_are_left_out_not_zero(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ posture = {+ "theaters": {+ "european": {"count": 20, "source": "opensky"},+ "arctic": {"count": 0, "source": "none"},+ },+ "unavailable_theaters": ["arctic"],+ "degraded": True,+ "data_gaps": ["no flights for arctic"],+ }+ _patch_components(+ monkeypatch,+ _returning(posture),+ _returning({"waterways": []}),+ _returning({"surges": [], "unchecked_regions": ["arctic"], "degraded": True,+ "data_gaps": ["arctic unchecked"]}),+ )++ result = await fetch_fleet_report(fetcher)++ assert [t["name"] for t in result["theater_summary"]] == ["european"]+ assert result["total_tracked_aircraft"] == 20+ assert result["unavailable_theaters"] == ["arctic"]+ assert result["readiness_score"] == 10+ assert result["readiness_lower_bound"] is True+ assert result["degraded"] is True+ assert result["data_gaps"] == [+ "military_surge: arctic unchecked",+ "theater_posture: no flights for arctic",+ "readiness_level and readiness_score are lower bounds: they leave out "+ "the aircraft of arctic; surges in arctic",+ ]+ assert "unavailable_components" not in result+++# ---------------------------------------------------------------------------+# M2: a frozen NGA feed is scored like an unavailable one+# ---------------------------------------------------------------------------+++async def test_a_stale_vessel_snapshot_is_not_scored(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Regression (M2): three 2024 warnings near Hormuz scored as a+ critical waterway in today's readiness."""+ stale_snapshot = {+ **_HORMUZ_CRITICAL,+ "feed_stale": True,+ "newest_issue_date": "2024-05-10T15:15:00Z",+ "stale_after_days": 14,+ "degraded": True,+ "data_gaps": ["NGA feed: stale"],+ }+ _patch_components(+ monkeypatch,+ _returning({"theaters": {"european": {"count": 20}}}),+ _returning(stale_snapshot),+ _returning({"surges": []}),+ )++ result = await fetch_fleet_report(fetcher)++ assert result["readiness_score"] == 10+ assert result["readiness_level"] == "LOW_ACTIVITY"+ assert result["readiness_lower_bound"] is True+ assert result["unavailable_components"] == ["vessel_snapshot"]+ assert result["data_gaps"] == [+ "vessel_snapshot: stale (its newest NGA warning was issued "+ "2024-05-10T15:15:00Z, past the 14-day threshold)",+ "readiness_level and readiness_score are lower bounds: they leave out "+ "vessel_snapshot, so the score can reach at most 60 of 90",+ ]+ # The waterway still shows what the snapshot said.+ assert result["waterway_summary"][0]["warning_count"] == 3+ assert "error" not in result+++# ---------------------------------------------------------------------------+# Military flights, theater posture and surge: no flight source is unknown,+# not zero+# ---------------------------------------------------------------------------++_ADSBLOL = r".*api\.adsb\.lol.*"+_OPENSKY = r".*opensky-network\.org.*"+++async def test_military_flights_with_both_sources_down_is_an_error(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Regression: with adsb.lol and OpenSky both down the result was an+ empty sky, count 0, told apart only by source "none"."""+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)+ 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["error"] == (+ "No military flight source available (adsb.lol and OpenSky both failed)"+ )+ assert result["degraded"] is True+ assert result["reason"] == "military_flights_unavailable"+ # The keys consumers already read are kept as they were.+ assert result["source"] == "none"+ assert result["aircraft"] == []+ assert result["count"] == 0+ assert result["military_filter"] == "icao_prefix+callsign"+++async def test_military_flights_names_an_empty_adsblol_answer(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)+ respx.get(url__regex=_ADSBLOL).mock(return_value=httpx.Response(200, json={"ac": []}))+ respx.get(url__regex=_OPENSKY).mock(return_value=httpx.Response(500))++ result = await military.fetch_military_flights(fetcher)++ assert result["error"] == (+ "No military flight source available "+ "(adsb.lol returned no positioned aircraft and OpenSky failed)"+ )+ assert result["reason"] == "military_flights_unavailable"+ assert result["source"] == "none"+++async def test_military_flights_zero_in_a_box_from_a_live_source_is_not_an_error(+ fetcher: Fetcher,+) -> None:+ """A live answer with no aircraft inside the box is a real zero."""+ respx.get(url__regex=_ADSBLOL).mock(+ return_value=httpx.Response(+ 200, json={"ac": [{"hex": "ae1234", "flight": "RCH1", "lat": 50.0, "lon": 10.0}]}+ )+ )+ opensky = respx.get(url__regex=_OPENSKY).mock(return_value=httpx.Response(500))++ result = await military.fetch_military_flights(fetcher, bbox="-10,95,55,155")++ assert result["count"] == 0+ assert result["source"] == "adsb.lol"+ assert not {"error", "degraded", "reason"} & set(result)+ assert not opensky.called+++def _flights(no_source: set[str]):+ async def _fake(fetcher, bbox=None):+ name = next(n for n, info in military.THEATERS.items() if info["bbox"] == bbox)+ if name in no_source:+ return {+ "aircraft": [],+ "count": 0,+ "source": "none",+ "error": "No military flight source available (adsb.lol and OpenSky both failed)",+ "degraded": True,+ "reason": "military_flights_unavailable",+ }+ aircraft = [{"callsign": "RCH1", "origin_country": "United States"}]+ return {"aircraft": aircraft, "count": 1, "source": "adsb.lol"}++ return _fake+++async def test_posture_names_theaters_no_flight_source_answered_for(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Regression (M1): a theater no flight source answered for came back+ as zero aircraft, the reading of an empty sky."""+ monkeypatch.setattr(military, "fetch_military_flights", _flights({"arctic", "korean_peninsula"}))++ result = await military.fetch_theater_posture(fetcher)++ assert result["unavailable_theaters"] == ["arctic", "korean_peninsula"]+ assert result["degraded"] is True+ assert "error" not in result+ assert result["total_military_aircraft"] == 3+ assert result["theaters"]["arctic"]["source"] == "none"+ assert result["theaters"]["european"]["source"] == "adsb.lol"+ assert result["data_gaps"] == [+ "neither adsb.lol nor OpenSky returned military flights for arctic, "+ "korean_peninsula: their counts are unknown, not zero, and "+ "total_military_aircraft counts only the other theaters"+ ]+ # A partial posture is not cached, so it is not replayed after recovery.+ assert fetcher.cache.get("military:posture") is None+++async def test_posture_with_no_flight_source_anywhere_is_an_error(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(military, "fetch_military_flights", _flights(set(military.THEATERS)))++ result = await military.fetch_theater_posture(fetcher)++ assert result["error"] == _NO_FLIGHTS+ assert result["reason"] == "military_flights_unavailable"+ assert result["unavailable_theaters"] == list(military.THEATERS)+ assert fetcher.cache.get("military:posture") is None+++async def test_a_complete_posture_is_cached_with_no_gaps(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(military, "fetch_military_flights", _flights(set()))++ result = await military.fetch_theater_posture(fetcher)++ assert result["data_gaps"] == []+ assert "degraded" not in result+ assert "unavailable_theaters" not in result+ assert fetcher.cache.get("military:posture") == result+++def _baseline_keys(baseline: TemporalBaseline) -> list[str]:+ return [row[0] for row in baseline._conn.execute("SELECT key FROM baselines")]+++async def test_surge_with_posture_down_is_an_error_and_records_nothing(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """Regression (M1): a posture outage recorded a zero in every region's+ surge baseline and reported no surges, the reading of an empty sky."""+ baseline = TemporalBaseline(db_path=str(tmp_path / "t.db"))+ monkeypatch.setattr(intelligence, "_temporal", baseline)+ monkeypatch.setattr(+ military,+ "fetch_theater_posture",+ _returning({"theaters": {}, "error": _NO_FLIGHTS, "reason": "military_flights_unavailable"}),+ )++ result = await intelligence.fetch_military_surge(fetcher)++ assert result["error"] == f"Theater posture unavailable: {_NO_FLIGHTS}"+ assert result["reason"] == "military_flights_unavailable"+ assert result["degraded"] is True+ assert result["regions_checked"] == 0+ assert result["surges"] == []+ assert _baseline_keys(baseline) == []+++async def test_surge_skips_regions_whose_theater_had_no_source(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ baseline = TemporalBaseline(db_path=str(tmp_path / "t.db"))+ monkeypatch.setattr(intelligence, "_temporal", baseline)+ monkeypatch.setattr(+ military,+ "fetch_theater_posture",+ _returning(+ {+ "theaters": {+ "european": {"count": 40, "countries": ["United States"]},+ "arctic": {"count": 0, "countries": [], "source": "none"},+ },+ "unavailable_theaters": ["arctic"],+ }+ ),+ )++ result = await intelligence.fetch_military_surge(fetcher)++ assert result["unchecked_regions"] == ["arctic"]+ assert result["regions_checked"] == 7+ assert result["degraded"] is True+ assert result["data_gaps"] == [+ "no military flight source answered for arctic, so arctic went "+ "unchecked and nothing was recorded in their baselines"+ ]+ assert [s["region"] for s in result["surges"]] == ["baltic_sea"]+ keys = _baseline_keys(baseline)+ assert len(keys) == 7+ assert not any(":arctic:" in key for key in keys)+ assert "error" not in result+++async def test_every_upstream_down_reads_unknown_through_the_real_components(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch, tmp_path+) -> None:+ """Regression (M1, measured by the reviewer with a real Fetcher): NGA,+ adsb.lol and OpenSky all failing gave LOW_ACTIVITY, score 0, zero+ aircraft and no error, because posture and surge turned the outage into+ zero aircraft and only the snapshot reported it."""+ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)+ monkeypatch.setattr(+ intelligence, "_temporal", TemporalBaseline(db_path=str(tmp_path / "t.db"))+ )+ for host in (r"msi\.nga\.mil", r"api\.adsb\.lol", r"opensky-network\.org"):+ respx.get(url__regex=rf".*{host}.*").mock(return_value=httpx.Response(500))++ result = await fetch_fleet_report(fetcher)++ assert result["readiness_level"] == "UNKNOWN"+ assert result["readiness_score"] is None+ assert result["error"] == (+ "All fleet report components unavailable: "+ "military_surge, theater_posture, vessel_snapshot"+ )+ assert result["data_gaps"] == [+ f"military_surge: unavailable (Theater posture unavailable: {_NO_FLIGHTS})",+ f"theater_posture: unavailable ({_NO_FLIGHTS})",+ "vessel_snapshot: unavailable (NGA navigational warnings unavailable: "+ "NGA MSI API unavailable (no live or cached data))",+ _UNKNOWN_LINE,+ ]+ assert result["total_tracked_aircraft"] == 0+ assert result["theater_summary"] == []+ assert {ww["status"] for ww in result["waterway_summary"]} == {"unknown"}+ assert fetcher.cache.get("military:posture") is Nonediff --git a/src/world_intel_mcp/tests/test_maritime_honesty.py b/src/world_intel_mcp/tests/test_maritime_honesty.pynew file mode 100644index 0000000..bf6092e--- /dev/null+++ b/src/world_intel_mcp/tests/test_maritime_honesty.py@@ -0,0 +1,704 @@+"""Tests for the second maritime-honesty review (2026-10-17): NAVAREA+credits (H1), the frozen feed (M2), the navarea filter (M3), positions and+dates (L1-L4), the report and CLI surfaces, and the mutants that survived+the first round (I2, M5, M6, M9).++NGA records are built in the live API's shape (msgYear, msgNumber,+navArea, text, issueDate, cancelDate); texts marked "live" are verbatim+from the 2026-10-17 capture, the others are constructed. The real+fetch_nav_warnings and fetch_vessel_snapshot run against a respx-mocked+NGA endpoint.++Gaps / not covered: no live NGA call is made here; the 300 km radius is a+chosen value tested at its boundary, not validated against chokepoint+geometry; positions written with a space between degrees and minutes+('25 30.00N') are not read, and no test claims they are; the dashboard and+collector, which also read these outputs, are not exercised.+"""++import asyncio as asyncio_mod+import math+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.config.countries import STRATEGIC_WATERWAYS+from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.reports import _render_maritime+from world_intel_mcp.sources import intelligence, maritime+from world_intel_mcp.sources.intelligence import _haversine_km++_MONTHS = "JAN FEB MAR APR MAY JUN JUL AUG SEP OCT NOV DEC".split()+_NGA_URL = r".*msi\.nga\.mil.*"+++def _stamp(when: datetime) -> str:+ """An NGA issue date ('101515Z MAY 2024')."""+ return f"{when:%d%H%M}Z {_MONTHS[when.month - 1]} {when.year}"+++def _ago(**delta: float) -> str:+ return _stamp(datetime.now(timezone.utc) - timedelta(**delta))+++def _iso(stamp: str) -> str:+ return maritime._parse_issue_date(stamp).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _record(year: int, number: int, area: str, text: str, issued: str) -> dict:+ return {+ "msgYear": year, "msgNumber": number, "navArea": area,+ "subregion": "00", "text": text, "status": "A",+ "issueDate": issued, "authority": "NAVSAFETY", "cancelDate": None,+ }+++def _mock_nga(records: list[dict]) -> None:+ respx.get(url__regex=_NGA_URL).mock(+ return_value=httpx.Response(200, json={"broadcast-warn": records})+ )+++def _by_name(result: dict) -> dict[str, dict]:+ return {ww["name"]: ww for ww in result["waterways"]}+++# ---------------------------------------------------------------------------+# H1: a warning that states no position is credited to no waterway+# ---------------------------------------------------------------------------+++async def test_positionless_navarea_iv_and_xii_warnings_credit_no_waterway(+ fetcher: Fetcher,+) -> None:+ """Regression (H1): NAVAREA IV and XII both contain the Panama Canal, so+ a warning that stated no position in either was credited to Panama.+ All five such credits in the live capture were wrong (Hawaii, California+ and "warnings in force" lists), and a naval one raised Panama's status.+ Requiring the name would not help: 4:2024-468 says "PANAMA CITY", in+ Florida."""+ issued = _ago(hours=2)+ _mock_nga([+ _record(2026, 1, "4", "WESTERN NORTH ATLANTIC.\nNAVAL OPERATIONS IN PROGRESS.\n", issued),+ _record(2026, 2, "12", "EASTERN NORTH PACIFIC.\nMISSILE FIRING IN PROGRESS.\n", issued),+ _record(+ 2026, 3, "4",+ "GULF OF MEXICO.\nFLORIDA.\nROCKET LAUNCHING OPERATIONS\n"+ "VISIBLE FROM:\nC. PENSACOLA.\nD. PANAMA CITY.\n",+ issued,+ ),+ ])++ result = await intelligence.fetch_vessel_snapshot(fetcher)+ panama = _by_name(result)["Panama Canal"]++ assert panama["status"] == "clear"+ assert panama["naval_warnings"] == 0+ assert panama["total_nearby"] == 0+ assert panama["nearby_by_match"] == {"proximity": 0}+ assert {ww["total_nearby"] for ww in result["waterways"]} == {0}+ assert [+ (w["navarea"], w["id"], w["reason"]) for w in result["unplaced_naval_warnings"]+ ] == [+ ("4", "2026-1", "multi_navarea_series"),+ ("12", "2026-2", "navarea_too_broad"),+ ]+ assert result["total_naval_warnings"] == 2+ assert "waterway_navareas" not in result["matching_rule"]+ assert result["data_gaps"] == [+ "2 naval warning(s) state no readable position, so no waterway is "+ "credited with them (unplaced_naval_warnings): "+ "4:2026-1 (multi_navarea_series), 12:2026-2 (navarea_too_broad)"+ ]+++async def test_a_stated_position_still_credits_panama(fetcher: Fetcher) -> None:+ """The positions rule is unchanged: live 4:2024-15 (BUOY NO1, 40.8 km+ from the canal) still counts there, by proximity only."""+ _mock_nga([+ _record(+ 2024, 15, "4",+ "WESTERN CARIBBEAN SEA.\nPANAMA.\nCHART 26060.\n"+ "BUOY NO1 09-25.09N 079-49.50W DESTROYED.\n",+ _ago(hours=2),+ )+ ])++ panama = _by_name(await intelligence.fetch_vessel_snapshot(fetcher))["Panama Canal"]++ assert panama["total_nearby"] == 1+ assert panama["nearby_by_match"] == {"proximity": 1}+ assert panama["naval_by_match"] == {"proximity": 0}+++def test_area_code_4_carries_more_than_navarea_iv() -> None:+ """Regression (H1): code 4 was marked single-NAVAREA, but live+ 4:2023-808 "HUDSON BAY. CANADA." names NAVAREA XVIII as its authority."""+ entry = maritime.NGA_AREA_CODES["4"]+ assert entry["single_navarea"] is False+ assert entry["navareas"] == ("IV",)+ assert entry["unlisted_navareas"] == ("XVIII",)+ assert maritime.area_codes_view()["4"]["single_navarea"] is False+++# ---------------------------------------------------------------------------+# L4: unplaced warnings are named by area code and id+# ---------------------------------------------------------------------------+++async def test_unplaced_gap_names_each_warning_by_area_code_and_id(+ fetcher: Fetcher,+) -> None:+ """Regression (L4): NGA numbers each series separately, so live id+ 2024-12 is both a NAVAREA IV and a HYDROPAC warning; the gap text named+ them by id alone. The id field itself keeps its format."""+ issued = _ago(hours=2)+ _mock_nga([+ _record(2024, 12, "4", "WESTERN NORTH ATLANTIC.\nNAVAL OPERATIONS.\n", issued),+ _record(2024, 12, "P", "NORTH PACIFIC.\nSUBMARINE OPERATIONS.\n", issued),+ ])++ result = await intelligence.fetch_vessel_snapshot(fetcher)++ assert [w["id"] for w in result["unplaced_naval_warnings"]] == ["2024-12", "2024-12"]+ assert result["data_gaps"][-1].endswith(+ "4:2024-12 (multi_navarea_series), P:2024-12 (multi_navarea_series)"+ )+++# ---------------------------------------------------------------------------+# M2: a frozen feed reads stale, per waterway+# ---------------------------------------------------------------------------+++def _hormuz_naval_records(issued: str) -> list[dict]:+ # 11.4, 140.6 and 98.0 km from the Strait of Hormuz.+ return [+ _record(2026, 1, "P", "PERSIAN GULF.\nNAVAL EXERCISE IN 26-30.00N 056-10.00E.\n", issued),+ _record(2026, 2, "P", "GULF OF OMAN.\nLIVE FIRING 25-30.00N 057-00.00E.\n", issued),+ _record(2026, 3, "P", "PERSIAN GULF.\nSUBMARINE OPERATIONS 26-00.00N 055-30.00E.\n", issued),+ ]+++async def test_frozen_feed_marks_every_waterway_stale_with_its_date(+ fetcher: Fetcher,+) -> None:+ """Regression (M2): with the feed past its staleness threshold, three+ naval warnings near Hormuz still read "critical", as if current; only+ the top-level degraded flag said otherwise. The live feed's newest+ warning dates from 10 May 2024."""+ issued = _ago(days=30)+ _mock_nga(_hormuz_naval_records(issued))++ result = await intelligence.fetch_vessel_snapshot(fetcher)+ hormuz = _by_name(result)["Strait of Hormuz"]++ assert {ww["status"] for ww in result["waterways"]} == {"stale"}+ assert {ww["status_as_of"] for ww in result["waterways"]} == {_iso(issued)}+ assert hormuz["naval_warnings"] == 3+ assert result["feed_stale"] is True+ assert result["degraded"] is True+ assert "error" not in result+ assert result["data_gaps"][-1] == (+ "every waterway reads stale, not a threat level: naval_warnings counts "+ f"warnings from a feed last updated {_iso(issued)} (status_as_of)"+ )+++async def test_fresh_feed_scores_waterways_and_says_it_is_not_stale(+ fetcher: Fetcher,+) -> None:+ issued = _ago(hours=2)+ _mock_nga(_hormuz_naval_records(issued))++ result = await intelligence.fetch_vessel_snapshot(fetcher)+ hormuz = _by_name(result)["Strait of Hormuz"]++ assert hormuz["status"] == "critical"+ assert hormuz["status_as_of"] == _iso(issued)+ assert result["feed_stale"] is False+ assert "degraded" not in result+ assert result["data_gaps"] == []+++async def test_feed_stale_is_unknown_when_no_issue_date_parses(fetcher: Fetcher) -> None:+ """feed_stale is the structured form of the staleness gap, and None (not+ False) when no usable issue date says how current the list is."""+ _mock_nga([_record(2026, 1, "A", "BUOY UNLIT.\n", "NOT A DATE")])++ result = await intelligence.fetch_vessel_snapshot(fetcher)++ assert result["feed_stale"] is None+ assert result["degraded"] is True+ assert {ww["status_as_of"] for ww in result["waterways"]} == {None}+++async def test_feed_stale_is_unknown_during_an_outage(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def _no_sleep(*args, **kwargs) -> None:+ return None++ monkeypatch.setattr(asyncio_mod, "sleep", _no_sleep)+ respx.get(url__regex=_NGA_URL).mock(return_value=httpx.Response(500))++ result = await intelligence.fetch_vessel_snapshot(fetcher)++ assert result["feed_stale"] is None+ assert {ww["status"] for ww in result["waterways"]} == {"unknown"}+ assert {ww["status_as_of"] for ww in result["waterways"]} == {None}+++# ---------------------------------------------------------------------------+# M3: the navarea filter takes the values it documents+# ---------------------------------------------------------------------------+++def _one_per_area(issued: str) -> list[dict]:+ return [+ _record(2026, number, area, f"WARNING IN AREA {area}.\n", issued)+ for number, area in enumerate(("4", "12", "A", "P", "C"), start=1)+ ]+++ ("value", "code"),+ [+ ("IV", "4"),+ ("4", "4"),+ ("NAVAREA IV", "4"),+ ("xii", "12"),+ ("12", "12"),+ ("HYDROPAC", "P"),+ ("a", "A"),+ ("hydroarc", "C"),+ ],+)+async def test_navarea_filter_accepts_codes_numerals_and_series_names(+ fetcher: Fetcher, value: str, code: str+) -> None:+ """Regression (M3): the API sends only the codes 4, 12, A, P and C, so+ the documented numerals matched nothing: navarea="IV" returned count 0+ with no marker on a feed holding 71 code-4 warnings."""+ _mock_nga(_one_per_area(_ago(hours=2)))++ result = await maritime.fetch_nav_warnings(fetcher, navarea=value)++ assert [w["navarea"] for w in result["warnings"]] == [code]+ assert result["count"] == 1+ assert result["navarea_filter"] == {"requested": value, "area_code": code}+ assert "error" not in result+++async def test_navarea_filter_value_no_area_carries_is_an_error_not_zero(+ fetcher: Fetcher,+) -> None:+ _mock_nga(_one_per_area(_ago(hours=2)))++ ix = await maritime.fetch_nav_warnings(fetcher, navarea="IX")+ assert ix["error"] == (+ "navarea 'IX' matches no area the NGA feed carries; filter by an area "+ "code (4, 12, A, P, C) or by IV or XII"+ )+ assert ix["reason"] == "navarea_not_carried"+ assert ix["data_gaps"] == [+ "NAVAREA IX has no area code of its own in the NGA feed: its warnings "+ "arrive inside series that also carry other NAVAREAs (P (HYDROPAC); "+ "see area_codes)"+ ]+ assert ix["count"] == 0+ assert ix["navarea_filter"] == {"requested": "IX", "area_code": None}++ bogus = await maritime.fetch_nav_warnings(fetcher, navarea="Z")+ assert bogus["reason"] == "navarea_not_carried"+ assert bogus["data_gaps"] == [+ "no NGA area code, series or NAVAREA is called 'Z' (see area_codes)"+ ]+++async def test_a_carried_area_with_no_active_warnings_is_an_honest_zero(+ fetcher: Fetcher,+) -> None:+ _mock_nga([_record(2026, 1, "A", "WARNING.\n", _ago(hours=2))])++ result = await maritime.fetch_nav_warnings(fetcher, navarea="C")++ assert result["count"] == 0+ assert result["navarea_filter"] == {"requested": "C", "area_code": "C"}+ assert "error" not in result+ assert result["data_gaps"] == []+ assert result["feed_stale"] is False+++async def test_a_filtered_area_on_a_frozen_feed_is_marked_stale(+ fetcher: Fetcher,+) -> None:+ """Regression (M2, M3): freshness was read from the filtered slice, so+ on a frozen feed an area with nothing in force came back as a count of+ 0 with feed_stale null and no gap, and an area's own older warnings+ dated the feed."""+ _mock_nga(+ [+ _record(2024, 1, "A", "WARNING.\n", "101515Z MAY 2024"),+ _record(2024, 2, "P", "WARNING.\n", "011200Z MAR 2024"),+ ]+ )++ arctic = await maritime.fetch_nav_warnings(fetcher, navarea="C")++ assert arctic["count"] == 0+ assert arctic["feed_stale"] is True+ assert arctic["degraded"] is True+ assert arctic["newest_issue_date"] == "2024-05-10T15:15:00Z"+ assert arctic["data_gaps"][0].startswith(+ "newest active warning was issued 2024-05-10T15:15:00Z, "+ )++ pacific = await maritime.fetch_nav_warnings(fetcher, navarea="P")++ assert [w["id"] for w in pacific["warnings"]] == ["2024-2"]+ assert pacific["newest_issue_date"] == "2024-05-10T15:15:00Z"+ assert pacific["feed_stale"] is True+++async def test_a_filtered_area_on_an_undated_feed_says_its_age_is_unknown(+ fetcher: Fetcher,+) -> None:+ _mock_nga([_record(2024, 1, "A", "WARNING.\n", None)])++ result = await maritime.fetch_nav_warnings(fetcher, navarea="C")++ assert result["count"] == 0+ assert result["feed_stale"] 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_nav_warnings_tool_documents_the_area_codes() -> None:+ from world_intel_mcp.tools import infrastructure as infra_tools+ from world_intel_mcp.tools import intelligence as intel_tools++ nav = next(t for t in infra_tools.TOOLS if t.name == "intel_nav_warnings")+ navarea = nav.inputSchema["properties"]["navarea"]["description"]+ assert "4 (NAVAREA IV)" in navarea+ assert "IV and XII are accepted for 4 and 12" in navarea+ assert "I-XVI" not in nav.description+ assert "feed_stale" in nav.description++ snapshot = next(t for t in intel_tools.TOOLS if t.name == "intel_vessel_snapshot")+ for status in ("clear", "advisory", "elevated", "critical", "stale", "unknown"):+ assert status in snapshot.description+ for tool in (nav, snapshot):+ assert "—" not in tool.description+++# ---------------------------------------------------------------------------+# L1, L2: positions read in full and in every notation the feed uses+# ---------------------------------------------------------------------------+++async def test_positions_after_the_500_character_cut_are_read(fetcher: Fetcher) -> None:+ """Regression (L1): positions were read from the text after its cut at+ 500 characters, so a naval warning whose position came later was+ unplaced (or, under NAVAREA IV, credited to Panama)."""+ text = (+ "PERSIAN GULF.\nNAVAL EXERCISE.\n"+ + "VESSELS ARE ADVISED TO KEEP CLEAR OF THE AREA. " * 13+ + "\nIN AREA 26-30.00N 056-10.00E.\n"+ )+ assert text.index("26-30.00N") > maritime._MAX_TEXT_LENGTH+ _mock_nga([_record(2026, 1, "4", text, _ago(hours=2))])++ nav = await maritime.fetch_nav_warnings(fetcher)+ warning = nav["warnings"][0]+ assert warning["text"].endswith("...")+ assert warning["positions"] == [[26.5, 56.1667]]+ assert (warning["lat"], warning["lon"]) == (26.5, 56.1667)+ assert warning["mentions_position"] is True++ result = await intelligence.fetch_vessel_snapshot(fetcher)+ hormuz = _by_name(result)["Strait of Hormuz"]+ assert hormuz["status"] == "advisory"+ assert hormuz["warning_details"][0]["distance_km"] == 11.4+ assert result["unplaced_naval_warnings"] == []+ assert result["data_gaps"] == []+++ ("text", "expected"),+ [+ # Live HYDROLANT 2024-473, 479 and 488 put a comma between them.+ ("ICE 60-17.40S, 050-16.80W.", [(-60.29, -50.28)]),+ ("AREA 25-30.00N/056-10.00E.", [(25.5, 56.1667)]),+ # Mixed notation used to read the '03-44N' as latitude 3.73.+ ("BUOY 20-03-44N 072-58.00W.", [(20.0622, -72.9667)]),+ ("BUOY 20-03.50N 072-58-30W.", [(20.0583, -72.975)]),+ ],+)+def test_positions_with_comma_slash_or_mixed_notation(text: str, expected: list) -> None:+ """Regression (L2)."""+ assert maritime.extract_positions(text) == expected+++def test_a_lone_latitude_or_longitude_counts_as_a_stated_position() -> None:+ """Regression (L2): latitude bands and meridians do state a place, so+ such a warning is unreadable, not positionless."""+ assert maritime.mentions_position("BETWEEN 24-30N AND 25-00N, WEST OF 080-00W.")+ assert maritime.mentions_position("SOUTH OF 65-07.80 S.")+ assert not maritime.mentions_position("NAVAL OPERATIONS IN PROGRESS. CHART 26060.")+ assert maritime.extract_positions("BETWEEN 24-30N AND 25-00N, WEST OF 080-00W.") == []+++async def test_a_warning_given_as_latitude_bands_is_unplaced_as_unreadable(+ fetcher: Fetcher,+) -> None:+ _mock_nga([+ _record(+ 2026, 1, "4",+ "STRAITS OF FLORIDA.\nNAVAL OPERATIONS BETWEEN 24-30N AND 25-00N,\n"+ "WEST OF 080-00W.\n",+ _ago(hours=2),+ )+ ])++ result = await intelligence.fetch_vessel_snapshot(fetcher)++ assert [(w["id"], w["reason"]) for w in result["unplaced_naval_warnings"]] == [+ ("2026-1", "position_unreadable")+ ]+ assert _by_name(result)["Panama Canal"]["status"] == "clear"+++# ---------------------------------------------------------------------------+# L3: a future-dated issue date cannot make a frozen feed look fresh+# ---------------------------------------------------------------------------+++async def test_future_dated_warning_is_left_out_of_the_freshness_check(+ fetcher: Fetcher,+) -> None:+ """Regression (L3): one "MAY 2042" among old warnings made the feed read+ 5,684 days fresh and cleared the staleness flag."""+ old = _ago(days=30)+ _mock_nga([+ _record(2024, 1, "A", "BUOY UNLIT.\n", old),+ _record(2042, 7, "P", "BUOY UNLIT.\n", "101515Z MAY 2042"),+ ])++ result = await maritime.fetch_nav_warnings(fetcher)++ assert result["newest_issue_date"] == _iso(old)+ assert result["feed_stale"] is True+ assert result["degraded"] is True+ assert result["data_gaps"][0] == (+ "1 warning(s) carry an issue date more than 1 day ahead, left out of "+ "the freshness check: P:2042-7 (101515Z MAY 2042)"+ )+ assert "staleness threshold" in result["data_gaps"][1]+++async def test_only_future_dated_warnings_leave_freshness_unknown(+ fetcher: Fetcher,+) -> None:+ _mock_nga([_record(2042, 7, "P", "BUOY UNLIT.\n", "101515Z MAY 2042")])++ result = await maritime.fetch_nav_warnings(fetcher)++ assert result["newest_issue_date"] is None+ assert result["feed_stale"] is None+ assert result["degraded"] is True+ assert result["data_gaps"][1] == (+ "no warning carries a usable issue date, so how current this list is "+ "cannot be checked"+ )+++async def test_an_issue_date_within_a_day_ahead_still_counts(fetcher: Fetcher) -> None:+ """Clock skew of hours is tolerated: such a date is not called a typo."""+ _mock_nga([_record(2026, 1, "A", "BUOY UNLIT.\n", _stamp(datetime.now(timezone.utc) + timedelta(hours=3)))])++ result = await maritime.fetch_nav_warnings(fetcher)++ assert result["newest_issue_date"] is not None+ assert result["feed_stale"] is False+ assert result["data_gaps"] == []+++# ---------------------------------------------------------------------------+# Report and CLI surfaces+# ---------------------------------------------------------------------------+++async def test_report_renders_the_real_vessel_snapshot(fetcher: Fetcher) -> None:+ """Regression: _render_maritime read vessels / snapshot, keys the+ snapshot never emits, so every report said "No maritime data"."""+ issued = _ago(hours=2)+ _mock_nga(_hormuz_naval_records(issued))++ html = _render_maritime(await intelligence.fetch_vessel_snapshot(fetcher))++ assert "No maritime data" not in html+ assert "Strait of Hormuz" in html+ assert '<span class="metric red">critical</span>' in html+ assert "Bosphorus" in html+ assert "STALE" not in html+++def test_report_marks_a_stale_snapshot_and_names_an_outage() -> None:+ stale = {+ "waterways": [{"name": "Strait of Hormuz", "status": "stale", "naval_warnings": 3}],+ "feed_stale": True,+ "newest_issue_date": "2024-05-10T15:15:00Z",+ "data_gaps": ["NGA feed: <old>"],+ }+ html = _render_maritime(stale)+ assert "STALE" in html+ assert "2024-05-10T15:15:00Z" in html+ assert "<li>NGA feed: <old></li>" in html++ down = _render_maritime({"error": "NGA navigational warnings unavailable: x", "waterways": []})+ assert "Maritime data unavailable: NGA navigational warnings unavailable: x" in down+++def _cli_env(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "cli-cache.db"))+ monkeypatch.setenv("COLUMNS", "200")+ monkeypatch.setattr(cli, "_fetcher", None)+++def _invoke(*args: str):+ return CliRunner().invoke(cli.main, list(args), catch_exceptions=False)+++def test_cli_warnings_help_names_the_area_codes(_cli_env) -> None:+ result = _invoke("warnings", "--help")+ assert "4, 12, A, P or C" in result.output+ assert "NAVAREA number" not in result.output+++def test_cli_warnings_prints_staleness_and_gaps(_cli_env) -> None:+ issued = _ago(days=30)+ _mock_nga([_record(2026, 1, "4", "BUOY UNLIT.\n", issued)])++ result = _invoke("warnings", "-n", "IV")++ assert result.exit_code == 0+ assert f"STALE: newest warning issued {_iso(issued)}" in result.output+ assert "1 active warnings" in result.output+ assert "Gap: newest active warning was issued" in result.output+++def test_cli_warnings_names_an_area_the_feed_does_not_carry(_cli_env) -> None:+ _mock_nga([_record(2026, 1, "4", "BUOY UNLIT.\n", _ago(hours=2))])++ result = _invoke("warnings", "-n", "IX")++ assert result.exit_code == 0+ assert "Error: navarea 'IX' matches no area the NGA feed carries" in result.output+ assert "Gap: NAVAREA IX has no area code of its own" in result.output+ assert "0 active warnings" not in result.output+++# ---------------------------------------------------------------------------+# Mutants that survived the first review round+# ---------------------------------------------------------------------------+++async def test_a_position_exactly_at_the_radius_is_credited(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch+) -> None:+ """Mutant I2 (<= to <) survived: no position sat on the boundary."""+ text = "GULF OF OMAN.\nLIVE FIRING 25-30.00N 057-00.00E.\n"+ hormuz = next(ww for ww in STRATEGIC_WATERWAYS if ww["name"] == "Strait of Hormuz")+ ((lat, lon),) = maritime.extract_positions(text)+ boundary = _haversine_km(hormuz["lat"], hormuz["lon"], lat, lon)+ _mock_nga([_record(2026, 1, "P", text, _ago(hours=2))])++ monkeypatch.setattr(intelligence, "_WATERWAY_PROXIMITY_KM", boundary)+ at = await intelligence.fetch_vessel_snapshot(fetcher)+ assert _by_name(at)["Strait of Hormuz"]["naval_warnings"] == 1++ monkeypatch.setattr(intelligence, "_WATERWAY_PROXIMITY_KM", math.nextafter(boundary, 0.0))+ inside = await intelligence.fetch_vessel_snapshot(fetcher)+ assert _by_name(inside)["Strait of Hormuz"]["naval_warnings"] == 0+++def test_dms_fields_of_60_or_more_are_malformed() -> None:+ """Mutant M5 (the DMS >= 60 guard off) survived: no test fed one."""+ assert maritime.extract_positions("BUOY 20-03-75N 072-58-02W MISSING.") == []+ assert maritime.extract_positions("BUOY 20-60-10N 072-58-02W MISSING.") == []+ assert maritime.extract_positions("BUOY 20-03-44N 072-58-60W MISSING.") == []+ assert maritime.extract_positions("BUOY 20-03-44N 072-58-02W MISSING.") == [+ (20.0622, -72.9672)+ ]+++def test_positions_come_back_in_text_order_across_notations() -> None:+ """Mutant M6 (text-order sort removed) survived: no input put a DMS+ position before a degrees-minutes one."""+ text = "A. 13-55-18N 090-47-53W.\nB. 05-30.0S 120-15.0E.\n"+ assert maritime.extract_positions(text) == [(13.9217, -90.7981), (-5.5, 120.25)]+++async def test_a_feed_exactly_at_the_staleness_threshold_is_not_stale(+ fetcher: Fetcher,+) -> None:+ """Mutant M9 (> to >=) survived: no newest warning sat on the threshold."""+ issued = datetime.now(timezone.utc) - timedelta(days=maritime.STALE_AFTER_DAYS)+ _mock_nga([_record(2026, 1, "A", "BUOY UNLIT.\n", _stamp(issued))])++ result = await maritime.fetch_nav_warnings(fetcher)++ assert result["newest_issue_age_days"] == maritime.STALE_AFTER_DAYS+ assert "degraded" not in result+ assert result["data_gaps"] == []diff --git a/src/world_intel_mcp/tools/infrastructure.py b/src/world_intel_mcp/tools/infrastructure.pyindex 6a3ae6a..713c9e8 100644--- a/src/world_intel_mcp/tools/infrastructure.py+++ b/src/world_intel_mcp/tools/infrastructure.py@@ -37,13 +37,13 @@ TOOLS: list[Tool] = [# --- Maritime (1 tool) ---Tool(name="intel_nav_warnings",- description="Get active navigational warnings from NGA Maritime Safety. Optional: navarea (I-XVI).",+ description="Get active navigational warnings from NGA Maritime Safety, each with every position its text states. feed_stale is true when the feed's newest active warning (before any navarea filter) is past the staleness threshold, and data_gaps then says so. Optional: navarea, an NGA area code (4, 12, A, P, C; IV and XII are accepted for 4 and 12).",inputSchema={"type": "object","properties": {"navarea": {"type": "string",- "description": "NAVAREA number (e.g., IV, XII)",+ "description": "NGA area code: 4 (NAVAREA IV), 12 (NAVAREA XII), A (HYDROLANT), P (HYDROPAC) or C (HYDROARC); IV and XII are accepted for 4 and 12. Other NAVAREAs arrive inside the A, P and C series, so a value that matches no carried area returns an error and a data_gaps line, never a count of 0.",},},},diff --git a/src/world_intel_mcp/tools/intelligence.py b/src/world_intel_mcp/tools/intelligence.pyindex d87aca8..57e82bf 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. Each waterway scored clear/advisory/elevated/critical.",+ 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.",inputSchema={"type": "object", "properties": {}},),Tool(