Skip to content

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.

History: ASCII-only dates; stable stale reason, copy age as a field

Phoenix Agent (mac-studio)acda3387b7f9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b772e54..ec41249 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,8 +10,12 @@
records. An empty payload is degraded, because a quiet period and a
silent upstream failure look the same.
- A run that any upstream fetch answered from an expired cached copy is a
- stale-cache replay: degraded, with the reason `served stale cache` and
- the copy's age. The collector reads this from a per-task log the fetcher
+ stale-cache replay: degraded, with the reason `served stale cache`. The
+ reason is the same text on every replay, so replays group; the copy's
+ age and the number of stale fetches are the capture fields
+ `stale_age_s` and `stale_fetches` (a run log created before them gains
+ the columns in place when opened, and the CLI shows them beside the
+ reason). The collector reads this from a per-task log the fetcher
keeps (`fetcher.recording_stale_serves()`, opened once per source task),
because most source modules rebuild their payload and drop the fetcher's
`_stale` marker. A replay's observations are counted but not stored: a
@@ -46,8 +50,8 @@
`expected=N` declares how many points a complete payload yields. The
Yahoo quote sources declare one per default symbol, so a run where some
symbols did not answer is degraded as `partial: X of N expected series`.
- Observation dates must name a real calendar period (`2026-02-30` and
- `0000` are rejected).
+ Observation dates must name a real calendar period in ASCII digits
+ (`2026-02-30`, `0000` and fullwidth digits are rejected).
- MCP tools `intel_collection_health`, `intel_capture_history`,
`intel_series_history` and `intel_revisions`, and the CLI group
`intel history health|captures|series|revisions`. History accrues only
diff --git a/src/world_intel_mcp/cli.py b/src/world_intel_mcp/cli.py
index 6de2132..9c26b01 100644
--- a/src/world_intel_mcp/cli.py
+++ b/src/world_intel_mcp/cli.py
@@ -2643,6 +2643,26 @@ def _with_history_store(fn: Any) -> dict:
store.close()
+def _reason_text(reason: str | None, stale_age: Any = None, stale_fetches: Any = None) -> str:
+ """A run-log reason for display, with a stale-cache replay's copy age
+ and fetch count beside it (stored apart, so the reason itself is the
+ same text on every replay)."""
+ from .history import STALE_REASON
+
+ text = reason or ""
+ if not text.startswith(STALE_REASON):
+ return text
+ if stale_fetches and stale_fetches > 1:
+ detail = f"{stale_fetches} fetches" + (
+ f", oldest {stale_age} s" if stale_age is not None else ""
+ )
+ elif stale_age is not None:
+ detail = f"age {stale_age} s"
+ else:
+ return text
+ return f"{STALE_REASON} ({detail}){text[len(STALE_REASON):]}"
+
+
@main.group(name="history")
def history_group() -> None:
"""Saved collector history: health, captures, series, revisions.
@@ -2691,7 +2711,8 @@ def history_health(ctx: click.Context, source: str | None) -> None:
_cell(row.get("last_ok_at") or "-"),
str(row.get("consecutive_failures", "-")),
_cell(row.get("latest_observed_at") or "-"),
- _cell(row.get("last_reason") or ""),
+ _cell(_reason_text(row.get("last_reason"), row.get("last_stale_age_s"),
+ row.get("last_stale_fetches"))),
)
console.print(table)
counts = ", ".join(f"{k} {v}" for k, v in sorted(data["state_counts"].items()))
@@ -2731,7 +2752,9 @@ def history_captures(
f"{cap['collected_at']}: {cap['status']} ({cap['change'] or 'no payload'})"
)
if cap.get("reason"):
- console.print(f"[yellow]Reason:[/yellow] {escape(str(cap['reason']))}")
+ reason = _reason_text(str(cap["reason"]), cap.get("stale_age_s"),
+ cap.get("stale_fetches"))
+ console.print(f"[yellow]Reason:[/yellow] {escape(reason)}")
if cap.get("payload_note"):
console.print(f"[yellow]Gap:[/yellow] {escape(cap['payload_note'])}")
if cap.get("payload") is not None:
@@ -2764,7 +2787,8 @@ def history_captures(
"-" if cap["duration_s"] is None else f"{cap['duration_s']:.2f}",
"-" if cap["record_count"] is None else str(cap["record_count"]),
cap["change"] or "-",
- _cell(cap.get("reason") or ""),
+ _cell(_reason_text(cap.get("reason"), cap.get("stale_age_s"),
+ cap.get("stale_fetches"))),
)
console.print(table)
console.print(f"[dim]{escape(data['note'])}[/dim]")
diff --git a/src/world_intel_mcp/history.py b/src/world_intel_mcp/history.py
index 09fd47f..aa2601b 100644
--- a/src/world_intel_mcp/history.py
+++ b/src/world_intel_mcp/history.py
@@ -14,10 +14,13 @@ settled on, fallback path included):
because a quiet period and a silent upstream failure look the same.
A run that was served an expired cached copy for any upstream fetch is
a stale-cache replay: ``degraded`` with a reason starting ``served
- stale cache`` (with the copy's age). The collector reads that from the
- fetcher's per-task log (``fetcher.recording_stale_serves``), because
- most source modules rebuild their dict and drop the fetcher's
- ``_stale`` marker; a top-level ``_stale`` marker counts too.
+ stale cache``, the same text on every replay so replays group; the
+ copy's age and the number of stale fetches are the capture's
+ ``stale_age_s`` and ``stale_fetches``. The collector reads that from
+ the fetcher's per-task log (``fetcher.recording_stale_serves``),
+ because most source modules rebuild their dict and drop the fetcher's
+ ``_stale`` marker; a top-level ``_stale`` marker counts too. A run log
+ created before those two columns gains them in place when opened.
- ``history_payloads``: the payload body as zlib-compressed JSON, stored
once per ``(source, payload_hash)``. The hash ignores the top-level
fetch-time stamps in ``VOLATILE_KEYS`` (they change on every call while
@@ -60,7 +63,8 @@ Registering an extractor (the public API)::
The store prefixes each ``series_key`` with the source name
(``my_source:rate``), so extractors cannot collide. ``observed_at`` must be
``YYYY``, ``YYYY-MM``, ``YYYY-MM-DD`` or a timezone-aware ISO 8601
-instant (use ``normalize_observed_at`` to convert, with ``assume_utc=True``
+instant, in ASCII digits and naming a real calendar date or period
+(use ``normalize_observed_at`` to convert, with ``assume_utc=True``
only when the publisher documents UTC); a point with an unparseable date
or a non-finite value is skipped and counted in the capture's
``extract_error``. Register at import time of your source module: the
@@ -96,6 +100,11 @@ Gaps / not covered:
the store; only what the collector sees from the first recorded cycle on.
- ``published_at`` is NULL for every built-in extractor: none of their
payloads names a release time.
+- A built-in extractor skips a row whose date it cannot read (not ASCII
+ ISO 8601, or no such calendar date) without counting it; that shows
+ only when every row is skipped, which reads ``degraded``. A point with
+ such a date that an extractor does return is counted in
+ ``extract_error``.
- ``record_count`` is a size hint (the payload's longest top-level list,
else its integer ``count``), not a semantic count; payloads shaped as
nested dicts read NULL.
@@ -260,12 +269,14 @@ def normalize_observed_at(value: Any, *, assume_utc: bool = False) -> str | None
when they name a real calendar period (year 0001 on, month 01-12, a
day that exists). An ISO 8601 instant becomes ``YYYY-MM-DDTHH:MM:SSZ``
in UTC. A naive instant (no offset) is only accepted with
- ``assume_utc=True``.
+ ``assume_utc=True``. Only ASCII text is read: ``\\d`` and ``int()``
+ also accept fullwidth and other Unicode digits, and a period stored in
+ those would match no date query.
"""
if value is None or isinstance(value, bool):
return None
text = str(value).strip()
- if not text:
+ if not text or not text.isascii():
return None
period = _DATE_PERIOD.fullmatch(text)
if period:
@@ -408,6 +419,8 @@ class _Classified:
observations: list[Observation] = field(default_factory=list)
extract_error: str | None = None
extracted: int | None = None
+ stale_age_s: float | None = None
+ stale_fetches: int | None = None
def record_count(payload: Any) -> int | None:
@@ -460,9 +473,13 @@ def _extract(source: str, payload: Any) -> tuple[list[Observation], str | None,
return valid, note, len(raw)
-def _stale_reason(outcome: SourceOutcome) -> str | None:
- """``served stale cache ...`` when any upstream fetch of this run was
- answered from an expired cached copy, else None."""
+def _stale_replay(outcome: SourceOutcome) -> tuple[int | None, float | None] | None:
+ """(upstream fetches answered from expired cache, oldest copy age in
+ seconds) when this run was a stale-cache replay, else None.
+
+ The fetch count is None when only the payload's ``_stale`` marker shows
+ the replay; the age is None when no serve or marker reported one.
+ """
serves = list(outcome.stale_serves or ())
payload = outcome.payload
marked = isinstance(payload, dict) and bool(payload.get("_stale"))
@@ -472,11 +489,7 @@ def _stale_reason(outcome: SourceOutcome) -> str | None:
if marked:
ages.append(_finite(payload.get("_stale_age_seconds")))
known = [age for age in ages if age is not None]
- if len(serves) > 1:
- return f"{STALE_REASON} for {len(serves)} upstream fetches" + (
- f" (oldest {max(known)} s)" if known else ""
- )
- return f"{STALE_REASON} (age {max(known)} s)" if known else STALE_REASON
+ return (len(serves) or None), (max(known) if known else None)
def classify(outcome: SourceOutcome) -> _Classified:
@@ -485,7 +498,9 @@ def classify(outcome: SourceOutcome) -> _Classified:
``error`` when the run produced no usable payload. ``degraded`` when it
was a stale-cache replay, or live but marked degraded, empty, partial,
or without the measures its extractor expects. Otherwise ``ok``. A
- stale-cache replay keeps its extracted count but no observations.
+ stale-cache replay keeps its extracted count but no observations. The
+ reason holds no per-run numbers for a replay (its copy age and fetch
+ count are fields), so successive replays share one reason.
"""
if outcome.error is not None:
return _Classified("error", outcome.error[:500], None)
@@ -498,9 +513,9 @@ def classify(outcome: SourceOutcome) -> _Classified:
count = record_count(payload)
observations, extract_error, extracted = _extract(outcome.source, payload)
notes = []
- stale = _stale_reason(outcome)
- if stale:
- notes.append(stale)
+ stale = _stale_replay(outcome)
+ if stale is not None:
+ notes.append(STALE_REASON)
if isinstance(payload, dict) and (
payload.get("degraded") is True or payload.get("status") == "degraded"
):
@@ -517,12 +532,14 @@ def classify(outcome: SourceOutcome) -> _Classified:
))
elif extracted is not None and expected is not None and len(observations) < expected:
notes.append(f"partial: {len(observations)} of {expected} expected series")
- if stale and observations:
+ if stale is not None and observations:
notes.append("observations not stored: a stale-cache replay is not a new observation")
observations = []
reason = "; ".join(notes)[:500] if notes else None
+ stale_fetches, stale_age_s = stale if stale is not None else (None, None)
return _Classified(
- "degraded" if notes else "ok", reason, count, observations, extract_error, extracted
+ "degraded" if notes else "ok", reason, count, observations, extract_error, extracted,
+ stale_age_s=stale_age_s, stale_fetches=stale_fetches,
)
@@ -727,6 +744,32 @@ def _outline(payload: Any) -> Any:
return _shape(payload)
+# Run-log columns added after the first schema, each with the statement
+# that adds it to an existing table in place.
+_ADDED_CAPTURE_COLUMNS = (
+ ("stale_age_s", "ALTER TABLE history_captures ADD COLUMN stale_age_s REAL"),
+ ("stale_fetches", "ALTER TABLE history_captures ADD COLUMN stale_fetches INTEGER"),
+)
+
+
+def _add_missing_capture_columns(conn: Any) -> None:
+ """Bring a run log created by an earlier schema up to date, in place.
+
+ Safe to run on every open. A second process can add a column between
+ this one's table_info read and its ALTER; that "duplicate column"
+ error means the work is done, any other error is raised.
+ """
+ present = {row[1] for row in conn.execute("PRAGMA table_info(history_captures)")}
+ for name, statement in _ADDED_CAPTURE_COLUMNS:
+ if name in present:
+ continue
+ try:
+ conn.execute(statement)
+ except sqlite3.OperationalError as exc:
+ if "duplicate column" not in str(exc):
+ raise
+
+
class HistoryStore:
"""Capture log, payload bodies and observations in the cache DB."""
@@ -752,7 +795,9 @@ class HistoryStore:
changed INTEGER,
observations_extracted INTEGER,
observations_stored INTEGER,
- extract_error TEXT
+ extract_error TEXT,
+ stale_age_s REAL,
+ stale_fetches INTEGER
);
CREATE INDEX IF NOT EXISTS idx_history_captures_source
ON history_captures(source, collected_at);
@@ -789,6 +834,7 @@ class HistoryStore:
ON history_observations(collected_at);
"""
)
+ _add_missing_capture_columns(self._conn)
self._conn.commit()
def close(self) -> None:
@@ -857,10 +903,12 @@ class HistoryStore:
capture_id = conn.execute(
"INSERT INTO history_captures (source, collected_at, status, duration_s, "
"record_count, error, payload_hash, changed, observations_extracted, "
- "extract_error) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ "extract_error, stale_age_s, stale_fetches) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(outcome.source, outcome.collected_at, c.status,
None if outcome.duration_s is None else round(outcome.duration_s, 3),
- c.record_count, c.reason, digest, changed, c.extracted, c.extract_error),
+ c.record_count, c.reason, digest, changed, c.extracted, c.extract_error,
+ c.stale_age_s, c.stale_fetches),
).lastrowid
stored = self._store_observations(capture_id, outcome, c.observations)
observations_stored += stored
@@ -978,8 +1026,9 @@ class HistoryStore:
cadence = overrides.get(name, default_cadence)
overdue_after = OVERDUE_MULTIPLE * cadence
last = conn.execute(
- "SELECT collected_at, status, error, extract_error FROM history_captures "
- "WHERE source = ? ORDER BY collected_at DESC, id DESC LIMIT 1",
+ "SELECT collected_at, status, error, extract_error, stale_age_s, stale_fetches "
+ "FROM history_captures WHERE source = ? ORDER BY collected_at DESC, id DESC "
+ "LIMIT 1",
(name,),
).fetchone()
entry: dict[str, Any] = {
@@ -996,7 +1045,11 @@ class HistoryStore:
entry["unrecorded_attempts"] = unrecorded
rows.append(entry)
continue
- last_at, last_status, last_reason, last_extract_error = last
+ (last_at, last_status, last_reason, last_extract_error,
+ last_stale_age, last_stale_fetches) = last
+ last_is_stale = last_status != "error" and (last_reason or "").startswith(
+ STALE_REASON
+ )
attempts = conn.execute(
"SELECT COUNT(*) FROM history_captures WHERE source = ?", (name,)
).fetchone()[0]
@@ -1034,7 +1087,7 @@ class HistoryStore:
state = "not_attempted_recently"
elif last_status == "error":
state = "failing"
- elif (last_reason or "").startswith(STALE_REASON):
+ elif last_is_stale:
state = "stale"
else:
state = last_status
@@ -1053,6 +1106,9 @@ class HistoryStore:
overdue=overdue,
attempt_overdue=attempt_overdue,
)
+ if last_is_stale:
+ entry["last_stale_age_s"] = last_stale_age
+ entry["last_stale_fetches"] = last_stale_fetches
unrecorded = _unrecorded_attempts(failures, name, last_at)
if unrecorded:
entry["unrecorded_attempts"] = unrecorded
@@ -1157,6 +1213,12 @@ class HistoryStore:
"last live capture",
"unrecorded_attempts": "cycles after this source's last recorded capture "
"whose history write failed",
+ "last_stale_age_s": "present when the last capture was a stale-cache "
+ "replay: age in seconds of the oldest expired copy it served (null when "
+ "none was reported)",
+ "last_stale_fetches": "present when the last capture was a stale-cache "
+ "replay: how many upstream fetches the fetcher answered from expired "
+ "cache (null when only the payload's _stale marker showed the replay)",
},
}
@@ -1168,7 +1230,7 @@ class HistoryStore:
columns = (
"c.id, c.collected_at, c.status, c.duration_s, c.record_count, c.error, "
"c.payload_hash, c.changed, c.observations_extracted, c.observations_stored, "
- "c.extract_error, p.body IS NOT NULL"
+ "c.extract_error, c.stale_age_s, c.stale_fetches, p.body IS NOT NULL"
)
join = (
"FROM history_captures c LEFT JOIN history_payloads p "
@@ -1253,7 +1315,7 @@ class HistoryStore:
@staticmethod
def _capture_row(row: tuple) -> dict:
(cid, collected_at, status, duration, count, error, digest, changed,
- extracted, stored, extract_error, body_retained) = row
+ extracted, stored, extract_error, stale_age_s, stale_fetches, body_retained) = row
return {
"capture_id": cid,
"collected_at": _iso(collected_at),
@@ -1271,6 +1333,8 @@ class HistoryStore:
"observations_extracted": extracted,
"observations_stored": stored,
"extract_error": extract_error,
+ "stale_age_s": stale_age_s,
+ "stale_fetches": stale_fetches,
}
def series_history(
diff --git a/src/world_intel_mcp/tests/test_history_honesty.py b/src/world_intel_mcp/tests/test_history_honesty.py
index 6c08caf..42d1260 100644
--- a/src/world_intel_mcp/tests/test_history_honesty.py
+++ b/src/world_intel_mcp/tests/test_history_honesty.py
@@ -676,3 +676,190 @@ async def test_collector_records_a_source_that_raised_a_base_exception(tmp_path,
s.close()
assert (cap["status"], cap["reason"], cap["record_count"]) == ("error", "source aborted", None)
assert cap["duration_s"] is not None
+
+
+# ---------------------------------------------------------------------------
+# ASCII-only observation dates; a stable stale reason with the age apart
+# ---------------------------------------------------------------------------
+
+_FULLWIDTH_2026 = "2026"
+
+
+ "text",
+ [
+ _FULLWIDTH_2026,
+ _FULLWIDTH_2026 + "-10",
+ "2026-10", # one fullwidth digit in the month
+ "٢٠٢٦", # 2026 in Arabic-Indic digits
+ _FULLWIDTH_2026 + "-10-17T00:00:00Z",
+ ],
+)
+def test_observed_at_must_use_ascii_digits(text) -> None:
+ assert history.normalize_observed_at(text) is None
+
+
+def test_a_point_dated_in_fullwidth_digits_is_skipped_and_counted(store, monkeypatch) -> None:
+ monkeypatch.setattr(history, "_EXTRACTORS", dict(history._EXTRACTORS))
+ monkeypatch.setattr(history, "_EXPECTED", dict(history._EXPECTED))
+ history.register_extractor("test_feed", lambda payload: [
+ Observation("level", 1.0, observed_at=_FULLWIDTH_2026 + "-10"),
+ Observation("level", 2.0, observed_at="2026-10"),
+ ])
+ _record(store, "test_feed", T0, {"rows": [1]})
+ (cap,) = store.capture_history("test_feed")["captures"]
+ assert (cap["observations_extracted"], cap["observations_stored"]) == (2, 1)
+ assert cap["extract_error"] == "1 invalid point(s) skipped"
+ (point,) = store.series_history("test_feed:level")["observations"]
+ assert (point["observed_at"], point["value"]) == ("2026-10", 2.0)
+
+
+def test_stale_reason_is_stable_and_the_age_is_a_field(store) -> None:
+ serves = tuple(StaleServe("polymarket", f"k{i}", age) for i, age in enumerate((30.0, 812.5)))
+ store.record_cycle([
+ SourceOutcome("prediction_markets", T0, 1.0, {"markets": [1]}, stale_serves=serves),
+ SourceOutcome("gas_prices", T0, 1.0, {"prices": [1], "_stale": True,
+ "_stale_age_seconds": 64.5}),
+ SourceOutcome("cyclones", T0, 1.0, {"cyclones": [1], "_stale": True}),
+ ], now=T0)
+ _replay(store, "wildfires", T0, FIRES, age=812.0)
+ _replay(store, "wildfires", T0 + 300, FIRES, age=1112.0)
+ _record(store, "wildfires", T0 + 600, FIRES)
+
+ def _fields(source):
+ return [(c["reason"], c["stale_age_s"], c["stale_fetches"])
+ for c in store.capture_history(source)["captures"]]
+
+ assert _fields("wildfires") == [
+ (None, None, None), # live
+ ("served stale cache", 1112.0, 1),
+ ("served stale cache", 812.0, 1),
+ ]
+ assert _fields("prediction_markets") == [("served stale cache", 812.5, 2)]
+ # Seen only through the payload's marker: the fetch count is unknown.
+ assert _fields("gas_prices") == [("served stale cache", 64.5, None)]
+ assert _fields("cyclones") == [("served stale cache", None, None)]
+
+
+def test_stale_reasons_with_points_stay_one_reason(store) -> None:
+ _replay(store, "market_quotes", T0, _quotes(1.0), age=10.0)
+ _replay(store, "market_quotes", T0 + 300, _quotes(1.0), age=310.0)
+ reasons = {c["reason"] for c in store.capture_history("market_quotes")["captures"]}
+ assert reasons == {
+ "served stale cache; partial: 1 of 7 expected series; observations not stored: "
+ "a stale-cache replay is not a new observation"
+ }
+
+
+def test_health_reports_the_stale_copy_age_apart_from_the_reason(store) -> None:
+ now = T0 + 10_000
+ _record(store, "wildfires", now - 5000, FIRES)
+ _replay(store, "wildfires", now - 10, FIRES, age=4990.0)
+ health = store.collection_health(["wildfires"], now=now)
+ row = health["sources"][0]
+ assert row["last_reason"] == "served stale cache"
+ assert (row["last_stale_age_s"], row["last_stale_fetches"]) == (4990.0, 1)
+ assert "last_stale_age_s" in health["fields_explained"]
+ _record(store, "wildfires", now - 5, FIRES)
+ row = store.collection_health(["wildfires"], now=now)["sources"][0]
+ assert "last_stale_age_s" not in row and "last_stale_fetches" not in row
+
+
+def test_cli_shows_the_stale_age_beside_the_stable_reason(cli_db, monkeypatch) -> None:
+ monkeypatch.setenv("COLUMNS", "260")
+ serves = tuple(StaleServe("polymarket", f"k{i}", age) for i, age in enumerate((30.0, 812.5)))
+ s = HistoryStore(cli_db)
+ _replay(s, "wildfires", T0, FIRES, age=812.0)
+ s.record_cycle([SourceOutcome("prediction_markets", T0, 1.0, {"markets": [1]},
+ stale_serves=serves)], now=T0)
+ s.close()
+ out = _invoke("history", "captures", "wildfires").output
+ assert "served stale cache (age 812.0 s)" in out
+ out = _invoke("history", "captures", "prediction_markets").output
+ assert "served stale cache (2 fetches, oldest 812.5 s)" in out
+ out = _invoke("history", "captures", "wildfires", "--capture-id", "1").output
+ assert "Reason: served stale cache (age 812.0 s)" in out
+
+
+# The run-log table as de73264 created it, before the stale columns.
+_CAPTURES_BEFORE_STALE_COLUMNS = """
+CREATE TABLE history_captures (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ source TEXT NOT NULL,
+ collected_at REAL NOT NULL,
+ status TEXT NOT NULL CHECK (status IN ('ok', 'degraded', 'error')),
+ duration_s REAL,
+ record_count INTEGER,
+ error TEXT,
+ payload_hash TEXT,
+ changed INTEGER,
+ observations_extracted INTEGER,
+ observations_stored INTEGER,
+ extract_error TEXT
+);
+"""
+
+
+def _capture_columns(db) -> list[str]:
+ conn = sqlite3.connect(str(db))
+ try:
+ return [row[1] for row in conn.execute("PRAGMA table_info(history_captures)")]
+ finally:
+ conn.close()
+
+
+def test_an_existing_run_log_gains_the_stale_columns_in_place(tmp_path) -> None:
+ db = tmp_path / "before.db"
+ conn = sqlite3.connect(str(db))
+ conn.executescript(_CAPTURES_BEFORE_STALE_COLUMNS)
+ with conn:
+ conn.execute(
+ "INSERT INTO history_captures (source, collected_at, status, error) "
+ "VALUES ('gas_prices', ?, 'degraded', 'served stale cache (age 812.0 s)')",
+ (T0,),
+ )
+ conn.close()
+ for _ in range(2): # opening again is a no-op
+ HistoryStore(db).close()
+ columns = _capture_columns(db)
+ assert columns.count("stale_age_s") == 1 and columns.count("stale_fetches") == 1
+
+ s = HistoryStore(db)
+ try:
+ _replay(s, "gas_prices", T0 + 300, {"prices": [1]}, age=99.0)
+ new, old = s.capture_history("gas_prices")["captures"]
+ row = s.collection_health(["gas_prices"], now=T0 + 400)["sources"][0]
+ finally:
+ s.close()
+ assert (old["reason"], old["stale_age_s"], old["stale_fetches"]) == (
+ "served stale cache (age 812.0 s)", None, None
+ )
+ assert (new["reason"], new["stale_age_s"], new["stale_fetches"]) == (
+ "served stale cache", 99.0, 1
+ )
+ # The old row's reason still marks it a stale replay.
+ assert (row["state"], row["consecutive_failures"], row["last_success_at"]) == ("stale", 2, None)
+
+
+def test_migration_tolerates_a_column_another_process_just_added(tmp_path) -> None:
+ db = tmp_path / "race.db"
+ HistoryStore(db).close()
+ conn = sqlite3.connect(str(db))
+
+ class _ReadBeforeTheOtherAlter:
+ """The table_info read happened before another process's ALTER."""
+
+ def execute(self, sql, *args):
+ if sql.startswith("PRAGMA table_info"):
+ return iter(())
+ return conn.execute(sql, *args)
+
+ try:
+ history._add_missing_capture_columns(_ReadBeforeTheOtherAlter())
+ empty = sqlite3.connect(str(tmp_path / "empty.db"))
+ with pytest.raises(sqlite3.OperationalError, match="no such table"):
+ history._add_missing_capture_columns(empty)
+ empty.close()
+ finally:
+ conn.close()
+ assert _capture_columns(db).count("stale_age_s") == 1
diff --git a/src/world_intel_mcp/tools/history.py b/src/world_intel_mcp/tools/history.py
index 555d358..5f0b66f 100644
--- a/src/world_intel_mcp/tools/history.py
+++ b/src/world_intel_mcp/tools/history.py
@@ -45,7 +45,8 @@ TOOLS: list[Tool] = [
description=(
"A source's earlier collector captures, newest first: status (ok / degraded / "
"error with reason; a run answered from expired cache is degraded with "
- "reason 'served stale cache'), duration, record count, payload hash and "
+ "reason 'served stale cache' and the copy's age in stale_age_s), duration, "
+ "record count, payload hash and "
"whether it changed from the previous capture. Pass capture_id to replay one "
"stored payload (over the replay cap, an outline of its top-level keys). "
+ _ACCRUAL