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
Merge fix/cache-isolation: private per-user temp fallback, read-only baseline reads, unknown Trends counts
Phoenix Agent (mac-studio)7a288f812575
diff --cc CHANGELOG.mdindex 9c06341,1df1a15..063daa8--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -37,956 -5,49 +37,992 @@@- Temporal and keyword spike databases now follow `XDG_CACHE_HOME` likethe cache: `$XDG_CACHE_HOME/world-intel-mcp/temporal.db` and`$XDG_CACHE_HOME/world-intel-mcp/keyword_spikes.db`. With it unset, they- remain in `~/.cache/world-intel-mcp/`. Users who set `XDG_CACHE_HOME`- can keep existing baselines by moving these two files from- `~/.cache/world-intel-mcp/` to `$XDG_CACHE_HOME/world-intel-mcp/`.- Importing the package no longer opens databases; they open on first use.+ remain in `~/.cache/world-intel-mcp/`. Existing baselines are not moved:+ with `XDG_CACHE_HOME` set, the two files already in+ `~/.cache/world-intel-mcp/` stay there unread and new, empty baselines+ start under `$XDG_CACHE_HOME/world-intel-mcp/`. To keep their history,+ move both files there yourself before the next run. Nothing points at+ the old files at runtime; `intel_weekly_trends` reports the new baseline+ as created by that call, then as short of history.+ - The cache's default path (`~/.cache/world-intel-mcp/cache.db` when+ neither `WORLD_INTEL_CACHE_DB` nor `XDG_CACHE_HOME` is set) is resolved+ when the cache opens, not at import, so it agrees with the baselines if+ `HOME` changes in between.+ - When the cache cannot open at its configured or default path, it now+ falls back to a per-user directory, `world-intel-mcp-<uid>` under the+ system temp directory, created with mode 0700, instead of a shared+ `world-intel-mcp` directory there. It refuses that directory with an+ error naming the reason if it is a symlink or not a directory, is owned+ by another user, gives group or other users access, or holds a symlink+ at `cache.db` or its `-wal`, `-shm` or `-journal` file. A fallback cache+ left in the old shared directory is not read or moved. On Windows the+ fallback keeps its old name and is not checked.+ - Importing the package no longer opens databases. The shared cache,+ circuit breaker, AOI store, vector store and fetcher behind the MCP+ tools are built on first use, under a lock, as one set: concurrent first+ uses get the same objects, and a first use that fails binds nothing and+ closes the databases it had opened, so the next use starts over.+ - `intel_weekly_trends` no longer reports a failed input as zero. When the+ baseline database is missing or unreadable, `trend_count` is `null` and+ `error` says why; when anomaly detection fails, `current_anomaly_count`+ is `null`. A new `data_gaps` list names each failed input, carries+ anomaly detection's own gaps, and flags a baseline created by the same+ call or with no metric at the 5 observations volatility needs. Reading+ the baselines no longer creates an empty database file.+ - The dashboard's Trends panel shows a count that could not be computed as+ a dimmed `?` instead of 0, stays visible when weekly trends report an+ error or time out, and lists the error and every data gap.- Apply per-source request spacing to every HTTP retry, including JSON,text, XML and binary fetches.+ - Known open: each retry now waits out its source's spacing and the+ breaker is still checked only before the first attempt, so a full outage+ of a rate-limited source takes longer than before to fall back to its+ stale copy. The registry tests' temp-cache premise still depends on test+ order.+### Fixed: database handles close on every exit path+- The collector (`run_once` and the daemon), standalone report generation+ and the weekly trends query now close their cache, HTTP client and SQLite+ connections when they finish or fail, instead of leaving them to garbage+ collection.+- The test suite closes every cache, fetcher and database it opens. Under+ `--cov` on Python 3.13 it held about 1,550 SQLite descriptors open (each+ unclosed connection's ResourceWarning kept it alive) and failed at the+ default 1,024 open-file limit. Test runs also no longer leave+ `wim-server-test-*` directories in the system temp directory.++### Fixed: the collector cycle summary separates data from errors+- A source that answers with an upstream error (`{"error": ...}`) still+ counts as a completed fetch, but the cycle summary now lists it under+ `upstream_errors`, and `intel-collector` prints how many of the+ "succeeded" sources stored nothing. Before, such a cycle read as data+ collected.+- A stale cache copy (`_stale`) is no longer stored in the vector store as+ if it were collected this cycle; the summary lists it under+ `stale_not_stored`.++### Added: liquidity and money (Phase 29)+Keyless sources only: the FRED graph CSV (`fred.stlouisfed.org/graph/fredgraph.csv`,+allowed by robots.txt with `Crawl-delay: 1`, honored by a 1 s `fred-graph` rate+floor) and the ECB Data Portal (SDMX-JSON). Every point carries `observed_at`,+`value` and `units`; every series is typed `amount_outstanding`, `flow`,+`growth_rate`, `index` or `unknown` and carries a freshness block that flags data older than+its publication cadence allows (a served stale cache copy or an outage shows up+there). `published_at` is null: neither payload carries release dates, and the+responses say so. `limit=0` returns the full history.+- `intel_net_liquidity`: weekly Fed total assets (WALCL) minus Treasury General+ Account (WDTGAL) minus overnight reverse repo (RRPONTSYD), in USD billions.+ WALCL and WDTGAL are USD millions and are divided by 1,000; RRPONTSYD is already+ USD billions. One point per WALCL Wednesday; the TGA must be reported for that+ Wednesday; RRP comes from that day or, when blank on or after 2013-09-23,+ Tuesday only. Before that date a blank Wednesday has no fallback. Each point+ names the RRP date used. Weeks without aligned components are skipped and counted, never filled+ with zero, and a failed component makes the whole response an error. The TGA+ term is the Wednesday level (WDTGAL), not the week average (WTREGEN). A+ `method` block, returned with errors too, states each term's observation basis+ (WALCL and WDTGAL Wednesday levels in USD millions, RRPONTSYD daily in USD+ billions), its conversion, the RRP alignment and why WTREGEN is not used.+- `intel_liquidity_board`: latest reading and change vs the previous observation+ for the Fed balance sheet, TGA, RRP, net liquidity, US M2, euro area M1/M2/M3+ stocks and Eurosystem total assets, sortable by `biggest_move` or `newest`.+ `biggest_move` ranks absolute changes in billions of each row currency, with+ no FX conversion; observation horizons differ. Percentage changes do not+ affect ranking. A+ failed source becomes an `unavailable` row; net liquidity is dropped, not+ computed with a zero term, when any of its components fails. A `blocked` list+ names each measure not covered with its publisher and the status measured on+ 2026-10-17.+- `intel_money_supply`: US M2 (FRED M2SL) and euro area M1, M2 and M3 from the ECB+ BSI dataset (end-of-month stocks, monthly flows, annual growth rates), kept+ separate and never summed. US M3 is reported as discontinued (FRED M3SL ends at+ 2006-02-01).+- `intel_fed_liquidity_series`: WALCL, WDTGAL, WTREGEN, RRPONTSYD or M2SL with full+ history; blank source dates (2,833 for RRPONTSYD on 2026-10-17, 2,679 of them+ before 2013-09-23, when daily values begin) are counted, not read as zero.+ Net liquidity therefore starts at 2003-03-19: of 1,244 WALCL weeks, 705 align+ and 539 are skipped and counted (first 2002-12-18, last 2018-12-05): 8 before+ RRPONTSYD begins on 2003-02-07, 530 with a blank Wednesday before 2013-09-23,+ and 2018-12-05, when RRPONTSYD is blank on both the Tuesday and the Wednesday.+ 10 points use the Tuesday value, all on holiday Wednesdays (measured+ 2026-10-17).+- `intel_ecb_series`: any ECB BSI or ILM series by SDMX key, with units, scale,+ titles and provisional flags taken from the response. A growth rate's change is+ reported in points, not as a percent of a percent.+- Stale cache responses carry `served_from_stale_cache`, `cache_age_seconds` and+ `fetch_failure`, and name the failure in `data_gaps`: the HTTP status, no+ response, an open circuit or an unexpected payload. Each stale copy served+ counts in the circuit breaker's `total_stale_serves` (`intel_status`), and none+ is re-cached as fresh. Only parsed bodies enter the cache. An ECB 404 is a+ final no-data answer, without outage retries, only when its body is the+ portal's JSON problem answer whose detail starts "No Series was returned for+ the query"; any other 404, an empty body or an HTML or plain-text error page+ included, is retried, counted as a breaker failure and takes the outage path.+ An empty ECB response is one only when a start was requested;+ without one it is an unexpected payload and takes the outage path, as does+ JSON that is not an object. An observation value that is not a finite number+ makes the response a parse error.+ Missing ECB roles and board rows are named; index bases, provisional status+ and percentage-point change units are retained. ECB keys must specify every+ dimension, request at most 50 series combinations and be at most 200+ characters long. An ECB start after today (UTC) is refused before any+ request, so a caller's input is never counted as a source failure.+- CLI: `intel liquidity`, `intel net-liquidity`, `intel money-supply`,+ `intel fed-liquidity`, `intel ecb-series`. Collector: `liquidity_board` and+ `net_liquidity` (group `liquidity`). `intel liquidity` prints the ranking+ rule of the chosen sort and each row's status; a terminal too narrow for the+ table gets one entry per indicator instead, so no value, date or unit is cut.+- Live reading 2026-10-17: net liquidity for Wednesday 2026-10-14 was+ USD 5,869.615 billion (WALCL 6,755,639 million, WDTGAL 885,823 million,+ RRPONTSYD 0.201 billion, all observed 2026-10-14).++Not added, measured 2026-10-17: ICI money market fund assets and ETF net issuance+(403 on every path, robots.txt included); FINRA margin statistics (the finra.org+Terms of Use, Restrictions d and e, forbid building a database from the site and+data mining, scraping or harvesting tools, robots included); BLS public API (keyless+v1 answers for CPI-U and payrolls, but api.bls.gov robots.txt disallows all paths+and the terms page answers 403). Fund flows and ETF net issuance therefore have no+source here, and no proxy is substituted for any of these measures.+### Added: news vs market reaction+- `intel_news_market_reaction` (CLI: `intel news-reaction`): the companies and+ countries named in recent story clusters, mapped to a listing (the entity+ table's ticker; a US ticker is annotated with its registrant when SEC's+ company_tickers.json lists it) or to the country's primary index (the table+ `intel_country_stocks` uses), with the move on the story's market session+ from Yahoo daily bars. Company rows give the stock's close-to-close return+ (adjusted closes), the benchmark's return over the same two dates (SPY for+ US listings, the exchange country's index otherwise) and the excess return;+ country rows give the index return and a z-score against its previous+ up-to-20 sessions.+- Session rule, stated in every response: the story time (earliest+ `published` in the cluster; that article also gives the headline and link)+ is converted to the exchange's timezone; before the regular close on a+ trading day it is that session, at or after the close the next one, and a+ weekend or holiday (read from the listing's own bars) maps to the next+ trading day. Each row names the close it used (`close_time_used`). A+ session that has not closed, or whose last bar Yahoo has not finalized+ (its regularMarketTime is before the close), is `pending`.+- Honest gaps: a failed quote, an expired cached chart or SEC file served+ during an outage, a missing benchmark bar, a stock series missing a day its+ benchmark traded (also between the two dates of a return), a cluster whose+ articles map to different sessions, a story timestamp later than the+ collection time and a story older than the bar range are each a `data_gap`+ row or line with the reason and no number, never a 0% move. A bar Yahoo+ fills for a day without trading (open, high, low and close equal to the+ previous close, no volume) is dropped, not read as a 0% session.+ `data_gaps` also names a listing whose Yahoo close differs from its zone's+ standard close, and a chart without adjusted closes. Stories whose earliest+ article is older than `max_age_hours` (default 168) are left out and+ counted. Unmapped names (companies without a ticker in the entity table,+ countries without an index) are listed, not dropped. Company names that are+ also common words (apple, amazon, meta, shell, bp, alphabet, chevron,+ samsung) are excluded with a stated reason unless the headlines carry a+ corroborating term or an article comes from a feed where the company sense+ dominates (a hyphen-joined use such as "meta-analysis" does not count); a+ phrase marking the other sense ("big apple", "amazon rainforest", "chevron+ ruling", "25 bp") excludes the name. A country gets an index row only when+ the headlines use its name; one named only by a demonym, capital or code,+ or inside a longer name such as "Gulf of Mexico", is listed as excluded.+ Responses say they describe same-session co-movement, not causation, and+ are not a trading signal. Tools 139 -> 140.++### Added: research guide over MCP (prompts and resources)+- The server now answers `resources/list`, `resources/read`, `prompts/list`+ and `prompts/get`, and advertises the resources and prompts capabilities+ at initialize. Before this it exposed tools only. No tools were added or+ removed, and no tool name, parameter or existing response key changed;+ the corrected tool descriptions and the new UCDP failure fields are+ listed under Fixed.+- At initialize the server sends `instructions` that point a model at+ `intel://guide` before its first tool call.+- `intel://guide` (markdown): how to ask a strong question (period,+ comparison, measure, place), what an answer contains, what this server+ will not do, the worked prompts, and every registered tool grouped by+ domain module, with a `[needs VARIABLE]` mark on each tool that returns+ an error without its API key. Built from the live registry on every+ read; a test fails if a registered tool is missing or listed twice. It+ says plainly that not every tool marks a failure: with every upstream+ request forced to fail (measured 2026-10-17), 53 of the 85 tools that+ call a source returned an empty list, a zero count or a neutral score+ with no error, `degraded` or `data_gaps` field.+- `intel://guide/source-health` (JSON): open circuit breakers, stale+ serves, stale cache prefixes, cache freshness, and which keyed sources+ have their variables set (names only, never values), with a `verdict`+ line that says when there is nothing to go on yet. Reads in-process+ state and the cache database only; reading it starts no fetch. A cache+ that cannot be read becomes `cache.available: false` with the error,+ and the rest of the snapshot is still returned. It says that breaker+ state covers this server process only. The keyed-source list is checked+ against every credential name quoted anywhere in the package.+- `intel://guide/measures` (markdown): stock versus flow, growth versus+ acceleration, percentage points, seasonal adjustment, the three dates+ (observation, publication, collection), revisions, correlation and+ timing offsets, composite scores, missing data versus zero.+- 29 prompts across conflict, markets, hazards, migration, aviation, cyber,+ infrastructure, maritime, areas of interest, news, politics, sanctions,+ health, stored history and country views. Each names the tools to call,+ the arguments to pass and the limits to respect. Arguments are+ validated: numbers and their ranges, listed values, no tool names from+ outside the prompt, whitespace collapsed so a value stays on its line.+ A missing, unknown or invalid one is an `invalid params` error. Tests+ fail if a prompt names a tool that is not registered, passes an argument+ its schema does not take (name, type, listed value or range), cites an+ output field the code does not produce, describes a step in words that+ share nothing with the called tool's description or names a provider+ that tool does not, or states a count or a table size the code does not+ match.+- `intel guide` prints the guide markdown; `intel guide --measures` prints+ the glossary.+- Two tests drive initialize, resources/list, resources/read, prompts/list,+ prompts/get and tools/list over stdio: one against the installed+ `world-intel-mcp` console script (or `python -m world_intel_mcp.server`+ where none is installed), one always against the module form. Neither+ is skipped.+- The maritime, hotspot and airspace prompts state the maritime and+ flight outage behaviour fixed below: a warning counts at a waterway only+ within 300 km of a position it states, a naval warning with no readable+ position changes no status, `unknown` is an NGA outage and `stale` a+ frozen feed (`status_as_of`), the `navarea` filter takes NGA area codes,+ and a flight source outage reads `source: "none"` with `reason`+ `military_flights_unavailable` in military flights, `unavailable_theaters`+ in theater posture and `unchecked_regions` in surge detection. The+ hotspot prompt also says that the escalation+ score's military component is 0 at every hotspot whatever the aircraft+ data (measured 2026-10-17 with mocked aircraft over all 22 hotspots), so+ military activity is read from the surge and posture tools instead. Tests+ hold each statement against the code through a real fetcher with every+ upstream mocked.++### Fixed+- `intel_ucdp_events`: a missing token or a refused request (the UCDP API+ answers 401 without a token) now returns `error`, `degraded: true` and+ `reason` (`ucdp_unconfigured` or `ucdp_fetch_failed`) next to the empty+ events list, the same shape as ACLED's fetch failure, instead of reading+ as zero events. The first page shared a cache key with the second, so a+ multi-page result repeated the first page in place of the second; every+ page now has its own key, which also carries the page size.+- Stale serves are counted for dictionary payloads too (before, only lists+ and text were counted), so `total_stale_serves` in breaker status and+ `stale_serves` in source health include every stale copy served.+- The cache records the database path it was asked to use and whether it+ fell back to a temporary one (`requested_path`, `fell_back`); source+ health shows both.+- `serverInfo.version` at initialize is the package version; it was the+ MCP SDK's version.+- Tool descriptions: `intel_acled_events` and `intel_risk_scores` name+ `ACLED_EMAIL` and `ACLED_PASSWORD`; `intel_ucdp_events` names+ `UCDP_ACCESS_TOKEN` and all three violence types and says its limit is a+ page size; `intel_btc_technicals` says its distance is from the highest+ daily price of the last 200 days, not the all-time high.+- README environment table: `ACLED_EMAIL` and `ACLED_PASSWORD` replace+ `ACLED_ACCESS_TOKEN`, which no code reads; added `UCDP_ACCESS_TOKEN`,+ `TOMTOM_API_KEY`, `WINDY_API_KEY`, `OPENSKY_USERNAME` and+ `OPENSKY_PASSWORD`.++### Added: tropical cyclone forecast tracks+- `intel_cyclones` and `intel_jtwc_cyclones` take `include_forecast`+ (boolean, default false). With it, each storm gains a `forecast`: the+ `initial` fix and forecast `points` (forecast hour, UTC valid time,+ latitude and longitude, max wind and gust in knots, status such as+ POST-TROP/REMNT LOW or DISSIPATED, and the agency's section label),+ `track_status`, and the advisory or warning number and issue time.+ Without it, both responses and the collector's NHC call are unchanged.+- NHC points come from the forecast/advisory text that CurrentStorms.json+ links: the one NHC product that states UTC valid times and post-tropical+ status outright (the KMZ track gives local times, and the shapefile+ labels a post-tropical remnant low "Subtropical Depression"). The cone+ comes from the linked CONE.kmz: its one ring, simplified+ (Douglas-Peucker, 0.01 degrees; Hurricane Trudy advisory 17 went from+ 1,167 vertices to 56) to `[lat, lon]` vertices, with the source vertex+ count, the tolerance, and a note pointing at the official geometry+ (`cone_url`).+- JTWC points come from each storm's linked warning text (its forecast,+ extended outlook and long range outlook blocks). JTWC links no cone:+ `cone_status` is `not_published`, and `data_gaps` says so.++### Data honesty: forecast tracks+- `data_gaps` names every track or cone not delivered, per storm, with a+ status: `fetch_failed`, `unparsed`, `refused_link`, `not_linked`,+ `not_published` or `not_fetched_cap` (at most 10 storms per call; the rest are named,+ never dropped). A failure marks the response `degraded`; a product the+ agency does not link is a gap, not degradation. A quiet basin still+ answers zero storms, not degraded, and makes no product fetches; a feed+ outage keeps its existing degraded shape and makes none either.+- The text pages are per storm bin, not per issuance, so one can lag the+ feed: an advisory or warning number that disagrees with the feed is+ returned as `stale_advisory` or `stale_warning` with the expected+ number, and its cached copy is dropped.+- Each product is fetched once per issuance (cache keys carry the+ advisory or warning number; one-hour TTL) under its own circuit breaker+ (`nhc-forecast`, `nhc-gis`, `jtwc-warning`), so a product outage does+ not trip the warning feeds' breakers.+- Remote KML is parsed with the standard library: strict UTF-8, any+ DOCTYPE refused, size caps (KMZ 2 MB, KML 8 MB), and a cone with more+ than one ring refused, never trimmed. A ring of more than 10,000+ vertices is refused before simplifying, and simplifying runs off the+ event loop.+- Product links come from the agencies' feeds and are fetched only when+ they are https on the agency's own host (www.nhc.noaa.gov,+ www.metoc.navy.mil). Any other link is reported as `refused_link` and+ never requested.+- Measured 2026-10-17: every product used answered HTTP 200 without a+ key; nhc.noaa.gov robots.txt disallows nothing and the NWS disclaimer+ puts the products in the public domain. The JTWC home page and+ robots.txt answered 403 (CloudFront "Request blocked"), so JTWC's site+ terms could not be read; its RSS and warning texts served 200 to the+ same client. Wind radii and seas are not parsed.++### Added: day timeline (Phase 29)+- `intel_day_timeline` (MCP) and `intel history day YYYY-MM-DD [--by+ collected|observed] [--source NAME] [--limit N] [--per-source N]` (CLI):+ what the history store holds for one UTC calendar day, the half-open+ window `[day 00:00:00Z, next day 00:00:00Z)`. Input is `YYYY-MM-DD` only;+ a malformed or impossible date, or a future day, is an error naming the+ format (the CLI exits 2). Today is allowed and reported as in progress.+- `by=collected` (default) reads the run log. Per source: attempts, ok /+ degraded / error counts with up to 5 distinct reasons, payload changes+ (changed, unchanged, first capture, not stored), first and last capture,+ observations stored and still retained, and how many of the day's+ payload bodies are still kept. Each source gets a `day_state`:+ `changed`, `unchanged`, `answered`, `degraded`, `failed`,+ `not_attempted` (the collector ran that day, not this source),+ `collector_did_not_run` (no capture of any source that day), `never_run`+ (no capture of it in the retained run log) or `unknown_past_retention`.+ A collector block gives the day's capture count, first and last capture+ and the longest stretch without any capture.+- `by=observed`: values whose `observed_at` is the day (a date) or a UTC+ instant on it, one item per series and `observed_at` with the latest+ value, how many values were stored for it and the first one when it was+ revised. Month (`YYYY-MM`) and year (`YYYY`) values containing the day+ are listed apart as period values. Observations without `observed_at`+ (Yahoo quotes) are excluded, and those collected that day are counted+ with the reason.+- Every item carries `observed_at`, `published_at` and `collected_at`.+ Retention is stated per record kind for the day (payload bodies, run+ log, observations): a day past the run-log window reads+ `unknown_past_retention`, never as a day on which nothing ran, and pruned+ payload bodies and observations that outlived their capture are counted.+ Output is capped (default 10 per source and 100 in all, at most 1,000+ and 5,000) with matched and returned counts per source.+- Read-only: the store is opened with SQLite `mode=ro`, so the tool cannot+ write it, and it never fetches. Queries range-scan+ `idx_history_captures_time` and `idx_history_obs_time` and walk+ `idx_history_obs_series` one key at a time; a test checks every+ statement's query plan for a full scan of a history table. On a+ synthetic store of 475,200 captures and 1.75 million observations+ (10,982 series), one call took 24 to 46 ms.+- Tools 152 -> 153.++### Added: observation history and collection health+- A history store in the cache SQLite file. Every collector source run is a+ capture: source, collected_at, status (ok, degraded or error), duration,+ record count, reason and payload hash. A failed fetch is an error capture+ with its reason and no record count, never an ok capture with zero+ records. An empty payload is degraded, because a quiet period and a+ silent upstream failure look the same.+- Payload bodies are kept once per distinct payload as compressed JSON+ (top-level fetch-time stamps are ignored when hashing). Retention, each+ 0 = keep forever: `WORLD_INTEL_HISTORY_PAYLOAD_DAYS` (default 7) for+ bodies, `WORLD_INTEL_HISTORY_CAPTURE_DAYS` (default 30) for the run log,+ `WORLD_INTEL_HISTORY_DAYS` (default 365) for observations. Measured over+ three full 55-source cycles: 90 KB and 193 KB of new compressed bodies in+ the two follow-up cycles (about 70 KB from sources that change every+ cycle, plus the military flight snapshot when it succeeds) and about+ 14 KB of capture rows per cycle. At `--interval 300` that is about+ 130-340 MB of bodies at the 7-day default and about 100 MB of run log at+ 30 days. Quote observations on a trading day were not measured.+- Observations with three dates: `observed_at` (from the payload, or null+ when it has none; never the collection time), `published_at` (when the+ payload names a release time) and `collected_at`. Built-in extractors:+ NOAA Kp, USGS per-event magnitude, FRED-sourced central bank rates+ (curated rows are skipped), Yahoo index and commodity quotes (null+ `observed_at`: the payload carries no quote time).+ `history.register_extractor()` is the public API for new sources.+- MCP tools `intel_collection_health`, `intel_capture_history`,+ `intel_series_history` and `intel_revisions`, and the CLI group+ `intel history health|captures|series|revisions`. History accrues only+ while the collector runs.+- The collector records every source outcome of a cycle in one+ transaction. Its summary gains a `history` key (and the CLI summary a+ History line); a history write failure is reported there and in the+ log, and never fails the cycle.+- Expected cadence for health is 300 s (the shipped plist interval);+ `WORLD_INTEL_HISTORY_CADENCE_S` and+ `WORLD_INTEL_HISTORY_CADENCES=source=seconds,...` override it.++### Notes+- The cycle summary's `successes` still counts a source that returned+ `{"error": ...}` (unchanged, pinned by an existing test); that run's+ history capture is an error.+- Tools 139 -> 143.++### Added: connections with timing offsets (Phase 29)+- `intel_lagged_connections` (CLI: `intel history connections`): Pearson+ correlation between 2 to 8 series in the history store (keys as+ `intel_series_history` lists them), aligned on a UTC day, week (Monday to+ Sunday) or month grid and tested at every lag from `-max_lag` to+ `+max_lag` (default 5, at most 30, reduced so one call runs at most 1,000+ tests). Lag +k compares A at period t with B at t+k, so A leads B by k.+- Default transform: period-over-period changes, never taken across a gap;+ `levels` on request. Responses say which ran and why changes are the+ default (levels of trending series correlate spuriously).+- Per pair: the lag with the smallest p, with r, n (overlapping periods+ after the transform and shift), a two-sided p from Student's t (computed+ from the regularized incomplete beta function, standard library only)+ that treats periods as independent, `p_ar1` (p recomputed with an AR(1)+ effective sample size, below), and the Benjamini-Hochberg `q` and `q_ar1`+ across every test in the call, with the Benjamini-Yekutieli `q_by` (of+ `q_ar1`) alongside. `significant` means `q_ar1` <= 0.05 by default+ (allowed 0.001 to 0.25), and `significant_if_independent` applies the+ threshold to `q`; the other significant lags are listed too. The summary+ gives both counts.+- A pair and lag with fewer than 30 overlapping periods (callers may go down+ to 20), or a constant side, is listed as not tested with its n, never+ dropped. 30 points give about 80% power for a true |r| of 0.5 at alpha+ 0.05 (module docstring).+- One vintage, the latest collected value for each `observed_at`. Rows+ without `observed_at` (Yahoo quotes) are not used, with the reason: rows+ are stored only on change, so a missing day cannot be told from an+ unchanged one. A period takes its last observation; nothing is averaged.+ On the week and month grids each series reports the shortest and longest+ interval its changes span (`change_interval_days`), and `data_gaps` names+ unequal intervals.+- Serial correlation: each series' lag-1 autocorrelation (phi) after the+ transform, and on every test an AR(1) effective sample size n (1 - phi_a+ phi_b) / (1 + phi_a phi_b), capped at n, with `p_ar1` recomputed from it;+ significance follows `q_ar1`. Below an effective size of 3, or without a+ measurable phi, `p_ar1` is 1 and the entry says "no evidence" or "not+ assessed". `serial_correlation_dominates` marks an effective size under a+ fifth of n, and `data_gaps` names those pairs and every series with+ |phi| above 0.3. The strongest lag's p and `p_ar1` are post-selection;+ `q` and `q_ar1` adjust for every test. Nothing is prewhitened. Measured in+ a scratch simulation through the store: two independent random walks of+ 300 daily points in levels (seeds 0-99, defaults) have a lag with q <=+ 0.05 in 91 seeds and with `q_ar1` <= 0.05 in none; two independent series+ of 200 AR(1) changes (4,000 runs, lag 0) reject at p <= 0.05 in 12.2%+ (phi 0.5) and 35.3% (phi 0.8) of runs, and at `q_ar1` <= 0.05 in 4.5% and+ 5.1%.+- `cannot_prove` in every response: correlation is not causation, a lead is+ not a causal direction, serial correlation inflates significance, a+ shared driver produces correlation, the store holds only what the+ collector recorded, BH under dependence is approximate and covers one+ call, and a small q is not a large effect.+- An unknown grid or transform is an error naming the allowed values;+ numeric inputs are clamped and each clamp is reported, in the MCP+ response (`inputs_clamped`) and as a `Clamped:` line in the CLI. A given+ `start` moved later by the 3,000-period window cut is reported the same+ way.+- Measured 2026-10-17 over a live MCP stdio session and the CLI, on four+ real FRED series (WALCL, WDTGAL, WTREGEN, RRPONTSYD) loaded into an+ isolated store as one capture; illustrative, not findings. The figures+ below were recomputed offline on that stored capture (direct, CLI and MCP+ stdio) after `q_ar1` became the significance rule. Week grid, changes: 24+ of 66 tests significant (26 if periods were independent); the Wednesday+ TGA level against its week average gives r 0.61 at lag 0 and 0.59 at lag+ +1, the averaging window rather than a cause. Levels: Fed total assets+ against either TGA series gives r 0.74 at lag 0 (n 1,244) and p near+ 1e-214 if the weeks were independent, but AR(1) effective sample sizes of+ 5.2 and 3.3 leave `p_ar1` 0.13 and 0.37: not significant, and `data_gaps`+ says serial correlation dominates. Day grid: the weekly series have no+ adjacent-day changes, so nothing is tested and the response says why.+- With the default 365-day observation retention+ (`WORLD_INTEL_HISTORY_DAYS`), a store filled only by the collector spans+ about a year, so the month grid cannot reach the 20-point floor without a+ longer retention or backfilled history.+- Tools 152 -> 153.++### Added: history backfill and more history extractors (Phase 29)+- `intel history backfill fred SERIES... [--start YYYY-MM-DD]`,+ `intel history backfill ecb DATASET.KEY... [--start YYYY-MM-DD]` and the+ MCP tool `intel_history_backfill` load the history that FRED's keyless graph CSV+ and the ECB Data Portal (BSI and ILM datasets) already serve into the+ history store. Requests reuse the liquidity tools' fetch and parse code,+ so they go through the Fetcher (FRED rate floor, circuit breaker, cache):+ a copy cached by an earlier call (FRED 1 h, ECB 3 h) is reused without a+ request.+- Backfilled rows have their own sources, `backfill:fred` and+ `backfill:ecb` (series `backfill:fred:<ID>` and+ `backfill:ecb:<DATASET>.<KEY>`), so they never read as collector+ captures; `intel_collection_health` and `intel history health` list them+ apart (`backfills`). Every run is logged in a new table,+ `history_backfills`, created in place with `CREATE TABLE IF NOT EXISTS`+ (existing rows untouched).+- Dates: `observed_at` is the publisher's period (FRED's date; ECB months+ as written, ECB weeks as the Sunday that ends the ISO week);+ `published_at` is NULL, because neither response names a release or+ vintage date; `collected_at` is the backfill time, stamped after the+ call's last fetch. Values are the publisher's vintage on the backfill+ day, already revised, so revisions made before the first backfill are+ invisible.+- Idempotent: a re-run stores only new or changed values, and a changed+ value is a revision in `intel_revisions`. FRED's missing cells (`.` and+ blank) are skipped and counted, never stored as zero. ECB missing values+ cannot be counted (the SDMX-JSON parser drops them) and read `unknown`.+- Failures are errors, never an empty success: an HTTP error, an empty or+ malformed body, a window without values, and a response available only+ as a stale cache copy each record an error capture and store nothing.+ The CLI exits 1 when any request failed.+- Caps per call: 5 FRED series or 2 ECB keys (at most 20 series per key),+ the newest 20,000 points per series and 100,000 per call; `--start`+ narrows the window.+- Retention: observations are pruned by `collected_at`, not `observed_at`,+ so a 1962 value is kept as long as any value stored by the same backfill+ (`WORLD_INTEL_HISTORY_DAYS`, default 365). A backfill prunes before it+ stores, so a pruned value is stored again as new.+- New history extractors (`history_extractors.py`): `liquidity_board`+ (latest and previous value per indicator; the derived net liquidity row+ is left to its own source), `net_liquidity` (net liquidity and its three+ terms per Wednesday, reverse repo dated by the day it was taken from) and+ `net_migration` (World Bank SM.POP.NETM per country and year). Each+ dates a value only from the payload.+- Measured 2026-10-17, live, isolated HOME: WALCL 1,244 values+ (2002-12-18 to 2026-10-14), RRPONTSYD 3,348 (2,833 blank cells skipped),+ DGS10 16,182 (721 skipped; units unknown, it is not in this server's+ FRED catalog), euro area M3 560 months (1980-01 to 2026-08, 1+ provisional). A second run from the cached copies and a refetch of WALCL+ and M3 stored 0.+- FRED's terms of use speak of personal, non-commercial use of FRED data;+ whether a deployment fits them is the operator's call.+- Tools 152 -> 153; the `intel history` group gains `backfill fred|ecb`.++### Added: news signals (ROADMAP Phase 29)+- `intel_hostility_timeline`: per UTC day, GDELT DOC 2.0 coverage of a+ country or a pair of countries (`timelinevolraw`): matching articles,+ articles that also use threat / sanction / force / criticism terms (one+ GDELT query per category, every term listed in `queries`), GDELT's total+ monitored articles, and average tone (`timelinetone`, weighted by the+ per-bucket article counts). A failed call, or one only an expired cached+ copy answered, leaves its column null for every day (`column_status`+ per call, `stale_age_seconds` per expired column); a day GDELT did not+ return is null in every column, and a day one series lacks is null in+ that column; all are listed in `data_gaps`. Partial days (GDELT answered+ 2026-10-17 in 15-minute buckets for 3 days and hourly buckets for 7) are+ flagged `partial` per volume column (`partial_columns`,+ `coverage_by_column`), and today's unfinished UTC day is flagged+ `in_progress`. Failed and expired columns get one retry pass, which+ stops at the first retry that fails again. Countries resolve from the+ 22-country table by name, ISO3 or ISO2 code; other names are searched+ verbatim, and other 2- and 3-letter codes are refused.+- `intel_situations`: country pairs ("between": a headline naming two or+ more countries) and single countries ("inside": a headline naming one)+ ranked over a recent RSS window by most covered, most hostile (headline+ keyword heuristic, `classifier.classify_hostility`) or biggest change.+ Change is defined in the response: current minus prior window, counted+ only over feeds whose retained history reaches back past the prior+ window's start; the feeds that do not are named. With no such feed,+ change fields are null and `change_measured` is false, and a change+ sort ranks by coverage (`sort_applied`); a change figure resting on+ under half of the window's items is named a thin sample.+- `intel_top_stories`: story clusters in the window carried by at least+ `min_outlets` distinct outlets, plus attention: the countries and+ organizations whose headline mentions grew most against the prior window+ (empty with `attention_change_measured: false` when no feed spans both+ windows).+- `intel_news_clusters` clusters gain `outlets` and `outlet_count`+ (distinct publishers among all members; sister feeds such as BBC World+ and BBC Mundo count once). Existing keys are unchanged.+- CLI: `intel hostility COUNTRY [OTHER]`, `intel situations`,+ `intel top-stories`. Nulls render as `n/a`, never 0; partial days are+ marked `*` (and each count from a partial column), today `~`, and+ expired columns are named with their age; unmeasured change and+ attention print as not measured.+- Collector: `situations` and `top_stories` (57 sources).++### Changed+- Concurrent `fetch_news_feed` reads of the same feed set share one+ request per feed. The collector starts its four news sources in one+ gather, and each used to request every feed itself; measured live+ 2026-10-17, a news-group cycle made 119 feed requests for 119 feeds+ (4 of 4 sources ok, 9.8 s). Each caller still gets its own limit and+ its own item copies, and a caller's timeout does not cancel the read+ the others are waiting on.+- Live GDELT calls are spaced at least 5 s apart by the fetcher+ (`_SOURCE_RATE_LIMITS["gdelt"]`), for every GDELT caller: GDELT's 429+ body asks for "one every 5 seconds" (measured 2026-10-17). Cache hits are+ not delayed. The floor holds across the processes that share one cache+ DB (collector, MCP servers, dashboard, CLI): every request that passes+ the fetcher's GDELT floor also reserves a slot in a `source_floor` table+ under `BEGIN IMMEDIATE` (`shared_floor.py`); a reservation that cannot+ be made is logged and the request keeps the in-process floor. A 429 from+ any source with a floor is retried no sooner than that floor+ (`get_json`; it was 1 s, then 2 s). Processes on different cache DB+ paths still do not coordinate. The AOI sweep makes one GDELT call per+ AOI, so the floor bounds it: against a mocked GDELT, 45 AOIs took 220 s+ of the collector's 240 s `aoi_digest` budget and 50 AOIs timed out+ after 48 calls (measured 2026-10-17, every other AOI domain stubbed).++### Fixed+- RSS outage read as a slow news day (ROADMAP Phase 24.5):+ `fetch_news_feed` returned `count: 0` with no marker when every feed+ failed. It now reports `feeds_attempted`, `feeds_ok`, `feeds_failed` and+ `feeds_stale` on every call, and `error` / `degraded` /+ `reason: all_feeds_failed` when no feed answered live;+ `intel_news_clusters` and `intel_trending_keywords` pass the marker+ through, so `intel trending` prints an error instead of an empty+ keyword table.+- RSS outage behind a warm cache read as healthy news: a feed whose fetch+ failed came back as its expired cached copy (the fetcher's stale+ fallback, which marks only dict payloads), so in a running deployment+ an outage counted every feed as fine until the expired copies were+ evicted (the collector evicts about hourly; a server running without+ the collector keeps them until `intel sync`). Such feeds are now listed+ in `feeds_stale`, never counted in `feeds_ok`, and kept out of+ situation and attention change figures.+ Verified live 2026-10-17: with an expired copy seeded for DW Europe+ (its feed answers 404), the europe category reported+ `feeds_stale: ["DW Europe"]`.+- Cluster `sources` was always empty: the clusterer read `source_name` /+ `source`, but RSS items name their outlet `feed_name` (measured live+ 2026-10-17: 23 of 23 clusters had `sources: []`, which also emptied+ `intel_world_brief` top-story sources).+- RSS `published` times were shifted by the host's UTC offset:+ `_parse_published` read feedparser's UTC struct with `time.mktime`+ (local time) instead of `calendar.timegm`. The struct carries+ `tm_isdst=0`, so the shift is the zone's standard offset: on mac-studio+ (US Eastern) an item published 14:43:52 UTC came out `19:43:52Z`, five+ hours ahead (measured 2026-10-17). The amount depends on the host zone+ (none on a UTC host). It skewed every RSS-based time window and any+ ordering against non-RSS times. The regression test sets its own zone,+ so it fails on the old code on a UTC CI runner too.+- Country dossier news was always empty, with no marker (ROADMAP Phase+ 24.5), for three reasons: it asked `fetch_news_feed` for+ `category="all"`, which is not a category (the feed answered with an+ error dict); it read `articles` and `source`, while the feed emits+ `items` and `feed_name`; and it checked only its own `_error`, never the+ feed's `error`. It now reads every feed, passes a feed error or outage+ through as `error` / `degraded` / `reason` with `mention_count: null`+ and a `data_gaps` entry, and names failed or stale feeds. A fourth+ quiet zero: 28 of the 50 accepted country codes (GB, DE, JP and others)+ have no headline keywords, so the search could never match; the section+ now says "mentions not searched" instead of reporting zero.+ `intel dossier` prints `News: not measured` and the gaps in that case.+- Review fixes for the news signals (independent review, 2026-10-17):+ - The hostility timeline showed an expired cached GDELT copy (days old+ when no collector evicts it) as current counts, with no marker. Such a+ column is now null, named in `data_gaps` with its age and in+ `column_status`, and the response is `degraded` with+ `reason: gdelt_stale`.+ - A day with no buckets in the series that judged completeness read as+ complete (`partial: false`), and a category series covering half a day+ sat unflagged next to full-day counts. Partial days are now judged per+ column; a half-day count gets no `hostile_share`.+ - With no comparable feed, situations reported change 0 and ratio 1.0+ ("no change"), and the CLI printed `+0`; attention read as "nothing+ grew". Both are now null or empty and marked not measured.+ - A 429 inside one GDELT call was retried after 1 s and 2 s, and the+ timeline's retry pass asked again for every failed column; see the+ GDELT spacing entry under Changed.+ - Dossier headline matching was a substring test ("Tirana" counted as+ Iran, "Indiana" as India) and hid its cap: it now matches whole words,+ removes four compound names first, and reports `matching_items`,+ `mention_count_capped`, `items_searched` and `searched_span`.+ - A near-total RSS outage (118 of 119 feeds down) read as normal:+ `fetch_news_feed` now marks a read where under half of the feeds+ answered live `degraded` with `reason: partial_feeds_failed`, and+ `intel_trending_keywords` passes the feed counts and marker through;+ situations, top stories and the dossier rank or count over the feeds+ that answered and say so.+ - Clustering ran on the event loop the collector and the MCP server+ share; unknown codes such as "GBR" were sent to GDELT as text; a limit+ of 0 or -1 returned nothing or dropped a result, and `min_articles: 0`+ divided by zero; feed links of any scheme (`javascript:`, `data:`)+ were passed on and titles had no length cap (now http(s) only, titles+ capped at 500 characters).++### Fixed: vessel snapshot waterway matching+- `intel_vessel_snapshot` counted every NGA warning at all nine waterways,+ so three naval-keyword warnings anywhere on Earth marked Panama and+ Hormuz critical alike. On the live feed of 2026-10-17 the old code marked+ all nine `critical` from 8 such warnings, none within 300 km of any of+ them. A warning now counts only at waterways within 300 km of a position+ its text states, read from the full text (positions past the+ 500-character cut used to be lost). A warning that states no readable+ position counts nowhere: its area code names at least a whole NAVAREA.+ Crediting such warnings to the Panama Canal by NAVAREA IV or XII was+ measured and rejected: on the same capture all 5 of those credits were+ wrong (Hawaii, California, "warnings in force" lists), and on the 3,480+ warnings of 2024 they were 200 of Panama's 203, none naming Panama.+ Naval warnings with no readable position are listed in+ `unplaced_naval_warnings` with a reason (`multi_navarea_series`,+ `navarea_too_broad`, `position_unreadable`, `unknown_area_code`) and+ named in `data_gaps` as `<area code>:<id>`, since one id can name+ warnings in two series. The rule is in `matching_rule`.+- Each waterway emits `total_nearby` (warnings of any topic credited to+ it, which the old code computed and dropped) and `status_as_of`;+ `warning_details` entries carry `match`, `distance_km` and `issue_date`.+- With NGA down every waterway read `clear`. It now reads `unknown`, and+ the response carries `error`, `degraded` and `reason`. With the feed past+ its staleness threshold every waterway reads `stale` (its counts kept,+ dated by `status_as_of`) instead of a current threat level.+- Positions are read in degrees-minutes, degrees-minutes-seconds and the+ two mixed, with whitespace, a comma or a slash between latitude and+ longitude; a lone latitude or longitude (a band or a meridian) counts as+ a stated but unreadable position. On the 3,866 warnings captured+ 2026-10-17 (386 active, 3,480 from 2024) this loses none of the previous+ parser's 21,780 positions and reads 34 more, in HYDROLANT 2024-473, 479+ and 488.++### Fixed: navigational warnings+- An NGA outage returned `warnings: []` with no marker, the same shape as a+ sea with no active warnings. It now carries `error`, `degraded`,+ `reason` (`nga_msi_fetch_failed`) and `data_gaps`. A payload with no+ warnings list is `nga_msi_unexpected_payload`; a stale cache serve is+ degraded and says how old the copy is.+- The NGA MSI API holds no warning issued after 10 May 2024 (measured+ 2026-10-17: `msgYear=2025` with `status=all` and `msgYear=2026` return+ none, `msgYear=2024` with `status=all` ends on 10 May, and+ `/current-warnings` and `/inforce` list the same 2024 state), yet+ responses read as current. `intel_nav_warnings` now reports+ `newest_issue_date`, `newest_issue_age_days` and `feed_stale`; past+ `stale_after_days` (14, twice the slowest series' longest gap between+ issues in 2024) the response is degraded with the age in `data_gaps`. An+ issue date more than a day ahead is left out of the check and named in+ `data_gaps`: one "MAY 2042" among frozen 2024 warnings used to make the+ feed read current. The vessel snapshot and fleet report pass this on,+ and `intel warnings` prints a STALE line and the data gaps.+- The `navarea` filter compared the value with the API's `navArea` field,+ which only ever holds the codes 4, 12, A, P and C, so the documented+ Roman numerals matched nothing: `navarea="IV"` returned 0 of the 71+ code-4 warnings on the live feed, with no marker. It now takes the codes,+ their series names (`HYDROPAC`) and IV or XII for 4 or 12; a value no+ carried area matches (most NAVAREAs arrive inside the A, P and C series)+ returns `error` and `reason` `navarea_not_carried` with a `data_gaps`+ line naming the series that carry it, never a bare 0. The tool schema+ and the CLI `--navarea` help say the same. The freshness fields describe+ the whole active feed, before the filter, so an area with nothing in+ force on a frozen feed reads stale instead of an undated 0.+- `area_codes` maps the codes the API sends in `navArea` (4, 12, A, P, C;+ never the Roman numerals) to the NAVAREAs, with each code's source in+ `sources/maritime.py`. Code 4 also carries Canadian Arctic (NAVAREA+ XVIII) warnings, so it is not a single NAVAREA.++### Fixed: fleet report and theater posture+- `intel_fleet_report` turned a failed component into `{}`, so with all+ three down it read `LOW_ACTIVITY` with no marker. A component that raises+ or reports an error is now named in `unavailable_components` and+ `data_gaps` and the report is degraded; so is a vessel snapshot whose NGA+ feed is stale, which is no longer scored. With all three unavailable the+ report carries `error` and `reason` (`fleet_components_unavailable`),+ `readiness_level` `UNKNOWN` and `readiness_score` null. With some+ missing, `readiness_lower_bound` is true and `data_gaps` says what the+ score leaves out and how high it can still reach (each component adds at+ most 30 of 90). Component `data_gaps` are passed on.+- `intel_military_flights` with adsb.lol and OpenSky both down returned+ zero aircraft, told apart from an empty sky only by `source: "none"`.+ Those keys stay, and the response now also carries `error`, `degraded`+ and `reason` (`military_flights_unavailable`).+- `intel_theater_posture` turned a theater that no flight source answered+ for (adsb.lol and OpenSky both failed) into zero aircraft, so a full+ outage read as an empty sky, and as `LOW_ACTIVITY` with no error in the+ fleet report. Each theater now names its `source`; unanswered ones are+ listed in `unavailable_theaters` and `data_gaps` and the response is+ degraded, with `error` and `reason` (`military_flights_unavailable`)+ when none answered. Only a complete posture is cached.+ `intel_military_surge` turns a posture error into its own error and+ skips regions whose theater had no source (`unchecked_regions`) instead+ of recording zeros in their baselines.++### Fixed: report maritime section+- The PDF/HTML report read `vessels` and `snapshot` for its maritime+ section, keys the vessel snapshot never emits, so every report said "No+ maritime data". It now shows the nine waterways' statuses, a STALE note+ for a frozen feed, the outage error, and the first data gaps.++### Tests+- Failing-first regression tests built on live NGA records captured+ 2026-10-17, and `test_maritime_honesty.py` and `test_fleet_honesty.py`+ for the second review round: each finding test fails on the previous+ branch head and passes now, and five tests kill the mutants that survived+ the first round (radius boundary, malformed DMS, notation order,+ staleness boundary, two components down).++### Still open+- The dashboard's nav-warnings table and fleet panel do not yet read+ `feed_stale`, `stale`, `unknown`, `readiness_lower_bound` or `UNKNOWN`,+ and the collector counts error results as successful collections.+- Strategic posture and temporal anomalies still read a posture outage as+ zero activity; posture now marks it, but they do not check.+- A naval warning that cannot be placed leaves every waterway's status+ unchanged; it is named only in `unplaced_naval_warnings` and+ `data_gaps`.++### Added: AOI escalation news and convergence components+- `intel_aoi_escalation` now scores the news and convergence components it+ used to report as null (ROADMAP Phase 23).+- News: the rise in the area's share of all GDELT coverage over the last 7+ days against the 7 days before, for the reverse-geocoded settlement and+ county (the query the AOI brief already uses, sent as `timelinevolraw`).+ Expected articles = prior share x current GDELT volume; change_pct =+ 100 x (current - expected) / max(expected, 20); component =+ min(20, 0.2 x max(0, change_pct)). Shares rather than raw counts because+ GDELT's own intake has multi-day outages (measured 2026-10-17 for+ Pittsburgh: no data for 16 of 85 days), which raw counts would read as a+ surge on recovery; a comparison where one week monitored under half the+ other's volume is refused as a data gap. An area that cannot be+ geocoded is not scored, rather than searched by the AOI's name.+- Convergence: `analysis/convergence.py`, unmodified, over the+ earthquakes, military flights, ACLED events and wildfires inside the+ AOI's exact shape (circle, polygon or corridor, through the same+ `filter_by_aoi` scoping as the brief). With an input missing, a+ convergent cell is reported as a lower bound; no cell at all is null,+ because quiet cannot be told from missing.+- New response keys; existing keys keep their meaning. `computed_from`+ names the components the score was computed from, and+ `zero_filled_components` the ones among them that are a 0 only because+ the military or ACLED fetch failed (`score_hotspot` takes no null for+ those, unchanged); `news_signal` (query, both windows' counts and+ shares, change), `news_scoping` and `convergence_signal` (cells, events+ per domain, inputs used, failed or partial) carry the working. A failed+ news or convergence input makes that component null in `components`,+ listed in `unavailable_components` and explained in `data_gaps`, never+ a 0.++### Changed+- The escalation also fetches earthquakes and wildfires (convergence+ inputs) and one GDELT timeline, in parallel with ACLED and military+ flights; their failures are named in `data_gaps`. The brief, the change+ sweep and the escalation now share one AOI scoping helper.+- `test_aoi.py` stubs every network-bound source by default: its older+ escalation tests stub only ACLED and military flights and would+ otherwise reach Nominatim, GDELT, USGS and FIRMS live.++### 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 ends at the file's last month and is+ 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 calendar dates a year earlier, compared+ only when every day of both spans is in the file (`year_to_date` gives+ `complete`, `days_reported` and `days_in_period`). Read through the+ GOV.UK Content API and the published ODS time series, parsed with the+ standard library (zipfile and the expat streaming parser, 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`.+- Downloaded files are untrusted input. The ODS reader refuses a DTD,+ reads only the sheets the tool uses (SB_01, SB_02 and Notes), and+ refuses a file past one budget for those sheets together (200,000 rows,+ 1,000,000 cells, 4,194,304 characters of text), checked before a repeat+ count is expanded, or past 16 MiB of content.xml, 10,000 levels of+ nesting, 2,000 distinct names or a tag (or text run) longer than 1 MiB;+ a member compressed other than stored or deflated is not opened. A file+ that cannot be read, whatever the parser fault, gives a degraded+ response with a reason (or the last good copy, marked stale), and a+ degraded response names its missing figures in `data_gaps` too. Rows+ and cells that cannot be read outside the columns the tool uses are+ named in `data_gaps` instead of failing the file; a CBP row with bytes+ that are not UTF-8 in a column the tool reads is counted as unreadable.+- Requests use an identifying User-Agent, two per refresh (the listing,+ then the file), cached 12 h (CBP) and 3 h (UK). Only https links on the+ publishers' own hosts (www.cbp.gov; assets.publishing.service.gov.uk or+ www.gov.uk), on the standard port and without credentials, are+ requested. CBP's robots.txt rule is checked on the path as normalized+ for the request (dot segments removed, escapes of unreserved characters+ decoded), so paths it disallows are never requested; a newer-looking CBP+ file at such a path is named in `data_gaps` instead, as is any+ encounters link the tool cannot read. Redirects are followed, and the+ download size caps apply after the body is read, both in the shared+ fetcher (see the module's gaps).+- 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.++### Added: Kalshi and cross-venue prediction markets+- `intel_kalshi_markets`: Kalshi open markets from its public market-data+ API (no account, no key), ranked by 24h then lifetime volume. Prices are+ YES implied probabilities (bid/ask midpoint when the book is two-sided,+ else the last trade, with the basis named); Kalshi's raw dollar quotes+ are kept. Filter by category (the category's highest-volume series) or+ series ticker. The response names the events it scanned and whether the+ scan was complete: Kalshi lists more than 8,000 open events, furthest+ close date first.+- `intel_prediction_compare`: the same event on Kalshi and Polymarket side+ by side. Matching is deterministic: quantities (with their direction,+ so "more than 25 bps" is not "25 bps"), years, end dates, negation and+ the outcome side must all agree, and each pair carries a+ `match_confidence` and its reasons. Below the threshold (default 0.6) a+ pair is not a match. Returns the price gap per pair, the closest+ rejected pairs with the reason, and unmatched counts per venue.+- `intel_prediction_settled`: recently settled markets on both venues with+ the outcome and the YES price at fixed offsets before close (default 24h+ and 168h) from each venue's price-history endpoint, and a Brier score per+ venue and offset with sample size, distinct events, selection and+ exclusions stated. A venue whose price history cannot be read is not+ scored. The two samples are different markets, and the response says so.+- Every number these three tools take has a stated range in its input+ schema: at most 25 Kalshi series or pages per scan, 2,000 Polymarket+ markets, 500 results, 100 settled markets per venue, and 10 offsets of+ at most 8,760 hours, so one call cannot fan out into an unbounded number+ of upstream requests. The MCP server refuses a value outside its range;+ the source functions clamp counts again for the CLI and other callers,+ and refuse a value that is not a number before any request.+- CLI: `intel kalshi`, `intel prediction-compare`, `intel prediction-settled`.+- Collector: `kalshi_markets` and `prediction_compare` (Economics+ category) join the `prediction` domain. Sources 55 -> 57. Tools 139 -> 142.++### Fixed: prediction markets outage read as "no markets"+- `intel_prediction_markets` returned `{"markets": [], "count": 0}` with no+ marker when Polymarket was down, the same shape as a quiet market. It now+ adds `error` and `degraded: true` on an outage or an unexpected response,+ and `stale: true` when the list came from an expired cache entry. Keys,+ parameters and the tool name are unchanged.++### Fixed: prediction-market review findings+- Expired-cache serves after a failed fetch are marked on every Kalshi read+ (open markets, settled listing, candlesticks) and on Polymarket's settled+ listing and price histories: `stale` and `degraded` are set and+ `data_gaps` names the count and the oldest age. A price history served+ from expired cache is excluded from Brier scoring, not scored as current.+- Matching: rate actions (cut, raise or hike, hold or no change) and+ directions (above, below) must agree; a four-digit number after `$` or a+ comparator is an amount, not a year; minus signs and ordinals are kept.+ "U.S." matches "US", "$100m" matches "$100 million", and "4.5% or higher"+ matches "above 4.5%" with a flag that the boundary differs. Candidate+ blocking no longer drops a same-event pair whose words many other titles+ share. `match_confidence` (key unchanged) is documented as an ordinal+ score for ranking pairs, not a probability.+- `intel_prediction_compare`: each side carries its price basis, bid, ask,+ spread and last-trade time (Kalshi's public trades endpoint, for pairs+ priced from a last trade; Gamma publishes none). A pair is flagged,+ ranked after comparable pairs and left out of `comparable_count` when+ either side is not a two-sided quote midpoint (a last trade or Gamma's+ listed outcome price), its spread is wider than 0.10, or the thresholds+ differ at the boundary.+- `intel_prediction_settled`: Polymarket markets are scored against the+ earlier of `endDate` and `closedTime` (`closedTime` comes after+ resolution), and each sample entry names which. The comparability text+ states that reference times differ by venue and that samples differ by+ offset; the CLI prints one Brier table per venue. An offset of 0 or below+ is refused, even next to a valid one, instead of being dropped.+- Kalshi requests wait for the pacing interval only on a cache miss.+ Non-finite or out-of-range prices and non-finite volumes are treated as+ unreadable and counted; identifiers must match each venue's measured+ format before they build a URL or a request; titles are capped at 500+ characters. `intel_prediction_markets` names how many markets it left+ out for an unusable price.+## 0.11.0 - 2026-10-12Cross-border migration (MCP tools, CLI, collector and a dashboarddiff --cc src/world_intel_mcp/tests/test_resource_cleanup.pyindex 9cfe599,0000000..283e671mode 100644,000000..100644--- a/src/world_intel_mcp/tests/test_resource_cleanup.py+++ b/src/world_intel_mcp/tests/test_resource_cleanup.py@@@ -1,121 -1,0 +1,124 @@@+"""Resource owners close connections even while callers retain references."""++import sqlite3++import pytest++from world_intel_mcp import collector, reports+from world_intel_mcp.analysis import alerts, temporal+from world_intel_mcp.sources import intelligence+from world_intel_mcp.tests.test_collector_runtime import FakeVectorStore++[email protected]("fail", [False, True])+async def test_standalone_report_closes_resources(tmp_path, monkeypatch, fail):+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "report.db"))+ opened = []++ async def generate(fetcher, *args):+ opened.append((fetcher.cache._conn, await fetcher._get_client()))+ if fail:+ raise RuntimeError("render failed")+ return {"path": "report.html"}++ monkeypatch.setattr(reports, "generate_report", generate)+ try:+ if fail:+ with pytest.raises(RuntimeError, match="render failed"):+ await reports.generate_report_standalone()+ else:+ assert await reports.generate_report_standalone() == {"path": "report.html"}+ conn, client = opened[0]+ assert client.is_closed+ with pytest.raises(sqlite3.ProgrammingError, match="closed"):+ conn.execute("SELECT 1")+ finally:+ for conn, client in opened:+ conn.close()+ await client.aclose()++[email protected]("fail", [False, True])+async def test_collector_closes_cache(tmp_path, monkeypatch, fail):+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "collector.db"))+ monkeypatch.setattr(collector, "VectorStore", FakeVectorStore)+ opened = []++ async def collect(fetcher, *args):+ opened.append((fetcher.cache._conn, await fetcher._get_client()))+ if fail:+ raise RuntimeError("collection failed")+ return {"collected": 0}++ monkeypatch.setattr(collector, "collect_once", collect)+ try:+ if fail:+ with pytest.raises(RuntimeError, match="collection failed"):+ await collector.run_once()+ else:+ assert await collector.run_once() == {"collected": 0}+ conn, client = opened[0]+ assert client.is_closed+ with pytest.raises(sqlite3.ProgrammingError, match="closed"):+ conn.execute("SELECT 1")+ finally:+ for conn, client in opened:+ conn.close()+ await client.aclose()+++async def test_weekly_trends_closes_database_on_query_error(tmp_path, monkeypatch):++ # An empty file is a database with no baselines table, so the read opens++ # a connection and its query fails (a missing file is never opened).+ path = tmp_path / "no-baselines.db"++ path.write_bytes(b"")+ monkeypatch.setattr(temporal, "_default_db_path", lambda: path)+ opened = []+ connect = sqlite3.connect++ def tracked_connect(*args, **kwargs):+ conn = connect(*args, **kwargs)+ opened.append(conn)+ return conn++ async def anomalies(fetcher):+ return {}++ monkeypatch.setattr(sqlite3, "connect", tracked_connect)+ monkeypatch.setattr(intelligence, "fetch_temporal_anomalies", anomalies)+ try:+ await alerts.fetch_weekly_trends(None)+ assert len(opened) == 1+ with pytest.raises(sqlite3.ProgrammingError, match="closed"):+ opened[0].execute("SELECT 1")+ finally:+ for conn in opened:+ conn.close()++[email protected]("run", [collector.run_once, collector.run_daemon])+async def test_collector_closes_cache_when_start_fails(tmp_path, monkeypatch, run):+ from world_intel_mcp.cache import Cache++ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "start-failure.db"))+ opened = []++ def cache():+ instance = Cache()+ opened.append(instance._conn)+ return instance++ class FailedStart(FakeVectorStore):+ async def start(self):+ raise RuntimeError("start failed")++ monkeypatch.setattr(collector, "Cache", cache)+ monkeypatch.setattr(collector, "VectorStore", FailedStart)+ try:+ with pytest.raises(RuntimeError, match="start failed"):+ await run()+ with pytest.raises(sqlite3.ProgrammingError, match="closed"):+ opened[0].execute("SELECT 1")+ finally:+ for conn in opened:+ conn.close()