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
Add day timeline: intel_day_timeline and intel history day (Phase 29)
Phoenix Agent (mac-studio)6dfaf3e74616
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c12802f..1dc2e51 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -186,6 +186,47 @@ source here, and no proxy is substituted for any of these measures.terms could not be read; its RSS and warning texts served 200 to thesame client. Wind radii and seas are not parsed.+### Added: day timeline (Phase 29)+- `intel_day_timeline` (MCP) and `intel history day YYYY-MM-DD [--by+ collected|observed] [--source NAME] [--limit N] [--per-source N]` (CLI):+ what the history store holds for one UTC calendar day, the half-open+ window `[day 00:00:00Z, next day 00:00:00Z)`. Input is `YYYY-MM-DD` only;+ a malformed or impossible date, or a future day, is an error naming the+ format (the CLI exits 2). Today is allowed and reported as in progress.+- `by=collected` (default) reads the run log. Per source: attempts, ok /+ degraded / error counts with up to 5 distinct reasons, payload changes+ (changed, unchanged, first capture, not stored), first and last capture,+ observations stored and still retained, and how many of the day's+ payload bodies are still kept. Each source gets a `day_state`:+ `changed`, `unchanged`, `answered`, `degraded`, `failed`,+ `not_attempted` (the collector ran that day, not this source),+ `collector_did_not_run` (no capture of any source that day), `never_run`+ (no capture of it in the retained run log) or `unknown_past_retention`.+ A collector block gives the day's capture count, first and last capture+ and the longest stretch without any capture.+- `by=observed`: values whose `observed_at` is the day (a date) or a UTC+ instant on it, one item per series and `observed_at` with the latest+ value, how many values were stored for it and the first one when it was+ revised. Month (`YYYY-MM`) and year (`YYYY`) values containing the day+ are listed apart as period values. Observations without `observed_at`+ (Yahoo quotes) are excluded, and those collected that day are counted+ with the reason.+- Every item carries `observed_at`, `published_at` and `collected_at`.+ Retention is stated per record kind for the day (payload bodies, run+ log, observations): a day past the run-log window reads+ `unknown_past_retention`, never as a day on which nothing ran, and pruned+ payload bodies and observations that outlived their capture are counted.+ Output is capped (default 10 per source and 100 in all, at most 1,000+ and 5,000) with matched and returned counts per source.+- Read-only: the store is opened with SQLite `mode=ro`, so the tool cannot+ write it, and it never fetches. Queries range-scan+ `idx_history_captures_time` and `idx_history_obs_time` and walk+ `idx_history_obs_series` one key at a time; a test checks every+ statement's query plan for a full scan of a history table. On a+ synthetic store of 475,200 captures and 1.75 million observations+ (10,982 series), one call took 24 to 46 ms.+- Tools 152 -> 153.+### Added: observation history and collection health- A history store in the cache SQLite file. Every collector source run is acapture: source, collected_at, status (ok, degraded or error), duration,diff --git a/README.md b/README.mdindex 0638fe3..274b516 100644--- a/README.md+++ b/README.md@@ -6,7 +6,7 @@[](https://python.org)[](LICENSE)-Real-time global intelligence across **30+ domains** with **152 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 **153 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.@@ -66,9 +66,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), with opt-in forecast tracks: positions, UTC valid times and intensities, plus NHC's cone of uncertainty || **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 |+| **Collection History** | 5 | Collector run log (per-source health, overdue and failing sources), saved captures with change detection and replay, dated observation series, revisions, and one UTC day's timeline by collection or observation date |-**Total: 152 tools** across 30+ intelligence domains.+**Total: 153 tools** across 30+ intelligence domains.---@@ -142,6 +142,7 @@ intel top-stories -m 4 # stories carried by 4+ outletsintel status # cache + circuit breaker healthintel guide # the research guide (also served as intel://guide)intel history health # per-source collection health from the collector's run log+intel history day 2026-10-17 --by observed # values observed on one UTC day (default: captures that day)```---@@ -596,7 +597,7 @@ 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)+### Collection History (5)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 |@@ -605,6 +606,7 @@ History accrues only while the collector (`intel-collector`) runs; nothing befor| `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) |+| `intel_day_timeline` | What the history store holds for one UTC day (`YYYY-MM-DD`; a future day is an error). `by=collected` (default): per source, that day's captures (attempts, ok / degraded / error with reasons, changed vs unchanged payloads, first and last capture, observations stored), and for a source with no capture whether the collector did not run that day, ran without it, never ran it, or the day is past run-log retention. `by=observed`: values whose `observed_at` falls on the day; month and year values containing the day are listed apart as period values, and undated observations are counted and excluded. Every item carries `observed_at`, `published_at` and `collected_at`; pruned records are named, never read as a quiet day; per-source and total caps with truncation disclosed. Read-only, never fetches |---diff --git a/ROADMAP.md b/ROADMAP.mdindex 259a553..75608db 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -581,7 +581,7 @@ dashboard.| 1 | Kalshi + cross-venue markets | Kalshi public market data next to Polymarket; same-event comparison with an explicit match confidence; settled markets scored against pre-settlement prices (Brier) | :red_circle: || 1 | News vs market reaction | Companies and countries named in story clusters mapped to tickers / country indices; same-day move against a benchmark | :white_check_mark: Built 2026-10-17, unreleased: `intel_news_market_reaction` and `intel news-reaction`. Company rows: stock, benchmark (SPY, or the exchange country's index) and excess return on the story's session; country rows: index return with a trailing z-score. Session rule in the exchange's timezone (after close = next session; weekends and holidays read from the listing's own bars). Open: `^TASI` and `^TA125` (Saudi and Israel in the country-index table) return 404 on Yahoo, so those benchmarks are data gaps; story times inherit `sources/news.py`'s RSS timestamp offset until that is fixed || 2 | Connections with timing offsets | Correlation between retained series over a shared sample, tested at leads and lags, with minimum sample size and false-discovery control; states that it does not prove causation | :red_circle: |-| 2 | Day timeline | What every retained source recorded for a given day, by observation date or collection date | :red_circle: |+| 2 | Day timeline | What every retained source recorded for a given day, by observation date or collection date | :white_check_mark: Built 2026-10-17, unreleased: `intel_day_timeline` and `intel history day` (`history_timeline.py`; read-only `mode=ro` connection, never fetches). by=collected: per-source run-log state (changed, unchanged, answered, degraded, failed, not_attempted, collector_did_not_run, never_run, unknown_past_retention) with attempts, status counts, reasons and payload changes; by=observed: date and UTC-instant values on the day, month and year values listed apart as period values, undated observations counted and excluded. Retention is stated per record kind for the day. Measured 2026-10-17: two live collector cycles of 6 sources four minutes apart (12 captures: ok 8, degraded 2, error 2; every payload in the second cycle matched the first) read back over a live MCP stdio session and the CLI; 2026-10-16 in the same store reads `collector_did_not_run` (context `before_first_capture`). On a synthetic store (475,200 captures, 1.75 million observations, 10,982 series) one call took 24 to 46 ms, and no statement full-scans a history table under SQLite 3.45.3, 3.53.4 and 3.54.0. Not measured: a live store with weeks of history || 3 | Dashboard views | Liquidity board, situations, top stories, collection health panels | :red_circle: |Considered and not planned:diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.pyindex 23e13a5..240cf9f 100644--- a/src/world_intel_mcp/cli.py+++ b/src/world_intel_mcp/cli.py@@ -3318,5 +3318,201 @@ def history_revisions(console.print(f"[yellow]Cannot prove:[/yellow] {escape(line)}")+@history_group.command(name="day")[email protected]("day")+ "--by",+ type=click.Choice(["collected", "observed"]),+ default="collected",+ show_default=True,+ help="collected: what was captured that day; observed: values whose observed_at is that day",+)[email protected]("--source", default=None, help="One collector source name")[email protected]("--limit", default=None, type=int, help="Most items listed in all")[email protected]("--per-source", "per_source", default=None, type=int, help="Most items listed per source")[email protected]_context+def history_day(+ ctx: click.Context,+ day: str,+ by: str,+ source: str | None,+ limit: int | None,+ per_source: int | None,+) -> None:+ """What the history store recorded for one UTC day (YYYY-MM-DD)."""+ import time++ from .collector import SOURCES+ from .history_timeline import (+ DEFAULT_LIMIT,+ DEFAULT_PER_SOURCE_LIMIT,+ day_timeline,+ parse_day,+ )++ now = time.time()+ _, problem = parse_day(day, now)+ if problem:+ raise click.BadParameter(problem, param_hint="DAY")+ data = day_timeline(+ _get_fetcher().cache.db_path,+ day,+ by=by,+ source=source,+ roster=[name for name, _, _, _ in SOURCES],+ limit=DEFAULT_LIMIT if limit is None else limit,+ per_source_limit=DEFAULT_PER_SOURCE_LIMIT if per_source is None else per_source,+ now=now,+ )+ if _bail_on_error(ctx, data):+ return++ window = data["window"]+ span = f"{window['start']} to {window['end']} (end exclusive)"+ if not window["complete"]:+ span += f", in progress through {window['through']}"+ console.print(f"[bold]{data['day']}[/bold] (UTC) by {data['by']} date: {span}")+ if by == "collected":+ _print_day_collected(data)+ else:+ _print_day_observed(data)+ _print_data_gaps(data)+ for line in data["cannot_prove"]:+ console.print(f"[yellow]Cannot prove:[/yellow] {escape(line)}")+++def _print_day_collected(data: dict) -> None:+ c = data["collector"]+ if c["state"] == "ran":+ console.print(+ f"Collector: ran, {c['captures']:,} captures of {c['sources_captured']} "+ f"source(s), {c['first_capture_at']} to {c['last_capture_at']}; longest gap "+ f"{c['longest_gap_s']:,.0f} s ({c['longest_gap_from']} to {c['longest_gap_to']})"+ )+ else:+ console.print(f"Collector: [yellow]{c['state']}[/yellow]. {escape(c['explanation'])}")++ styles = {"changed": "green", "unchanged": "green", "answered": "green",+ "failed": "red", "never_run": "dim"}+ table = Table(title=f"Sources on {data['day']}", box=box.SIMPLE_HEAVY)+ for name in ("Source", "State", "Tries", "OK", "Degr", "Err", "Changed", "Same",+ "First", "Last", "Obs", "Reason / context"):+ table.add_column(name, justify="right" if name in {+ "Tries", "OK", "Degr", "Err", "Changed", "Same", "Obs"} else "left")+ for row in data["sources"]:+ counts = row.get("status_counts") or {}+ changes = row.get("payload_changes") or {}+ if row["attempts"]:+ top = (row.get("reasons") or [None])[0]+ context = f"{top['reason']} (x{top['count']})" if top else ""+ if row.get("more_reasons"):+ context += f" +{row['more_reasons']} more"+ stored = row.get("observations_stored")+ obs = "-" if stored is None else str(stored)+ else:+ parts = []+ if row.get("last_capture_before"):+ parts.append(f"last before {row['last_capture_before']}")+ if row.get("next_capture_after"):+ parts.append(f"next after {row['next_capture_after']}")+ context = ", ".join(parts)+ obs = str(row["observations_retained"]) if row["observations_retained"] else "-"+ table.add_row(+ _cell(row["source"]),+ Text(row["day_state"], style=styles.get(row["day_state"], "yellow")),+ str(row["attempts"]),+ str(counts.get("ok", "-")),+ str(counts.get("degraded", "-")),+ str(counts.get("error", "-")),+ (f"{changes['changed']}" + (f" +{changes['first']} first" if changes["first"] else ""))+ if changes else "-",+ str(changes.get("unchanged", "-")),+ _cell(row.get("first_capture_at") or "-"),+ _cell(row.get("last_capture_at") or "-"),+ obs,+ _cell(context),+ )+ console.print(table)+ states = ", ".join(f"{k} {v}" for k, v in sorted(data["state_counts"].items()))+ console.print(f"States: {states}.")++ items = data["observations"]+ trunc = data["truncation"]+ if items:+ obs_table = Table(+ title=f"Observations saved that day ({trunc['returned']:,} of {trunc['matched']:,})",+ box=box.SIMPLE_HEAVY,+ )+ for name in ("Collected", "Source", "Series", "Observed", "Published", "Value", "Unit"):+ obs_table.add_column(name, justify="right" if name == "Value" else "left")+ for item in items:+ obs_table.add_row(+ item["collected_at"],+ _cell(item["source"]),+ _cell(item["series_key"]),+ _cell(item["observed_at"] or "unknown"),+ _cell(item["published_at"] or "unknown"),+ f"{item['value']:g}",+ _cell(item.get("unit") or ""),+ )+ console.print(obs_table)+ else:+ console.print("[dim]No observations saved that day.[/dim]")+++def _print_day_observed(data: dict) -> None:+ def _points_table(title: str, points: list[dict]) -> Table:+ table = Table(title=title, box=box.SIMPLE_HEAVY)+ for name in ("Observed", "Precision", "Series", "Value", "Unit", "Published",+ "Collected", "Stored"):+ table.add_column(name, justify="right" if name in {"Value", "Stored"} else "left")+ for point in points:+ stored = str(point["stored_values"])+ if point["stored_values"] > 1:+ stored += f" (first {point['first_value']:g} at {point['first_collected_at']})"+ table.add_row(+ _cell(point["observed_at"]),+ point["precision"],+ _cell(point["series_key"]),+ f"{point['value']:g}",+ _cell(point.get("unit") or ""),+ _cell(point["published_at"] or "unknown"),+ point["collected_at"],+ stored,+ )+ return table++ day_trunc = data["truncation"]["day_values"]+ if data["day_values"]:+ console.print(_points_table(+ f"Values observed on {data['day']} ({day_trunc['returned']:,} of "+ f"{day_trunc['matched']:,})",+ data["day_values"],+ ))+ else:+ console.print(f"[yellow]No stored value is observed on {data['day']}.[/yellow]")+ if data["period_values"]:+ period_trunc = data["truncation"]["period_values"]+ console.print(_points_table(+ f"Period values containing the day, not values for it "+ f"({period_trunc['returned']:,} of {period_trunc['matched']:,})",+ data["period_values"],+ ))+ console.print(f"[dim]{escape(data['period_values_note'])}[/dim]")+ if data["sources"]:+ table = Table(title="By source", box=box.SIMPLE_HEAVY)+ for name in ("Source", "Day values", "Revised", "Period values", "No observed_at"):+ table.add_column(name, justify="left" if name == "Source" else "right")+ for row in data["sources"]:+ table.add_row(+ _cell(row["source"]),+ str(row["day_values"]),+ str(row["day_values_revised"]),+ str(row["period_values"]),+ str(row["without_observed_at_collected_that_day"]),+ )+ console.print(table)++if __name__ == "__main__":main()diff --git a/src/world_intel_mcp/history_timeline.py b/src/world_intel_mcp/history_timeline.pynew file mode 100644index 0000000..5acb95f--- /dev/null+++ b/src/world_intel_mcp/history_timeline.py@@ -0,0 +1,905 @@+"""Day timeline: what the history store holds for one UTC calendar day+(ROADMAP Phase 29).++Two views over the store that ``history.py`` keeps in the cache database,+both read through a read-only SQLite connection (``mode=ro``), so this+module cannot write the store; it never fetches upstream either.++- ``by="collected"``: the run log for the day. Per source: attempts,+ ok / degraded / error counts with their reasons, captures whose payload+ changed or matched the capture before it, first and last capture time,+ observations stored, and how many of the day's payload bodies are still+ kept. A source without a capture that day says why: the collector+ recorded no capture of any source that day, it ran but not this source,+ the source has no capture in the retained run log (``never_run``), or+ the day is past run-log retention. The observations saved that day are+ listed too.+- ``by="observed"``: observations whose ``observed_at`` falls on the day,+ as a date (``YYYY-MM-DD``) or a UTC instant, one item per series and+ observed_at with its latest stored value and how many values were+ stored for it. Month (``YYYY-MM``) and year (``YYYY``) values that+ contain the day are listed separately, as period values. Observations+ without ``observed_at`` cannot be placed on any day: they are excluded,+ and the ones collected that day are counted.++The day is ``YYYY-MM-DD`` in UTC, the half-open window+``[day 00:00:00Z, next day 00:00:00Z)``. Collection times are compared as+epoch seconds, ``observed_at`` as stored text (the store keeps instants in+UTC as ``YYYY-MM-DDTHH:MM:SSZ``). A future day is an error; today is+allowed and reported as in progress.++Retention (``history.retention_days()``) is stated per record kind for the+requested day, so a day whose records were pruned reads as pruned, never+as a day on which nothing happened.++Queries use the existing indexes: the run log and the observations saved+on a day range-scan ``idx_history_captures_time`` and+``idx_history_obs_time``; the observed-date view walks the distinct+series keys of ``idx_history_obs_series`` (one seek per key, a loose index+scan) and range-seeks each key's ``observed_at``, so only matching rows+are read.++Gaps / not covered:+- Retention windows come from this process's environment. The collector+ prunes with its own, so a collector run with different+ ``WORLD_INTEL_HISTORY_*`` values makes the windows stated here wrong.+- A date-only ``observed_at`` is the publisher's calendar date; it is+ matched to the requested day by its label, not converted from the+ publisher's time zone, which the payloads do not state.+- Collector cycles are not stored as such: "the collector did not run"+ means no capture of any source is recorded in the day's window of this+ database.+- The observed-date view costs one index seek per distinct series key.+ USGS quakes get a series per event, so the cost grows with the event+ count: about 12 ms for 11,000 series in 1.75 million rows, measured on+ a synthetic store, not on a live one.+"""++from __future__ import annotations++import re+import sqlite3+import time+from collections import Counter+from dataclasses import dataclass+from datetime import date, datetime, timedelta, timezone+from pathlib import Path+from typing import Any, Iterable++from .history import HISTORY_ACCRUAL_NOTE, retention_days++DAY_FORMAT = "YYYY-MM-DD"+VIEWS = ("collected", "observed")+DEFAULT_LIMIT = 100+DEFAULT_PER_SOURCE_LIMIT = 10+MAX_LIMIT = 5000+MAX_PER_SOURCE_LIMIT = 1000+# Distinct (status, reason) pairs shown per source; the rest are counted.+MAX_REASONS = 5++_DAY = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")+_TABLES = ("history_captures", "history_payloads", "history_observations")++# ---------------------------------------------------------------------------+# SQL. Every statement is a constant; values travel as named parameters.+# ---------------------------------------------------------------------------++_CAPTURE_SUMMARY_SQL = """+SELECT c.source, COUNT(*),+ SUM(c.status = 'ok'), SUM(c.status = 'degraded'), SUM(c.status = 'error'),+ SUM(c.status != 'error' AND c.changed IS 1),+ SUM(c.status != 'error' AND c.changed IS 0),+ SUM(c.status != 'error' AND c.payload_hash IS NOT NULL AND c.changed IS NULL),+ SUM(c.status != 'error' AND c.payload_hash IS NULL),+ MIN(c.collected_at), MAX(c.collected_at),+ SUM(c.observations_stored), COUNT(c.observations_extracted),+ SUM(c.payload_hash IS NOT NULL AND p.payload_hash IS NOT NULL),+ SUM(c.payload_hash IS NOT NULL AND p.payload_hash IS NULL)+FROM history_captures c+LEFT JOIN history_payloads p ON p.source = c.source AND p.payload_hash = c.payload_hash+WHERE c.collected_at >= :start AND c.collected_at < :end+ AND (:source IS NULL OR c.source = :source)+GROUP BY c.source+"""++_CAPTURE_REASONS_SQL = """+SELECT source, status, error, COUNT(*), MIN(collected_at), MAX(collected_at)+FROM history_captures+WHERE collected_at >= :start AND collected_at < :end AND error IS NOT NULL+ AND (:source IS NULL OR source = :source)+GROUP BY source, status, error+ORDER BY source, COUNT(*) DESC, MAX(collected_at) DESC+"""++_COLLECTOR_DAY_SQL = """+SELECT COUNT(*), COUNT(DISTINCT source), MIN(collected_at), MAX(collected_at)+FROM history_captures WHERE collected_at >= :start AND collected_at < :end+"""++_LONGEST_INTERNAL_GAP_SQL = """+SELECT prev, collected_at FROM (+ SELECT collected_at, LAG(collected_at) OVER (ORDER BY collected_at) AS prev+ FROM history_captures WHERE collected_at >= :start AND collected_at < :end+) WHERE prev IS NOT NULL+ORDER BY collected_at - prev DESC, collected_at+LIMIT 1+"""++# Two scalar subqueries: SQLite turns a lone MIN or MAX into one index+# seek, but MIN and MAX in the same SELECT scan the whole index.+_RUN_LOG_BOUNDS_SQL = (+ "SELECT (SELECT MIN(collected_at) FROM history_captures), "+ "(SELECT MAX(collected_at) FROM history_captures)"+)++_SOURCE_NEIGHBOURS_SQL = """+SELECT (SELECT MAX(collected_at) FROM history_captures+ WHERE source = :name AND collected_at < :start),+ (SELECT MIN(collected_at) FROM history_captures+ WHERE source = :name AND collected_at >= :end)+"""++# Distinct values of an indexed leading column, one index seek each.+_CAPTURE_SOURCES_SQL = """+WITH RECURSIVE s(name) AS (+ SELECT MIN(source) FROM history_captures+ UNION ALL+ SELECT (SELECT MIN(source) FROM history_captures WHERE source > s.name)+ FROM s WHERE s.name IS NOT NULL+)+SELECT name FROM s WHERE name IS NOT NULL+"""++_OBSERVATION_SOURCES_SQL = """+WITH RECURSIVE s(name) AS (+ SELECT MIN(source) FROM history_observations+ UNION ALL+ SELECT (SELECT MIN(source) FROM history_observations WHERE source > s.name)+ FROM s WHERE s.name IS NOT NULL+)+SELECT name FROM s WHERE name IS NOT NULL+"""++_COLLECTED_OBS_COUNTS_SQL = """+SELECT source, COUNT(*)+FROM history_observations+WHERE collected_at >= :start AND collected_at < :end+ AND (:source IS NULL OR source = :source)+GROUP BY source+"""++_ITEM_COLUMNS = (+ "source, series_key, observed_at, published_at, collected_at, value, unit, label, "+ "capture_id, (SELECT 1 FROM history_captures c WHERE c.id = capture_id) IS NOT NULL"+)++_COLLECTED_OBS_ITEMS_SQL = (+ "SELECT " + _ITEM_COLUMNS + " FROM ("+ " SELECT o.*, ROW_NUMBER() OVER (PARTITION BY source ORDER BY collected_at, id) AS in_source"+ " FROM history_observations o"+ " WHERE collected_at >= :start AND collected_at < :end"+ " AND (:source IS NULL OR source = :source)"+ ") WHERE in_source <= :per_source ORDER BY collected_at, id LIMIT :limit"+)++_SERIES_KEYS_CTE = """+WITH RECURSIVE keys(k) AS (+ SELECT MIN(series_key) FROM history_observations+ UNION ALL+ SELECT (SELECT MIN(series_key) FROM history_observations WHERE series_key > keys.k)+ FROM keys WHERE keys.k IS NOT NULL+)+"""++# Every stored string with the day as prefix sorts between :day and+# :day_last ('<day>T23:59:59Z'); the CASE keeps the two recognized forms+# and leaves anything else (only a writer bypassing record_cycle can+# store it) NULL, to be counted rather than shown.+_DAY_MATCHED_CTE = """+, matched AS (+ SELECT o.id, o.source, o.series_key, o.observed_at, o.published_at, o.collected_at,+ o.value, o.unit, o.label, o.capture_id,+ CASE WHEN o.observed_at = :day THEN 'date'+ WHEN o.observed_at GLOB :instant_glob THEN 'instant' END AS precision+ FROM keys JOIN history_observations o+ ON o.series_key = keys.k AND o.observed_at >= :day AND o.observed_at <= :day_last+ WHERE :source IS NULL OR o.source = :source+)+"""++_PERIOD_MATCHED_CTE = """+, matched AS (+ SELECT o.id, o.source, o.series_key, o.observed_at, o.published_at, o.collected_at,+ o.value, o.unit, o.label, o.capture_id,+ CASE o.observed_at WHEN :month THEN 'month' WHEN :year THEN 'year' END AS precision+ FROM keys JOIN history_observations o+ ON o.series_key = keys.k AND o.observed_at IN (:month, :year)+ WHERE :source IS NULL OR o.source = :source+)+"""++_POINTS_CTE = """+, points AS (+ SELECT matched.*,+ ROW_NUMBER() OVER (PARTITION BY series_key, observed_at+ ORDER BY collected_at DESC, id DESC) AS latest,+ COUNT(*) OVER (PARTITION BY series_key, observed_at) AS stored_values,+ FIRST_VALUE(value) OVER (PARTITION BY series_key, observed_at+ ORDER BY collected_at, id) AS first_value,+ FIRST_VALUE(collected_at) OVER (PARTITION BY series_key, observed_at+ ORDER BY collected_at, id) AS first_collected_at+ FROM matched+)+"""++_POINT_COUNTS_SELECT = """+SELECT source,+ SUM(precision IS NOT NULL AND latest = 1),+ SUM(precision IS NOT NULL AND latest = 1 AND stored_values > 1),+ SUM(precision IS NULL)+FROM points GROUP BY source+"""++_POINT_ITEMS_SELECT = (+ "SELECT " + _ITEM_COLUMNS + ", precision, stored_values, first_value, first_collected_at "+ "FROM ("+ " SELECT points.*, ROW_NUMBER() OVER (PARTITION BY source ORDER BY observed_at, series_key)"+ " AS in_source"+ " FROM points WHERE latest = 1 AND precision IS NOT NULL"+ ") WHERE in_source <= :per_source ORDER BY observed_at, series_key, source LIMIT :limit"+)++_DAY_COUNTS_SQL = _SERIES_KEYS_CTE + _DAY_MATCHED_CTE + _POINTS_CTE + _POINT_COUNTS_SELECT+_DAY_ITEMS_SQL = _SERIES_KEYS_CTE + _DAY_MATCHED_CTE + _POINTS_CTE + _POINT_ITEMS_SELECT+_PERIOD_COUNTS_SQL = _SERIES_KEYS_CTE + _PERIOD_MATCHED_CTE + _POINTS_CTE + _POINT_COUNTS_SELECT+_PERIOD_ITEMS_SQL = _SERIES_KEYS_CTE + _PERIOD_MATCHED_CTE + _POINTS_CTE + _POINT_ITEMS_SELECT++_NO_OBSERVED_AT_SQL = """+SELECT source, COUNT(*) FROM history_observations+WHERE collected_at >= :start AND collected_at < :end AND observed_at IS NULL+ AND (:source IS NULL OR source = :source)+GROUP BY source+"""++# ---------------------------------------------------------------------------+# Explanations returned with every answer+# ---------------------------------------------------------------------------++STATES_EXPLAINED = {+ "changed": "answered that day, and at least one delivered payload differed from the "+ "source's capture before it (or was the source's first capture)",+ "unchanged": "answered that day, and every delivered payload was identical to the "+ "capture before it",+ "answered": "answered that day, but no payload hash was stored, so change is unknown",+ "degraded": "no ok capture that day; every delivered payload was marked stale or "+ "degraded, was empty, or lacked the measures its extractor expects",+ "failed": "every attempt that day was an error (reasons lists why)",+ "not_attempted": "the collector captured other sources that day but not this one; "+ "this source has captures on other days",+ "collector_did_not_run": "no capture of any source is recorded that day",+ "never_run": "no capture of this source anywhere in the retained run log",+ "unknown_past_retention": "part or all of the day is past run-log retention and no "+ "capture of this source from it remains: whether it ran cannot be read",+}++PRECISION_EXPLAINED = {+ "date": "observed_at is the day itself, as the publisher dates it",+ "instant": "observed_at is a UTC time on the day",+ "month": "a value for the whole month containing the day, not a value for the day",+ "year": "a value for the whole year containing the day, not a value for the day",+}++_NO_OBSERVED_AT_REASON = (+ "the payload carries no observation date (for example Yahoo quotes); collected_at is "+ "when this server saved the value, not when it was observed, so it cannot be placed "+ "on an observation date"+)++_RETENTION_ENV_NOTE = (+ "Retention windows are read from this server's environment "+ "(WORLD_INTEL_HISTORY_PAYLOAD_DAYS, WORLD_INTEL_HISTORY_CAPTURE_DAYS, "+ "WORLD_INTEL_HISTORY_DAYS); the collector prunes with its own, at the end of each cycle."+)+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _iso(ts: float | None) -> str | None:+ if ts is None:+ return None+ try:+ return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+ except (OverflowError, OSError, ValueError):+ return None+++def _bounded(value: Any, default: int, maximum: int) -> int:+ try:+ number = int(value)+ except (TypeError, ValueError):+ return default+ return max(1, min(maximum, number))+++def parse_day(value: Any, now: float) -> tuple[date | None, str | None]:+ """``YYYY-MM-DD`` -> (date, None), or (None, problem)."""+ if not isinstance(value, str) or not _DAY.fullmatch(value):+ return None, f"day must be {DAY_FORMAT}, a UTC calendar date; got {value!r}"+ try:+ day = date.fromisoformat(value)+ except ValueError:+ return None, f"day must be a real calendar date in {DAY_FORMAT}; got {value!r}"+ today = datetime.fromtimestamp(now, tz=timezone.utc).date()+ if day > today:+ return None, f"day {value} is in the future (today is {today.isoformat()} UTC)"+ return day, None+++@dataclass(frozen=True)+class _Window:+ day: date+ start: float+ end: float+ now: float++ @classmethod+ def for_day(cls, day: date, now: float) -> "_Window":+ start = datetime(day.year, day.month, day.day, tzinfo=timezone.utc).timestamp()+ return cls(day, start, start + 86400.0, now)++ @property+ def in_progress(self) -> bool:+ return self.now < self.end++ def describe(self) -> dict:+ nxt = self.day + timedelta(days=1)+ out = {+ "start": f"{self.day.isoformat()}T00:00:00Z",+ "end": f"{nxt.isoformat()}T00:00:00Z",+ "end_exclusive": True,+ "complete": not self.in_progress,+ }+ if self.in_progress:+ out["through"] = _iso(self.now)+ return out+++class _Reader:+ """Read-only access; with no store every query reads as empty."""++ def __init__(self, conn: sqlite3.Connection | None):+ self.conn = conn++ def all(self, sql: str, params: dict | None = None) -> list[tuple]:+ if self.conn is None:+ return []+ return self.conn.execute(sql, params or {}).fetchall()++ def one(self, sql: str, params: dict | None, default: tuple) -> tuple:+ rows = self.all(sql, params)+ return rows[0] if rows else default+++def _connect(db_path: Path) -> sqlite3.Connection | None:+ """A read-only connection, or None when the database does not exist+ (opening it read-only never creates it)."""+ path = Path(db_path).resolve()+ if not path.exists():+ return None+ return sqlite3.connect(f"{path.as_uri()}?mode=ro", uri=True, timeout=10)+++def _has_history_tables(conn: sqlite3.Connection) -> bool:+ found = {+ row[0]+ for row in conn.execute(+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?)",+ _TABLES,+ )+ }+ return found == set(_TABLES)+++def _retention(window: _Window) -> dict:+ """Configured window per record kind, against the requested day."""+ days = retention_days()+ out: dict[str, Any] = {"note": _RETENTION_ENV_NOTE}+ for label, key in (+ ("payload_bodies", "payload_days"),+ ("run_log", "capture_days"),+ ("observations", "history_days"),+ ):+ span = days[key]+ if span <= 0:+ out[label] = {"days": span, "cutoff": None, "day": "kept_forever"}+ continue+ cutoff = window.now - span * 86400+ if window.end <= cutoff:+ status = "past_window"+ elif window.start < cutoff:+ status = "partly_past_window"+ else:+ status = "within_window"+ out[label] = {"days": span, "cutoff": _iso(cutoff), "cutoff_ts": cutoff, "day": status}+ return out+++def _public_retention(retention: dict) -> dict:+ return {+ k: ({kk: vv for kk, vv in v.items() if kk != "cutoff_ts"} if isinstance(v, dict) else v)+ for k, v in retention.items()+ }+++def _item(row: tuple) -> dict:+ (source, series_key, observed_at, published_at, collected_at, value, unit, label,+ capture_id, capture_retained) = row[:10]+ return {+ "source": source,+ "series_key": series_key,+ "observed_at": observed_at,+ "published_at": published_at,+ "collected_at": _iso(collected_at),+ "value": value,+ "unit": unit,+ "label": label,+ "capture_id": capture_id,+ "capture_retained": bool(capture_retained),+ }+++def _point(row: tuple) -> dict:+ item = _item(row)+ precision, stored_values, first_value, first_collected_at = row[10:14]+ item["precision"] = precision+ item["stored_values"] = stored_values+ if stored_values > 1:+ item["first_value"] = first_value+ item["first_collected_at"] = _iso(first_collected_at)+ return item+++def _truncation(matched_by_source: dict[str, int], items: list[dict], limit: int,+ per_source: int) -> dict:+ returned = Counter(item["source"] for item in items)+ matched = sum(matched_by_source.values())+ return {+ "matched": matched,+ "returned": len(items),+ "truncated": len(items) < matched,+ "limit": limit,+ "per_source_limit": per_source,+ "sources_truncated": {+ name: {"matched": count, "returned": returned.get(name, 0)}+ for name, count in sorted(matched_by_source.items())+ if returned.get(name, 0) < count+ },+ }+++def _truncation_gap(what: str, block: dict, order: str) -> str | None:+ if not block["truncated"]:+ return None+ return (+ f"{what}: {block['returned']:,} of {block['matched']:,} returned ({order}; at most "+ f"{block['per_source_limit']:,} per source and {block['limit']:,} in all). The per-source "+ "counts are complete; raise limit or per_source_limit, or pass source, to see more."+ )+++# ---------------------------------------------------------------------------+# by="collected"+# ---------------------------------------------------------------------------+++def _collector_block(r: _Reader, w: _Window, run_log: dict) -> dict:+ params = {"start": w.start, "end": w.end}+ captures, sources, first, last = r.one(_COLLECTOR_DAY_SQL, params, (0, 0, None, None))+ log_first, log_last = r.one(_RUN_LOG_BOUNDS_SQL, None, (None, None))+ block: dict[str, Any] = {+ "captures": captures,+ "sources_captured": sources,+ "run_log_first_capture_at": _iso(log_first),+ "run_log_last_capture_at": _iso(log_last),+ }+ if captures:+ # The retained part of the day starts at the run-log cutoff when+ # the day straddles it; time before that is unknown, not silent.+ lower = w.start+ if run_log["day"] == "partly_past_window":+ lower = min(max(w.start, run_log["cutoff_ts"]), first)+ spans = [(lower, first), (last, min(w.end, w.now))]+ internal = r.one(_LONGEST_INTERNAL_GAP_SQL, params, (None, None))+ if internal[0] is not None:+ spans.append(internal)+ gap_from, gap_to = max(spans, key=lambda span: span[1] - span[0])+ block.update(+ state="ran",+ first_capture_at=_iso(first),+ last_capture_at=_iso(last),+ longest_gap_s=round(max(0.0, gap_to - gap_from), 1),+ longest_gap_from=_iso(gap_from),+ longest_gap_to=_iso(gap_to),+ explanation=f"{captures:,} captures of {sources} source(s) are recorded that day.",+ )+ return block+ if run_log["day"] in ("past_window", "partly_past_window"):+ block.update(+ state="unknown_past_retention",+ explanation=(+ f"No capture from this day remains, and the day is past the "+ f"{run_log['days']:g}-day run-log retention (cutoff {run_log['cutoff']}): "+ "whether the collector ran cannot be read."+ ),+ )+ return block+ if log_first is None:+ context, why = "empty_run_log", "the run log has no capture at all in this database"+ elif log_first >= w.end:+ context, why = "before_first_capture", f"the run log starts later, at {_iso(log_first)}"+ elif log_last < w.start:+ context, why = "after_last_capture", f"no capture is recorded since {_iso(log_last)}"+ else:+ context, why = "between_captures", "captures exist before and after this day"+ block.update(+ state="did_not_run",+ context=context,+ explanation=f"The collector recorded no capture of any source that day: {why}.",+ )+ return block+++def _captured_state(ok: int, degraded: int, changed: int, unchanged: int, first: int) -> str:+ if ok == 0 and degraded == 0:+ return "failed"+ if ok == 0:+ return "degraded"+ if changed or first:+ return "changed"+ if unchanged:+ return "unchanged"+ return "answered"+++def _collected_view(r: _Reader, w: _Window, names: list[str], roster: set[str],+ source: str | None, limit: int, per_source: int,+ retention: dict) -> dict:+ params = {"start": w.start, "end": w.end, "source": source}+ run_log = retention["run_log"]+ summary = {row[0]: row for row in r.all(_CAPTURE_SUMMARY_SQL, params)}+ reasons: dict[str, list[tuple]] = {}+ for row in r.all(_CAPTURE_REASONS_SQL, params):+ reasons.setdefault(row[0], []).append(row[1:])+ obs_counts = dict(r.all(_COLLECTED_OBS_COUNTS_SQL, params))+ collector = _collector_block(r, w, run_log)++ if source is None:+ names = names + sorted((set(summary) | set(obs_counts)) - set(names))+ rows = []+ for name in names:+ retained_obs = obs_counts.get(name, 0)+ entry: dict[str, Any] = {"source": name, "in_collector_roster": name in roster}+ cap = summary.get(name)+ if cap is None:+ if run_log["day"] in ("past_window", "partly_past_window"):+ state = "unknown_past_retention"+ else:+ before, after = r.one(+ _SOURCE_NEIGHBOURS_SQL, {"name": name, "start": w.start, "end": w.end},+ (None, None),+ )+ if before is None and after is None:+ state = "never_run"+ elif collector["captures"] == 0:+ state = "collector_did_not_run"+ else:+ state = "not_attempted"+ entry["last_capture_before"] = _iso(before)+ entry["next_capture_after"] = _iso(after)+ entry.update(day_state=state, attempts=0, observations_retained=retained_obs)+ rows.append(entry)+ continue+ (_, attempts, ok, degraded, error, changed, unchanged, first, not_stored,+ first_at, last_at, obs_stored, with_extractor, bodies_kept, bodies_pruned) = cap+ source_reasons = reasons.get(name, [])+ entry.update(+ day_state=_captured_state(ok, degraded, changed, unchanged, first),+ attempts=attempts,+ status_counts={"ok": ok, "degraded": degraded, "error": error},+ payload_changes={+ "changed": changed, "unchanged": unchanged, "first": first,+ "not_stored": not_stored,+ },+ first_capture_at=_iso(first_at),+ last_capture_at=_iso(last_at),+ observations_stored=obs_stored if with_extractor else None,+ observations_retained=retained_obs,+ captures_with_body_retained=bodies_kept,+ captures_with_body_pruned=bodies_pruned,+ reasons=[+ {"status": status, "reason": reason, "count": count,+ "first_at": _iso(r_first), "last_at": _iso(r_last)}+ for status, reason, count, r_first, r_last in source_reasons[:MAX_REASONS]+ ],+ )+ if len(source_reasons) > MAX_REASONS:+ entry["more_reasons"] = len(source_reasons) - MAX_REASONS+ rows.append(entry)++ items = [+ _item(row)+ for row in r.all(+ _COLLECTED_OBS_ITEMS_SQL, {**params, "per_source": per_source, "limit": limit}+ )+ ]+ truncation = _truncation(obs_counts, items, limit, per_source)++ gaps = []+ retained_captures = sum(row[1] for row in summary.values())+ if run_log["day"] == "past_window":+ if retained_captures:+ gaps.append(+ f"This day is past the {run_log['days']:g}-day run-log retention (cutoff "+ f"{run_log['cutoff']}); its {retained_captures:,} captures are still here only "+ "because pruning runs at the end of a collector cycle, and the next cycle "+ "removes them."+ )+ else:+ gaps.append(+ f"The run log keeps captures {run_log['days']:g} days (cutoff "+ f"{run_log['cutoff']}); this day is past it, so its captures are gone. Whether "+ "the collector or any source ran that day cannot be read here: absence is "+ "not evidence that nothing happened."+ )+ elif run_log["day"] == "partly_past_window":+ gaps.append(+ f"Captures before {run_log['cutoff']} (the {run_log['days']:g}-day run-log cutoff) "+ "are pruned: this day's earlier hours may be missing from the counts above, and "+ "a source shown as unknown_past_retention may have run then."+ )+ pruned_bodies = sum(row[14] for row in summary.values())+ kept_bodies = sum(row[13] for row in summary.values())+ if pruned_bodies:+ gaps.append(+ f"Payload bodies of {pruned_bodies:,} of this day's captures were pruned (bodies "+ f"are kept {retention['payload_bodies']['days']:g} days after the payload was last "+ "seen); intel_capture_history can replay only captures whose body is retained "+ f"({kept_bodies:,} of {kept_bodies + pruned_bodies:,})."+ )+ observations = retention["observations"]+ if observations["day"] in ("past_window", "partly_past_window"):+ gaps.append(+ f"Observations collected before {observations['cutoff']} are past the "+ f"{observations['days']:g}-day retention and pruned; observations_retained counts "+ "only what remains."+ )+ truncated = _truncation_gap("Observations saved that day", truncation, "earliest first")+ if truncated:+ gaps.append(truncated)++ states: dict[str, int] = {}+ for entry in rows:+ states[entry["day_state"]] = states.get(entry["day_state"], 0) + 1+ return {+ "collector": collector,+ "sources": rows,+ "state_counts": states,+ "observations": items,+ "truncation": truncation,+ "data_gaps": gaps,+ "states_explained": STATES_EXPLAINED,+ "cannot_prove": [+ "This is the run log of the database this server reads; a collector writing "+ "to another cache database is invisible here.",+ "changed compares each capture's payload hash with the source's previous "+ "capture: the stored payload differed, which does not by itself show the "+ "upstream published new data.",+ "A degraded capture with no records cannot tell a quiet period from a silent "+ "upstream failure.",+ HISTORY_ACCRUAL_NOTE,+ ],+ }+++# ---------------------------------------------------------------------------+# by="observed"+# ---------------------------------------------------------------------------+++def _observed_view(r: _Reader, w: _Window, obs_sources: list[str], roster: set[str],+ source: str | None, limit: int, per_source: int,+ retention: dict) -> dict:+ day = w.day.isoformat()+ base = {"source": source, "per_source": per_source, "limit": limit}+ day_params = {**base, "day": day, "day_last": f"{day}T23:59:59Z",+ "instant_glob": f"{day}T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]Z"}+ period_params = {**base, "month": day[:7], "year": day[:4]}++ day_counts = {row[0]: row[1:] for row in r.all(_DAY_COUNTS_SQL, day_params)}+ period_counts = {row[0]: row[1:] for row in r.all(_PERIOD_COUNTS_SQL, period_params)}+ no_date = dict(r.all(_NO_OBSERVED_AT_SQL, {"start": w.start, "end": w.end, "source": source}))+ day_items = [_point(row) for row in r.all(_DAY_ITEMS_SQL, day_params)]+ period_items = [_point(row) for row in r.all(_PERIOD_ITEMS_SQL, period_params)]++ names = [source] if source is not None else sorted(+ set(obs_sources) | set(day_counts) | set(period_counts) | set(no_date)+ )+ rows = []+ for name in names:+ values, revised, unrecognized = day_counts.get(name, (0, 0, 0))+ periods = period_counts.get(name, (0, 0, 0))+ rows.append({+ "source": name,+ "in_collector_roster": name in roster,+ "day_values": values,+ "day_values_revised": revised,+ "period_values": periods[0],+ "unrecognized_observed_at": unrecognized,+ "without_observed_at_collected_that_day": no_date.get(name, 0),+ })++ day_truncation = _truncation(+ {name: c[0] for name, c in day_counts.items() if c[0]}, day_items, limit, per_source+ )+ period_truncation = _truncation(+ {name: c[0] for name, c in period_counts.items() if c[0]}, period_items, limit,+ per_source,+ )+ gaps = []+ excluded = sum(no_date.values())+ if excluded:+ by_source = ", ".join(f"{name} {count:,}" for name, count in sorted(no_date.items()))+ gaps.append(+ f"{excluded:,} observation(s) collected this day have no observed_at "+ f"({by_source}) and are excluded: {_NO_OBSERVED_AT_REASON}. by=collected lists them."+ )+ unrecognized_total = sum(c[2] for c in day_counts.values())+ if unrecognized_total:+ gaps.append(+ f"{unrecognized_total:,} stored observed_at value(s) on this day are in neither "+ f"recognized form ({day} or {day}THH:MM:SSZ) and are excluded; only a writer "+ "that bypasses the history store's validation can store them."+ )+ observations = retention["observations"]+ if observations["day"] in ("past_window", "partly_past_window"):+ gaps.append(+ f"Observations are pruned {observations['days']:g} days after collection (cutoff "+ f"{observations['cutoff']}): values for this day collected before then are gone, "+ "and only later ones (revisions, late reports) remain."+ )+ pruned_captures = sum(+ 1 for item in day_items + period_items if not item["capture_retained"]+ )+ if pruned_captures:+ gaps.append(+ f"{pruned_captures:,} listed value(s) outlived the capture that produced them "+ f"(the run log keeps {retention['run_log']['days']:g} days); capture_retained "+ "marks them."+ )+ for what, block in (("Day values", day_truncation), ("Period values", period_truncation)):+ truncated = _truncation_gap(what, block, "by observed_at, then series")+ if truncated:+ gaps.append(truncated)+ if w.in_progress:+ gaps.append("The day is in progress: values observed later today may still arrive.")+ return {+ "day_values": day_items,+ "period_values": period_items,+ "period_values_note": (+ f"Period values describe the whole month {day[:7]} or year {day[:4]}, not "+ f"{day}; they are listed apart from the day's values."+ ),+ "sources": rows,+ "without_observed_at": {+ "collected_that_day": excluded,+ "by_source": dict(sorted(no_date.items())),+ "reason": _NO_OBSERVED_AT_REASON,+ },+ "truncation": {"day_values": day_truncation, "period_values": period_truncation},+ "precision_explained": PRECISION_EXPLAINED,+ "data_gaps": gaps,+ "cannot_prove": [+ "observed_at comes from each payload. A date-only value is the publisher's "+ "calendar date, matched to this day by its label, not converted from the "+ "publisher's time zone.",+ "Only values this server saw are here: a value published and revised between "+ "two captures, or while the collector was not running, is not.",+ "Only sources with a registered history extractor store observations; the "+ "others appear only in by=collected.",+ HISTORY_ACCRUAL_NOTE,+ ],+ }+++# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------+++def day_timeline(+ db_path: Path | str,+ day: Any,+ *,+ by: Any = "collected",+ source: Any = None,+ roster: Iterable[str] = (),+ limit: Any = DEFAULT_LIMIT,+ per_source_limit: Any = DEFAULT_PER_SOURCE_LIMIT,+ now: float | None = None,+) -> dict:+ """What the history store at ``db_path`` holds for one UTC day.++ ``roster`` is the collector's source list (sources that should have a+ run-log state even with no capture). Read-only: opens the database+ with ``mode=ro`` and never fetches.+ """+ now = time.time() if now is None else now+ parsed, problem = parse_day(day, now)+ if problem:+ return {"error": problem, "accepted_format": DAY_FORMAT, "timezone": "UTC"}+ if by not in VIEWS:+ return {"error": f"by must be 'collected' or 'observed'; got {by!r}"}+ if source is not None and (not isinstance(source, str) or not source):+ return {"error": f"source must be a source name; got {source!r}"}+ limit = _bounded(limit, DEFAULT_LIMIT, MAX_LIMIT)+ per_source = _bounded(per_source_limit, DEFAULT_PER_SOURCE_LIMIT, MAX_PER_SOURCE_LIMIT)+ window = _Window.for_day(parsed, now)+ roster_names = list(dict.fromkeys(roster))++ try:+ conn = _connect(Path(db_path))+ except sqlite3.Error as exc:+ return {"error": f"history store could not be opened read-only: {exc}"}+ try:+ ready = conn is not None and _has_history_tables(conn)+ r = _Reader(conn if ready else None)+ logged = [row[0] for row in r.all(_CAPTURE_SOURCES_SQL)]+ obs_sources = [row[0] for row in r.all(_OBSERVATION_SOURCES_SQL)]+ known = set(roster_names) | set(logged) | set(obs_sources)+ if source is not None and source not in known:+ return {+ "error": f"unknown source {source!r}: not a collector source and nothing "+ "recorded under that name",+ "known_sources": sorted(known),+ }+ retention = _retention(window)+ if by == "collected":+ names = [source] if source is not None else roster_names + sorted(+ set(logged) - set(roster_names)+ )+ view = _collected_view(r, window, names, set(roster_names), source, limit,+ per_source, retention)+ else:+ view = _observed_view(r, window, obs_sources, set(roster_names), source, limit,+ per_source, retention)+ except sqlite3.Error as exc:+ return {"error": f"history store could not be read: {type(exc).__name__}: {exc}"}+ finally:+ if conn is not None:+ conn.close()++ if not ready:+ view["data_gaps"].insert(+ 0,+ f"No history tables in {Path(db_path)}: the collector has not recorded a cycle "+ "in this database, so there is nothing to read for any day.",+ )+ if by == "collected" and window.in_progress:+ view["data_gaps"].append(+ f"The day is in progress: counts run through {_iso(now)}, and sources not yet "+ "attempted today may still run."+ )+ return {+ "day": parsed.isoformat(),+ "timezone": "UTC",+ "by": by,+ "window": window.describe(),+ "source_filter": source,+ **view,+ "retention": _public_retention(retention),+ "db_path": str(db_path),+ "note": HISTORY_ACCRUAL_NOTE,+ }diff --git a/src/world_intel_mcp/tests/test_history_timeline.py b/src/world_intel_mcp/tests/test_history_timeline.pynew file mode 100644index 0000000..07ffd0b--- /dev/null+++ b/src/world_intel_mcp/tests/test_history_timeline.py@@ -0,0 +1,842 @@+"""Tests for the day timeline (history_timeline.py), the intel_day_timeline+tool and the ``intel history day`` command.++Every store here is a real ``HistoryStore`` on a tmp SQLite file, written+through ``record_cycle`` (the collector's write path, retention pruning+included) and read back through the day timeline's read-only connection.+Assertions are exact values at a fixed ``now``: which day a capture at+23:59:59Z or 00:00:00Z lands on, per-source states and counts, retention+verdicts, truncation counts. The tool and CLI tests use days relative to+the real clock because those paths read ``time.time()``.+"""++import contextlib+import hashlib+import json+import os+import re+import sqlite3+import types+from datetime import datetime, timedelta, timezone++import httpx+import pytest+from click.testing import CliRunner++from world_intel_mcp import cli, collector, history, history_timeline+from world_intel_mcp.history import HistoryStore, Observation, SourceOutcome+from world_intel_mcp.history_timeline import day_timeline+++def at(text: str) -> float:+ return datetime.fromisoformat(text.replace("Z", "+00:00")).timestamp()+++NOON = at("2026-10-17T12:00:00Z") # "now" while 2026-10-17 is in progress+LATER = at("2026-10-20T12:00:00Z") # "now" once 2026-10-17 is complete+# 2026 in fullwidth digits: a regex \d and int() accept them; the day pattern is [0-9].+_FULLWIDTH_YEAR = "".join(chr(0xFF10 + int(d)) for d in "2026")++[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 db(tmp_path):+ return tmp_path / "history.db"+++def store(db):+ s = HistoryStore(db)+ yield s+ s.close()+++def feeds(monkeypatch):+ """Register a test extractor for feed_a and feed_b: the payload lists+ (series, value, observed_at) points."""+ monkeypatch.setattr(history, "_EXTRACTORS", dict(history._EXTRACTORS))++ def _extract(payload):+ return [Observation(key, value, observed_at=obs) for key, value, obs in payload["points"]]++ history.register_extractor("feed_a", _extract)+ history.register_extractor("feed_b", _extract)+ return lambda *points: {"points": [list(p) for p in points], "rows": [1]}+++def out(source, when, payload=None, error=None):+ return SourceOutcome(source, at(when), 1.0, payload, error)+++def cycle(store, when, *outcomes):+ """One collector cycle, pruned as the collector would at ``when``."""+ return store.record_cycle(list(outcomes), now=at(when))+++def kp(*rows):+ return {"kp_recent": [{"time": t, "kp": v} for t, v in rows], "alerts": []}+++def by_source(result):+ return {row["source"]: row for row in result["sources"]}+++# ---------------------------------------------------------------------------+# Input: YYYY-MM-DD, UTC, never in the future+# ---------------------------------------------------------------------------+++ "day",+ [+ "2026-10-17T00:00:00Z", "2026/10/17", "20261017", "2026-W42-6", "2026-1-07",+ "", " 2026-10-17", "2026-10-17 ", _FULLWIDTH_YEAR + "-10-17", None, 20261017,+ ],+)+def test_malformed_day_is_an_error_naming_the_format(db, day) -> None:+ result = day_timeline(db, day, now=NOON)+ assert result == {+ "error": f"day must be YYYY-MM-DD, a UTC calendar date; got {day!r}",+ "accepted_format": "YYYY-MM-DD",+ "timezone": "UTC",+ }+ assert not db.exists() # a refused request opens nothing+++def test_impossible_and_future_days_are_errors(db) -> None:+ assert day_timeline(db, "2026-02-30", now=NOON)["error"] == (+ "day must be a real calendar date in YYYY-MM-DD; got '2026-02-30'"+ )+ assert day_timeline(db, "2026-10-18", now=NOON)["error"] == (+ "day 2026-10-18 is in the future (today is 2026-10-17 UTC)"+ )+ # Today is UTC today: one second before midnight UTC, tomorrow is refused.+ assert "in the future" in day_timeline(db, "2026-10-18", now=at("2026-10-17T23:59:59Z"))["error"]+ assert "error" not in day_timeline(db, "2026-10-18", now=at("2026-10-18T00:00:00Z"))+++def test_other_arguments_are_checked(db) -> None:+ assert day_timeline(db, "2026-10-17", by="hourly", now=NOON)["error"] == (+ "by must be 'collected' or 'observed'; got 'hourly'"+ )+ assert day_timeline(db, "2026-10-17", source=5, now=NOON)["error"] == (+ "source must be a source name; got 5"+ )+++def test_window_is_stated_in_utc_and_today_reads_in_progress(store, db) -> None:+ cycle(store, "2026-10-17T01:00:00Z", out("space_weather", "2026-10-17T01:00:00Z", kp(("2026-10-17T00:00:00Z", 2.0))))+ today = day_timeline(db, "2026-10-17", now=NOON)+ assert (today["day"], today["timezone"], today["by"]) == ("2026-10-17", "UTC", "collected")+ assert today["window"] == {+ "start": "2026-10-17T00:00:00Z", "end": "2026-10-18T00:00:00Z", "end_exclusive": True,+ "complete": False, "through": "2026-10-17T12:00:00Z",+ }+ assert today["data_gaps"][-1].startswith("The day is in progress: counts run through 2026-10-17T12:00:00Z")+ # In progress, the longest gap runs to now, not to midnight.+ assert (today["collector"]["longest_gap_from"], today["collector"]["longest_gap_to"]) == (+ "2026-10-17T01:00:00Z", "2026-10-17T12:00:00Z"+ )+ done = day_timeline(db, "2026-10-17", now=LATER)+ assert done["window"]["complete"] is True and "through" not in done["window"]+ assert done["collector"]["longest_gap_to"] == "2026-10-18T00:00:00Z"+ assert not any("in progress" in gap for gap in done["data_gaps"])+++# ---------------------------------------------------------------------------+# The day boundary+# ---------------------------------------------------------------------------+++def test_midnight_boundary_puts_each_record_on_exactly_one_day(store, db) -> None:+ cycle(store, "2026-10-16T23:59:59Z",+ out("space_weather", "2026-10-16T23:59:59Z", kp(("2026-10-16T23:59:59Z", 1.0))))+ cycle(store, "2026-10-17T00:00:00Z",+ out("space_weather", "2026-10-17T00:00:00Z",+ kp(("2026-10-16T23:59:59Z", 1.0), ("2026-10-17T00:00:00Z", 2.0))))+ roster = ["space_weather"]+ before = day_timeline(db, "2026-10-16", roster=roster, now=LATER)+ after = day_timeline(db, "2026-10-17", roster=roster, now=LATER)+ b, a = by_source(before)["space_weather"], by_source(after)["space_weather"]+ assert (b["attempts"], b["first_capture_at"], b["last_capture_at"]) == (+ 1, "2026-10-16T23:59:59Z", "2026-10-16T23:59:59Z"+ )+ assert (a["attempts"], a["first_capture_at"], a["last_capture_at"]) == (+ 1, "2026-10-17T00:00:00Z", "2026-10-17T00:00:00Z"+ )+ assert (before["collector"]["captures"], after["collector"]["captures"]) == (1, 1)+ assert [(o["collected_at"], o["observed_at"]) for o in before["observations"]] == [+ ("2026-10-16T23:59:59Z", "2026-10-16T23:59:59Z")+ ]+ assert [(o["collected_at"], o["observed_at"]) for o in after["observations"]] == [+ ("2026-10-17T00:00:00Z", "2026-10-17T00:00:00Z")+ ]+ seen_16 = day_timeline(db, "2026-10-16", by="observed", now=LATER)["day_values"]+ seen_17 = day_timeline(db, "2026-10-17", by="observed", now=LATER)["day_values"]+ assert [p["observed_at"] for p in seen_16] == ["2026-10-16T23:59:59Z"]+ assert [p["observed_at"] for p in seen_17] == ["2026-10-17T00:00:00Z"]+++# ---------------------------------------------------------------------------+# by=collected: per-source states from the run log+# ---------------------------------------------------------------------------++ROSTER = ["space_weather", "earthquakes", "gas_prices", "market_quotes", "wildfires", "cyclones"]+++def _busy_day(store) -> None:+ calm = kp(("2026-10-16T09:00:00Z", 2.0))+ cycle(store, "2026-10-16T12:00:00Z",+ out("space_weather", "2026-10-16T12:00:00Z", calm),+ out("wildfires", "2026-10-16T12:00:00Z", {"fires": [1]}))+ cycle(store, "2026-10-17T01:00:00Z",+ out("space_weather", "2026-10-17T01:00:00Z", calm),+ out("earthquakes", "2026-10-17T01:00:00Z", error="timeout (45.0s)"),+ out("gas_prices", "2026-10-17T01:00:00Z",+ {"prices": [1], "_stale": True, "_stale_age_seconds": 812.0}),+ out("market_quotes", "2026-10-17T01:00:00Z", {"quotes": [{"symbol": "^GSPC", "price": 6000.0}]}),+ out("weird_source", "2026-10-17T01:00:00Z", {"rows": [1], "by_key": {1: "a", "b": 2}}))+ cycle(store, "2026-10-17T01:05:00Z",+ out("space_weather", "2026-10-17T01:05:00Z", calm),+ out("earthquakes", "2026-10-17T01:05:00Z", error="boom"),+ out("gas_prices", "2026-10-17T01:05:00Z",+ {"prices": [1], "_stale": True, "_stale_age_seconds": 1112.0}),+ out("market_quotes", "2026-10-17T01:05:00Z", {"quotes": [{"symbol": "^GSPC", "price": 6001.0}]}))+ cycle(store, "2026-10-17T01:10:00Z",+ out("earthquakes", "2026-10-17T01:10:00Z", error="timeout (45.0s)"))+++def test_collected_view_distinguishes_every_source_state(store, db) -> None:+ _busy_day(store)+ result = day_timeline(db, "2026-10-17", roster=ROSTER, now=LATER)+ rows = by_source(result)+ assert [r["source"] for r in result["sources"]] == ROSTER + ["weird_source"]++ sw = rows["space_weather"]+ assert sw["day_state"] == "unchanged"+ assert (sw["attempts"], sw["status_counts"]) == (2, {"ok": 2, "degraded": 0, "error": 0})+ assert sw["payload_changes"] == {"changed": 0, "unchanged": 2, "first": 0, "not_stored": 0}+ # Its extractor ran and found nothing new: 0, not "no extractor".+ assert (sw["observations_stored"], sw["observations_retained"]) == (0, 0)+ assert (sw["captures_with_body_retained"], sw["captures_with_body_pruned"]) == (2, 0)++ quakes = rows["earthquakes"]+ assert quakes["day_state"] == "failed"+ assert quakes["status_counts"] == {"ok": 0, "degraded": 0, "error": 3}+ assert [(r["status"], r["reason"], r["count"]) for r in quakes["reasons"]] == [+ ("error", "timeout (45.0s)", 2), ("error", "boom", 1)+ ]+ assert (quakes["reasons"][0]["first_at"], quakes["reasons"][0]["last_at"]) == (+ "2026-10-17T01:00:00Z", "2026-10-17T01:10:00Z"+ )+ assert quakes["observations_stored"] is None # no capture ran an extractor++ gas = rows["gas_prices"]+ assert gas["day_state"] == "degraded"+ assert gas["payload_changes"] == {"changed": 0, "unchanged": 1, "first": 1, "not_stored": 0}+ assert [r["reason"] for r in gas["reasons"]] == [+ "served stale cache (age 1112.0 s)", "served stale cache (age 812.0 s)"+ ]++ quotes = rows["market_quotes"]+ assert quotes["day_state"] == "changed"+ assert quotes["payload_changes"] == {"changed": 1, "unchanged": 0, "first": 1, "not_stored": 0}+ assert (quotes["first_capture_at"], quotes["last_capture_at"]) == (+ "2026-10-17T01:00:00Z", "2026-10-17T01:05:00Z"+ )+ assert (quotes["observations_stored"], quotes["observations_retained"]) == (2, 2)++ fires = rows["wildfires"]+ assert (fires["day_state"], fires["attempts"]) == ("not_attempted", 0)+ assert (fires["last_capture_before"], fires["next_capture_after"]) == ("2026-10-16T12:00:00Z", None)+ assert rows["cyclones"]["day_state"] == "never_run"++ weird = rows["weird_source"]+ assert (weird["day_state"], weird["in_collector_roster"]) == ("answered", False)+ assert weird["payload_changes"]["not_stored"] == 1+ assert weird["reasons"][0]["status"] == "ok"+ assert weird["reasons"][0]["reason"].startswith("payload not stored in history: TypeError")++ assert result["state_counts"] == {+ "unchanged": 1, "failed": 1, "degraded": 1, "changed": 1, "not_attempted": 1,+ "never_run": 1, "answered": 1,+ }+ assert set(result["state_counts"]) <= set(result["states_explained"])+ c = result["collector"]+ assert (c["state"], c["captures"], c["sources_captured"]) == ("ran", 10, 5)+ assert (c["first_capture_at"], c["last_capture_at"]) == ("2026-10-17T01:00:00Z", "2026-10-17T01:10:00Z")+ assert (c["longest_gap_s"], c["longest_gap_from"], c["longest_gap_to"]) == (+ 82_200.0, "2026-10-17T01:10:00Z", "2026-10-18T00:00:00Z"+ )+ # Saved observations: the two quote prices, each with its three dates.+ assert [(o["series_key"], o["value"], o["observed_at"], o["published_at"], o["collected_at"])+ for o in result["observations"]] == [+ ("market_quotes:^GSPC:price", 6000.0, None, None, "2026-10-17T01:00:00Z"),+ ("market_quotes:^GSPC:price", 6001.0, None, None, "2026-10-17T01:05:00Z"),+ ]+ assert result["data_gaps"] == []+++def test_reasons_are_capped_per_source_and_the_rest_counted(store, db) -> None:+ for minute in range(7):+ when = f"2026-10-17T01:{minute:02d}:00Z"+ cycle(store, when, out("earthquakes", when, error=f"failure {minute}"))+ row = by_source(day_timeline(db, "2026-10-17", source="earthquakes", now=LATER))["earthquakes"]+ assert [r["reason"] for r in row["reasons"]] == [f"failure {m}" for m in (6, 5, 4, 3, 2)]+ assert row["more_reasons"] == 2+++def test_source_filter_keeps_the_collector_block_whole(store, db) -> None:+ _busy_day(store)+ result = day_timeline(db, "2026-10-17", source="market_quotes", roster=ROSTER, now=LATER)+ assert [r["source"] for r in result["sources"]] == ["market_quotes"]+ assert result["source_filter"] == "market_quotes"+ assert result["collector"]["captures"] == 10 # every source, not just the filtered one+ unknown = day_timeline(db, "2026-10-17", source="nope", roster=ROSTER, now=LATER)+ assert unknown["error"].startswith("unknown source 'nope'")+ assert "weird_source" in unknown["known_sources"] and "cyclones" in unknown["known_sources"]+++def test_day_without_any_collector_cycle(store, db) -> None:+ cycle(store, "2026-10-15T12:00:00Z",+ out("space_weather", "2026-10-15T12:00:00Z", kp(("2026-10-15T09:00:00Z", 2.0))),+ out("earthquakes", "2026-10-15T12:00:00Z", error="timeout (45.0s)"))+ cycle(store, "2026-10-17T12:00:00Z",+ out("space_weather", "2026-10-17T12:00:00Z", kp(("2026-10-17T09:00:00Z", 1.0))))+ roster = ["space_weather", "earthquakes", "cyclones"]+ quiet = day_timeline(db, "2026-10-16", roster=roster, now=LATER)+ c = quiet["collector"]+ assert (c["state"], c["context"], c["captures"]) == ("did_not_run", "between_captures", 0)+ assert c["explanation"] == (+ "The collector recorded no capture of any source that day: captures exist before "+ "and after this day."+ )+ rows = by_source(quiet)+ assert rows["space_weather"]["day_state"] == "collector_did_not_run"+ assert (rows["space_weather"]["last_capture_before"], rows["space_weather"]["next_capture_after"]) == (+ "2026-10-15T12:00:00Z", "2026-10-17T12:00:00Z"+ )+ assert (rows["earthquakes"]["day_state"], rows["earthquakes"]["next_capture_after"]) == (+ "collector_did_not_run", None+ )+ assert rows["cyclones"]["day_state"] == "never_run"+ assert quiet["state_counts"] == {"collector_did_not_run": 2, "never_run": 1}+ assert quiet["observations"] == [] and quiet["data_gaps"] == []++ early = day_timeline(db, "2026-10-14", roster=roster, now=LATER)["collector"]+ assert (early["context"], early["run_log_first_capture_at"]) == (+ "before_first_capture", "2026-10-15T12:00:00Z"+ )+ late = day_timeline(db, "2026-10-19", roster=roster, now=LATER)["collector"]+ assert (late["context"], late["run_log_last_capture_at"]) == (+ "after_last_capture", "2026-10-17T12:00:00Z"+ )+++def test_empty_store_missing_tables_and_missing_file(tmp_path) -> None:+ empty = tmp_path / "empty.db"+ HistoryStore(empty).close()+ result = day_timeline(empty, "2026-10-17", roster=["space_weather"], now=LATER)+ assert result["collector"]["context"] == "empty_run_log"+ assert by_source(result)["space_weather"]["day_state"] == "never_run"+ assert result["data_gaps"] == []++ bare = tmp_path / "bare.db"+ sqlite3.connect(bare).close()+ for by in ("collected", "observed"):+ result = day_timeline(bare, "2026-10-17", by=by, roster=["space_weather"], now=LATER)+ assert result["data_gaps"][0].startswith(f"No history tables in {bare}")+ assert by_source(day_timeline(bare, "2026-10-17", roster=["space_weather"], now=LATER))[+ "space_weather"]["day_state"] == "never_run"++ missing = tmp_path / "nowhere" / "missing.db"+ result = day_timeline(missing, "2026-10-17", roster=["space_weather"], now=LATER)+ assert result["data_gaps"][0].startswith("No history tables")+ assert not missing.exists() and not missing.parent.exists()+++# ---------------------------------------------------------------------------+# by=observed+# ---------------------------------------------------------------------------+++def test_observed_view_lists_day_values_and_separates_periods(store, db, feeds) -> None:+ points = [+ ("daily", 1.0, "2026-10-17"),+ ("hourly", 2.0, "2026-10-17T06:00:00Z"),+ ("late", 8.0, "2026-10-17T23:59:59Z"),+ ("monthly", 3.0, "2026-10"),+ ("annual", 4.0, "2026"),+ ("yesterday", 5.0, "2026-10-16"),+ ("next_month", 6.0, "2026-11"),+ ("undated", 7.0, None),+ ]+ cycle(store, "2026-10-17T08:00:00Z", out("feed_a", "2026-10-17T08:00:00Z", feeds(*points)))+ revised = [p if p[0] != "hourly" else ("hourly", 2.5, p[2]) for p in points]+ cycle(store, "2026-10-17T09:00:00Z", out("feed_a", "2026-10-17T09:00:00Z", feeds(*revised)))+ # The undated value changes the next day: collected then, not on the 17th.+ next_day = [p if p[0] != "undated" else ("undated", 7.5, None) for p in revised]+ cycle(store, "2026-10-18T09:00:00Z", out("feed_a", "2026-10-18T09:00:00Z", feeds(*next_day)))++ result = day_timeline(db, "2026-10-17", by="observed", now=LATER)+ assert [(p["series_key"], p["observed_at"], p["precision"], p["value"]) for p in result["day_values"]] == [+ ("feed_a:daily", "2026-10-17", "date", 1.0),+ ("feed_a:hourly", "2026-10-17T06:00:00Z", "instant", 2.5),+ ("feed_a:late", "2026-10-17T23:59:59Z", "instant", 8.0),+ ]+ hourly = result["day_values"][1]+ assert (hourly["stored_values"], hourly["first_value"], hourly["first_collected_at"]) == (+ 2, 2.0, "2026-10-17T08:00:00Z"+ )+ assert hourly["collected_at"] == "2026-10-17T09:00:00Z"+ assert result["day_values"][0]["stored_values"] == 1 and "first_value" not in result["day_values"][0]+ assert [(p["series_key"], p["observed_at"], p["precision"]) for p in result["period_values"]] == [+ ("feed_a:annual", "2026", "year"), ("feed_a:monthly", "2026-10", "month"),+ ]+ for item in result["day_values"] + result["period_values"]:+ assert {"observed_at", "published_at", "collected_at"} <= set(item)+ assert by_source(result)["feed_a"] == {+ "source": "feed_a", "in_collector_roster": False, "day_values": 3, "day_values_revised": 1,+ "period_values": 2, "unrecognized_observed_at": 0,+ "without_observed_at_collected_that_day": 1,+ }+ assert result["without_observed_at"]["collected_that_day"] == 1+ assert result["without_observed_at"]["by_source"] == {"feed_a": 1}+ assert "no observation date" in result["without_observed_at"]["reason"]+ assert result["data_gaps"][0].startswith(+ "1 observation(s) collected this day have no observed_at (feed_a 1) and are excluded"+ )+ assert "2026-10-17" in result["period_values_note"] and "not 2026-10-17" in result["period_values_note"]+++def test_month_boundary_never_reads_a_month_value_as_a_day_value(store, db, feeds) -> None:+ points = [("oct31", 1.0, "2026-10-31"), ("oct", 2.0, "2026-10"), ("nov", 3.0, "2026-11"),+ ("nov1", 4.0, "2026-11-01"), ("year", 5.0, "2026")]+ cycle(store, "2026-11-01T08:00:00Z", out("feed_a", "2026-11-01T08:00:00Z", feeds(*points)))+ now = at("2026-11-02T00:00:00Z")+ oct31 = day_timeline(db, "2026-10-31", by="observed", now=now)+ assert [p["series_key"] for p in oct31["day_values"]] == ["feed_a:oct31"]+ assert [p["series_key"] for p in oct31["period_values"]] == ["feed_a:year", "feed_a:oct"]+ nov1 = day_timeline(db, "2026-11-01", by="observed", now=now)+ assert [p["series_key"] for p in nov1["day_values"]] == ["feed_a:nov1"]+ assert [p["series_key"] for p in nov1["period_values"]] == ["feed_a:year", "feed_a:nov"]+++def test_unrecognized_observed_at_forms_are_counted_not_shown(store, db, feeds) -> None:+ cycle(store, "2026-10-17T08:00:00Z",+ out("feed_a", "2026-10-17T08:00:00Z", feeds(("ok", 1.0, "2026-10-17T06:00:00Z"))))+ with store._conn: # a writer that bypasses record_cycle's validation+ for odd in ("2026-10-17T06:00:00.500Z", "2026-10-17 06:00:00"):+ store._conn.execute(+ "INSERT INTO history_observations (capture_id, source, series_key, observed_at, "+ "collected_at, value) VALUES (1, 'feed_a', 'feed_a:odd', ?, ?, 1.0)",+ (odd, at("2026-10-17T08:00:00Z")),+ )+ result = day_timeline(db, "2026-10-17", by="observed", now=LATER)+ assert [p["series_key"] for p in result["day_values"]] == ["feed_a:ok"]+ assert by_source(result)["feed_a"]["unrecognized_observed_at"] == 2+ assert any(g.startswith("2 stored observed_at value(s) on this day are in neither recognized form")+ for g in result["data_gaps"])+++def test_observed_view_source_filter(store, db, feeds) -> None:+ cycle(store, "2026-10-17T08:00:00Z",+ out("feed_a", "2026-10-17T08:00:00Z", feeds(("x", 1.0, "2026-10-17"))),+ out("feed_b", "2026-10-17T08:00:00Z", feeds(("y", 2.0, "2026-10-17"))))+ result = day_timeline(db, "2026-10-17", by="observed", source="feed_b", now=LATER)+ assert [p["series_key"] for p in result["day_values"]] == ["feed_b:y"]+ assert [r["source"] for r in result["sources"]] == ["feed_b"]+++# ---------------------------------------------------------------------------+# Retention: pruned records read as pruned, never as a quiet day+# ---------------------------------------------------------------------------+++def test_day_past_payload_retention_names_the_pruned_bodies(store, db) -> None:+ cycle(store, "2026-10-01T12:00:00Z",+ out("space_weather", "2026-10-01T12:00:00Z", kp(("2026-10-01T09:00:00Z", 2.0))),+ out("election_calendar", "2026-10-01T12:00:00Z", {"elections": [1]}))+ # Eight days on, space weather changed and the calendar did not. The+ # cycle's pruning drops bodies last seen before 2026-10-02T12:00Z; the+ # calendar's body was seen again just now, so it stays.+ summary = cycle(store, "2026-10-09T12:00:00Z",+ out("space_weather", "2026-10-09T12:00:00Z", kp(("2026-10-09T09:00:00Z", 3.0))),+ out("election_calendar", "2026-10-09T12:00:00Z", {"elections": [1]}))+ assert summary["pruned"]["payloads"] == 1+ result = day_timeline(db, "2026-10-01", roster=["space_weather", "election_calendar"],+ now=at("2026-10-09T12:00:00Z"))+ assert result["retention"]["payload_bodies"] == {+ "days": 7.0, "cutoff": "2026-10-02T12:00:00Z", "day": "past_window"+ }+ assert result["retention"]["run_log"]["day"] == "within_window"+ rows = by_source(result)+ assert rows["space_weather"]["day_state"] == "changed" # the run log itself is kept+ assert (rows["space_weather"]["captures_with_body_retained"],+ rows["space_weather"]["captures_with_body_pruned"]) == (0, 1)+ assert (rows["election_calendar"]["captures_with_body_retained"],+ rows["election_calendar"]["captures_with_body_pruned"]) == (1, 0)+ assert result["data_gaps"] == [+ "Payload bodies of 1 of this day's captures were pruned (bodies are kept 7 days after "+ "the payload was last seen); intel_capture_history can replay only captures whose body "+ "is retained (1 of 2)."+ ]+++def test_day_past_run_log_retention_reads_unknown_not_quiet(store, db, monkeypatch) -> None:+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")+ monkeypatch.setenv("WORLD_INTEL_HISTORY_DAYS", "10")+ cycle(store, "2026-10-10T12:00:00Z",+ out("space_weather", "2026-10-10T12:00:00Z", kp(("2026-10-10T09:00:00Z", 2.0))))+ summary = cycle(store, "2026-10-13T12:00:00Z",+ out("space_weather", "2026-10-13T12:00:00Z", kp(("2026-10-13T09:00:00Z", 1.0))))+ assert summary["pruned"]["captures"] == 1++ result = day_timeline(db, "2026-10-10", roster=["space_weather", "cyclones"],+ now=at("2026-10-13T12:00:00Z"))+ assert result["retention"]["run_log"] == {+ "days": 2.0, "cutoff": "2026-10-11T12:00:00Z", "day": "past_window"+ }+ assert result["collector"]["state"] == "unknown_past_retention"+ assert {r["day_state"] for r in result["sources"]} == {"unknown_past_retention"}+ assert result["data_gaps"][0] == (+ "The run log keeps captures 2 days (cutoff 2026-10-11T12:00:00Z); this day is past it, "+ "so its captures are gone. Whether the collector or any source ran that day cannot be "+ "read here: absence is not evidence that nothing happened."+ )+ # The observation collected that day outlived its capture.+ (item,) = result["observations"]+ assert (item["observed_at"], item["capture_retained"]) == ("2026-10-10T09:00:00Z", False)+ assert by_source(result)["space_weather"]["observations_retained"] == 1++ observed = day_timeline(db, "2026-10-10", by="observed", now=at("2026-10-13T12:00:00Z"))+ assert [p["capture_retained"] for p in observed["day_values"]] == [False]+ assert any(g.startswith("1 listed value(s) outlived the capture") for g in observed["data_gaps"])+++def test_captures_past_the_window_but_not_yet_pruned_are_flagged(store, db, monkeypatch) -> None:+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")+ cycle(store, "2026-10-10T12:00:00Z",+ out("space_weather", "2026-10-10T12:00:00Z", kp(("2026-10-10T09:00:00Z", 2.0))))+ # No cycle since, so nothing pruned them yet.+ result = day_timeline(db, "2026-10-10", roster=["space_weather"], now=at("2026-10-13T12:00:00Z"))+ assert (result["collector"]["state"], by_source(result)["space_weather"]["attempts"]) == ("ran", 1)+ assert result["data_gaps"][0].startswith(+ "This day is past the 2-day run-log retention (cutoff 2026-10-11T12:00:00Z); its 1 "+ "captures are still here only because pruning runs at the end of a collector cycle"+ )+++def test_day_straddling_the_run_log_cutoff(store, db, monkeypatch) -> None:+ monkeypatch.setenv("WORLD_INTEL_HISTORY_CAPTURE_DAYS", "2")+ cycle(store, "2026-10-11T20:00:00Z",+ out("space_weather", "2026-10-11T20:00:00Z", kp(("2026-10-11T18:00:00Z", 2.0))))+ result = day_timeline(db, "2026-10-11", roster=["space_weather", "cyclones"],+ now=at("2026-10-13T12:00:00Z"))+ assert result["retention"]["run_log"]["day"] == "partly_past_window"+ rows = by_source(result)+ assert rows["space_weather"]["day_state"] == "changed"+ assert rows["cyclones"]["day_state"] == "unknown_past_retention"+ # Before the cutoff the day is unknown, so the gap starts at the cutoff.+ c = result["collector"]+ assert (c["longest_gap_from"], c["longest_gap_to"], c["longest_gap_s"]) == (+ "2026-10-11T12:00:00Z", "2026-10-11T20:00:00Z", 28_800.0+ )+ assert result["data_gaps"][0].startswith(+ "Captures before 2026-10-11T12:00:00Z (the 2-day run-log cutoff) are pruned"+ )+++def test_observation_retention_is_stated_for_old_days(store, db, monkeypatch) -> None:+ monkeypatch.setenv("WORLD_INTEL_HISTORY_DAYS", "10")+ monkeypatch.setenv("WORLD_INTEL_HISTORY_PAYLOAD_DAYS", "0")+ now = at("2026-10-13T12:00:00Z")+ result = day_timeline(db, "2026-10-02", by="observed", now=now)+ assert result["retention"]["observations"]["day"] == "past_window"+ assert result["retention"]["payload_bodies"] == {"days": 0.0, "cutoff": None, "day": "kept_forever"}+ assert any(g.startswith("Observations are pruned 10 days after collection (cutoff "+ "2026-10-03T12:00:00Z)") for g in result["data_gaps"])+ collected = day_timeline(db, "2026-10-02", now=now)+ assert any(g.startswith("Observations collected before 2026-10-03T12:00:00Z are past the "+ "10-day retention") for g in collected["data_gaps"])+++# ---------------------------------------------------------------------------+# Caps+# ---------------------------------------------------------------------------+++def test_caps_bound_both_views_and_disclose_truncation(store, db, feeds) -> None:+ many = [(f"a{i:02d}", float(i), f"2026-10-17T00:{i:02d}:00Z") for i in range(30)]+ few = [(f"b{i}", float(i), f"2026-10-17T12:0{i}:00Z") for i in range(5)]+ cycle(store, "2026-10-17T13:00:00Z",+ out("feed_a", "2026-10-17T13:00:00Z", feeds(*many)),+ out("feed_b", "2026-10-17T13:00:00Z", feeds(*few)))++ observed = day_timeline(db, "2026-10-17", by="observed", limit=12, per_source_limit=10, now=LATER)+ assert [p["series_key"] for p in observed["day_values"]] == (+ [f"feed_a:a{i:02d}" for i in range(10)] + ["feed_b:b0", "feed_b:b1"]+ )+ assert observed["truncation"]["day_values"] == {+ "matched": 35, "returned": 12, "truncated": True, "limit": 12, "per_source_limit": 10,+ "sources_truncated": {"feed_a": {"matched": 30, "returned": 10},+ "feed_b": {"matched": 5, "returned": 2}},+ }+ assert {r["source"]: r["day_values"] for r in observed["sources"]} == {"feed_a": 30, "feed_b": 5}+ assert any(g.startswith("Day values: 12 of 35 returned (by observed_at, then series; at most "+ "10 per source and 12 in all)") for g in observed["data_gaps"])+ assert observed["truncation"]["period_values"]["truncated"] is False++ collected = day_timeline(db, "2026-10-17", limit=12, per_source_limit=10, now=LATER)+ assert [o["series_key"] for o in collected["observations"]] == (+ [f"feed_a:a{i:02d}" for i in range(10)] + ["feed_b:b0", "feed_b:b1"]+ )+ assert (collected["truncation"]["matched"], collected["truncation"]["returned"]) == (35, 12)+ assert any(g.startswith("Observations saved that day: 12 of 35 returned (earliest first")+ for g in collected["data_gaps"])++ defaults = day_timeline(db, "2026-10-17", now=LATER)["truncation"]+ assert (defaults["limit"], defaults["per_source_limit"], defaults["returned"]) == (100, 10, 15)+ full = day_timeline(db, "2026-10-17", per_source_limit=50, now=LATER)+ assert full["truncation"]["truncated"] is False and len(full["observations"]) == 35+++ "limit,per_source,expected",+ [(0, -3, (1, 1)), (10**9, 10**9, (5000, 1000)), ("x", None, (100, 10)), (7, "7", (7, 7))],+)+def test_limits_are_clamped(store, db, limit, per_source, expected) -> None:+ trunc = day_timeline(db, "2026-10-17", limit=limit, per_source_limit=per_source, now=LATER)["truncation"]+ assert (trunc["limit"], trunc["per_source_limit"]) == expected+++# ---------------------------------------------------------------------------+# Read-only, and the indexes the queries use+# ---------------------------------------------------------------------------+++def test_reads_leave_the_store_untouched(store, db) -> None:+ _busy_day(store)+ store.close() # checkpoint: the main file now holds everything+ before = hashlib.sha256(db.read_bytes()).hexdigest()+ for by in ("collected", "observed"):+ assert "error" not in day_timeline(db, "2026-10-17", by=by, roster=ROSTER, now=LATER)+ assert hashlib.sha256(db.read_bytes()).hexdigest() == before+ wal = db.with_name(db.name + "-wal")+ assert not wal.exists() or wal.stat().st_size == 0+ conn = history_timeline._connect(db)+ try:+ with pytest.raises(sqlite3.OperationalError, match="readonly"):+ conn.execute("DELETE FROM history_captures")+ finally:+ conn.close()+++class _RecordingConnection:+ def __init__(self, conn, log):+ self._conn, self._log = conn, log++ def execute(self, sql, params=()):+ self._log.append((sql, params))+ return self._conn.execute(sql, params)++ def close(self):+ self._conn.close()+++def test_queries_seek_the_history_indexes_and_never_scan_a_history_table(store, db, monkeypatch, feeds) -> None:+ """EXPLAIN QUERY PLAN of every statement the timeline runs: no full+ scan of a history table (named, or by the aliases c, o and p used in+ the SQL), and the three indexes the design rests on are used."""+ _busy_day(store)+ cycle(store, "2026-10-17T13:00:00Z", out("feed_a", "2026-10-17T13:00:00Z", feeds(("x", 1.0, "2026-10"))))+ log: list = []+ real = history_timeline._connect+ monkeypatch.setattr(history_timeline, "_connect", lambda path: _RecordingConnection(real(path), log))+ for by in ("collected", "observed"):+ for source in (None, "space_weather"):+ assert "error" not in day_timeline(db, "2026-10-17", by=by, source=source, roster=ROSTER, now=LATER)+ assert len(log) > 20+ forbidden = {"history_captures", "history_observations", "history_payloads", "c", "o", "p"}+ scans, indexes = [], set()+ with contextlib.closing(sqlite3.connect(db)) as conn:+ for sql, params in log:+ for row in conn.execute("EXPLAIN QUERY PLAN " + sql, params):+ detail = row[-1]+ indexes.update(re.findall(r"INDEX (\w+)", detail))+ match = re.match(r"SCAN (?:TABLE )?(\w+)", detail)+ if match and match.group(1) in forbidden:+ scans.append((sql.split("\n")[1] if sql.startswith("\n") else sql[:60], detail))+ assert scans == []+ assert {"idx_history_captures_time", "idx_history_obs_time", "idx_history_obs_series"} <= indexes+++# ---------------------------------------------------------------------------+# MCP tool through the real dispatcher+# ---------------------------------------------------------------------------++[email protected](scope="module")+def server():+ """server.py imported under a temp cache (test_server_registry's pattern).++ The shared runtime is not rebound here: the tool test replaces+ ``runtime.cache`` with its own store, and rebinding would drop an+ earlier module's open connections unclosed."""+ import importlib++ 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:+ module = importlib.import_module("world_intel_mcp.server")+ yield module+ finally:+ if prior is None:+ os.environ.pop("WORLD_INTEL_CACHE_DB", None)+ else:+ os.environ["WORLD_INTEL_CACHE_DB"] = prior+++def _recent_day(days_ago: int = 2) -> str:+ return (datetime.now(timezone.utc) - timedelta(days=days_ago)).date().isoformat()+++async def test_tool_through_the_real_dispatcher_never_fetches(server, tmp_path, monkeypatch) -> None:+ from world_intel_mcp import runtime++ db = tmp_path / "dispatch.db"+ monkeypatch.setattr(runtime, "cache", types.SimpleNamespace(db_path=db))+ day = _recent_day()+ s = HistoryStore(db)+ s.record_cycle([+ SourceOutcome("space_weather", at(f"{day}T01:00:00Z"), 1.0, kp((f"{day}T00:00:00Z", 2.0))),+ SourceOutcome("energy_prices", at(f"{day}T01:00:00Z"), 1.0, {"error": "EIA_API_KEY not configured"}),+ ], now=at(f"{day}T01:00:00Z"))+ s.close()++ def _no_network(*args, **kwargs):+ raise AssertionError("the day timeline must never fetch")++ monkeypatch.setattr(httpx.AsyncClient, "send", _no_network)+ monkeypatch.setattr(httpx.Client, "send", _no_network)++ result = await server._dispatch("intel_day_timeline", {"day": day})+ rows = by_source(result)+ assert set(rows) == {name for name, _, _, _ in collector.SOURCES}+ assert rows["space_weather"]["day_state"] == "changed"+ assert rows["energy_prices"]["day_state"] == "failed"+ assert rows["energy_prices"]["reasons"][0]["reason"] == "EIA_API_KEY not configured"+ assert rows["cyclones"]["day_state"] == "never_run"+ assert result["db_path"] == str(db)++ observed = await server._dispatch(+ "intel_day_timeline", {"day": day, "by": "observed", "source": "space_weather"}+ )+ assert [p["observed_at"] for p in observed["day_values"]] == [f"{day}T00:00:00Z"]++ capped = await server._dispatch("intel_day_timeline", {"day": day, "limit": 3, "per_source_limit": 2})+ assert (capped["truncation"]["limit"], capped["truncation"]["per_source_limit"]) == (3, 2)+ bad = await server._dispatch("intel_day_timeline", {"day": "17-10-2026"})+ assert bad["accepted_format"] == "YYYY-MM-DD"+ assert (await server._dispatch("intel_day_timeline", {}))["error"].startswith("day is required")+++def test_tool_registration(server) -> None:+ (tool,) = [t for t in server.TOOLS if t.name == "intel_day_timeline"]+ assert tool.inputSchema["required"] == ["day"]+ assert tool.inputSchema["properties"]["by"]["enum"] == ["collected", "observed"]+ assert re.fullmatch(tool.inputSchema["properties"]["day"]["pattern"], "2026-10-17")+ assert "accrues only while the collector" in tool.description+ assert chr(0x2014) not in tool.description # no em dash in user-facing text+++# ---------------------------------------------------------------------------+# CLI+# ---------------------------------------------------------------------------+++def cli_day(tmp_path, monkeypatch):+ db = tmp_path / "cli-day.db"+ monkeypatch.setenv("WORLD_INTEL_CACHE_DB", str(db))+ monkeypatch.setenv("COLUMNS", "220")+ monkeypatch.setattr(cli, "_fetcher", None)+ day = _recent_day()+ s = HistoryStore(db)+ first, second = at(f"{day}T01:00:00Z"), at(f"{day}T01:05:00Z")+ quote = {"quotes": [{"symbol": "^GSPC", "price": 6000.0}]}+ rates = {"rates": [{"bank": "Federal Reserve", "label": "Federal Funds Rate", "rate": 4.33,+ "as_of": day[:7], "source": "fred"}]}+ s.record_cycle([+ SourceOutcome("space_weather", first, 1.0, kp((f"{day}T00:00:00Z", 2.0))),+ SourceOutcome("energy_prices", first, 1.0, {"error": "EIA_API_KEY [red]not[/red] configured"}),+ SourceOutcome("market_quotes", first, 1.0, quote),+ SourceOutcome("central_bank_rates", first, 1.0, rates),+ ], now=first)+ s.record_cycle([+ SourceOutcome("space_weather", second, 1.0, kp((f"{day}T00:00:00Z", 2.0))),+ SourceOutcome("market_quotes", second, 1.0, quote),+ ], now=second)+ s.close()+ yield day+ if cli._fetcher is not None: # the shared Cache the command opened+ cli._fetcher.cache.close()+++def _invoke(*args):+ return CliRunner().invoke(cli.main, list(args), catch_exceptions=False)+++def test_cli_history_day_collected(cli_day) -> None:+ assert "day" in cli.history_group.commands+ result = _invoke("history", "day", cli_day)+ assert result.exit_code == 0+ text = result.output+ assert f"{cli_day} (UTC) by collected date: {cli_day}T00:00:00Z to" in text+ assert "Collector: ran, 6 captures of 4 source(s)" in text+ rows = {line.split()[0]: line for line in text.splitlines() if line.strip()}+ assert "changed" in rows["space_weather"] and "0 +1 first" in rows["space_weather"]+ assert "failed" in rows["energy_prices"]+ assert "EIA_API_KEY [red]not[/red] configured (x1)" in rows["energy_prices"] # literal+ assert "never_run" in rows["cyclones"]+ assert "Observations saved that day (3 of 3)" in text+ assert "Cannot prove:" in text++ data = json.loads(_invoke("--json-output", "history", "day", cli_day, "--source", "market_quotes").output)+ assert [r["source"] for r in data["sources"]] == ["market_quotes"]+ assert data["sources"][0]["payload_changes"] == {"changed": 0, "unchanged": 1, "first": 1, "not_stored": 0}+++def test_cli_history_day_observed(cli_day) -> None:+ text = _invoke("history", "day", cli_day, "--by", "observed").output+ assert f"Values observed on {cli_day} (1 of 1)" in text+ assert f"{cli_day}T00:00:00Z" in text and "instant" in text+ assert "Period values containing the day, not values for it (1 of 1)" in text+ assert "central_bank_rates:federal_funds_rate" in text and "month" in text+ assert "Gap: 1 observation(s) collected this day have no observed_at (market_quotes 1)" in text+++def test_cli_history_day_errors(cli_day) -> None:+ bad = CliRunner().invoke(cli.main, ["history", "day", "2026/10/17"])+ assert bad.exit_code == 2 and "YYYY-MM-DD" in bad.output+ tomorrow = _recent_day(-1)+ future = CliRunner().invoke(cli.main, ["history", "day", tomorrow])+ assert future.exit_code == 2 and "in the future" in future.output+ wrong_view = CliRunner().invoke(cli.main, ["history", "day", cli_day, "--by", "hourly"])+ assert wrong_view.exit_code == 2+ unknown = _invoke("history", "day", cli_day, "--source", "nope").output+ assert unknown.startswith("Error:") and "unknown source" in unknowndiff --git a/src/world_intel_mcp/tools/__init__.py b/src/world_intel_mcp/tools/__init__.pyindex fc0bb4d..7c18d63 100644--- a/src/world_intel_mcp/tools/__init__.py+++ b/src/world_intel_mcp/tools/__init__.py@@ -25,6 +25,7 @@ Handler = Callable[[dict[str, Any]], Awaitable[Any]]from . import ( # noqa: E402aoi,conflict,+ day_timeline,finance,geospatial,hazards,@@ -59,6 +60,7 @@ _MODULES = [vector,aoi,history,+ day_timeline,system,]diff --git a/src/world_intel_mcp/tools/day_timeline.py b/src/world_intel_mcp/tools/day_timeline.pynew file mode 100644index 0000000..a087ae4--- /dev/null+++ b/src/world_intel_mcp/tools/day_timeline.py@@ -0,0 +1,98 @@+"""Day timeline tool: what the history store recorded for one UTC day.++Reads the history store that the collector writes into the cache DB, on+the ``db_path`` the runtime cache resolved, through a read-only+connection (``world_intel_mcp.history_timeline``); nothing here fetches+upstream data or writes history.+"""++import time+from typing import Any++from mcp.types import Tool++from .. import runtime+from ..history_timeline import (+ DEFAULT_LIMIT,+ DEFAULT_PER_SOURCE_LIMIT,+ MAX_LIMIT,+ MAX_PER_SOURCE_LIMIT,+ day_timeline,+)++TOOLS: list[Tool] = [+ Tool(+ name="intel_day_timeline",+ description=(+ "What the history store recorded for one UTC calendar day (YYYY-MM-DD; today "+ "allowed, a future day refused). by=collected (default): per source, that day's "+ "collector captures from the run log (attempts; ok / degraded / error counts with "+ "reasons; changed vs unchanged payloads; first and last capture; observations "+ "stored), sources with no capture that day and why, whether the collector ran at "+ "all, and the observations saved that day. by=observed: values whose observed_at "+ "falls on the day (dates and UTC instants); month and year values containing the "+ "day are listed apart as period values; values without observed_at are excluded "+ "and counted. Items carry observed_at, published_at and collected_at where known. "+ "Says which records are past retention (payload bodies 7 days, run log 30, "+ "observations 365 by default) instead of reading them as a quiet day. Output is "+ "capped and truncation is stated. Read-only: never fetches. History accrues only "+ "while the collector (intel-collector, or intel_collect) runs."+ ),+ inputSchema={+ "type": "object",+ "properties": {+ "day": {+ "type": "string",+ "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}$",+ "description": "UTC calendar date, YYYY-MM-DD (e.g. '2026-10-17')",+ },+ "by": {+ "type": "string",+ "enum": ["collected", "observed"],+ "default": "collected",+ "description": "collected: what was captured that day; observed: values "+ "whose observed_at is that day",+ },+ "source": {+ "type": "string",+ "description": "One collector source name (e.g. 'space_weather'); omit for all",+ },+ "limit": {+ "type": "integer",+ "description": f"Most items listed in all (default {DEFAULT_LIMIT}, "+ f"max {MAX_LIMIT})",+ "default": DEFAULT_LIMIT,+ },+ "per_source_limit": {+ "type": "integer",+ "description": f"Most items listed per source (default "+ f"{DEFAULT_PER_SOURCE_LIMIT}, max {MAX_PER_SOURCE_LIMIT})",+ "default": DEFAULT_PER_SOURCE_LIMIT,+ },+ },+ "required": ["day"],+ },+ ),+]+++async def _day_timeline(arguments: dict[str, Any]) -> Any:+ from ..collector import SOURCES++ if "day" not in arguments:+ return {"error": "day is required (YYYY-MM-DD, a UTC calendar date)"}+ return day_timeline(+ runtime.cache.db_path,+ arguments.get("day"),+ by=arguments.get("by", "collected"),+ source=arguments.get("source"),+ roster=[name for name, _, _, _ in SOURCES],+ limit=arguments.get("limit", DEFAULT_LIMIT),+ per_source_limit=arguments.get("per_source_limit", DEFAULT_PER_SOURCE_LIMIT),+ now=time.time(),+ )+++HANDLERS = {+ "intel_day_timeline": _day_timeline,+}