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
Prediction markets: review fixes (stale marking, matching gates, price basis, reference times)
Phoenix Agent (mac-studio)93d633e1593c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a864ad0..2d699ca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -42,6 +42,40 @@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 --git a/README.md b/README.mdindex fe62ecf..c8ffb2e 100644--- a/README.md+++ b/README.md@@ -329,9 +329,9 @@ collector.py (daemon) ─┘| Tool | Description ||------|-------------|| `intel_prediction_markets` | Polymarket prediction contracts |-| `intel_kalshi_markets` | Kalshi open markets from its public market data (no account), ranked by volume; YES implied probabilities with the venue's units stated; filter by category or series. Says which events it scanned and whether the scan was complete |-| `intel_prediction_compare` | The same event on Kalshi and Polymarket: deterministic matching (quantities, years, end dates, negation and outcome side must agree), a `match_confidence` with reasons per pair, the price gap, the closest rejected pairs and why, and unmatched counts per venue |-| `intel_prediction_settled` | Settled markets on both venues with the outcome, the YES price at fixed offsets before close, and a Brier score per venue and offset with sample size, distinct events, selection and exclusions. A venue without price history is not scored |+| `intel_kalshi_markets` | Kalshi open markets from its public market data (no account), ranked by volume; YES implied probabilities with the venue's units stated; filter by category or series. Says which events it scanned and whether the scan was complete. Data served from an expired cache entry after a failed fetch is marked `stale` and `degraded`, with its age |+| `intel_prediction_compare` | The same event on Kalshi and Polymarket: deterministic matching (quantities, years, end dates, negation, rate actions such as cut/raise/hold, directions such as above/below, and outcome side must agree), a `match_confidence` with reasons per pair, the price gap, the closest rejected pairs and why, and unmatched counts per venue. `match_confidence` is an ordinal score for ranking pairs, not a probability that two markets are the same event. Each side names its price basis, spread and last-trade time; a pair is flagged and listed after comparable ones when either side is not a two-sided quote midpoint or its spread is wider than 0.10 |+| `intel_prediction_settled` | Settled markets on both venues with the outcome, the YES price at fixed offsets before close, and a Brier score per venue and offset with sample size, distinct events, selection and exclusions. A venue without price history is not scored, and a price history served from expired cache is excluded. Reference times differ by venue (Kalshi `close_time`; Polymarket the earlier of `endDate` and `closedTime`), so the two scores are not a head-to-head comparison. Polymarket's price histories share the `polymarket` circuit breaker with `intel_prediction_markets`: three failed history calls pause every Polymarket read for the breaker's 300 s cooldown |### Elections (1)| Tool | Description |diff --git a/ROADMAP.md b/ROADMAP.mdindex 30b5c3b..16c5c50 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -578,7 +578,7 @@ dashboard.| 1 | Hostility timeline | Per country pair or country, daily counts of threat / sanction / force / criticism coverage plus tone; sortable by most covered, most hostile, biggest change | :red_circle: || 1 | Story breadth | News clusters carry a distinct-outlet count; a top-stories view ranks by how many outlets carry a story | :red_circle: || 1 | Liquidity and flows | Fed balance sheet, Treasury General Account, reverse repo and net liquidity (FRED keyless CSV), money supply (US M2, euro area M1/M2/M3, never summed), ECB, ICI fund flows and ETF net issuance, FINRA margin statistics, BLS series; amounts kept separate from flows | :red_circle: |-| 1 | Kalshi + cross-venue markets | Kalshi public market data next to Polymarket; same-event comparison with an explicit match confidence; settled markets scored against pre-settlement prices (Brier) | :white_check_mark: Unreleased: `intel_kalshi_markets`, `intel_prediction_compare`, `intel_prediction_settled` (`sources/kalshi.py`, `sources/prediction_cross.py`, `analysis/prediction_matching.py`), CLI and 2 collector sources. Kalshi endpoints measured 2026-10-17, all HTTP 200 without an account: `/events` (nested markets), `/series` (`include_volume`), `/markets?status=settled`, `/markets/candlesticks` (batch, capped at 10,000 candles per call), `/historical/cutoff`. The `/events` `category` parameter is ignored by the API, so categories resolve through `/series?category=`, whose filter is loose too (7 of the 869 series it returned for Economics were other categories), so series are matched exactly; an unknown category answers `{"series": null}` and is reported as a gap, not an outage. The exchange-wide settled listing is intraday sports (1,000 rows covered about 40 minutes; none open 24h), so settled samples default to the Economics category's top series. Polymarket Gamma caps a page at 100 rows. Matching is deliberately conservative: live 2026-10-17 it matched the Fed 25 bps hike/cut pairs for October and December and rejected 25 vs 50+ bps, 2026 vs 2027, and the Fed-hold pair ("no change" vs "Hike 0bps": a known false negative). Team and person aliases are not resolved, so most sports pairs stay unmatched. Kalshi requests are spaced 0.2 s apart in-process: the two collector sources scanning the same series at once drew HTTP 429, and at 0.1 s a 26-request category scan still drew one (none at 0.2 s in one live run). Settled samples are the most recently settled markets and cluster in time (one football match supplied 11 of 25 Polymarket markets in a live run), so a Brier score describes its sample, not a venue's skill. Every number a caller passes has a range stated in the input schema (at most 25 Kalshi series or pages per scan), so one call cannot fan out into unbounded upstream requests |+| 1 | Kalshi + cross-venue markets | Kalshi public market data next to Polymarket; same-event comparison with an explicit match confidence; settled markets scored against pre-settlement prices (Brier) | :white_check_mark: Unreleased: `intel_kalshi_markets`, `intel_prediction_compare`, `intel_prediction_settled` (`sources/kalshi.py`, `sources/prediction_cross.py`, `analysis/prediction_matching.py`), CLI and 2 collector sources. Kalshi endpoints measured 2026-10-17, all HTTP 200 without an account: `/events` (nested markets), `/series` (`include_volume`), `/markets?status=settled`, `/markets/candlesticks` (batch, capped at 10,000 candles per call), `/historical/cutoff`. The `/events` `category` parameter is ignored by the API, so categories resolve through `/series?category=`, whose filter is loose too (7 of the 869 series it returned for Economics were other categories), so series are matched exactly; an unknown category answers `{"series": null}` and is reported as a gap, not an outage. The exchange-wide settled listing is intraday sports (1,000 rows covered about 40 minutes; none open 24h), so settled samples default to the Economics category's top series. Polymarket Gamma caps a page at 100 rows. Matching is deliberately conservative: live 2026-10-17 it matched the Fed 25 bps hike/cut pairs for October and December and rejected 25 vs 50+ bps, 2026 vs 2027, and the Fed-hold pair ("no change" vs "Hike 0bps": a known false negative). Team and person aliases are not resolved, so most sports pairs stay unmatched. Kalshi requests are spaced 0.2 s apart in-process: the two collector sources scanning the same series at once drew HTTP 429, and at 0.1 s a 26-request category scan still drew one (none at 0.2 s in one live run). Settled samples are the most recently settled markets and cluster in time (one football match supplied 11 of 25 Polymarket markets in a live run), so a Brier score describes its sample, not a venue's skill. Every number a caller passes has a range stated in the input schema (at most 25 Kalshi series or pages per scan), so one call cannot fan out into unbounded upstream requests. Review round (2026-10-17): expired-cache serves are marked on every Kalshi read and on Polymarket's settled listing and histories, and a stale history is not scored; matching adds rate-action and direction gates, keeps signs and ordinals, reads a $ amount as an amount, and its candidate blocking is complete against a brute-force scan in tests; compare carries each side's price basis, spread and Kalshi last-trade time (public `/markets/trades`, HTTP 200 without an account, measured 2026-10-17) and ranks flagged pairs after comparable ones; Polymarket is scored against the earlier of endDate and closedTime (on 20 closed markets measured 2026-10-17, closedTime came 2.7 to 5.5 h after endDate for football and 164 h before it for one early resolution, and umaEndDate equalled closedTime in all 20, so no outcome-known time is published); Kalshi pacing applies only on a cache miss. The shared `polymarket` circuit breaker (three failed history calls pause all Polymarket reads for 300 s) is documented, not changed || 1 | News vs market reaction | Companies and countries named in story clusters mapped to tickers / country indices; same-day move against a benchmark | :red_circle: || 2 | Connections with timing offsets | Correlation between retained series over a shared sample, tested at leads and lags, with minimum sample size and false-discovery control; states that it does not prove causation | :red_circle: || 2 | Day timeline | What every retained source recorded for a given day, by observation date or collection date | :red_circle: |diff --git a/src/world_intel_mcp/analysis/prediction_matching.py b/src/world_intel_mcp/analysis/prediction_matching.pyindex 6654ce7..6c02b8f 100644--- a/src/world_intel_mcp/analysis/prediction_matching.py+++ b/src/world_intel_mcp/analysis/prediction_matching.py@@ -1,14 +1,20 @@"""Cross-venue prediction-market matching and forecast scoring.-Pure functions, no I/O. Used by ``tools/prediction_markets.py`` to put+Pure functions, no I/O. Used by ``sources/prediction_cross.py`` to putthe same event on Kalshi and Polymarket side by side and to scoresettled markets against their pre-settlement prices.Matching is deterministic: normalized title tokens, quantities, years,-end dates, negation and the outcome side must all agree before a pair-is scored, and a pair below ``DEFAULT_MIN_CONFIDENCE`` is not a match.-A wrong match is worse than no match, so every gate is a hard reject-and every reject carries its reason.+negation, rate actions (cut / raise / hold), directions (above /+below), end dates and the outcome side must all agree before a pair is+scored, and a pair below ``DEFAULT_MIN_CONFIDENCE`` is not a match. A+wrong match is worse than no match, so every gate is a hard reject and+every reject carries its reason.++``match_confidence`` (``confidence`` in ``score_pair``) is an ordinal+similarity score for ranking candidate pairs: title-word Dice overlap+times a date factor. It is not a calibrated probability that two+markets are the same event.Normalized market shape (both venues) consumed here::@@ -17,7 +23,8 @@ Normalized market shape (both venues) consumed here::"yes_side": str, # what YES pays out on ("" = the question itself)"outcomes": [str, str], # Polymarket labels; Kalshi ["Yes", "No"]"end_time": iso8601 | None,- "probability": float | None} # YES implied probability, 0..1+ "probability": float | None, # YES implied probability, 0..1+ "price_basis": str, "spread": float | None} # quote fields (optional)Gaps / not covered:- No synonym coverage beyond the small table below (month names, rate@@ -29,15 +36,32 @@ Gaps / not covered:- Resolution-rule equivalence is not checked: two markets can share atitle and still settle on different sources or times. The reasonslist says what was compared; it does not claim more.+- Ordinals written as words ("first", "second") are plain words, not+ quantities, and a number glued to a unit ("100mm") loses the unit.+- A fractional threshold worded strict on one venue and inclusive on+ the other ("above 4.5%" vs "4.5% or higher") is matched with a+ boundary flag; an integer one is not, because "more than 50" means+ "51 or more"."""from __future__ import annotations+import mathimport reimport unicodedatafrom datetime import datetime, timezoneDEFAULT_MIN_CONFIDENCE = 0.6+# Pairs whose title overlap could reach the lower of min_confidence and+# this floor are scored, so near misses include pairs just under a high+# threshold.+NEAR_MISS_FLOOR = 0.5+# A pair is ranked by its price gap only when both prices are two-sided+# quote midpoints whose spread is at most this wide (price units, 0..1).+MAX_COMPARABLE_SPREAD = 0.10+# Upstream titles longer than this are cut (the longest seen live on+# 2026-10-17 was a 313-character Kalshi market title).+MAX_TEXT_CHARS = 500# Date tolerance: the larger of a floor and a fraction of the horizon,# so a 2028 election may differ by weeks but a weekly market by days.@@ -61,10 +85,13 @@ _SYNONYMS = {"sept": "september", "oct": "october", "nov": "november", "dec": "december","cuts": "cut", "decrease": "cut", "decreases": "cut", "lower": "cut","lowers": "cut", "hike": "raise", "hikes": "raise", "increase": "raise",- "increases": "raise", "raises": "raise", "over": "above", "more": "above",- "exceed": "above", "exceeds": "above", "under": "below", "fewer": "below",+ "increases": "raise", "raises": "raise", "holds": "hold", "maintain": "hold",+ "maintains": "hold", "unchanged": "hold", "pause": "hold", "pauses": "hold",+ "over": "above", "more": "above", "exceed": "above", "exceeds": "above",+ "higher": "above", "greater": "above", "under": "below", "fewer": "below","less": "below", "wins": "win", "won": "win", "winner": "win",- "usa": "us", "u.s.": "us", "bp": "bps", "basis": "bps",+ # "U.S." tokenizes to "u.s" (edge dots are stripped).+ "usa": "us", "u.s": "us", "u.s.a": "us", "bp": "bps", "basis": "bps",}_MONTHS = frozenset(@@ -73,30 +100,48 @@ _MONTHS = frozenset()_NEGATIONS = frozenset({"not", "no", "never", "without"})_YES_NO = frozenset({"yes", "no"})+# Hard gates: two titles must name the same rate action and the same+# direction (after synonym folding), or the pair is rejected.+_ACTIONS = frozenset({"cut", "raise", "hold"})+_DIRECTIONS = {"above": "above", "below": "below", "atleast": "above", "atmost": "below", "ormore": "above"}+_SCALE_WORDS = {"thousand": 1e3, "million": 1e6, "billion": 1e9, "trillion": 1e12}+_MULTIPLIERS = {"": 1.0, "k": 1e3, "m": 1e6, "mn": 1e6, "b": 1e9, "bn": 1e9, "t": 1e12, "tn": 1e12}++_NUM_RE = re.compile(r"^(-?)\$?(\d+(?:\.\d+)?)(k|mn|m|bn|b|tn|t)?$")+_ORDINAL_RE = re.compile(r"^(\d+)(st|nd|rd|th)$")+# Ordinal | number (a leading minus only when it is not a hyphen inside+# a word or range; never starting inside a digit run, so "100mm" cannot+# leave a partial "10") | word.+_TOKEN_RE = re.compile(+ r"(?<![\d.,])\d+(?:st|nd|rd|th)(?![a-z0-9])"+ r"|(?:(?<![a-z0-9.,])-)?\$?(?<![\d.,])\d(?:[\d,]*\d)?(?:\.\d+)?(?:(?:k|mn|m|bn|b|tn|t)(?![a-z]))?"+ r"|[a-z][a-z.&']*"+)+_QUANTITY_RE = re.compile(r"^(>=|<=|>|<)?(.+)$")-_NUM_RE = re.compile(r"^\$?(\d+(?:\.\d+)?)([kmb]?)$")-_TOKEN_RE = re.compile(r"\$?\d[\d,]*(?:\.\d+)?[kmb]?(?![a-z])|[a-z][a-z.&']*")++def clip_text(value: object, limit: int = MAX_TEXT_CHARS) -> str:+ """Upstream text as a string of at most ``limit`` characters."""+ text = value if isinstance(value, str) else ("" if value is None else str(value))+ return text if len(text) <= limit else text[: limit - 3] + "..."# ---------------------------------------------------------------------------# Tokenization# ----------------------------------------------------------------------------def _canonical_number(raw: str) -> str | None:+def _canonical_number(raw: str, scale: float = 1.0) -> str | None:m = _NUM_RE.match(raw.replace(",", ""))if not m:return None- value = float(m.group(1)) * {"": 1, "k": 1e3, "m": 1e6, "b": 1e9}[m.group(2)]- return f"{value:g}" if value != int(value) else str(int(value))-+ value = float(m.group(2)) * _MULTIPLIERS[m.group(3) or ""] * scale+ if m.group(1):+ value = -value+ return f"{value:.12g}" if value != int(value) else str(int(value))-def tokenize(text: str) -> list[str]:- """Lowercase, fold synonyms, canonicalize numbers; stopwords kept.- ``"25bps"`` -> ``["25", "bps"]``; ``"$100k"`` -> ``["100000"]``;- ``"2.75%"`` -> ``["2.75"]``; ``"Fed's"`` -> ``["fed"]``.- """- text = (text or "").replace("’", "'").replace("≥", ">=").replace("≤", "<=")+def _prepare(text: str) -> str:+ text = (text or "").replace("’", "'").replace("≥", ">=").replace("≤", "<=").replace("−", "-")text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode().lower()# Comparators become words so a quantity keeps its direction:# ">25bps" and "25 bps" are different contracts.@@ -105,24 +150,66 @@ def tokenize(text: str) -> list[str]:text = re.sub(r"(\d)\s*\+", r"\1 ormore ", text)text = re.sub(r"\bat least\b", " atleast ", text)text = re.sub(r"\bat most\b", " atmost ", text)- text = re.sub(r"(\d)(bps|bp)\b", r"\1 \2", text)- out: list[str] = []- for raw in _TOKEN_RE.findall(text):- if raw[0].isdigit() or raw[0] == "$":- num = _canonical_number(raw)- if num is not None:- out.append(num)+ # "lower" alone is the rate verb (folded to "cut"); before "than" or+ # after "or" it is a comparator.+ text = re.sub(r"\blower\s+than\b", " below ", text)+ text = re.sub(r"\bor\s+lower\b", " or below ", text)+ # "No change" names the hold outcome; it is not a negation.+ text = re.sub(r"\bno\s+changes?\b", " hold ", text)+ return re.sub(r"(\d)(bps|bp)\b", r"\1 \2", text)+++def _scan(text: str) -> list[tuple[str, str]]:+ """``(token, kind)`` pairs; kind is word, number, money, year or ordinal.++ ``year`` is only the shape (four plain digits, 1900-2100); whether it+ is a year or an amount depends on what precedes it (text_features).+ """+ raws = _TOKEN_RE.findall(_prepare(text))+ out: list[tuple[str, str]] = []+ i = 0+ while i < len(raws):+ raw = raws[i]+ i += 1+ ordinal = _ORDINAL_RE.match(raw)+ if ordinal:+ out.append((f"{int(ordinal.group(1))}{ordinal.group(2)}", "ordinal"))+ continue+ if raw[0].isdigit() or raw[0] in "$-":+ scale = 1.0+ if i < len(raws) and raws[i] in _SCALE_WORDS and raw[-1].isdigit():+ scale = _SCALE_WORDS[raws[i]] # "$100 million" is "$100m"+ i += 1+ num = _canonical_number(raw, scale)+ if num is None:+ continue+ if "$" in raw:+ kind = "money"+ elif scale == 1.0 and raw.isdigit() and len(raw) == 4 and 1900 <= int(raw) <= 2100:+ kind = "year"+ else:+ kind = "number"+ out.append((num, kind))continueword = raw.strip(".'&")if word.endswith("'s"):word = word[:-2]word = word.replace("'", "")- if not word:- continue- out.append(_SYNONYMS.get(word, word))+ if word:+ out.append((_SYNONYMS.get(word, word), "word"))return out+def tokenize(text: str) -> list[str]:+ """Lowercase, fold synonyms, canonicalize numbers; stopwords kept.++ ``"25bps"`` -> ``["25", "bps"]``; ``"$100k"`` and ``"$100 thousand"``+ -> ``["100000"]``; ``"2.75%"`` -> ``["2.75"]``; ``"-0.5%"`` ->+ ``["-0.5"]``; ``"1st"`` -> ``["1st"]``; ``"Fed's"`` -> ``["fed"]``.+ """+ return [tok for tok, _ in _scan(text)]++_COMPARATOR_WORDS = frozenset({"above", "below", "atleast", "atmost", "ormore"})@@ -143,49 +230,64 @@ def _comparator(toks: list[str], i: int) -> str:return {"above": ">", "below": "<", "atleast": ">=", "atmost": "<="}.get(before, "")-def _is_year(tok: str) -> bool:- return tok.isdigit() and len(tok) == 4 and 1900 <= int(tok) <= 2100---def _is_number(tok: str) -> bool:- return bool(tok) and (tok[0].isdigit())+def _day_of_month(tok: str, kind: str) -> str | None:+ digits = tok[:-2] if kind == "ordinal" else tok+ if kind in ("number", "ordinal") and digits.isdigit() and 1 <= int(digits) <= 31:+ return str(int(digits))+ return Nonedef text_features(text: str) -> dict:"""Split a title into content words, quantities, years and flags.- A 1-31 number right after a month name is a day of month and goes to- ``days``, not ``quantities``: "Oct 28, 2026" must not block a pair- with "October 2026" on the number gate (the end-date gate covers it).+ A 1-31 number (or ordinal) right after a month name is a day of+ month and goes to ``days``, not ``quantities``: "Oct 28, 2026" must+ not block a pair with "October 2026" on the number gate (the+ end-date gate covers it). A four-digit 1900-2100 number is a year+ unless a dollar sign, a thousands comma or a comparator makes it an+ amount: "above $2,000" is the quantity ``>2000``. ``actions`` and+ ``directions`` are the rate verbs and above/below words the title+ uses, after synonym folding."""- toks = tokenize(text)+ scanned = _scan(text)+ toks = [tok for tok, _ in scanned]words: set[str] = set()quantities: set[str] = set()years: set[str] = set()days: set[str] = set()+ actions: set[str] = set()+ directions: set[str] = set()negated = False- for i, tok in enumerate(toks):- prev = toks[i - 1] if i > 0 else ""- if _is_number(tok):- if _is_year(tok):- years.add(tok)- elif prev in _MONTHS and tok.isdigit() and 1 <= int(tok) <= 31:- days.add(tok)- else:- quantities.add(_comparator(toks, i) + tok)- elif tok in _NEGATIONS:- negated = True- elif tok in _COMPARATOR_WORDS:- if tok in ("above", "below"):+ for i, (tok, kind) in enumerate(scanned):+ if kind == "word":+ if tok in _ACTIONS:+ actions.add(tok)+ if tok in _DIRECTIONS:+ directions.add(_DIRECTIONS[tok])+ if tok in _NEGATIONS:+ negated = True+ elif tok in _COMPARATOR_WORDS:+ if tok in ("above", "below"):+ words.add(tok)+ elif tok not in _STOPWORDS:words.add(tok)- elif tok not in _STOPWORDS:- words.add(tok)+ continue+ comparator = _comparator(toks, i)+ day = _day_of_month(tok, kind)+ if kind == "year" and not comparator:+ years.add(tok)+ elif i > 0 and toks[i - 1] in _MONTHS and day is not None:+ days.add(day)+ else:+ quantities.add(comparator + tok)return {"words": words,"quantities": quantities,"years": years,"days": days,"negated": negated,+ "actions": actions,+ "directions": directions,}@@ -205,16 +307,46 @@ def _parse_time(value: str | None) -> datetime | None:return dt-def _side_alignment(kalshi: dict, k_side: set[str], poly: dict) -> tuple[str | None, str]:+def _text(m: dict, *keys: str) -> str:+ return " ".join(s for s in (m.get(k) for k in keys) if isinstance(s, str) and s)+++def _market_features(m: dict, venue: str) -> dict:+ """Everything the gates read from one market, computed once.++ ``bag`` (question, event title and, on Kalshi, the YES side) feeds+ the overlap score, quantities, years and negation. Actions and+ directions come from the contract's own wording (question plus YES+ side), not the event title, which can list every alternative.+ """+ if venue == "kalshi":+ bag = text_features(_text(m, "question", "context", "yes_side"))+ gate = text_features(_text(m, "question", "yes_side"))+ else:+ bag = text_features(_text(m, "question", "context"))+ gate = text_features(_text(m, "question"))+ outcomes = [str(o) for o in (m.get("outcomes") or [])]+ return {+ "bag": bag,+ "actions": gate["actions"],+ "directions": gate["directions"],+ "question_words": text_features(_text(m, "question"))["words"],+ "side_words": text_features(_text(m, "yes_side"))["words"],+ "outcomes": outcomes,+ "labels": [set(tokenize(o)) for o in outcomes],+ "end": _parse_time(m.get("end_time")),+ }+++def _side_alignment(kf: dict, pf: dict) -> tuple[str | None, str]:"""Which Polymarket outcome the Kalshi YES side corresponds to.Returns ``("aligned" | "inverted" | None, reason)``. ``inverted``means the Kalshi YES pays out on Polymarket's second outcome, so thePolymarket probability is flipped before the gap is taken."""- outcomes = [str(o) for o in (poly.get("outcomes") or [])]- labels = [set(tokenize(o)) for o in outcomes]- poly_question = text_features(poly.get("question", ""))["words"]+ k_side = kf["side_words"]+ outcomes, labels, poly_question = pf["outcomes"], pf["labels"], pf["question_words"]if len(outcomes) == 2 and {o.lower() for o in outcomes} == _YES_NO:if k_side and not k_side <= poly_question:missing = sorted(k_side - poly_question)@@ -224,7 +356,7 @@ def _side_alignment(kalshi: dict, k_side: set[str], poly: dict) -> tuple[str | Nreturn "aligned", "both venues price YES on the question as worded"if len(outcomes) != 2:return None, f"Polymarket market has {len(outcomes)} outcomes, not a binary pair"- side = k_side or text_features(kalshi.get("question", ""))["words"]+ side = k_side or kf["question_words"]hits = [bool(side & (lab - _STOPWORDS)) for lab in labels]if hits == [True, False]:return "aligned", f"Kalshi YES side matches Polymarket outcome {outcomes[0]!r}"@@ -235,49 +367,72 @@ def _side_alignment(kalshi: dict, k_side: set[str], poly: dict) -> tuple[str | Nreturn None, f"Kalshi YES side {sorted(side)} matches neither Polymarket outcome {outcomes}"-def score_pair(kalshi: dict, poly: dict, now: datetime | None = None) -> dict:- """Score one Kalshi/Polymarket pair.+def _threshold_class(quantity: str) -> str:+ """A fractional threshold's direction and value, strictness dropped.- Returns ``{"confidence": float, "rejected": bool, "reasons": [...],- "side": "aligned" | "inverted" | None}``. A rejected pair has- confidence 0.0 and its first failing gate as the last reason.+ ">4.5" and ">=4.5" differ only when the outcome lands exactly on+ 4.5; ">50" and ">=50" differ by a whole unit, so integers keep it."""- now = now or datetime.now(timezone.utc)- k_text = " ".join(- s for s in (kalshi.get("question", ""), kalshi.get("context", ""), kalshi.get("yes_side", "")) if s+ comparator, number = _QUANTITY_RE.match(quantity).groups()+ if comparator and "." in number:+ return ("above" if comparator[0] == ">" else "below") + number+ return quantity+++def _boundary_only(k_quantities: set[str], p_quantities: set[str]) -> bool:+ return len(k_quantities) == len(p_quantities) and (+ {_threshold_class(q) for q in k_quantities} == {_threshold_class(q) for q in p_quantities})- kf = text_features(k_text)- pf = text_features(" ".join(s for s in (poly.get("question", ""), poly.get("context", "")) if s))- k_side_words = text_features(kalshi.get("yes_side", ""))["words"]+++def _score(kf: dict, pf: dict, now: datetime) -> dict:+ kb, pb = kf["bag"], pf["bag"]reasons: list[str] = []def reject(reason: str) -> dict:reasons.append(reason)- return {"confidence": 0.0, "rejected": True, "reasons": reasons, "side": None}+ return {"confidence": 0.0, "rejected": True, "reasons": reasons, "side": None, "boundary_differs": False}- shared = kf["words"] & pf["words"]- union = len(kf["words"]) + len(pf["words"])+ shared = kb["words"] & pb["words"]+ union = len(kb["words"]) + len(pb["words"])dice = (2 * len(shared) / union) if union else 0.0reasons.append(f"title word overlap {dice:.2f} (dice; {len(shared)} shared of "- f"{len(kf['words'])} Kalshi / {len(pf['words'])} Polymarket words)"+ f"{len(kb['words'])} Kalshi / {len(pb['words'])} Polymarket words)")- if kf["quantities"] != pf["quantities"]:- return reject(- f"quantities differ: Kalshi {sorted(kf['quantities'])} vs Polymarket {sorted(pf['quantities'])}"+ boundary = False+ if kb["quantities"] != pb["quantities"]:+ if not _boundary_only(kb["quantities"], pb["quantities"]):+ return reject(+ f"quantities differ: Kalshi {sorted(kb['quantities'])} vs Polymarket {sorted(pb['quantities'])}"+ )+ boundary = True+ reasons.append(+ f"quantities agree except at the boundary: Kalshi {sorted(kb['quantities'])} vs Polymarket "+ f"{sorted(pb['quantities'])} (the same unless the outcome lands exactly on the threshold)")- if kf["quantities"]:- reasons.append(f"quantities agree {sorted(kf['quantities'])}")+ elif kb["quantities"]:+ reasons.append(f"quantities agree {sorted(kb['quantities'])}")- if kf["years"] and pf["years"] and not (kf["years"] & pf["years"]):- return reject(f"years differ: Kalshi {sorted(kf['years'])} vs Polymarket {sorted(pf['years'])}")+ if kb["years"] and pb["years"] and not (kb["years"] & pb["years"]):+ return reject(f"years differ: Kalshi {sorted(kb['years'])} vs Polymarket {sorted(pb['years'])}")- if kf["negated"] != pf["negated"]:+ if kb["negated"] != pb["negated"]:return reject("negation differs (one title says not/no/never/without, the other does not)")- k_end, p_end = _parse_time(kalshi.get("end_time")), _parse_time(poly.get("end_time"))- date_factor = 1.0+ if kf["actions"] != pf["actions"]:+ return reject(f"actions differ: Kalshi {sorted(kf['actions'])} vs Polymarket {sorted(pf['actions'])}")+ if kf["actions"]:+ reasons.append(f"actions agree {sorted(kf['actions'])}")+ if kf["directions"] != pf["directions"]:+ return reject(+ f"directions differ: Kalshi {sorted(kf['directions'])} vs Polymarket {sorted(pf['directions'])}"+ )+ if kf["directions"]:+ reasons.append(f"directions agree {sorted(kf['directions'])}")++ k_end, p_end = kf["end"], pf["end"]if k_end is None or p_end is None:return reject("end date missing on one venue; cannot confirm the same event window")gap_days = abs((k_end - p_end).total_seconds()) / 86400@@ -288,26 +443,65 @@ def score_pair(kalshi: dict, poly: dict, now: datetime | None = None) -> dict:date_factor = 1.0 - 0.5 * (gap_days / tolerance)reasons.append(f"end dates {gap_days:.1f} days apart (tolerance {tolerance:.1f} days)")- side, side_reason = _side_alignment(kalshi, k_side_words, poly)+ side, side_reason = _side_alignment(kf, pf)if side is None:return reject(side_reason)reasons.append(side_reason)confidence = round(dice * date_factor, 3)- return {"confidence": confidence, "rejected": False, "reasons": reasons, "side": side}+ return {"confidence": confidence, "rejected": False, "reasons": reasons, "side": side, "boundary_differs": boundary}+++def score_pair(kalshi: dict, poly: dict, now: datetime | None = None) -> dict:+ """Score one Kalshi/Polymarket pair.++ Returns ``{"confidence": float, "rejected": bool, "reasons": [...],+ "side": "aligned" | "inverted" | None, "boundary_differs": bool}``.+ A rejected pair has confidence 0.0 and its first failing gate as the+ last reason. ``confidence`` is an ordinal score, not a probability.+ """+ now = now or datetime.now(timezone.utc)+ return _score(_market_features(kalshi, "kalshi"), _market_features(poly, "polymarket"), now)# ---------------------------------------------------------------------------# Matching# ----------------------------------------------------------------------------def _blocking_index(markets: list[dict]) -> tuple[dict[str, list[int]], int]:+def _candidate_pairs(k_feats: list[dict], p_feats: list[dict], min_dice: float) -> list[tuple[int, int]]:+ """Every pair whose title-word Dice can reach ``min_dice``.++ Prefix filtering: with both venues' words in one rarest-first order,+ each market keeps its first ``n - need + 1`` words, where ``need =+ ceil(min_dice * n / (2 - min_dice))``. Dice >= t means the overlap+ o satisfies o >= t * n / (2 - t) for either market's word count n+ (from 2o >= t * (n + m) and m >= o), and the first shared word sits+ within the first n - o + 1 words of each market, so both prefixes+ hold it. Pairs sharing no word are never candidates. (The bound and+ the prefix step were checked with z3 on 2026-10-17, the prefix step+ for up to 16 words; a test compares this with a brute-force scan.)+ """+ t = min(max(float(min_dice), 0.0), 1.0)+ df: dict[str, int] = {}+ for f in k_feats + p_feats:+ for w in f["bag"]["words"]:+ df[w] = df.get(w, 0) + 1++ def prefix(words: set[str]) -> list[str]:+ ordered = sorted(words, key=lambda w: (df[w], w))+ need = math.ceil(t * len(ordered) / (2 - t) - 1e-9) # rounding can only lengthen the prefix+ return ordered[: len(ordered) - max(need, 1) + 1]+index: dict[str, list[int]] = {}- for i, m in enumerate(markets):- words = text_features(" ".join((m.get("question", ""), m.get("context", ""))))["words"]- for w in words:- index.setdefault(w, []).append(i)- return index, len(markets)+ for pi, f in enumerate(p_feats):+ for w in prefix(f["bag"]["words"]):+ index.setdefault(w, []).append(pi)+ pairs: set[tuple[int, int]] = set()+ for ki, f in enumerate(k_feats):+ for w in prefix(f["bag"]["words"]):+ for pi in index.get(w, ()):+ pairs.add((ki, pi))+ return sorted(pairs)def match_markets(@@ -319,43 +513,33 @@ def match_markets() -> dict:"""One-to-one deterministic matching, greedy by confidence.- Candidate pairs share at least two title words that appear in fewer- than 20% of the Polymarket set (blocking keeps the pair count- tractable; a pair with fewer shared words could not reach the- threshold anyway). Returns matched pairs, near misses (the highest- similarity pairs that a gate or the threshold rejected) and counts.+ Every pair whose title-word overlap could reach the lower of+ ``min_confidence`` and ``NEAR_MISS_FLOOR`` is scored+ (``_candidate_pairs``), so no pair that would pass the threshold is+ skipped: the date factor only lowers a score. A pair sharing no+ title word is never scored. Returns matched pairs, near misses (the+ highest similarity pairs that a gate or the threshold rejected) and+ counts."""now = now or datetime.now(timezone.utc)- index, n_poly = _blocking_index(polymarket)- common_cut = max(5, int(0.2 * n_poly))+ k_feats = [_market_features(m, "kalshi") for m in kalshi]+ p_feats = [_market_features(m, "polymarket") for m in polymarket]+ # 0.001 under the floor: scores are rounded to 3 places, so a pair can+ # pass the threshold with an overlap up to 0.0005 below it.+ candidates = _candidate_pairs(k_feats, p_feats, min(min_confidence, NEAR_MISS_FLOOR) - 0.001)scored: list[tuple[float, int, int, dict]] = []near: list[tuple[float, int, int, dict]] = []- pairs_scored = 0- for ki, km in enumerate(kalshi):- words = text_features(- " ".join((km.get("question", ""), km.get("context", ""), km.get("yes_side", "")))- )["words"]- counts: dict[int, int] = {}- for w in words:- posting = index.get(w)- if not posting or len(posting) > common_cut:- continue- for pi in posting:- counts[pi] = counts.get(pi, 0) + 1- for pi, c in counts.items():- if c < 2:- continue- pairs_scored += 1- result = score_pair(km, polymarket[pi], now=now)- if not result["rejected"] and result["confidence"] >= min_confidence:- scored.append((result["confidence"], ki, pi, result))- else:- overlap = _overlap_of(result)- if not result["rejected"]:- result["reasons"].append(- f"confidence {result['confidence']:.3f} below threshold {min_confidence}"- )- near.append((overlap, ki, pi, result))+ for ki, pi in candidates:+ result = _score(k_feats[ki], p_feats[pi], now)+ if not result["rejected"] and result["confidence"] >= min_confidence:+ scored.append((result["confidence"], ki, pi, result))+ else:+ overlap = _overlap_of(result)+ if not result["rejected"]:+ result["reasons"].append(+ f"confidence {result['confidence']:.3f} below threshold {min_confidence}"+ )+ near.append((overlap, ki, pi, result))scored.sort(key=lambda t: (-t[0], t[1], t[2]))used_k: set[int] = set()@@ -381,7 +565,7 @@ def match_markets(return {"matched": matched,"near_misses": near_misses,- "pairs_scored": pairs_scored,+ "pairs_scored": len(candidates),"unmatched_kalshi": len(kalshi) - len(used_k),"unmatched_polymarket": len(polymarket) - len(used_p),"min_confidence": min_confidence,@@ -401,10 +585,30 @@ def _brief(m: dict) -> dict:"outcomes": m.get("outcomes"),"end_time": m.get("end_time"),"probability": m.get("probability"),+ "price_basis": m.get("price_basis"),+ "yes_bid": m.get("yes_bid"),+ "yes_ask": m.get("yes_ask"),+ "spread": m.get("spread"),+ "last_price": m.get("last_price"),+ "last_trade_time": m.get("last_trade_time"),"url": m.get("url"),}+def _quote_flags(venue: str, m: dict) -> list[str]:+ """Why one side's price is not a live two-sided quote ([] when it is)."""+ if m.get("probability") is None:+ return [] # no price: the gap is None and the pair sorts last anyway+ flags = []+ basis = m.get("price_basis")+ if basis != "bid_ask_midpoint":+ flags.append(f"{venue} price is not a two-sided quote midpoint (basis: {basis or 'not stated'})")+ spread = m.get("spread")+ if isinstance(spread, (int, float)) and spread > MAX_COMPARABLE_SPREAD:+ flags.append(f"{venue} bid/ask spread {spread:.2f} is wider than {MAX_COMPARABLE_SPREAD:.2f}")+ return flags++def _pair_record(km: dict, pm: dict, result: dict) -> dict:k_prob = km.get("probability")p_raw = pm.get("probability")@@ -412,6 +616,9 @@ def _pair_record(km: dict, pm: dict, result: dict) -> dict:if p_raw is not None:p_aligned = round(1.0 - p_raw, 4) if result["side"] == "inverted" else p_rawgap = round(k_prob - p_aligned, 4) if k_prob is not None and p_aligned is not None else None+ flags = _quote_flags("kalshi", km) + _quote_flags("polymarket", pm)+ if result.get("boundary_differs"):+ flags.append("thresholds differ at the boundary (strict on one venue, inclusive on the other)")return {"match_confidence": result["confidence"],"reasons": result["reasons"],@@ -421,6 +628,8 @@ def _pair_record(km: dict, pm: dict, result: dict) -> dict:"kalshi_yes_probability": k_prob,"polymarket_yes_probability": p_aligned,"price_gap": gap,+ "flags": flags,+ "comparable": gap is not None and not flags,}diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.pyindex b57d7c2..8c09b94 100644--- a/src/world_intel_mcp/cli.py+++ b/src/world_intel_mcp/cli.py@@ -987,11 +987,13 @@ def prediction_compare(return_print_data_gaps(data)+ comparable = data.get("comparable_count")console.print(f"Compared {data.get('kalshi_markets_compared', 0)} Kalshi / "f"{data.get('polymarket_markets_compared', 0)} Polymarket markets: "f"{data.get('matched_count', 0)} matched, unmatched Kalshi "f"{data.get('unmatched_kalshi')}, unmatched Polymarket {data.get('unmatched_polymarket')}"+ + ("" if comparable is None else f"; {comparable} comparable (both prices live two-sided quotes)"))pairs = data.get("matched", [])if not pairs:@@ -1003,12 +1005,19 @@ def prediction_compare(table = Table(title="Cross-venue Matches", box=box.SIMPLE_HEAVY)table.add_column("Kalshi", max_width=40)table.add_column("Polymarket", max_width=40)- table.add_column("Conf", justify="right")+ table.add_column("Score", justify="right")table.add_column("Kalshi YES", justify="right")table.add_column("Poly YES", justify="right")table.add_column("Gap", justify="right")+ table.add_column("Flags", max_width=40)+ flagged = Falsefor p in pairs:gap = p.get("price_gap")+ flags = list(p.get("flags") or [])+ flagged = flagged or bool(flags)+ traded = (p.get("kalshi") or {}).get("last_trade_time")+ if traded:+ flags.append(f"kalshi last trade {traded}")table.add_row( # wrapped, not sliced (see the kalshi table)_cell(p.get("kalshi", {}).get("question") or ""),_cell(p.get("polymarket", {}).get("question") or ""),@@ -1016,8 +1025,15 @@ def prediction_compare(_pct(p.get("kalshi_yes_probability")),_pct(p.get("polymarket_yes_probability")),"-" if gap is None else f"{gap * 100:+.1f}pp",+ _cell("; ".join(flags) or "-"),)console.print(table)+ console.print("Score: ordinal match score for ranking pairs, not a probability.")+ if flagged:+ console.print(+ "Flagged pairs are listed after comparable ones: a flagged gap is not a like-for-like "+ "difference of two live quotes on the same terms."+ )@main.command("prediction-settled")@@ -1055,24 +1071,24 @@ def prediction_settled(return_print_data_gaps(data)- table = Table(title="Settled-market Brier Scores", box=box.SIMPLE_HEAVY)- table.add_column("Venue")- table.add_column("Offset")- table.add_column("n", justify="right")- table.add_column("Events", justify="right")- table.add_column("Brier", justify="right")- table.add_column("YES rate", justify="right")- table.add_column("Excluded", no_wrap=True)+ # One table per venue: the samples are different markets with+ # different reference times, so their rows must not read as comparable.for venue, entry in (data.get("venues") or {}).items():if not entry.get("scores"):- reason = entry.get("error") or entry.get("not_scored_reason") or "not scored"- table.add_row(_cell(venue), "-", "-", "-", "not scored", "-", _cell(reason))+ reason = entry.get("error") or entry.get("not_scored_reason") or "no scores returned"+ console.print(f"{escape(venue)}: not scored ({escape(reason)})")continue+ table = Table(title=f"Brier scores, {escape(venue)} sample only", box=box.SIMPLE_HEAVY)+ table.add_column("Offset")+ table.add_column("n", justify="right")+ table.add_column("Events", justify="right")+ table.add_column("Brier", justify="right")+ table.add_column("YES rate", justify="right")+ table.add_column("Excluded", no_wrap=True)for label, sc in entry["scores"].items():brier = sc.get("brier")excluded = ", ".join(f"{k}: {v}" for k, v in (sc.get("excluded") or {}).items())table.add_row(- _cell(venue),_cell(label),str(sc.get("n", 0)),str(sc.get("distinct_events", 0)),@@ -1080,8 +1096,10 @@ def prediction_settled(_pct(sc.get("yes_rate")),_cell(excluded or "-"),)- console.print(table)- console.print(f"[dim]{escape(data.get('comparability', ''))}[/dim]")+ console.print(table)+ if entry.get("reference_time"):+ console.print(f"{escape(venue)} reference time: {escape(entry['reference_time'])}")+ console.print(escape(data.get("comparability", "")))# ---------------------------------------------------------------------------diff --git a/src/world_intel_mcp/sources/kalshi.py b/src/world_intel_mcp/sources/kalshi.pyindex 577cba0..24eb96e 100644--- a/src/world_intel_mcp/sources/kalshi.py+++ b/src/world_intel_mcp/sources/kalshi.py@@ -3,8 +3,9 @@Reads only the unauthenticated endpoints of Kalshi's trade API v2(``https://api.elections.kalshi.com/trade-api/v2``), verified live2026-10-17: ``/events`` (with nested markets), ``/series`` (with-``include_volume``), ``/markets`` (``status=settled``) and the batch-``/markets/candlesticks``. Nothing here places orders or needs keys.+``include_volume``), ``/markets`` (``status=settled``), the batch+``/markets/candlesticks`` and ``/markets/trades`` (last trade time).+Nothing here places orders or needs keys.Units, as the venue serves them: prices are strings in US dollars percontract that pays $1 on YES (``yes_bid_dollars="0.6300"``), so a price@@ -13,7 +14,10 @@ contract counts as strings (``volume_fp="3251.19"``).Every function returns a dict. An upstream failure is never an emptysuccess: it carries ``error`` and ``degraded: True``; a partial scan-lists what was not read under ``data_gaps``.+lists what was not read under ``data_gaps``. A response the fetcher+served from an expired cache entry after a failed live fetch (it marks+such dicts ``_stale``) is counted and its age reported, so old data+never reads as fresh.Gaps / not covered:- The open-events endpoint orders events by close time, furthest out@@ -30,22 +34,33 @@ Gaps / not covered:no series, ``Climate and Weather`` returns 444.- Combo (multivariate) markets are excluded from settled samples(``mve_filter=exclude``); they never appear in the events listing.+- Pacing is per process: the MCP server and the collector daemon each+ space their own requests, and two concurrent identical cache misses in+ one process are both sent (no request coalescing). A 429 gets the+ fetcher's generic retries (1 s, then 2 s); ``Retry-After`` is not read."""from __future__ import annotationsimport asyncioimport logging+import math+import reimport timefrom datetime import datetime, timezonefrom typing import Any+from urllib.parse import quote+from ..analysis.prediction_matching import clip_textfrom ..fetcher import Fetcherlogger = logging.getLogger("world-intel-mcp.sources.kalshi")_BASE = "https://api.elections.kalshi.com/trade-api/v2"_SOURCE = "kalshi"+# Last-trade lookups are supplementary: their own circuit-breaker key, so+# three failed lookups cannot open the breaker that guards market data.+_TRADES_SOURCE = "kalshi_trades"_PAGE_SIZE = 200# Caps on caller-chosen counts. A category scan costs one /series call# plus up to 5 /events pages (open) or 3 /markets pages (settled) per@@ -62,10 +77,15 @@ _CANDLE_BUDGET = 9000 # API refuses a batch above 10,000 candlesticks (measured# scanning the same series at once drew HTTP 429 (measured 2026-10-17:# about 12 requests in 0.3 s). At 0.1 s spacing a 26-request category# scan still drew one 429 on its 21st request, 2.0 s in; at 0.2 s the-# same scan drew none (26 requests in 5.0 s). Spacing comes before the-# fetcher's cache check, so a request repeated by a second caller is-# usually a cache hit.+# same scan drew none (26 requests in 5.0 s). Only a cache miss waits:+# _get answers a live cache entry before pacing._MIN_INTERVAL = 0.2+# Identifier shapes, from every series (15,187) and the open markets in+# the 2026-10-17 captures: series tickers are letters, digits and hyphens+# (at most 39 characters seen); market tickers add dots (at most 46).+# Anything else is not used to build a URL or a request.+_SERIES_RE = re.compile(r"[A-Za-z0-9-]{1,64}")+_TICKER_RE = re.compile(r"[A-Z0-9][A-Z0-9._-]{0,99}")_pace_state: dict[str, Any] = {"loop": None, "lock": None, "last": 0.0}@@ -102,6 +122,49 @@ def _num(value: Any) -> float | None:return None+def _finite(value: Any) -> float | None:+ """Like ``_num``, but NaN and infinities are None too (they are not+ valid JSON and no comparison with them means anything)."""+ number = _num(value)+ return number if number is not None and math.isfinite(number) else None+++def _volume(value: Any) -> float | None:+ """A contract count: absent means 0.0; unparseable, non-finite or+ negative means None (unreadable, counted by the caller)."""+ if value is None or value == "":+ return 0.0+ number = _finite(value)+ return number if number is not None and number >= 0 else None+++def valid_series(value: Any) -> bool:+ return isinstance(value, str) and _SERIES_RE.fullmatch(value) is not None+++def valid_ticker(value: Any) -> bool:+ return isinstance(value, str) and _TICKER_RE.fullmatch(value) is not None+++def _stale_age(data: dict) -> float | None:+ age = data.get("_stale_age_seconds")+ if isinstance(age, bool) or not isinstance(age, (int, float)) or not math.isfinite(age):+ return None+ return float(age)+++def max_stale_age(ages: list[float | None]) -> float | None:+ known = [a for a in ages if a is not None]+ return max(known) if known else None+++def stale_gap(what: str, ages: list[float | None]) -> str:+ """Data-gap text for responses the fetcher served from expired cache."""+ oldest = max_stale_age(ages)+ age = f", the oldest {oldest / 3600:.1f} h old" if oldest is not None else ""+ return f"{what}: {len(ages)} response(s) served from expired cache after a failed live fetch{age}"++def count_arg(value: Any, name: str, high: int) -> int:"""A caller's count clamped to ``[1, high]``.@@ -120,60 +183,88 @@ def implied_probability(market: dict) -> tuple[float | None, str]:"""YES implied probability and the basis it came from.Midpoint of a two-sided book when both quotes are live (bid > 0 and- ask < 1); otherwise the last trade; otherwise None ("no price").+ ask < 1); otherwise the last trade when it is a finite price in+ (0, 1]; otherwise None ("no price")."""- bid = _num(market.get("yes_bid_dollars"))- ask = _num(market.get("yes_ask_dollars"))- last = _num(market.get("last_price_dollars"))+ bid = _finite(market.get("yes_bid_dollars"))+ ask = _finite(market.get("yes_ask_dollars"))+ last = _finite(market.get("last_price_dollars"))if bid is not None and ask is not None and 0 < bid <= ask < 1:return round((bid + ask) / 2, 4), "bid_ask_midpoint"- if last is not None and last > 0:+ if last is not None and 0 < last <= 1:return round(last, 4), "last_trade"return None, "no_price"def normalize_market(market: dict, event: dict | None = None) -> dict:- """One Kalshi market in the cross-venue shape plus venue fields."""+ """One Kalshi market in the cross-venue shape plus venue fields.++ ``volume`` and ``volume_24h`` are None when the venue's value is+ unreadable (callers count such rows); ``spread`` is set only for a+ two-sided book. Kalshi's market listings carry no last-trade time+ (``last_trade_time`` is None here; see fetch_kalshi_last_trade_times).+ """event = event or {}prob, basis = implied_probability(market)event_ticker = market.get("event_ticker") or event.get("event_ticker") or ""series_ticker = event.get("series_ticker") or (event_ticker.split("-", 1)[0] if event_ticker else "")yes_side = market.get("yes_sub_title") or ""title = market.get("title") or ""+ bid = _finite(market.get("yes_bid_dollars"))+ ask = _finite(market.get("yes_ask_dollars"))+ two_sided = bid is not None and ask is not None and 0 < bid <= ask < 1return {"venue": "kalshi","id": market.get("ticker", ""),- "question": title,- "context": event.get("title", ""),- "yes_side": "" if yes_side.strip().lower() == title.strip().lower() else yes_side,+ "question": clip_text(title),+ "context": clip_text(event.get("title", "")),+ "yes_side": "" if yes_side.strip().lower() == title.strip().lower() else clip_text(yes_side),"outcomes": ["Yes", "No"],"end_time": market.get("expected_expiration_time") or market.get("close_time"),"close_time": market.get("close_time"),"probability": prob,"price_basis": basis,- "yes_bid": _num(market.get("yes_bid_dollars")),- "yes_ask": _num(market.get("yes_ask_dollars")),- "last_price": _num(market.get("last_price_dollars")),- "volume": _num(market.get("volume_fp")) or 0.0,- "volume_24h": _num(market.get("volume_24h_fp")) or 0.0,- "open_interest": _num(market.get("open_interest_fp")),+ "yes_bid": bid,+ "yes_ask": ask,+ "spread": round(ask - bid, 4) if two_sided else None,+ "last_price": _finite(market.get("last_price_dollars")),+ "last_trade_time": None,+ "volume": _volume(market.get("volume_fp")),+ "volume_24h": _volume(market.get("volume_24h_fp")),+ "open_interest": _finite(market.get("open_interest_fp")),"event_ticker": event_ticker,"series_ticker": series_ticker,"category": event.get("category"),"status": market.get("status"),- "url": f"https://kalshi.com/markets/{series_ticker.lower()}" if series_ticker else "",+ "url": (+ f"https://kalshi.com/markets/{quote(series_ticker.lower(), safe='')}"+ if valid_series(series_ticker) else ""+ ),}-async def _get(fetcher: Fetcher, path: str, params: dict, cache_key: str, ttl: int) -> Any:- await _pace()- return await fetcher.get_json(- f"{_BASE}{path}", source=_SOURCE, cache_key=cache_key, cache_ttl=ttl, params=params- )+async def _get(+ fetcher: Fetcher, path: str, params: dict, cache_key: str, ttl: int,+ stale: list[float | None] | None = None, source: str = _SOURCE,+) -> Any:+ """One Kalshi read. A live cache entry is answered without pacing; a+ miss waits its turn, then goes through the fetcher. When the fetcher+ falls back to an expired entry (it marks the dict ``_stale``), that+ entry's age in seconds (None if unknown) is appended to ``stale``."""+ data = fetcher.cache.get(cache_key)+ if data is None:+ await _pace()+ data = await fetcher.get_json(+ f"{_BASE}{path}", source=source, cache_key=cache_key, cache_ttl=ttl, params=params+ )+ if stale is not None and isinstance(data, dict) and data.get("_stale"):+ stale.append(_stale_age(data))+ return dataasync def _events_pages(- fetcher: Fetcher, params: dict, max_pages: int, key_prefix: str+ fetcher: Fetcher, params: dict, max_pages: int, key_prefix: str,+ stale: list[float | None] | None = None,) -> tuple[list[dict], int, bool, str | None]:"""Follow the events cursor. Returns (events, pages, exhaustive, error)."""events: list[dict] = []@@ -183,7 +274,7 @@ async def _events_pages(q = dict(params, limit=str(_PAGE_SIZE), with_nested_markets="true")if cursor:q["cursor"] = cursor- data = await _get(fetcher, "/events", q, f"{key_prefix}:{cursor or 'first'}", 300)+ data = await _get(fetcher, "/events", q, f"{key_prefix}:{cursor or 'first'}", 300, stale)if not isinstance(data, dict) or not isinstance(data.get("events"), list):return events, pages, False, (f"Kalshi /events page {pages + 1} unavailable (no live or cached data)"@@ -196,13 +287,16 @@ async def _events_pages(return events, pages, False, None-async def _top_series(fetcher: Fetcher, category: str, series_limit: int) -> tuple[list[dict], str | None]:+async def _top_series(+ fetcher: Fetcher, category: str, series_limit: int, stale: list[float | None] | None = None+) -> tuple[list[dict], str | None]:data = await _get(fetcher,"/series",{"category": category, "include_volume": "true"},f"kalshi:series:{category}",3600,+ stale,)rows = data.get("series") if isinstance(data, dict) else Noneif rows is None and isinstance(data, dict) and "series" in data:@@ -236,23 +330,27 @@ async def fetch_kalshi_open_markets(Scan modes: ``series`` reads that series' open events in full;``category`` reads the category's ``series_limit`` highest-volumeseries; neither reads the first ``pages`` pages of all open events.- ``pages`` and ``series_limit`` are clamped to 1..25.+ ``pages`` and ``series_limit`` are clamped to 1..25. ``stale`` is+ True when any response came from expired cache; ``scan`` then also+ carries ``stale_responses`` and ``stale_max_age_seconds``."""pages = count_arg(pages, "pages", MAX_PAGES)series_limit = count_arg(series_limit, "series_limit", MAX_SERIES)gaps: list[str] = []errors: list[str] = []events: list[dict] = []+ stale: list[float | None] = []scan: dict[str, Any]if series:events, n, exhaustive, err = await _events_pages(- fetcher, {"status": "open", "series_ticker": series}, MAX_PAGES, f"kalshi:events:series:{series}"+ fetcher, {"status": "open", "series_ticker": series}, MAX_PAGES,+ f"kalshi:events:series:{series}", stale,)scan = {"mode": "series", "series": series, "pages_fetched": n, "exhaustive": exhaustive}if err:errors.append(err)elif category:- top, err = await _top_series(fetcher, category, series_limit)+ top, err = await _top_series(fetcher, category, series_limit, stale)scan = {"mode": "category_top_series","category": category,@@ -267,7 +365,8 @@ async def fetch_kalshi_open_markets(failed = []for s in top:ev, _, _, e_err = await _events_pages(- fetcher, {"status": "open", "series_ticker": s["ticker"]}, 5, f"kalshi:events:series:{s['ticker']}"+ fetcher, {"status": "open", "series_ticker": s["ticker"]}, 5,+ f"kalshi:events:series:{s['ticker']}", stale,)if e_err:failed.append(s["ticker"])@@ -276,7 +375,7 @@ async def fetch_kalshi_open_markets(errors.append(f"open events unavailable for series {failed}")else:events, n, exhaustive, err = await _events_pages(- fetcher, {"status": "open"}, pages, "kalshi:events:open"+ fetcher, {"status": "open"}, pages, "kalshi:events:open", stale)scan = {"mode": "open_events_pages",@@ -301,12 +400,17 @@ async def fetch_kalshi_open_markets(if isinstance(m, dict) and m.get("status") in (None, "active", "open"):markets.append(normalize_market(m, ev))scan["events_scanned"] = len(events)+ if stale:+ scan["stale_responses"] = len(stale)+ scan["stale_max_age_seconds"] = max_stale_age(stale)+ gaps.append(stale_gap("Kalshi open markets", stale))return {"markets": markets,"scan": scan,"errors": errors,"data_gaps": errors + gaps,"nothing_read": not events and bool(errors),+ "stale": bool(stale),}@@ -323,9 +427,12 @@ async def fetch_kalshi_markets(Returns ``{"markets": [...], "count", "source": "kalshi", "scan","units", "data_gaps", "timestamp"}``; on a total outage also- ``error`` and ``degraded: True`` (never an empty success). ``limit``- is clamped to 1..500; a count that is not a whole number is an- ``error`` answered before any request.+ ``error`` and ``degraded: True`` (never an empty success). Data+ served from expired cache sets ``degraded`` and ``stale``. Rows whose+ volume is unreadable are left out and counted in+ ``volume_unreadable_excluded``. ``limit`` is clamped to 1..500; a+ count that is not a whole number is an ``error`` answered before any+ request."""try:limit = count_arg(limit, "limit", MAX_RESULTS)@@ -336,26 +443,34 @@ async def fetch_kalshi_markets(raw = await fetch_kalshi_open_markets(fetcher, category=category, series=series, pages=pages, series_limit=series_limit)- markets = raw["markets"]+ readable = [m for m in raw["markets"] if m["volume"] is not None and m["volume_24h"] is not None]+ unreadable = len(raw["markets"]) - len(readable)+ markets = readableuntraded = sum(1 for m in markets if m["volume"] <= 0)if not include_untraded:markets = [m for m in markets if m["volume"] > 0]markets.sort(key=lambda m: (m["volume_24h"], m["volume"]), reverse=True)+ gaps = list(raw["data_gaps"])+ if unreadable:+ gaps.append(f"{unreadable} market(s) left out: volume unreadable (not a finite contract count)")out: dict[str, Any] = {"markets": markets[:limit],"count": min(len(markets), limit),"markets_considered": len(markets),"untraded_excluded": 0 if include_untraded else untraded,+ "volume_unreadable_excluded": unreadable,"source": "kalshi","scan": raw["scan"],"units": UNITS,- "data_gaps": raw["data_gaps"],+ "data_gaps": gaps,"timestamp": _utc_now_iso(),}- if raw["errors"]:+ if raw["errors"] or raw["stale"]:out["degraded"] = True- if raw["nothing_read"]:- out["error"] = raw["errors"][0]+ if raw["stale"]:+ out["stale"] = True+ if raw["errors"] and raw["nothing_read"]:+ out["error"] = raw["errors"][0]return out@@ -373,11 +488,13 @@ def _ts(value: str | None) -> int | None:def _settled_record(m: dict, min_volume: float, min_open_hours: float) -> tuple[dict | None, str]:+ """A settled row as a sample record, or why it is skipped. An+ unreadable volume counts as below the floor ("volume")."""result = (m.get("result") or "").lower()- volume = _num(m.get("volume_fp")) or 0.0+ volume = _volume(m.get("volume_fp"))if result not in ("yes", "no"):return None, "result"- if volume < min_volume:+ if volume is None or volume < min_volume:return None, "volume"ref = _ts(m.get("close_time"))if ref is None:@@ -388,8 +505,8 @@ def _settled_record(m: dict, min_volume: float, min_open_hours: float) -> tuple[return {"venue": "kalshi","id": m.get("ticker", ""),- "question": m.get("title", ""),- "yes_side": m.get("yes_sub_title") or "",+ "question": clip_text(m.get("title", "")),+ "yes_side": clip_text(m.get("yes_sub_title") or ""),"event": m.get("event_ticker") or "","outcome": 1 if result == "yes" else 0,"result": result,@@ -425,22 +542,28 @@ async def fetch_kalshi_settled((measured 2026-10-17: 1,000 rows spanned about 40 minutes and nonewas open 24h), which is why callers scoring at day-scale offsetspass a category or series. ``pages`` and ``series_limit`` are- clamped to 1..25, ``limit`` to 1..100.+ clamped to 1..25, ``limit`` to 1..100. A row whose ticker is not a+ Kalshi market ticker is skipped and counted in+ ``invalid_ticker_skipped`` (tickers build the candlestick request).+ Listing pages served from expired cache are counted in+ ``stale_responses`` and described in ``stale_gap`` (None when fresh)."""limit = count_arg(limit, "limit", MAX_SETTLED)pages = count_arg(pages, "pages", MAX_PAGES)series_limit = count_arg(series_limit, "series_limit", MAX_SERIES)candidates: list[dict] = []skipped = {"result": 0, "volume": 0, "too_short": 0}+ invalid_ticker = 0seen = 0fetched = 0errors: list[str] = []gaps: list[str] = []+ stale: list[float | None] = []scope: list[str | None]if series:scope = [series]elif category:- top, err = await _top_series(fetcher, category, series_limit)+ top, err = await _top_series(fetcher, category, series_limit, stale)if err:errors.append(err)elif not top:@@ -459,7 +582,7 @@ async def fetch_kalshi_settled(if cursor:params["cursor"] = cursordata = await _get(- fetcher, "/markets", params, f"kalshi:settled:{tick or 'all'}:{cursor or 'first'}", 900+ fetcher, "/markets", params, f"kalshi:settled:{tick or 'all'}:{cursor or 'first'}", 900, stale)if not isinstance(data, dict) or not isinstance(data.get("markets"), list):errors.append(f"Kalshi settled markets unavailable for {tick or 'the exchange listing'}")@@ -469,6 +592,9 @@ async def fetch_kalshi_settled(if not isinstance(m, dict):continueseen += 1+ if not valid_ticker(m.get("ticker")):+ invalid_ticker += 1+ continuerec, why = _settled_record(m, min_volume, min_open_hours)if rec is None:skipped[why] += 1@@ -485,7 +611,11 @@ async def fetch_kalshi_settled("listing_rows_read": seen,"skipped": skipped,"open_too_briefly_skipped": skipped["too_short"],+ "invalid_ticker_skipped": invalid_ticker,"pages_fetched": fetched,+ "stale_responses": len(stale),+ "stale_max_age_seconds": max_stale_age(stale),+ "stale_gap": stale_gap("Kalshi settled listing", stale) if stale else None,"error": errors[0] if errors and not candidates else None,"errors": errors,"data_gaps": gaps,@@ -497,6 +627,8 @@ async def fetch_kalshi_price_history(markets: list[dict],window_start_hours: float,window_end_hours: float,+ *,+ stale: dict[str, float | None] | None = None,) -> tuple[dict[str, list[tuple[int, float]]], list[str]]:"""Hourly last-trade prices for each market over a window before close.@@ -508,11 +640,15 @@ async def fetch_kalshi_price_history(no trade carry no price and are skipped.Returns (``{ticker: [(end_period_ts, price)]}``, errors). A ticker- absent from the dict had no readable history.+ absent from the dict had no readable history. A batch the fetcher+ served from expired cache is still parsed, named in ``errors``, and+ each of its tickers is recorded in ``stale`` (ticker -> age in+ seconds) when the caller passes a dict."""history: dict[str, list[tuple[int, float]]] = {}errors: list[str] = []batch: list[tuple[dict, int, int]] = []+ stale_markets: list[tuple[str, float | None]] = []async def flush() -> None:nonlocal batch@@ -521,16 +657,20 @@ async def fetch_kalshi_price_history(start = min(s for _, s, _ in batch)end = max(e for _, _, e in batch)tickers = ",".join(m["id"] for m, _, _ in batch)+ ages: list[float | None] = []data = await _get(fetcher,"/markets/candlesticks",{"market_tickers": tickers, "start_ts": str(start), "end_ts": str(end), "period_interval": "60"},f"kalshi:candles:{tickers}:{start}:{end}",21600,+ ages,)if not isinstance(data, dict) or not isinstance(data.get("markets"), list):errors.append(f"candlesticks unavailable for {len(batch)} market(s)")else:+ if ages:+ stale_markets.extend((m["id"], ages[0]) for m, _, _ in batch)for entry in data["markets"]:if not isinstance(entry, dict):continue@@ -562,4 +702,57 @@ async def fetch_kalshi_price_history(await flush()batch.append((m, start, end))await flush()+ if stale_markets:+ oldest = max_stale_age([a for _, a in stale_markets])+ age = f", the oldest {oldest / 3600:.1f} h old" if oldest is not None else ""+ errors.append(+ f"candlesticks for {len(stale_markets)} market(s) served from expired cache "+ f"after a failed live fetch{age}"+ )+ if stale is not None:+ stale.update(stale_markets)return history, errors+++async def fetch_kalshi_last_trade_times(+ fetcher: Fetcher, tickers: list[str]+) -> tuple[dict[str, str | None], list[str]]:+ """When each market last traded, from the public ``/markets/trades``+ endpoint (``limit=1``). The market listings carry no trade time+ (measured 2026-10-17), so a price whose basis is the last trade has+ no age without this lookup.++ Returns (``{ticker: created_time or None}``, gaps): None means the+ venue returned no trade; a ticker missing from the dict could not be+ looked up or its trade time was unreadable (named in the gaps, never+ guessed).+ """+ times: dict[str, str | None] = {}+ failed = 0+ stale: list[float | None] = []+ for ticker in tickers:+ if not valid_ticker(ticker):+ failed += 1+ continue+ data = await _get(+ fetcher, "/markets/trades", {"ticker": ticker, "limit": "1"},+ f"kalshi:trades:last:{ticker}", 300, stale, _TRADES_SOURCE,+ )+ trades = data.get("trades") if isinstance(data, dict) else None+ if not isinstance(trades, list):+ failed += 1+ continue+ if not trades:+ times[ticker] = None+ continue+ created = trades[0].get("created_time") if isinstance(trades[0], dict) else None+ if not isinstance(created, str) or _ts(created) is None:+ failed += 1+ continue+ times[ticker] = created+ gaps: list[str] = []+ if failed:+ gaps.append(f"Kalshi last-trade time unavailable for {failed} market(s)")+ if stale:+ gaps.append(stale_gap("Kalshi last-trade times", stale))+ return times, gapsdiff --git a/src/world_intel_mcp/sources/prediction.py b/src/world_intel_mcp/sources/prediction.pyindex e38dc15..8bde54b 100644--- a/src/world_intel_mcp/sources/prediction.py+++ b/src/world_intel_mcp/sources/prediction.py@@ -15,15 +15,26 @@ Gaps / not covered:``_stale`` marker; a stale serve is detected through the circuitbreaker's per-source stale counter, which concurrent calls for thesame source share, so ``stale`` may also be set by a neighbour's- stale serve (over-reporting, never under-reporting).+ stale serve (over-reporting, never under-reporting). CLOB price+ histories are dicts and carry the inline marker.+- Gamma and the CLOB share the ``polymarket`` circuit breaker and its+ 1 s request floor: three failed price-history calls open the breaker+ for every Polymarket read (including ``intel_prediction_markets``) for+ its 300 s cooldown, and scoring ``limit`` settled markets makes up to+ ``limit`` sequential CLOB calls (100 markets: over 100 s).- Polymarket units: prices are USDC per share paying 1 USDC (directlya probability); volumes are USDC notional.+- Gamma publishes no last-trade time; ``last_trade_time`` is None."""import jsonimport logging+import math+import refrom datetime import datetime, timezone+from urllib.parse import quote+from ..analysis.prediction_matching import clip_textfrom ..fetcher import Fetcherlogger = logging.getLogger("world-intel-mcp.sources.prediction")@@ -36,6 +47,9 @@ _GAMMA_MARKETS_URL = "https://gamma-api.polymarket.com/markets"_CLOB_PRICES_HISTORY_URL = "https://clob.polymarket.com/prices-history"_GAMMA_PAGE_MAX = 100 # Gamma returns at most 100 rows per page (measured 2026-10-17)MAX_OPEN_MARKETS = 2000 # fetch_polymarket_open: at most 20 Gamma pages per call+# Every sampled market and event slug (2026-10-17 captures) is lowercase+# letters, digits and hyphens; anything else never builds a URL.+_SLUG_RE = re.compile(r"[a-z0-9-]{1,200}")UNITS = {"price": "Polymarket prices are USDC per share paying 1 USDC (0.63 = 63% implied probability)",@@ -56,19 +70,46 @@ def _parse_outcome_prices(raw: str | None) -> float | None:``outcomePrices`` is a JSON-encoded list like ``"[0.85, 0.15]"``where the first element represents the YES probability.- Returns None if the value is missing or unparseable.+ Returns None if the value is missing, unparseable, or not a finite+ price from 0 to 1."""if raw is None:return Nonetry:prices = json.loads(raw)if isinstance(prices, list) and len(prices) > 0:- return float(prices[0])+ return _price(prices[0])except (json.JSONDecodeError, ValueError, TypeError, IndexError):logger.debug("Failed to parse outcomePrices: %r", raw)return None+def _price(value) -> float | None:+ """A price as a finite float from 0 to 1, else None."""+ number = _float_or_none(value)+ if number is None or not math.isfinite(number) or not 0 <= number <= 1:+ return None+ return number+++def _volume(value) -> float | None:+ """A notional volume: absent means 0.0; unparseable, non-finite or+ negative means None (unreadable)."""+ if value is None or value == "":+ return 0.0+ number = _float_or_none(value)+ if number is None or not math.isfinite(number) or number < 0:+ return None+ return number+++def event_url(slug) -> str:+ """polymarket.com event URL for a well-formed slug, else ""."""+ if not isinstance(slug, str) or _SLUG_RE.fullmatch(slug) is None:+ return ""+ return f"https://polymarket.com/event/{quote(slug, safe='-')}"++def _classify_sentiment(yes_probability: float) -> str:"""Classify a YES probability into a human-readable sentiment label."""if yes_probability > 0.85:@@ -175,13 +216,15 @@ async def fetch_prediction_markets(fetcher: Fetcher, limit: int = 20) -> dict:}markets: list[dict] = []+ unpriced = 0for item in data:if not isinstance(item, dict):continueyes_probability = _parse_outcome_prices(item.get("outcomePrices"))if yes_probability is None:- # Skip markets with unparseable outcome data+ # Skip markets with unparseable outcome data (counted below)+ unpriced += 1continuevolume_24h = _safe_float(item.get("volume24hr"))@@ -190,14 +233,14 @@ async def fetch_prediction_markets(fetcher: Fetcher, limit: int = 20) -> dict:slug = item.get("slug", "")markets.append({- "question": item.get("question", ""),+ "question": clip_text(item.get("question", "")),"yes_probability": round(yes_probability, 4),"sentiment": _classify_sentiment(yes_probability),"volume_24h": volume_24h,"total_volume": total_volume,"liquidity": liquidity,"category": item.get("category", ""),- "url": f"https://polymarket.com/event/{slug}" if slug else "",+ "url": event_url(slug),})# Ensure descending sort by 24h volume (API should already return@@ -210,9 +253,14 @@ async def fetch_prediction_markets(fetcher: Fetcher, limit: int = 20) -> dict:"source": "polymarket","timestamp": _utc_now_iso(),}+ gaps = []if stale:result["stale"] = True- result["data_gaps"] = ["served from expired cache after a failed live fetch"]+ gaps.append("served from expired cache after a failed live fetch")+ if unpriced:+ gaps.append(f"{unpriced} market(s) left out: outcome price missing, unreadable or outside 0..1")+ if gaps:+ result["data_gaps"] = gapsreturn result@@ -224,15 +272,18 @@ def normalize_gamma_market(item: dict) -> dict | None:"""One Gamma market in the cross-venue shape; None if not binary.Probability is the first outcome's: midpoint of bestBid/bestAsk when- both are live, else Gamma's ``outcomePrices[0]``.+ both are live, else Gamma's ``outcomePrices[0]``. Prices outside 0..1+ or non-finite count as absent; ``volume`` is None when unreadable;+ ``spread`` is set only for a two-sided book."""- outcomes = [str(o) for o in _json_list(item.get("outcomes"))]- prices = [_float_or_none(p) for p in _json_list(item.get("outcomePrices"))]+ outcomes = [clip_text(o, 100) for o in _json_list(item.get("outcomes"))]+ prices = [_price(p) for p in _json_list(item.get("outcomePrices"))]if len(outcomes) != 2 or len(prices) != 2:return None- bid = _float_or_none(item.get("bestBid"))- ask = _float_or_none(item.get("bestAsk"))- if bid is not None and ask is not None and 0 < bid <= ask < 1:+ bid = _price(item.get("bestBid"))+ ask = _price(item.get("bestAsk"))+ two_sided = bid is not None and ask is not None and 0 < bid <= ask < 1+ if two_sided:prob, basis = round((bid + ask) / 2, 4), "bid_ask_midpoint"elif prices[0] is not None:prob, basis = round(prices[0], 4), "gamma_outcome_price"@@ -245,8 +296,8 @@ def normalize_gamma_market(item: dict) -> dict | None:return {"venue": "polymarket","id": str(item.get("id") or item.get("conditionId") or slug),- "question": item.get("question", "") or "",- "context": event.get("title", "") if event.get("title") != item.get("question") else "",+ "question": clip_text(item.get("question", "") or ""),+ "context": clip_text(event.get("title", "")) if event.get("title") != item.get("question") else "","yes_side": "","outcomes": outcomes,"outcome_prices": prices,@@ -254,12 +305,17 @@ def normalize_gamma_market(item: dict) -> dict | None:"closed_time": item.get("closedTime"),"probability": prob,"price_basis": basis,- "volume": _safe_float(item.get("volumeNum") if item.get("volumeNum") is not None else item.get("volume")),- "volume_24h": _safe_float(item.get("volume24hr")),+ "yes_bid": bid,+ "yes_ask": ask,+ "spread": round(ask - bid, 4) if two_sided else None,+ "last_price": _price(item.get("lastTradePrice")),+ "last_trade_time": None,+ "volume": _volume(item.get("volumeNum") if item.get("volumeNum") is not None else item.get("volume")),+ "volume_24h": _volume(item.get("volume24hr")),"token_ids": tokens,"event_id": str(event.get("id") or ""),"resolution_status": item.get("umaResolutionStatus"),- "url": f"https://polymarket.com/event/{slug}" if slug else "",+ "url": event_url(slug),}@@ -337,10 +393,24 @@ async def fetch_polymarket_settled(Selection: Gamma closed markets ordered by ``closedTime`` descendingwith ``volume_num_min``; kept when UMA status is ``resolved``, the- final outcome prices are exactly one 1 and one 0, and the market- opened (``startDate``) at least ``min_open_hours`` before it closed.- The first outcome is the YES side for scoring.+ final outcome prices are exactly one 1 and one 0, the volume is+ readable and at least ``min_volume`` (checked here too, counted in+ ``volume_skipped``), and the market opened (``startDate``) at least+ ``min_open_hours`` before its reference time. The first outcome is+ the YES side for scoring.++ Reference time: the earlier of ``endDate`` (the scheduled end; for a+ game, its start) and ``closedTime`` (when the market closed, which+ comes after resolution: measured 2026-10-17 on 20 closed markets,+ 2.7 to 5.5 h after ``endDate`` for football, the same time for+ 5-minute crypto markets, and up to 164 h before ``endDate`` for a+ market that resolved early). Gamma publishes no time at which the+ outcome became known (``umaEndDate`` equalled ``closedTime`` in every+ measured row), so an early resolution can still put an offset point+ after the outcome was known. A listing served from expired cache+ sets ``stale``."""+ stale_before = _stale_serves(fetcher, "polymarket")data = await fetcher.get_json(_GAMMA_MARKETS_URL,source="polymarket",@@ -351,6 +421,7 @@ async def fetch_polymarket_settled("order": "closedTime", "ascending": "false", "volume_num_min": str(min_volume),},)+ stale = _stale_serves(fetcher, "polymarket") > stale_beforeif not isinstance(data, list):return {"markets": [],@@ -359,6 +430,7 @@ async def fetch_polymarket_settled(}kept: list[dict] = []too_short = 0+ volume_skipped = 0for item in data:if not isinstance(item, dict):continue@@ -367,9 +439,19 @@ async def fetch_polymarket_settled(continueif sorted(p for p in m["outcome_prices"] if p is not None) != [0.0, 1.0]:continue- ref = _closed_ts(m["closed_time"])- if ref is None:+ closed = _closed_ts(m["closed_time"])+ if closed is None:+ continue+ if m["volume"] is None or m["volume"] < min_volume:+ volume_skipped += 1continue+ scheduled = _closed_ts(m["end_time"])+ if scheduled is None:+ ref, reference = closed, "closedTime (no endDate published)"+ elif scheduled < closed:+ ref, reference = scheduled, "endDate (scheduled end; the market closed later, after resolution)"+ else:+ ref, reference = closed, "closedTime (closed at or before its scheduled endDate)"opened = _closed_ts(item.get("startDate"))if min_open_hours and (opened is None or ref - opened < min_open_hours * 3600):too_short += 1@@ -385,26 +467,34 @@ async def fetch_polymarket_settled("volume": m["volume"],"token_id": m["token_ids"][0],"reference_ts": ref,- "reference": "closedTime (market closed after resolution)",+ "reference": reference,"settled_at": m["closed_time"],})if len(kept) >= limit:break- return {+ out = {"markets": kept,"listing_rows_read": len(data),"open_too_briefly_skipped": too_short,+ "volume_skipped": volume_skipped,"error": None,}+ if stale:+ out["stale"] = True+ out["data_gaps"] = ["closed-markets listing served from expired cache after a failed live fetch"]+ return outasync def fetch_polymarket_price_history(- fetcher: Fetcher, token_id: str, start_ts: int, end_ts: int+ fetcher: Fetcher, token_id: str, start_ts: int, end_ts: int,+ *, stale: list[float | None] | None = None,) -> list[tuple[int, float]] | None:"""CLOB price history for one outcome token; None when unavailable.Hourly fidelity. An empty list means the endpoint answered with nopoints in the window, which differs from None (the call failed).+ When the fetcher served an expired cache entry (inline ``_stale``),+ its age in seconds (None if unknown) is appended to ``stale``."""data = await fetcher.get_json(_CLOB_PRICES_HISTORY_URL,@@ -415,6 +505,10 @@ async def fetch_polymarket_price_history()if not isinstance(data, dict) or not isinstance(data.get("history"), list):return None+ if stale is not None and data.get("_stale"):+ age = data.get("_stale_age_seconds")+ stale.append(float(age) if isinstance(age, (int, float)) and not isinstance(age, bool)+ and math.isfinite(age) else None)points: list[tuple[int, float]] = []for row in data["history"]:if isinstance(row, dict) and isinstance(row.get("t"), int):diff --git a/src/world_intel_mcp/sources/prediction_cross.py b/src/world_intel_mcp/sources/prediction_cross.pyindex 4643da0..a373195 100644--- a/src/world_intel_mcp/sources/prediction_cross.py+++ b/src/world_intel_mcp/sources/prediction_cross.py@@ -10,17 +10,29 @@ markets".Gaps / not covered:- The two venues' settled samples are different markets, so theirBrier scores are not a head-to-head comparison; the response says so.-- Kalshi reference time is ``close_time`` (trading end, which can be- early when the outcome is known); Polymarket's is ``closedTime``- (after UMA resolution, often hours after the event). Prices inside- that last window already know the answer, which is why offsets- default to 24h and 168h, not minutes.+- Reference times differ by venue (stated in the response's+ ``comparability``). Kalshi's is ``close_time``, when trading actually+ ended (measured 2026-10-17 on 40 settled sports markets: 2.2 to 5.2 h+ before the expected expiration, settled 1.5 to 6.1 minutes later).+ Polymarket's is the earlier of ``endDate`` and ``closedTime`` (closed+ after resolution); Gamma publishes no time at which the outcome became+ known, so an early resolution can still put an offset point after it.+ Offsets default to 24h and 168h, not minutes, for that reason.+- A Kalshi market whose outcome was known well before a ``close_time``+ that did not move can lose its offset price to the staleness limit+ and drop out of the sample (not measured).- Price history comes from venue endpoints whose retention was notmeasured beyond the recent markets probed on 2026-10-17.- Samples are the most recently settled markets, so they cluster intime. Measured 2026-10-17 17:05 UTC: one football match supplied 11 of25 Polymarket markets (3 event ids), and two CPI releases supplied all24 Kalshi markets scored at 24h.+- Price histories served from expired cache are excluded, not scored,+ although a settled market's past window cannot change; the exclusion+ is the conservative reading of "never score old data as current".+- Polymarket scoring shares the ``polymarket`` circuit breaker and 1 s+ floor with Gamma (see sources/prediction.py): ``limit=100`` makes up+ to 100 sequential CLOB calls."""from __future__ import annotations@@ -32,6 +44,7 @@ from typing import Anyfrom ..analysis.prediction_matching import (DEFAULT_MIN_CONFIDENCE,+ MAX_COMPARABLE_SPREAD,brier_score,match_markets,price_at_offset,@@ -43,15 +56,31 @@ logger = logging.getLogger("world-intel-mcp.sources.prediction_cross")_MATCH_METHOD = ("Deterministic: titles lowercased with a small synonym table (month names, "- "cut/raise verbs, above/below); quantities (non-year numbers) must be equal sets; "- "years must intersect when both titles state one; negation must agree; end dates "- "within max(3 days, 15% of the horizon); the Kalshi YES side must be named in the "- "Polymarket question or match exactly one Polymarket outcome. "- "match_confidence = title word overlap (Dice) x date factor (1.0 same day, 0.5 at "- "the tolerance edge). One-to-one, greedy by confidence."+ "cut/raise/hold verbs, above/below); quantities must be equal sets (a four-digit "+ "number is a year unless a $ sign, a thousands comma or a comparator makes it an "+ "amount; signs and ordinals are kept), except that a fractional threshold strict on "+ "one venue and inclusive on the other is accepted with a flag; years must intersect "+ "when both titles state one; negation, rate actions (cut, raise, hold) and directions "+ "(above, below) must agree; end dates within max(3 days, 15% of the horizon); the "+ "Kalshi YES side must be named in the Polymarket question or match exactly one "+ "Polymarket outcome. match_confidence = title word overlap (Dice) x date factor "+ "(1.0 same day, 0.5 at the tolerance edge): an ordinal score for ranking candidate "+ "pairs, not a probability that two markets are the same event. One-to-one, greedy "+ "by confidence."+)++_RANKING = (+ "Pairs with comparable: true (both prices two-sided quote midpoints, spreads at most "+ f"{MAX_COMPARABLE_SPREAD:.2f}, no boundary flag) come first, largest absolute price gap "+ "first; flagged pairs follow, ranked the same way among themselves, because a gap "+ "taken from a last trade, a listed outcome price, a wide book or thresholds that "+ "differ at the boundary is not a like-for-like difference of live prices.")MAX_PAIRS = 500+# Matched pairs whose Kalshi price is a last trade get that trade's time+# looked up (one /markets/trades request each), for the first this many.+MAX_TRADE_LOOKUPS = 10MAX_OFFSETS = 10# A price window spans at most 8760 + 720 hours, so one market's hourly# candles stay under the candlestick endpoint's 10,000 cap.@@ -85,11 +114,12 @@ def _number_arg(value: Any, name: str, low: float, high: float) -> Any:def _offsets_arg(value: Any) -> list[float]:- """Positive offsets in hours, sorted and de-duplicated (default 24, 168).+ """Positive offsets in hours, sorted and de-duplicated.- Non-positive values are ignored; a list with none left, more than- MAX_OFFSETS values, or a value that is not a finite number of hours- up to MAX_OFFSET_HOURS raises ValueError.+ None or an empty list means the defaults (24, 168). More than+ MAX_OFFSETS values, a value that is not a finite number of hours up+ to MAX_OFFSET_HOURS, or a value of 0 or below raises ValueError: a+ bad offset is refused, never silently dropped."""raw = value or [24, 168]if not isinstance(raw, (list, tuple)):@@ -99,10 +129,12 @@ def _offsets_arg(value: Any) -> list[float]:for o in raw:if not _is_number(o) or o > MAX_OFFSET_HOURS:raise ValueError(f"offsets_hours values must be numbers of hours up to {MAX_OFFSET_HOURS} (got {o!r})")- offsets = sorted({float(o) for o in raw if o > 0})- if not offsets:- raise ValueError("offsets_hours must contain at least one positive number of hours")- return offsets+ if not any(o > 0 for o in raw):+ raise ValueError(f"offsets_hours must contain at least one positive number of hours (got {list(raw)!r})")+ for o in raw:+ if o <= 0:+ raise ValueError(f"offsets_hours values must be above 0 hours (got {o!r})")+ return sorted({float(o) for o in raw})def _arg_error(message: str) -> dict:@@ -121,13 +153,16 @@ async def fetch_prediction_compare() -> dict:"""The same events on Kalshi and Polymarket, side by side.- Returns matched pairs (largest absolute price gap first), the+ Returns matched pairs (comparable pairs first, each group by largest+ absolute price gap; see ``ranking`` in the response), thehighest-similarity rejected pairs with their reasons, and unmatchedcounts per venue. Below ``min_confidence`` a pair is not a match.- Counts are clamped (kalshi_pages and series_limit 1..25,- polymarket_limit 1..2000, limit 1..500); a count that is not a whole- number, or a min_confidence outside 0..1, is an ``error`` answered- before any request.+ Each side carries its price basis, quotes, spread and last-trade+ time where the venue publishes one. Data served from expired cache+ on either venue sets ``degraded``. Counts are clamped (kalshi_pages+ and series_limit 1..25, polymarket_limit 1..2000, limit 1..500); a+ count that is not a whole number, or a min_confidence outside 0..1,+ is an ``error`` answered before any request."""try:kalshi_pages = kalshi.count_arg(kalshi_pages, "kalshi_pages", kalshi.MAX_PAGES)@@ -161,6 +196,12 @@ async def fetch_prediction_compare("min_confidence": min_confidence,"method": _MATCH_METHOD,"price_gap": "kalshi YES probability minus polymarket probability of the same side",+ "price_basis": (+ "per side: bid_ask_midpoint (two-sided book), last_trade (Kalshi's last trade; its time is "+ "looked up for the first matched pairs), gamma_outcome_price (Polymarket's listed outcome "+ "price; Gamma publishes no last-trade time) or no_price"+ ),+ "ranking": _RANKING,"units": {"kalshi": kalshi.UNITS, "polymarket": prediction.UNITS},"timestamp": _utc_now_iso(),}@@ -185,26 +226,42 @@ async def fetch_prediction_compare(result = match_markets(k_markets, p_markets, min_confidence=min_confidence)matched = result["matched"]- matched.sort(key=lambda r: (r["price_gap"] is None, -abs(r["price_gap"] or 0.0), -r["match_confidence"]))+ matched.sort(key=lambda r: (+ r["price_gap"] is None, not r["comparable"], -abs(r["price_gap"] or 0.0), -r["match_confidence"],+ ))+ shown = matched[:limit]+ lookups = [p for p in shown if p["kalshi"].get("price_basis") == "last_trade"][:MAX_TRADE_LOOKUPS]+ if lookups:+ times, trade_gaps = await kalshi.fetch_kalshi_last_trade_times(fetcher, [p["kalshi"]["id"] for p in lookups])+ for p in lookups:+ p["kalshi"]["last_trade_time"] = times.get(p["kalshi"]["id"])+ # Supplementary: a failed lookup leaves the time null and is named+ # here; the comparison itself is complete, so it is not degraded.+ gaps.extend(f"kalshi: {g}" for g in trade_gaps)out.update({- "matched": matched[:limit],+ "matched": shown,"matched_count": len(matched),+ "comparable_count": sum(1 for p in matched if p["comparable"]),"near_misses": result["near_misses"],"pairs_scored": result["pairs_scored"],"unmatched_kalshi": result["unmatched_kalshi"],"unmatched_polymarket": result["unmatched_polymarket"],"data_gaps": gaps,})- if k_raw["errors"] or p_raw.get("error") or p_raw.get("stale"):+ if k_raw["errors"] or k_raw.get("stale") or p_raw.get("error") or p_raw.get("stale"):out["degraded"] = Truereturn out+_STALE_HISTORY = "price history served from expired cache"++def _score_venue(markets: list[dict],histories: dict[str, list[tuple[int, float]] | None],offsets: list[float],max_staleness_hours: float,+ stale_ids: set[str] = frozenset(),) -> tuple[dict, list[dict]]:scores: dict[str, Any] = {}sample: list[dict] = []@@ -216,8 +273,9 @@ def _score_venue(excluded: dict[str, int] = {}for m in markets:hist = histories.get(m["id"])- if hist is None:- excluded["price history unavailable"] = excluded.get("price history unavailable", 0) + 1+ if hist is None or m["id"] in stale_ids:+ key = "price history unavailable" if hist is None else _STALE_HISTORY+ excluded[key] = excluded.get(key, 0) + 1per_market_prices[m["id"]][label] = Nonecontinueprice, reason = price_at_offset(hist, m["reference_ts"], off, max_staleness_hours)@@ -251,6 +309,7 @@ def _score_venue("result": m["result"],"volume": m["volume"],"settled_at": m["settled_at"],+ "reference": m.get("reference"),"price_before_reference": per_market_prices[m["id"]],})return scores, sample@@ -274,11 +333,13 @@ async def fetch_prediction_settled(reference time (the last price inside ``max_staleness_hours`` up tothat point), and a Brier score per offset over the markets that hadone. A venue whose price history could not be read is not scored.- ``limit`` is clamped to 1..100 and ``kalshi_series_limit`` to 1..25;- more than 10 offsets, an offset above 8760 hours, a staleness limit- outside 0..720 hours, a volume floor outside 0..10**12 or a value- that is not a finite number is an ``error`` answered before any- request.+ A price history served from expired cache is excluded (counted per+ offset); a listing served from expired cache is still scored and+ marked. ``limit`` is clamped to 1..100 and ``kalshi_series_limit``+ to 1..25; more than 10 offsets, an offset of 0 or below or above+ 8760 hours, a staleness limit outside 0..720 hours, a volume floor+ outside 0..10**12 or a value that is not a finite number is an+ ``error`` answered before any request."""try:offsets = _offsets_arg(offsets_hours)@@ -310,25 +371,34 @@ async def fetch_prediction_settled()else:k_scope = "the exchange-wide settled listing (intraday sports dominate it)"+ k_selection = (+ f"most recently settled Kalshi markets (combos excluded) from {k_scope}, with result yes/no, "+ f"lifetime volume >= {kalshi_min_volume:g} contracts and open >= {window_end:g}h "+ f"before close; first {limit} kept from {k['listing_rows_read']} listing rows read "+ f"({k['open_too_briefly_skipped']} skipped as open too briefly)"+ )+ if k.get("stale_responses"):+ k_selection += f"; {k['stale_responses']} listing response(s) served from expired cache"k_entry: dict[str, Any] = {- "selection": (- f"most recently settled Kalshi markets (combos excluded) from {k_scope}, with result yes/no, "- f"lifetime volume >= {kalshi_min_volume:g} contracts and open >= {window_end:g}h "- f"before close; first {limit} kept from {k['listing_rows_read']} listing rows read "- f"({k['open_too_briefly_skipped']} skipped as open too briefly)"- ),- "reference_time": "close_time (trading end)",+ "selection": k_selection,+ "reference_time": "close_time (when trading ended; the actual close when a market closes early)","price_source": "batch /markets/candlesticks, hourly, price.close_dollars (last trade in the hour)","settled_markets": len(k["markets"]),}+ listing_gaps = [k["stale_gap"]] if k.get("stale_gap") else []if k["error"] and not k["markets"]:k_entry.update({"error": k["error"], "scored": False, "scores": None, "sample": []})+ k_entry["history_errors"] = listing_gapselse:- hist, h_errors = await kalshi.fetch_kalshi_price_history(fetcher, k["markets"], window_start, window_end)- histories = {m["id"]: hist.get(m["id"]) for m in k["markets"]}- k_entry.update(- _venue_result(k["markets"], histories, offsets, max_staleness_hours, h_errors + k["errors"], None)+ stale_candles: dict[str, float | None] = {}+ hist, h_errors = await kalshi.fetch_kalshi_price_history(+ fetcher, k["markets"], window_start, window_end, stale=stale_candles)+ histories = {m["id"]: hist.get(m["id"]) for m in k["markets"]}+ k_entry.update(_venue_result(+ k["markets"], histories, offsets, max_staleness_hours,+ h_errors + k["errors"] + listing_gaps, None, set(stale_candles),+ ))if k.get("data_gaps") and not k["markets"]:k_entry["not_scored_reason"] = "; ".join(k["data_gaps"])venues["kalshi"] = k_entry@@ -337,36 +407,60 @@ async def fetch_prediction_settled(p = await prediction.fetch_polymarket_settled(fetcher, limit=limit, min_volume=polymarket_min_volume, min_open_hours=window_end)+ p_selection = (+ f"most recently closed Polymarket binary markets with volume >= "+ f"{polymarket_min_volume:g} USDC, UMA status resolved, final prices exactly 1/0, "+ f"open >= {window_end:g}h before the reference time; first {limit} kept from "+ f"{p['listing_rows_read']} listing rows read "+ f"({p.get('open_too_briefly_skipped', 0)} skipped as open too briefly"+ f"{', %d below the volume floor or unreadable' % p['volume_skipped'] if p.get('volume_skipped') else ''}); "+ "first outcome is the YES side"+ )+ if p.get("stale"):+ p_selection += "; the listing was served from expired cache"p_entry: dict[str, Any] = {- "selection": (- f"most recently closed Polymarket binary markets with volume >= "- f"{polymarket_min_volume:g} USDC, UMA status resolved, final prices exactly 1/0, "- f"open >= {window_end:g}h before close; first {limit} kept from "- f"{p['listing_rows_read']} listing rows read "- f"({p.get('open_too_briefly_skipped', 0)} skipped as open too briefly); "- "first outcome is the YES side"+ "selection": p_selection,+ "reference_time": (+ "the earlier of endDate (scheduled end; a game's start) and closedTime (closed after "+ "resolution); each sample entry names which"),- "reference_time": "closedTime (market closed after resolution)","price_source": "CLOB /prices-history, hourly fidelity, first outcome token","settled_markets": len(p["markets"]),}+ p_listing_gaps = list(p.get("data_gaps") or [])if p["error"]:p_entry.update({"error": p["error"], "scored": False, "scores": None, "sample": []})else:histories = {}failed = 0+ stale_ids: set[str] = set()+ stale_ages: list[float | None] = []for m in p["markets"]:+ ages: list[float | None] = []pts = await prediction.fetch_polymarket_price_history(fetcher,m["token_id"],m["reference_ts"] - int(window_start * 3600),m["reference_ts"] - int(window_end * 3600),+ stale=ages,)if pts is None:failed += 1+ elif ages:+ stale_ids.add(m["id"])+ stale_ages.extend(ages)histories[m["id"]] = ptsh_errors = [f"price history unavailable for {failed} market(s)"] if failed else []- p_entry.update(_venue_result(p["markets"], histories, offsets, max_staleness_hours, h_errors, None))+ if stale_ids:+ oldest = kalshi.max_stale_age(stale_ages)+ age = f", the oldest {oldest / 3600:.1f} h old" if oldest is not None else ""+ h_errors.append(+ f"price history for {len(stale_ids)} market(s) served from expired cache after a "+ f"failed live fetch{age}; not scored"+ )+ p_entry.update(_venue_result(+ p["markets"], histories, offsets, max_staleness_hours, h_errors + p_listing_gaps, None, stale_ids,+ ))venues["polymarket"] = p_entrygaps = []@@ -389,7 +483,15 @@ async def fetch_prediction_settled("event ids behind them, and one real-world event can span several ids ""(Polymarket lists a match's result, halftime and totals markets as separate ""events). A strike ladder's far strikes trade near 0 or 1 and pull a Brier "- "score down."+ "score down. Reference times differ by venue: Kalshi counts back from "+ "close_time, when trading actually ended (measured on 40 settled sports "+ "markets: 2.2 to 5.2 h before the expected expiration, settled 1.5 to 6.1 "+ "minutes later); Polymarket from the earlier of endDate (scheduled end; a "+ "game's start) and closedTime (closed after resolution), and Gamma publishes "+ "no time at which the outcome became known, so an early resolution can put an "+ "offset point after it. Each offset scores only the markets with a price "+ "inside the staleness limit at that offset, so samples differ by offset: "+ "compare n per offset."),"brier": "mean of (price - outcome)^2 with outcome 1 for YES; 0 is perfect, always 0.5 scores 0.25","data_gaps": gaps,@@ -407,19 +509,26 @@ def _venue_result(max_staleness_hours: float,history_errors: list[str],listing_error: str | None,+ stale_ids: set[str] = frozenset(),) -> dict:entry: dict[str, Any] = {"history_errors": history_errors}if listing_error:entry["history_errors"] = history_errors + [listing_error]- if markets and all(histories.get(m["id"]) is None for m in markets):- entry.update({- "scored": False,- "not_scored_reason": "price history unavailable for every market in the sample",- "scores": None,- "sample": [],- })+ unusable = [m for m in markets if histories.get(m["id"]) is None or m["id"] in stale_ids]+ if markets and len(unusable) == len(markets):+ stale = sum(1 for m in unusable if histories.get(m["id"]) is not None)+ if not stale:+ reason = "price history unavailable for every market in the sample"+ elif stale == len(markets):+ reason = "price history served from expired cache for every market in the sample"+ else:+ reason = (+ "price history unavailable or served from expired cache for every market "+ f"in the sample ({stale} from expired cache)"+ )+ entry.update({"scored": False, "not_scored_reason": reason, "scores": None, "sample": []})return entry- scores, sample = _score_venue(markets, histories, offsets, max_staleness_hours)+ scores, sample = _score_venue(markets, histories, offsets, max_staleness_hours, stale_ids)entry.update({"scored": bool(markets), "scores": scores, "sample": sample})if not markets:entry["not_scored_reason"] = "no settled markets passed the selection"diff --git a/src/world_intel_mcp/tests/test_cli_prediction_review.py b/src/world_intel_mcp/tests/test_cli_prediction_review.pynew file mode 100644index 0000000..5b7a147--- /dev/null+++ b/src/world_intel_mcp/tests/test_cli_prediction_review.py@@ -0,0 +1,97 @@+"""CLI tests for the review round (2026-10-17): ``prediction-settled``+prints one Brier table per venue with its reference time, and+``prediction-compare`` shows each pair's flags, the Kalshi last-trade+time and what the score is.++Fetch functions are replaced with fakes returning the documented shapes+(pinned against respx-mocked upstreams in test_prediction_cross_review.py).++Gaps / not covered: terminal widths below 200 columns.+"""++import pytest++from world_intel_mcp import cli+from world_intel_mcp.tests.test_cli_prediction_markets import COMPARE_PAYLOAD, _fake, _invoke++LAST_TRADE = "2026-10-17T17:43:15.314853Z"++[email protected](autouse=True)+def _cli_isolation(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "cli-cache.db"))+ monkeypatch.setenv("COLUMNS", "200")+ monkeypatch.setattr(cli, "_fetcher", None)+++def _scores(brier: float, n: int) -> dict:+ return {"24h": {"n": n, "distinct_events": n, "brier": brier, "yes_rate": 0.5, "excluded": {}}}+++SETTLED_BOTH = {+ "venues": {+ "kalshi": {"scored": True, "scores": _scores(0.065, 2),+ "reference_time": "close_time (when trading ended; the actual close when a market closes early)"},+ "polymarket": {"scored": True, "scores": _scores(0.125, 2),+ "reference_time": "the earlier of endDate (scheduled end; a game's start) and closedTime"},+ },+ "comparability": "Reference times differ by venue.",+ "data_gaps": [],+}+++def test_prediction_settled_prints_one_table_per_venue(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(cli.prediction_cross, "fetch_prediction_settled", _fake(SETTLED_BOTH))+ out = _invoke("prediction-settled").output+ kalshi_at = out.index("Brier scores, kalshi sample only")+ polymarket_at = out.index("Brier scores, polymarket sample only")+ assert kalshi_at < out.index("0.0650") < polymarket_at < out.index("0.1250")+ assert "kalshi reference time: close_time (when trading ended" in out+ assert "polymarket reference time: the earlier of endDate" in out+ assert "Reference times differ by venue." in out+++def test_prediction_settled_unscored_venue_prints_no_table(monkeypatch: pytest.MonkeyPatch) -> None:+ payload = dict(SETTLED_BOTH, venues={+ "kalshi": SETTLED_BOTH["venues"]["kalshi"],+ "polymarket": {"scored": False, "scores": None,+ "not_scored_reason": "price history served from expired cache for every market in the sample"},+ })+ monkeypatch.setattr(cli.prediction_cross, "fetch_prediction_settled", _fake(payload))+ out = _invoke("prediction-settled").output+ assert "Brier scores, polymarket sample only" not in out+ assert "polymarket: not scored (price history served from expired cache for every market in the sample)" in out+++def _pair(kalshi_id: str, gap: float, flags: list, last_trade: str | None) -> dict:+ base = COMPARE_PAYLOAD["matched"][0]+ return dict(+ base, price_gap=gap, flags=flags, comparable=not flags,+ kalshi=dict(base["kalshi"], id=kalshi_id, last_trade_time=last_trade),+ )+++def test_prediction_compare_shows_flags_last_trade_and_score_meaning(monkeypatch: pytest.MonkeyPatch) -> None:+ payload = dict(+ COMPARE_PAYLOAD,+ matched=[+ _pair("H25", 0.0, [], None),+ _pair("C25", 0.0065, ["kalshi price is not a two-sided quote midpoint (basis: last_trade)"], LAST_TRADE),+ ],+ matched_count=2, comparable_count=1,+ )+ monkeypatch.setattr(cli.prediction_cross, "fetch_prediction_compare", _fake(payload))+ out = _invoke("prediction-compare").output+ assert "2 matched" in out and "; 1 comparable (both prices live two-sided quotes)" in out+ assert "Flags" in out and "Score" in out+ assert "last_trade" in out and LAST_TRADE in out+ assert "Score: ordinal match score for ranking pairs, not a probability." in out+ assert "Flagged pairs are listed after comparable ones" in out+++def test_prediction_compare_without_flags_prints_no_flag_note(monkeypatch: pytest.MonkeyPatch) -> None:+ payload = dict(COMPARE_PAYLOAD, matched=[_pair("H25", 0.0, [], None)], comparable_count=1)+ monkeypatch.setattr(cli.prediction_cross, "fetch_prediction_compare", _fake(payload))+ out = _invoke("prediction-compare").output+ assert "Flagged pairs are listed" not in out+ assert "Score: ordinal match score for ranking pairs, not a probability." in outdiff --git a/src/world_intel_mcp/tests/test_prediction_cross_review.py b/src/world_intel_mcp/tests/test_prediction_cross_review.pynew file mode 100644index 0000000..c22e2bf--- /dev/null+++ b/src/world_intel_mcp/tests/test_prediction_cross_review.py@@ -0,0 +1,289 @@+"""Cross-venue compare and settled scoring: expired-cache marking, price+basis and ranking, reference times and offset checks (review round,+2026-10-17).++Same fixtures as test_prediction_cross.py. respx keeps one route per+pattern, and a later ``.mock()`` on the same pattern replaces the+earlier response, so each test sets up the shared venues first and+then overrides the one endpoint it fails.++Gaps / not covered: a real outage on either venue; ordering of the live+trades endpoint (the lookup asks for one trade and does not depend on+it).+"""++import asyncio as asyncio_mod+from datetime import datetime, timezone++import httpx+import pytest+import respx++from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.sources.prediction_cross import fetch_prediction_compare, fetch_prediction_settled+from world_intel_mcp.tests.test_prediction_cross import (+ CLOB,+ GAMMA,+ K_REF,+ KALSHI_CANDLES,+ P1_REF,+ P2_REF,+ POLY_CLOSED,+ POLY_OPEN,+ _mock_settled_venues,+)+from world_intel_mcp.tests.test_sources_kalshi import EVENTS, FED_MARKETS, SETTLED_ROWS, _event+from world_intel_mcp.tests.test_sources_kalshi_stale import TEN_DAYS, TRADES, expire++STALE_SUFFIX = "served from expired cache after a failed live fetch, the oldest 240.0 h old"+LAST_TRADE = "2026-10-17T17:43:15.314853Z" # live shape and value, KXFEDDECISION-26OCT-C25++[email protected](autouse=True)+def _no_sleep(monkeypatch: pytest.MonkeyPatch) -> None:+ async def _sleep(*args, **kwargs) -> None:+ return None++ monkeypatch.setattr(asyncio_mod, "sleep", _sleep)+++def _fed_events(status: int = 200) -> None:+ respx.get(url__regex=EVENTS).mock(+ return_value=httpx.Response(status, json={"events": [_event(FED_MARKETS)], "cursor": ""})+ )+++def _trades(status: int = 200):+ return respx.get(url__regex=TRADES).mock(return_value=httpx.Response(status, json={"trades": [+ {"created_time": LAST_TRADE, "yes_price_dollars": "0.0100", "count_fp": "935.00"},+ ], "cursor": ""}))+++# ---------------------------------------------------------------------------+# intel_prediction_compare+# ---------------------------------------------------------------------------++async def test_compare_with_kalshi_from_expired_cache_is_degraded_and_says_so(fetcher: Fetcher) -> None:+ expire(fetcher, "kalshi:events:series:KXFEDDECISION:first", {"events": [_event(FED_MARKETS)], "cursor": ""})+ _fed_events(500)+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=POLY_OPEN))+ _trades()++ out = await fetch_prediction_compare(fetcher, series="KXFEDDECISION")++ assert out["matched_count"] == 2 and "error" not in out # still compared, and marked+ assert out["degraded"] is True+ assert out["kalshi_scan"]["stale_responses"] == 1+ assert TEN_DAYS <= out["kalshi_scan"]["stale_max_age_seconds"] < TEN_DAYS + 60+ assert f"kalshi: Kalshi open markets: 1 response(s) {STALE_SUFFIX}" in out["data_gaps"]+++async def test_compare_with_polymarket_from_expired_cache_is_degraded(fetcher: Fetcher) -> None:+ _fed_events()+ expire(fetcher, "prediction:polymarket:open:5:0", POLY_OPEN)+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(500))+ _trades()++ out = await fetch_prediction_compare(fetcher, series="KXFEDDECISION", polymarket_limit=5)++ assert out["matched_count"] == 2 and "error" not in out+ assert out["degraded"] is True+ assert "polymarket: served from expired cache after a failed live fetch" in out["data_gaps"]+++async def test_compare_ranks_comparable_pairs_before_flagged_ones(fetcher: Fetcher) -> None:+ """C25's Kalshi price is a last trade on a one-sided book (bid 0): its+ 0.0065 gap is not a like-for-like difference, so the live H25 pair+ (both sides two-sided, spread 0.01) ranks first despite a 0 gap."""+ _fed_events()+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=POLY_OPEN))+ trades = _trades()++ out = await fetch_prediction_compare(fetcher, series="KXFEDDECISION")++ h25, c25 = out["matched"]+ assert (h25["kalshi"]["id"], c25["kalshi"]["id"]) == ("KXFEDDECISION-26OCT-H25", "KXFEDDECISION-26OCT-C25")+ assert h25["comparable"] is True and h25["flags"] == []+ assert (h25["kalshi"]["price_basis"], h25["kalshi"]["spread"]) == ("bid_ask_midpoint", 0.01)+ assert (h25["polymarket"]["price_basis"], h25["polymarket"]["spread"]) == ("bid_ask_midpoint", 0.01)+ assert c25["comparable"] is False and c25["price_gap"] == 0.0065+ assert c25["flags"] == ["kalshi price is not a two-sided quote midpoint (basis: last_trade)"]+ assert (c25["kalshi"]["price_basis"], c25["kalshi"]["spread"]) == ("last_trade", None)+ assert c25["kalshi"]["last_trade_time"] == LAST_TRADE+ assert h25["kalshi"]["last_trade_time"] is None and c25["polymarket"]["last_trade_time"] is None+ # Only the last-trade pair is looked up, one trade per market.+ assert [c.request.url.params["ticker"] for c in trades.calls] == ["KXFEDDECISION-26OCT-C25"]+ assert [c.request.url.params["limit"] for c in trades.calls] == ["1"]+ assert out["comparable_count"] == 1 and "degraded" not in out+ assert out["ranking"].startswith("Pairs with comparable: true")+ assert "not a probability" in out["method"]+++async def test_compare_failed_last_trade_lookup_is_a_gap_not_an_outage(fetcher: Fetcher) -> None:+ _fed_events()+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=POLY_OPEN))+ _trades(500)++ out = await fetch_prediction_compare(fetcher, series="KXFEDDECISION")++ assert [p["kalshi"]["last_trade_time"] for p in out["matched"]] == [None, None]+ assert "kalshi: Kalshi last-trade time unavailable for 1 market(s)" in out["data_gaps"]+ assert "degraded" not in out and out["matched_count"] == 2+++# ---------------------------------------------------------------------------+# intel_prediction_settled: expired-cache serves+# ---------------------------------------------------------------------------++async def test_settled_kalshi_candles_from_expired_cache_are_not_scored(fetcher: Fetcher) -> None:+ expire(fetcher, f"kalshi:candles:M2,M1,M6:{K_REF - 192 * 3600}:{K_REF - 24 * 3600}", {"markets": [+ {"market_ticker": "M1", "candlesticks": [{"end_period_ts": K_REF - 30 * 3600, "price": {"close_dollars": "0.8000"}}]},+ {"market_ticker": "M2", "candlesticks": [{"end_period_ts": K_REF - 48 * 3600, "price": {"close_dollars": "0.3000"}}]},+ {"market_ticker": "M6", "candlesticks": []},+ ]})+ _mock_settled_venues()+ respx.get(url__regex=KALSHI_CANDLES).mock(return_value=httpx.Response(500))++ out = await fetch_prediction_settled(fetcher, offsets_hours=[24], kalshi_series="KXCPIYOY")++ k = out["venues"]["kalshi"]+ assert k["scored"] is False and k["scores"] is None+ assert k["not_scored_reason"] == "price history served from expired cache for every market in the sample"+ assert f"kalshi: candlesticks for 3 market(s) {STALE_SUFFIX}" in out["data_gaps"]+ assert out["degraded"] is True+ assert out["venues"]["polymarket"]["scores"]["24h"]["brier"] == 0.125 # unaffected+++async def test_settled_polymarket_history_from_expired_cache_is_excluded(fetcher: Fetcher) -> None:+ expire(fetcher, f"prediction:polymarket:history:p1a:{P1_REF - 192 * 3600}:{P1_REF - 24 * 3600}",+ {"history": [{"t": P1_REF - 26 * 3600, "p": 0.7}]})+ _mock_settled_venues()++ def _clob(request: httpx.Request) -> httpx.Response:+ if request.url.params["market"] == "p1a":+ return httpx.Response(500)+ return httpx.Response(200, json={"history": [{"t": P2_REF - 25 * 3600, "p": 0.4}]})++ respx.get(url__regex=CLOB).mock(side_effect=_clob)++ out = await fetch_prediction_settled(fetcher, offsets_hours=[24], kalshi_series="KXCPIYOY")++ p = out["venues"]["polymarket"]+ # p2 only: 0.4 vs its first outcome ("Up", lost) -> 0.16. p1's+ # 10-day-old copy is not scored as if it were current.+ assert p["scores"]["24h"] == {+ "n": 1, "distinct_events": 1, "brier": 0.16, "yes_rate": 0.0,+ "excluded": {"price history served from expired cache": 1},+ }+ assert [s["price_before_reference"]["24h"] for s in p["sample"]] == [None, 0.4]+ assert (+ f"polymarket: price history for 1 market(s) {STALE_SUFFIX}; not scored" in out["data_gaps"]+ )+ assert out["degraded"] is True+++async def test_settled_kalshi_listing_from_expired_cache_is_scored_and_marked(fetcher: Fetcher) -> None:+ expire(fetcher, "kalshi:settled:KXCPIYOY:first", {"markets": SETTLED_ROWS, "cursor": ""})+ _mock_settled_venues(kalshi_status=500)++ out = await fetch_prediction_settled(fetcher, offsets_hours=[24], kalshi_series="KXCPIYOY")++ k = out["venues"]["kalshi"]+ assert k["scores"]["24h"]["brier"] == 0.065 # the listing is old; the prices are live+ assert k["selection"].endswith("; 1 listing response(s) served from expired cache")+ assert out["data_gaps"] == [f"kalshi: Kalshi settled listing: 1 response(s) {STALE_SUFFIX}"]+ assert out["degraded"] is True+++async def test_settled_polymarket_listing_from_expired_cache_is_scored_and_marked(fetcher: Fetcher) -> None:+ expire(fetcher, "prediction:polymarket:settled:100:10000.0", POLY_CLOSED)+ _mock_settled_venues()+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(500))++ out = await fetch_prediction_settled(fetcher, offsets_hours=[24], kalshi_series="KXCPIYOY")++ p = out["venues"]["polymarket"]+ assert p["scores"]["24h"]["brier"] == 0.125+ assert p["selection"].endswith("; the listing was served from expired cache")+ assert out["data_gaps"] == [+ "polymarket: closed-markets listing served from expired cache after a failed live fetch"+ ]+ assert out["degraded"] is True+++# ---------------------------------------------------------------------------+# intel_prediction_settled: reference times, windows and offsets+# ---------------------------------------------------------------------------++async def test_settled_history_window_ends_at_the_smallest_offset_before_the_reference(fetcher: Fetcher) -> None:+ _mock_settled_venues()+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=[+ dict(POLY_CLOSED[0], endDate="2026-10-17T12:00:00Z"),+ ] + POLY_CLOSED[1:]))+ clob = respx.get(url__regex=CLOB).mock(return_value=httpx.Response(200, json={"history": []}))++ out = await fetch_prediction_settled(fetcher, offsets_hours=[24, 72], kalshi_series="KXCPIYOY")++ windows = {c.request.url.params["market"]: (int(c.request.url.params["startTs"]),+ int(c.request.url.params["endTs"])) for c in clob.calls}+ p1_ref = int(datetime(2026, 10, 17, 12, tzinfo=timezone.utc).timestamp()) # endDate, before closedTime+ # Window: [reference - (72 + 168) h, reference - 24 h].+ assert windows == {+ "p1a": (p1_ref - 240 * 3600, p1_ref - 24 * 3600),+ "p2a": (P2_REF - 240 * 3600, P2_REF - 24 * 3600),+ }+ assert [s["reference"] for s in out["venues"]["polymarket"]["sample"]] == [+ "endDate (scheduled end; the market closed later, after resolution)",+ "closedTime (closed at or before its scheduled endDate)",+ ]+++async def test_settled_refuses_any_offset_at_or_below_zero(fetcher: Fetcher) -> None:+ """A bad offset next to a good one is refused, not dropped."""+ routes = [+ respx.get(url__regex=p).mock(return_value=httpx.Response(200, json={}))+ for p in (r".*api\.elections\.kalshi\.com/.*", GAMMA, CLOB)+ ]+ for offsets, message in (+ ([-5, 24], "offsets_hours values must be above 0 hours (got -5)"),+ ([24, 0], "offsets_hours values must be above 0 hours (got 0)"),+ ):+ out = await fetch_prediction_settled(fetcher, offsets_hours=offsets)+ assert out["error"] == message and out["degraded"] is True and "venues" not in out+ assert sum(r.call_count for r in routes) == 0+++async def test_settled_states_reference_times_and_per_offset_samples(fetcher: Fetcher) -> None:+ _mock_settled_venues()++ out = await fetch_prediction_settled(fetcher, offsets_hours=[24], kalshi_series="KXCPIYOY")++ assert "Reference times differ by venue" in out["comparability"]+ assert "samples differ by offset" in out["comparability"]+ k, p = out["venues"]["kalshi"], out["venues"]["polymarket"]+ assert k["reference_time"].startswith("close_time (when trading ended")+ assert p["reference_time"].startswith("the earlier of endDate")+ assert [s["reference"] for s in k["sample"]] == ["close_time (trading end)"] * 3+ assert [s["reference"] for s in p["sample"]] == ["closedTime (closed at or before its scheduled endDate)"] * 2diff --git a/src/world_intel_mcp/tests/test_prediction_matching_gates.py b/src/world_intel_mcp/tests/test_prediction_matching_gates.pynew file mode 100644index 0000000..c046302--- /dev/null+++ b/src/world_intel_mcp/tests/test_prediction_matching_gates.py@@ -0,0 +1,235 @@+"""Matching gates and candidate completeness for+analysis/prediction_matching.py (review round, 2026-10-17).++Pairs that name different events must be rejected, each with the gate+that caught it: rate actions, directions, signed numbers, a dollar+amount that looks like a year, ordinals. Same-event pairs that the old+blocking never scored ("Trump pardon Bannon?" among 30 "trump pardon"+titles), "U.S." against "US", "$10m" against "$10 million" and a+fractional threshold worded strict on one venue and inclusive on the+other must match. The negation gate, the date factor and one-to-one+matching each get a case that fails if the rule is removed.++Every expected reason and score below was computed with the module+before it was written here (scratch probes); "now" is pinned so the+date tolerance is fixed.++Gaps / not covered: wording beyond these cases; the candidate-pair+completeness check is randomized over a small vocabulary, not+exhaustive (the prefix bound itself was checked with z3).+"""++import random+from datetime import datetime, timezone++import pytest++from world_intel_mcp.analysis import prediction_matching as pm++NOW = datetime(2026, 10, 17, 16, 0, tzinfo=timezone.utc)+END = "2026-12-10T19:00:00Z"+++def _k(question, yes="", end=END, id_="K", prob=0.5, **quote):+ return dict({"venue": "kalshi", "id": id_, "question": question, "context": "", "yes_side": yes,+ "outcomes": ["Yes", "No"], "end_time": end, "probability": prob}, **quote)+++def _p(question, end=END, id_="P", prob=0.5, **quote):+ return dict({"venue": "polymarket", "id": id_, "question": question, "context": "", "yes_side": "",+ "outcomes": ["Yes", "No"], "end_time": end, "probability": prob}, **quote)+++# ---------------------------------------------------------------------------+# Different events: rejected, with the gate that caught them+# ---------------------------------------------------------------------------++REJECTED = {+ "cut vs raise": (+ "Will the Fed cut rates in December 2026?", "Will the Fed raise rates in December 2026?",+ "actions differ: Kalshi ['cut'] vs Polymarket ['raise']",+ ),+ "cut vs hold": (+ "Will the Fed cut rates in December 2026?", "Will the Fed hold rates in December 2026?",+ "actions differ: Kalshi ['cut'] vs Polymarket ['hold']",+ ),+ "above vs below a dollar amount that looks like a year": (+ "Will Ethereum be above $2,000 on Dec 10, 2026?", "Will Ethereum be below $2,000 on December 10, 2026?",+ "quantities differ: Kalshi ['>2000'] vs Polymarket ['<2000']",+ ),+ "a minus sign": (+ "Will Q4 GDP growth be below -0.5%?", "Will Q4 GDP growth be below 0.5%?",+ "quantities differ: Kalshi ['4', '<-0.5'] vs Polymarket ['4', '<0.5']",+ ),+ "ordinals": (+ "Will Smith finish 1st in the 2026 Boston Marathon?", "Will Smith finish 2nd in the 2026 Boston Marathon?",+ "quantities differ: Kalshi ['1st'] vs Polymarket ['2nd']",+ ),+ "directions without numbers": (+ "Will gas prices end the year above last year's level in 2026?",+ "Will gas prices end the year below last year's level in 2026?",+ "directions differ: Kalshi ['above'] vs Polymarket ['below']",+ ),+ "an integer threshold strict on one venue and inclusive on the other": (+ "Will the Fed cut rates by more than 50 bps in December 2026?",+ "Will the Fed cut rates by 50+ bps in December 2026?",+ "quantities differ: Kalshi ['>50'] vs Polymarket ['>=50']",+ ),+}++[email protected]("case", sorted(REJECTED))+def test_pairs_naming_different_events_are_rejected(case: str) -> None:+ kalshi_q, poly_q, reason = REJECTED[case]+ result = pm.score_pair(_k(kalshi_q), _p(poly_q), now=NOW)+ assert result["rejected"] is True and result["confidence"] == 0.0+ assert result["reasons"][-1] == reason+++def test_a_rejected_pair_is_never_matched() -> None:+ out = pm.match_markets(+ [_k("Will the Fed cut rates in December 2026?")], [_p("Will the Fed raise rates in December 2026?")], now=NOW+ )+ assert out["matched"] == [] and out["unmatched_kalshi"] == 1 and out["unmatched_polymarket"] == 1+ assert [nm["reasons"][-1] for nm in out["near_misses"]] == ["actions differ: Kalshi ['cut'] vs Polymarket ['raise']"]+++def test_negation_gate_rejects_an_otherwise_identical_pair() -> None:+ same = pm.score_pair(_k("Will Bitcoin hit $150k in 2026?"), _p("Will Bitcoin hit $150k in 2026?"), now=NOW)+ assert same["rejected"] is False and same["confidence"] == 1.0+ negated = pm.score_pair(_k("Will Bitcoin hit $150k in 2026?"), _p("Will Bitcoin not hit $150k in 2026?"), now=NOW)+ assert negated["rejected"] is True+ assert negated["reasons"][-1] == "negation differs (one title says not/no/never/without, the other does not)"+++def test_no_change_names_the_hold_outcome_not_a_negation() -> None:+ result = pm.score_pair(+ _k("Will the Fed hold rates in December 2026?"), _p("Will there be no change in Fed rates in December 2026?"), now=NOW+ )+ assert result["rejected"] is False and result["confidence"] == 1.0+++# ---------------------------------------------------------------------------+# Same events worded differently: matched+# ---------------------------------------------------------------------------++def test_us_with_dots_matches_us() -> None:+ result = pm.score_pair(+ _k("Will the U.S. enter a recession in 2026?"), _p("Will the US enter a recession in 2026?"), now=NOW+ )+ assert result["rejected"] is False and result["confidence"] == 1.0+++def test_money_scale_words_and_suffixes_are_the_same_amount() -> None:+ assert pm.tokenize("$10m") == pm.tokenize("$10 million") == ["10000000"]+ result = pm.score_pair(+ _k("Will the Ethereum Foundation sell $10m of ETH in 2026?"),+ _p("Will the Ethereum Foundation sell $10 million of ETH in 2026?"),+ now=NOW,+ )+ assert result["rejected"] is False and result["confidence"] == 1.0+++def test_fractional_threshold_strict_vs_inclusive_matches_with_a_flag() -> None:+ kalshi = _k("Will the unemployment rate be 4.5% or higher in November 2026?",+ price_basis="bid_ask_midpoint", spread=0.02)+ poly = _p("Will the unemployment rate be above 4.5% in November 2026?",+ price_basis="bid_ask_midpoint", spread=0.02)+ result = pm.score_pair(kalshi, poly, now=NOW)+ assert result["rejected"] is False and result["boundary_differs"] is True+ (pair,) = pm.match_markets([kalshi], [poly], now=NOW)["matched"]+ assert pair["match_confidence"] == 1.0+ assert pair["flags"] == ["thresholds differ at the boundary (strict on one venue, inclusive on the other)"]+ assert pair["comparable"] is False+++def test_rare_word_pair_among_many_shared_word_titles_is_scored_and_matched() -> None:+ """Old blocking needed two shared words each in under 20% of the+ Polymarket titles, so this pair was never scored (pairs_scored 0)."""+ names = ["Bannon", "Giuliani", "Hunter", "Navarro", "Flynn", "Stone", "Manafort", "Meadows", "Eastman", "Clark",+ "Chesebro", "Ellis", "Powell", "Kerik", "Epshteyn", "Roman", "Trusty", "Smith", "Jones", "Brown",+ "Taylor", "Wilson", "Moore", "Martin", "Lee", "Walker", "Hall", "Allen", "Young", "King"]+ poly = [_p(f"Will Trump pardon {n}?", end="2026-12-31T00:00:00Z", id_=f"P{i}") for i, n in enumerate(names)]+ out = pm.match_markets([_k("Trump pardon Bannon?", end="2026-12-31T00:00:00Z", id_="KB")], poly, now=NOW)+ assert [(m["kalshi"]["id"], m["polymarket"]["id"], m["match_confidence"]) for m in out["matched"]] == [+ ("KB", "P0", 1.0)+ ]+ assert out["pairs_scored"] == 30+++def test_candidate_pairs_include_every_pair_a_brute_force_scan_finds() -> None:+ vocabulary = "alpha bravo charlie delta echo foxtrot golf hotel india juliet kilo lima".split()+ rng = random.Random(20261017)++ def bag() -> str:+ return " ".join(rng.sample(vocabulary, rng.randint(1, 6)))++ k_feats = [pm._market_features(_k(bag()), "kalshi") for _ in range(40)]+ p_feats = [pm._market_features(_p(bag()), "polymarket") for _ in range(40)]+ for threshold in (0.3, 0.499, 0.6, 0.75, 1.0):+ brute = set()+ for ki, kf in enumerate(k_feats):+ for pi, pf in enumerate(p_feats):+ a, b = kf["bag"]["words"], pf["bag"]["words"]+ if 2 * len(a & b) / (len(a) + len(b)) >= threshold:+ brute.add((ki, pi))+ candidates = set(pm._candidate_pairs(k_feats, p_feats, threshold))+ assert brute and brute <= candidates, threshold+++# ---------------------------------------------------------------------------+# Score: date factor, one-to-one, ordinal statement, quote flags+# ---------------------------------------------------------------------------++def test_date_factor_lowers_the_score_with_the_end_date_gap() -> None:+ question = "Will Bitcoin hit $150k by Oct 20, 2026?"+ same_day = pm.score_pair(_k(question, end="2026-10-20T00:00:00Z"), _p(question, end="2026-10-20T00:00:00Z"), now=NOW)+ apart = pm.score_pair(_k(question, end="2026-10-20T00:00:00Z"), _p(question, end="2026-10-21T12:00:00Z"), now=NOW)+ assert same_day["confidence"] == 1.0+ # 1.5 days apart, tolerance 3 days: 1 - 0.5 * 1.5 / 3 = 0.75.+ assert apart["confidence"] == 0.75+ assert "end dates 1.5 days apart (tolerance 3.0 days)" in apart["reasons"]+++def test_matching_is_one_to_one_on_both_venues() -> None:+ question = "Will Bitcoin hit $150k in 2026?"+ later = "2026-12-12T07:00:00Z" # 1.5 days after END: scores 0.91, above the threshold+ two_kalshi = pm.match_markets([_k(question, id_="K1"), _k(question, id_="K2", end=later)], [_p(question, id_="P1")], now=NOW)+ assert [(m["kalshi"]["id"], m["polymarket"]["id"]) for m in two_kalshi["matched"]] == [("K1", "P1")]+ assert two_kalshi["unmatched_kalshi"] == 1 and two_kalshi["unmatched_polymarket"] == 0+ two_poly = pm.match_markets([_k(question, id_="K1")], [_p(question, id_="P1", end=later), _p(question, id_="P2")], now=NOW)+ assert [(m["kalshi"]["id"], m["polymarket"]["id"]) for m in two_poly["matched"]] == [("K1", "P2")]+ assert two_poly["unmatched_kalshi"] == 0 and two_poly["unmatched_polymarket"] == 1+++def test_score_is_documented_as_ordinal_not_a_probability() -> None:+ assert "not a calibrated probability" in pm.__doc__+ assert "ordinal score, not a probability" in pm.score_pair.__doc__+++def test_pairs_carry_quotes_and_flag_prices_that_are_not_live_two_sided_quotes() -> None:+ question = "Will Bitcoin hit $150k in 2026?"+ last_trade = dict(price_basis="last_trade", yes_bid=0.0, yes_ask=0.01, spread=None, last_price=0.01,+ last_trade_time=None)+ wide = dict(price_basis="bid_ask_midpoint", yes_bid=0.30, yes_ask=0.50, spread=0.2, last_price=0.4,+ last_trade_time=None)+ (flagged,) = pm.match_markets([_k(question, prob=0.01, **last_trade)], [_p(question, prob=0.4, **wide)], now=NOW)["matched"]+ assert flagged["flags"] == [+ "kalshi price is not a two-sided quote midpoint (basis: last_trade)",+ "polymarket bid/ask spread 0.20 is wider than 0.10",+ ]+ assert flagged["comparable"] is False and flagged["price_gap"] == -0.39+ assert {k: flagged["kalshi"][k] for k in ("price_basis", "yes_bid", "yes_ask", "spread", "last_price")} == {+ "price_basis": "last_trade", "yes_bid": 0.0, "yes_ask": 0.01, "spread": None, "last_price": 0.01,+ }+ assert "last_trade_time" in flagged["kalshi"] and "last_trade_time" in flagged["polymarket"]+ live_k = dict(price_basis="bid_ask_midpoint", yes_bid=0.39, yes_ask=0.41, spread=0.02)+ live_p = dict(price_basis="bid_ask_midpoint", yes_bid=0.38, yes_ask=0.40, spread=0.02)+ (clean,) = pm.match_markets([_k(question, prob=0.4, **live_k)], [_p(question, prob=0.39, **live_p)], now=NOW)["matched"]+ assert clean["flags"] == [] and clean["comparable"] is True and clean["price_gap"] == 0.01+++def test_upstream_text_is_capped() -> None:+ clipped = pm.clip_text("x" * 600)+ assert len(clipped) == pm.MAX_TEXT_CHARS == 500 and clipped.endswith("...")+ assert pm.clip_text(None) == "" and pm.clip_text(12) == "12" and pm.clip_text("short") == "short"diff --git a/src/world_intel_mcp/tests/test_sources_kalshi_stale.py b/src/world_intel_mcp/tests/test_sources_kalshi_stale.pynew file mode 100644index 0000000..0d92543--- /dev/null+++ b/src/world_intel_mcp/tests/test_sources_kalshi_stale.py@@ -0,0 +1,351 @@+"""Expired-cache marking, pacing, value checks and request bounds for+sources/kalshi.py (review round, 2026-10-17).++An expired-cache serve is produced the way it happens live: an entry+exists under the request's cache key but has expired, the upstream+answers 500, and the fetcher falls back to the expired entry, marking+the dict ``_stale`` with its age. ``expire`` backdates the entry by 10+days (864,000 s, 240.0 h).++Gaps / not covered: a real Kalshi outage; two processes sharing the+upstream rate limit (pacing is per process).+"""++import asyncio as asyncio_mod+import json+from collections import Counter++import httpx+import pytest+import respx++from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.sources import kalshi+from world_intel_mcp.tests.test_sources_kalshi import (+ CANDLES,+ EVENTS,+ FED_MARKETS,+ MANY_SERIES,+ MARKETS,+ SERIES,+ SETTLED_ROWS,+ _event,+ _m,+ _settled,+)++TRADES = r".*api\.elections\.kalshi\.com/trade-api/v2/markets/trades.*"+TEN_DAYS = 864000+STALE_SUFFIX = "served from expired cache after a failed live fetch, the oldest 240.0 h old"++[email protected](autouse=True)+def _no_sleep(monkeypatch: pytest.MonkeyPatch) -> None:+ async def _sleep(*args, **kwargs) -> None:+ return None++ monkeypatch.setattr(asyncio_mod, "sleep", _sleep)+++def expire(fetcher: Fetcher, key: str, value, age_seconds: int = TEN_DAYS) -> None:+ """Store ``value`` under ``key`` as an expired entry written ``age_seconds`` ago."""+ fetcher.cache.set(key, value, -10)+ conn = fetcher.cache._get_conn()+ conn.execute("UPDATE cache SET created_at = created_at - ? WHERE key = ?", (age_seconds, key))+ conn.commit()+++# ---------------------------------------------------------------------------+# Expired-cache serves are marked+# ---------------------------------------------------------------------------++async def test_open_markets_from_expired_cache_are_marked_stale_and_degraded(fetcher: Fetcher) -> None:+ expire(fetcher, "kalshi:events:series:KXFEDDECISION:first", {"events": [_event(FED_MARKETS)], "cursor": ""})+ respx.get(url__regex=EVENTS).mock(return_value=httpx.Response(500))++ out = await kalshi.fetch_kalshi_markets(fetcher, series="KXFEDDECISION", limit=3)++ assert out["count"] == 3 # the old data is still shown, and marked+ assert out["stale"] is True and out["degraded"] is True and "error" not in out+ assert out["scan"]["stale_responses"] == 1+ assert TEN_DAYS <= out["scan"]["stale_max_age_seconds"] < TEN_DAYS + 60+ assert out["data_gaps"] == [f"Kalshi open markets: 1 response(s) {STALE_SUFFIX}"]+++async def test_category_series_listing_from_expired_cache_is_counted(fetcher: Fetcher) -> None:+ expire(fetcher, "kalshi:series:Economics", {"series": [+ {"ticker": "KXFEDDECISION", "category": "Economics", "volume_fp": "9.00"},+ ]})+ respx.get(url__regex=SERIES).mock(return_value=httpx.Response(503))+ respx.get(url__regex=EVENTS).mock(+ return_value=httpx.Response(200, json={"events": [_event(FED_MARKETS)], "cursor": ""})+ )++ out = await kalshi.fetch_kalshi_markets(fetcher, category="Economics", limit=2)++ assert out["count"] == 2 and out["scan"]["series_scanned"] == ["KXFEDDECISION"]+ assert out["stale"] is True and out["degraded"] is True+ assert out["scan"]["stale_responses"] == 1+++async def test_settled_listing_from_expired_cache_is_counted(fetcher: Fetcher) -> None:+ expire(fetcher, "kalshi:settled:KXCPIYOY:first", {"markets": SETTLED_ROWS, "cursor": ""})+ respx.get(url__regex=MARKETS).mock(return_value=httpx.Response(500))++ out = await kalshi.fetch_kalshi_settled(fetcher, series="KXCPIYOY", min_volume=1000, min_open_hours=24)++ assert [m["id"] for m in out["markets"]] == ["M2", "M1", "M6"]+ assert out["error"] is None and out["stale_responses"] == 1+ assert TEN_DAYS <= out["stale_max_age_seconds"] < TEN_DAYS + 60+ assert out["stale_gap"] == f"Kalshi settled listing: 1 response(s) {STALE_SUFFIX}"+++async def test_fresh_settled_listing_reports_no_stale_responses(fetcher: Fetcher) -> None:+ respx.get(url__regex=MARKETS).mock(return_value=httpx.Response(200, json={"markets": SETTLED_ROWS, "cursor": ""}))+ out = await kalshi.fetch_kalshi_settled(fetcher, series="KXCPIYOY")+ assert out["stale_responses"] == 0 and out["stale_gap"] is None and out["stale_max_age_seconds"] is None+++async def test_candles_from_expired_cache_are_named_per_ticker(fetcher: Fetcher) -> None:+ ref = 1792252800+ start, end = ref - 48 * 3600, ref - 24 * 3600+ expire(fetcher, f"kalshi:candles:A:{start}:{end}", {"markets": [+ {"market_ticker": "A", "candlesticks": [{"end_period_ts": ref - 30 * 3600, "price": {"close_dollars": "0.4200"}}]},+ ]})+ respx.get(url__regex=CANDLES).mock(return_value=httpx.Response(500))+ stale: dict = {}++ history, errors = await kalshi.fetch_kalshi_price_history(+ fetcher, [{"id": "A", "reference_ts": ref, "open_ts": None}], 48, 24, stale=stale+ )++ assert history == {"A": [(ref - 30 * 3600, 0.42)]}+ assert list(stale) == ["A"] and TEN_DAYS <= stale["A"] < TEN_DAYS + 60+ assert errors == [f"candlesticks for 1 market(s) {STALE_SUFFIX}"]+++# ---------------------------------------------------------------------------+# Pacing: only a cache miss waits+# ---------------------------------------------------------------------------++async def test_cache_hits_are_not_paced(fetcher: Fetcher, monkeypatch: pytest.MonkeyPatch) -> None:+ paced: list[int] = []++ async def _count() -> None:+ paced.append(1)++ monkeypatch.setattr(kalshi, "_pace", _count)+ route = respx.get(url__regex=EVENTS).mock(+ return_value=httpx.Response(200, json={"events": [_event(FED_MARKETS)], "cursor": ""})+ )+ first = await kalshi.fetch_kalshi_markets(fetcher, series="KXFEDDECISION")+ second = await kalshi.fetch_kalshi_markets(fetcher, series="KXFEDDECISION")++ assert route.call_count == 1 # the second scan is a cache hit...+ assert len(paced) == 1 # ...and waits for nothing+ assert second["markets"] == first["markets"]+++# ---------------------------------------------------------------------------+# Request bounds: 5 open-event pages and 3 settled pages per series+# ---------------------------------------------------------------------------++def _endless(payload_key: str):+ """Every page names a next page; cursors are distinct, so none is a cache hit."""++ def _page(request: httpx.Request) -> httpx.Response:+ params = request.url.params+ page = int(params["cursor"].rsplit(":", 1)[1]) + 1 if "cursor" in params else 1+ return httpx.Response(200, json={payload_key: [], "cursor": f"{params['series_ticker']}:{page}"})++ return _page+++async def test_category_scan_makes_at_most_126_requests(fetcher: Fetcher) -> None:+ series_route = respx.get(url__regex=SERIES).mock(return_value=httpx.Response(200, json={"series": MANY_SERIES}))+ events_route = respx.get(url__regex=EVENTS).mock(side_effect=_endless("events"))++ await kalshi.fetch_kalshi_markets(fetcher, category="Economics", series_limit=10**6, pages=10**6)++ per_series = Counter(c.request.url.params["series_ticker"] for c in events_route.calls)+ assert len(per_series) == 25 and set(per_series.values()) == {5}+ assert series_route.call_count + events_route.call_count == 126+++async def test_settled_category_listing_makes_at_most_76_requests(fetcher: Fetcher) -> None:+ series_route = respx.get(url__regex=SERIES).mock(return_value=httpx.Response(200, json={"series": MANY_SERIES}))+ markets_route = respx.get(url__regex=MARKETS).mock(side_effect=_endless("markets"))++ await kalshi.fetch_kalshi_settled(fetcher, category="Economics", series_limit=10**6, pages=10**6)++ per_series = Counter(c.request.url.params["series_ticker"] for c in markets_route.calls)+ assert len(per_series) == 25 and set(per_series.values()) == {3}+ assert series_route.call_count + markets_route.call_count == 76+++# ---------------------------------------------------------------------------+# Values: finite prices in 0..1, readable volumes+# ---------------------------------------------------------------------------++def test_prices_must_be_finite_and_within_0_to_1() -> None:+ assert kalshi.implied_probability({"last_price_dollars": "inf"}) == (None, "no_price")+ assert kalshi.implied_probability({"last_price_dollars": "1.5"}) == (None, "no_price")+ assert kalshi.implied_probability({"last_price_dollars": "1.0000"}) == (1.0, "last_trade")+ assert kalshi.implied_probability(+ {"yes_bid_dollars": "nan", "yes_ask_dollars": "0.6", "last_price_dollars": "0.55"}+ ) == (0.55, "last_trade")+ bad = dict(FED_MARKETS[0], yes_bid_dollars="nan", last_price_dollars="inf", open_interest_fp="inf")+ n = kalshi.normalize_market(bad, None)+ assert n["probability"] is None and n["price_basis"] == "no_price"+ assert n["yes_bid"] is None and n["last_price"] is None and n["open_interest"] is None+ json.dumps(n, allow_nan=False) # strict JSON: no NaN or Infinity anywhere+++def test_spread_is_set_only_for_a_two_sided_book() -> None:+ assert kalshi.normalize_market(FED_MARKETS[2], None)["spread"] == 0.01 # 0.86 / 0.87+ assert kalshi.normalize_market(FED_MARKETS[1], None)["spread"] is None # bid 0: one-sided+ assert kalshi.normalize_market(FED_MARKETS[1], None)["last_trade_time"] is None+++async def test_open_market_with_unreadable_volume_is_excluded_and_counted(fetcher: Fetcher) -> None:+ nan_row = _m("KXFEDDECISION-26OCT-NAN", "NaN volume", "X", "0.4000", "0.5000", "0.4500", "NaN", "10.00")+ respx.get(url__regex=EVENTS).mock(+ return_value=httpx.Response(200, json={"events": [_event(FED_MARKETS + [nan_row])], "cursor": ""})+ )++ out = await kalshi.fetch_kalshi_markets(fetcher, series="KXFEDDECISION")++ assert out["markets_considered"] == 5 and out["untraded_excluded"] == 0+ assert out["volume_unreadable_excluded"] == 1+ assert out["data_gaps"] == ["1 market(s) left out: volume unreadable (not a finite contract count)"]+ assert "KXFEDDECISION-26OCT-NAN" not in [m["id"] for m in out["markets"]]+++async def test_settled_rows_with_unreadable_volume_are_skipped_not_kept(fetcher: Fetcher) -> None:+ rows = [+ _settled("MN", "yes", "nan", "2026-07-20T14:00:00Z", "2026-09-11T12:35:00Z"),+ _settled("MI", "no", "inf", "2026-07-20T14:00:00Z", "2026-09-11T12:36:00Z"),+ ] + SETTLED_ROWS+ respx.get(url__regex=MARKETS).mock(return_value=httpx.Response(200, json={"markets": rows, "cursor": ""}))++ out = await kalshi.fetch_kalshi_settled(fetcher, series="KXCPIYOY", min_volume=1000, min_open_hours=24)++ assert [m["id"] for m in out["markets"]] == ["M2", "M1", "M6"]+ assert out["skipped"] == {"result": 1, "volume": 3, "too_short": 1}+++# ---------------------------------------------------------------------------+# Identifiers and text+# ---------------------------------------------------------------------------++def test_identifiers_that_are_not_tickers_build_no_url() -> None:+ evil = dict(FED_MARKETS[0], event_ticker="../EVIL x-1", ticker="../EVIL x-1-A")+ assert kalshi.normalize_market(evil, None)["url"] == ""+ assert kalshi.normalize_market(FED_MARKETS[0], {"series_ticker": "KX FED"})["url"] == ""+ assert kalshi.normalize_market(FED_MARKETS[0], None)["url"] == "https://kalshi.com/markets/kxfeddecision"+++def test_long_titles_are_capped() -> None:+ long_title = dict(FED_MARKETS[0], title="x" * 600, yes_sub_title="y" * 600)+ n = kalshi.normalize_market(long_title, {"title": "z" * 600})+ assert len(n["question"]) == len(n["context"]) == len(n["yes_side"]) == 500+ assert n["question"].endswith("...")+++async def test_settled_rows_without_a_valid_ticker_are_skipped_and_counted(fetcher: Fetcher) -> None:+ """Tickers are joined into the candlestick request, so a comma or a+ blank in one would corrupt it."""+ bad = [dict(SETTLED_ROWS[0], ticker="M1,M9"), dict(SETTLED_ROWS[1], ticker="")]+ respx.get(url__regex=MARKETS).mock(+ return_value=httpx.Response(200, json={"markets": bad + SETTLED_ROWS, "cursor": ""})+ )++ out = await kalshi.fetch_kalshi_settled(fetcher, series="KXCPIYOY", min_volume=1000, min_open_hours=24)++ assert out["invalid_ticker_skipped"] == 2 and out["listing_rows_read"] == 8+ assert [m["id"] for m in out["markets"]] == ["M2", "M1", "M6"]+++# ---------------------------------------------------------------------------+# Last-trade time+# ---------------------------------------------------------------------------++async def test_last_trade_times_come_from_the_trades_endpoint(fetcher: Fetcher) -> None:+ def _trades(request: httpx.Request) -> httpx.Response:+ ticker = request.url.params["ticker"]+ if ticker == "KXFEDDECISION-26OCT-C25": # live shape, 2026-10-17+ return httpx.Response(200, json={"trades": [+ {"created_time": "2026-10-17T17:43:15.314853Z", "yes_price_dollars": "0.0100", "count_fp": "935.00"},+ ], "cursor": ""})+ if ticker == "KXFEDDECISION-26OCT-X":+ return httpx.Response(200, json={"trades": [], "cursor": ""})+ return httpx.Response(500)++ route = respx.get(url__regex=TRADES).mock(side_effect=_trades)++ times, gaps = await kalshi.fetch_kalshi_last_trade_times(+ fetcher, ["KXFEDDECISION-26OCT-C25", "KXFEDDECISION-26OCT-X", "KXFEDDECISION-26OCT-DOWN", "not a ticker"]+ )++ assert times == {"KXFEDDECISION-26OCT-C25": "2026-10-17T17:43:15.314853Z", "KXFEDDECISION-26OCT-X": None}+ assert gaps == ["Kalshi last-trade time unavailable for 2 market(s)"]+ assert {c.request.url.params["ticker"] for c in route.calls} == {+ "KXFEDDECISION-26OCT-C25", "KXFEDDECISION-26OCT-X", "KXFEDDECISION-26OCT-DOWN",+ } # the malformed ticker is never requested+ assert {c.request.url.params["limit"] for c in route.calls} == {"1"}+++async def test_an_unreadable_trade_time_is_a_gap_not_no_trade(fetcher: Fetcher) -> None:+ respx.get(url__regex=TRADES).mock(+ return_value=httpx.Response(200, json={"trades": [{"created_time": "yesterday"}], "cursor": ""})+ )+ times, gaps = await kalshi.fetch_kalshi_last_trade_times(fetcher, ["KXFEDDECISION-26OCT-C25"])+ assert times == {}+ assert gaps == ["Kalshi last-trade time unavailable for 1 market(s)"]+++async def test_failed_trade_lookups_do_not_open_the_market_data_breaker(fetcher: Fetcher) -> None:+ """Three failed lookups trip a breaker (threshold 3); it must be the+ lookups' own, or the next market scan would be refused for 300 s."""+ respx.get(url__regex=TRADES).mock(return_value=httpx.Response(500))+ events = respx.get(url__regex=EVENTS).mock(+ return_value=httpx.Response(200, json={"events": [_event(FED_MARKETS)], "cursor": ""})+ )++ _, gaps = await kalshi.fetch_kalshi_last_trade_times(+ fetcher, ["KXFEDDECISION-26OCT-C25", "KXFEDDECISION-26OCT-C26", "KXFEDDECISION-26OCT-H26"]+ )+ out = await kalshi.fetch_kalshi_markets(fetcher, series="KXFEDDECISION")++ assert gaps == ["Kalshi last-trade time unavailable for 3 market(s)"]+ assert fetcher.breaker.is_available("kalshi") is True+ assert events.call_count == 1 and out["count"] == 5 and "degraded" not in out+ assert fetcher.breaker.is_available("kalshi_trades") is Falsediff --git a/src/world_intel_mcp/tests/test_sources_prediction_review.py b/src/world_intel_mcp/tests/test_sources_prediction_review.pynew file mode 100644index 0000000..005d21d--- /dev/null+++ b/src/world_intel_mcp/tests/test_sources_prediction_review.py@@ -0,0 +1,194 @@+"""Expired-cache marking, value checks and request bounds for+sources/prediction.py (review round, 2026-10-17).++Gamma serves lists, which cannot carry the fetcher's inline ``_stale``+marker, so a stale settled listing is detected through the breaker's+stale counter, as for the open listing; CLOB histories are dicts and+carry the marker with its age.++Gaps / not covered: a real Gamma or CLOB outage; the shared polymarket+breaker opening part-way through scoring (documented, not changed).+"""++import asyncio as asyncio_mod+import json+from datetime import datetime, timezone++import httpx+import pytest+import respx++from world_intel_mcp.fetcher import Fetcher+from world_intel_mcp.sources import prediction+from world_intel_mcp.tests.test_prediction_cross import CLOB, GAMMA, P1_REF, P2_REF, POLY_CLOSED, _gamma+from world_intel_mcp.tests.test_sources_kalshi_stale import TEN_DAYS, expire+from world_intel_mcp.tests.test_sources_prediction import _MARKETS++LISTING_STALE = "closed-markets listing served from expired cache after a failed live fetch"++[email protected](autouse=True)+def _no_sleep(monkeypatch: pytest.MonkeyPatch) -> None:+ async def _sleep(*args, **kwargs) -> None:+ return None++ monkeypatch.setattr(asyncio_mod, "sleep", _sleep)+++# ---------------------------------------------------------------------------+# Expired-cache serves are marked+# ---------------------------------------------------------------------------++async def test_settled_listing_from_expired_cache_is_marked_stale(fetcher: Fetcher) -> None:+ expire(fetcher, "prediction:polymarket:settled:100:10000.0", POLY_CLOSED)+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(500))++ out = await prediction.fetch_polymarket_settled(fetcher, min_open_hours=24)++ assert [m["id"] for m in out["markets"]] == ["p1", "p2"] # still usable, and marked+ assert out["error"] is None and out["stale"] is True+ assert out["data_gaps"] == [LISTING_STALE]+++async def test_fresh_settled_listing_is_not_marked_stale(fetcher: Fetcher) -> None:+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=POLY_CLOSED))+ out = await prediction.fetch_polymarket_settled(fetcher, min_open_hours=24)+ assert [m["id"] for m in out["markets"]] == ["p1", "p2"]+ assert "stale" not in out and "data_gaps" not in out+++async def test_price_history_from_expired_cache_reports_its_age(fetcher: Fetcher) -> None:+ expire(fetcher, "prediction:polymarket:history:tok:1000:5000", {"history": [+ {"t": 2000, "p": 0.4}, {"t": 3000, "p": "x"},+ ]})+ route = respx.get(url__regex=CLOB).mock(return_value=httpx.Response(500))+ ages: list = []++ points = await prediction.fetch_polymarket_price_history(fetcher, "tok", 1000, 5000, stale=ages)++ assert points == [(2000, 0.4)]+ assert len(ages) == 1 and TEN_DAYS <= ages[0] < TEN_DAYS + 60++ route.mock(return_value=httpx.Response(200, json={"history": [{"t": 7000, "p": 0.5}]}))+ fresh: list = []+ assert await prediction.fetch_polymarket_price_history(fetcher, "tok", 6000, 9000, stale=fresh) == [(7000, 0.5)]+ assert fresh == []+++# ---------------------------------------------------------------------------+# Values: finite prices in 0..1, readable volumes+# ---------------------------------------------------------------------------++def test_outcome_prices_must_be_finite_and_within_0_to_1() -> None:+ parse = prediction._parse_outcome_prices+ assert parse("[1.5, -0.5]") is None+ assert parse('["NaN", "0.5"]') is None+ assert parse('["inf", "0"]') is None+ assert parse('["1", "0"]') == 1.0+ bad = dict(_gamma("9", "Q?", '["inf", "0"]', "nan", 1.5), lastTradePrice="Infinity")+ n = prediction.normalize_gamma_market(bad)+ assert n["probability"] is None and n["price_basis"] == "no_price"+ assert n["outcome_prices"] == [None, 0.0]+ assert n["yes_bid"] is None and n["yes_ask"] is None and n["last_price"] is None+ json.dumps(n, allow_nan=False) # strict JSON: no NaN or Infinity anywhere+++def test_spread_is_set_only_for_a_two_sided_book() -> None:+ two_sided = prediction.normalize_gamma_market(_gamma("8", "Q?", '["0.4", "0.6"]', 0.39, 0.41))+ assert (two_sided["probability"], two_sided["price_basis"], two_sided["spread"]) == (0.4, "bid_ask_midpoint", 0.02)+ assert two_sided["last_trade_time"] is None # Gamma publishes none+ one_sided = prediction.normalize_gamma_market(_gamma("7", "Q?", '["0.4", "0.6"]', 0, 0.41))+ assert (one_sided["price_basis"], one_sided["spread"]) == ("gamma_outcome_price", None)+++async def test_open_listing_counts_markets_left_out_for_their_price(fetcher: Fetcher) -> None:+ rows = _MARKETS + [{"question": "Impossible", "outcomePrices": "[1.5, -0.5]", "volume24hr": 5}]+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=rows))++ out = await prediction.fetch_prediction_markets(fetcher)++ assert out["count"] == 3 # the impossible price is not shown as a probability+ assert out["data_gaps"] == ["2 market(s) left out: outcome price missing, unreadable or outside 0..1"]+ assert "degraded" not in out+++def test_unreadable_volume_is_none_not_zero() -> None:+ ok = _gamma("8", "Q?", '["0.4", "0.6"]', 0.39, 0.41)+ assert prediction.normalize_gamma_market(dict(ok, volumeNum="NaN"))["volume"] is None+ unreadable = prediction.normalize_gamma_market(dict(ok, volumeNum="x", volume24hr="inf"))+ assert unreadable["volume"] is None and unreadable["volume_24h"] is None+ assert prediction.normalize_gamma_market(dict(ok, volumeNum=None, volume=None))["volume"] == 0.0+++async def test_settled_volume_floor_is_checked_here_and_counted(fetcher: Fetcher) -> None:+ """Gamma's volume_num_min filter is not trusted alone: a NaN volume+ or one below the floor is skipped and counted."""+ rows = [dict(POLY_CLOSED[0], volumeNum="NaN"), dict(POLY_CLOSED[1], volumeNum=500)] + POLY_CLOSED[2:]+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=rows))++ out = await prediction.fetch_polymarket_settled(fetcher, min_open_hours=24)++ assert out["markets"] == []+ assert out["volume_skipped"] == 2 and out["open_too_briefly_skipped"] == 1+++# ---------------------------------------------------------------------------+# Identifiers and text+# ---------------------------------------------------------------------------++def test_slugs_that_are_not_slugs_build_no_url() -> None:+ assert prediction.event_url("../../x?y=1#z) [click](https://evil.example)") == ""+ assert prediction.event_url("Will-X") == "" and prediction.event_url(None) == ""+ assert prediction.event_url("will-x-2026") == "https://polymarket.com/event/will-x-2026"+ evil = dict(_gamma("6", "x" * 600, '["0.4", "0.6"]', 0.39, 0.41), slug="../../x?y=1#z")+ evil["events"] = [{"id": "e", "slug": "../../x?y=1#z) [click](https://evil.example)", "title": "t" * 600}]+ n = prediction.normalize_gamma_market(evil)+ assert n["url"] == ""+ assert len(n["question"]) == len(n["context"]) == 500 and n["question"].endswith("...")+++# ---------------------------------------------------------------------------+# Reference time and request bounds+# ---------------------------------------------------------------------------++async def test_settled_reference_is_the_earlier_of_end_date_and_closed_time(fetcher: Fetcher) -> None:+ rows = [dict(POLY_CLOSED[0], endDate="2026-10-17T12:00:00Z"), dict(POLY_CLOSED[1], endDate=None)] + POLY_CLOSED[2:]+ respx.get(url__regex=GAMMA).mock(return_value=httpx.Response(200, json=rows))++ out = await prediction.fetch_polymarket_settled(fetcher, min_open_hours=24)++ p1, p2 = out["markets"]+ # p1 closed 16:16:26, after its scheduled end at 12:00: the end counts.+ assert p1["reference_ts"] == int(datetime(2026, 10, 17, 12, tzinfo=timezone.utc).timestamp()) < P1_REF+ assert p1["reference"] == "endDate (scheduled end; the market closed later, after resolution)"+ assert (p2["reference_ts"], p2["reference"]) == (P2_REF, "closedTime (no endDate published)")+++async def test_open_listing_reads_at_most_2000_markets(fetcher: Fetcher) -> None:+ def _page(request: httpx.Request) -> httpx.Response:+ offset, size = int(request.url.params["offset"]), int(request.url.params["limit"])+ return httpx.Response(200, json=[+ _gamma(str(offset + i), f"Q{offset + i}?", '["0.4", "0.6"]', 0.39, 0.41) for i in range(size)+ ])++ route = respx.get(url__regex=GAMMA).mock(side_effect=_page)++ out = await prediction.fetch_polymarket_open(fetcher, limit=10**6)++ assert route.call_count == 20+ assert [int(c.request.url.params["offset"]) for c in route.calls] == list(range(0, 2000, 100))+ assert out["requested"] == 2000 and out["rows_read"] == 2000diff --git a/src/world_intel_mcp/tools/prediction_markets.py b/src/world_intel_mcp/tools/prediction_markets.pyindex 5489b65..f4b97f1 100644--- a/src/world_intel_mcp/tools/prediction_markets.py+++ b/src/world_intel_mcp/tools/prediction_markets.py@@ -25,7 +25,8 @@ TOOLS: list[Tool] = ["24h then lifetime volume. Prices are YES implied probabilities (Kalshi quotes dollars per ""$1 contract; raw bid/ask/last kept). Filter by category (e.g. 'Economics', 'Politics', ""'Elections', 'Financials', 'Climate and Weather') or series ticker (e.g. 'KXFED'). The "- "response states which events were scanned and whether the scan was exhaustive."+ "response states which events were scanned and whether the scan was exhaustive; data "+ "served from expired cache after a failed fetch is marked stale and degraded."),inputSchema={"type": "object",@@ -69,9 +70,13 @@ TOOLS: list[Tool] = [name="intel_prediction_compare",description=("The same event on Kalshi and Polymarket side by side: deterministic matching on normalized "- "titles, quantities, years, end dates, negation and outcome side, with a match_confidence "- "and the reasons for each pair. Below min_confidence a pair is not a match. Returns matched "- "pairs with the price gap, the closest rejected pairs with why, and unmatched counts per venue."+ "titles, quantities, years, end dates, negation, rate actions (cut/raise/hold), directions "+ "(above/below) and outcome side, with a match_confidence (an ordinal score for ranking "+ "pairs, not a probability) and the reasons for each pair. Below min_confidence a pair is "+ "not a match. Returns matched pairs with the price gap, each side's price basis, spread "+ "and last-trade time (a pair is flagged and ranked after comparable ones when either side "+ "is not a two-sided quote midpoint or its spread is wide), the closest rejected pairs with "+ "why, and unmatched counts per venue."),inputSchema={"type": "object",@@ -106,7 +111,9 @@ TOOLS: list[Tool] = ["type": "number","minimum": 0,"maximum": 1,- "description": f"Match threshold 0..1 (default {DEFAULT_MIN_CONFIDENCE})",+ "description": (+ f"Match threshold on the ordinal match score, 0..1 (default {DEFAULT_MIN_CONFIDENCE})"+ ),"default": DEFAULT_MIN_CONFIDENCE,},"limit": {@@ -125,7 +132,9 @@ TOOLS: list[Tool] = ["Recently settled Kalshi and Polymarket markets with their outcome and the YES price at fixed ""offsets before close (from each venue's price-history endpoint), plus a Brier score per venue ""and offset with sample size, selection and exclusions stated. A venue whose price history is "- "unavailable is not scored. The two venues' samples are different markets."+ "unavailable is not scored, and a history served from expired cache is excluded. The two "+ "venues' samples are different markets with different reference times (Kalshi close_time; "+ "Polymarket the earlier of endDate and closedTime), stated in the response."),inputSchema={"type": "object",@@ -142,9 +151,9 @@ TOOLS: list[Tool] = ["maxItems": prediction_cross.MAX_OFFSETS,"items": {"type": "number", "exclusiveMinimum": 0, "maximum": prediction_cross.MAX_OFFSET_HOURS},"description": (- "Hours before the reference time to read the price at (default [24, 168]; up to "- f"{prediction_cross.MAX_OFFSETS} values, each above 0 and at most "- f"{prediction_cross.MAX_OFFSET_HOURS})"+ "Hours before the reference time to read the price at (default [24, 168], also "+ f"for an empty list; up to {prediction_cross.MAX_OFFSETS} values, each above 0 and at "+ f"most {prediction_cross.MAX_OFFSET_HOURS})"),},"kalshi_min_volume": {