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
History store, collection health and four history tools (Phase 29)
Phoenix Agent (mac-studio)3f0e3a1f23c5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6311734..8eaf7f3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,46 @@# Changelog+## Unreleased++### Added: observation history and collection health+- A history store in the cache SQLite file. Every collector source run is a+ capture: source, collected_at, status (ok, degraded or error), duration,+ record count, reason and payload hash. A failed fetch is an error capture+ with its reason and no record count, never an ok capture with zero+ records. An empty payload is degraded, because a quiet period and a+ silent upstream failure look the same.+- Payload bodies are kept once per distinct payload as compressed JSON+ (top-level fetch-time stamps are ignored when hashing). Retention, each+ 0 = keep forever: `WORLD_INTEL_HISTORY_PAYLOAD_DAYS` (default 7) for+ bodies, `WORLD_INTEL_HISTORY_CAPTURE_DAYS` (default 30) for the run log,+ `WORLD_INTEL_HISTORY_DAYS` (default 365) for observations. Measured on a+ full 55-source cycle: about 65-80 KB of new compressed bodies and about+ 14 KB of capture rows per 5-minute cycle.+- Observations with three dates: `observed_at` (from the payload, or null+ when it has none; never the collection time), `published_at` (when the+ payload names a release time) and `collected_at`. Built-in extractors:+ NOAA Kp, USGS per-event magnitude, FRED-sourced central bank rates+ (curated rows are skipped), Yahoo index and commodity quotes (null+ `observed_at`: the payload carries no quote time).+ `history.register_extractor()` is the public API for new sources.+- MCP tools `intel_collection_health`, `intel_capture_history`,+ `intel_series_history` and `intel_revisions`, and the CLI group+ `intel history health|captures|series|revisions`. History accrues only+ while the collector runs.+- The collector records every source outcome of a cycle in one+ transaction. Its summary gains a `history` key (and the CLI summary a+ History line); a history write failure is reported there and in the+ log, and never fails the cycle.+- Expected cadence for health is 300 s (the shipped plist interval);+ `WORLD_INTEL_HISTORY_CADENCE_S` and+ `WORLD_INTEL_HISTORY_CADENCES=source=seconds,...` override it.++### Notes+- The cycle summary's `successes` still counts a source that returned+ `{"error": ...}` (unchanged, pinned by an existing test); that run's+ history capture is an error.+- Tools 139 -> 143.+## 0.11.0 - 2026-10-12Cross-border migration (MCP tools, CLI, collector and a dashboarddiff --git a/README.md b/README.mdindex 77f7474..6cf9025 100644--- a/README.md+++ b/README.md@@ -6,7 +6,7 @@[](https://python.org)[](LICENSE)-Real-time global intelligence across **30+ domains** with **139 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.+Real-time global intelligence across **30+ domains** with **143 MCP tools**, a live ops-center dashboard, a CLI, and a **Qdrant vector store** for enterprise-grade semantic search across accumulated intelligence. All data comes from free, public APIs: no paid subscriptions required.Built for AI agents that need world awareness: market conditions, geopolitical risk, military posture, aircraft-cohort early warning, refugee and migration flows, supply chain disruptions, cyber threats, and more — all queryable via the Model Context Protocol. The vector store enables natural language queries like *"military activity near Taiwan"* or *"cyber threats targeting healthcare"* across all historical data.@@ -63,8 +63,9 @@ Built for AI agents that need world awareness: market conditions, geopolitical r| **Volcanoes** | 1 | Smithsonian GVP weekly activity report || **Tropical Cyclones** | 2 | NHC (Atlantic, E/C Pacific) + JTWC (NW Pacific, N Indian, S Hemisphere) || **Situation Brief** | 1 | Cited situational awareness brief over MCP: bounded server-side overview synthesized via local Ollama, with a mechanically-cited fallback |+| **Collection History** | 4 | Collector run log (per-source health, overdue and failing sources), saved captures with change detection and replay, dated observation series, revisions |-**Total: 139 tools** across 30+ intelligence domains.+**Total: 143 tools** across 30+ intelligence domains.---@@ -130,6 +131,7 @@ intel earthquakes --min-mag 5.0intel migration-surges # year-over-year displacement jumps (UNHCR)intel migration-flows -o Sudanintel status # cache + circuit breaker health+intel history health # per-source collection health from the collector's run log```---@@ -510,6 +512,16 @@ different, openly licensed data source; no ews code is used.|------|-------------|| `intel_situation_brief` | Cited situational awareness brief, generated on demand over MCP: a bounded server-side overview (earthquakes, military flights, ACLED conflict events, wildfires, cyber threats, disease outbreaks, news, space weather, strategic posture, alert digest), synthesized via local Ollama or a mechanically-cited fallback when Ollama is unreachable |+### Collection History (4)+History accrues only while the collector (`intel-collector`) runs; nothing before its first recorded cycle exists. Every observation keeps three dates: `observed_at` (the period the value describes, from the payload, or null when the payload has none), `published_at` (publisher release, when known) and `collected_at` (when this server saved it).++| Tool | Description |+|------|-------------|+| `intel_collection_health` | Per-source health from the collector's run log: last attempt, last success, consecutive failures, overdue against the expected cadence, never-run sources, history storage size; states what it cannot prove (a fresh capture does not mean upstream observations are current) |+| `intel_capture_history` | A source's earlier captures (ok / degraded / error with reason, duration, record count) and whether each changed from the previous one; `capture_id` replays one stored payload |+| `intel_series_history` | One series' observations with all three dates, or the list of available series |+| `intel_revisions` | Values for the same `observed_at` that a later capture changed (USGS magnitude revisions, NOAA Kp updates) |+---## Watching your own area (geofences/AOIs)diff --git a/ROADMAP.md b/ROADMAP.mdindex 7249537..c22ef24 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -571,9 +571,9 @@ dashboard.| Wave | Feature | What it means here | Status ||------|---------|--------------------|--------|-| 1 | Observation history store | Every collector capture saved with `observed_at` (period the data describe), `published_at` (publisher release, when known) and `collected_at` (when we saved it); unchanged payloads stored once; bounded retention; backfill for sources that serve history (FRED CSV) | :red_circle: |-| 1 | Capture history and revisions | Earlier saved copies of a source, and values a later copy revised | :red_circle: |-| 1 | Collection health | Per-source expected cadence; overdue / failing / never-run per source, measured from the run log, not inferred from cache freshness. Says what it cannot prove | :red_circle: |+| 1 | Observation history store | Every collector capture saved with `observed_at` (period the data describe), `published_at` (publisher release, when known) and `collected_at` (when we saved it); unchanged payloads stored once; bounded retention; backfill for sources that serve history (FRED CSV) | :yellow_circle: Unreleased: store, three dates, dedupe, retention and `register_extractor()` done (`history.py`; extractors for Kp, USGS magnitudes, FRED central bank rates, Yahoo quotes); backfill not done |+| 1 | Capture history and revisions | Earlier saved copies of a source, and values a later copy revised | :white_check_mark: Unreleased (`intel_capture_history` with payload replay, `intel_revisions`) |+| 1 | Collection health | Per-source expected cadence; overdue / failing / never-run per source, measured from the run log, not inferred from cache freshness. Says what it cannot prove | :white_check_mark: Unreleased (`intel_collection_health`, `intel history health`) || 1 | Research guide over MCP | MCP resources (guide generated from the live registry and source health, measures glossary, "what this server will not do") and MCP prompts (worked research questions, each naming the tools it needs and the limit to respect). Server exposed no prompts or resources before | :red_circle: || 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: |diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.pyindex af3204c..542403d 100644--- a/src/world_intel_mcp/cli.py+++ b/src/world_intel_mcp/cli.py@@ -2628,5 +2628,240 @@ def aoi_changes(ctx: click.Context, name: str) -> None:_print_data_gaps(data)+# ---------------------------------------------------------------------------+# History (collector run log, captures, series, revisions)+# ---------------------------------------------------------------------------+++def _with_history_store(fn: Any) -> dict:+ from .history import HistoryStore++ store = HistoryStore(_get_fetcher().cache.db_path)+ try:+ return fn(store)+ finally:+ store.close()++[email protected](name="history")+def history_group() -> None:+ """Saved collector history: health, captures, series, revisions.++ History accrues only while the collector (intel-collector) runs.+ """+++@history_group.command(name="health")[email protected]("--source", default=None, help="One collector source name")[email protected]_context+def history_health(ctx: click.Context, source: str | None) -> None:+ """Per-source collection health from the collector's run log."""+ from .collector import SOURCES++ roster = [name for name, _, _, _ in SOURCES]+ data = _with_history_store(+ lambda s: s.collection_health(roster, source=source)+ )+ if _bail_on_error(ctx, data):+ return++ table = Table(+ title=f"Collection health (cadence {data['default_cadence_s']:g} s, "+ f"overdue past {data['overdue_multiple']:g}x)",+ box=box.SIMPLE_HEAVY,+ )+ table.add_column("Source", style="bold")+ table.add_column("State")+ table.add_column("Last attempt")+ table.add_column("Last success")+ table.add_column("Fails", justify="right")+ table.add_column("Latest observed")+ table.add_column("Reason")+ styles = {"ok": "green", "degraded": "yellow", "never_run": "dim"}+ for row in data["sources"]:+ state = row["state"]+ table.add_row(+ _cell(row["source"]),+ Text(state, style=styles.get(state, "red")),+ _cell(row.get("last_attempt_at") or "-"),+ _cell(row.get("last_success_at") or "-"),+ str(row.get("consecutive_failures", "-")),+ _cell(row.get("latest_observed_at") or "-"),+ _cell(row.get("last_reason") or ""),+ )+ console.print(table)+ counts = ", ".join(f"{k} {v}" for k, v in sorted(data["state_counts"].items()))+ storage = data["storage"]+ console.print(+ f"States: {counts}. Stored: {storage['captures']} captures, "+ f"{storage['payload_bodies']} payload bodies "+ f"({storage['payload_bytes_compressed']:,} bytes compressed), "+ f"{storage['observations']} observations in {storage['series']} series."+ )+ for line in data["cannot_prove"]:+ console.print(f"[yellow]Cannot prove:[/yellow] {escape(line)}")+++@history_group.command(name="captures")[email protected]("source")[email protected]("--limit", default=20, type=int, help="Captures to show")+ "--capture-id", default=None, type=int, help="Show one capture with its payload"+)[email protected]_context+def history_captures(+ ctx: click.Context, source: str, limit: int, capture_id: int | None+) -> None:+ """A source's earlier captures, newest first."""+ data = _with_history_store(+ lambda s: s.capture_history(source, limit=limit, capture_id=capture_id)+ )+ if _bail_on_error(ctx, data):+ return++ if "capture" in data:+ cap = data["capture"]+ console.print(+ f"Capture {cap['capture_id']} of [bold]{escape(source)}[/bold] at "+ f"{cap['collected_at']}: {cap['status']} ({cap['change'] or 'no payload'})"+ )+ if cap.get("reason"):+ console.print(f"[yellow]Reason:[/yellow] {escape(str(cap['reason']))}")+ if cap.get("payload_note"):+ console.print(f"[yellow]Gap:[/yellow] {escape(cap['payload_note'])}")+ if cap.get("payload") is not None:+ _print_json(cap["payload"])+ return++ captures = data["captures"]+ if not captures:+ _print_data_gaps(data)+ return+ table = Table(+ title=f"Captures of {escape(source)} ({data['total_captures']} total, "+ f"{data['changed_captures']} changed, {data['distinct_payloads']} distinct)",+ box=box.SIMPLE_HEAVY,+ )+ table.add_column("ID", justify="right")+ table.add_column("Collected")+ table.add_column("Status")+ table.add_column("Duration s", justify="right")+ table.add_column("Records", justify="right")+ table.add_column("Change")+ table.add_column("Reason")+ for cap in captures:+ table.add_row(+ str(cap["capture_id"]),+ cap["collected_at"],+ cap["status"],+ "-" if cap["duration_s"] is None else f"{cap['duration_s']:.2f}",+ "-" if cap["record_count"] is None else str(cap["record_count"]),+ cap["change"] or "-",+ _cell(cap.get("reason") or ""),+ )+ console.print(table)+ console.print(f"[dim]{escape(data['note'])}[/dim]")+++@history_group.command(name="series")[email protected]("series_key", required=False)[email protected]("--source", default=None, help="Filter the listing to one source")[email protected]("--limit", default=None, type=int, help="Rows to show")[email protected]_context+def history_series(+ ctx: click.Context, series_key: str | None, source: str | None, limit: int | None+) -> None:+ """One series' observations (three dates), or the list of series."""+ default_limit = 100 if series_key else 200+ data = _with_history_store(+ lambda s: s.series_history(+ series_key, source=source, limit=limit or default_limit+ )+ )+ if _bail_on_error(ctx, data):+ return++ if series_key is None:+ if not data["series"]:+ _print_data_gaps(data)+ return+ table = Table(+ title=f"Series ({data['total_series']})", box=box.SIMPLE_HEAVY+ )+ table.add_column("Series", style="bold")+ table.add_column("Label")+ table.add_column("Points", justify="right")+ table.add_column("Observed from")+ table.add_column("Observed to")+ table.add_column("Last collected")+ for row in data["series"]:+ table.add_row(+ _cell(row["series_key"]),+ _cell(row.get("label") or ""),+ str(row["points"]),+ _cell(row.get("first_observed_at") or "unknown"),+ _cell(row.get("last_observed_at") or "unknown"),+ row["last_collected_at"],+ )+ console.print(table)+ return++ table = Table(title=escape(series_key), box=box.SIMPLE_HEAVY)+ table.add_column("Observed")+ table.add_column("Published")+ table.add_column("Collected")+ table.add_column("Value", justify="right")+ table.add_column("Unit")+ for obs in data["observations"]:+ table.add_row(+ _cell(obs["observed_at"] or "unknown"),+ _cell(obs["published_at"] or "unknown"),+ obs["collected_at"],+ f"{obs['value']:g}",+ _cell(obs.get("unit") or ""),+ )+ console.print(table)+ _print_data_gaps(data)+++@history_group.command(name="revisions")[email protected]("--source", default=None, help="Filter to one source")[email protected]("--series", "series_key", default=None, help="Filter to one series")[email protected]("--limit", default=100, type=int, help="Revisions to show")[email protected]_context+def history_revisions(+ ctx: click.Context, source: str | None, series_key: str | None, limit: int+) -> None:+ """Values a later capture changed for the same observed_at."""+ data = _with_history_store(+ lambda s: s.revisions(source=source, series_key=series_key, limit=limit)+ )+ if _bail_on_error(ctx, data):+ return++ if not data["revisions"]:+ console.print("[yellow]No revisions seen between saved captures[/yellow]")+ else:+ table = Table(title=f"Revisions ({data['count']})", box=box.SIMPLE_HEAVY)+ table.add_column("Series", style="bold")+ table.add_column("Observed")+ table.add_column("Was", justify="right")+ table.add_column("Now", justify="right")+ table.add_column("Delta", justify="right")+ table.add_column("Revised at")+ for rev in data["revisions"]:+ table.add_row(+ _cell(rev["series_key"]),+ _cell(rev["observed_at"]),+ f"{rev['previous_value']:g}",+ f"{rev['revised_value']:g}",+ f"{rev['delta']:+g}",+ rev["revised_collected_at"],+ )+ console.print(table)+ for line in data["cannot_prove"]:+ console.print(f"[yellow]Cannot prove:[/yellow] {escape(line)}")++if __name__ == "__main__":main()diff --git a/src/world_intel_mcp/collector.py b/src/world_intel_mcp/collector.pyindex 4211562..b9ed67f 100644--- a/src/world_intel_mcp/collector.py+++ b/src/world_intel_mcp/collector.py@@ -4,6 +4,11 @@ Fetches all intelligence sources in parallel and stores results in theQdrant vector store. Runs independently of the MCP server and dashboard,ensuring data accumulates 24/7 for semantic search and historical analysis.+Every source outcome of a cycle (ok, degraded or error, with duration and+payload hash) is also written to the history store (``history.py``) in the+cache DB, in one transaction per cycle. That run log is what+``intel_collection_health`` and the other history tools read.+Usage:intel-collector # Single collection cycleintel-collector --daemon # Run every 5 minutes@@ -15,6 +20,7 @@ import asyncioimport loggingimport osimport signal+import sqlite3import sysimport timefrom pathlib import Path@@ -32,6 +38,7 @@ logger = logging.getLogger("world-intel-collector")from .cache import Cachefrom .circuit_breaker import CircuitBreakerfrom .fetcher import Fetcher+from .history import HistoryStore, SourceOutcomefrom .vector_store import VectorStore# All fetchable sources grouped by domain.@@ -209,6 +216,34 @@ def _import_fetch_fn(module_path: str, fn_name: str):return getattr(mod, fn_name)+def _record_history(fetcher: Fetcher, outcomes: list) -> dict:+ """Write one cycle's outcomes to the history store in the fetcher's+ cache DB. A history failure is reported in the cycle summary and the+ log; it never fails the cycle itself."""+ db_path = getattr(getattr(fetcher, "cache", None), "db_path", None)+ if db_path is None:+ logger.warning("History not recorded: fetcher has no cache db_path")+ return {+ "recorded": 0,+ "error": "fetcher has no cache db_path; history not recorded",+ }+ try:+ store = HistoryStore(db_path)+ try:+ return store.record_cycle(outcomes)+ finally:+ store.close()+ except (sqlite3.Error, OSError) as exc:+ logger.warning("History write failed: %s", exc)+ return {"recorded": 0, "error": f"history write failed: {exc}"}+ except Exception as exc: # a history bug must not cost the cycle+ logger.exception("History write failed unexpectedly")+ return {+ "recorded": 0,+ "error": f"history write failed: {type(exc).__name__}: {exc}",+ }++async def collect_once(fetcher: Fetcher,vector_store: VectorStore,@@ -224,8 +259,12 @@ async def collect_once(s for s in SOURCES if source_filter is None or s[0] in source_filter]+ # Per-source wall time and finish time, for the history run log.+ timings: dict[str, tuple[float, float]] = {}+async def _fetch_one(name: str, module_path: str, fn_name: str, kwargs: dict):budget = SOURCE_TIMEOUTS.get(name, timeout)+ t0 = time.monotonic()try:fn = _import_fetch_fn(module_path, fn_name)result = await asyncio.wait_for(fn(fetcher, **kwargs), timeout=budget)@@ -234,6 +273,8 @@ async def collect_once(return name, None, f"timeout ({budget}s)"except Exception as exc:return name, None, str(exc)[:120]+ finally:+ timings[name] = (time.monotonic() - t0, time.time())tasks = [_fetch_one(name, mod, fn, kw) for name, mod, fn, kw in sources_to_run]@@ -242,6 +283,21 @@ async def collect_once(successes = 0failures = 0errors = []+ outcomes = []++ for (source_name, _, _, _), item in zip(sources_to_run, results):+ duration, finished = timings.get(source_name, (None, time.time()))+ if isinstance(item, BaseException):+ reason = str(item)[:500] or repr(item)+ outcomes.append(+ SourceOutcome(source_name, finished, duration, error=reason)+ )+ else:+ outcomes.append(+ SourceOutcome(+ source_name, finished, duration, payload=item[1], error=item[2]+ )+ )for item in results:if isinstance(item, Exception):@@ -263,6 +319,8 @@ async def collect_once(else:failures += 1+ history = _record_history(fetcher, outcomes)+elapsed = time.time() - startstats = await vector_store.collection_stats()@@ -273,6 +331,7 @@ async def collect_once("failures": failures,"errors": errors[:10],"vector_store_points": stats.get("points_count", 0),+ "history": history,}logger.info(@@ -399,6 +458,17 @@ def main():)print(f" Time: {summary['cycle_time_s']}s")print(f" Vector store: {summary['vector_store_points']} points")+ history = summary.get("history") or {}+ if history.get("error"):+ print(f" History: NOT recorded ({history['error']})")+ elif history:+ counts = history.get("status_counts", {})+ print(+ f" History: {history.get('recorded', 0)} captures "+ f"(ok {counts.get('ok', 0)}, degraded {counts.get('degraded', 0)}, "+ f"error {counts.get('error', 0)}), "+ f"{history.get('observations_stored', 0)} new observations"+ )if summary["errors"]:print(f" Errors ({len(summary['errors'])}):")for e in summary["errors"]:diff --git a/src/world_intel_mcp/history.py b/src/world_intel_mcp/history.pynew file mode 100644index 0000000..9ca1685--- /dev/null+++ b/src/world_intel_mcp/history.py@@ -0,0 +1,1022 @@+"""Observation history store and collection health (ROADMAP Phase 29).++The cache keeps one latest value per key, so on its own nothing can be+correlated, revised or replayed. This module keeps what the collector+saw, in three tables of the same SQLite file the process-wide ``Cache``+opened (pass ``cache.db_path`` in, as ``analysis/aoi.py`` and+``sources/jet_cohort.py`` do, so this lands in the literal file the cache+settled on, fallback path included):++- ``history_captures``: one row per collector source run, the run log.+ ``status`` is ``ok``, ``degraded`` or ``error``; a failed fetch is an+ ``error`` row with a reason and a null record count, never an ``ok``+ row with zero records. A payload with no records is ``degraded``,+ because a quiet period and a silent upstream failure look the same.+- ``history_payloads``: the payload body as zlib-compressed JSON, stored+ once per ``(source, payload_hash)``. The hash ignores the top-level+ fetch-time stamps in ``VOLATILE_KEYS`` (they change on every call while+ the data do not); the body kept is the first capture's.+- ``history_observations``: dated numeric points pulled out of payloads by+ per-source extractors, each with three dates. ``observed_at`` is the+ period or instant the value describes, taken from the payload; when a+ payload carries no observation date it is NULL, never ``collected_at``.+ ``published_at`` is the publisher's release time when the payload names+ one, else NULL. ``collected_at`` is when this server saved the capture.+ A point is stored when it is new or its value differs from the last+ stored value for the same series and ``observed_at``, so successive+ rows for one ``(series_key, observed_at)`` are revisions.++History accrues only while the collector runs: nothing is backfilled, and+a source the collector does not run reads ``never_run``.++Registering an extractor (the public API)::++ from world_intel_mcp.history import Observation, register_extractor++ @register_extractor("my_source") # the collector SOURCES name+ def _extract(payload: dict) -> list[Observation]:+ return [Observation("rate", 4.33, observed_at="2026-10-15", unit="percent")]++The store prefixes each ``series_key`` with the source name+(``my_source:rate``), so extractors cannot collide. ``observed_at`` must be+``YYYY``, ``YYYY-MM``, ``YYYY-MM-DD`` or a timezone-aware ISO 8601+instant (use ``normalize_observed_at`` to convert, with ``assume_utc=True``+only when the publisher documents UTC); a point with an unparseable date+or a non-finite value is skipped and counted in the capture's+``extract_error``. Register at import time of your source module: the+collector imports a source's module before it records that source's+capture. A registered extractor that finds nothing in a non-error payload+marks the capture ``degraded``.++Retention, each ``0`` = keep forever, pruned at the end of every recorded+cycle in the same transaction:++- ``WORLD_INTEL_HISTORY_PAYLOAD_DAYS`` (default 7) bounds payload bodies by+ last sighting. Measured 2026-10-17 on a full 55-source cycle: about+ 65-80 KB of new compressed bodies per 5-minute cycle (crypto quotes with+ sparklines, the domestic flight snapshot and the news feed change every+ cycle), so about 20 MB a day.+- ``WORLD_INTEL_HISTORY_CAPTURE_DAYS`` (default 30) bounds the run log:+ 55 capture rows per cycle at about 250 bytes each with indexes, about+ 4 MB a day.+- ``WORLD_INTEL_HISTORY_DAYS`` (default 365) bounds observations, which are+ stored only when new or changed. An observation can outlive the capture+ that produced it; its ``capture_id`` then names a pruned capture.++Gaps / not covered:+- No backfill: sources that serve history (FRED CSV) are not replayed into+ the store; only what the collector sees from the first recorded cycle on.+- ``published_at`` is NULL for every built-in extractor: none of their+ payloads names a release time.+- ``record_count`` is a size hint (the payload's longest top-level list,+ else its integer ``count``), not a semantic count; payloads shaped as+ nested dicts read NULL.+- Degradation is read from top-level ``_stale`` / ``degraded`` markers;+ a source that degrades without marking its payload reads ``ok`` unless+ it is empty or its extractor finds nothing.+"""++from __future__ import annotations++import hashlib+import json+import logging+import math+import os+import re+import sqlite3+import time+import zlib+from dataclasses import dataclass, field+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Callable, Iterable++logger = logging.getLogger("world-intel-mcp.history")++# Top-level keys that carry this server's fetch time, not upstream data.+VOLATILE_KEYS = frozenset({"timestamp", "fetched_at", "generated_at", "_stale_age_seconds"})++# Expected seconds between collector attempts. The shipped launchd plist+# and the daemon default both run every 300 s; an operator running a+# different --interval sets WORLD_INTEL_HISTORY_CADENCE_S.+DEFAULT_CADENCE_S = 300.0+# Per-source overrides. Every source runs every cycle today, so this is+# empty in code; a deployment that runs some sources from a second, slower+# collector sets WORLD_INTEL_HISTORY_CADENCES="aoi_digest=900,news_feed=600".+SOURCE_CADENCES: dict[str, float] = {}+# A source is overdue when its last delivered payload is older than this+# many cadences.+OVERDUE_MULTIPLE = 3.0++_DEFAULT_PAYLOAD_DAYS = 7.0+_DEFAULT_CAPTURE_DAYS = 30.0+_DEFAULT_HISTORY_DAYS = 365.0+_MAX_LIMIT = 1000++HISTORY_ACCRUAL_NOTE = (+ "History accrues only while the collector (intel-collector) runs; "+ "nothing before its first recorded cycle exists here."+)+++# ---------------------------------------------------------------------------+# Extractor registry+# ---------------------------------------------------------------------------+++@dataclass(frozen=True)+class Observation:+ """One numeric point an extractor read from a payload."""++ series_key: str+ value: float+ observed_at: str | None = None+ unit: str | None = None+ label: str | None = None+ published_at: str | None = None+++Extractor = Callable[[Any], Iterable[Observation]]+_EXTRACTORS: dict[str, Extractor] = {}+++def register_extractor(+ source: str, fn: Extractor | None = None, *, replace: bool = False+) -> Any:+ """Register ``fn`` as the extractor for collector source ``source``.++ Usable as ``register_extractor("src", fn)`` or as a decorator. A second+ registration for the same source raises unless ``replace=True``.+ """++ def _register(f: Extractor) -> Extractor:+ existing = _EXTRACTORS.get(source)+ if existing is not None and existing is not f and not replace:+ raise ValueError(f"an extractor is already registered for {source!r}")+ _EXTRACTORS[source] = f+ return f++ return _register(fn) if fn is not None else _register+++def registered_extractors() -> dict[str, Extractor]:+ """Snapshot of the source -> extractor map."""+ return dict(_EXTRACTORS)+++_DATE_PERIOD = re.compile(r"\d{4}(-\d{2}(-\d{2})?)?")+++def normalize_observed_at(value: Any, *, assume_utc: bool = False) -> str | None:+ """Payload date -> stored form, or None when it cannot be read.++ ``YYYY``, ``YYYY-MM`` and ``YYYY-MM-DD`` periods are kept as written.+ An ISO 8601 instant becomes ``YYYY-MM-DDTHH:MM:SSZ`` in UTC. A naive+ instant (no offset) is only accepted with ``assume_utc=True``.+ """+ if value is None or isinstance(value, bool):+ return None+ text = str(value).strip()+ if not text:+ return None+ if _DATE_PERIOD.fullmatch(text):+ return text+ try:+ parsed = datetime.fromisoformat(text.replace("Z", "+00:00").replace(" ", "T", 1))+ except ValueError:+ return None+ if parsed.tzinfo is None:+ if not assume_utc:+ return None+ parsed = parsed.replace(tzinfo=timezone.utc)+ return parsed.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _finite(value: Any) -> float | None:+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ return None+ number = float(value)+ return number if math.isfinite(number) else None+++def _slug(text: str) -> str:+ return re.sub(r"[^a-z0-9]+", "_", text.lower()).strip("_")+++@register_extractor("space_weather")+def _extract_space_weather(payload: dict) -> list[Observation]:+ """NOAA planetary K-index rows. SWPC time tags are UTC by product spec."""+ points = []+ for row in payload.get("kp_recent") or []:+ kp = _finite(row.get("kp"))+ observed = normalize_observed_at(row.get("time"), assume_utc=True)+ if kp is None or observed is None:+ continue+ points.append(+ Observation("kp", kp, observed_at=observed, unit="Kp index",+ label="NOAA planetary K-index")+ )+ return points+++@register_extractor("earthquakes")+def _extract_earthquakes(payload: dict) -> list[Observation]:+ """Per-event USGS magnitude at the event's origin time. USGS revises+ magnitudes after review, which ``revisions`` then shows."""+ points = []+ for quake in payload.get("earthquakes") or []:+ magnitude = _finite(quake.get("magnitude"))+ observed = normalize_observed_at(quake.get("time"))+ event_id = quake.get("id")+ if magnitude is None or observed is None or not event_id:+ continue+ points.append(+ Observation(f"{event_id}:magnitude", magnitude, observed_at=observed,+ unit="magnitude", label=quake.get("place"))+ )+ return points+++@register_extractor("central_bank_rates")+def _extract_central_bank_rates(payload: dict) -> list[Observation]:+ """FRED-sourced policy rates only, dated by the FRED observation date.+ Curated rows are values written into this repo, not observations this+ capture fetched, so they are skipped."""+ points = []+ for rate in payload.get("rates") or []:+ if rate.get("source") != "fred":+ continue+ value = _finite(rate.get("rate"))+ observed = normalize_observed_at(rate.get("as_of"))+ label = rate.get("label") or rate.get("bank")+ if value is None or observed is None or not label:+ continue+ points.append(+ Observation(_slug(label), value, observed_at=observed, unit="percent",+ label=f"{rate.get('bank')}: {label}")+ )+ return points+++def _quote_extractor(list_key: str, label_key: str, unit_key: str | None):+ def _extract(payload: dict) -> list[Observation]:+ """Yahoo quotes. The source module keeps price and change only, not+ the quote time, so observed_at is NULL (unknown), not collected_at."""+ points = []+ for quote in payload.get(list_key) or []:+ price = _finite(quote.get("price"))+ symbol = quote.get("symbol")+ if price is None or not symbol:+ continue+ points.append(+ Observation(f"{symbol}:price", price, observed_at=None,+ unit=quote.get(unit_key) if unit_key else None,+ label=quote.get(label_key) or symbol)+ )+ return points++ return _extract+++register_extractor("market_quotes", _quote_extractor("quotes", "symbol", "currency"))+register_extractor("commodity_quotes", _quote_extractor("commodities", "name", None))+++# ---------------------------------------------------------------------------+# Capture classification+# ---------------------------------------------------------------------------+++@dataclass+class SourceOutcome:+ """What one collector source run produced, handed to ``record_cycle``."""++ source: str+ collected_at: float+ duration_s: float | None = None+ payload: Any = None+ error: str | None = None+++@dataclass+class _Classified:+ status: str+ reason: str | None+ record_count: int | None+ observations: list[Observation] = field(default_factory=list)+ extract_error: str | None = None+ extracted: int | None = None+++def record_count(payload: Any) -> int | None:+ """Size hint: longest top-level list, else an integer ``count``."""+ if isinstance(payload, list):+ return len(payload)+ if not isinstance(payload, dict):+ return None+ lengths = [len(v) for v in payload.values() if isinstance(v, list)]+ if lengths:+ return max(lengths)+ count = payload.get("count")+ if isinstance(count, int) and not isinstance(count, bool):+ return count+ return None+++def payload_hash(payload: Any) -> str:+ """sha256 of the canonical JSON, top-level ``VOLATILE_KEYS`` removed."""+ if isinstance(payload, dict):+ payload = {k: v for k, v in payload.items() if k not in VOLATILE_KEYS}+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)+ return hashlib.sha256(canonical.encode()).hexdigest()+++def _extract(source: str, payload: Any) -> tuple[list[Observation], str | None, int | None]:+ extractor = _EXTRACTORS.get(source)+ if extractor is None:+ return [], None, None+ try:+ raw = list(extractor(payload))+ except Exception as exc: # an extractor bug must not lose the capture+ logger.warning("History extractor for %s failed: %s", source, exc)+ return [], f"extractor raised: {type(exc).__name__}: {str(exc)[:200]}", None+ valid: list[Observation] = []+ skipped = 0+ for obs in raw:+ if (+ not isinstance(obs, Observation)+ or not isinstance(obs.series_key, str)+ or not obs.series_key+ or _finite(obs.value) is None+ or (obs.observed_at is not None and normalize_observed_at(obs.observed_at) != obs.observed_at)+ or (obs.published_at is not None and normalize_observed_at(obs.published_at) != obs.published_at)+ ):+ skipped += 1+ continue+ valid.append(obs)+ note = f"{skipped} invalid point(s) skipped" if skipped else None+ return valid, note, len(raw)+++def classify(outcome: SourceOutcome) -> _Classified:+ """Status, reason and observations for one source run."""+ if outcome.error is not None:+ return _Classified("error", outcome.error[:500], None)+ payload = outcome.payload+ if payload is None:+ return _Classified("error", "fetch returned no payload", None)+ if isinstance(payload, dict) and payload.get("error"):+ return _Classified("error", str(payload["error"])[:500], None)++ count = record_count(payload)+ observations, extract_error, extracted = _extract(outcome.source, payload)+ status, reason = "ok", None+ if isinstance(payload, dict) and payload.get("_stale"):+ age = payload.get("_stale_age_seconds")+ status, reason = "degraded", (+ f"served stale cache (age {age} s)" if age is not None else "served stale cache"+ )+ elif isinstance(payload, dict) and (+ payload.get("degraded") is True or payload.get("status") == "degraded"+ ):+ status, reason = "degraded", "payload marked degraded"+ elif count == 0:+ status, reason = "degraded", (+ "payload has no records: a quiet period and a silent upstream "+ "failure look the same here"+ )+ elif extracted is not None and not observations:+ status, reason = "degraded", "registered extractor found no measures in this payload" + (+ f" ({extract_error})" if extract_error else ""+ )+ return _Classified(status, reason, count, observations, extract_error, extracted)+++# ---------------------------------------------------------------------------+# Store+# ---------------------------------------------------------------------------+++def _env_days(name: str, default: float) -> float:+ raw = os.environ.get(name)+ if raw is None or not raw.strip():+ return default+ try:+ days = float(raw)+ except ValueError:+ logger.warning("%s=%r is not a number; using %s", name, raw, default)+ return default+ if not math.isfinite(days) or days < 0:+ logger.warning("%s=%r must be >= 0; using %s", name, raw, default)+ return default+ return days+++def retention_days() -> dict[str, float]:+ """Configured retention (bodies, run log, observations); 0 = keep forever."""+ return {+ "payload_days": _env_days("WORLD_INTEL_HISTORY_PAYLOAD_DAYS", _DEFAULT_PAYLOAD_DAYS),+ "capture_days": _env_days("WORLD_INTEL_HISTORY_CAPTURE_DAYS", _DEFAULT_CAPTURE_DAYS),+ "history_days": _env_days("WORLD_INTEL_HISTORY_DAYS", _DEFAULT_HISTORY_DAYS),+ }+++def cadence_config() -> tuple[float, dict[str, float]]:+ """(default cadence, per-source overrides) after env overrides."""+ default = DEFAULT_CADENCE_S+ raw = os.environ.get("WORLD_INTEL_HISTORY_CADENCE_S")+ if raw:+ try:+ value = float(raw)+ if value > 0 and math.isfinite(value):+ default = value+ else:+ logger.warning("WORLD_INTEL_HISTORY_CADENCE_S=%r must be > 0", raw)+ except ValueError:+ logger.warning("WORLD_INTEL_HISTORY_CADENCE_S=%r is not a number", raw)+ overrides = dict(SOURCE_CADENCES)+ for part in (os.environ.get("WORLD_INTEL_HISTORY_CADENCES") or "").split(","):+ name, sep, secs = part.partition("=")+ if not sep:+ continue+ try:+ value = float(secs)+ except ValueError:+ logger.warning("Ignoring cadence override %r", part)+ continue+ if value > 0 and math.isfinite(value) and name.strip():+ overrides[name.strip()] = value+ return default, overrides+++def _iso(ts: float | None) -> str | None:+ if ts is None:+ return None+ return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def _clamp(limit: Any, default: int) -> int:+ try:+ value = int(limit)+ except (TypeError, ValueError):+ return default+ return max(1, min(_MAX_LIMIT, value))+++class HistoryStore:+ """Capture log, payload bodies and observations in the cache DB."""++ def __init__(self, db_path: Path | str):+ self.db_path = Path(db_path)+ self.db_path.parent.mkdir(parents=True, exist_ok=True)+ self._conn = sqlite3.connect(str(self.db_path), timeout=10)+ self._conn.execute("PRAGMA journal_mode=WAL")+ self._conn.execute("PRAGMA busy_timeout=5000")+ self._conn.execute("PRAGMA synchronous=NORMAL")+ self._conn.executescript(+ """+ CREATE TABLE IF NOT EXISTS history_captures (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ source TEXT NOT NULL,+ collected_at REAL NOT NULL,+ status TEXT NOT NULL CHECK (status IN ('ok', 'degraded', 'error')),+ duration_s REAL,+ record_count INTEGER,+ error TEXT,+ payload_hash TEXT,+ changed INTEGER,+ observations_extracted INTEGER,+ observations_stored INTEGER,+ extract_error TEXT+ );+ CREATE INDEX IF NOT EXISTS idx_history_captures_source+ ON history_captures(source, collected_at);+ CREATE INDEX IF NOT EXISTS idx_history_captures_time+ ON history_captures(collected_at);+ CREATE TABLE IF NOT EXISTS history_payloads (+ source TEXT NOT NULL,+ payload_hash TEXT NOT NULL,+ first_seen_at REAL NOT NULL,+ last_seen_at REAL NOT NULL,+ raw_bytes INTEGER NOT NULL,+ body BLOB NOT NULL,+ PRIMARY KEY (source, payload_hash)+ );+ CREATE INDEX IF NOT EXISTS idx_history_payloads_seen+ ON history_payloads(last_seen_at);+ CREATE TABLE IF NOT EXISTS history_observations (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ capture_id INTEGER NOT NULL,+ source TEXT NOT NULL,+ series_key TEXT NOT NULL,+ observed_at TEXT,+ published_at TEXT,+ collected_at REAL NOT NULL,+ value REAL NOT NULL,+ unit TEXT,+ label TEXT+ );+ CREATE INDEX IF NOT EXISTS idx_history_obs_series+ ON history_observations(series_key, observed_at, collected_at);+ CREATE INDEX IF NOT EXISTS idx_history_obs_source+ ON history_observations(source, collected_at);+ CREATE INDEX IF NOT EXISTS idx_history_obs_time+ ON history_observations(collected_at);+ """+ )+ self._conn.commit()++ def close(self) -> None:+ self._conn.close()++ # -- writes -------------------------------------------------------------++ def record_cycle(self, outcomes: list[SourceOutcome], now: float | None = None) -> dict:+ """Record every outcome of one collector cycle in one transaction,+ then prune past retention in the same transaction."""+ conn = self._conn+ counts = {"ok": 0, "degraded": 0, "error": 0}+ payloads_stored = 0+ observations_stored = 0+ with conn:+ for outcome in outcomes:+ c = classify(outcome)+ counts[c.status] += 1+ digest = changed = body = None+ if c.status != "error":+ try:+ digest = payload_hash(outcome.payload)+ body = json.dumps(+ outcome.payload, separators=(",", ":"), default=str+ ).encode()+ except (TypeError, ValueError) as exc:+ # One unserializable payload (mixed-type dict keys,+ # a reference cycle) must not cost the cycle's+ # other captures; the capture says what was lost.+ digest = body = None+ note = f"payload not stored in history: {type(exc).__name__}: {exc}"+ c.reason = (f"{c.reason}; {note}" if c.reason else note)[:500]+ if digest is not None and body is not None:+ prev = conn.execute(+ "SELECT payload_hash FROM history_captures "+ "WHERE source = ? AND payload_hash IS NOT NULL "+ "ORDER BY collected_at DESC, id DESC LIMIT 1",+ (outcome.source,),+ ).fetchone()+ changed = None if prev is None else int(prev[0] != digest)+ inserted = conn.execute(+ "INSERT OR IGNORE INTO history_payloads "+ "(source, payload_hash, first_seen_at, last_seen_at, raw_bytes, body) "+ "VALUES (?, ?, ?, ?, ?, ?)",+ (outcome.source, digest, outcome.collected_at, outcome.collected_at,+ len(body), zlib.compress(body, 6)),+ ).rowcount+ if inserted:+ payloads_stored += 1+ else:+ conn.execute(+ "UPDATE history_payloads SET last_seen_at = MAX(last_seen_at, ?) "+ "WHERE source = ? AND payload_hash = ?",+ (outcome.collected_at, outcome.source, digest),+ )+ capture_id = conn.execute(+ "INSERT INTO history_captures (source, collected_at, status, duration_s, "+ "record_count, error, payload_hash, changed, observations_extracted, "+ "extract_error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ (outcome.source, outcome.collected_at, c.status,+ None if outcome.duration_s is None else round(outcome.duration_s, 3),+ c.record_count, c.reason, digest, changed, c.extracted, c.extract_error),+ ).lastrowid+ stored = self._store_observations(capture_id, outcome, c.observations)+ observations_stored += stored+ if c.extracted is not None:+ conn.execute(+ "UPDATE history_captures SET observations_stored = ? WHERE id = ?",+ (stored, capture_id),+ )+ pruned = self._prune(now if now is not None else time.time())+ return {+ "recorded": len(outcomes),+ "status_counts": counts,+ "payloads_stored": payloads_stored,+ "observations_stored": observations_stored,+ "pruned": pruned,+ "db_path": str(self.db_path),+ }++ def _store_observations(+ self, capture_id: int, outcome: SourceOutcome, observations: list[Observation]+ ) -> int:+ stored = 0+ for obs in observations:+ key = f"{outcome.source}:{obs.series_key}"+ last = self._conn.execute(+ "SELECT value FROM history_observations "+ "WHERE series_key = ? AND observed_at IS ? "+ "ORDER BY collected_at DESC, id DESC LIMIT 1",+ (key, obs.observed_at),+ ).fetchone()+ value = float(obs.value)+ if last is not None and last[0] == value:+ continue+ self._conn.execute(+ "INSERT INTO history_observations (capture_id, source, series_key, "+ "observed_at, published_at, collected_at, value, unit, label) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",+ (capture_id, outcome.source, key, obs.observed_at, obs.published_at,+ outcome.collected_at, value, obs.unit,+ None if obs.label is None else str(obs.label)[:300]),+ )+ stored += 1+ return stored++ def _prune(self, now: float) -> dict:+ days = retention_days()+ pruned = {"payloads": 0, "captures": 0, "observations": 0}+ if days["payload_days"] > 0:+ cutoff = now - days["payload_days"] * 86400+ pruned["payloads"] = self._conn.execute(+ "DELETE FROM history_payloads WHERE last_seen_at < ?", (cutoff,)+ ).rowcount+ if days["capture_days"] > 0:+ cutoff = now - days["capture_days"] * 86400+ pruned["captures"] = self._conn.execute(+ "DELETE FROM history_captures WHERE collected_at < ?", (cutoff,)+ ).rowcount+ if days["history_days"] > 0:+ cutoff = now - days["history_days"] * 86400+ pruned["observations"] = self._conn.execute(+ "DELETE FROM history_observations WHERE collected_at < ?", (cutoff,)+ ).rowcount+ return pruned++ # -- reads --------------------------------------------------------------++ def storage_stats(self) -> dict:+ conn = self._conn+ captures = conn.execute("SELECT COUNT(*) FROM history_captures").fetchone()[0]+ payloads, compressed, raw = conn.execute(+ "SELECT COUNT(*), COALESCE(SUM(LENGTH(body)), 0), COALESCE(SUM(raw_bytes), 0) "+ "FROM history_payloads"+ ).fetchone()+ observations = conn.execute("SELECT COUNT(*) FROM history_observations").fetchone()[0]+ series = conn.execute(+ "SELECT COUNT(DISTINCT series_key) FROM history_observations"+ ).fetchone()[0]+ first = conn.execute("SELECT MIN(collected_at) FROM history_captures").fetchone()[0]+ return {+ "captures": captures,+ "payload_bodies": payloads,+ "payload_bytes_compressed": compressed,+ "payload_bytes_raw": raw,+ "observations": observations,+ "series": series,+ "first_capture_at": _iso(first),+ "retention": retention_days(),+ "db_path": str(self.db_path),+ }++ def collection_health(+ self, roster: Iterable[str], source: str | None = None, now: float | None = None+ ) -> dict:+ """Per-source attempt / success / failure state from the run log."""+ now = time.time() if now is None else now+ default_cadence, overrides = cadence_config()+ roster = list(roster)+ known = set(roster)+ conn = self._conn+ logged = [r[0] for r in conn.execute("SELECT DISTINCT source FROM history_captures")]+ names = roster + sorted(set(logged) - known)+ if source is not None:+ if source not in names:+ return {+ "error": f"unknown source {source!r}: not a collector source and never captured",+ "known_sources": sorted(names),+ }+ names = [source]++ rows = []+ for name in names:+ cadence = overrides.get(name, default_cadence)+ overdue_after = OVERDUE_MULTIPLE * cadence+ last = conn.execute(+ "SELECT collected_at, status, error, extract_error FROM history_captures "+ "WHERE source = ? ORDER BY collected_at DESC, id DESC LIMIT 1",+ (name,),+ ).fetchone()+ entry: dict[str, Any] = {+ "source": name,+ "in_collector_roster": name in known,+ "cadence_s": cadence,+ "overdue_after_s": overdue_after,+ }+ if last is None:+ entry.update(state="never_run", attempts=0, overdue=None,+ last_attempt_at=None, last_success_at=None)+ rows.append(entry)+ continue+ last_at, last_status, last_reason, last_extract_error = last+ attempts = conn.execute(+ "SELECT COUNT(*) FROM history_captures WHERE source = ?", (name,)+ ).fetchone()[0]+ last_success = conn.execute(+ "SELECT MAX(collected_at) FROM history_captures "+ "WHERE source = ? AND status IN ('ok', 'degraded')",+ (name,),+ ).fetchone()[0]+ last_ok = conn.execute(+ "SELECT MAX(collected_at) FROM history_captures WHERE source = ? AND status = 'ok'",+ (name,),+ ).fetchone()[0]+ # Errors recorded after the last non-error capture, in insertion+ # order (robust to a clock that stepped backwards).+ consecutive = conn.execute(+ "SELECT COUNT(*) FROM history_captures WHERE source = ? AND status = 'error' "+ "AND id > COALESCE((SELECT MAX(id) FROM history_captures "+ "WHERE source = ? AND status != 'error'), 0)",+ (name, name),+ ).fetchone()[0]+ obs = conn.execute(+ "SELECT MAX(observed_at), COUNT(DISTINCT series_key), "+ "SUM(observed_at IS NULL) FROM history_observations WHERE source = ?",+ (name,),+ ).fetchone()+ age_attempt = now - last_at+ age_success = None if last_success is None else now - last_success+ overdue = age_success is None or age_success > overdue_after+ attempt_overdue = age_attempt > overdue_after+ if attempt_overdue:+ state = "not_attempted_recently"+ elif last_status == "error":+ state = "failing"+ elif overdue:+ state = "overdue"+ else:+ state = last_status+ entry.update(+ state=state,+ attempts=attempts,+ last_attempt_at=_iso(last_at),+ last_attempt_age_s=round(age_attempt, 1),+ last_status=last_status,+ last_reason=last_reason,+ last_success_at=_iso(last_success),+ last_success_age_s=None if age_success is None else round(age_success, 1),+ last_ok_at=_iso(last_ok),+ consecutive_failures=consecutive,+ overdue=overdue,+ attempt_overdue=attempt_overdue,+ )+ if last_extract_error:+ entry["last_extract_error"] = last_extract_error+ if obs[1]:+ entry["observation_series"] = obs[1]+ entry["latest_observed_at"] = obs[0]+ if obs[2]:+ entry["observations_without_observed_at"] = obs[2]+ rows.append(entry)++ states: dict[str, int] = {}+ for entry in rows:+ states[entry["state"]] = states.get(entry["state"], 0) + 1+ return {+ "sources": rows,+ "state_counts": states,+ "checked_at": _iso(now),+ "default_cadence_s": default_cadence,+ "overdue_multiple": OVERDUE_MULTIPLE,+ "storage": self.storage_stats(),+ "cannot_prove": [+ "A recent capture shows the collector reached the upstream and saved a "+ "payload; it does not show the upstream's observations are current. "+ "Check latest_observed_at here or observed_at in intel_series_history.",+ "Cadence is the stated expectation (default and overrides above), not "+ "the live daemon's --interval; a collector deliberately run less often "+ "reads overdue.",+ "A degraded capture with no records cannot tell a quiet period from a "+ "silent upstream failure.",+ HISTORY_ACCRUAL_NOTE + " A source the collector never ran reads never_run, "+ "not healthy.",+ ],+ "states_explained": {+ "ok": "last capture delivered records with no degradation marker",+ "degraded": "last capture delivered a payload marked stale/degraded, empty, "+ "or without the measures its extractor expects",+ "failing": "last capture was an error (consecutive_failures counts the run)",+ "overdue": f"no payload delivered within {OVERDUE_MULTIPLE:g} cadences",+ "not_attempted_recently": f"the collector has not attempted it within "+ f"{OVERDUE_MULTIPLE:g} cadences",+ "never_run": "no capture recorded",+ },+ }++ def capture_history(+ self, source: str, limit: Any = 20, capture_id: Any = None+ ) -> dict:+ """A source's earlier captures, newest first, changed vs unchanged."""+ conn = self._conn+ columns = (+ "c.id, c.collected_at, c.status, c.duration_s, c.record_count, c.error, "+ "c.payload_hash, c.changed, c.observations_extracted, c.observations_stored, "+ "c.extract_error, p.body IS NOT NULL"+ )+ join = (+ "FROM history_captures c LEFT JOIN history_payloads p "+ "ON p.source = c.source AND p.payload_hash = c.payload_hash"+ )+ if capture_id is not None:+ try:+ cid = int(capture_id)+ except (TypeError, ValueError):+ return {"error": f"capture_id must be an integer, got {capture_id!r}"}+ row = conn.execute(+ f"SELECT {columns}, p.body {join} WHERE c.id = ? AND c.source = ?",+ (cid, source),+ ).fetchone()+ if row is None:+ return {"error": f"no capture {cid} for source {source!r}"}+ capture = self._capture_row(row[:-1])+ if row[-1] is not None:+ capture["payload"] = json.loads(zlib.decompress(row[-1]))+ elif capture["payload_hash"]:+ capture["payload"] = None+ capture["payload_note"] = "body pruned past WORLD_INTEL_HISTORY_PAYLOAD_DAYS"+ return {"source": source, "capture": capture, "note": HISTORY_ACCRUAL_NOTE}++ n = _clamp(limit, 20)+ rows = conn.execute(+ f"SELECT {columns} {join} WHERE c.source = ? "+ "ORDER BY c.collected_at DESC, c.id DESC LIMIT ?",+ (source, n),+ ).fetchall()+ total, changed, distinct = conn.execute(+ "SELECT COUNT(*), COALESCE(SUM(changed), 0), COUNT(DISTINCT payload_hash) "+ "FROM history_captures WHERE source = ?",+ (source,),+ ).fetchone()+ result = {+ "source": source,+ "captures": [self._capture_row(r) for r in rows],+ "total_captures": total,+ "changed_captures": changed,+ "distinct_payloads": distinct,+ "note": HISTORY_ACCRUAL_NOTE,+ }+ if total == 0:+ result["data_gaps"] = [+ f"no captures recorded for {source!r}: the collector has not run it "+ "against this database"+ ]+ return result++ @staticmethod+ def _capture_row(row: tuple) -> dict:+ (cid, collected_at, status, duration, count, error, digest, changed,+ extracted, stored, extract_error, body_retained) = row+ return {+ "capture_id": cid,+ "collected_at": _iso(collected_at),+ "status": status,+ "duration_s": duration,+ "record_count": count,+ "reason": error,+ "payload_hash": digest,+ "change": (+ None if digest is None+ else "first" if changed is None+ else "changed" if changed else "unchanged"+ ),+ "body_retained": bool(body_retained) if digest else None,+ "observations_extracted": extracted,+ "observations_stored": stored,+ "extract_error": extract_error,+ }++ def series_history(+ self, series_key: str | None = None, source: str | None = None, limit: Any = 100+ ) -> dict:+ """One series' observations with all three dates, or (no key) the+ listing of available series."""+ conn = self._conn+ if not series_key:+ params: list[Any] = []+ where = ""+ if source:+ where, params = "WHERE source = ?", [source]+ rows = conn.execute(+ "SELECT series_key, source, MAX(unit), MAX(label), COUNT(*), "+ "MIN(observed_at), MAX(observed_at), SUM(observed_at IS NULL), "+ f"MAX(collected_at) FROM history_observations {where} "+ "GROUP BY series_key ORDER BY MAX(collected_at) DESC, series_key LIMIT ?",+ (*params, _clamp(limit, 200)),+ ).fetchall()+ total = conn.execute(+ f"SELECT COUNT(DISTINCT series_key) FROM history_observations {where}", params+ ).fetchone()[0]+ result = {+ "series": [+ {+ "series_key": r[0], "source": r[1], "unit": r[2], "label": r[3],+ "points": r[4], "first_observed_at": r[5], "last_observed_at": r[6],+ "points_without_observed_at": r[7],+ "last_collected_at": _iso(r[8]),+ }+ for r in rows+ ],+ "total_series": total,+ "sources_with_extractors": sorted(_EXTRACTORS),+ "note": HISTORY_ACCRUAL_NOTE,+ }+ if total == 0:+ result["data_gaps"] = [+ "no observations recorded yet"+ + (f" for source {source!r}" if source else "")+ ]+ return result++ rows = conn.execute(+ "SELECT observed_at, published_at, collected_at, value, unit, label, capture_id, "+ "source FROM history_observations WHERE series_key = ? "+ "ORDER BY observed_at IS NULL, observed_at DESC, collected_at DESC, id DESC LIMIT ?",+ (series_key, _clamp(limit, 100)),+ ).fetchall()+ if not rows:+ return {+ "error": f"no observations for series {series_key!r}; call without "+ "series_key to list available series",+ }+ observations = [+ {+ "observed_at": r[0], "published_at": r[1], "collected_at": _iso(r[2]),+ "value": r[3], "unit": r[4], "label": r[5], "capture_id": r[6],+ }+ for r in rows+ ]+ gaps = []+ missing_observed = sum(1 for o in observations if o["observed_at"] is None)+ if missing_observed:+ gaps.append(+ f"{missing_observed} point(s) have no observed_at: the payload carries no "+ "observation date, and collected_at is when this server saved it, not when "+ "the value was observed"+ )+ if all(o["published_at"] is None for o in observations):+ gaps.append("published_at unknown: this source's payload names no release time")+ return {+ "series_key": series_key,+ "source": rows[0][7],+ "observations": observations,+ "data_gaps": gaps,+ "note": (+ "Rows for the same observed_at are successive values this server saw "+ "(revisions); a row is stored only when new or changed. "+ + HISTORY_ACCRUAL_NOTE+ ),+ }++ def revisions(+ self, source: str | None = None, series_key: str | None = None, limit: Any = 100+ ) -> dict:+ """Values for the same observed_at that a later capture changed."""+ filters = ["observed_at IS NOT NULL"]+ params: list[Any] = []+ if source:+ filters.append("source = ?")+ params.append(source)+ if series_key:+ filters.append("series_key = ?")+ params.append(series_key)+ rows = self._conn.execute(+ "SELECT series_key, source, observed_at, prev_value, prev_collected_at, "+ "prev_capture_id, value, collected_at, capture_id, unit, label FROM ("+ " SELECT *, LAG(value) OVER w AS prev_value, "+ " LAG(collected_at) OVER w AS prev_collected_at, "+ " LAG(capture_id) OVER w AS prev_capture_id "+ f" FROM history_observations WHERE {' AND '.join(filters)} "+ " WINDOW w AS (PARTITION BY series_key, observed_at ORDER BY collected_at, id)"+ ") WHERE prev_value IS NOT NULL AND value != prev_value "+ "ORDER BY collected_at DESC, id DESC LIMIT ?",+ (*params, _clamp(limit, 100)),+ ).fetchall()+ return {+ "revisions": [+ {+ "series_key": r[0], "source": r[1], "observed_at": r[2],+ "previous_value": r[3], "previous_collected_at": _iso(r[4]),+ "previous_capture_id": r[5], "revised_value": r[6],+ "revised_collected_at": _iso(r[7]), "revised_capture_id": r[8],+ "delta": round(r[6] - r[3], 10), "unit": r[9], "label": r[10],+ }+ for r in rows+ ],+ "count": len(rows),+ "cannot_prove": [+ "Only changes between two of this server's own captures are visible; a "+ "revision made before the first capture, or while the collector was not "+ "running, is not.",+ "Series without observed_at (for example Yahoo quotes) cannot be checked "+ "for revisions: there is no observation date to hold fixed.",+ ],+ "note": HISTORY_ACCRUAL_NOTE,+ }diff --git a/src/world_intel_mcp/tests/test_cli.py b/src/world_intel_mcp/tests/test_cli.pyindex 5fdbb1b..cda2182 100644--- a/src/world_intel_mcp/tests/test_cli.py+++ b/src/world_intel_mcp/tests/test_cli.py@@ -133,6 +133,7 @@ def test_command_registry() -> None:"dashboard","report","aoi",+ "history",} <= names# webcams_cmd has no explicit name=, but click >= 8.1 strips the# `_cmd` suffix when deriving default command names, so thediff --git a/src/world_intel_mcp/tests/test_history.py b/src/world_intel_mcp/tests/test_history.pynew file mode 100644index 0000000..14c549b--- /dev/null+++ b/src/world_intel_mcp/tests/test_history.py@@ -0,0 +1,734 @@+"""Tests for history.py, the collector's history recording, the history MCP+tools and the ``intel history`` CLI group.++Every test drives a real ``HistoryStore`` on a tmp SQLite file and asserts+actual values: dates as stored, dedupe counts, overdue arithmetic at a+fixed ``now``, revision pairs. The collector tests fake only the fetch+functions (the ``_import_fetch_fn`` boundary) and give the fake fetcher a+real ``cache.db_path``, so ``collect_once`` writes through the production+history path.+"""++import asyncio+import json+import types++import pytest+from click.testing import CliRunner++from world_intel_mcp import cli, collector, history+from world_intel_mcp.history import HistoryStore, Observation, SourceOutcome++T0 = 1_760_000_000.0 # 2025-10-09T08:53:20Z+++def _kp(*rows):+ return {"kp_recent": [{"time": t, "kp": v} for t, v in rows], "alerts": []}+++def store(tmp_path):+ s = HistoryStore(tmp_path / "history.db")+ yield s+ s.close()++[email protected](autouse=True)+def _default_history_env(monkeypatch):+ for var in (+ "WORLD_INTEL_HISTORY_DAYS",+ "WORLD_INTEL_HISTORY_PAYLOAD_DAYS",+ "WORLD_INTEL_HISTORY_CAPTURE_DAYS",+ "WORLD_INTEL_HISTORY_CADENCE_S",+ "WORLD_INTEL_HISTORY_CADENCES",+ ):+ monkeypatch.delenv(var, raising=False)+++def _record(store, source, at, payload=None, error=None, duration=1.0):+ return store.record_cycle([SourceOutcome(source, at, duration, payload, error)], now=at)+++# ---------------------------------------------------------------------------+# Dates+# ---------------------------------------------------------------------------+++def test_normalize_observed_at_forms() -> None:+ n = history.normalize_observed_at+ assert n("2026-10-15") == "2026-10-15"+ assert n("2026-10") == "2026-10"+ assert n("2026") == "2026"+ assert n("2026-10-17T03:00:00Z") == "2026-10-17T03:00:00Z"+ assert n("2026-10-17T05:00:00+02:00") == "2026-10-17T03:00:00Z"+ # A naive instant is refused unless the publisher's zone is known.+ assert n("2026-10-17 03:00:00.000") is None+ assert n("2026-10-17 03:00:00.000", assume_utc=True) == "2026-10-17T03:00:00Z"+ assert n("not a date") is None+ assert n(None) is None+ assert n(True) is None+++def test_kp_observed_at_comes_from_payload_not_collection_time(store) -> None:+ _record(store, "space_weather", T0, _kp(("2026-10-17 03:00:00.000", 3.0)))+ rows = store.series_history("space_weather:kp")["observations"]+ assert rows == [+ {+ "observed_at": "2026-10-17T03:00:00Z",+ "published_at": None,+ "collected_at": "2025-10-09T08:53:20Z",+ "value": 3.0,+ "unit": "Kp index",+ "label": "NOAA planetary K-index",+ "capture_id": 1,+ }+ ]+++def test_payload_without_observation_date_stores_null_not_collected_at(store) -> None:+ quotes = {"quotes": [{"symbol": "^GSPC", "price": 6_123.5, "currency": "USD"}]}+ _record(store, "market_quotes", T0, quotes)+ result = store.series_history("market_quotes:^GSPC:price")+ (obs,) = result["observations"]+ assert obs["observed_at"] is None+ assert obs["collected_at"] == "2025-10-09T08:53:20Z"+ assert obs["value"] == 6_123.5 and obs["unit"] == "USD"+ assert any("no observed_at" in gap for gap in result["data_gaps"])+ listing = store.series_history()["series"]+ assert listing[0]["points_without_observed_at"] == 1+ assert listing[0]["first_observed_at"] is None+++# ---------------------------------------------------------------------------+# Status classification: a failure is never an ok capture with zero records+# ---------------------------------------------------------------------------+++ "payload,error,reason",+ [+ (None, "timeout (45.0s)", "timeout (45.0s)"),+ (None, None, "fetch returned no payload"),+ ({"error": "EIA_API_KEY not configured"}, None, "EIA_API_KEY not configured"),+ ],+)+def test_failures_are_error_captures_with_no_record_count(store, payload, error, reason):+ summary = _record(store, "energy_prices", T0, payload, error)+ assert summary["status_counts"] == {"ok": 0, "degraded": 0, "error": 1}+ (cap,) = store.capture_history("energy_prices")["captures"]+ assert cap["status"] == "error"+ assert cap["reason"] == reason+ assert cap["record_count"] is None+ assert cap["payload_hash"] is None and cap["change"] is None+ assert store.storage_stats()["payload_bodies"] == 0+++def test_empty_payload_is_degraded_not_ok(store) -> None:+ _record(store, "earthquakes", T0, {"earthquakes": [], "count": 0})+ (cap,) = store.capture_history("earthquakes")["captures"]+ assert cap["status"] == "degraded"+ assert cap["record_count"] == 0+ assert "quiet period" in cap["reason"]+++def test_stale_and_marked_degraded_payloads(store) -> None:+ _record(store, "gas_prices", T0, {"prices": [1], "_stale": True, "_stale_age_seconds": 812.0})+ _record(store, "cyclones", T0, {"cyclones": [1], "degraded": True})+ assert store.capture_history("gas_prices")["captures"][0]["reason"] == (+ "served stale cache (age 812.0 s)"+ )+ assert store.capture_history("cyclones")["captures"][0]["status"] == "degraded"+++def test_extractor_that_finds_nothing_marks_degraded(store) -> None:+ curated_only = {"rates": [{"bank": "Bank of Japan", "rate": 0.5, "as_of": "2025-01-24",+ "source": "curated", "label": "BoJ Policy Rate"}]}+ _record(store, "central_bank_rates", T0, curated_only)+ (cap,) = store.capture_history("central_bank_rates")["captures"]+ assert cap["status"] == "degraded"+ assert cap["observations_extracted"] == 0+ assert "found no measures" in cap["reason"]+++def test_record_count_hint() -> None:+ assert history.record_count([1, 2, 3]) == 3+ assert history.record_count({"a": [1], "b": [1, 2]}) == 2+ assert history.record_count({"count": 4, "zones": {}}) == 4+ assert history.record_count({"oil": {"brent": None}}) is None+ assert history.record_count({"count": True}) is None+++# ---------------------------------------------------------------------------+# Dedupe+# ---------------------------------------------------------------------------+++def test_unchanged_payload_body_stored_once_despite_new_fetch_timestamp(store) -> None:+ first = dict(_kp(("2026-10-17T00:00:00Z", 2.0)), timestamp="2026-10-17T16:00:00Z")+ again = dict(first, timestamp="2026-10-17T16:05:00Z")+ s1 = _record(store, "space_weather", T0, first)+ s2 = _record(store, "space_weather", T0 + 300, again)+ assert (s1["payloads_stored"], s2["payloads_stored"]) == (1, 0)+ assert (s1["observations_stored"], s2["observations_stored"]) == (1, 0)+ caps = store.capture_history("space_weather")["captures"]+ assert [c["change"] for c in caps] == ["unchanged", "first"]+ assert caps[0]["payload_hash"] == caps[1]["payload_hash"]+ assert store.storage_stats()["payload_bodies"] == 1+++def test_changed_then_reverted_payload_keeps_two_bodies(store) -> None:+ a = _kp(("2026-10-17T00:00:00Z", 2.0))+ b = _kp(("2026-10-17T00:00:00Z", 2.0), ("2026-10-17T03:00:00Z", 1.0))+ for i, payload in enumerate((a, b, a)):+ _record(store, "space_weather", T0 + 300 * i, payload)+ result = store.capture_history("space_weather")+ assert [c["change"] for c in result["captures"]] == ["changed", "changed", "first"]+ assert result["distinct_payloads"] == 2+ assert result["changed_captures"] == 2+ assert store.storage_stats()["payload_bodies"] == 2+ # The unchanged 00:00 point was stored once across all three captures.+ assert len(store.series_history("space_weather:kp")["observations"]) == 2+++def test_capture_replay_returns_stored_body(store) -> None:+ payload = _kp(("2026-10-17T00:00:00Z", 2.0))+ _record(store, "space_weather", T0, payload)+ replay = store.capture_history("space_weather", capture_id=1)+ assert replay["capture"]["payload"] == payload+ assert store.capture_history("space_weather", capture_id=99)["error"].startswith("no capture 99")+ assert "integer" in store.capture_history("space_weather", capture_id="x")["error"]+++# ---------------------------------------------------------------------------+# Revisions+# ---------------------------------------------------------------------------+++def test_revisions_detect_changed_value_for_same_observed_at(store) -> None:+ _record(store, "space_weather", T0, _kp(("2026-10-17T00:00:00Z", 2.33), ("2026-10-17T03:00:00Z", 3.0)))+ _record(store, "space_weather", T0 + 600, _kp(("2026-10-17T00:00:00Z", 2.67), ("2026-10-17T03:00:00Z", 3.0)))+ quake = {"earthquakes": [{"id": "us7000tst1", "magnitude": 4.6, "time": "2026-10-16T22:10:00Z", "place": "Test Ridge"}]}+ _record(store, "earthquakes", T0, quake)+ quake["earthquakes"][0]["magnitude"] = 4.9+ _record(store, "earthquakes", T0 + 900, quake)+ # A quote whose price moves has no observed_at: never a revision.+ _record(store, "market_quotes", T0, {"quotes": [{"symbol": "^DJI", "price": 1.0}]})+ _record(store, "market_quotes", T0 + 300, {"quotes": [{"symbol": "^DJI", "price": 2.0}]})++ result = store.revisions()+ assert result["count"] == 2+ by_key = {r["series_key"]: r for r in result["revisions"]}+ kp = by_key["space_weather:kp"]+ assert kp["observed_at"] == "2026-10-17T00:00:00Z"+ assert (kp["previous_value"], kp["revised_value"], kp["delta"]) == (2.33, 2.67, 0.34)+ assert kp["previous_collected_at"] == "2025-10-09T08:53:20Z"+ assert kp["revised_collected_at"] == "2025-10-09T09:03:20Z"+ mag = by_key["earthquakes:us7000tst1:magnitude"]+ assert (mag["previous_value"], mag["revised_value"]) == (4.6, 4.9)+ assert mag["label"] == "Test Ridge"+ assert store.revisions(source="earthquakes")["count"] == 1+ assert store.revisions(series_key="space_weather:kp")["count"] == 1+++def test_revisions_ignore_a_repeated_equal_value_from_any_writer(store) -> None:+ """record_cycle never stores an unchanged value twice, but a future+ writer (a backfill) might: a repeated value must not read as a revision."""+ _record(store, "space_weather", T0, _kp(("2026-10-17T00:00:00Z", 2.0)))+ with store._conn:+ store._conn.execute(+ "INSERT INTO history_observations (capture_id, source, series_key, observed_at, "+ "collected_at, value) VALUES (1, 'space_weather', 'space_weather:kp', "+ "'2026-10-17T00:00:00Z', ?, 2.0)",+ (T0 + 60,),+ )+ assert store.revisions()["count"] == 0+++def test_consecutive_failures_follow_insertion_order_not_clock(store) -> None:+ """An error logged after a success counts even if the clock stepped back."""+ _record(store, "wildfires", T0 - 100, None, "earlier failure, before the success")+ _record(store, "wildfires", T0, {"fires": [1]})+ _record(store, "wildfires", T0 - 30, None, "boom")+ row = store.collection_health(["wildfires"], now=T0 + 10)["sources"][0]+ assert row["consecutive_failures"] == 1+++# ---------------------------------------------------------------------------+# Collection health+# ---------------------------------------------------------------------------+++def test_overdue_math_and_consecutive_failures(store) -> None:+ now = T0 + 10_000+ _record(store, "earthquakes", now - 899, {"earthquakes": [{"id": "a", "magnitude": 5.0, "time": "2026-10-16T22:10:00Z"}]})+ _record(store, "wildfires", now - 901, {"fires": [1]})+ _record(store, "wildfires", now - 120, None, "timeout (45.0s)")+ _record(store, "wildfires", now - 60, None, "boom")+ _record(store, "acled_events", now - 950, {"events": [1]})++ health = store.collection_health(+ ["earthquakes", "wildfires", "acled_events", "cyclones"], now=now+ )+ rows = {r["source"]: r for r in health["sources"]}+ quake = rows["earthquakes"]+ assert quake["overdue_after_s"] == 900.0+ assert quake["last_success_age_s"] == 899.0+ assert quake["overdue"] is False and quake["state"] == "ok"+ assert quake["latest_observed_at"] == "2026-10-16T22:10:00Z"+ fires = rows["wildfires"]+ assert fires["consecutive_failures"] == 2+ assert fires["overdue"] is True # last payload 901 s ago > 900 s+ assert fires["state"] == "failing"+ assert fires["last_reason"] == "boom"+ assert rows["acled_events"]["state"] == "not_attempted_recently"+ assert rows["cyclones"]["state"] == "never_run"+ assert rows["cyclones"]["attempts"] == 0+ assert health["state_counts"] == {+ "ok": 1, "failing": 1, "not_attempted_recently": 1, "never_run": 1+ }+ assert any("observations are current" in line for line in health["cannot_prove"])+++def test_cadence_overrides_from_env(store, monkeypatch) -> None:+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CADENCE_S", "600")+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CADENCES", "wildfires=60, junk, bad=x")+ _record(store, "wildfires", T0, {"fires": [1]})+ _record(store, "earthquakes", T0, {"earthquakes": [{"id": "a", "magnitude": 5.0, "time": "2026-10-16T22:10:00Z"}]})+ health = store.collection_health(["wildfires", "earthquakes"], now=T0 + 200)+ rows = {r["source"]: r for r in health["sources"]}+ assert rows["wildfires"]["overdue_after_s"] == 180.0+ assert rows["wildfires"]["state"] == "not_attempted_recently"+ assert rows["earthquakes"]["overdue_after_s"] == 1800.0+ assert rows["earthquakes"]["state"] == "ok"+++def test_health_unknown_source_and_off_roster_source(store) -> None:+ _record(store, "retired_source", T0, {"x": [1]})+ assert "unknown source" in store.collection_health(["earthquakes"], source="nope", now=T0)["error"]+ health = store.collection_health(["earthquakes"], now=T0)+ retired = [r for r in health["sources"] if r["source"] == "retired_source"][0]+ assert retired["in_collector_roster"] is False+ one = store.collection_health(["earthquakes"], source="earthquakes", now=T0)+ assert [r["source"] for r in one["sources"]] == ["earthquakes"]+++# ---------------------------------------------------------------------------+# Retention+# ---------------------------------------------------------------------------+++def test_retention_defaults() -> None:+ assert history.retention_days() == {+ "payload_days": 7.0, "capture_days": 30.0, "history_days": 365.0+ }+++def test_run_log_retention_is_separate_from_observations(store, monkeypatch) -> None:+ """Captures (the run log) age out at capture_days while the+ observations they produced stay until history_days."""+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")+ monkeypatch.setenv("WORLD_INTEL_HISTORY_DAYS", "10")+ _record(store, "space_weather", T0, _kp(("2026-10-17T00:00:00Z", 2.0)))+ summary = _record(store, "space_weather", T0 + 3 * 86400, _kp(("2026-10-20T00:00:00Z", 1.0)))+ assert summary["pruned"]["captures"] == 1+ assert summary["pruned"]["observations"] == 0+ observed = [o["observed_at"] for o in store.series_history("space_weather:kp")["observations"]]+ assert observed == ["2026-10-20T00:00:00Z", "2026-10-17T00:00:00Z"]+ assert store.capture_history("space_weather")["total_captures"] == 1+++def test_retention_prunes_bodies_then_rows(store, monkeypatch) -> None:+ monkeypatch.setenv("WORLD_INTEL_HISTORY_PAYLOAD_DAYS", "1")+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "3")+ monkeypatch.setenv("WORLD_INTEL_HISTORY_DAYS", "3")+ _record(store, "space_weather", T0, _kp(("2026-10-17T00:00:00Z", 2.0)))+ later = T0 + 2 * 86400+ summary = _record(store, "space_weather", later, _kp(("2026-10-18T00:00:00Z", 1.0)))+ assert summary["pruned"] == {"payloads": 1, "captures": 0, "observations": 0}+ replay = store.capture_history("space_weather", capture_id=1)["capture"]+ assert replay["payload"] is None and "pruned" in replay["payload_note"]+ assert store.capture_history("space_weather")["captures"][1]["body_retained"] is False++ summary = _record(store, "space_weather", T0 + 4 * 86400, _kp(("2026-10-18T00:00:00Z", 1.0)))+ assert summary["pruned"]["captures"] == 1+ assert summary["pruned"]["observations"] == 1+++def test_retention_zero_keeps_forever_and_bad_values_fall_back(store, monkeypatch) -> None:+ monkeypatch.setenv("WORLD_INTEL_HISTORY_PAYLOAD_DAYS", "0")+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "0")+ monkeypatch.setenv("WORLD_INTEL_HISTORY_DAYS", "-5")+ assert history.retention_days() == {+ "payload_days": 0.0, "capture_days": 0.0, "history_days": 365.0+ }+ _record(store, "space_weather", T0, _kp(("2026-10-17T00:00:00Z", 2.0)))+ summary = _record(store, "space_weather", T0 + 200 * 86400, _kp(("2026-10-18T00:00:00Z", 1.0)))+ assert summary["pruned"] == {"payloads": 0, "captures": 0, "observations": 0}+++# ---------------------------------------------------------------------------+# Extractor registry+# ---------------------------------------------------------------------------+++def test_register_extractor_api(store, monkeypatch) -> None:+ monkeypatch.setattr(history, "_EXTRACTORS", dict(history._EXTRACTORS))++ @history.register_extractor("test_feed")+ def _extract(payload):+ return [+ Observation("level", payload["level"], observed_at="2026-10-15", unit="m"),+ Observation("bad_date", 1.0, observed_at="2026-10-15 03:00"),+ Observation("nan", float("nan"), observed_at="2026-10-15"),+ ]++ with pytest.raises(ValueError, match="already registered"):+ history.register_extractor("test_feed", lambda p: [])+ history.register_extractor("test_feed", _extract, replace=True)+ assert "test_feed" in history.registered_extractors()++ _record(store, "test_feed", T0, {"level": 3.25, "rows": [1]})+ (cap,) = store.capture_history("test_feed")["captures"]+ assert cap["observations_extracted"] == 3+ assert cap["observations_stored"] == 1+ assert cap["extract_error"] == "2 invalid point(s) skipped"+ assert cap["status"] == "ok"+ (obs,) = store.series_history("test_feed:level")["observations"]+ assert (obs["observed_at"], obs["value"], obs["unit"]) == ("2026-10-15", 3.25, "m")+++def test_raising_extractor_keeps_capture_and_reports(store, monkeypatch) -> None:+ monkeypatch.setattr(history, "_EXTRACTORS", dict(history._EXTRACTORS))+ history.register_extractor("test_feed", lambda payload: payload["missing"])+ _record(store, "test_feed", T0, {"rows": [1]})+ (cap,) = store.capture_history("test_feed")["captures"]+ assert cap["status"] == "ok"+ assert cap["extract_error"].startswith("extractor raised: KeyError")+ health = store.collection_health(["test_feed"], now=T0)+ assert health["sources"][0]["last_extract_error"].startswith("extractor raised")+++def test_builtin_extractors() -> None:+ rates = {"rates": [+ {"bank": "Federal Reserve", "label": "Federal Funds Rate", "rate": 4.33,+ "as_of": "2026-10-15", "source": "fred"},+ {"bank": "Bank of Japan", "label": "BoJ Policy Rate", "rate": 0.5,+ "as_of": "2025-01-24", "source": "curated"},+ ]}+ (fed,) = history._EXTRACTORS["central_bank_rates"](rates)+ assert (fed.series_key, fed.value, fed.observed_at, fed.unit) == (+ "federal_funds_rate", 4.33, "2026-10-15", "percent"+ )+ quakes = {"earthquakes": [+ {"id": "us1", "magnitude": 5.1, "time": "2026-10-16T22:10:00Z", "place": "P"},+ {"id": "us2", "magnitude": None, "time": "2026-10-16T22:10:00Z"},+ {"id": None, "magnitude": 4.0, "time": "2026-10-16T22:10:00Z"},+ ]}+ (q,) = history._EXTRACTORS["earthquakes"](quakes)+ assert (q.series_key, q.observed_at, q.label) == ("us1:magnitude", "2026-10-16T22:10:00Z", "P")+ commodities = {"commodities": [{"symbol": "GC=F", "name": "Gold", "price": 2_400.0}]}+ (gold,) = history._EXTRACTORS["commodity_quotes"](commodities)+ assert (gold.series_key, gold.label, gold.observed_at, gold.unit) == (+ "GC=F:price", "Gold", None, None+ )+++# ---------------------------------------------------------------------------+# Collector integration+# ---------------------------------------------------------------------------+++class _VS:+ _store_queue = None++ async def store(self, name, data):+ pass++ async def collection_stats(self):+ return {"points_count": 0}+++def _importer(fakes):+ name_by_ref = {(mod, fn): name for name, mod, fn, _ in collector.SOURCES}++ def _import(module_path, fn_name):+ return fakes[name_by_ref[(module_path, fn_name)]]++ return _import+++async def test_collect_once_records_failed_fetch_as_failure_capture(tmp_path, monkeypatch):+ """The error-dict source counts as a cycle 'success' (pinned in+ test_collector_runtime) but the history records what happened: an error+ capture with the reason, not an ok capture with zero records."""++ async def _quakes(fetcher, **kw):+ return {"earthquakes": [{"id": "x1", "magnitude": 5.0, "time": "2026-10-16T22:10:00Z"}], "count": 1}++ async def _raises(fetcher, **kw):+ raise ValueError("acled exploded")++ async def _none(fetcher, **kw):+ return None++ async def _hangs(fetcher, **kw):+ await asyncio.sleep(5)++ async def _error_dict(fetcher, **kw):+ return {"error": "EIA_API_KEY not configured"}++ monkeypatch.setattr(collector, "_import_fetch_fn", _importer({+ "earthquakes": _quakes, "acled_events": _raises, "wildfires": _none,+ "nav_warnings": _hangs, "energy_prices": _error_dict,+ }))+ db = tmp_path / "cache.db"+ fetcher = types.SimpleNamespace(cache=types.SimpleNamespace(db_path=db))+ summary = await collector.collect_once(+ fetcher, _VS(),+ source_filter={"earthquakes", "acled_events", "wildfires", "nav_warnings", "energy_prices"},+ timeout=0.05,+ )+ assert summary["successes"] == 2 # earthquakes + the error dict, as before+ assert summary["history"]["recorded"] == 5+ assert summary["history"]["status_counts"] == {"ok": 1, "degraded": 0, "error": 4}++ store = HistoryStore(db)+ try:+ reasons = {+ src: store.capture_history(src)["captures"][0]+ for src in ("acled_events", "wildfires", "nav_warnings", "energy_prices", "earthquakes")+ }+ finally:+ store.close()+ assert reasons["acled_events"]["reason"] == "acled exploded"+ assert reasons["wildfires"]["reason"] == "fetch returned no payload"+ assert reasons["nav_warnings"]["reason"] == "timeout (0.05s)"+ assert reasons["energy_prices"]["reason"] == "EIA_API_KEY not configured"+ for src in ("acled_events", "wildfires", "nav_warnings", "energy_prices"):+ assert reasons[src]["status"] == "error"+ assert reasons[src]["record_count"] is None+ ok = reasons["earthquakes"]+ assert (ok["status"], ok["record_count"], ok["observations_stored"]) == ("ok", 1, 1)+ assert all(r["duration_s"] is not None and r["duration_s"] >= 0 for r in reasons.values())+++def test_unserializable_payload_loses_only_its_body(store) -> None:+ """Mixed-type dict keys break sort_keys hashing; that capture keeps+ its status and says what was lost, and the cycle's other captures+ are still recorded."""+ summary = store.record_cycle([+ SourceOutcome("weird_source", T0, 1.0, {"rows": [1], "by_key": {1: "a", "b": 2}}),+ SourceOutcome("space_weather", T0, 1.0, _kp(("2026-10-17T00:00:00Z", 2.0))),+ ], now=T0)+ assert summary["recorded"] == 2+ assert summary["payloads_stored"] == 1+ (weird,) = store.capture_history("weird_source")["captures"]+ assert weird["status"] == "ok"+ assert weird["payload_hash"] is None and weird["change"] is None+ assert weird["reason"].startswith("payload not stored in history: TypeError")+ assert store.capture_history("space_weather")["captures"][0]["change"] == "first"+++async def test_collect_once_survives_an_unexpected_history_bug(tmp_path, monkeypatch):+ async def _ok(fetcher, **kw):+ return {"earthquakes": [1]}++ def _boom(self, outcomes, now=None):+ raise RuntimeError("history bug")++ monkeypatch.setattr(collector, "_import_fetch_fn", _importer({"earthquakes": _ok}))+ monkeypatch.setattr(HistoryStore, "record_cycle", _boom)+ fetcher = types.SimpleNamespace(cache=types.SimpleNamespace(db_path=tmp_path / "c.db"))+ summary = await collector.collect_once(fetcher, _VS(), source_filter={"earthquakes"})+ assert summary["successes"] == 1+ assert summary["history"] == {+ "recorded": 0, "error": "history write failed: RuntimeError: history bug"+ }+++async def test_collect_once_reports_unrecordable_history(monkeypatch):+ async def _ok(fetcher, **kw):+ return {"earthquakes": [1]}++ monkeypatch.setattr(collector, "_import_fetch_fn", _importer({"earthquakes": _ok}))+ summary = await collector.collect_once(object(), _VS(), source_filter={"earthquakes"})+ assert summary["history"]["recorded"] == 0+ assert "no cache db_path" in summary["history"]["error"]++ bad = types.SimpleNamespace(cache=types.SimpleNamespace(db_path="/dev/null/x/cache.db"))+ summary = await collector.collect_once(bad, _VS(), source_filter={"earthquakes"})+ assert summary["history"]["recorded"] == 0+ assert summary["history"]["error"].startswith("history write failed")+++def test_collector_main_prints_history_line(monkeypatch, capsys) -> None:+ async def _fake_run_once(source_filter=None):+ return {"successes": 1, "sources_attempted": 1, "cycle_time_s": 0.1,+ "vector_store_points": 0, "errors": [], "failures": 0,+ "history": {"recorded": 1, "status_counts": {"ok": 0, "degraded": 0, "error": 1},+ "observations_stored": 0}}++ monkeypatch.setattr(collector, "run_once", _fake_run_once)+ monkeypatch.setattr("sys.argv", ["intel-collector"])+ with pytest.raises(SystemExit):+ collector.main()+ assert "History: 1 captures (ok 0, degraded 0, error 1), 0 new observations" in capsys.readouterr().out++ async def _unrecorded(source_filter=None):+ out = await _fake_run_once()+ out["history"] = {"recorded": 0, "error": "history write failed: disk"}+ return out++ monkeypatch.setattr(collector, "run_once", _unrecorded)+ with pytest.raises(SystemExit):+ collector.main()+ assert "History: NOT recorded (history write failed: disk)" in capsys.readouterr().out+++# ---------------------------------------------------------------------------+# MCP tools+# ---------------------------------------------------------------------------+++def _history_tools():+ """Import the tools package under the suite's temp cache path (the+ test_aoi.py pattern): importing it imports runtime, which opens a+ Cache() at WORLD_INTEL_CACHE_DB."""+ import importlib+ import os++ from .test_server_registry import _TMP_CACHE++ prior = os.environ.get("WORLD_INTEL_CACHE_DB")+ os.environ["WORLD_INTEL_CACHE_DB"] = str(_TMP_CACHE)+ try:+ importlib.import_module("world_intel_mcp.tools")+ return importlib.import_module("world_intel_mcp.tools.history")+ finally:+ if prior is None:+ os.environ.pop("WORLD_INTEL_CACHE_DB", None)+ else:+ os.environ["WORLD_INTEL_CACHE_DB"] = prior+++def tool_db(tmp_path, monkeypatch):+ db = tmp_path / "tools.db"+ tools_mod = _history_tools()+ monkeypatch.setattr(tools_mod.runtime, "cache", types.SimpleNamespace(db_path=db))+ s = HistoryStore(db)+ _record(s, "space_weather", T0, _kp(("2026-10-17T00:00:00Z", 2.33)))+ _record(s, "space_weather", T0 + 600, _kp(("2026-10-17T00:00:00Z", 2.67)))+ _record(s, "energy_prices", T0, {"error": "EIA_API_KEY not configured"})+ s.close()+ return db+++async def test_history_tools_read_the_runtime_cache_db(tool_db) -> None:+ h = _history_tools().HANDLERS+ health = await h["intel_collection_health"]({})+ rows = {r["source"]: r for r in health["sources"]}+ assert set(rows) == {name for name, _, _, _ in collector.SOURCES}+ assert rows["energy_prices"]["state"] in {"failing", "not_attempted_recently"}+ assert rows["energy_prices"]["last_reason"] == "EIA_API_KEY not configured"+ assert rows["cyclones"]["state"] == "never_run"+ one = await h["intel_collection_health"]({"source": "space_weather"})+ assert one["sources"][0]["latest_observed_at"] == "2026-10-17T00:00:00Z"++ caps = await h["intel_capture_history"]({"source": "space_weather", "limit": 1})+ assert len(caps["captures"]) == 1 and caps["total_captures"] == 2+ assert caps["captures"][0]["change"] == "changed"+ replay = await h["intel_capture_history"]({"source": "space_weather", "capture_id": 1})+ assert replay["capture"]["payload"]["kp_recent"][0]["kp"] == 2.33+ assert "required" in (await h["intel_capture_history"]({}))["error"]++ listing = await h["intel_series_history"]({})+ assert [s["series_key"] for s in listing["series"]] == ["space_weather:kp"]+ series = await h["intel_series_history"]({"series_key": "space_weather:kp"})+ assert [o["value"] for o in series["observations"]] == [2.67, 2.33]+ missing = await h["intel_series_history"]({"series_key": "nope"})+ assert "no observations" in missing["error"]++ revs = await h["intel_revisions"]({"source": "space_weather"})+ assert revs["count"] == 1 and revs["revisions"][0]["delta"] == 0.34+++def test_tool_descriptions_state_history_accrues_only_while_collecting() -> None:+ history_tools = _history_tools()+ names = {t.name for t in history_tools.TOOLS}+ assert names == {+ "intel_collection_health", "intel_capture_history",+ "intel_series_history", "intel_revisions",+ }+ for tool in history_tools.TOOLS:+ assert "accrues only while the collector" in tool.description+++# ---------------------------------------------------------------------------+# CLI+# ---------------------------------------------------------------------------+++def cli_db(tmp_path, monkeypatch):+ db = tmp_path / "cli-cache.db"+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(db))+ monkeypatch.setenv("COLUMNS", "220")+ monkeypatch.setattr(cli, "_fetcher", None)+ s = HistoryStore(db)+ _record(s, "space_weather", T0, _kp(("2026-10-17T00:00:00Z", 2.33)))+ _record(s, "space_weather", T0 + 600, _kp(("2026-10-17T00:00:00Z", 2.67)))+ _record(s, "energy_prices", T0, {"error": "EIA_API_KEY [red]not[/red] configured"})+ s.close()+ return db+++def _invoke(*args):+ return CliRunner().invoke(cli.main, list(args), catch_exceptions=False)+++def test_cli_history_registry() -> None:+ assert set(cli.history_group.commands) == {"health", "captures", "series", "revisions"}+++def test_cli_history_health_table_and_json(cli_db) -> None:+ out = _invoke("history", "health").output+ assert "space_weather" in out and "never_run" in out+ assert "EIA_API_KEY [red]not[/red] configured" in out # rendered literally+ assert "Cannot prove:" in out+ data = json.loads(_invoke("--json-output", "history", "health", "--source", "energy_prices").output)+ assert data["sources"][0]["consecutive_failures"] == 1+ bad = _invoke("history", "health", "--source", "nope").output+ assert bad.startswith("Error:") and "unknown source" in bad+++def test_cli_history_captures(cli_db) -> None:+ out = _invoke("history", "captures", "space_weather").output+ assert "2 total, 1 changed, 2 distinct" in out+ assert "changed" in out and "first" in out+ replay = _invoke("history", "captures", "space_weather", "--capture-id", "1").output+ assert "Capture 1 of space_weather" in replay and "2.33" in replay+ assert "Error:" in _invoke("history", "captures", "space_weather", "--capture-id", "9").output+ empty = _invoke("history", "captures", "cyclones").output+ assert "Gap:" in empty and "no captures recorded" in empty+++def test_cli_history_series_and_revisions(cli_db) -> None:+ listing = _invoke("history", "series").output+ assert "space_weather:kp" in listing+ one = _invoke("history", "series", "space_weather:kp").output+ assert "2026-10-17T00:00:00Z" in one and "2.67" in one and "Gap:" in one+ assert "Error:" in _invoke("history", "series", "nope").output+ revs = _invoke("history", "revisions").output+ assert "+0.34" in revs and "2.33" in revs+ none = _invoke("history", "revisions", "--source", "earthquakes").output+ assert "No revisions seen" in none+ data = json.loads(_invoke("--json-output", "history", "revisions").output)+ assert data["count"] == 1+++def test_cli_history_empty_series_listing(tmp_path, monkeypatch) -> None:+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(tmp_path / "empty.db"))+ monkeypatch.setattr(cli, "_fetcher", None)+ out = _invoke("history", "series").output+ assert "Gap:" in out and "no observations recorded yet" in outdiff --git a/src/world_intel_mcp/tools/__init__.py b/src/world_intel_mcp/tools/__init__.pyindex d1b68a7..d41763d 100644--- a/src/world_intel_mcp/tools/__init__.py+++ b/src/world_intel_mcp/tools/__init__.py@@ -28,6 +28,7 @@ from . import ( # noqa: E402finance,geospatial,hazards,+ history,infrastructure,intelligence,markets,@@ -51,6 +52,7 @@ _MODULES = [finance,vector,aoi,+ history,system,]diff --git a/src/world_intel_mcp/tools/history.py b/src/world_intel_mcp/tools/history.pynew file mode 100644index 0000000..fe93892--- /dev/null+++ b/src/world_intel_mcp/tools/history.py@@ -0,0 +1,179 @@+"""History tools: collection health, capture history, series, revisions.++Read the history store (``world_intel_mcp.history``) that the collector+writes into the cache DB. Each handler opens the store on the same+``db_path`` the runtime cache resolved, reads, and closes it; nothing here+fetches upstream data or writes history.+"""++from typing import Any++from mcp.types import Tool++from .. import runtime+from ..history import HistoryStore++_ACCRUAL = (+ "History accrues only while the collector (intel-collector, or intel_collect) "+ "runs; nothing before its first recorded cycle exists."+)++TOOLS: list[Tool] = [+ Tool(+ name="intel_collection_health",+ description=(+ "Per-source collection health from the collector's run log: last attempt, "+ "last success, consecutive failures, overdue against the expected cadence "+ "(default 300 s, overdue past 3 cadences), never-run sources, and history "+ "storage size. States what it cannot prove: a fresh capture does not mean "+ "upstream observations are current (see latest_observed_at). " + _ACCRUAL+ ),+ inputSchema={+ "type": "object",+ "properties": {+ "source": {+ "type": "string",+ "description": "One collector source name (e.g. 'earthquakes'); omit for all",+ },+ },+ },+ ),+ Tool(+ name="intel_capture_history",+ description=(+ "A source's earlier collector captures, newest first: status (ok / degraded / "+ "error with reason), duration, record count, payload hash and whether it "+ "changed from the previous capture. Pass capture_id to replay one stored "+ "payload. " + _ACCRUAL+ ),+ inputSchema={+ "type": "object",+ "properties": {+ "source": {+ "type": "string",+ "description": "Collector source name (e.g. 'space_weather')",+ },+ "limit": {+ "type": "integer",+ "description": "Captures to return (default 20, max 1000)",+ "default": 20,+ },+ "capture_id": {+ "type": "integer",+ "description": "Return this capture with its stored payload body",+ },+ },+ "required": ["source"],+ },+ ),+ Tool(+ name="intel_series_history",+ description=(+ "Observations of one series with all three dates: observed_at (period the "+ "value describes, from the payload; null when the payload has none), "+ "published_at (publisher release, when known) and collected_at (when saved). "+ "Omit series_key to list available series. " + _ACCRUAL+ ),+ inputSchema={+ "type": "object",+ "properties": {+ "series_key": {+ "type": "string",+ "description": "Series key from the listing, e.g. 'space_weather:kp'",+ },+ "source": {+ "type": "string",+ "description": "Filter the listing to one source",+ },+ "limit": {+ "type": "integer",+ "description": "Rows to return (default 100 points or 200 series, max 1000)",+ },+ },+ },+ ),+ Tool(+ name="intel_revisions",+ description=(+ "Values for the same observed_at that a later capture changed (for example "+ "USGS magnitude revisions, NOAA Kp updates), with both values and both "+ "collection times. Only changes between this server's own captures are "+ "visible. " + _ACCRUAL+ ),+ inputSchema={+ "type": "object",+ "properties": {+ "source": {"type": "string", "description": "Filter to one source"},+ "series_key": {"type": "string", "description": "Filter to one series"},+ "limit": {+ "type": "integer",+ "description": "Revisions to return (default 100, max 1000)",+ "default": 100,+ },+ },+ },+ ),+]+++def _store() -> HistoryStore:+ return HistoryStore(runtime.cache.db_path)+++async def _collection_health(arguments: dict[str, Any]) -> Any:+ from ..collector import SOURCES++ store = _store()+ try:+ return store.collection_health(+ [name for name, _, _, _ in SOURCES], source=arguments.get("source")+ )+ finally:+ store.close()+++async def _capture_history(arguments: dict[str, Any]) -> Any:+ if not arguments.get("source"):+ return {"error": "source is required (a collector source name)"}+ store = _store()+ try:+ return store.capture_history(+ arguments["source"],+ limit=arguments.get("limit", 20),+ capture_id=arguments.get("capture_id"),+ )+ finally:+ store.close()+++async def _series_history(arguments: dict[str, Any]) -> Any:+ store = _store()+ try:+ series_key = arguments.get("series_key")+ return store.series_history(+ series_key,+ source=arguments.get("source"),+ limit=arguments.get("limit", 100 if series_key else 200),+ )+ finally:+ store.close()+++async def _revisions(arguments: dict[str, Any]) -> Any:+ store = _store()+ try:+ return store.revisions(+ source=arguments.get("source"),+ series_key=arguments.get("series_key"),+ limit=arguments.get("limit", 100),+ )+ finally:+ store.close()+++HANDLERS = {+ "intel_collection_health": _collection_health,+ "intel_capture_history": _capture_history,+ "intel_series_history": _series_history,+ "intel_revisions": _revisions,+}