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
Border crossings: US CBP encounters and UK small-boat arrivals
Phoenix Agent (mac-studio)457a49fed966
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6311734..c765312 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,47 @@# Changelog+## Unreleased++### Added: border crossings (flows)+- `intel_us_border_encounters`: U.S. CBP encounters per calendar month+ (Border Patrol Title 8 apprehensions, Field Operations Title 8+ inadmissibles, Title 42 expulsions), read from the newest CSV on CBP's+ public dataset page, which spans four fiscal years (October 2022 to+ August 2026 when written). Nationwide or one land border region, all+ components or USBP / OFO, optionally one citizenship as CBP names it;+ with the latest month against the same month a year earlier, fiscal-year+ totals (the year in progress compared with the same months of the prior+ year, only when every one is published), breakdowns by component,+ encounter type and demographic, and the top citizenships with CBP's+ OTHER bucket reported apart and never ranked. CBP's fiscal months are+ mapped to calendar months (FY2026 October is October 2025).+- `intel_uk_small_boat_arrivals`: Home Office daily and weekly counts of+ migrants and boats detected crossing the English Channel in small boats,+ with uncontrolled landings and the weekly migrants and events prevented+ by French authorities; month and year sums of the daily rows, and the+ year to date against the same span a year earlier. Read through the+ GOV.UK Content API and the published ODS time series, parsed with the+ standard library (zipfile + ElementTree, no new dependency). The+ publisher's numbered notes are quoted from the file on every refresh.+- Both are flows (events per period), stated in every response with units,+ date semantics and the publisher's caveats, and kept apart from the+ UNHCR and World Bank year-end stocks. Neither file has a person+ identifier, so neither counts unique people (said in each response as a+ tool note, not as the publisher's words).+- An outage is a degraded error with no figures; a failed refresh serves+ the last good copy marked `stale` with its age. A '-' in the UK file is+ null, never 0; a CBP month with no rows inside the file's coverage is 0,+ because CBP lists only non-zero cells, and months outside it are never+ invented. Weekly UK totals are checked against their seven days and any+ mismatch is named in `data_gaps`.+- Requests use an identifying User-Agent, two per refresh (the listing,+ then the file), cached 12 h (CBP) and 3 h (UK). Paths that robots.txt+ disallows are never requested; a newer-looking CBP file at such a path+ is named in `data_gaps` instead.+- Frontex is not built: its only data file is an XLSX under `/assets/`,+ which its robots.txt disallows (measured 2026-10-17, see ROADMAP Phase 28).+- Tools 139 -> 141.+## 0.11.0 - 2026-10-12Cross-border migration (MCP tools, CLI, collector and a dashboarddiff --git a/README.md b/README.mdindex 77f7474..31740d2 100644--- a/README.md+++ b/README.md@@ -6,7 +6,7 @@[](https://python.org)[](LICENSE)-Real-time global intelligence across **30+ domains** with **139 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.+Real-time global intelligence across **30+ domains** with **141 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.Built for AI agents that need world awareness: market conditions, geopolitical risk, military posture, aircraft-cohort early warning, refugee and migration flows, supply chain disruptions, cyber threats, and more — all queryable via the Model Context Protocol. The vector store enables natural language queries like *"military activity near Taiwan"* or *"cyber threats targeting healthcare"* across all historical data.@@ -47,7 +47,7 @@ Built for AI agents that need world awareness: market conditions, geopolitical r| **Country Intelligence** | 3 | Country brief, country stocks, financial centers || **Prediction Markets** | 1 | Polymarket event contracts || **Elections** | 1 | Global election calendar with risk scoring |-| **Displacement and Migration** | 5 | UNHCR refugee/IDP data, origin -> destination corridors since 1951, year-over-year surge detection; World Bank net migration and migrant stock |+| **Displacement and Migration** | 7 | UNHCR refugee/IDP data, origin -> destination corridors since 1951, year-over-year surge detection; World Bank net migration and migrant stock; border crossings as flows (CBP monthly encounters, UK small-boat arrivals), never mixed with the year-end stocks || **Shipping** | 1 | Dry bulk shipping stress index || **Government** | 1 | USAspending.gov federal contracts || **Traffic** | 2 | Road traffic flow, real-time incidents |@@ -64,7 +64,7 @@ Built for AI agents that need world awareness: market conditions, geopolitical r| **Tropical Cyclones** | 2 | NHC (Atlantic, E/C Pacific) + JTWC (NW Pacific, N Indian, S Hemisphere) || **Situation Brief** | 1 | Cited situational awareness brief over MCP: bounded server-side overview synthesized via local Ollama, with a mechanically-cited fallback |-**Total: 139 tools** across 30+ intelligence domains.+**Total: 141 tools** across 30+ intelligence domains.---@@ -332,7 +332,7 @@ collector.py (daemon) ─┘|------|-------------|| `intel_election_calendar` | Global election calendar with risk scoring |-### Displacement and migration (5)+### Displacement and migration (7)| Tool | Description ||------|-------------|| `intel_displacement_summary` | UNHCR refugee/IDP statistics, top 30 origins |@@ -340,6 +340,8 @@ collector.py (daemon) ─┘| `intel_migration_surges` | Largest year-over-year increases and decreases by origin and corridor, plus IDPs, sized against population || `intel_migration_history` | One country's yearly series since 1951 as an origin or a host, with its peak and largest waves || `intel_net_migration` | World Bank net migration and migrant stock: latest ranking, regions, or one country since 1960 |+| `intel_us_border_encounters` | CBP encounters per month over the four fiscal years in CBP's newest file (from October 2022 as of October 2026; apprehensions, inadmissibles, Title 42 expulsions): nationwide or by land border region, by component and citizenship, with same-month prior-year change and fiscal-year totals. Events, not unique people |+| `intel_uk_small_boat_arrivals` | Home Office daily and weekly small-boat arrivals across the English Channel (migrants, boats, uncontrolled landings) with French-reported preventions, month and year sums, and year to date vs last year. Provisional operational data |### Aviation (5)| Tool | Description |diff --git a/ROADMAP.md b/ROADMAP.mdindex 4f03400..befa8e0 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -2,7 +2,7 @@**Benchmark**: [koala73/worldmonitor](https://github.com/koala73/worldmonitor)**Updated**: 2026-10-12 (0.11.0: aircraft-cohort early warning, cross-border migration)-**Current tools**: 139 (138 intel + 1 status)+**Current tools**: 141 (140 intel + 1 status)---@@ -132,7 +132,7 @@| `intel_strategic_ports` | Static dataset (40 ports) | :white_check_mark: || `intel_pipelines` | Static dataset (24 pipelines) | :white_check_mark: |-### Humanitarian & Social (8 tools)+### Humanitarian & Social (10 tools)| Tool | WM Equivalent | Status ||------|---------------|--------|| `intel_humanitarian_summary` | `get-humanitarian-summary` | :white_check_mark: |@@ -141,6 +141,8 @@| `intel_migration_surges` | none (beyond parity) | :white_check_mark: year-over-year mass-movement ranking || `intel_migration_history` | none (beyond parity) | :white_check_mark: per-country series since 1951 || `intel_net_migration` | none (beyond parity) | :white_check_mark: World Bank net migration + migrant stock |+| `intel_us_border_encounters` | none (beyond parity) | :white_check_mark: CBP monthly encounters (a flow) |+| `intel_uk_small_boat_arrivals` | none (beyond parity) | :white_check_mark: Home Office small-boat arrivals (a flow) || `intel_social_signals` | Reddit public intelligence | :white_check_mark: || `intel_disease_outbreaks` | WHO/ProMED/CIDRAP RSS | :white_check_mark: |@@ -534,8 +536,9 @@ heatmaps; the excess-origins tool infers takeoffs/landings and clustersthem. Only aircraft first seen 24 h before the window count, so a freshinstall answers `warming_up` for a day.-### Phase 28: Cross-Border Migration (+4 = 139 tools)-`intel_migration_flows`, `intel_migration_surges`, `intel_migration_history`, `intel_net_migration`+### Phase 28: Cross-Border Migration (+6 = 141 tools)+`intel_migration_flows`, `intel_migration_surges`, `intel_migration_history`, `intel_net_migration`,+`intel_us_border_encounters`, `intel_uk_small_boat_arrivals`UNHCR origin -> destination corridors (about 6,000 for 2025) withprior-year change and country/region filters; a surge ranking by@@ -548,8 +551,21 @@ year-end stocks (stated in each response), not crossings.Shipped in 0.11.0 with the dashboard corridor map, CLI commands andcollector sources. Open: near-real-time displacement (IOM DTM, HDX HAPI:-both need keys) and regional border-crossing series (Frontex, CBP, UK-small boats).+both need keys).++Border crossings (Unreleased, `sources/border_crossings.py`): FLOWS, events+per day, week or month, kept apart from the stocks above and never added to+or compared with them. Publisher status as measured on 2026-10-17 with an+identifying User-Agent:++| Publisher | Measured | Status |+|-----------|----------|--------|+| U.S. CBP | Dataset page `cbp.gov/document/stats/nationwide-encounters` 200; newest file a 6.7 MB CSV under `/sites/default/files/2026-09/` (200); robots.txt 200, disallows `/sites/default/files/assets/documents/` (the FY20-FY23 files and data dictionary, never requested); public domain, cite CBP | :white_check_mark: `intel_us_border_encounters`, monthly from October 2022 |+| UK Home Office | GOV.UK Content API 200 (keyless, 10 requests/s); time series published only as ODS on `assets.publishing.service.gov.uk` (200, robots.txt 404), read with zipfile + ElementTree, no new dependency; Open Government Licence v3.0 | :white_check_mark: `intel_uk_small_boat_arrivals`, daily from 2018, weekly preventions from May 2024 |+| Frontex | Migratory map page 200; its only data file is an XLSX under `/assets/`, which robots.txt (200) disallows for every user agent; not requested, no workaround | :red_circle: blocked by robots.txt (and XLSX only) |++Not exposed yet: CBP sector and field-office (area of responsibility) and+by-state detail, and CBP years before FY2023 (robots-disallowed path).---@@ -635,8 +651,8 @@ suite, and a live MCP stdio session.| Category | Current | Notes ||----------|---------|-------|-| Total MCP tools | 139 | 138 intelligence tools + `intel_status` |-| Tool parity | 139 / 139 | `TOOLS` and handlers are aligned at import time; README's per-tool reference is pinned to the registry by `test_readme_documents_every_registered_tool` |+| Total MCP tools | 141 | 140 intelligence tools + `intel_status` |+| Tool parity | 141 / 141 | `TOOLS` and handlers are aligned at import time; README's per-tool reference is pinned to the registry by `test_readme_documents_every_registered_tool` || Static datasets | 18 | Bases, ports, pipelines, nuclear, cables, datacenters, spaceports, minerals, exchanges, trade routes, cloud regions, financial centers || RSS feeds | 119 | 24 categories || Tests in repo | 991 | 973 non-smoke tests + 18 live smoke tests (measured 2026-10-12: `pytest -m 'not smoke'` -> 973 passed, 18 deselected); full suite requires `.[dev]` |diff --git a/src/world_intel_mcp/sources/border_crossings.py b/src/world_intel_mcp/sources/border_crossings.pynew file mode 100644index 0000000..1d1b0b8--- /dev/null+++ b/src/world_intel_mcp/sources/border_crossings.py@@ -0,0 +1,1332 @@+"""Border crossings: monthly U.S. CBP encounters and daily UK small-boat arrivals.++Crossings are FLOWS (events per day, week or month). The UNHCR and World Bank+tools in ``sources/migration.py`` report year-end STOCKS of people. They are+different measures, and nothing here adds, subtracts or compares the two.++Publishers, as measured on 2026-10-17 (HTTP status, robots.txt, terms):++* U.S. Customs and Border Protection: the "Nationwide Encounters" dataset page+ https://www.cbp.gov/document/stats/nationwide-encounters (200) lists one CSV+ per monthly update under /sites/default/files/YYYY-MM/. The newest (FY2023 to+ FY2026, through August 2026) is 6.7 MB and 52,986 rows, one per fiscal month,+ component, land border region, area of responsibility, demographic,+ citizenship and encounter type. https://www.cbp.gov/robots.txt (200)+ disallows /sites/default/files/assets/documents/, where the older FY2020 to+ FY2023 files and the data dictionary live, so nothing there is requested.+ CBP's copyright notice: site information is in the public domain unless a+ copyright is indicated, and CBP asks to be cited as the source.+* UK Home Office: "Small boat activity in the English Channel" on GOV.UK, read+ through the GOV.UK Content API (200, keyless, at most 10 requests per second+ per client). The time series is published only as an ODS spreadsheet, on+ assets.publishing.service.gov.uk (robots.txt 404). ODS is a zip of XML, read+ here with zipfile and ElementTree, so no new dependency. GOV.UK content is+ under the Open Government Licence v3.0.+* Frontex is not built. Its monthly detections file is XLSX only and sits under+ /assets/, which https://www.frontex.europa.eu/robots.txt (200) disallows for+ every user agent. Nothing under /assets/ is requested.++A refresh makes two requests (the listing, then the file) with an identifying+User-Agent, and the parsed dataset is cached (CBP 12 h, UK 3 h). A failed+refresh serves the last good copy marked ``stale`` with its age and the+failure in ``data_gaps``; with no copy the tool returns a degraded error that+carries no figures, so an outage never reads as zero.++Gaps / not covered:++* Frontex (robots.txt disallows its only data file, which is XLSX).+* CBP: only the newest file is read, so the series covers its four fiscal+ years (from October 2022 in the file read on 2026-10-17); older years sit+ under the disallowed path. Area-of-responsibility (sector and field+ office) and by-state detail are not exposed. Figures are provisional+ until CBP's fiscal-year close and change between monthly files. CBP's+ caveats are quoted as captured on 2026-10-17: the two on the dataset page+ are re-checked on every refresh, the ones on its encounters page are not+ re-read.+* UK: the Home Office figures are provisional operational data, superseded by+ the quarterly "Illegal entry routes to the UK" statistics, which are not read+ here. Month, year and year-to-date figures are this module's sums of the+ daily rows, not Home Office figures. The Notes column is read only for+ "Revised". The last-7-days and weekly-summary HTML pages are not read (on+ 2026-10-17 their figures matched the ODS).+* robots.txt is not re-read at run time; the CBP path rule is pinned as read on+ 2026-10-17.+* Neither file has a person identifier, so neither series counts unique+ people; the responses say so as a tool note, not in the publishers' words.+"""++from __future__ import annotations++import asyncio+import calendar+import csv+import io+import json+import logging+import re+import time+import weakref+import xml.etree.ElementTree as ET+import zipfile+import zlib+from collections import Counter, defaultdict+from datetime import date, datetime, timedelta, timezone+from html.parser import HTMLParser+from typing import Any, Awaitable, Callable+from urllib.parse import urljoin, urlsplit++from ..fetcher import BinaryResult, Fetcher++logger = logging.getLogger("world-intel-mcp.sources.border_crossings")++USER_AGENT = "world-intel-mcp (+https://github.com/marc-shade/world-intel-mcp)"+_HEADERS = {"User-Agent": USER_AGENT}+_MONTHS = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC")++_FLOW_NOT_STOCK = (+ "Flow, not stock: these are events per period. The UNHCR and World Bank migration tools report "+ "year-end stocks of people; the two measures do not add, subtract or compare."+)+++def _now() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _usage(source: str, error: str) -> dict[str, Any]:+ return {"error": error, "source": source, "timestamp": _now()}+++def _degraded(source: str, error: str, reason: str) -> dict[str, Any]:+ return {"error": error, "degraded": True, "reason": reason, "source": source, "timestamp": _now()}+++def _is_int(value: Any) -> bool:+ return isinstance(value, int) and not isinstance(value, bool)+++def _why(result: BinaryResult) -> str:+ if result.error:+ return result.error+ return f"HTTP {result.status}" if result.status is not None else "no response"+++def _pct(current: int | None, prior: int | None) -> float | None:+ if current is None or not prior:+ return None+ return round(100 * (current - prior) / prior, 1)+++def _diff(current: int | None, prior: int | None) -> int | None:+ return None if current is None or prior is None else current - prior+++class _SourceError(Exception):+ """A refresh failed; ``reason`` is the degraded-response reason code."""++ def __init__(self, reason: str, message: str) -> None:+ super().__init__(message)+ self.reason = reason+ self.message = message+++_refresh_locks: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]] = (+ weakref.WeakKeyDictionary()+)+++def _refresh_lock(key: str) -> asyncio.Lock:+ """One refresh per dataset at a time (per event loop), so concurrent cold+ calls download a file once instead of once each."""+ locks = _refresh_locks.setdefault(asyncio.get_running_loop(), {})+ if key not in locks:+ locks[key] = asyncio.Lock()+ return locks[key]+++def _valid(value: Any, schema: int) -> dict[str, Any] | None:+ return value if isinstance(value, dict) and value.get("schema") == schema else None+++async def _load(+ fetcher: Fetcher,+ key: str,+ ttl: int,+ schema: int,+ fetch: Callable[[Fetcher], Awaitable[dict[str, Any]]],+) -> tuple[dict[str, Any] | None, dict[str, Any]]:+ """The parsed dataset and its freshness: cached, refreshed, or the last good copy marked stale.++ Returns ``(None, {"error", "reason"})`` when the refresh fails and no copy exists.+ """+ cached = _valid(fetcher.cache.get(key), schema)+ if cached is not None:+ return cached, {"stale": False}+ async with _refresh_lock(key):+ cached = _valid(fetcher.cache.get(key), schema)+ if cached is not None:+ return cached, {"stale": False}+ try:+ dataset = await fetch(fetcher)+ except _SourceError as exc:+ logger.warning("Refresh of %s failed: %s", key, exc.message)+ meta = fetcher.cache.get_stale_meta(key)+ value = _valid(meta[0], schema) if meta else None+ if value is None:+ return None, {"error": exc.message, "reason": exc.reason}+ age = round(max(0.0, time.time() - meta[1]), 1)+ return value, {"stale": True, "stale_age_seconds": age, "refresh_error": exc.message}+ fetcher.cache.set(key, dataset, ttl_seconds=ttl)+ return dataset, {"stale": False}+++def _freshness(result: dict[str, Any], state: dict[str, Any], gaps: list[str], fetched_at: str) -> None:+ result["stale"] = state["stale"]+ if state["stale"]:+ result["stale_age_seconds"] = state["stale_age_seconds"]+ gaps.append(f"Refresh failed ({state['refresh_error']}); this is the copy fetched at {fetched_at}.")+++# ---------------------------------------------------------------------------+# U.S. Customs and Border Protection: nationwide encounters+# ---------------------------------------------------------------------------++CBP_SOURCE = "cbp"+CBP_DATASET_PAGE = "https://www.cbp.gov/document/stats/nationwide-encounters"+CBP_STATS_PAGE = "https://www.cbp.gov/newsroom/stats/nationwide-encounters"+CBP_CACHE_KEY = "border_crossings:cbp_encounters"+_CBP_SCHEMA = 1+_CBP_TTL = 43200 # 12 h; CBP posts one file a month+_CBP_PAGE_MAX_BYTES = 8 * 1024 * 1024+_CBP_CSV_MAX_BYTES = 64 * 1024 * 1024 # the August 2026 file is 6.7 MB+_CBP_HOST = "www.cbp.gov"+# https://www.cbp.gov/robots.txt, read 2026-10-17: "#Disallow the files/assets/documents directory".+_CBP_DISALLOWED_PREFIXES = ("/sites/default/files/assets/documents/",)+_CBP_FILE_NAME = re.compile(+ r"/nationwide-encounters-fy(?P<fy_from>\d{2})-fy(?P<fy_to>\d{2})(?:-(?P<month>[a-z]{3}))?-aor(?:_(?P<dup>\d+))?\.csv$"+)+_CBP_FILE_FOLDER = re.compile(r"^/sites/default/files/(\d{4}-\d{2})/[^/]+$")+_LAST_MODIFIED = re.compile(r"Last Modified:\s*([A-Za-z]{3})[A-Za-z]*\.?\s+(\d{1,2}),\s*(\d{4})")++CBP_REGIONS = {"southwest": "Southwest Land Border", "northern": "Northern Land Border", "other": "Other"}+CBP_COMPONENTS = {"usbp": "U.S. Border Patrol", "ofo": "Office of Field Operations"}+_CBP_OTHER = "OTHER"+_CBP_COLUMNS = {+ "fiscal_year": "Fiscal Year",+ "month": "Month (abbv)",+ "component": "Component",+ "region": "Land Border Region",+ "demographic": "Demographic",+ "citizenship": "Citizenship",+ "encounter_type": "Encounter Type",+ "count": "Encounter Count",+}+# Order of the dimensions in a compact cell: [period, region, component, type, demographic, citizenship, count].+_CBP_DIMS = ("region", "component", "encounter_type", "demographic", "citizenship")+_REGION, _COMPONENT, _TYPE, _DEMOGRAPHIC, _CITIZENSHIP, _COUNT = 1, 2, 3, 4, 5, 6++# Quoted from the dataset page (CBP_DATASET_PAGE), captured 2026-10-17 and+# re-checked against the live page on every refresh.+_CBP_PAGE_CAVEATS = (+ "Encounter data includes U.S. Border Patrol Title 8 apprehensions, Office of Field Operations Title 8 "+ "inadmissibles, and all Title 42 expulsions for fiscal years 2020 to date. Data is available for the "+ "Northern Land Border, Southwest Land Border, and Nationwide (i.e., air, land, and sea modes of "+ "transportation) encounters.",+ "Data is extracted from live CBP systems and data sources. Statistical information is subject to change "+ "due to corrections, systems changes, change in data definition, additional information, or encounters "+ "pending final review. Final statistics are available at the conclusion of each fiscal year.",+)+# Quoted from CBP's encounters page (CBP_STATS_PAGE), captured 2026-10-17; not re-read at run time.+_CBP_STATS_CAVEATS = (+ "Note: Nationwide encounters are the sum of CBP encounters across all areas of responsibility including "+ "Northern Land Border, Southwest Land Border, OFO non-land border ports of entry (e.g., airports, "+ "seaports), and USBP sectors that do not share a land border with Canada or Mexico (e.g., Miami Sector).",+ "To ensure that law enforcement sensitive statistics are not publicly released, modifications to data "+ "filters have been made that may alter the format of data previously obtained from this dashboard.",+)+_CBP_DEFINITIONS = {+ "encounter_types": {+ "Apprehensions": (+ "Apprehensions refers to the physical control or temporary detainment of a person by USBP between "+ "POEs who is not lawfully in the U.S. which may or may not result in an arrest."+ ),+ "Inadmissibles": (+ "Inadmissibles refers to individuals encountered at ports of entry (POEs) by OFO who are seeking "+ "lawful admission into the United States (U.S.) but are determined to be inadmissible, individuals "+ "presenting themselves to seek humanitarian protection under our laws, and individuals who withdraw "+ "an application for admission and return to their countries of origin within a short timeframe."+ ),+ "Expulsions": (+ "Title 42 Expulsions refers to individuals encountered by USBP and OFO and expelled to the country "+ "of last transit or home country in the interest of public health under Title 42 U.S.C. 265 from "+ "March 21, 2020 to May 11, 2023."+ ),+ },+ "demographics": {+ "Accompanied Minors": "Accompanied Minors (AM)",+ "FMUA": "Individuals in a Family Unit (FMUA)",+ "Single Adults": "Single Adults",+ "UAC": "Unaccompanied Alien Children (UAC) / Single Minors",+ },+ "source": f"Quoted from {CBP_STATS_PAGE} as captured 2026-10-17.",+}+_CBP_MEASURE = (+ "CBP encounters per calendar month: U.S. Border Patrol (USBP) Title 8 apprehensions between ports of "+ "entry, Office of Field Operations (OFO) Title 8 inadmissibles at ports of entry, and Title 42 "+ "expulsions (21 March 2020 to 11 May 2023)."+)+_CBP_UNIT = "encounters (enforcement events) per calendar month"+_CBP_DATE_SEMANTICS = (+ "Each figure counts the encounters in one calendar month. CBP labels months by fiscal year (1 October to "+ "30 September), so October to December belong to the next fiscal year: FY2026 October is October 2025. "+ "'(FYTD)' is CBP's label for the fiscal year in progress. Figures are as of the file's posting "+ "(dataset.file_date) and can change in later files until CBP's fiscal-year close."+)+_CBP_NOTES = (+ _FLOW_NOT_STOCK,+ "Encounters are events, not unique people: CBP's file has no person identifier, so one person "+ "encountered twice is counted twice. (Tool note from the file's structure; the CBP pages read on "+ "2026-10-17 do not say it in these words.)",+ "CBP's file lists only non-zero cells (no count of 0 appears and counts of 1 are published), so a month "+ "in the file with no row for this selection is reported as 0. Months the file does not contain are never "+ "listed or filled in (see dataset.coverage).",+ "OTHER is CBP's bucket for every citizenship it does not name; it is reported as "+ "other_citizenships_latest_month and never ranked as a country.",+ "Region 'other' is CBP's 'Other' land border region: OFO ports of entry away from the land borders (CBP's "+ "nationwide note gives airports and seaports as examples; the file also has a Preclearance Field Office) "+ "and the Miami, New Orleans and Ramey Border Patrol sectors.",+)+_CBP_TERMS = (+ "Public domain unless a copyright is indicated; CBP asks to be cited as the source "+ "(https://www.cbp.gov/site-policy-notices/copyright-notice)."+)+++def cbp_period(fiscal_year: int, month_abbv: str) -> str:+ """Calendar month (YYYY-MM) of a CBP fiscal-year month: October to December fall in fiscal_year - 1."""+ month = str(month_abbv).strip().upper()+ if month not in _MONTHS:+ raise ValueError(f"unknown CBP month {month_abbv!r}")+ number = _MONTHS.index(month) + 1+ return f"{fiscal_year - 1 if number >= 10 else fiscal_year:04d}-{number:02d}"+++def _fiscal_year(period: str) -> int:+ year, month = int(period[:4]), int(period[5:7])+ return year + 1 if month >= 10 else year+++def _month_bounds(period: str) -> tuple[str, str]:+ year, month = int(period[:4]), int(period[5:7])+ return f"{period}-01", f"{period}-{calendar.monthrange(year, month)[1]:02d}"+++def _shift_months(period: str, delta: int) -> str:+ index = int(period[:4]) * 12 + int(period[5:7]) - 1 + delta+ return f"{index // 12:04d}-{index % 12 + 1:02d}"+++def parse_cbp_csv(text: str) -> dict[str, Any]:+ """Aggregate CBP's encounters CSV into compact cells, summing out the area of responsibility.++ Raises ValueError when the header lacks a needed column or no data row is readable.+ """+ reader = csv.reader(io.StringIO(text.lstrip("\ufeff")))+ names = [name.strip() for name in next(reader, None) or []]+ missing = [column for column in _CBP_COLUMNS.values() if column not in names]+ if missing:+ raise ValueError(f"CBP file lacks the columns {', '.join(missing)}")+ index = {key: names.index(column) for key, column in _CBP_COLUMNS.items()}+ width = max(index.values()) + 1+ vocab: dict[str, dict[str, int]] = {dim: {} for dim in _CBP_DIMS}+ totals: dict[tuple, int] = defaultdict(int)+ fiscal_year_labels: dict[str, str] = {}+ rows = unreadable = 0+ for row in reader:+ if not any(cell.strip() for cell in row):+ continue+ rows += 1+ try:+ if len(row) < width:+ raise ValueError("short row")+ label = row[index["fiscal_year"]].strip()+ match = re.match(r"(\d{4})\b", label)+ if match is None:+ raise ValueError(f"fiscal year {label!r}")+ fiscal_year = int(match.group(1))+ period = cbp_period(fiscal_year, row[index["month"]])+ count = int(row[index["count"]].strip().replace(",", ""))+ if count < 0:+ raise ValueError(f"negative count {count}")+ values = [" ".join(row[index[dim]].split()) for dim in _CBP_DIMS]+ if not all(values):+ raise ValueError("empty dimension")+ except ValueError:+ unreadable += 1+ continue+ keys = tuple(vocab[dim].setdefault(value, len(vocab[dim])) for dim, value in zip(_CBP_DIMS, values))+ fiscal_year_labels.setdefault(str(fiscal_year), label)+ totals[(period, *keys)] += count+ if rows == 0:+ raise ValueError("CBP file has no data rows")+ if not totals:+ raise ValueError(f"none of the CBP file's {rows} data rows could be read")+ periods = sorted({key[0] for key in totals})+ position = {period: i for i, period in enumerate(periods)}+ return {+ "schema": _CBP_SCHEMA,+ "periods": periods,+ "fiscal_year_labels": fiscal_year_labels,+ "dims": {dim: list(vocab[dim]) for dim in _CBP_DIMS},+ "cells": [[position[key[0]], *key[1:], count] for key, count in totals.items()],+ "rows": rows,+ "unreadable_rows": unreadable,+ }+++class _PageParser(HTMLParser):+ """Links, table rows (their links and data-sort-value cells) and visible text of an HTML page."""++ def __init__(self) -> None:+ super().__init__(convert_charrefs=True)+ self.anchors: list[tuple[str, str]] = []+ self.rows: list[tuple[list[str], list[str]]] = []+ self.chunks: list[str] = []+ self._anchor: list[str] | None = None+ self._href = ""+ self._row: tuple[list[str], list[str]] | None = None+ self._hidden = 0++ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:+ attr = {name: value or "" for name, value in attrs}+ if tag in ("script", "style", "noscript"):+ self._hidden += 1+ elif tag == "a" and attr.get("href"):+ self._href, self._anchor = attr["href"].strip(), []+ if self._row is not None:+ self._row[0].append(self._href)+ elif tag == "tr":+ if self._row is not None:+ self.rows.append(self._row)+ self._row = ([], [])+ elif tag == "td" and self._row is not None and "data-sort-value" in attr:+ self._row[1].append(attr["data-sort-value"].strip())++ def handle_endtag(self, tag: str) -> None:+ if tag in ("script", "style", "noscript"):+ self._hidden = max(0, self._hidden - 1)+ elif tag == "a" and self._anchor is not None:+ self.anchors.append((self._href, " ".join("".join(self._anchor).split())))+ self._anchor = None+ elif tag == "tr" and self._row is not None:+ self.rows.append(self._row)+ self._row = None++ def handle_data(self, data: str) -> None:+ if self._hidden:+ return+ if self._anchor is not None:+ self._anchor.append(data)+ self.chunks.append(data)+++def _parse_page(html: str) -> _PageParser:+ parser = _PageParser()+ parser.feed(html)+ parser.close()+ return parser+++def _page_text(page: _PageParser) -> str:+ return " ".join("".join(page.chunks).split())+++def _cbp_link(href: str) -> tuple[str, str, bool] | None:+ """(absolute URL, path, robots.txt allows it) of a link on www.cbp.gov, else None."""+ url = urljoin(CBP_DATASET_PAGE, href).split("#", 1)[0]+ parts = urlsplit(url)+ if parts.scheme != "https" or parts.hostname != _CBP_HOST:+ return None+ allowed = not any(parts.path.startswith(prefix) for prefix in _CBP_DISALLOWED_PREFIXES)+ return url, parts.path, allowed+++def _us_date(value: str) -> str | None:+ try:+ return datetime.strptime(value, "%m/%d/%Y").date().isoformat()+ except ValueError:+ return None+++def _latest_file(page: _PageParser) -> dict[str, Any] | None:+ best: tuple[tuple, str, str, str | None] | None = None+ newest_disallowed: tuple[tuple, str] | None = None+ for href, text in page.anchors:+ link = _cbp_link(href)+ if link is None:+ continue+ url, path, allowed = link+ name = _CBP_FILE_NAME.search(path)+ month = (name["month"] or "").upper() if name else ""+ if name is None or (month and month not in _MONTHS):+ continue+ folder = _CBP_FILE_FOLDER.match(path)+ rank = (+ int(name["fy_to"]),+ (_MONTHS.index(month) - 9) % 12 + 1 if month else 12, # through which fiscal month: OCT=1 .. SEP=12+ folder.group(1) if folder else "",+ int(name["dup"] or -1),+ )+ if not allowed:+ if newest_disallowed is None or rank > newest_disallowed[0]:+ newest_disallowed = (rank, url)+ elif best is None or rank > best[0]:+ best = (rank, url, path, text or None)+ if best is None:+ return None+ rank, url, path, title = best+ file_date = size = None+ for hrefs, sort_values in page.rows:+ if path not in {link[1] for link in map(_cbp_link, hrefs) if link}:+ continue+ for value in sort_values:+ if re.fullmatch(r"\d{2}/\d{2}/\d{4}", value):+ file_date = _us_date(value)+ elif value.isdigit():+ size = int(value)+ break+ newer = newest_disallowed[1] if newest_disallowed and newest_disallowed[0] > rank else None+ return {"url": url, "title": title, "file_date": file_date, "size_bytes": size, "newer_disallowed_url": newer}+++def latest_cbp_file(html: str) -> dict[str, Any] | None:+ """The newest nationwide encounters CSV (by area of responsibility) on CBP's dataset page.++ Ranked by its last fiscal year, then the fiscal month it runs through (from the+ file name), then its upload folder. A link under a path robots.txt disallows, or off+ www.cbp.gov, is never chosen; when such a link looks newer than the one chosen, its+ URL is returned as ``newer_disallowed_url`` so the response can say so. ``file_date``+ and ``size_bytes`` come from the page's file table (its Date and Size columns).+ """+ return _latest_file(_parse_page(html))+++def _last_modified(text: str) -> str | None:+ match = _LAST_MODIFIED.search(text)+ if match is None or match.group(1).upper() not in _MONTHS:+ return None+ try:+ return date(int(match.group(3)), _MONTHS.index(match.group(1).upper()) + 1, int(match.group(2))).isoformat()+ except ValueError:+ return None+++def cbp_page_last_modified(html: str) -> str | None:+ """ISO date of the page's "Last Modified: Sep 16, 2026" line, or None."""+ return _last_modified(_page_text(_parse_page(html)))+++async def _fetch_cbp_dataset(fetcher: Fetcher) -> dict[str, Any]:+ page_result = await fetcher.get_bytes(+ CBP_DATASET_PAGE, CBP_SOURCE, headers=_HEADERS, max_bytes=_CBP_PAGE_MAX_BYTES+ )+ if page_result.content is None:+ raise _SourceError("cbp_fetch_failed", f"CBP dataset page unavailable: {_why(page_result)}")+ page = _parse_page(page_result.content.decode("utf-8", errors="replace"))+ latest = _latest_file(page)+ if latest is None:+ raise _SourceError(+ "cbp_unexpected_format",+ "CBP's dataset page lists no nationwide encounters CSV by area of responsibility at a path "+ "robots.txt allows",+ )+ csv_result = await fetcher.get_bytes(latest["url"], CBP_SOURCE, headers=_HEADERS, max_bytes=_CBP_CSV_MAX_BYTES)+ if csv_result.content is None:+ raise _SourceError("cbp_fetch_failed", f"CBP encounters file unavailable: {_why(csv_result)}")+ try:+ dataset = parse_cbp_csv(csv_result.content.decode("utf-8-sig"))+ except ValueError as exc: # includes UnicodeDecodeError+ raise _SourceError("cbp_unexpected_format", f"CBP encounters file not readable: {exc}") from exc+ text = _page_text(page)+ dataset["meta"] = {+ "title": latest["title"],+ "url": latest["url"],+ "page": CBP_DATASET_PAGE,+ "file_date": latest["file_date"],+ "file_size_bytes": latest["size_bytes"],+ "page_last_modified": _last_modified(text),+ "newer_disallowed_url": latest["newer_disallowed_url"],+ "fetched_at": _now(),+ }+ dataset["page_caveats_missing"] = [c for c in _CBP_PAGE_CAVEATS if " ".join(c.split()) not in text]+ return dataset+++def _named(counter: Counter, names: list[str]) -> dict[str, int]:+ """Counter keyed by vocabulary index -> {name: count}, non-zero only, largest first."""+ items = sorted(((names[k], v) for k, v in counter.items() if v), key=lambda item: (-item[1], item[0]))+ return dict(items)+++async def fetch_us_border_encounters(+ fetcher: Fetcher,+ region: str | None = "nationwide",+ component: str | None = "all",+ citizenship: str | None = None,+ months: int | None = 13,+) -> dict[str, Any]:+ """Monthly CBP encounters for a region, component and citizenship, with year-over-year context."""+ region_key = "nationwide" if region is None else str(region).strip().lower()+ component_key = "all" if component is None else str(component).strip().lower()+ months = 13 if months is None else months+ if region_key != "nationwide" and region_key not in CBP_REGIONS:+ return _usage(CBP_SOURCE, f"region must be one of: nationwide, {', '.join(CBP_REGIONS)}")+ if component_key != "all" and component_key not in CBP_COMPONENTS:+ return _usage(CBP_SOURCE, f"component must be one of: all, {', '.join(CBP_COMPONENTS)}")+ if citizenship is not None and (not isinstance(citizenship, str) or not citizenship.strip()):+ return _usage(CBP_SOURCE, "citizenship must be a non-empty string")+ if not _is_int(months) or not 1 <= months <= 120:+ return _usage(CBP_SOURCE, "months must be an integer from 1 to 120")++ dataset, state = await _load(fetcher, CBP_CACHE_KEY, _CBP_TTL, _CBP_SCHEMA, _fetch_cbp_dataset)+ if dataset is None:+ return _degraded(CBP_SOURCE, state["error"], state["reason"])++ dims = dataset["dims"]+ filters: dict[int, int] = {}+ for position, dim, labels, key in (+ (_REGION, "region", CBP_REGIONS, region_key),+ (_COMPONENT, "component", CBP_COMPONENTS, component_key),+ ):+ if key in labels:+ if labels[key] not in dims[dim]:+ return _degraded(+ CBP_SOURCE,+ f"CBP's file has no rows for the {dim} {labels[key]!r} (it has: {', '.join(dims[dim])})",+ "cbp_unexpected_format",+ )+ filters[position] = dims[dim].index(labels[key])+ citizenship_label = None+ if citizenship is not None:+ wanted = " ".join(citizenship.split()).upper()+ found = [i for i, name in enumerate(dims["citizenship"]) if name.upper() == wanted]+ if not found:+ named = sorted(name for name in dims["citizenship"] if name != _CBP_OTHER)+ return _usage(+ CBP_SOURCE,+ f"CBP publishes no citizenship {citizenship.strip()!r}. It names {len(named)} citizenships and "+ f"counts every other one in OTHER: {', '.join(named)}",+ )+ filters[_CITIZENSHIP] = found[0]+ citizenship_label = dims["citizenship"][found[0]]++ periods: list[str] = dataset["periods"]+ position_of = {period: i for i, period in enumerate(periods)}+ last = len(periods) - 1+ totals = [0] * len(periods)+ breakdown = {dim: [Counter() for _ in periods] for dim in ("component", "encounter_type", "demographic")}+ latest_by_citizenship: Counter = Counter()+ for cell in dataset["cells"]:+ if any(cell[pos] != want for pos, want in filters.items()):+ continue+ period, count = cell[0], cell[_COUNT]+ totals[period] += count+ breakdown["component"][period][cell[_COMPONENT]] += count+ breakdown["encounter_type"][period][cell[_TYPE]] += count+ breakdown["demographic"][period][cell[_DEMOGRAPHIC]] += count+ if period == last:+ latest_by_citizenship[cell[_CITIZENSHIP]] += count++ def month(i: int) -> dict[str, Any]:+ start, end = _month_bounds(periods[i])+ return {+ "period": periods[i],+ "period_start": start,+ "period_end": end,+ "fiscal_year": _fiscal_year(periods[i]),+ "encounters": totals[i],+ "by_component": _named(breakdown["component"][i], dims["component"]),+ "by_encounter_type": _named(breakdown["encounter_type"][i], dims["encounter_type"]),+ "by_demographic": _named(breakdown["demographic"][i], dims["demographic"]),+ }++ gaps: list[str] = []+ meta = dataset["meta"]+ window = list(range(max(0, len(periods) - months), len(periods)))+ first_shown, span = periods[window[0]], []+ while first_shown <= periods[last]:+ span.append(first_shown)+ first_shown = _shift_months(first_shown, 1)+ absent = [p for p in span if p not in position_of]+ if absent:+ gaps.append(+ f"{len(absent)} month(s) between {periods[window[0]]} and {periods[last]} have no rows in CBP's file "+ f"and are not listed: {', '.join(absent[:12])}{' ...' if len(absent) > 12 else ''}."+ )+ if dataset["unreadable_rows"]:+ gaps.append(+ f"{dataset['unreadable_rows']} of the file's {dataset['rows']} rows could not be read and are not counted."+ )+ if meta.get("newer_disallowed_url"):+ gaps.append(f"CBP lists a newer-looking encounters file at a path its robots.txt disallows "+ f"({meta['newer_disallowed_url']}); it is not read, so these may not be CBP's newest figures.")+ for caveat in dataset.get("page_caveats_missing", []):+ gaps.append(f"CBP's dataset page no longer shows this caveat word for word (quoted as captured 2026-10-17): "+ f"{caveat[:90]}...")++ latest_start, latest_end = _month_bounds(periods[last])+ prior_index = position_of.get(_shift_months(periods[last], -12))+ prior = totals[prior_index] if prior_index is not None else None+ latest = {+ "period": periods[last],+ "period_start": latest_start,+ "period_end": latest_end,+ "fiscal_year": _fiscal_year(periods[last]),+ "encounters": totals[last],+ "same_month_prior_year": prior,+ "change_vs_prior_year": _diff(totals[last], prior),+ "pct_change_vs_prior_year": _pct(totals[last], prior),+ }++ by_fiscal_year: dict[int, list[int]] = defaultdict(list)+ for i, period in enumerate(periods):+ by_fiscal_year[_fiscal_year(period)].append(i)+ fiscal_years = []+ for fiscal_year in sorted(by_fiscal_year):+ members = by_fiscal_year[fiscal_year]+ label = dataset["fiscal_year_labels"].get(str(fiscal_year), str(fiscal_year))+ entry: dict[str, Any] = {+ "fiscal_year": fiscal_year,+ "period_start": f"{fiscal_year - 1}-10-01",+ "period_end": f"{fiscal_year}-09-30",+ "months_reported": len(members),+ "complete": len(members) == 12,+ "fiscal_year_to_date": "FYTD" in label.upper(),+ "encounters": sum(totals[i] for i in members),+ }+ if entry["fiscal_year_to_date"]:+ earlier = [position_of.get(_shift_months(periods[i], -12)) for i in members]+ # Only a like-for-like comparison: every same month of the prior year must be in the file.+ entry["prior_fiscal_year_same_months"] = (+ None if any(j is None for j in earlier) else sum(totals[j] for j in earlier)+ )+ fiscal_years.append(entry)++ result: dict[str, Any] = {+ "publisher": "U.S. Customs and Border Protection (CBP)",+ "dataset": {+ "title": meta["title"],+ "url": meta["url"],+ "page": meta["page"],+ "file_date": meta["file_date"],+ "file_size_bytes": meta["file_size_bytes"],+ "page_last_modified": meta["page_last_modified"],+ "coverage": {"first_period": periods[0], "last_period": periods[last]},+ "fetched_at": meta["fetched_at"],+ },+ "measure_kind": "flow",+ "measure": _CBP_MEASURE,+ "unit": _CBP_UNIT,+ "date_semantics": _CBP_DATE_SEMANTICS,+ "definitions": _CBP_DEFINITIONS,+ "selection": {+ "region": CBP_REGIONS.get(region_key, "Nationwide"),+ "component": CBP_COMPONENTS.get(component_key, "All components"),+ "citizenship": citizenship_label,+ },+ "latest": latest,+ "months": [month(i) for i in window],+ "fiscal_years": fiscal_years,+ }+ if citizenship_label is None:+ other = dims["citizenship"].index(_CBP_OTHER) if _CBP_OTHER in dims["citizenship"] else None+ ranked = sorted(+ ((dims["citizenship"][k], v) for k, v in latest_by_citizenship.items() if k != other and v),+ key=lambda item: (-item[1], item[0]),+ )[:10]+ result["top_citizenships_latest_month"] = [+ {"citizenship": name, "encounters": count,+ "share_pct": round(100 * count / totals[last], 1) if totals[last] else None}+ for name, count in ranked+ ]+ result["other_citizenships_latest_month"] = latest_by_citizenship.get(other, 0) if other is not None else None+ result["publisher_caveats"] = [*_CBP_PAGE_CAVEATS, *_CBP_STATS_CAVEATS]+ result["publisher_caveats_source"] = (+ f"Quoted as captured 2026-10-17: the first two from {CBP_DATASET_PAGE} (re-checked on every refresh), "+ f"the others from {CBP_STATS_PAGE} (not re-read)."+ )+ result["terms"] = _CBP_TERMS+ result["notes"] = list(_CBP_NOTES)+ _freshness(result, state, gaps, meta["fetched_at"])+ result["data_gaps"] = gaps+ result["source"] = CBP_SOURCE+ result["timestamp"] = _now()+ return result+++# ---------------------------------------------------------------------------+# UK Home Office: small boats crossing the English Channel+# ---------------------------------------------------------------------------++UK_SOURCE = "uk-home-office"+UK_PUBLICATION_PATH = "/government/publications/migrants-detected-crossing-the-english-channel-in-small-boats"+UK_PUBLICATION_PAGE = "https://www.gov.uk" + UK_PUBLICATION_PATH+UK_CONTENT_API = "https://www.gov.uk/api/content" + UK_PUBLICATION_PATH+UK_CACHE_KEY = "border_crossings:uk_small_boats"+_UK_SCHEMA = 1+_UK_TTL = 10800 # 3 h; its change history shows 72 updates from 1 August to 16 October 2026+_UK_API_MAX_BYTES = 8 * 1024 * 1024+_UK_ODS_MAX_BYTES = 32 * 1024 * 1024 # the 16 October 2026 file is 76,787 bytes+_UK_FILE_HOSTS = {"assets.publishing.service.gov.uk", "www.gov.uk"}+_ODS_TYPE = "application/vnd.oasis.opendocument.spreadsheet"+_ODS_MAX_XML_BYTES = 64 * 1024 * 1024 # the live content.xml is 2.5 MB+_ODS_MAX_COLUMNS = 256+_ODS_MAX_ROWS = 200_000+_T = "{urn:oasis:names:tc:opendocument:xmlns:table:1.0}"+_O = "{urn:oasis:names:tc:opendocument:xmlns:office:1.0}"+_X = "{urn:oasis:names:tc:opendocument:xmlns:text:1.0}"++_UK_MEASURE = (+ "Migrants and boats detected crossing the English Channel in small boats and arriving in the UK "+ "(Home Office provisional operational data): per day (table SB_01) and per week (table SB_02, which "+ "adds migrants and events prevented by French authorities)."+)+_UK_UNIT = "people (migrants) and boats per day or week; preventions per week"+_UK_DATE_SEMANTICS = (+ "SB_01 'Date' is the day of arrival. SB_02 'Week ending' is the Sunday that closes a Monday-to-Sunday week "+ "(period_start is six days earlier); the Home Office notes the activity may have occurred on any day "+ "within that week. Months, years and year to date are this tool's sums of SB_01 days. "+ "dataset.public_updated_at is when GOV.UK last changed the publication."+)+_UK_NOTES = (+ _FLOW_NOT_STOCK,+ "Arrivals are counted when detected and the file has no person identifier, so a person who crosses more "+ "than once is counted each time. (Tool note, not a Home Office statement.)",+ "'-' in the file means no figure is published; it is returned as null, never 0 (dataset.coverage gives "+ "the first date with a figure). A month, year or week sum is null when any day in it is null.",+ "Months, years and year to date are sums of the SB_01 daily rows computed here, not Home Office "+ "publications; the quarterly 'Illegal entry routes to the UK' statistics hold the final figures.",+)+_UK_TERMS = "Open Government Licence v3.0 (GOV.UK terms); the time series is Crown copyright."+_UK_NOTE_ROW = re.compile(r"^\d+\.\s")+++def _repeat(element: ET.Element, attribute: str) -> int:+ raw = element.get(_T + attribute)+ if raw is None:+ return 1+ try:+ return max(int(raw), 1)+ except ValueError:+ raise ValueError(f"unreadable table:{attribute} {raw!r}") from None+++def _ods_inline(element: ET.Element) -> str:+ parts = [element.text or ""]+ for child in element:+ if child.tag == _X + "s":+ try:+ parts.append(" " * min(max(int(child.get(_X + "c", "1")), 1), 1024))+ except ValueError:+ parts.append(" ")+ elif child.tag == _X + "tab":+ parts.append("\t")+ elif child.tag == _X + "line-break":+ parts.append("\n")+ elif child.tag not in (_O + "annotation", _X + "note"):+ parts.append(_ods_inline(child))+ parts.append(child.tail or "")+ return "".join(parts)+++def _ods_text(cell: ET.Element) -> str:+ paragraphs: list[str] = []++ def walk(node: ET.Element) -> None:+ for child in node:+ if child.tag in (_X + "p", _X + "h"):+ paragraphs.append(_ods_inline(child))+ elif child.tag != _O + "annotation": # cell comments are not cell content+ walk(child)++ walk(cell)+ return "\n".join(paragraphs)+++def _ods_value(cell: ET.Element) -> Any:+ kind = cell.get(_O + "value-type")+ if kind in ("float", "percentage", "currency"):+ raw = cell.get(_O + "value")+ try:+ return float(raw)+ except (TypeError, ValueError):+ raise ValueError(f"unreadable number {raw!r}") from None+ if kind == "date":+ raw = cell.get(_O + "date-value") or ""+ try:+ moment = datetime.fromisoformat(raw)+ except ValueError:+ raise ValueError(f"unreadable date {raw!r}") from None+ if moment.tzinfo is None and moment.time() == datetime.min.time():+ return moment.date()+ return moment+ if kind == "boolean":+ return (cell.get(_O + "boolean-value") or "").lower() == "true"+ if kind == "time":+ return cell.get(_O + "time-value")+ if kind == "string" and cell.get(_O + "string-value") is not None:+ return cell.get(_O + "string-value")+ text = _ods_text(cell)+ return text if text else None+++def _ods_row(row: ET.Element) -> list[Any]:+ values: list[Any] = []+ pending_blank = 0+ for cell in row:+ if cell.tag not in (_T + "table-cell", _T + "covered-table-cell"):+ continue+ repeat = _repeat(cell, "number-columns-repeated")+ value = _ods_value(cell)+ if value is None:+ pending_blank += repeat # counted, never expanded: trailing blanks are dropped+ continue+ if len(values) + pending_blank >= _ODS_MAX_COLUMNS:+ break+ values.extend([None] * pending_blank)+ pending_blank = 0+ values.extend([value] * min(repeat, _ODS_MAX_COLUMNS - len(values)))+ if len(values) >= _ODS_MAX_COLUMNS:+ break+ return values+++def read_ods_tables(data: bytes) -> dict[str, list[list[Any]]]:+ """Every sheet of an ODS spreadsheet as rows of cell values.++ Numbers come back as float, dates as ``datetime.date`` (``datetime`` when the cell has a+ time of day), booleans as bool, anything else as its text with paragraphs joined by newlines;+ an empty cell is None. Blank rows are dropped and trailing blank cells trimmed, so the repeat+ counts that pad a sheet to 16,384 columns and 1,048,576 rows are never expanded. Columns past+ the 256th are not read. Raises ValueError for anything that is not a readable ODS spreadsheet.+ """+ try:+ archive = zipfile.ZipFile(io.BytesIO(data))+ except zipfile.BadZipFile as exc:+ raise ValueError("not an ODS file (not a zip archive)") from exc+ try:+ with archive:+ names = set(archive.namelist())+ if "mimetype" in names:+ with archive.open("mimetype") as handle:+ mimetype = handle.read(200).decode("ascii", errors="replace").strip()+ if mimetype != _ODS_TYPE:+ raise ValueError(f"not an ODS spreadsheet (mimetype {mimetype!r})")+ if "content.xml" not in names:+ raise ValueError("ODS file has no content.xml")+ if archive.getinfo("content.xml").file_size > _ODS_MAX_XML_BYTES:+ raise ValueError("ODS content.xml is larger than 64 MiB")+ with archive.open("content.xml") as handle:+ xml_bytes = handle.read(_ODS_MAX_XML_BYTES + 1)+ except (zipfile.BadZipFile, zlib.error, EOFError, OSError, NotImplementedError) as exc:+ raise ValueError(f"ODS archive not readable: {exc}") from exc+ if len(xml_bytes) > _ODS_MAX_XML_BYTES:+ raise ValueError("ODS content.xml is larger than 64 MiB")+ # Entities can only be declared in a DTD, so refusing one rules out entity+ # expansion ("billion laughs") and external entities (XXE) before the+ # standard-library parser runs;+ # ODF content.xml never carries a DTD. A hardened third-party XML parser+ # would be a new dependency.+ if b"<!DOCTYPE" in xml_bytes or b"<!ENTITY" in xml_bytes:+ raise ValueError("ODS content.xml declares a DTD; refused")+ try:+ root = ET.fromstring(xml_bytes)+ except ET.ParseError as exc:+ raise ValueError(f"ODS content.xml is not well-formed XML: {exc}") from exc+ tables: dict[str, list[list[Any]]] = {}+ for table in root.iter(_T + "table"):+ name = table.get(_T + "name") or f"Sheet{len(tables) + 1}"+ rows: list[list[Any]] = []+ for row in table.iter(_T + "table-row"):+ values = _ods_row(row)+ if not values:+ continue+ repeat = _repeat(row, "number-rows-repeated")+ if len(rows) + repeat > _ODS_MAX_ROWS:+ raise ValueError(f"sheet {name!r} has more than {_ODS_MAX_ROWS} rows")+ rows.extend(list(values) for _ in range(repeat))+ tables[name] = rows+ if not tables:+ raise ValueError("ODS file has no sheets")+ return tables+++def _header(value: Any) -> str:+ return " ".join(value.split()).lower() if isinstance(value, str) else ""+++def _locate(tables: dict[str, list[list[Any]]], preferred: str, first: str) -> tuple[str, int, dict] | None:+ """(sheet, header row index, column positions) of the table whose header names `first` and the arrivals."""+ order = [preferred, *[name for name in tables if name != preferred]] if preferred in tables else list(tables)+ for name in order:+ for i, row in enumerate(tables[name][:30]):+ heads = [_header(value) for value in row]+ if first in heads and "migrants arrived" in heads and "boats arrived" in heads:+ def find(label: str) -> int | None:+ return heads.index(label) if label in heads else None++ return name, i, {+ "when": heads.index(first),+ "migrants": heads.index("migrants arrived"),+ "boats": heads.index("boats arrived"),+ "uncontrolled": next((j for j, head in enumerate(heads) if "uncontrolled" in head), None),+ "prevented": find("migrants prevented"),+ "events": find("events prevented"),+ "notes": find("notes"),+ }+ return None+++def _uk_date(value: Any) -> date | None:+ if isinstance(value, datetime):+ return value.date()+ if isinstance(value, date):+ return value+ if isinstance(value, str):+ text = value.strip()+ for parse in (date.fromisoformat, lambda s: datetime.strptime(s, "%d/%m/%Y").date()):+ try:+ return parse(text)+ except ValueError:+ continue+ return None+++def _uk_count(value: Any) -> tuple[int | None, bool]:+ """(count, readable): '-' is a published "no figure" (None, readable)."""+ if isinstance(value, float) and value.is_integer() and value >= 0:+ return int(value), True+ if _is_int(value) and value >= 0:+ return value, True+ if isinstance(value, str) and value.strip() == "-":+ return None, True+ return None, False+++_UK_COLUMN_LABELS = {+ "migrants": "Migrants arrived",+ "boats": "Boats arrived",+ "uncontrolled": "Boats arrived - involved in uncontrolled landings",+ "prevented": "Migrants prevented",+ "events": "Events prevented",+}+++def _uk_series(table: list[list[Any]], located: tuple[str, int, dict], keys: tuple[str, ...],+ gaps: list[str]) -> list[list[Any]]:+ sheet, header_row, columns = located+ for key in keys:+ if columns[key] is None:+ gaps.append(f"{sheet} has no {_UK_COLUMN_LABELS[key]!r} column; those figures are null.")+ records: dict[str, list[Any]] = {}+ undated = unreadable = duplicates = 0+ for row in table[header_row + 1:]:+ def cell(key: str) -> Any:+ col = columns[key]+ return row[col] if col is not None and col < len(row) else None++ day = _uk_date(cell("when"))+ if day is None:+ undated += 1+ continue+ if day.isoformat() in records:+ duplicates += 1+ continue+ record: list[Any] = [day.isoformat()]+ for key in keys:+ if columns[key] is None:+ record.append(None)+ continue+ value, readable = _uk_count(cell(key))+ unreadable += not readable+ record.append(value)+ note = cell("notes")+ record.append(isinstance(note, str) and "revised" in note.lower())+ records[day.isoformat()] = record+ if undated:+ gaps.append(f"{undated} row(s) of {sheet} have no readable date and are not counted.")+ if unreadable:+ gaps.append(f"{unreadable} cell(s) of {sheet} are neither a count nor '-' and are read as null.")+ if duplicates:+ gaps.append(f"{duplicates} row(s) of {sheet} repeat an earlier date; the first is kept.")+ return [records[key] for key in sorted(records)]+++def parse_uk_small_boats(tables: dict[str, list[list[Any]]]) -> dict[str, Any]:+ """Daily (SB_01) and weekly (SB_02) rows plus the numbered notes of the Home Office time series.++ Daily rows are [date, migrants, boats, uncontrolled, revised]; weekly rows are+ [week ending, migrants, boats, uncontrolled, prevented, events prevented, revised].+ Raises ValueError when there is no daily table or it has no dated rows.+ """+ gaps: list[str] = []+ located = _locate(tables, "SB_01", "date")+ if located is None:+ raise ValueError("no SB_01 daily table (Date, Migrants arrived, Boats arrived) in the ODS")+ daily = _uk_series(tables[located[0]], located, ("migrants", "boats", "uncontrolled"), gaps)+ if not daily:+ raise ValueError(f"the daily table {located[0]} has no dated rows")+ weekly: list[list[Any]] = []+ located_weekly = _locate(tables, "SB_02", "week ending")+ if located_weekly is None:+ gaps.append("no SB_02 weekly table (Week ending, Migrants arrived, ...) in the ODS; weekly figures and "+ "preventions are missing.")+ else:+ weekly = _uk_series(tables[located_weekly[0]], located_weekly,+ ("migrants", "boats", "uncontrolled", "prevented", "events"), gaps)+ notes: list[str] = []+ for row in tables.get("Notes", []):+ if row and isinstance(row[0], str):+ text = "\n".join(line for line in (" ".join(part.split()) for part in row[0].split("\n")) if line)+ if _UK_NOTE_ROW.match(text):+ notes.append(text)+ if not notes:+ gaps.append("the ODS has no numbered notes on a Notes sheet; the Home Office caveats are missing.")+ return {"schema": _UK_SCHEMA, "daily": daily, "weekly": weekly, "notes": notes, "gaps": gaps}+++def _uk_attachment(item: Any) -> dict[str, Any]:+ details = item.get("details") if isinstance(item, dict) else None+ attachments = details.get("attachments") if isinstance(details, dict) else None+ candidates = [+ a for a in attachments or []+ if isinstance(a, dict)+ and (a.get("content_type") == _ODS_TYPE or str(a.get("filename") or "").lower().endswith(".ods"))+ ]+ if not candidates:+ raise _SourceError("uk_unexpected_format", "the GOV.UK publication lists no ODS time-series attachment")+ candidates.sort(key=lambda a: "time series" not in str(a.get("title") or "").lower())+ chosen = candidates[0]+ url = urljoin("https://www.gov.uk/", str(chosen.get("url") or ""))+ parts = urlsplit(url)+ if parts.scheme != "https" or parts.hostname not in _UK_FILE_HOSTS:+ raise _SourceError("uk_unexpected_format",+ f"the time-series attachment is not on GOV.UK ({parts.hostname or 'no host'})")+ size = chosen.get("file_size")+ return {"url": url, "title": chosen.get("title"), "file_size_bytes": size if _is_int(size) else None}+++async def _fetch_uk_dataset(fetcher: Fetcher) -> dict[str, Any]:+ api = await fetcher.get_bytes(+ UK_CONTENT_API, UK_SOURCE, headers={**_HEADERS, "Accept": "application/json"}, max_bytes=_UK_API_MAX_BYTES+ )+ if api.content is None:+ raise _SourceError("uk_fetch_failed", f"GOV.UK Content API unavailable: {_why(api)}")+ try:+ item = json.loads(api.content)+ except ValueError as exc:+ raise _SourceError("uk_unexpected_format", f"GOV.UK Content API did not return JSON: {exc}") from exc+ attachment = _uk_attachment(item)+ ods = await fetcher.get_bytes(attachment["url"], UK_SOURCE, headers=_HEADERS, max_bytes=_UK_ODS_MAX_BYTES)+ if ods.content is None:+ raise _SourceError("uk_fetch_failed", f"Home Office time series unavailable: {_why(ods)}")+ try:+ dataset = parse_uk_small_boats(read_ods_tables(ods.content))+ except ValueError as exc:+ raise _SourceError("uk_unexpected_format", f"Home Office time series not readable: {exc}") from exc+ history = [h for h in (item.get("details") or {}).get("change_history") or [] if isinstance(h, dict)]+ newest = max(history, key=lambda h: str(h.get("public_timestamp") or ""), default={})+ dataset["meta"] = {+ "title": attachment["title"],+ "url": attachment["url"],+ "publication": item.get("title"),+ "page": "https://www.gov.uk" + str(item.get("base_path") or UK_PUBLICATION_PATH),+ "public_updated_at": item.get("public_updated_at"),+ "latest_change_note": str(newest.get("note") or "").strip() or None,+ "file_size_bytes": attachment["file_size_bytes"],+ "fetched_at": _now(),+ }+ return dataset+++def _total(rows: list[list[Any]], column: int) -> int | None:+ """Sum of one column, or None when any row has no figure for it."""+ values = [row[column] for row in rows]+ return None if any(v is None for v in values) else sum(values)+++def _iso_days(start: date, end: date) -> list[str]:+ return [(start + timedelta(days=k)).isoformat() for k in range((end - start).days + 1)]+++async def fetch_uk_small_boat_arrivals(+ fetcher: Fetcher,+ days: int | None = 14,+ weeks: int | None = 8,+ months: int | None = 13,+) -> dict[str, Any]:+ """UK small-boat arrivals: latest days and weeks, month and year sums, year to date vs last year."""+ days = 14 if days is None else days+ weeks = 8 if weeks is None else weeks+ months = 13 if months is None else months+ for name, value, high in (("days", days, 400), ("weeks", weeks, 520), ("months", months, 240)):+ if not _is_int(value) or not 1 <= value <= high:+ return _usage(UK_SOURCE, f"{name} must be an integer from 1 to {high}")++ dataset, state = await _load(fetcher, UK_CACHE_KEY, _UK_TTL, _UK_SCHEMA, _fetch_uk_dataset)+ if dataset is None:+ return _degraded(UK_SOURCE, state["error"], state["reason"])++ daily: list[list[Any]] = dataset["daily"]+ weekly: list[list[Any]] = dataset["weekly"]+ gaps = list(dataset["gaps"])+ meta = dataset["meta"]+ by_date = {row[0]: row for row in daily}+ first_day, last_day = date.fromisoformat(daily[0][0]), date.fromisoformat(daily[-1][0])+ missing_days = (last_day - first_day).days + 1 - len(daily)+ if missing_days:+ gaps.append(f"{missing_days} day(s) between {first_day} and {last_day} have no SB_01 row; sums over them "+ "cover only the days reported (see days_reported).")++ def day(row: list[Any]) -> dict[str, Any]:+ return {"date": row[0], "migrants_arrived": row[1], "boats_arrived": row[2],+ "boats_uncontrolled_landings": row[3], "revised": row[4]}++ def week(row: list[Any]) -> dict[str, Any]:+ return {"week_ending": row[0],+ "period_start": (date.fromisoformat(row[0]) - timedelta(days=6)).isoformat(),+ "period_end": row[0], "migrants_arrived": row[1], "boats_arrived": row[2],+ "boats_uncontrolled_landings": row[3], "migrants_prevented": row[4], "events_prevented": row[5],+ "revised": row[6]}++ seven = [row for row in daily if row[0] >= (last_day - timedelta(days=6)).isoformat()]+ last_7_days = {+ "period_start": (last_day - timedelta(days=6)).isoformat(),+ "period_end": last_day.isoformat(),+ "days_reported": len(seven),+ "migrants_arrived": _total(seven, 1),+ "boats_arrived": _total(seven, 2),+ "boats_uncontrolled_landings": _total(seven, 3),+ }++ shown_weeks = weekly[-weeks:]+ for row in shown_weeks:+ ending = date.fromisoformat(row[0])+ days_in_week = [by_date.get(d) for d in _iso_days(ending - timedelta(days=6), ending)]+ if not all(days_in_week):+ continue+ for column, label in ((1, "migrants"), (2, "boats")):+ summed = _total(days_in_week, column)+ if row[column] is not None and summed is not None and summed != row[column]:+ gaps.append(f"SB_02 week ending {row[0]} has {row[column]} {label}; the seven SB_01 days sum to "+ f"{summed}.")++ by_month: dict[str, list[list[Any]]] = defaultdict(list)+ by_year: dict[int, list[list[Any]]] = defaultdict(list)+ for row in daily:+ by_month[row[0][:7]].append(row)+ by_year[int(row[0][:4])].append(row)+ window_start = _shift_months(last_day.isoformat()[:7], -(months - 1))+ month_list = []+ for period in sorted(p for p in by_month if p >= window_start):+ rows = by_month[period]+ year, number = int(period[:4]), int(period[5:])+ length = calendar.monthrange(year, number)[1]+ month_list.append({+ "period": period,+ "period_start": max(date(year, number, 1), first_day).isoformat(),+ "period_end": min(date(year, number, length), last_day).isoformat(),+ "complete": len(rows) == length,+ "days_reported": len(rows),+ "days_in_month": length,+ "migrants_arrived": _total(rows, 1),+ "boats_arrived": _total(rows, 2),+ "boats_uncontrolled_landings": _total(rows, 3),+ })+ year_list = []+ for year in sorted(by_year):+ rows = by_year[year]+ year_list.append({+ "year": year,+ "period_start": max(date(year, 1, 1), first_day).isoformat(),+ "period_end": min(date(year, 12, 31), last_day).isoformat(),+ "complete": len(rows) == (366 if calendar.isleap(year) else 365),+ "days_reported": len(rows),+ "migrants_arrived": _total(rows, 1),+ "boats_arrived": _total(rows, 2),+ "boats_uncontrolled_landings": _total(rows, 3),+ })++ ytd_rows = [row for row in daily if row[0] >= f"{last_day.year:04d}-01-01"]+ prior_start = date(last_day.year - 1, 1, 1)+ prior_end = (last_day.replace(day=28) if (last_day.month, last_day.day) == (2, 29) else last_day).replace(+ year=last_day.year - 1)+ prior_rows = [by_date.get(d) for d in _iso_days(prior_start, prior_end)]+ prior = None+ if all(prior_rows):+ prior = {"period_start": prior_start.isoformat(), "period_end": prior_end.isoformat(),+ "migrants_arrived": _total(prior_rows, 1), "boats_arrived": _total(prior_rows, 2)}+ else:+ gaps.append(f"SB_01 has no complete daily series for {prior_start} to {prior_end}, so year to date has no "+ "prior-year comparison.")+ current_migrants, current_boats = _total(ytd_rows, 1), _total(ytd_rows, 2)+ prior_migrants = prior["migrants_arrived"] if prior else None+ prior_boats = prior["boats_arrived"] if prior else None+ year_to_date = {+ "period_start": f"{last_day.year:04d}-01-01",+ "period_end": last_day.isoformat(),+ "migrants_arrived": current_migrants,+ "boats_arrived": current_boats,+ "prior_year": prior,+ "change_migrants": _diff(current_migrants, prior_migrants),+ "pct_change_migrants": _pct(current_migrants, prior_migrants),+ "change_boats": _diff(current_boats, prior_boats),+ "pct_change_boats": _pct(current_boats, prior_boats),+ }++ def first_with(rows: list[list[Any]], column: int) -> str | None:+ return next((row[0] for row in rows if row[column] is not None), None)++ result: dict[str, Any] = {+ "publisher": "UK Home Office",+ "dataset": {+ "title": meta["title"],+ "url": meta["url"],+ "publication": meta["publication"],+ "page": meta["page"],+ "public_updated_at": meta["public_updated_at"],+ "latest_change_note": meta["latest_change_note"],+ "file_size_bytes": meta["file_size_bytes"],+ "daily_data_through": last_day.isoformat(),+ "weekly_data_through": weekly[-1][0] if weekly else None,+ "coverage": {+ "daily_from": first_day.isoformat(),+ "uncontrolled_landings_from": first_with(daily, 3),+ "weekly_from": weekly[0][0] if weekly else None,+ "preventions_from": first_with(weekly, 4),+ },+ "fetched_at": meta["fetched_at"],+ },+ "measure_kind": "flow",+ "measure": _UK_MEASURE,+ "unit": _UK_UNIT,+ "date_semantics": _UK_DATE_SEMANTICS,+ "latest_day": day(daily[-1]),+ "last_7_days": last_7_days,+ "daily": [day(row) for row in daily[-days:]],+ "latest_week": week(weekly[-1]) if weekly else None,+ "weeks": [week(row) for row in shown_weeks],+ "months": month_list,+ "years": year_list,+ "year_to_date": year_to_date,+ "revised_dates": [row[0] for row in daily if row[4] and row[0][:7] >= window_start],+ "publisher_caveats": list(dataset["notes"]),+ "publisher_caveats_source": "Notes sheet of the time-series file (dataset.url), read on every refresh.",+ "terms": _UK_TERMS,+ "notes": list(_UK_NOTES),+ }+ _freshness(result, state, gaps, meta["fetched_at"])+ result["data_gaps"] = gaps+ result["source"] = UK_SOURCE+ result["timestamp"] = _now()+ return resultdiff --git a/src/world_intel_mcp/tests/test_sources_border_crossings.py b/src/world_intel_mcp/tests/test_sources_border_crossings.pynew file mode 100644index 0000000..d2aab40--- /dev/null+++ b/src/world_intel_mcp/tests/test_sources_border_crossings.py@@ -0,0 +1,1666 @@+"""Tests for sources/border_crossings.py: CBP encounters and UK small-boat arrivals.++Every figure asserted here comes from data captured live on 2026-10-17.++* CBP: the dataset page https://www.cbp.gov/document/stats/nationwide-encounters+ (its "Last Modified: Sep 16, 2026") and its newest file,+ nationwide-encounters-fy23-fy26-aug-aor_0.csv (6,730,588 bytes, 52,986 rows).+ ``_CBP_NORTHERN_USBP_AUG`` is every row of that file for U.S. Border Patrol on+ the Northern Land Border in August FY2025 and August FY2026 (167 rows,+ verbatim). Their sums, 586 and 563, are the figures CBP itself publishes as+ "Northern Border Total Apprehensions" for Aug-25 and Aug-26 on its FY2025 and+ FY2026 encounter pages, so those assertions check the parser against the+ publisher, not against the fixture. ``_CBP_FEATURE_ROWS`` are nine more+ verbatim rows chosen to exercise the "2026 (FYTD)" label, October rows+ (calendar year FY-1), the "Remaining" month grouping, a Title 42 expulsion,+ a quoted citizenship and CBP's OTHER bucket; sums over them are fixture sums.+* UK: the GOV.UK Content API item for "Small boat activity in the English+ Channel" (public_updated_at 2026-10-16T13:13:46+01:00) and its ODS time series+ (16_October_2026_Small_boats_-_time_series.ods, 76,787 bytes). An ODS is a+ zip, which a text diff cannot carry, so ``_ods`` rebuilds one from verbatim+ values (every daily row from 1 January 2025 to 15 October 2026, ten weekly+ rows, three of the nine notes) using the cell markup of the live+ content.xml, including the trailing blank repeats that pad every sheet to+ 16,384 columns and 1,048,576 rows. The latest week (1,066 migrants, 15+ boats, 245 prevented, 12 events prevented) and the last 7 days (all 0) are+ the figures the Home Office publishes on its weekly-summary and last-7-days+ pages.++Gaps / not covered: the live publishers are reached only by the two smoke+tests at the end (deselected by default; ``pytest -m smoke -k live_``), whose+assertions are structural because live figures move; CBP's by-state file; an+ODS written by an application other than the one the Home Office uses;+GOV.UK redirects; a CBP CSV that is not UTF-8.+"""++from __future__ import annotations++import asyncio as asyncio_mod+import copy+import io+import zipfile+from collections import Counter+from contextlib import contextmanager+from datetime import date++import httpx+import pytest+import respx++from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.sources import border_crossings as bc+++def _no_sleep(monkeypatch: pytest.MonkeyPatch) -> None:+ async def _instant(*args, **kwargs) -> None:+ return None++ monkeypatch.setattr(asyncio_mod, "sleep", _instant)+++def _no_numbers(result: dict) -> bool:+ """True when a response carries no numeric figure at any top-level key."""+ return not any(isinstance(v, (int, float)) and not isinstance(v, bool) for v in result.values())+++# ---------------------------------------------------------------------------+# CBP: captured shapes+# ---------------------------------------------------------------------------++_CBP_CSV_URL = "https://www.cbp.gov/sites/default/files/2026-09/nationwide-encounters-fy23-fy26-aug-aor_0.csv"++_CBP_HEADER = (+ "Fiscal Year,Month Grouping,Month (abbv),Component,Land Border Region,Area of Responsibility,"+ "AOR (Abbv),Demographic,Citizenship,Title of Authority,Encounter Type,Encounter Count"+)++# Every row of the live file for U.S. Border Patrol, Northern Land Border, August FY2025 and FY2026.+_CBP_NORTHERN_USBP_AUG = """\+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,FMUA,INDIA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,FMUA,ROMANIA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,CANADA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,EL SALVADOR,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,GUATEMALA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,INDIA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,MEXICO,Title 8,Apprehensions,5+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,OTHER,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,VENEZUELA,Title 8,Apprehensions,3+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,FMUA,GUATEMALA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,BRAZIL,Title 8,Apprehensions,6+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,CANADA,Title 8,Apprehensions,30+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,COLOMBIA,Title 8,Apprehensions,11+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,ECUADOR,Title 8,Apprehensions,28+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,EL SALVADOR,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,GUATEMALA,Title 8,Apprehensions,22+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,HAITI,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,HONDURAS,Title 8,Apprehensions,8+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,MEXICO,Title 8,Apprehensions,32+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,NICARAGUA,Title 8,Apprehensions,9+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,OTHER,Title 8,Apprehensions,7+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,PERU,Title 8,Apprehensions,3+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,RUSSIA,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,TURKEY,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,VENEZUELA,Title 8,Apprehensions,8+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,UAC,ECUADOR,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,UAC,GUATEMALA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,UAC,MEXICO,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,FMUA,MEXICO,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,"CHINA, PEOPLES REPUBLIC OF",Title 8,Apprehensions,4+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,COLOMBIA,Title 8,Apprehensions,5+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,CUBA,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,ECUADOR,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,EL SALVADOR,Title 8,Apprehensions,4+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,GUATEMALA,Title 8,Apprehensions,12+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,HONDURAS,Title 8,Apprehensions,23+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,MEXICO,Title 8,Apprehensions,89+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,NICARAGUA,Title 8,Apprehensions,3+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,OTHER,Title 8,Apprehensions,9+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,PERU,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,ROMANIA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,TURKEY,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,VENEZUELA,Title 8,Apprehensions,20+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,UAC,MEXICO,Title 8,Apprehensions,4+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,CANADA,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,ECUADOR,Title 8,Apprehensions,5+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,EL SALVADOR,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,GUATEMALA,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,HONDURAS,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,MEXICO,Title 8,Apprehensions,21+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,NICARAGUA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,PERU,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,VENEZUELA,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,Single Adults,GUATEMALA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,Single Adults,MEXICO,Title 8,Apprehensions,13+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,UAC,MEXICO,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,FMUA,GUATEMALA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,BRAZIL,Title 8,Apprehensions,3+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,COLOMBIA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,ECUADOR,Title 8,Apprehensions,19+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,EL SALVADOR,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,GUATEMALA,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,HONDURAS,Title 8,Apprehensions,3+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,INDIA,Title 8,Apprehensions,3+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,MEXICO,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,OTHER,Title 8,Apprehensions,9+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,TURKEY,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,FMUA,GUATEMALA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,FMUA,VENEZUELA,Title 8,Apprehensions,4+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,Single Adults,EL SALVADOR,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,Single Adults,GUATEMALA,Title 8,Apprehensions,7+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,Single Adults,HONDURAS,Title 8,Apprehensions,3+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,Single Adults,MEXICO,Title 8,Apprehensions,12+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,Single Adults,NICARAGUA,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,Single Adults,OTHER,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,Single Adults,VENEZUELA,Title 8,Apprehensions,3+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,FMUA,INDIA,Title 8,Apprehensions,4+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,CANADA,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,"CHINA, PEOPLES REPUBLIC OF",Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,COLOMBIA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,ECUADOR,Title 8,Apprehensions,9+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,EL SALVADOR,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,GUATEMALA,Title 8,Apprehensions,10+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,HAITI,Title 8,Apprehensions,3+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,HONDURAS,Title 8,Apprehensions,7+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,INDIA,Title 8,Apprehensions,4+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,MEXICO,Title 8,Apprehensions,11+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,NICARAGUA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,OTHER,Title 8,Apprehensions,8+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,PERU,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,RUSSIA,Title 8,Apprehensions,2+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,TURKEY,Title 8,Apprehensions,1+2025,FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,VENEZUELA,Title 8,Apprehensions,5+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,"CHINA, PEOPLES REPUBLIC OF",Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,EL SALVADOR,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,GUATEMALA,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,INDIA,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,MEXICO,Title 8,Apprehensions,15+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,NICARAGUA,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Blaine Sector,BLW,Single Adults,RUSSIA,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,BRAZIL,Title 8,Apprehensions,5+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,CANADA,Title 8,Apprehensions,13+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,"CHINA, PEOPLES REPUBLIC OF",Title 8,Apprehensions,9+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,COLOMBIA,Title 8,Apprehensions,7+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,CUBA,Title 8,Apprehensions,3+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,ECUADOR,Title 8,Apprehensions,16+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,EL SALVADOR,Title 8,Apprehensions,4+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,GUATEMALA,Title 8,Apprehensions,35+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,HONDURAS,Title 8,Apprehensions,24+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,MEXICO,Title 8,Apprehensions,51+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,NICARAGUA,Title 8,Apprehensions,7+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,OTHER,Title 8,Apprehensions,10+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,RUSSIA,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Buffalo Sector,BUN,Single Adults,VENEZUELA,Title 8,Apprehensions,23+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,FMUA,GUATEMALA,Title 8,Apprehensions,3+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,FMUA,HONDURAS,Title 8,Apprehensions,7+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,COLOMBIA,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,ECUADOR,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,EL SALVADOR,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,GUATEMALA,Title 8,Apprehensions,23+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,HAITI,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,HONDURAS,Title 8,Apprehensions,25+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,MEXICO,Title 8,Apprehensions,67+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,NICARAGUA,Title 8,Apprehensions,6+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,ROMANIA,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,Single Adults,VENEZUELA,Title 8,Apprehensions,12+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,UAC,CANADA,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Detroit Sector,DTM,UAC,HONDURAS,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,COLOMBIA,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,GUATEMALA,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,HONDURAS,Title 8,Apprehensions,3+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,MEXICO,Title 8,Apprehensions,8+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,NICARAGUA,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Grand Forks Sector,GFN,Single Adults,OTHER,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,FMUA,COLOMBIA,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,FMUA,MEXICO,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,Single Adults,CANADA,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,Single Adults,COLOMBIA,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,Single Adults,EL SALVADOR,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,Single Adults,GUATEMALA,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,Single Adults,HONDURAS,Title 8,Apprehensions,10+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,Single Adults,MEXICO,Title 8,Apprehensions,28+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,Single Adults,OTHER,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,Single Adults,VENEZUELA,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Havre Sector,HVM,UAC,MEXICO,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,FMUA,OTHER,Title 8,Apprehensions,6+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,BRAZIL,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,ECUADOR,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Houlton Sector,HLT,Single Adults,HONDURAS,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,Single Adults,CANADA,Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,Single Adults,GUATEMALA,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Spokane Sector,SPW,Single Adults,MEXICO,Title 8,Apprehensions,14+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,FMUA,BRAZIL,Title 8,Apprehensions,4+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,FMUA,OTHER,Title 8,Apprehensions,6+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,FMUA,VENEZUELA,Title 8,Apprehensions,4+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,CANADA,Title 8,Apprehensions,6+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,"CHINA, PEOPLES REPUBLIC OF",Title 8,Apprehensions,1+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,ECUADOR,Title 8,Apprehensions,3+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,GUATEMALA,Title 8,Apprehensions,3+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,HAITI,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,HONDURAS,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,INDIA,Title 8,Apprehensions,17+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,MEXICO,Title 8,Apprehensions,5+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,OTHER,Title 8,Apprehensions,29+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,Single Adults,VENEZUELA,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,UAC,INDIA,Title 8,Apprehensions,2+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Northern Land Border,Swanton Sector,SWB,UAC,OTHER,Title 8,Apprehensions,1+"""++_CBP_FEATURE_ROWS = """\+2026 (FYTD),FYTD,AUG,U.S. Border Patrol,Southwest Land Border,Big Bend Sector,BBT,Single Adults,MEXICO,Title 8,Apprehensions,86+2025,FYTD,AUG,U.S. Border Patrol,Southwest Land Border,Big Bend Sector,BBT,Single Adults,MEXICO,Title 8,Apprehensions,123+2026 (FYTD),FYTD,AUG,Office of Field Operations,Southwest Land Border,El Paso Field Office,El Paso,Single Adults,"CHINA, PEOPLES REPUBLIC OF",Title 8,Inadmissibles,6+2026 (FYTD),FYTD,AUG,Office of Field Operations,Other,Atlanta Field Office,Atlanta,Accompanied Minors,INDIA,Title 8,Inadmissibles,2+2026 (FYTD),FYTD,AUG,Office of Field Operations,Other,Atlanta Field Office,Atlanta,Accompanied Minors,OTHER,Title 8,Inadmissibles,3+2026 (FYTD),FYTD,AUG,Office of Field Operations,Southwest Land Border,Tucson Field Office,Tucson,UAC,GUATEMALA,Title 8,Inadmissibles,1+2026 (FYTD),FYTD,OCT,U.S. Border Patrol,Southwest Land Border,Big Bend Sector,BBT,Single Adults,MEXICO,Title 8,Apprehensions,105+2023,Remaining,SEP,U.S. Border Patrol,Southwest Land Border,Big Bend Sector,BBT,Single Adults,MEXICO,Title 8,Apprehensions,361+2023,FYTD,OCT,U.S. Border Patrol,Southwest Land Border,Big Bend Sector,BBT,Single Adults,MEXICO,Title 42,Expulsions,700+"""++# Excerpt of the dataset page, markup verbatim: its two caveat paragraphs, two+# listings of the same files (the list, and the table with Size and Date), and its date.+_CBP_PAGE = """<html><body><main>+<p>Encounter data includes U.S. Border Patrol Title 8 apprehensions, Office of Field Operations Title 8 inadmissibles, and all Title 42 expulsions for fiscal years 2020 to date. Data is available for the Northern Land Border, Southwest Land Border, and Nationwide (i.e., air, land, and sea modes of transportation) encounters.</p><p>Data is extracted from live CBP systems and data sources. Statistical information is subject to change due to corrections, systems changes, change in data definition, additional information, or encounters pending final review. Final statistics are available at the conclusion of each fiscal year.</p><h2 class="usa-prose">Dashboard Dataset</h2><ul class="undecorated list">+<li data-list-item-id="e1ecbc5891880c7a7d8acd71071175f63"><a href="/sites/default/files/2026-09/nationwide-encounters-fy23-fy26-aug-aor_0.csv">FY23 - FY26 (FYTD) Nationwide Encounters by Area of Responsibility - August</a></li>+<li data-list-item-id="e0df05b7a56b969b8b26877053451d6f5"><a href="/sites/default/files/2026-09/nationwide-encounters-fy23-fy26-aug-state.csv">FY23 - FY26 (FYTD) Nationwide Encounters by State - August</a></li>+<li data-list-item-id="e4cae405a56918198ee5dbf1fc5ec7d53"><a href="/sites/default/files/2026-08/nationwide-encounters-fy23-fy26-jul-aor.csv">FY23 - FY26 (FYTD) Nationwide Encounters by Area of Responsibility - July</a></li>+<li data-list-item-id="e5a208075bf353a5ada9645c00e4d8c4d"><a href="/sites/default/files/2025-11/nationwide-encounters-fy22-fy25-aor.csv">FY22 - FY25 Nationwide Encounters by Area of Responsibility</a></li>+<li data-list-item-id="e56e6b8ae6cb5e3b64889e44724858fdf"><a href="/sites/default/files/2024-10/nationwide-encounters-fy21-fy24-aor.csv">FY21 - FY24 Nationwide Encounters by Area of Responsibility</a></li>+<li data-list-item-id="e1fbf2f1de91328f2c6b5881685a722fd"><a href="/sites/default/files/assets/documents/2023-Nov/nationwide-encounters-fy20-fy23-aor.csv">FY20 - FY23 Nationwide Encounters by Area of Responsibility</a></li>+</ul>+<table><tbody>+<tr scope="row">+ <th scope="row" role="rowheader" data-sort-value=" Nationwide Encounters Dataset FY23-FY26 by Area of Responsibility - August">+ <a href="/sites/default/files/2026-09/nationwide-encounters-fy23-fy26-aug-aor_0.csv">+ Nationwide Encounters Dataset FY23-FY26 by Area of Responsibility - August+ </a>+ </th>+ <td data-sort-value="CSV">CSV</td>+ <td data-sort-value="6730588">+ 6.42 MB+ </td>+ <td data-sort-value="09/04/2026">+ 09/04/2026+ </td>+</tr>+<tr scope="row">+ <th scope="row" role="rowheader" data-sort-value="Nationwide Encounters Dataset FY23-FY26 by Area of Responsibility - July">+ <a href="/sites/default/files/2026-08/nationwide-encounters-fy23-fy26-jul-aor.csv">+ Nationwide Encounters Dataset FY23-FY26 by Area of Responsibility - July+ </a>+ </th>+ <td data-sort-value="CSV">CSV</td>+ <td data-sort-value="6616104">+ 6.31 MB+ </td>+ <td data-sort-value="08/05/2026">+ 08/05/2026+ </td>+</tr>+</tbody></table>+<div class="margin-top-8 margin-bottom-0 "><span class="text-bold">Last Modified: Sep 16, 2026</span></div>+</main></body></html>"""+++@contextmanager+def _cbp_mock(rows: str, csv_response: httpx.Response | None = None, page: str = _CBP_PAGE):+ with respx.mock(assert_all_called=False) as mock:+ mock.get(bc.CBP_DATASET_PAGE).mock(return_value=httpx.Response(+ 200, text=page, headers={"content-type": "text/html; charset=utf-8"}))+ mock.get(_CBP_CSV_URL).mock(return_value=csv_response or httpx.Response(+ 200, text=_CBP_HEADER + "\n" + rows, headers={"content-type": "text/csv"}))+ yield mock+++# ---------------------------------------------------------------------------+# CBP: file discovery and calendar mapping+# ---------------------------------------------------------------------------++def test_cbp_newest_aor_file_and_its_dates_come_from_the_dataset_page() -> None:+ assert bc.latest_cbp_file(_CBP_PAGE) == {+ "url": _CBP_CSV_URL,+ "title": "FY23 - FY26 (FYTD) Nationwide Encounters by Area of Responsibility - August",+ "file_date": "2026-09-04",+ "size_bytes": 6730588,+ "newer_disallowed_url": None, # the FY20-FY23 file under /assets/documents/ is older+ }+ assert bc.cbp_page_last_modified(_CBP_PAGE) == "2026-09-16"+ assert bc.latest_cbp_file("<html><body><p>No links today.</p></body></html>") is None+++_INVENTED_DISALLOWED = "/sites/default/files/assets/documents/2026-10/nationwide-encounters-fy23-fy26-sep-aor.csv"+++def _page_with_disallowed_september() -> str:+ # Invented link, not on the live page: the newest-looking file, but under+ # /sites/default/files/assets/documents/, which cbp.gov's robots.txt disallows.+ return _CBP_PAGE.replace(+ '<ul class="undecorated list">',+ f'<ul class="undecorated list"><li><a href="{_INVENTED_DISALLOWED}">FY23 - FY26 (FYTD) Nationwide '+ 'Encounters by Area of Responsibility - September</a></li>',+ )+++def test_cbp_never_picks_a_path_robots_txt_disallows() -> None:+ latest = bc.latest_cbp_file(_page_with_disallowed_september())+ assert latest["url"] == _CBP_CSV_URL+ assert latest["newer_disallowed_url"] == "https://www.cbp.gov" + _INVENTED_DISALLOWED+ # Only disallowed links: nothing is chosen.+ only = '<html><body><a href="%s">September</a></body></html>' % _INVENTED_DISALLOWED+ assert bc.latest_cbp_file(only) is None+++async def test_cbp_newer_file_behind_robots_txt_is_named_not_read(fetcher: Fetcher) -> None:+ with _cbp_mock(_CBP_NORTHERN_USBP_AUG, page=_page_with_disallowed_september()) as mock:+ result = await bc.fetch_us_border_encounters(fetcher, region="northern", component="usbp")+ urls = [str(call.request.url) for call in mock.calls] # read inside: respx clears calls on exit+ assert urls == [bc.CBP_DATASET_PAGE, _CBP_CSV_URL] # nothing under /assets/documents/ was requested+ assert result["latest"]["period"] == "2026-08"+ assert any("robots.txt disallows" in gap and _INVENTED_DISALLOWED in gap for gap in result["data_gaps"])+++def test_cbp_fiscal_months_map_to_calendar_months() -> None:+ assert bc.cbp_period(2026, "OCT") == "2025-10" # FY2026 starts 1 October 2025+ assert bc.cbp_period(2026, "DEC") == "2025-12"+ assert bc.cbp_period(2026, "JAN") == "2026-01"+ assert bc.cbp_period(2023, "SEP") == "2023-09"+ with pytest.raises(ValueError):+ bc.cbp_period(2026, "Sept")+++def test_cbp_csv_without_the_expected_columns_is_refused() -> None:+ with pytest.raises(ValueError, match="Encounter Count"):+ bc.parse_cbp_csv("Fiscal Year,Month (abbv),Citizenship\n2026 (FYTD),AUG,MEXICO\n")+ with pytest.raises(ValueError, match="no data rows"):+ bc.parse_cbp_csv(_CBP_HEADER + "\n")+++def test_cbp_csv_with_a_byte_order_mark_still_parses() -> None:+ # The live file starts with "Fiscal Year" (no BOM, checked 2026-10-17); a+ # re-saved export often gains one, and the header must still be found.+ parsed = bc.parse_cbp_csv("\ufeff" + _CBP_HEADER + "\n" + _CBP_NORTHERN_USBP_AUG)+ assert (parsed["rows"], parsed["unreadable_rows"]) == (167, 0)+ by_period = Counter()+ for cell in parsed["cells"]:+ by_period[parsed["periods"][cell[0]]] += cell[-1]+ assert by_period == {"2025-08": 586, "2026-08": 563}+++# ---------------------------------------------------------------------------+# CBP: real figures+# ---------------------------------------------------------------------------++async def test_cbp_northern_border_patrol_matches_cbp_published_apprehensions(fetcher: Fetcher) -> None:+ with _cbp_mock(_CBP_NORTHERN_USBP_AUG) as mock:+ result = await bc.fetch_us_border_encounters(fetcher, region="northern", component="usbp")+ requests = [call.request for call in mock.calls] # read inside: respx clears calls on exit+ assert "degraded" not in result and "error" not in result+ assert result["stale"] is False+ assert result["selection"] == {"region": "Northern Land Border", "component": "U.S. Border Patrol",+ "citizenship": None}+ latest = result["latest"]+ assert latest["period"] == "2026-08"+ assert (latest["period_start"], latest["period_end"]) == ("2026-08-01", "2026-08-31")+ assert latest["fiscal_year"] == 2026+ assert latest["encounters"] == 563 # CBP FY2026 page, Northern Border Total Apprehensions, Aug-26+ assert latest["same_month_prior_year"] == 586 # CBP FY2025 page, Aug-25+ assert latest["change_vs_prior_year"] == -23+ assert latest["pct_change_vs_prior_year"] == -3.9+ month = result["months"][-1]+ assert month["by_encounter_type"] == {"Apprehensions": 563}+ assert month["by_demographic"] == {"Single Adults": 522, "FMUA": 34, "UAC": 7}+ top = result["top_citizenships_latest_month"]+ assert [(c["citizenship"], c["encounters"]) for c in top[:3]] == [+ ("MEXICO", 191), ("HONDURAS", 73), ("GUATEMALA", 70)]+ assert top[0]["share_pct"] == 33.9+ assert result["other_citizenships_latest_month"] == 54 # CBP's OTHER bucket, never ranked+ assert all(c["citizenship"] != "OTHER" for c in top)++ dataset = result["dataset"]+ assert dataset["url"] == _CBP_CSV_URL+ assert dataset["file_date"] == "2026-09-04"+ assert dataset["page_last_modified"] == "2026-09-16"+ assert dataset["coverage"] == {"first_period": "2025-08", "last_period": "2026-08"}+ assert result["measure_kind"] == "flow"+ assert result["unit"].startswith("encounters")+ assert any("not unique people" in n for n in result["notes"])+ assert any("Data is extracted from live CBP systems" in c for c in result["publisher_caveats"])+ # The slice holds two months a year apart: the eleven between are named, never filled with zeros.+ assert len(result["data_gaps"]) == 1+ assert result["data_gaps"][0].startswith(+ "11 month(s) between 2025-08 and 2026-08 have no rows in CBP's file and are not listed: 2025-09, ")+ assert [m["period"] for m in result["months"]] == ["2025-08", "2026-08"]+ # Two requests (the page, then the file), each with an honest, identifying User-Agent.+ assert [str(r.url) for r in requests] == [bc.CBP_DATASET_PAGE, _CBP_CSV_URL]+ assert all(r.headers["user-agent"] == bc.USER_AGENT for r in requests)+ assert "github.com/marc-shade/world-intel-mcp" in bc.USER_AGENT+++async def test_cbp_regions_citizenships_and_the_other_bucket(fetcher: Fetcher) -> None:+ with _cbp_mock(_CBP_FEATURE_ROWS):+ nation = await bc.fetch_us_border_encounters(fetcher)+ south = await bc.fetch_us_border_encounters(fetcher, region="southwest")+ other = await bc.fetch_us_border_encounters(fetcher, region="other")+ mexico = await bc.fetch_us_border_encounters(fetcher, citizenship="mexico")+ china = await bc.fetch_us_border_encounters(fetcher, citizenship="China, Peoples Republic of")+ nowhere = await bc.fetch_us_border_encounters(fetcher, citizenship="Atlantis")++ latest = nation["latest"]+ assert (latest["period"], latest["encounters"]) == ("2026-08", 98)+ assert latest["same_month_prior_year"] == 123 and latest["change_vs_prior_year"] == -25+ month = nation["months"][-1]+ assert month["by_component"] == {"U.S. Border Patrol": 86, "Office of Field Operations": 12}+ assert month["by_encounter_type"] == {"Apprehensions": 86, "Inadmissibles": 12}+ assert month["by_demographic"] == {"Single Adults": 92, "Accompanied Minors": 5, "UAC": 1}+ assert [c["citizenship"] for c in nation["top_citizenships_latest_month"]] == [+ "MEXICO", "CHINA, PEOPLES REPUBLIC OF", "INDIA", "GUATEMALA"]+ assert nation["other_citizenships_latest_month"] == 3++ assert south["latest"]["encounters"] == 93+ assert other["latest"]["encounters"] == 5+ assert [(m["period"], m["encounters"]) for m in mexico["months"]] == [+ ("2022-10", 700), ("2023-09", 361), ("2025-08", 123), ("2025-10", 105), ("2026-08", 86)]+ assert mexico["months"][0]["by_encounter_type"] == {"Expulsions": 700} # Title 42+ assert mexico["months"][3]["fiscal_year"] == 2026 # October 2025 is FY2026+ assert "top_citizenships_latest_month" not in mexico+ assert china["selection"]["citizenship"] == "CHINA, PEOPLES REPUBLIC OF"+ assert china["latest"]["encounters"] == 6+ # A citizenship CBP does not publish is a usage error that names OTHER, never a zero.+ assert "OTHER" in nowhere["error"] and "degraded" not in nowhere and "latest" not in nowhere++ years = {f["fiscal_year"]: f for f in nation["fiscal_years"]}+ assert years[2023] == {"fiscal_year": 2023, "period_start": "2022-10-01", "period_end": "2023-09-30",+ "months_reported": 2, "complete": False, "fiscal_year_to_date": False,+ "encounters": 1061}+ assert years[2026]["fiscal_year_to_date"] is True and years[2026]["encounters"] == 203+ # FY2025 has no October row here, so a same-months comparison would be partial: none is made.+ assert years[2026]["prior_fiscal_year_same_months"] is None+++async def test_cbp_month_without_rows_inside_coverage_is_zero_and_after_it_absent(fetcher: Fetcher) -> None:+ """CBP's file lists only non-zero cells (no 0 among its 52,986 counts), so a+ covered month with no row for a selection is 0; months after the newest+ published month are never invented."""+ with _cbp_mock(_CBP_FEATURE_ROWS):+ india = await bc.fetch_us_border_encounters(fetcher, citizenship="INDIA")+ assert [(m["period"], m["encounters"]) for m in india["months"]] == [+ ("2022-10", 0), ("2023-09", 0), ("2025-08", 0), ("2025-10", 0), ("2026-08", 2)]+ assert india["latest"]["period"] == "2026-08"+++# ---------------------------------------------------------------------------+# CBP: failure is never a zero+# ---------------------------------------------------------------------------++async def test_cbp_outage_is_degraded_never_zero(fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch) -> None:+ _no_sleep(monkeypatch)+ with respx.mock:+ respx.get(bc.CBP_DATASET_PAGE).mock(return_value=httpx.Response(503))+ result = await bc.fetch_us_border_encounters(fetcher)+ assert result["degraded"] is True+ assert result["reason"] == "cbp_fetch_failed"+ assert "503" in result["error"]+ for key in ("latest", "months", "fiscal_years", "top_citizenships_latest_month"):+ assert key not in result+ assert _no_numbers(result)+++async def test_cbp_outage_after_a_good_fetch_serves_that_copy_marked_stale(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch) -> None:+ _no_sleep(monkeypatch)+ with _cbp_mock(_CBP_NORTHERN_USBP_AUG):+ fresh = await bc.fetch_us_border_encounters(fetcher, region="northern", component="usbp")+ value, _created = fetcher.cache.get_stale_meta(bc.CBP_CACHE_KEY)+ fetcher.cache.set(bc.CBP_CACHE_KEY, value, ttl_seconds=-1) # past its TTL, still on disk++ with respx.mock:+ respx.get(bc.CBP_DATASET_PAGE).mock(return_value=httpx.Response(503))+ stale = await bc.fetch_us_border_encounters(fetcher, region="northern", component="usbp")+ assert fresh["stale"] is False+ assert stale["stale"] is True and stale["stale_age_seconds"] >= 0+ assert stale["latest"]["encounters"] == 563 # the last good figure, not 0+ assert any("503" in gap for gap in stale["data_gaps"])+++async def test_cbp_html_in_place_of_the_csv_is_degraded(fetcher: Fetcher) -> None:+ denied = httpx.Response(200, text="<html><body><h1>Access Denied</h1></body></html>",+ headers={"content-type": "text/html"})+ with _cbp_mock("", csv_response=denied):+ result = await bc.fetch_us_border_encounters(fetcher)+ assert result["degraded"] is True+ assert result["reason"] == "cbp_unexpected_format"+ assert "latest" not in result and _no_numbers(result)+++async def test_cbp_caveat_missing_from_the_live_page_is_flagged(fetcher: Fetcher) -> None:+ page = _CBP_PAGE.replace("Final statistics are available at the conclusion of each fiscal year.", "")+ with _cbp_mock(_CBP_NORTHERN_USBP_AUG, page=page):+ result = await bc.fetch_us_border_encounters(fetcher, region="northern", component="usbp")+ assert result["latest"]["encounters"] == 563+ drift = [gap for gap in result["data_gaps"] if "no longer shows this caveat" in gap]+ assert len(drift) == 1 and "Data is extracted from live CBP systems" in drift[0]+++async def test_cbp_bad_arguments_are_usage_errors_checked_before_any_fetch(fetcher: Fetcher) -> None:+ with respx.mock(assert_all_called=False): # no routes: any request would fail the call+ region = await bc.fetch_us_border_encounters(fetcher, region="mars")+ component = await bc.fetch_us_border_encounters(fetcher, component="navy")+ assert "region" in region["error"] and "degraded" not in region+ assert "component" in component["error"] and "degraded" not in component+++# ---------------------------------------------------------------------------+# UK: captured shapes+# ---------------------------------------------------------------------------++_UK_ODS_URL = ("https://assets.publishing.service.gov.uk/media/6ad1f5b949ba86d6c953cabd/"+ "16_October_2026_Small_boats_-_time_series.ods")++# GOV.UK Content API item, trimmed to the fields the module reads (values verbatim).+_UK_ITEM = {+ "base_path": "/government/publications/migrants-detected-crossing-the-english-channel-in-small-boats",+ "title": "Small boat activity in the English Channel",+ "document_type": "transparency",+ "schema_name": "publication",+ "first_published_at": "2023-02-01T00:00:00+00:00",+ "public_updated_at": "2026-10-16T13:13:46+01:00",+ "details": {+ "attachments": [+ {"attachment_type": "html", "id": "9561576", "title": "Small boat arrivals: last 7 days",+ "url": "/government/publications/migrants-detected-crossing-the-english-channel-in-small-boats/"+ "migrants-detected-crossing-the-english-channel-in-small-boats-last-7-days"},+ {"attachment_type": "html", "id": "9561577",+ "title": "Weekly summary of small boat arrivals and preventions",+ "url": "/government/publications/migrants-detected-crossing-the-english-channel-in-small-boats/"+ "weekly-summary-of-small-boat-arrivals-and-preventions"},+ {"attachment_type": "file", "id": "9561578",+ "content_type": "application/vnd.oasis.opendocument.spreadsheet", "file_size": 76787,+ "filename": "16_October_2026_Small_boats_-_time_series.ods",+ "title": "Migrants detected crossing the English Channel in small boats – time series",+ "url": _UK_ODS_URL},+ ],+ "change_history": [+ {"note": "Daily and weekly figures updated. ", "public_timestamp": "2026-10-16T12:13:46Z"},+ {"note": "Updated with latest statistics.", "public_timestamp": "2026-10-15T12:34:06Z"},+ ],+ },+}++# SB_01, every row from 1 January 2025 to 15 October 2026: date, migrants, boats, uncontrolled, note.+_UK_DAILY = """\+2025-01-01,0,0,0+2025-01-02,0,0,0+2025-01-03,0,0,0+2025-01-04,61,1,0+2025-01-05,0,0,0+2025-01-06,0,0,0+2025-01-07,0,0,0+2025-01-08,0,0,0+2025-01-09,0,0,0+2025-01-10,0,0,0+2025-01-11,67,1,0+2025-01-12,0,0,0+2025-01-13,260,5,0+2025-01-14,0,0,0+2025-01-15,215,4,0+2025-01-16,104,2,0+2025-01-17,183,3,0+2025-01-18,0,0,0+2025-01-19,0,0,0+2025-01-20,0,0,0+2025-01-21,129,2,0+2025-01-22,79,2,0+2025-01-23,0,0,0+2025-01-24,0,0,0+2025-01-25,0,0,0+2025-01-26,0,0,0+2025-01-27,0,0,0+2025-01-28,0,0,0+2025-01-29,0,0,0+2025-01-30,0,0,0+2025-01-31,0,0,0+2025-02-01,47,1,0+2025-02-02,147,3,0+2025-02-03,52,1,0+2025-02-04,0,0,0+2025-02-05,145,2,0+2025-02-06,0,0,0+2025-02-07,0,0,0+2025-02-08,0,0,0+2025-02-09,62,2,0+2025-02-10,3,1,0+2025-02-11,0,0,0+2025-02-12,99,2,0+2025-02-13,0,0,0+2025-02-14,0,0,0+2025-02-15,240,4,0+2025-02-16,0,0,0+2025-02-17,0,0,0+2025-02-18,0,0,0+2025-02-19,0,0,0+2025-02-20,0,0,0+2025-02-21,0,0,0+2025-02-22,0,0,0+2025-02-23,0,0,0+2025-02-24,0,0,0+2025-02-25,163,3,0+2025-02-26,0,0,0+2025-02-27,0,0,0+2025-02-28,0,0,0+2025-03-01,68,1,0+2025-03-02,592,11,0+2025-03-03,182,3,0+2025-03-04,326,6,0+2025-03-05,210,3,0+2025-03-06,235,4,0+2025-03-07,54,1,0+2025-03-08,174,3,0+2025-03-09,237,4,0+2025-03-10,261,5,0+2025-03-11,0,0,0+2025-03-12,0,0,0+2025-03-13,0,0,0+2025-03-14,0,0,0+2025-03-15,0,0,0+2025-03-16,0,0,0+2025-03-17,0,0,0+2025-03-18,0,0,0+2025-03-19,289,5,0+2025-03-20,341,6,0+2025-03-21,246,5,0+2025-03-22,241,4,0+2025-03-23,335,6,0+2025-03-24,73,1,0+2025-03-25,129,2,0+2025-03-26,357,6,0+2025-03-27,236,4,0+2025-03-28,0,0,0+2025-03-29,0,0,0+2025-03-30,0,0,0+2025-03-31,0,0,0+2025-04-01,0,0,0+2025-04-02,0,0,0+2025-04-03,0,0,0+2025-04-04,154,4,0+2025-04-05,0,0,0+2025-04-06,0,0,0+2025-04-07,0,0,0+2025-04-08,432,8,0+2025-04-09,0,0,0+2025-04-10,0,0,0+2025-04-11,180,3,0+2025-04-12,656,11,0+2025-04-13,0,0,0+2025-04-14,119,2,0+2025-04-15,705,12,0+2025-04-16,0,0,0+2025-04-17,211,3,0+2025-04-18,253,5,0+2025-04-19,24,1,0+2025-04-20,0,0,0+2025-04-21,184,3,0+2025-04-22,63,1,0+2025-04-23,15,1,0+2025-04-24,0,0,0+2025-04-25,0,0,0+2025-04-26,0,0,0+2025-04-27,247,5,0+2025-04-28,473,8,0+2025-04-29,422,8,0+2025-04-30,294,5,0+2025-05-01,226,6,0+2025-05-02,216,4,0+2025-05-03,0,0,0+2025-05-04,0,0,0+2025-05-05,0,0,0+2025-05-06,0,0,0+2025-05-07,0,0,0+2025-05-08,0,0,0+2025-05-09,0,0,0+2025-05-10,58,1,0+2025-05-11,232,4,0+2025-05-12,601,10,0+2025-05-13,292,5,0+2025-05-14,0,0,0+2025-05-15,0,0,0+2025-05-16,0,0,0+2025-05-17,0,0,0+2025-05-18,0,0,0+2025-05-19,0,0,0+2025-05-20,49,1,0+2025-05-21,825,13,0+2025-05-22,0,0,0+2025-05-23,44,1,0+2025-05-24,0,0,0+2025-05-25,0,0,0+2025-05-26,0,0,0+2025-05-27,0,0,0+2025-05-28,0,0,0+2025-05-29,0,0,0+2025-05-30,0,0,0+2025-05-31,1195,19,0+2025-06-01,0,0,0+2025-06-02,0,0,0+2025-06-03,0,0,0+2025-06-04,0,0,0+2025-06-05,0,0,0+2025-06-06,0,0,0+2025-06-07,0,0,0+2025-06-08,0,0,0+2025-06-09,0,0,0+2025-06-10,0,0,0+2025-06-11,400,6,0+2025-06-12,52,1,0+2025-06-13,919,14,0+2025-06-14,134,2,0+2025-06-15,0,0,0+2025-06-16,228,4,0+2025-06-17,489,8,0+2025-06-18,244,4,0+2025-06-19,102,2,0+2025-06-20,437,7,0+2025-06-21,583,9,0+2025-06-22,0,0,0+2025-06-23,0,0,0+2025-06-24,0,0,0+2025-06-25,118,2,0+2025-06-26,0,0,0+2025-06-27,0,0,0+2025-06-28,0,0,0+2025-06-29,585,8,0+2025-06-30,879,13,0+2025-07-01,440,8,0+2025-07-02,178,3,0+2025-07-03,0,0,0+2025-07-04,517,8,0+2025-07-05,0,0,0+2025-07-06,0,0,0+2025-07-07,0,0,0+2025-07-08,0,0,0+2025-07-09,0,0,0+2025-07-10,573,10,0+2025-07-11,353,5,0+2025-07-12,317,6,0+2025-07-13,132,2,0+2025-07-14,12,1,0+2025-07-15,0,0,0+2025-07-16,0,0,0+2025-07-17,398,6,0+2025-07-18,419,6,0+2025-07-19,153,3,0+2025-07-20,60,1,0+2025-07-21,0,0,0+2025-07-22,0,0,0+2025-07-23,132,2,0+2025-07-24,225,4,0+2025-07-25,68,1,0+2025-07-26,122,2,0+2025-07-27,96,2,0+2025-07-28,212,3,0+2025-07-29,149,2,0+2025-07-30,898,13,0+2025-07-31,0,0,0+2025-08-01,0,0,0+2025-08-02,0,0,0+2025-08-03,0,0,0+2025-08-04,0,0,0+2025-08-05,0,0,0+2025-08-06,155,2,0+2025-08-07,248,5,0+2025-08-08,0,0,0+2025-08-09,435,7,0+2025-08-10,281,5,0+2025-08-11,474,8,0+2025-08-12,445,6,0+2025-08-13,325,4,0+2025-08-14,82,1,0+2025-08-15,116,2,0+2025-08-16,0,0,0+2025-08-17,0,0,0+2025-08-18,0,0,0+2025-08-19,0,0,0+2025-08-20,0,0,0+2025-08-21,0,0,0+2025-08-22,79,1,0+2025-08-23,0,0,0+2025-08-24,212,4,0+2025-08-25,659,9,0+2025-08-26,56,2,0+2025-08-27,0,0,0+2025-08-28,0,0,0+2025-08-29,0,0,0+2025-08-30,0,0,0+2025-08-31,0,0,0+2025-09-01,0,0,0+2025-09-02,0,0,0+2025-09-03,0,0,0+2025-09-04,0,0,0+2025-09-05,0,0,0+2025-09-06,1101,18,1,Revised+2025-09-07,65,1,0+2025-09-08,0,0,0+2025-09-09,674,9,0+2025-09-10,188,3,0+2025-09-11,0,0,0+2025-09-12,0,0,0+2025-09-13,0,0,0+2025-09-14,0,0,0+2025-09-15,0,0,0+2025-09-16,0,0,0+2025-09-17,0,0,0+2025-09-18,0,0,0+2025-09-19,1072,13,0+2025-09-20,85,1,0+2025-09-21,0,0,0+2025-09-22,0,0,0+2025-09-23,0,0,0+2025-09-24,0,0,0+2025-09-25,0,0,0+2025-09-26,0,0,0+2025-09-27,895,12,0+2025-09-28,403,7,0+2025-09-29,70,1,0+2025-09-30,531,7,0+2025-10-01,138,3,0+2025-10-02,176,3,0+2025-10-03,0,0,0+2025-10-04,0,0,0+2025-10-05,0,0,0+2025-10-06,0,0,0+2025-10-07,0,0,0+2025-10-08,1075,15,0+2025-10-09,27,1,0+2025-10-10,557,7,0+2025-10-11,184,3,0+2025-10-12,89,1,0+2025-10-13,32,1,0+2025-10-14,0,0,0+2025-10-15,0,0,0+2025-10-16,0,0,0+2025-10-17,0,0,0+2025-10-18,369,7,0+2025-10-19,0,0,0+2025-10-20,0,0,0+2025-10-21,0,0,0+2025-10-22,220,3,0+2025-10-23,0,0,0+2025-10-24,0,0,0+2025-10-25,0,0,0+2025-10-26,0,0,0+2025-10-27,0,0,0+2025-10-28,0,0,0+2025-10-29,0,0,0+2025-10-30,0,0,0+2025-10-31,0,0,0+2025-11-01,0,0,0+2025-11-02,0,0,0+2025-11-03,0,0,0+2025-11-04,0,0,0+2025-11-05,0,0,0+2025-11-06,621,9,0+2025-11-07,648,9,0+2025-11-08,503,7,0+2025-11-09,349,5,0+2025-11-10,0,0,0+2025-11-11,0,0,0+2025-11-12,0,0,0+2025-11-13,0,0,0+2025-11-14,217,3,0+2025-11-15,0,0,0+2025-11-16,0,0,0+2025-11-17,0,0,0+2025-11-18,0,0,0+2025-11-19,0,0,0+2025-11-20,0,0,0+2025-11-21,0,0,0+2025-11-22,0,0,0+2025-11-23,0,0,0+2025-11-24,0,0,0+2025-11-25,0,0,0+2025-11-26,0,0,0+2025-11-27,0,0,0+2025-11-28,0,0,0+2025-11-29,0,0,0+2025-11-30,0,0,0+2025-12-01,0,0,0+2025-12-02,0,0,0+2025-12-03,0,0,0+2025-12-04,0,0,0+2025-12-05,0,0,0+2025-12-06,0,0,0+2025-12-07,0,0,0+2025-12-08,0,0,0+2025-12-09,0,0,0+2025-12-10,0,0,0+2025-12-11,0,0,0+2025-12-12,0,0,0+2025-12-13,737,11,0+2025-12-14,52,1,0+2025-12-15,0,0,0+2025-12-16,74,1,0+2025-12-17,497,9,0+2025-12-18,0,0,0+2025-12-19,0,0,0+2025-12-20,803,13,0+2025-12-21,0,0,0+2025-12-22,17,1,0+2025-12-23,0,0,0+2025-12-24,0,0,0+2025-12-25,0,0,0+2025-12-26,0,0,0+2025-12-27,0,0,0+2025-12-28,0,0,0+2025-12-29,0,0,0+2025-12-30,0,0,0+2025-12-31,0,0,0+2026-01-01,0,0,0+2026-01-02,0,0,0+2026-01-03,0,0,0+2026-01-04,0,0,0+2026-01-05,32,1,0+2026-01-06,0,0,0+2026-01-07,0,0,0+2026-01-08,0,0,0+2026-01-09,0,0,0+2026-01-10,0,0,0+2026-01-11,0,0,0+2026-01-12,0,0,0+2026-01-13,0,0,0+2026-01-14,171,3,0+2026-01-15,0,0,0+2026-01-16,0,0,0+2026-01-17,317,5,0+2026-01-18,138,2,0+2026-01-19,275,4,0+2026-01-20,0,0,0+2026-01-21,0,0,0+2026-01-22,0,0,0+2026-01-23,0,0,0+2026-01-24,0,0,0+2026-01-25,0,0,0+2026-01-26,0,0,0+2026-01-27,0,0,0+2026-01-28,0,0,0+2026-01-29,0,0,0+2026-01-30,0,0,0+2026-01-31,0,0,0+2026-02-01,0,0,0+2026-02-02,56,1,0+2026-02-03,0,0,0+2026-02-04,0,0,0+2026-02-05,0,0,0+2026-02-06,0,0,0+2026-02-07,0,0,0+2026-02-08,219,3,0+2026-02-09,322,5,0+2026-02-10,0,0,0+2026-02-11,0,0,0+2026-02-12,0,0,0+2026-02-13,0,0,0+2026-02-14,0,0,0+2026-02-15,0,0,0+2026-02-16,0,0,0+2026-02-17,0,0,0+2026-02-18,0,0,0+2026-02-19,0,0,0+2026-02-20,0,0,0+2026-02-21,0,0,0+2026-02-22,0,0,0+2026-02-23,0,0,0+2026-02-24,74,1,0+2026-02-25,605,10,0+2026-02-26,0,0,0+2026-02-27,0,0,0+2026-02-28,0,0,0+2026-03-01,0,0,0+2026-03-02,0,0,0+2026-03-03,204,3,0+2026-03-04,275,4,0+2026-03-05,66,1,0+2026-03-06,157,3,0+2026-03-07,114,2,0+2026-03-08,75,1,0+2026-03-09,309,4,0+2026-03-10,0,0,0+2026-03-11,0,0,0+2026-03-12,0,0,0+2026-03-13,0,0,0+2026-03-14,0,0,0+2026-03-15,48,1,0+2026-03-16,0,0,0+2026-03-17,0,0,0+2026-03-18,262,4,0+2026-03-19,144,2,0+2026-03-20,116,3,0+2026-03-21,0,0,0+2026-03-22,190,3,0+2026-03-23,272,4,0+2026-03-24,0,0,0+2026-03-25,0,0,0+2026-03-26,0,0,0+2026-03-27,0,0,0+2026-03-28,0,0,0+2026-03-29,0,0,0+2026-03-30,0,0,0+2026-03-31,0,0,0+2026-04-01,325,5,0+2026-04-02,0,0,0+2026-04-03,0,0,0+2026-04-04,0,0,0+2026-04-05,0,0,0+2026-04-06,0,0,0+2026-04-07,137,2,0+2026-04-08,159,2,0+2026-04-09,74,1,0+2026-04-10,0,0,0+2026-04-11,0,0,0+2026-04-12,0,0,0+2026-04-13,201,3,0+2026-04-14,75,1,0+2026-04-15,0,0,0+2026-04-16,0,0,0+2026-04-17,63,1,0+2026-04-18,602,9,0+2026-04-19,0,0,0+2026-04-20,0,0,0+2026-04-21,0,0,0+2026-04-22,0,0,0+2026-04-23,0,0,0+2026-04-24,0,0,0+2026-04-25,122,2,0+2026-04-26,127,2,0+2026-04-27,90,2,0+2026-04-28,0,0,0+2026-04-29,0,0,0+2026-04-30,0,0,0+2026-05-01,55,1,0+2026-05-02,325,6,0+2026-05-03,422,6,0+2026-05-04,92,2,0+2026-05-05,0,0,0+2026-05-06,0,0,0+2026-05-07,0,0,0+2026-05-08,70,1,0+2026-05-09,196,3,0+2026-05-10,0,0,0+2026-05-11,0,0,0+2026-05-12,0,0,0+2026-05-13,0,0,0+2026-05-14,0,0,0+2026-05-15,0,0,0+2026-05-16,0,0,0+2026-05-17,0,0,0+2026-05-18,0,0,0+2026-05-19,0,0,0+2026-05-20,0,0,0+2026-05-21,0,0,0+2026-05-22,394,6,0+2026-05-23,287,4,0+2026-05-24,231,3,0+2026-05-25,77,1,0+2026-05-26,139,2,0+2026-05-27,74,1,0+2026-05-28,0,0,0+2026-05-29,128,2,0+2026-05-30,223,3,0+2026-05-31,13,1,0+2026-06-01,0,0,0+2026-06-02,0,0,0+2026-06-03,0,0,0+2026-06-04,0,0,0+2026-06-05,0,0,0+2026-06-06,0,0,0+2026-06-07,0,0,0+2026-06-08,0,0,0+2026-06-09,0,0,0+2026-06-10,0,0,0+2026-06-11,0,0,0+2026-06-12,0,0,0+2026-06-13,0,0,0+2026-06-14,0,0,0+2026-06-15,710,11,0+2026-06-16,0,0,0+2026-06-17,0,0,0+2026-06-18,392,6,0+2026-06-19,406,5,0+2026-06-20,94,1,0+2026-06-21,310,5,0+2026-06-22,27,1,0+2026-06-23,186,3,0+2026-06-24,221,3,0+2026-06-25,150,2,0+2026-06-26,0,0,0+2026-06-27,105,1,0+2026-06-28,78,1,0+2026-06-29,0,0,0+2026-06-30,63,1,0+2026-07-01,0,0,0+2026-07-02,0,0,0+2026-07-03,0,0,0+2026-07-04,0,0,0+2026-07-05,0,0,0+2026-07-06,0,0,0+2026-07-07,0,0,0+2026-07-08,249,4,0+2026-07-09,81,1,0+2026-07-10,255,3,0+2026-07-11,0,0,0+2026-07-12,0,0,0+2026-07-13,0,0,0+2026-07-14,0,0,0+2026-07-15,0,0,0+2026-07-16,0,0,0+2026-07-17,0,0,0+2026-07-18,0,0,0+2026-07-19,0,0,0+2026-07-20,0,0,0+2026-07-21,0,0,0+2026-07-22,172,3,0+2026-07-23,366,3,0+2026-07-24,103,2,0+2026-07-25,240,5,0+2026-07-26,0,0,0+2026-07-27,0,0,0+2026-07-28,26,1,0+2026-07-29,752,9,0+2026-07-30,72,1,0+2026-07-31,0,0,0+2026-08-01,326,4,0+2026-08-02,0,0,0+2026-08-03,35,1,0+2026-08-04,0,0,0+2026-08-05,0,0,0+2026-08-06,0,0,0+2026-08-07,0,0,0+2026-08-08,258,4,0+2026-08-09,423,5,0+2026-08-10,230,1,0+2026-08-11,0,0,0+2026-08-12,0,0,0+2026-08-13,0,0,0+2026-08-14,93,1,0+2026-08-15,82,1,0+2026-08-16,0,0,0+2026-08-17,250,3,0+2026-08-18,0,0,0+2026-08-19,0,0,0+2026-08-20,0,0,0+2026-08-21,0,0,0+2026-08-22,0,0,0+2026-08-23,0,0,0+2026-08-24,0,0,0+2026-08-25,0,0,0+2026-08-26,0,0,0+2026-08-27,494,7,0+2026-08-28,122,3,0+2026-08-29,0,0,0+2026-08-30,0,0,0+2026-08-31,0,0,0+2026-09-01,0,0,0+2026-09-02,0,0,0+2026-09-03,0,0,0+2026-09-04,0,0,0+2026-09-05,0,0,0+2026-09-06,625,8,0+2026-09-07,143,2,0+2026-09-08,0,0,0+2026-09-09,0,0,0+2026-09-10,0,0,0+2026-09-11,0,0,0+2026-09-12,0,0,0+2026-09-13,0,0,0+2026-09-14,144,2,0+2026-09-15,55,1,0+2026-09-16,0,0,0+2026-09-17,0,0,0+2026-09-18,0,0,0+2026-09-19,0,0,0+2026-09-20,0,0,0+2026-09-21,150,3,1+2026-09-22,154,3,1+2026-09-23,781,10,0+2026-09-24,44,1,0+2026-09-25,0,0,0+2026-09-26,0,0,0+2026-09-27,526,7,0+2026-09-28,0,0,0+2026-09-29,61,1,0+2026-09-30,0,0,0+2026-10-01,0,0,0+2026-10-02,91,1,0+2026-10-03,164,2,0+2026-10-04,418,5,0+2026-10-05,609,8,0+2026-10-06,338,5,0+2026-10-07,119,2,0+2026-10-08,0,0,0+2026-10-09,0,0,0+2026-10-10,0,0,0+2026-10-11,0,0,0+2026-10-12,0,0,0+2026-10-13,0,0,0+2026-10-14,0,0,0+2026-10-15,0,0,0+"""++# SB_02 rows: week ending, migrants, boats, uncontrolled, migrants prevented, events prevented.+_UK_WEEKLY = """\+2024-04-28,902,17,0,-,-+2024-05-05,1409,28,0,849,30+2026-08-23,250,3,0,136,3+2026-08-30,616,10,0,339,13+2026-09-06,625,8,0,282,10+2026-09-13,143,2,0,100,2+2026-09-20,199,3,0,40,5+2026-09-27,1655,24,2,860,29+2026-10-04,734,9,0,475,17+2026-10-11,1066,15,0,245,12"""++_DAILY_HEADER = ["Date", "Migrants arrived", "Boats arrived",+ "Boats arrived - involved in uncontrolled landings", "Notes"]+_WEEKLY_HEADER = ["Week ending", "Migrants arrived", "Boats arrived",+ "Boats arrived - involved in uncontrolled landings", "Migrants prevented",+ "Events prevented", "Notes"]++# Notes sheet: title row and notes 1, 6 and 7, row markup verbatim from the live content.xml.+_UK_NOTES_ROWS = (+ '<table:table-row table:style-name="ro8"><table:table-cell office:value-type="string" table:style-name="ce10"><text:p>Notes</text:p></table:table-cell><table:table-cell table:number-columns-repeated="15" table:style-name="ce11"/><table:table-cell table:number-columns-repeated="16368" table:style-name="ce4"/></table:table-row>'+ '<table:table-row table:style-name="ro9"><table:table-cell office:value-type="string" table:style-name="ce12"><text:p>1. These statistics are taken from provisional operational data and are subject to change. They may differ from figures published in the final official statistics on Illegal entry routes <text:s/>to the UK, which will have undergone a more thorough quality assurance process.<text:s/></text:p><text:p>The data may also differ from daily figures previously published by the Ministry of Defence, due to the point at which arrivals are counted and differences in the counting of ‘boats’ compared to ‘events’. This means that total arrivals over long time periods should be similar between the two sources, but Home Office figures for number of boats detected will be higher than the Ministry of Defence’s figures where boats arriving together would be counted as one. The quarterly Illegal entry routes <text:s/>to the UK statistical release presents final and authoritative statistics on small boat arrivals.</text:p></table:table-cell><table:table-cell table:number-columns-repeated="9" table:style-name="ce13"/><table:table-cell table:number-columns-repeated="5" table:style-name="ce14"/><table:table-cell table:number-columns-repeated="16369" table:style-name="ce13"/></table:table-row>'+ '<table:table-row table:style-name="ro11"><table:table-cell office:value-type="string" table:style-name="ce15"><text:p>6. The data in table SB_01 covers arrivals only, and relates to daily totals. The data in table SB_02 covers both arrivals and preventions, and relates to weekly totals - the data is shown on the last day of the week period, but the activity may have occurred on any day within that week period.<text:s/></text:p></table:table-cell><table:table-cell table:number-columns-repeated="9" table:style-name="ce16"/><table:table-cell table:number-columns-repeated="5" table:style-name="ce17"/><table:table-cell table:style-name="ce11"/><table:table-cell table:number-columns-repeated="16368" table:style-name="ce4"/></table:table-row>'+ '<table:table-row table:style-name="ro5"><table:table-cell office:value-type="string" table:style-name="ce15"><text:p>7. Data on preventions are operational estimates collected and provided to the UK by French authorities.<text:s/></text:p></table:table-cell><table:table-cell table:number-columns-repeated="9" table:style-name="ce16"/><table:table-cell table:number-columns-repeated="5" table:style-name="ce17"/><table:table-cell table:style-name="ce11"/><table:table-cell table:number-columns-repeated="16368" table:style-name="ce4"/></table:table-row>'+)++_ODS_NS = ('xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" '+ 'xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" '+ 'xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0"')+_BLANK_TAIL = ('<table:table-row table:number-rows-repeated="1048553" table:style-name="ro15">'+ '<table:table-cell table:number-columns-repeated="16384"/></table:table-row>')+++def _cell(value: str) -> str:+ """One cell in the live file's markup: dates, floats, and strings ("-", "Revised")."""+ if len(value) == 10 and value[4] == "-" and value[7] == "-":+ shown = date.fromisoformat(value).strftime("%d/%m/%Y")+ return (f'<table:table-cell office:value-type="date" office:date-value="{value}T00:00:00" '+ f'table:style-name="ce27"><text:p>{shown}</text:p></table:table-cell>')+ if value.isdigit():+ return (f'<table:table-cell office:value-type="float" office:value="{value}" '+ f'table:style-name="ce11"><text:p>{value}</text:p></table:table-cell>')+ return (f'<table:table-cell office:value-type="string" table:style-name="ce28">'+ f'<text:p>{value}</text:p></table:table-cell>')+++def _sheet(name: str, header: list[str], lines: list[str]) -> str:+ """A data sheet as the live file writes it: each row padded to 16,384 columns+ by one repeated blank cell, the sheet padded to 1,048,576 rows by one+ repeated blank row (1,045,365 of them after SB_01's 3,211 live rows)."""+ rows = [header] + [line.split(",") for line in lines]+ xml = []+ for i, values in enumerate(rows):+ cells = "".join(_cell(v) for v in values)+ xml.append(f'<table:table-row table:style-name="{"ro10" if i == 0 else "ro16"}">{cells}'+ f'<table:table-cell table:number-columns-repeated="{16384 - len(values)}" '+ 'table:style-name="ce11"/></table:table-row>')+ tail = (f'<table:table-row table:number-rows-repeated="{1048576 - len(rows)}" table:style-name="ro16">'+ '<table:table-cell table:number-columns-repeated="16384"/></table:table-row>')+ return (f'<table:table table:name="{name}" table:style-name="ta1">'+ '<table:table-column table:style-name="co6" table:default-cell-style-name="ce27"/>'+ + "".join(xml) + tail + "</table:table>")+++def _ods_bytes(tables_xml: str) -> bytes:+ content = ('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+ f'<office:document-content {_ODS_NS} office:version="1.4"><office:body>'+ f'<office:spreadsheet>{tables_xml}</office:spreadsheet></office:body></office:document-content>')+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("mimetype", "application/vnd.oasis.opendocument.spreadsheet") # stored, first+ zf.writestr("content.xml", content, compress_type=zipfile.ZIP_DEFLATED)+ return buf.getvalue()+++def _ods(daily: list[str], weekly: list[str], notes: str = _UK_NOTES_ROWS) -> bytes:+ notes_sheet = f'<table:table table:name="Notes" table:style-name="ta1">{notes}{_BLANK_TAIL}</table:table>'+ return _ods_bytes(notes_sheet + _sheet("SB_01", _DAILY_HEADER, daily)+ + _sheet("SB_02", _WEEKLY_HEADER, weekly))+++def _main_ods() -> bytes:+ return _ods(_UK_DAILY.splitlines(), _UK_WEEKLY.splitlines())+++@contextmanager+def _uk_mock(ods: bytes, item: dict | None = None):+ with respx.mock(assert_all_called=False) as mock:+ mock.get(bc.UK_CONTENT_API).mock(return_value=httpx.Response(200, json=item or _UK_ITEM))+ mock.get(_UK_ODS_URL).mock(return_value=httpx.Response(+ 200, content=ods, headers={"content-type": "application/vnd.oasis.opendocument.spreadsheet"}))+ yield mock+++# ---------------------------------------------------------------------------+# UK: the ODS reader+# ---------------------------------------------------------------------------++def test_read_ods_tables_keeps_positions_and_never_expands_blank_repeats() -> None:+ xml = ('<table:table table:name="T"><table:table-row>'+ '<table:table-cell table:number-columns-repeated="2"/>'+ '<table:table-cell office:value-type="float" office:value="7"><text:p>7</text:p></table:table-cell>'+ '<table:table-cell office:value-type="string" table:number-columns-repeated="2">'+ '<text:p>a<text:s text:c="3"/>b</text:p></table:table-cell>'+ '<table:table-cell table:number-columns-repeated="16379"/>'+ '</table:table-row>' + _BLANK_TAIL + '</table:table>')+ assert bc.read_ods_tables(_ods_bytes(xml)) == {"T": [[None, None, 7.0, "a b", "a b"]]}+++def test_read_ods_tables_refuses_a_file_that_is_not_an_ods() -> None:+ with pytest.raises(ValueError):+ bc.read_ods_tables(b"<!DOCTYPE html><html><body>Page not found</body></html>")+++# ---------------------------------------------------------------------------+# UK: real figures+# ---------------------------------------------------------------------------++async def test_uk_latest_week_and_last_7_days_match_the_home_office_pages(fetcher: Fetcher) -> None:+ with _uk_mock(_main_ods()) as mock:+ result = await bc.fetch_uk_small_boat_arrivals(fetcher)+ requests = [call.request for call in mock.calls] # read inside: respx clears calls on exit+ assert "degraded" not in result and result["stale"] is False+ assert result["latest_week"] == {+ "week_ending": "2026-10-11", "period_start": "2026-10-05", "period_end": "2026-10-11",+ "migrants_arrived": 1066, "boats_arrived": 15, "boats_uncontrolled_landings": 0,+ "migrants_prevented": 245, "events_prevented": 12, "revised": False}+ assert result["last_7_days"] == {+ "period_start": "2026-10-09", "period_end": "2026-10-15", "days_reported": 7,+ "migrants_arrived": 0, "boats_arrived": 0, "boats_uncontrolled_landings": 0}+ assert result["latest_day"] == {"date": "2026-10-15", "migrants_arrived": 0, "boats_arrived": 0,+ "boats_uncontrolled_landings": 0, "revised": False}+ assert [d["date"] for d in result["daily"]][0] == "2026-10-02"+ assert [d["migrants_arrived"] for d in result["daily"]] == [91, 164, 418, 609, 338, 119] + [0] * 8+ assert [w["week_ending"] for w in result["weeks"]] == [+ "2026-08-23", "2026-08-30", "2026-09-06", "2026-09-13", "2026-09-20", "2026-09-27",+ "2026-10-04", "2026-10-11"]++ dataset = result["dataset"]+ assert dataset["url"] == _UK_ODS_URL+ assert dataset["public_updated_at"] == "2026-10-16T13:13:46+01:00"+ assert dataset["latest_change_note"] == "Daily and weekly figures updated."+ assert dataset["daily_data_through"] == "2026-10-15"+ assert dataset["weekly_data_through"] == "2026-10-11"+ assert dataset["file_size_bytes"] == 76787+ assert result["measure_kind"] == "flow"+ assert result["data_gaps"] == []+ assert [str(r.url) for r in requests] == [bc.UK_CONTENT_API, _UK_ODS_URL]+ assert all(r.headers["user-agent"] == bc.USER_AGENT for r in requests)+++async def test_uk_months_years_and_year_to_date_are_sums_of_the_daily_table(fetcher: Fetcher) -> None:+ with _uk_mock(_main_ods()):+ result = await bc.fetch_uk_small_boat_arrivals(fetcher, months=14)+ months = {m["period"]: m for m in result["months"]}+ assert [m["period"] for m in result["months"]][0] == "2025-09" and len(result["months"]) == 14+ assert months["2026-10"] == {+ "period": "2026-10", "period_start": "2026-10-01", "period_end": "2026-10-15", "complete": False,+ "days_reported": 15, "days_in_month": 31, "migrants_arrived": 1739, "boats_arrived": 23,+ "boats_uncontrolled_landings": 0}+ assert months["2026-09"]["complete"] is True+ assert (months["2026-09"]["migrants_arrived"], months["2026-09"]["boats_arrived"]) == (2683, 38)+ assert months["2026-09"]["boats_uncontrolled_landings"] == 2+ assert (months["2025-09"]["migrants_arrived"], months["2025-09"]["boats_arrived"]) == (5084, 72)+ assert result["revised_dates"] == ["2025-09-06"]++ years = {y["year"]: y for y in result["years"]}+ assert years[2025] == {"year": 2025, "period_start": "2025-01-01", "period_end": "2025-12-31",+ "complete": True, "days_reported": 365, "migrants_arrived": 41472,+ "boats_arrived": 672, "boats_uncontrolled_landings": 1}+ assert years[2026]["complete"] is False and years[2026]["period_end"] == "2026-10-15"+ assert years[2026]["migrants_arrived"] == 20935++ ytd = result["year_to_date"]+ assert (ytd["period_start"], ytd["period_end"]) == ("2026-01-01", "2026-10-15")+ assert (ytd["migrants_arrived"], ytd["boats_arrived"]) == (20935, 305)+ assert ytd["prior_year"] == {"period_start": "2025-01-01", "period_end": "2025-10-15",+ "migrants_arrived": 36365, "boats_arrived": 593}+ assert (ytd["change_migrants"], ytd["pct_change_migrants"]) == (-15430, -42.4)+ assert (ytd["change_boats"], ytd["pct_change_boats"]) == (-288, -48.6)+++async def test_uk_dash_means_not_collected_and_is_never_zero(fetcher: Fetcher) -> None:+ # Real rows: the series' first days (no uncontrolled-landing figure yet) and+ # the weeks either side of the first French preventions figure.+ ods = _ods(["2018-01-01,0,0,-", "2018-01-02,0,0,-", "2018-01-03,0,0,-"],+ ["2018-01-07,0,0,-,-,-", "2024-04-28,902,17,0,-,-", "2024-05-05,1409,28,0,849,30"])+ with _uk_mock(ods):+ result = await bc.fetch_uk_small_boat_arrivals(fetcher)+ assert result["latest_day"] == {"date": "2018-01-03", "migrants_arrived": 0, "boats_arrived": 0,+ "boats_uncontrolled_landings": None, "revised": False}+ assert result["months"][-1]["boats_uncontrolled_landings"] is None+ weeks = {w["week_ending"]: w for w in result["weeks"]}+ assert weeks["2018-01-07"]["boats_uncontrolled_landings"] is None+ assert weeks["2024-04-28"]["migrants_prevented"] is None and weeks["2024-04-28"]["events_prevented"] is None+ assert weeks["2024-05-05"]["migrants_prevented"] == 849+ # 2017 is not in the file, so there is nothing to compare 2018 with: no zero baseline.+ assert result["year_to_date"]["prior_year"] is None+ assert result["year_to_date"]["change_migrants"] is None+ assert any("2017" in gap for gap in result["data_gaps"])+++async def test_uk_missing_day_makes_sums_partial_and_drops_the_comparison(fetcher: Fetcher) -> None:+ # The live rows with one day (10 March 2025) taken out: a gap in the publisher's series.+ daily = [line for line in _UK_DAILY.splitlines() if not line.startswith("2025-03-10,")]+ with _uk_mock(_ods(daily, _UK_WEEKLY.splitlines())):+ result = await bc.fetch_uk_small_boat_arrivals(fetcher, months=24)+ march = next(m for m in result["months"] if m["period"] == "2025-03")+ assert (march["days_reported"], march["complete"]) == (30, False)+ years = {y["year"]: y for y in result["years"]}+ assert (years[2025]["days_reported"], years[2025]["complete"]) == (364, False)+ # 2025-01-01 to 2025-10-15 is no longer whole, so no like-for-like comparison is made.+ assert result["year_to_date"]["prior_year"] is None+ assert result["year_to_date"]["pct_change_migrants"] is None+ assert result["year_to_date"]["migrants_arrived"] == 20935 # 2026 itself is untouched+ assert any(gap.startswith("1 day(s) between 2025-01-01 and 2026-10-15") for gap in result["data_gaps"])+ assert any("2025-01-01 to 2025-10-15" in gap for gap in result["data_gaps"])+++async def test_uk_year_to_date_on_29_february_compares_with_28_february(fetcher: Fetcher) -> None:+ # Invented all-zero rows: only the calendar matters here (the live file ends in October).+ from datetime import timedelta++ start, end = date(2023, 1, 1), date(2024, 2, 29)+ daily = [f"{start + timedelta(days=k)},0,0,0" for k in range((end - start).days + 1)]+ with _uk_mock(_ods(daily, ["2024-02-25,0,0,0,0,0"])):+ result = await bc.fetch_uk_small_boat_arrivals(fetcher)+ ytd = result["year_to_date"]+ assert (ytd["period_start"], ytd["period_end"]) == ("2024-01-01", "2024-02-29")+ assert (ytd["prior_year"]["period_start"], ytd["prior_year"]["period_end"]) == ("2023-01-01", "2023-02-28")+ assert ytd["pct_change_migrants"] is None # 0 against 0: no percentage, not 0%+ assert ytd["change_migrants"] == 0+++async def test_uk_weekly_total_that_disagrees_with_its_days_is_flagged(fetcher: Fetcher) -> None:+ # Deliberately altered: the live SB_02 row says 1066 for the week ending 2026-10-11.+ weekly = _UK_WEEKLY.replace("2026-10-11,1066,", "2026-10-11,1065,").splitlines()+ with _uk_mock(_ods(_UK_DAILY.splitlines(), weekly)):+ result = await bc.fetch_uk_small_boat_arrivals(fetcher)+ assert result["latest_week"]["migrants_arrived"] == 1065 # the publisher's weekly figure, as published+ assert result["data_gaps"] == [+ "SB_02 week ending 2026-10-11 has 1065 migrants; the seven SB_01 days sum to 1066."]+++async def test_uk_publisher_notes_are_read_from_the_file(fetcher: Fetcher) -> None:+ with _uk_mock(_main_ods()):+ result = await bc.fetch_uk_small_boat_arrivals(fetcher)+ notes = result["publisher_caveats"]+ assert len(notes) == 3+ assert notes[0].startswith("1. These statistics are taken from provisional operational data and are "+ "subject to change.")+ assert "Illegal entry routes to the UK, which will have undergone" in notes[0]+ assert "\nThe data may also differ from daily figures previously published by the Ministry of Defence" in notes[0]+ assert notes[2] == ("7. Data on preventions are operational estimates collected and provided to the UK "+ "by French authorities.")+++# ---------------------------------------------------------------------------+# UK: failure is never a zero+# ---------------------------------------------------------------------------++_UK_FIGURE_KEYS = ("latest_day", "last_7_days", "daily", "latest_week", "weeks", "months", "years",+ "year_to_date")+++async def test_uk_outage_is_degraded_never_zero(fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch) -> None:+ _no_sleep(monkeypatch)+ with respx.mock:+ respx.get(bc.UK_CONTENT_API).mock(side_effect=httpx.ConnectError("connection refused"))+ result = await bc.fetch_uk_small_boat_arrivals(fetcher)+ assert result["degraded"] is True+ assert result["reason"] == "uk_fetch_failed"+ assert "ConnectError" in result["error"]+ assert not any(key in result for key in _UK_FIGURE_KEYS)+ assert _no_numbers(result)+++async def test_uk_time_series_file_outage_is_degraded(fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch) -> None:+ _no_sleep(monkeypatch)+ with respx.mock:+ respx.get(bc.UK_CONTENT_API).mock(return_value=httpx.Response(200, json=_UK_ITEM))+ respx.get(_UK_ODS_URL).mock(return_value=httpx.Response(404))+ result = await bc.fetch_uk_small_boat_arrivals(fetcher)+ assert result["degraded"] is True and result["reason"] == "uk_fetch_failed"+ assert "404" in result["error"]+ assert not any(key in result for key in _UK_FIGURE_KEYS)+++async def test_uk_outage_after_a_good_fetch_serves_that_copy_marked_stale(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch) -> None:+ _no_sleep(monkeypatch)+ with _uk_mock(_main_ods()):+ fresh = await bc.fetch_uk_small_boat_arrivals(fetcher)+ value, _created = fetcher.cache.get_stale_meta(bc.UK_CACHE_KEY)+ fetcher.cache.set(bc.UK_CACHE_KEY, value, ttl_seconds=-1)+ with respx.mock:+ respx.get(bc.UK_CONTENT_API).mock(return_value=httpx.Response(502))+ stale = await bc.fetch_uk_small_boat_arrivals(fetcher)+ assert fresh["stale"] is False+ assert stale["stale"] is True and stale["stale_age_seconds"] >= 0+ assert stale["latest_week"]["migrants_arrived"] == 1066+ assert any("502" in gap for gap in stale["data_gaps"])+++async def test_uk_html_in_place_of_the_ods_is_degraded(fetcher: Fetcher) -> None:+ with _uk_mock(b"<!DOCTYPE html><html><body>Page not found</body></html>"):+ result = await bc.fetch_uk_small_boat_arrivals(fetcher)+ assert result["degraded"] is True and result["reason"] == "uk_unexpected_format"+ assert not any(key in result for key in _UK_FIGURE_KEYS)+++async def test_uk_publication_without_a_time_series_attachment_is_degraded(fetcher: Fetcher) -> None:+ item = copy.deepcopy(_UK_ITEM)+ item["details"]["attachments"] = item["details"]["attachments"][:2] # the two HTML pages only+ with _uk_mock(b"", item=item):+ result = await bc.fetch_uk_small_boat_arrivals(fetcher)+ assert result["degraded"] is True and result["reason"] == "uk_unexpected_format"+ assert "attachment" in result["error"]+++async def test_uk_ods_without_the_daily_table_is_degraded(fetcher: Fetcher) -> None:+ ods = _ods_bytes(_sheet("SB_02", _WEEKLY_HEADER, _UK_WEEKLY.splitlines()))+ with _uk_mock(ods):+ result = await bc.fetch_uk_small_boat_arrivals(fetcher)+ assert result["degraded"] is True and result["reason"] == "uk_unexpected_format"+ assert "SB_01" in result["error"]+++async def test_uk_bad_arguments_are_usage_errors_checked_before_any_fetch(fetcher: Fetcher) -> None:+ with respx.mock(assert_all_called=False):+ result = await bc.fetch_uk_small_boat_arrivals(fetcher, days="many")+ assert "days" in result["error"] and "degraded" not in result+++# ---------------------------------------------------------------------------+# Registry wiring (tools/society.py)+# ---------------------------------------------------------------------------++def _tools_registry():+ """Import world_intel_mcp.tools under the suite's temp cache path (same+ helper as test_daily_digest: importing it opens runtime's Cache)."""+ import importlib+ import os++ from .test_server_registry import _TMP_CACHE++ prior = os.environ.get("WORLD_INTEL_CACHE_DB")+ os.environ["WORLD_INTEL_CACHE_DB"] = str(_TMP_CACHE)+ try:+ return importlib.import_module("world_intel_mcp.tools")+ finally:+ if prior is None:+ os.environ.pop("WORLD_INTEL_CACHE_DB", None)+ else:+ os.environ["WORLD_INTEL_CACHE_DB"] = prior+++async def test_border_tools_are_registered_and_dispatch_to_real_figures(+ fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch) -> None:+ tools_pkg = _tools_registry()+ tools = {t.name: t for t in tools_pkg.ALL_TOOLS}+ us_tool, uk_tool = tools["intel_us_border_encounters"], tools["intel_uk_small_boat_arrivals"]+ props = us_tool.inputSchema["properties"]+ assert set(props["region"]["enum"]) == {"nationwide", *bc.CBP_REGIONS}+ assert set(props["component"]["enum"]) == {"all", *bc.CBP_COMPONENTS}+ assert set(uk_tool.inputSchema["properties"]) == {"days", "weeks", "months"}++ from world_intel_mcp import runtime++ monkeypatch.setattr(runtime, "fetcher", fetcher)+ with _cbp_mock(_CBP_NORTHERN_USBP_AUG):+ us = await tools_pkg.ALL_HANDLERS["intel_us_border_encounters"](+ {"region": "northern", "component": "usbp"})+ with _uk_mock(_main_ods()):+ uk = await tools_pkg.ALL_HANDLERS["intel_uk_small_boat_arrivals"]({"weeks": 1})+ assert us["latest"]["encounters"] == 563+ assert [w["week_ending"] for w in uk["weeks"]] == ["2026-10-11"]+++# ---------------------------------------------------------------------------+# Live publishers (deselected by default; run with: pytest -m smoke -k live_)+# ---------------------------------------------------------------------------++async def live_fetcher(tmp_path):+ from world_intel_mcp.cache import Cache+ from world_intel_mcp.circuit_breaker import CircuitBreaker++ cache = Cache(db_path=tmp_path / "live.db")+ fetcher = Fetcher(cache=cache, breaker=CircuitBreaker())+ yield fetcher+ await fetcher.close()+ cache.close()+++async def test_live_cbp_encounters(live_fetcher: Fetcher) -> None:+ result = await bc.fetch_us_border_encounters(live_fetcher)+ assert "degraded" not in result and "error" not in result, result+ assert result["stale"] is False and result["measure_kind"] == "flow"+ assert result["dataset"]["url"].startswith("https://www.cbp.gov/")+ assert "/assets/documents/" not in result["dataset"]["url"]+ latest = result["latest"]+ assert latest["encounters"] > 0 # nationwide CBP encounters, never 0 in a published month+ assert latest["period"] == result["dataset"]["coverage"]["last_period"]+ assert result["top_citizenships_latest_month"]+ assert result["data_gaps"] == [], result["data_gaps"]+++async def test_live_uk_small_boat_arrivals(live_fetcher: Fetcher) -> None:+ result = await bc.fetch_uk_small_boat_arrivals(live_fetcher)+ assert "degraded" not in result and "error" not in result, result+ assert result["stale"] is False and result["measure_kind"] == "flow"+ assert result["dataset"]["url"].startswith("https://assets.publishing.service.gov.uk/")+ week_ending = date.fromisoformat(result["latest_week"]["week_ending"])+ assert week_ending.weekday() == 6 # SB_02 weeks end on a Sunday+ assert result["dataset"]["daily_data_through"] >= result["dataset"]["weekly_data_through"]+ assert len(result["publisher_caveats"]) >= 5+ assert result["data_gaps"] == [], result["data_gaps"]diff --git a/src/world_intel_mcp/tools/society.py b/src/world_intel_mcp/tools/society.pyindex 41568e0..69d9ea9 100644--- a/src/world_intel_mcp/tools/society.py+++ b/src/world_intel_mcp/tools/society.py@@ -18,6 +18,7 @@ from ..sources import (prediction,displacement,migration,+ border_crossings,cyber,ai_watch,health,@@ -46,7 +47,7 @@ TOOLS: list[Tool] = [},},),- # --- Displacement and migration (5 tools) ---+ # --- Displacement and migration (7 tools) ---Tool(name="intel_displacement_summary",description="Get UNHCR refugee/displacement statistics by country of origin. No API key needed.",@@ -131,6 +132,52 @@ TOOLS: list[Tool] = [},},),+ Tool(+ name="intel_us_border_encounters",+ description=(+ "U.S. CBP encounters per month (Border Patrol apprehensions, OFO inadmissibles, Title 42 "+ "expulsions) from CBP's public dataset: nationwide or one land border region, by component, "+ "optionally one citizenship, with same-month prior-year change, fiscal-year totals and the top "+ "citizenships. A flow of events, not unique people and not a stock. No API key needed."+ ),+ inputSchema={+ "type": "object",+ "properties": {+ "region": {+ "type": "string",+ "enum": ["nationwide", *border_crossings.CBP_REGIONS],+ "description": "Land border region (default nationwide; 'other' = ports and sectors away from the land borders)",+ },+ "component": {+ "type": "string",+ "enum": ["all", *border_crossings.CBP_COMPONENTS],+ "description": "usbp = Border Patrol between ports of entry, ofo = Field Operations at ports (default all)",+ },+ "citizenship": {+ "type": "string",+ "description": "Citizenship as CBP names it (e.g. MEXICO, 'CHINA, PEOPLES REPUBLIC OF', OTHER); default all",+ },+ "months": {"type": "integer", "description": "Months of series to return (default 13)"},+ },+ },+ ),+ Tool(+ name="intel_uk_small_boat_arrivals",+ description=(+ "UK Home Office counts of migrants and boats detected crossing the English Channel in small boats "+ "(provisional operational data): latest days and weeks, French-reported preventions per week, "+ "month and year sums, and year to date vs the same span last year. A flow of arrivals, not a "+ "stock. No API key needed."+ ),+ inputSchema={+ "type": "object",+ "properties": {+ "days": {"type": "integer", "description": "Latest daily rows to return (default 14)"},+ "weeks": {"type": "integer", "description": "Latest weekly rows to return (default 8)"},+ "months": {"type": "integer", "description": "Calendar months of sums to return (default 13)"},+ },+ },+ ),# --- Cyber (1 tool) ---Tool(name="intel_cyber_threats",@@ -439,6 +486,25 @@ async def _net_migration(arguments: dict[str, Any]) -> Any:)+async def _us_border_encounters(arguments: dict[str, Any]) -> Any:+ return await border_crossings.fetch_us_border_encounters(+ runtime.fetcher,+ region=arguments.get("region", "nationwide"),+ component=arguments.get("component", "all"),+ citizenship=arguments.get("citizenship"),+ months=arguments.get("months", 13),+ )+++async def _uk_small_boat_arrivals(arguments: dict[str, Any]) -> Any:+ return await border_crossings.fetch_uk_small_boat_arrivals(+ runtime.fetcher,+ days=arguments.get("days", 14),+ weeks=arguments.get("weeks", 8),+ months=arguments.get("months", 13),+ )++async def _cyber_threats(arguments: dict[str, Any]) -> Any:return await cyber.fetch_cyber_threats(runtime.fetcher, limit=arguments.get("limit", 50)@@ -543,6 +609,8 @@ HANDLERS = {"intel_migration_surges": _migration_surges,"intel_migration_history": _migration_history,"intel_net_migration": _net_migration,+ "intel_us_border_encounters": _us_border_encounters,+ "intel_uk_small_boat_arrivals": _uk_small_boat_arrivals,"intel_cyber_threats": _cyber_threats,"intel_news_feed": _news_feed,"intel_trending_keywords": _trending_keywords,