Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

feat(grounding): per-claim freshness verdicts (--verify-freshness) (#805)

Matt Van Horn9c020b1393ec
diff --git a/CONFIGURATION.md b/CONFIGURATION.md
index e9f57ed3..3383d45f 100644
--- a/CONFIGURATION.md
+++ b/CONFIGURATION.md
@@ -49,6 +49,7 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(
- `--register {default,exec,dev,creator,eli5}` - shape a standard single-topic Markdown or HTML research brief for its audience. `exec` is decisions-first with five core findings and numbers up top; `dev` gives GitHub, code, and technical signals more room; `creator` leads with hooks, Best Takes, community reactions, and virality metrics; `eli5` keeps the established evidence layout and asks the synthesizing agent for accessible language. Registers do not change retrieval, JSON exports, discovery, drill, library feed/search, or comparison output.
- `--discover <domain>` - topic-less trending discovery. Sweeps rising/top-week Reddit listings (category-mapped communities, with r/all as the uncategorized fallback), Hacker News front/best stories, Digg AI 1000 clusters when `digg-pp-cli` is on PATH, and broad X activity when an X backend is authenticated, then returns 5-10 engagement-velocity-ranked topics. Run without a positional topic; it is mutually exclusive with `--drill`. `--emit=json` uses the separate versioned discovery contract documented in the [JSON export reference](docs/reference/json-export.md).
- `--drill <target>` - deep follow-up over the fresh `~/.config/last30days/last-report.json` cache. Accepts a 1-based index (`--drill "cluster 3"` or `--drill "3"`) or a fuzzy cluster title/entity description. It re-fetches only sources that contributed to the matched cluster, enables their deep comment/transcript enrichment paths, merges/dedupes the evidence, and replaces the cache so drills can chain. Run it without a positional topic; if the cache is absent or expired, run a normal research pass first.
+- `--verify-freshness` - opt into an act-time verification pass for conservatively extracted, source-grounded claims (Polymarket odds/end dates, GitHub stars, StockTwits sentiment ratios, and explicit status assertions). With a topic, verification runs after research; without a topic, it re-verifies the fresh `last-report.json` cache without repeating research. Verdicts are `current`, `stale`, `contradicted`, or `unsupported` and include evidence timestamps. Set `LAST30DAYS_VERIFY_FRESHNESS=on` in `.env` to make the pass default for normal research runs.
- `--save-suffix <name>` - distinguish runs of the same topic (e.g. per client: `--save-suffix=acme`).
- `--no-browser-cookies` - hard-disable browser-cookie extraction for this run, even when `FROM_BROWSER` is configured. MCP and folder-mode hosts use this for safe defaults.
- `--publish-html` - with `--emit=html`, publish the rendered HTML to `ht-ml.app` after local output/save-dir writes. This is explicit opt-in only; pages are public by default.
@@ -65,7 +66,7 @@ The engine's `.env` reader doesn't expand `$HOME` — only the tilde, via `Path(
The footer line `📎 Raw results saved to ${LAST30DAYS_MEMORY_DIR:-$HOME/Documents/Last30Days}/<slug>-raw.md` is the canonical pointer; if it shows backslashes on Windows update past v3.1.1.
-Every completed research pass writes a structured `last-report.json` cache beside `last-run.json`. HTML follow-up renders use it so `--emit=html --synthesis-file` can reuse report metadata/footer without fetching sources again; `--drill <target>` uses it as the grounded starting point for targeted re-research. Reuse is intentionally short-lived: `LAST30DAYS_REPORT_CACHE_TTL_SECONDS` defaults to `3600` (one hour). Set it to another integer number of seconds to tune the window, or `0` to disable report-cache reuse and drill follow-ups.
+Every completed research pass writes a structured `last-report.json` cache beside `last-run.json`. HTML follow-up renders use it so `--emit=html --synthesis-file` can reuse report metadata/footer without fetching sources again; `--drill <target>` uses it as the grounded starting point for targeted re-research; bare `--verify-freshness` updates only the cached report's claim verdicts. Reuse is intentionally short-lived: `LAST30DAYS_REPORT_CACHE_TTL_SECONDS` defaults to `3600` (one hour). Set it to another integer number of seconds to tune the window, or `0` to disable report-cache reuse and post-run follow-ups.
---
diff --git a/docs/reference/json-export.md b/docs/reference/json-export.md
index 136485ee..85d01ff6 100644
--- a/docs/reference/json-export.md
+++ b/docs/reference/json-export.md
@@ -37,16 +37,21 @@ When `LAST30DAYS_API_KEY` and `LAST30DAYS_API_BASE` route a run through a config
| Field | Type | Meaning |
| --- | --- | --- |
-| `schema_version` | string | Agent export contract version. The current version is `1.0`. |
+| `schema_version` | string | Agent export contract version. The current version is `1.2`. |
| `query` | string | The research topic supplied to the engine. |
| `generated_at` | string | UTC generation timestamp in RFC 3339 format. |
| `window_days` | integer | Number of days between the report's start and end dates. |
| `source_status` | object | Map of source name to the outcome observed during this run. |
+| `freshness_verdicts` | array | Per-claim act-time verdicts produced by `--verify-freshness`; empty when verification was not requested or no conservative claims were extractable. |
| `clusters` | array | Ranked groups of related results. |
| `results` | array | Ranked, flat evidence results for downstream processing. |
All top-level fields are always present. Empty runs contain empty `clusters` and `results` arrays. Sources appear in `source_status` when the run recorded an outcome for them.
+## `freshness_verdicts`
+
+Each entry identifies the grounded claim and candidate, its primary source item, the typed `verdict` (`current`, `stale`, `contradicted`, or `unsupported`), the original and re-derived values when applicable, and source/evidence URLs and timestamps. `stale` means a successful point re-fetch returned a moved value; `contradicted` means a newer item in the report window explicitly disagrees; `unsupported` means the datum could not be re-checked, including degraded `source_status` outcomes. Consumers can gate actions on `verdict == "current"` without treating an unreachable source as evidence that a claim moved.
+
## `source_status`
Each value distinguishes a clean empty result from incomplete coverage:
@@ -81,6 +86,7 @@ Cluster array order is ranking order. A result's `cluster` value is the zero-bas
| Field | Type | Meaning |
| --- | --- | --- |
+| `candidate_id` | string | Stable identifier joining this result to `freshness_verdicts[].candidate_id`. Added in `1.2`. |
| `title` | string | Result title. |
| `source` | string | Primary source name, such as `reddit`, `x`, `youtube`, or `grounding`. |
| `url` | string | Canonical result URL. It may be empty when the provider supplies no link. |
@@ -98,12 +104,12 @@ Comparison queries use an envelope so each entity keeps its own contract:
```json
{
- "schema_version": "1.0",
+ "schema_version": "1.2",
"comparison": true,
"entities": ["OpenAI", "Anthropic"],
"reports": [
- {"entity": "OpenAI", "report": {"schema_version": "1.0", "query": "OpenAI"}},
- {"entity": "Anthropic", "report": {"schema_version": "1.0", "query": "Anthropic"}}
+ {"entity": "OpenAI", "report": {"schema_version": "1.2", "query": "OpenAI"}},
+ {"entity": "Anthropic", "report": {"schema_version": "1.2", "query": "Anthropic"}}
]
}
```
@@ -115,7 +121,8 @@ The abbreviated reports above only illustrate the envelope; real reports contain
- `schema_version` uses `major.minor` numbering.
- Any breaking field removal, rename, type change, semantic change, or envelope change requires a major-version bump.
- Backward-compatible field additions may use a minor-version bump. Consumers should ignore fields they do not recognize.
-- The checked-in golden snapshot test locks the complete `1.0` shape. Contract changes must update the version and snapshot deliberately.
+- The checked-in golden snapshot test locks the complete current shape. Contract changes must update the version and snapshot deliberately.
+- `1.2` added `candidate_id` to each `results` entry so verdicts can be joined to the result they annotate.
- `--json-profile=raw` is outside this compatibility policy because it mirrors internal pipeline dataclasses.
`--preflight --emit=json` is a different machine contract for permission and configuration inspection. `--json-profile` does not alter preflight output.
diff --git a/skills/last30days/SKILL.md b/skills/last30days/SKILL.md
index 02355b14..98996fa1 100644
--- a/skills/last30days/SKILL.md
+++ b/skills/last30days/SKILL.md
@@ -2016,6 +2016,7 @@ Close with `I have all the links to the {N} {source list} I pulled from. Just as
- If they say **"eli5 on"**, **"eli5 mode"**, **"explain simpler"**, or similar → Treat it as `register eli5`: append `LAST30DAYS_REGISTER=eli5` to `~/.config/last30days/.env`, then re-synthesize the current research immediately using the ELI5 guidance without fetching again. Confirm: "ELI5 mode on. All future runs will explain things like you're 5."
- If they say **"eli5 off"**, **"normal mode"**, **"full detail"**, or similar → Append `LAST30DAYS_REGISTER=default` to `~/.config/last30days/.env`. Confirm: "ELI5 mode off. Back to full detail."
- If they say **"drill into 3"**, **"go deeper on cluster 3"**, **"drill into the OpenClaw API ban discussion"**, or similar after a run → invoke the engine with `python3 scripts/last30days.py --drill "<their target>"`. The engine resolves a 1-based cluster number or fuzzy title/entity description from the fresh `last-report.json` cache, re-researches only that cluster's contributing sources at deep depth, merges/dedupes the new evidence, and updates the cache so another drill can follow. Relay the rendered **Original / Deeper** brief. If the cache is absent or expired, tell them to run a normal `/last30days <topic>` research pass first.
+- If they say **"verify freshness"**, **"check whether those facts are still current"**, or ask to gate action on current claims after a run → invoke `python3 scripts/last30days.py --verify-freshness` with no topic. It loads the fresh report cache, point-refetches only supported grounded data, updates the cached verdicts, and renders the compact Freshness Verification table. For a first-pass request, translate the intent into the normal engine invocation plus `--verify-freshness`. `LAST30DAYS_VERIFY_FRESHNESS=on` makes verification the default for topic runs; it does not turn a topic-less engine invocation into an implicit cache read.
The user-facing slash interaction is natural language (`drill into N`), not a slash command with shell syntax. `--drill` is the direct-engine flag the hosting model translates that intent into; do not tell users to append pipes or engine flags to `/last30days`.
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index 61c9bcb2..d3c05000 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -48,7 +48,7 @@ if os.name == "nt":
SCRIPT_DIR = Path(__file__).parent.resolve()
sys.path.insert(0, str(SCRIPT_DIR))
-from lib import dates, env, html_render, http, permission_preflight, pipeline, registers, render, schema, ui
+from lib import dates, env, freshness, html_render, http, permission_preflight, pipeline, registers, render, schema, ui
_child_pids: set[int] = set()
_child_pids_lock = threading.Lock()
@@ -427,6 +427,19 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument("--search", help="Comma-separated source list")
parser.add_argument("--quick", action="store_true", help="Lower-latency retrieval profile")
parser.add_argument("--deep", action="store_true", help="Higher-recall retrieval profile")
+ freshness_group = parser.add_mutually_exclusive_group()
+ freshness_group.add_argument(
+ "--verify-freshness",
+ action="store_true",
+ default=None,
+ help="Re-check source-grounded claims after research, or verify the cached report when no topic is supplied",
+ )
+ freshness_group.add_argument(
+ "--no-verify-freshness",
+ dest="verify_freshness",
+ action="store_false",
+ help="Disable freshness verification configured by LAST30DAYS_VERIFY_FRESHNESS",
+ )
parser.add_argument(
"--drill",
metavar="TARGET",
@@ -888,6 +901,87 @@ def _load_last_report_cache(
return None
+def _config_truthy(value: object) -> bool:
+ return str(value or "").strip().lower() in {"1", "true", "yes", "on"}
+
+
+def _freshness_enabled(args: argparse.Namespace, config: dict[str, object]) -> bool:
+ if args.verify_freshness is not None:
+ return bool(args.verify_freshness)
+ return _config_truthy(config.get("LAST30DAYS_VERIFY_FRESHNESS"))
+
+
+def _update_cached_freshness(
+ cache_path: Path,
+ report: schema.Report,
+ entity_reports: list[tuple[str, schema.Report]] | None,
+) -> bool:
+ """Rewrite cached report bodies without extending the research-cache TTL."""
+ try:
+ payload = json.loads(cache_path.read_text(encoding="utf-8"))
+ if not isinstance(payload, dict) or payload.get("schema") != REPORT_CACHE_VERSION:
+ return False
+ existing = payload.get("reports") or []
+ if entity_reports:
+ cached_reports = entity_reports
+ else:
+ label = (
+ str(existing[0].get("entity") or report.topic)
+ if existing and isinstance(existing[0], dict)
+ else report.topic
+ )
+ cached_reports = [(label, report)]
+ payload["reports"] = [
+ {"entity": label, "report": schema.to_dict(cached_report)}
+ for label, cached_report in cached_reports
+ ]
+ cache_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
+ return True
+ except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc:
+ sys.stderr.write(
+ f"[last30days] warning: could not update freshness cache: {exc}\n"
+ )
+ return False
+
+
+def _verify_report_set(
+ report: schema.Report,
+ entity_reports: list[tuple[str, schema.Report]] | None,
+ *,
+ allow_network: bool,
+) -> None:
+ reports = [item for _, item in entity_reports] if entity_reports else [report]
+ for current_report in reports:
+ freshness.verify_report(current_report, allow_network=allow_network)
+ if not any(current_report.freshness_verdicts for current_report in reports):
+ # An empty verdict list is a legitimate outcome, but a silent one has
+ # already misled operators once; say why there is nothing to show.
+ sys.stderr.write(
+ "[last30days] Freshness verification found no re-checkable claims"
+ " in this report; the verdict list is empty.\n"
+ )
+
+
+def _run_cached_freshness(
+ args: argparse.Namespace,
+ config: dict[str, object],
+) -> int:
+ cached = _load_last_report_cache(
+ None,
+ ttl_seconds=_report_cache_ttl_seconds(config),
+ )
+ if cached is None:
+ sys.stderr.write("[last30days] No fresh cached report; run a research pass first.\n")
+ return 2
+ report, entity_reports, cache_path = cached
+ _verify_report_set(report, entity_reports, allow_network=not args.mock)
+ if _update_cached_freshness(cache_path, report, entity_reports):
+ sys.stderr.write(f"[last30days] Updated freshness verdicts in {cache_path}\n")
+ else:
+ sys.stderr.write("[last30days] warning: freshness cache update failed\n")
+ return _render_save_and_print(args, report, entity_reports, None, config)
+
+
def _drill_config(config: dict[str, object], sources: list[str]) -> dict[str, object]:
"""Enable configured comment enrichments for a deep follow-up."""
drill_config = dict(config)
@@ -1023,6 +1117,10 @@ def _run_drill(
matched_clusters,
target=args.drill,
)
+ if _freshness_enabled(args, config):
+ _verify_report_set(merged, None, allow_network=not args.mock)
+ else:
+ merged.freshness_verdicts = []
if _write_last_run(report.topic, merged):
sys.stderr.write(f"[last30days] Updated drill cache in {cache_path}\n")
else:
@@ -1443,10 +1541,16 @@ def _config_policy_for_args(args: argparse.Namespace, topic: str, extra_argv: li
or normalized_topic == "library search"
or normalized_topic.startswith("library search ")
)
+ is_cached_verification = bool(getattr(args, "verify_freshness", None)) and not normalized_topic
if args.no_browser_cookies:
browser_mode = "off"
- elif args.diagnose or args.preflight or normalized_topic == "doctor" or is_library_command:
+ elif (
+ args.diagnose or args.preflight or normalized_topic == "doctor"
+ or is_library_command or is_cached_verification
+ ):
# doctor is plan-only like --diagnose: it must never read cookies.
+ # Cache-only freshness verification hits only point APIs (Polymarket,
+ # GitHub, StockTwits) - no cookie-backed source, so no Keychain prompt.
browser_mode = "plan_only"
elif normalized_topic == "setup":
browser_mode = "read" if _setup_allows_browser_cookies(args, extra_argv) else "off"
@@ -1855,6 +1959,9 @@ def _main(
]
return _run_drill(args, config)
+ if args.verify_freshness and not topic:
+ return _run_cached_freshness(args, config)
+
if args.lookback_days is None:
args.lookback_days = 30
@@ -1880,6 +1987,16 @@ def _main(
and env.read_secret_env("LAST30DAYS_API_KEY")
and os.environ.get("LAST30DAYS_API_BASE")
):
+ if _freshness_enabled(args, config):
+ if args.verify_freshness is True:
+ sys.stderr.write(
+ "[last30days] Freshness verification is not supported by the hosted backend; "
+ "run locally or omit --verify-freshness.\n"
+ )
+ return 2
+ sys.stderr.write(
+ "hosted backend does not support freshness verification; skipping\n"
+ )
if args.emit == "json" and args.json_profile == "agent":
sys.stderr.write(
"[last30days] --json-profile=agent requires the local Report; "
@@ -1941,6 +2058,17 @@ def _main(
f"[last30days] Reusing cached report data from {cache_path}\n"
)
sys.stderr.flush()
+ if _freshness_enabled(args, config):
+ _verify_report_set(
+ cached_report,
+ cached_entity_reports,
+ allow_network=not args.mock,
+ )
+ _update_cached_freshness(
+ cache_path,
+ cached_report,
+ cached_entity_reports,
+ )
return _render_save_and_print(
args, cached_report, cached_entity_reports, synthesis_md, config
)
@@ -2273,6 +2401,9 @@ def _main(
progress.end_processing()
progress.show_error(str(exc))
raise
+ if _freshness_enabled(args, config):
+ _verify_report_set(report, entity_reports, allow_network=not args.mock)
+
_show_runtime_ui(
report, progress, diag,
suppress_web_promo=bool(external_plan or comp_plan),
diff --git a/skills/last30days/scripts/lib/env.py b/skills/last30days/scripts/lib/env.py
index 4b24b1d6..fe95b6db 100644
--- a/skills/last30days/scripts/lib/env.py
+++ b/skills/last30days/scripts/lib/env.py
@@ -528,6 +528,7 @@ def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
('ELI5_MODE', None),
('LAST30DAYS_YOUTUBE_SSH_HOST', None),
('LAST30DAYS_REPORT_CACHE_TTL_SECONDS', None),
+ ('LAST30DAYS_VERIFY_FRESHNESS', None),
('LAST30DAYS_TRANSCRIPT_TIMEOUT', None),
(KEYCHAIN_ALIASES_ENV, None),
# Whisper transcription provider for caption-free audio/video. Groq's
diff --git a/skills/last30days/scripts/lib/freshness.py b/skills/last30days/scripts/lib/freshness.py
new file mode 100644
index 00000000..06d66170
--- /dev/null
+++ b/skills/last30days/scripts/lib/freshness.py
@@ -0,0 +1,566 @@
+"""Deterministic, source-grounded act-time freshness verification."""
+
+from __future__ import annotations
+
+import hashlib
+import re
+from collections import Counter, defaultdict
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Any, Callable
+
+from . import github, grounding, health, polymarket, schema, stocktwits
+
+
+@dataclass(frozen=True)
+class Claim:
+ """A conservative, machine-verifiable claim extracted from one source item."""
+
+ claim_id: str
+ candidate_id: str
+ text: str
+ source: str
+ source_item_id: str
+ source_url: str
+ source_timestamp: str | None
+ datum_kind: str
+ datum_key: str
+ original_value: Any
+
+
+@dataclass(frozen=True)
+class RefetchedDatum:
+ value: Any
+ url: str
+ timestamp: str | None = None
+ values: dict[str, Any] | None = None
+
+
+Refetcher = Callable[[schema.SourceItem | None, str], RefetchedDatum | dict[str, Any] | Any]
+
+_STATUS_PATTERN = re.compile(
+ r"\b(?P<subject>[A-Z][A-Za-z0-9&.'’/+_-]*(?:\s+[A-Z0-9][A-Za-z0-9&.'’/+_-]*){0,5})"
+ r"\s+(?:is|was|remains|became|has been)\s+"
+ r"(?P<status>open|closed|active|inactive|available|unavailable|"
+ r"approved|rejected|launched|discontinued|online|offline)\b"
+)
+_OPPOSITE_STATUS = {
+ "open": "closed",
+ "closed": "open",
+ "active": "inactive",
+ "inactive": "active",
+ "available": "unavailable",
+ "unavailable": "available",
+ "approved": "rejected",
+ "rejected": "approved",
+ "launched": "discontinued",
+ "discontinued": "launched",
+ "online": "offline",
+ "offline": "online",
+}
+_REFETCHABLE_SOURCES = frozenset({"polymarket", "github", "stocktwits"})
+_USABLE_SOURCE_STATES = frozenset({health.OK, schema.PARTIAL})
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def _claim_id(candidate_id: str, kind: str, key: str) -> str:
+ digest = hashlib.sha256(f"{candidate_id}\0{kind}\0{key}".encode()).hexdigest()[:12]
+ return f"claim-{digest}"
+
+
+def _claim(
+ grounded: grounding.GroundedClaimText,
+ kind: str,
+ key: str,
+ value: Any,
+ text: str,
+) -> Claim:
+ item = grounded.item
+ return Claim(
+ claim_id=_claim_id(grounded.candidate_id, kind, key),
+ candidate_id=grounded.candidate_id,
+ text=text,
+ source=item.source,
+ source_item_id=item.item_id,
+ source_url=item.url,
+ source_timestamp=item.published_at,
+ datum_kind=kind,
+ datum_key=key,
+ original_value=value,
+ )
+
+
+def extract_claims(report: schema.Report) -> list[Claim]:
+ """Extract only structured numerics/dates and tightly shaped status claims."""
+ claims: list[Claim] = []
+ item_level_repos: set[str] = set()
+ for grounded in grounding.claim_source_map(report).values():
+ item = grounded.item
+ if item.source == "polymarket":
+ outcome_pairs = item.metadata.get("outcome_prices") or []
+ outcome_counts = Counter(
+ str(pair[0]).strip().casefold()
+ for pair in outcome_pairs
+ if isinstance(pair, (list, tuple)) and len(pair) == 2
+ )
+ seen_outcomes: dict[str, int] = defaultdict(int)
+ for pair in outcome_pairs:
+ if not isinstance(pair, (list, tuple)) or len(pair) != 2:
+ continue
+ name, value = pair
+ if not isinstance(value, (int, float)) or isinstance(value, bool):
+ continue
+ key = str(name).strip()
+ if not key:
+ continue
+ normalized_key = key.casefold()
+ occurrence = seen_outcomes[normalized_key]
+ seen_outcomes[normalized_key] += 1
+ datum_key = (
+ f"{key}\x1f{occurrence}"
+ if outcome_counts[normalized_key] > 1
+ else key
+ )
+ claims.append(
+ _claim(
+ grounded,
+ "polymarket_probability",
+ datum_key,
+ float(value),
+ f"{item.title}: {key} is {float(value) * 100:g}%",
+ )
+ )
+ end_date = item.metadata.get("end_date")
+ if isinstance(end_date, str) and re.fullmatch(r"\d{4}-\d{2}-\d{2}", end_date):
+ claims.append(
+ _claim(
+ grounded,
+ "polymarket_end_date",
+ "end_date",
+ end_date,
+ f"{item.title} closes {end_date}",
+ )
+ )
+ elif item.source == "github":
+ stars = item.engagement.get("stars")
+ repo = _github_repo(item)
+ if repo and isinstance(stars, (int, float)) and not isinstance(stars, bool):
+ item_level_repos.add((grounded.candidate_id, repo.casefold()))
+ claims.append(
+ _claim(
+ grounded,
+ "github_stars",
+ "stars",
+ int(stars),
+ f"{repo} has {int(stars):,} GitHub stars",
+ )
+ )
+ elif item.source == "stocktwits":
+ aggregate = item.metadata.get("sentiment_aggregate") or {}
+ pct = aggregate.get("pct_bullish") if isinstance(aggregate, dict) else None
+ symbol = str(item.metadata.get("symbol") or item.container or "").strip()
+ if symbol and isinstance(pct, (int, float)) and not isinstance(pct, bool):
+ claims.append(
+ _claim(
+ grounded,
+ "stocktwits_bullish_pct",
+ "pct_bullish",
+ float(pct),
+ f"StockTwits ${symbol} tagged sentiment is {float(pct):g}% bullish",
+ )
+ )
+
+ # Status assertions are accepted only when a short, explicit subject +
+ # copula + status occurs in the exact candidate text tied above.
+ status_text = " ".join(part for part in (grounded.title, grounded.summary) if part)
+ match = _STATUS_PATTERN.search(status_text)
+ if match:
+ subject = match.group("subject").strip()
+ status = match.group("status").lower()
+ claims.append(
+ _claim(
+ grounded,
+ "status_assertion",
+ subject.lower(),
+ status,
+ match.group(0),
+ )
+ )
+
+ claims.extend(_candidate_star_claims(report, item_level_repos))
+ return claims
+
+
+def _candidate_star_claims(
+ report: schema.Report,
+ item_level_repos: set[tuple[str, str]],
+) -> list[Claim]:
+ """Emit star claims from candidate enrichment metadata.
+
+ Star enrichment attaches ``metadata["github_stars"]`` (repo -> stars)
+ after reranking, so these facts never appear on item-level engagement -
+ typically the candidate's primary item is a non-GitHub source. Each repo
+ becomes one repo-keyed claim unless the same candidate already claimed it
+ at item level; a different candidate's item-level claim never suppresses
+ this candidate's own verdict (and its inline freshness flag).
+ """
+ claims: list[Claim] = []
+ candidates_by_id = {
+ candidate.candidate_id: candidate for candidate in report.ranked_candidates
+ }
+ for grounded in grounding.claim_source_map(report).values():
+ candidate = candidates_by_id.get(grounded.candidate_id)
+ if candidate is None:
+ continue
+ stars_map = candidate.metadata.get("github_stars")
+ if not isinstance(stars_map, dict):
+ continue
+ for repo, stars in sorted(stars_map.items()):
+ if not isinstance(repo, str) or not re.fullmatch(r"[^/\s]+/[^/\s]+", repo):
+ continue
+ if isinstance(stars, bool) or not isinstance(stars, (int, float)):
+ continue
+ if (grounded.candidate_id, repo.casefold()) in item_level_repos:
+ continue
+ item = grounded.item
+ claims.append(
+ Claim(
+ claim_id=_claim_id(grounded.candidate_id, "github_stars", repo),
+ candidate_id=grounded.candidate_id,
+ text=f"{repo} has {int(stars):,} GitHub stars",
+ source="github",
+ source_item_id=item.item_id,
+ source_url=f"https://github.com/{repo}",
+ source_timestamp=item.published_at,
+ datum_kind="github_stars",
+ datum_key=repo,
+ original_value=int(stars),
+ )
+ )
+ return claims
+
+
+def _github_repo(item: schema.SourceItem) -> str | None:
+ if item.container and re.fullmatch(r"[^/\s]+/[^/\s]+", item.container):
+ return item.container
+ match = re.match(r"https?://github\.com/([^/]+/[^/#?]+)", item.url)
+ return match.group(1).removesuffix(".git") if match else None
+
+
+def _default_refetchers() -> dict[str, Refetcher]:
+ return {
+ "polymarket": polymarket.refetch_datum,
+ "github": github.refetch_datum,
+ "stocktwits": stocktwits.refetch_datum,
+ }
+
+
+def _coerce_refetched(value: RefetchedDatum | dict[str, Any] | Any, fallback_url: str) -> RefetchedDatum:
+ if isinstance(value, RefetchedDatum):
+ return value
+ if isinstance(value, dict) and "value" in value:
+ return RefetchedDatum(
+ value=value["value"],
+ url=str(value.get("url") or fallback_url),
+ timestamp=value.get("timestamp"),
+ values=value.get("values") if isinstance(value.get("values"), dict) else None,
+ )
+ return RefetchedDatum(value=value, url=fallback_url)
+
+
+def _format_verdict_value(kind: str, value: Any) -> str:
+ """Format a verdict value the way the matching claim text renders it."""
+ if kind == "polymarket_probability":
+ try:
+ return f"{float(value) * 100:g}%"
+ except (TypeError, ValueError):
+ return str(value)
+ if kind == "stocktwits_bullish_pct":
+ try:
+ return f"{float(value):g}%"
+ except (TypeError, ValueError):
+ return str(value)
+ if isinstance(value, bool):
+ return str(value)
+ if isinstance(value, int):
+ return f"{value:,}"
+ if isinstance(value, float):
+ return f"{value:g}"
+ return str(value)
+
+
+def _values_match(claim: Claim, current: Any) -> bool:
+ if claim.datum_kind == "polymarket_probability":
+ try:
+ return abs(float(claim.original_value) - float(current)) < 0.005
+ except (TypeError, ValueError):
+ return False
+ if isinstance(claim.original_value, (int, float)) and isinstance(current, (int, float)):
+ return float(claim.original_value) == float(current)
+ return claim.original_value == current
+
+
+def _newer_status_contradiction(
+ report: schema.Report,
+ claim: Claim,
+) -> schema.SourceItem | None:
+ opposite = _OPPOSITE_STATUS.get(str(claim.original_value))
+ if not opposite:
+ return None
+ subject_tokens = [
+ token.lower()
+ for token in re.findall(r"[A-Za-z0-9]+", claim.datum_key)
+ if len(token) >= 3
+ ]
+ if not subject_tokens:
+ return None
+ candidates = [
+ item
+ for items in report.items_by_source.values()
+ for item in items
+ if (item.source, item.item_id) != (claim.source, claim.source_item_id)
+ and item.published_at
+ and (not claim.source_timestamp or item.published_at > claim.source_timestamp)
+ ]
+ candidates.sort(key=lambda item: item.published_at or "", reverse=True)
+ for item in candidates:
+ text = f"{item.title} {item.snippet} {item.body}"
+ for match in _STATUS_PATTERN.finditer(text):
+ asserted_subject = [
+ token.lower()
+ for token in re.findall(r"[A-Za-z0-9]+", match.group("subject"))
+ if len(token) >= 3
+ ]
+ if asserted_subject == subject_tokens and match.group("status").lower() == opposite:
+ return item
+ return None
+
+
+def _point_refetch_key(item: schema.SourceItem, claim: Claim) -> tuple[str, ...]:
+ """Identify the source snapshot shared by claims in one verification pass."""
+ if claim.source == "polymarket":
+ key = item.metadata.get("event_id") or item.url
+ elif claim.source == "stocktwits":
+ window = item.metadata.get("freshness_window") or {}
+ return tuple(
+ str(value or "").strip().casefold()
+ for value in (
+ claim.source,
+ item.metadata.get("symbol") or item.container or item.url,
+ window.get("depth"),
+ window.get("from_date"),
+ window.get("to_date"),
+ )
+ )
+ elif claim.source == "github":
+ key = _github_repo(item) or item.url
+ else:
+ key = item.item_id
+ return claim.source, str(key).strip().casefold()
+
+
+def _point_verdict(
+ claim: Claim,
+ checked_at: str,
+ refreshed: RefetchedDatum,
+) -> schema.FreshnessVerdict:
+ """Build the current/stale verdict for a successfully re-fetched datum."""
+ matches = _values_match(claim, refreshed.value)
+ return schema.FreshnessVerdict(
+ claim_id=claim.claim_id,
+ candidate_id=claim.candidate_id,
+ claim=claim.text,
+ source=claim.source,
+ source_item_id=claim.source_item_id,
+ verdict="current" if matches else "stale",
+ checked_at=checked_at,
+ source_url=claim.source_url,
+ source_timestamp=claim.source_timestamp,
+ evidence_url=refreshed.url,
+ evidence_timestamp=refreshed.timestamp or checked_at,
+ original_value=claim.original_value,
+ current_value=refreshed.value,
+ detail=None if matches else (
+ "moved: "
+ f"{_format_verdict_value(claim.datum_kind, claim.original_value)}"
+ " -> "
+ f"{_format_verdict_value(claim.datum_kind, refreshed.value)}"
+ ),
+ )
+
+
+def _unsupported(
+ claim: Claim,
+ checked_at: str,
+ detail: str,
+) -> schema.FreshnessVerdict:
+ return schema.FreshnessVerdict(
+ claim_id=claim.claim_id,
+ candidate_id=claim.candidate_id,
+ claim=claim.text,
+ source=claim.source,
+ source_item_id=claim.source_item_id,
+ verdict="unsupported",
+ checked_at=checked_at,
+ source_url=claim.source_url,
+ source_timestamp=claim.source_timestamp,
+ # No fresh evidence was obtained; the original source stays on
+ # source_url/source_timestamp and the evidence fields stay empty.
+ evidence_url="",
+ evidence_timestamp=None,
+ original_value=claim.original_value,
+ detail=detail,
+ )
+
+
+def verify_report(
+ report: schema.Report,
+ *,
+ refetchers: dict[str, Refetcher] | None = None,
+ allow_network: bool = True,
+ checked_at: str | None = None,
+) -> list[schema.FreshnessVerdict]:
+ """Attach and return deterministic freshness verdicts for ``report``."""
+ checked = checked_at or _now()
+ dispatch = _default_refetchers() if refetchers is None else refetchers
+ items = {
+ (item.source, item.item_id): item
+ for source_items in report.items_by_source.values()
+ for item in source_items
+ }
+ for candidate in report.ranked_candidates:
+ for item in candidate.source_items:
+ items.setdefault((item.source, item.item_id), item)
+
+ verdicts: list[schema.FreshnessVerdict] = []
+ point_cache: dict[tuple[str, ...], tuple[str, RefetchedDatum]] = {}
+ point_errors: dict[tuple[str, ...], str] = {}
+ for claim in extract_claims(report):
+ if claim.datum_kind == "status_assertion":
+ contradiction = _newer_status_contradiction(report, claim)
+ if contradiction:
+ verdicts.append(
+ schema.FreshnessVerdict(
+ claim_id=claim.claim_id,
+ candidate_id=claim.candidate_id,
+ claim=claim.text,
+ source=claim.source,
+ source_item_id=claim.source_item_id,
+ verdict="contradicted",
+ checked_at=checked,
+ source_url=claim.source_url,
+ source_timestamp=claim.source_timestamp,
+ evidence_url=contradiction.url,
+ evidence_timestamp=contradiction.published_at,
+ original_value=claim.original_value,
+ current_value=_OPPOSITE_STATUS.get(str(claim.original_value)),
+ detail=f"Newer {contradiction.source} item disagrees",
+ )
+ )
+ else:
+ verdicts.append(
+ _unsupported(
+ claim,
+ checked,
+ "Status could not be positively re-derived from a current source",
+ )
+ )
+ continue
+
+ if claim.datum_kind == "github_stars" and claim.datum_key != "stars":
+ # Candidate-enrichment star claim: the repo slug in datum_key is
+ # the refetch subject. The datum came from post-rerank enrichment,
+ # not the github search source, so it bypasses the grounding-item
+ # lookup and the per-source outcome gate.
+ refetcher = dispatch.get("github")
+ if refetcher is None:
+ verdicts.append(
+ _unsupported(claim, checked, "No point-refetch verifier is registered")
+ )
+ continue
+ if not allow_network:
+ verdicts.append(
+ _unsupported(claim, checked, "Network verification is disabled for this run")
+ )
+ continue
+ cache_key = ("github", claim.datum_key.strip().casefold())
+ if cache_key in point_errors:
+ verdicts.append(_unsupported(claim, checked, point_errors[cache_key]))
+ continue
+ try:
+ cached = point_cache.get(cache_key)
+ if cached:
+ # Any snapshot for this repo is the star count, whether an
+ # item-level claim ("stars") or a repo-keyed one fetched it.
+ refreshed = cached[1]
+ else:
+ refreshed = _coerce_refetched(
+ refetcher(None, claim.datum_key), claim.source_url
+ )
+ point_cache[cache_key] = (claim.datum_key, refreshed)
+ verdicts.append(_point_verdict(claim, checked, refreshed))
+ except Exception as exc: # verifier failures degrade to a typed verdict
+ detail = f"Re-check failed: {exc}"
+ point_errors[cache_key] = detail
+ verdicts.append(_unsupported(claim, checked, detail))
+ continue
+
+ item = items.get((claim.source, claim.source_item_id))
+ outcome = report.source_status.get(claim.source)
+ if item is None:
+ verdicts.append(_unsupported(claim, checked, "Grounding source item is unavailable"))
+ continue
+ if outcome and outcome.state not in _USABLE_SOURCE_STATES:
+ verdicts.append(
+ _unsupported(
+ claim,
+ checked,
+ f"Source status is {outcome.state}; the datum could not be re-checked",
+ )
+ )
+ continue
+ refetcher = dispatch.get(claim.source)
+ if claim.source not in _REFETCHABLE_SOURCES or refetcher is None:
+ verdicts.append(_unsupported(claim, checked, "No point-refetch verifier is registered"))
+ continue
+ if not allow_network:
+ verdicts.append(_unsupported(claim, checked, "Network verification is disabled for this run"))
+ continue
+ cache_key = _point_refetch_key(item, claim)
+ if cache_key in point_errors:
+ verdicts.append(_unsupported(claim, checked, point_errors[cache_key]))
+ continue
+ try:
+ cached = point_cache.get(cache_key)
+ if cached and cached[0] == claim.datum_key:
+ refreshed = cached[1]
+ elif cached and cached[1].values and claim.datum_key in cached[1].values:
+ refreshed = RefetchedDatum(
+ value=cached[1].values[claim.datum_key],
+ url=cached[1].url,
+ timestamp=cached[1].timestamp,
+ values=cached[1].values,
+ )
+ elif cached:
+ verdicts.append(
+ _unsupported(
+ claim,
+ checked,
+ "Re-fetched snapshot did not include this datum",
+ )
+ )
+ continue
+ else:
+ refreshed = _coerce_refetched(refetcher(item, claim.datum_key), claim.source_url)
+ point_cache[cache_key] = (claim.datum_key, refreshed)
+ verdicts.append(_point_verdict(claim, checked, refreshed))
+ except Exception as exc: # verifier failures degrade to a typed verdict
+ detail = f"Re-check failed: {exc}"
+ point_errors[cache_key] = detail
+ verdicts.append(_unsupported(claim, checked, detail))
+
+ report.freshness_verdicts = verdicts
+ return verdicts
diff --git a/skills/last30days/scripts/lib/github.py b/skills/last30days/scripts/lib/github.py
index d428b9ee..1d6465a6 100644
--- a/skills/last30days/scripts/lib/github.py
+++ b/skills/last30days/scripts/lib/github.py
@@ -17,7 +17,7 @@ import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Dict, List, Optional
-from . import dates, env, log
+from . import dates, env, http, log, schema
from .query import extract_core_subject
from .relevance import token_overlap_relevance
@@ -545,6 +545,45 @@ def _format_stars(n: int) -> str:
return str(n)
+def refetch_datum(item: schema.SourceItem | None, datum_key: str) -> dict[str, Any]:
+ """Re-fetch one repository counter through the shared HTTP wrapper.
+
+ ``datum_key`` is either the literal ``"stars"`` (item-level claim; the
+ repo derives from the grounding item) or an ``owner/repo`` slug
+ (candidate-enrichment claim; the repo itself is the refetch subject and
+ the item is not consulted, so it may be ``None``).
+ """
+ if re.fullmatch(r"[^/\s]+/[^/\s]+", datum_key):
+ repo = datum_key
+ elif datum_key != "stars":
+ raise KeyError(f"Unsupported GitHub datum: {datum_key}")
+ else:
+ if item is None:
+ raise ValueError("Item-level star refetch requires the grounding item")
+ repo = item.container or ""
+ if not re.fullmatch(r"[^/\s]+/[^/\s]+", repo):
+ match = re.match(r"https?://github\.com/([^/]+/[^/#?]+)", item.url)
+ repo = match.group(1).removesuffix(".git") if match else ""
+ if not repo:
+ raise ValueError("GitHub item has no owner/repository reference")
+ headers = {"Accept": "application/vnd.github+json"}
+ token = _resolve_token()
+ if token:
+ headers["Authorization"] = f"Bearer {token}"
+ data = http.request(
+ "GET", f"https://api.github.com/repos/{repo}",
+ headers=headers, timeout=10, retries=2,
+ )
+ if not isinstance(data, dict) or not isinstance(data.get("stargazers_count"), int):
+ raise KeyError("GitHub star count was not returned")
+ fallback_url = item.url if item is not None else f"https://github.com/{repo}"
+ return {
+ "value": data["stargazers_count"],
+ "url": str(data.get("html_url") or fallback_url),
+ "timestamp": data.get("updated_at"),
+ }
+
+
def search_github_person(
username: str,
from_date: str,
diff --git a/skills/last30days/scripts/lib/grounding.py b/skills/last30days/scripts/lib/grounding.py
index c3ae7f70..0e1985f5 100644
--- a/skills/last30days/scripts/lib/grounding.py
+++ b/skills/last30days/scripts/lib/grounding.py
@@ -4,10 +4,42 @@ from __future__ import annotations
import sys
import urllib.parse
+from dataclasses import dataclass
from datetime import datetime
from urllib.parse import urlparse
-from . import dates, env, http, web_search_keyless
+from . import dates, env, http, schema, web_search_keyless
+
+
+@dataclass(frozen=True)
+class GroundedClaimText:
+ """Candidate text with its exact primary evidence item."""
+
+ candidate_id: str
+ title: str
+ summary: str
+ item: schema.SourceItem
+
+
+def claim_source_map(report: schema.Report) -> dict[str, GroundedClaimText]:
+ """Expose only candidate claims that have a clean primary-item trace.
+
+ Freshness verification deliberately starts here instead of scanning all
+ report prose. A candidate without a primary ``SourceItem`` cannot produce
+ an auditable per-claim verdict.
+ """
+ grounded: dict[str, GroundedClaimText] = {}
+ for candidate in report.ranked_candidates:
+ item = schema.candidate_primary_item(candidate)
+ if item is None:
+ continue
+ grounded[candidate.candidate_id] = GroundedClaimText(
+ candidate_id=candidate.candidate_id,
+ title=candidate.title,
+ summary=candidate.snippet or item.snippet or item.body,
+ item=item,
+ )
+ return grounded
# ---------------------------------------------------------------------------
diff --git a/skills/last30days/scripts/lib/normalize.py b/skills/last30days/scripts/lib/normalize.py
index a1f62103..ed8c77ba 100644
--- a/skills/last30days/scripts/lib/normalize.py
+++ b/skills/last30days/scripts/lib/normalize.py
@@ -663,7 +663,7 @@ def _normalize_polymarket(
"liquidity": item.get("liquidity") or 0,
}
return _source_item(
- item_id=str(item.get("id") or f"PM{index + 1}"),
+ item_id=str(item.get("event_id") or item.get("id") or f"PM{index + 1}"),
source=source,
title=title or question or f"Polymarket event {index + 1}",
body="\n".join(part for part in [title, question, str(item.get("price_movement") or "")] if part),
@@ -677,6 +677,7 @@ def _normalize_polymarket(
why_relevant=str(item.get("why_relevant") or ""),
snippet=str(item.get("price_movement") or ""),
metadata={
+ "event_id": item.get("event_id"),
"question": question,
"end_date": item.get("end_date"),
"outcome_prices": item.get("outcome_prices") or [],
diff --git a/skills/last30days/scripts/lib/polymarket.py b/skills/last30days/scripts/lib/polymarket.py
index 235c6f57..f7e7b7a2 100644
--- a/skills/last30days/scripts/lib/polymarket.py
+++ b/skills/last30days/scripts/lib/polymarket.py
@@ -10,12 +10,13 @@ import re
import sys
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Dict, List, Optional
-from urllib.parse import quote_plus, urlencode
+from urllib.parse import quote, quote_plus, urlencode
from . import http, log
from .relevance import LOW_SIGNAL_QUERY_TOKENS, token_overlap_relevance
GAMMA_SEARCH_URL = "https://gamma-api.polymarket.com/public-search"
+GAMMA_EVENTS_URL = "https://gamma-api.polymarket.com/events"
# Pages to fetch per query (API returns 5 events per page, limit param is a no-op)
DEPTH_CONFIG = {
@@ -562,7 +563,13 @@ def _safe_float(val, default=0.0) -> float:
return default
-def parse_polymarket_response(response: Dict[str, Any], topic: str = "") -> List[Dict[str, Any]]:
+def parse_polymarket_response(
+ response: Dict[str, Any],
+ topic: str = "",
+ *,
+ include_all_outcomes: bool = False,
+ include_closed: bool = False,
+) -> List[Dict[str, Any]]:
"""Parse Gamma API response into normalized item dicts.
Each event becomes one item showing its title and top markets.
@@ -584,10 +591,11 @@ def parse_polymarket_response(response: Dict[str, Any], topic: str = "") -> List
slug = event.get("slug", "")
# Filter: skip closed/resolved events
- if event.get("closed", False):
- continue
- if not event.get("active", True):
- continue
+ if not include_closed:
+ if event.get("closed", False):
+ continue
+ if not event.get("active", True):
+ continue
# Filter: skip events that don't match the topic's core subject
# This prevents "NFC West" from matching a "Kanye West" search
@@ -603,16 +611,17 @@ def parse_polymarket_response(response: Dict[str, Any], topic: str = "") -> List
# Filter to active, open markets with liquidity (excludes resolved markets)
active_markets = []
for m in markets:
- if m.get("closed", False):
- continue
- if not m.get("active", True):
- continue
+ if not include_closed:
+ if m.get("closed", False):
+ continue
+ if not m.get("active", True):
+ continue
# Must have liquidity (resolved markets have 0 or None)
try:
liq = float(m.get("liquidity", 0) or 0)
except (ValueError, TypeError):
liq = 0
- if liq > 0:
+ if include_closed or liq > 0:
active_markets.append(m)
if not active_markets:
@@ -743,8 +752,9 @@ def parse_polymarket_response(response: Dict[str, Any], topic: str = "") -> List
if reordered:
outcome_prices = reordered + rest
- # Top 3 outcomes for multi-outcome markets
- top_outcomes = outcome_prices[:3]
+ # Normal display payloads stay compact. Verification requests the
+ # complete snapshot so topic-promoted outcomes remain re-checkable.
+ top_outcomes = outcome_prices if include_all_outcomes else outcome_prices[:3]
remaining = len(outcome_prices) - 3
if remaining < 0:
remaining = 0
@@ -792,3 +802,136 @@ def parse_polymarket_response(response: Dict[str, Any], topic: str = "") -> List
cap = response.get("_cap", len(items))
return items[:cap]
+
+
+def refetch_datum(item: Any, datum_key: str) -> dict[str, Any]:
+ """Re-fetch one event datum through the replay-aware HTTP wrapper."""
+ event_id = str(getattr(item, "metadata", {}).get("event_id") or "").strip()
+ slug_match = re.search(r"/event/([^/?#]+)", str(getattr(item, "url", "")))
+ cached_item_id = str(getattr(item, "item_id", "") or "").strip()
+ # On the slug fallback, a slug can be re-used by a re-created event. When
+ # the cached item still carries the original Gamma event id (numeric; the
+ # synthetic PM<N> parse fallback carries no identity), the response id
+ # must match it too, or the verdict would come from another market.
+ expected_id = (
+ cached_item_id
+ if not event_id and re.fullmatch(r"\d+", cached_item_id)
+ else ""
+ )
+ if event_id:
+ payload = http.request(
+ "GET", f"{GAMMA_EVENTS_URL}/{quote(event_id)}", timeout=10, retries=2,
+ )
+ elif slug_match:
+ if not expected_id:
+ # No event id anywhere: slug equality alone cannot verify event
+ # identity, so fail closed (unsupported) instead of re-deriving a
+ # verdict from whatever event currently owns the slug.
+ raise ValueError(
+ "Polymarket item carries no event id; slug equality alone "
+ "cannot verify event identity"
+ )
+ requested_slug = slug_match.group(1)
+ payload = http.request(
+ "GET", GAMMA_EVENTS_URL, params={"slug": requested_slug},
+ timeout=10, retries=2,
+ )
+ else:
+ raise ValueError("Polymarket item has no event id or slug")
+
+ requested_slug = slug_match.group(1) if slug_match else None
+
+ def _matches_identity(entry: dict) -> bool:
+ if str(entry.get("slug") or "").strip() != requested_slug:
+ return False
+ if expected_id and str(entry.get("id") or "").strip() != expected_id:
+ return False
+ return True
+
+ def _pick_event(events: list) -> Any:
+ candidates = [entry for entry in events if isinstance(entry, dict)]
+ if requested_slug is None:
+ return candidates[0] if candidates else None
+ # Verify identity: Gamma slug queries can return multiple or loosely
+ # matched events, and verifying a claim against another market's
+ # prices would fabricate current/stale verdicts.
+ for entry in candidates:
+ if _matches_identity(entry):
+ return entry
+ return None
+
+ if isinstance(payload, list):
+ event = _pick_event(payload)
+ elif isinstance(payload, dict) and isinstance(payload.get("events"), list):
+ event = _pick_event(payload.get("events") or [])
+ else:
+ event = payload
+ if (
+ requested_slug is not None
+ and isinstance(event, dict)
+ and (
+ str(event.get("slug") or "").strip() not in ("", requested_slug)
+ or (
+ expected_id
+ and str(event.get("id") or "").strip() not in ("", expected_id)
+ )
+ )
+ ):
+ event = None
+ if not isinstance(event, dict):
+ raise KeyError("Polymarket event was not found")
+ # Mixed events: an active event can carry resolved child markets whose
+ # high volume would win the parse and swap the outcome labels. Only fall
+ # back to closed markets when nothing is active (fully resolved event -
+ # the stale-odds transition verification exists to catch).
+ markets = event.get("markets") or []
+ has_active = any(
+ isinstance(m, dict) and m.get("active", True) and not m.get("closed", False)
+ for m in markets
+ )
+ parsed = parse_polymarket_response(
+ {"events": [event]},
+ include_all_outcomes=True,
+ include_closed=not has_active,
+ )
+ if not parsed:
+ raise KeyError("Polymarket event is closed, unavailable, or malformed")
+ refreshed = parsed[0]
+ values: dict[str, Any] = {}
+ outcome_pairs = refreshed.get("outcome_prices") or []
+ outcome_totals: dict[str, int] = {}
+ for name, _price in outcome_pairs:
+ normalized = str(name).casefold()
+ outcome_totals[normalized] = outcome_totals.get(normalized, 0) + 1
+ outcome_counts: dict[str, int] = {}
+ for name, price in outcome_pairs:
+ normalized = str(name).casefold()
+ occurrence = outcome_counts.get(normalized, 0)
+ outcome_counts[normalized] = occurrence + 1
+ key = f"{name}\x1f{occurrence}" if outcome_totals[normalized] > 1 else str(name)
+ values[key] = price
+ if refreshed.get("end_date") is not None:
+ values["end_date"] = refreshed["end_date"]
+
+ if datum_key == "end_date":
+ value = values.get("end_date")
+ else:
+ if "\x1f" in datum_key:
+ outcome_name, raw_occurrence = datum_key.rsplit("\x1f", 1)
+ occurrence = int(raw_occurrence)
+ else:
+ outcome_name, occurrence = datum_key, 0
+ matches = [
+ price
+ for name, price in refreshed.get("outcome_prices") or []
+ if str(name).casefold() == outcome_name.casefold()
+ ]
+ value = matches[occurrence] if occurrence < len(matches) else None
+ if value is None:
+ raise KeyError(f"Polymarket datum {datum_key!r} was not found")
+ return {
+ "value": value,
+ "values": values,
+ "url": str(getattr(item, "url", "")),
+ "timestamp": event.get("updatedAt"),
+ }
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index a30b0f6b..01d93fd7 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -272,11 +272,58 @@ def _render_ranked_clusters(
candidate = candidate_by_id.get(candidate_id)
if not candidate:
continue
- lines.extend(_render_candidate(candidate, prefix=f"{rep_index}."))
+ lines.extend(_render_candidate(candidate, prefix=f"{rep_index}.", report=report))
lines.append("")
return lines
+_FRESHNESS_PRIORITY = {
+ "contradicted": 0,
+ "stale": 1,
+ "unsupported": 2,
+ "current": 3,
+}
+
+
+def _candidate_freshness_flag(report: schema.Report, candidate_id: str) -> str:
+ states = {
+ verdict.verdict
+ for verdict in report.freshness_verdicts
+ if verdict.candidate_id == candidate_id
+ }
+ if not states:
+ return ""
+ ordered = sorted(states, key=lambda state: _FRESHNESS_PRIORITY[state])
+ return " [freshness:" + ",".join(ordered) + "]"
+
+
+def _render_freshness_verdicts(report: schema.Report) -> list[str]:
+ if not report.freshness_verdicts:
+ return []
+ lines = [
+ "## Freshness Verification",
+ "",
+ "| Verdict | Claim | Evidence | Checked |",
+ "| --- | --- | --- | --- |",
+ ]
+ for verdict in report.freshness_verdicts:
+ claim = verdict.claim.replace("|", "\\|")
+ if verdict.detail:
+ # The verifier's detail carries the formatted movement for stale
+ # rows and the reason a claim could not be re-checked otherwise.
+ claim += f" ({verdict.detail.replace('|', chr(92) + '|')})"
+ evidence_label = verdict.evidence_timestamp or verdict.source_timestamp or "source"
+ evidence = (
+ f"[{evidence_label}]({verdict.evidence_url})"
+ if verdict.evidence_url
+ else evidence_label
+ )
+ lines.append(
+ f"| **{verdict.verdict}** | {claim} | {evidence} | {verdict.checked_at} |"
+ )
+ return lines
+
+
def _clusters_for_register(
report: schema.Report,
audience: registers.AudienceRegister,
@@ -449,6 +496,11 @@ def render_compact(
lines.append("")
lines.append("<!-- END EVIDENCE FOR SYNTHESIS -->")
+ freshness_verdicts = _render_freshness_verdicts(report)
+ if freshness_verdicts:
+ lines.append("")
+ lines.extend(freshness_verdicts)
+
pre_research_warning = _render_pre_research_warning(report)
if pre_research_warning:
lines.append("")
@@ -519,6 +571,9 @@ def render_for_html(
include_source_diagnostics=False,
),
])
+ freshness_verdicts = _render_freshness_verdicts(report)
+ if freshness_verdicts:
+ lines.extend(["", *freshness_verdicts])
# Data quality warnings are NOT rendered into the HTML artifact. The HTML
# is meant to be shared (Slack, email, Notion); recipients haven't asked
# for technical commentary about how the run was produced. Generators see
@@ -554,6 +609,10 @@ def render_for_html_comparison(
]
if synthesis_md:
lines.extend(["", synthesis_md.strip()])
+ for label, report in entity_reports:
+ freshness_verdicts = _render_freshness_verdicts(report)
+ if freshness_verdicts:
+ lines.extend(["", f"## {label}", "", *freshness_verdicts])
# Comparison data quality notes also go to stderr, not into the artifact.
_append_html_footer(lines, main_report, save_path)
return "\n".join(lines).strip() + "\n"
@@ -964,6 +1023,11 @@ def render_comparison_multi(
lines.append("<!-- END EVIDENCE FOR SYNTHESIS -->")
lines.append("")
+ for label, report in entity_reports:
+ freshness_verdicts = _render_freshness_verdicts(report)
+ if freshness_verdicts:
+ lines.extend([f"## {label}", "", *freshness_verdicts, ""])
+
# Reuse the existing comparison scaffold by feeding it the synthesized
# topic. _parse_comparison_entities splits on " vs " so the scaffold
# picks up all N entities automatically.
@@ -1059,7 +1123,7 @@ def _render_entity_evidence_block(
candidate = candidate_by_id.get(candidate_id)
if not candidate:
continue
- out.extend(_render_candidate(candidate, prefix=f"{rep_index}."))
+ out.extend(_render_candidate(candidate, prefix=f"{rep_index}.", report=report))
out.append("")
best_takes = _render_best_takes(
@@ -1158,7 +1222,7 @@ def render_full(report: schema.Report) -> str:
candidate = candidate_by_id.get(cid)
if not candidate:
continue
- lines.extend(_render_candidate(candidate, prefix=f"{rep_index}."))
+ lines.extend(_render_candidate(candidate, prefix=f"{rep_index}.", report=report))
lines.append("")
fun_params = _FUN_LEVELS["medium"]
@@ -1244,6 +1308,10 @@ def render_full(report: schema.Report) -> str:
lines.append(f" Closes: {end_date}")
lines.append("")
+ freshness_verdicts = _render_freshness_verdicts(report)
+ if freshness_verdicts:
+ lines.extend(freshness_verdicts)
+ lines.append("")
lines.extend(_render_stats(report))
lines.extend(_render_source_coverage(report))
return "\n".join(lines).strip() + "\n"
@@ -1301,6 +1369,12 @@ def render_context(report: schema.Report, cluster_limit: int = 6) -> str:
if report.warnings:
lines.append("Warnings:")
lines.extend(f"- {warning}" for warning in report.warnings)
+ if report.freshness_verdicts:
+ lines.append("Freshness verdicts:")
+ lines.extend(
+ f"- {verdict.verdict}: {verdict.claim} ({verdict.evidence_url or verdict.source_url})"
+ for verdict in report.freshness_verdicts
+ )
return "\n".join(lines).strip() + "\n"
@@ -1400,6 +1474,11 @@ def render_brief(report: schema.Report, cluster_limit: int = 8) -> str:
lines.append(f"- **{cluster.title}**: {source_tags}")
lines.append("")
+ freshness_verdicts = _render_freshness_verdicts(report)
+ if freshness_verdicts:
+ lines.extend(freshness_verdicts)
+ lines.append("")
+
return "\n".join(lines).strip() + "\n"
@@ -1484,7 +1563,11 @@ def _render_hiring_signals(report: schema.Report) -> list[str]:
return out
-def _render_candidate(candidate: schema.Candidate, prefix: str) -> list[str]:
+def _render_candidate(
+ candidate: schema.Candidate,
+ prefix: str,
+ report: schema.Report | None = None,
+) -> list[str]:
primary = schema.candidate_primary_item(candidate)
detail_parts = [
_format_date(primary),
@@ -1502,7 +1585,8 @@ def _render_candidate(candidate: schema.Candidate, prefix: str) -> list[str]:
detail_parts.append("interaction:→@" + ",@".join(interaction_targets[:2]))
details = " | ".join(part for part in detail_parts if part)
lines = [
- f"{prefix} [{schema.candidate_source_label(candidate)}] {candidate.title}",
+ f"{prefix} [{schema.candidate_source_label(candidate)}] {candidate.title}"
+ + (_candidate_freshness_flag(report, candidate.candidate_id) if report else ""),
f" - {details}",
f" - URL: {candidate.url}",
]
diff --git a/skills/last30days/scripts/lib/schema.py b/skills/last30days/scripts/lib/schema.py
index 07efdf35..d3425cd2 100644
--- a/skills/last30days/scripts/lib/schema.py
+++ b/skills/last30days/scripts/lib/schema.py
@@ -155,6 +155,13 @@ RunOutcomeState = Literal[
"error",
]
+FreshnessVerdictState = Literal[
+ "current",
+ "stale",
+ "contradicted",
+ "unsupported",
+]
+
NO_RESULTS = health.NO_RESULTS
PARTIAL = health.PARTIAL
RATE_LIMITED = health.RATE_LIMITED
@@ -205,6 +212,26 @@ class SourceOutcome:
raise ValueError("items_returned cannot be negative")
+@dataclass(frozen=True)
+class FreshnessVerdict:
+ """Act-time verification result for one source-grounded claim."""
+
+ claim_id: str
+ candidate_id: str
+ claim: str
+ source: str
+ source_item_id: str
+ verdict: FreshnessVerdictState
+ checked_at: str
+ source_url: str = ""
+ source_timestamp: str | None = None
+ evidence_url: str = ""
+ evidence_timestamp: str | None = None
+ original_value: Any = None
+ current_value: Any = None
+ detail: str | None = None
+
+
@dataclass(frozen=True)
class LibraryContext:
"""One prior research run relevant to the current report."""
@@ -231,6 +258,7 @@ class Report:
items_by_source: dict[str, list[SourceItem]]
errors_by_source: dict[str, str]
source_status: dict[str, SourceOutcome] = field(default_factory=dict)
+ freshness_verdicts: list[FreshnessVerdict] = field(default_factory=list)
warnings: list[str] = field(default_factory=list)
artifacts: dict[str, Any] = field(default_factory=dict)
library_context: list[LibraryContext] = field(default_factory=list)
@@ -463,6 +491,26 @@ def report_from_dict(payload: dict[str, Any]) -> Report:
)
for source, outcome in (payload.get("source_status") or {}).items()
},
+ freshness_verdicts=[
+ FreshnessVerdict(
+ claim_id=item["claim_id"],
+ candidate_id=item["candidate_id"],
+ claim=item["claim"],
+ source=item["source"],
+ source_item_id=item["source_item_id"],
+ verdict=item["verdict"],
+ checked_at=item["checked_at"],
+ source_url=item.get("source_url") or "",
+ source_timestamp=item.get("source_timestamp"),
+ evidence_url=item.get("evidence_url") or "",
+ evidence_timestamp=item.get("evidence_timestamp"),
+ original_value=item.get("original_value"),
+ current_value=item.get("current_value"),
+ detail=item.get("detail"),
+ )
+ for item in (payload.get("freshness_verdicts") or [])
+ if isinstance(item, dict)
+ ],
warnings=list(payload.get("warnings") or []),
artifacts=dict(payload.get("artifacts") or {}),
library_context=[
@@ -509,7 +557,7 @@ def candidate_primary_item(candidate: Candidate) -> SourceItem | None:
return candidate.source_items[0]
-AGENT_EXPORT_SCHEMA_VERSION = "1.0"
+AGENT_EXPORT_SCHEMA_VERSION = "1.2"
DISCOVERY_EXPORT_SCHEMA_VERSION = "1.0"
@@ -620,6 +668,7 @@ def to_agent_export(report: Report) -> dict[str, Any]:
results.append(
_drop_none(
{
+ "candidate_id": candidate.candidate_id,
"title": candidate.title,
"source": candidate.source,
"url": candidate.url,
@@ -644,6 +693,9 @@ def to_agent_export(report: Report) -> dict[str, Any]:
source: outcome.state
for source, outcome in sorted(report.source_status.items())
},
+ "freshness_verdicts": [
+ _drop_none(asdict(verdict)) for verdict in report.freshness_verdicts
+ ],
"clusters": exported_clusters,
"results": results,
}
diff --git a/skills/last30days/scripts/lib/stocktwits.py b/skills/last30days/scripts/lib/stocktwits.py
index 71c3cc2d..05738990 100644
--- a/skills/last30days/scripts/lib/stocktwits.py
+++ b/skills/last30days/scripts/lib/stocktwits.py
@@ -196,11 +196,30 @@ def search_stocktwits(
time.sleep(0.8) # be polite to the unauth quota
except Exception as e: # noqa: BLE001
_log(f"stream fetch failed for {symbol}: {e}")
- return {"messages": messages, "symbols": symbols, "error": str(e)}
+ messages = _filter_by_date(messages, from_date, to_date)
+ return {
+ "messages": messages,
+ "symbols": symbols,
+ "error": str(e),
+ "freshness_window": {
+ "depth": depth,
+ "from_date": from_date,
+ "to_date": to_date,
+ },
+ }
messages = _filter_by_date(messages, from_date, to_date)
_log(f"{symbol}: {len(messages)} messages (watchlist {watchlist})")
- return {"messages": messages, "symbols": symbols, "watchlist": watchlist}
+ return {
+ "messages": messages,
+ "symbols": symbols,
+ "watchlist": watchlist,
+ "freshness_window": {
+ "depth": depth,
+ "from_date": from_date,
+ "to_date": to_date,
+ },
+ }
def _filter_by_date(messages: list[dict], from_date: str | None, to_date: str | None) -> list[dict]:
@@ -255,6 +274,7 @@ def parse_stocktwits_response(response: dict[str, Any], query: str = "") -> list
"symbol": symbols[0] if symbols else None,
"sentiment_aggregate": agg, # same dict on every item; cheap, lets synthesis cite it
"watchlist": response.get("watchlist"),
+ "freshness_window": response.get("freshness_window"),
},
})
return items
@@ -279,6 +299,57 @@ def aggregate_sentiment(messages: list[dict[str, Any]]) -> dict[str, Any]:
}
+def refetch_datum(item: Any, datum_key: str) -> dict[str, Any]:
+ """Re-fetch the same paginated, date-filtered symbol-stream population."""
+ from . import http
+
+ if datum_key != "pct_bullish":
+ raise KeyError(f"Unsupported StockTwits datum: {datum_key}")
+ symbol = str(item.metadata.get("symbol") or item.container or "").strip().upper()
+ if not symbol:
+ raise ValueError("StockTwits item has no symbol")
+ url = _STREAM_URL.format(symbol=urllib.parse.quote(symbol))
+ window = item.metadata.get("freshness_window") or {}
+ depth = str(window.get("depth") or "default")
+ target = _DEPTH.get(depth, _DEPTH["default"])
+ messages: list[dict[str, Any]] = []
+ cursor_max = None
+ while len(messages) < target:
+ request_kwargs: dict[str, Any] = {"timeout": 10, "retries": 2}
+ if cursor_max:
+ request_kwargs["params"] = {"max": cursor_max}
+ data = http.request("GET", url, **request_kwargs)
+ if not isinstance(data, dict) or not isinstance(data.get("messages"), list):
+ raise KeyError("StockTwits symbol stream was not returned")
+ batch = data["messages"]
+ if not batch:
+ break
+ messages.extend(batch)
+ cursor = data.get("cursor") or {}
+ if not cursor.get("more") or not cursor.get("max"):
+ break
+ cursor_max = cursor["max"]
+ messages = _filter_by_date(
+ messages,
+ window.get("from_date"),
+ window.get("to_date"),
+ )
+ aggregate = aggregate_sentiment(messages)
+ value = aggregate.get("pct_bullish")
+ if value is None:
+ raise KeyError("StockTwits stream has no tagged sentiment")
+ newest = max(
+ (str(message.get("created_at") or "") for message in messages),
+ default="",
+ )
+ return {
+ "value": value,
+ "values": {"pct_bullish": value},
+ "url": item.url,
+ "timestamp": newest or None,
+ }
+
+
# --------------------------------------------------------------------------- #
# Standalone CLI (ad-hoc use today, before any engine wiring) #
# python3 stocktwits.py "ServiceNow stock" #
diff --git a/tests/fixtures/agent_export_v1.json b/tests/fixtures/agent_export_v1.json
index 4ad5b276..e2d33738 100644
--- a/tests/fixtures/agent_export_v1.json
+++ b/tests/fixtures/agent_export_v1.json
@@ -1,5 +1,5 @@
{
- "schema_version": "1.0",
+ "schema_version": "1.2",
"query": "AI coding agents",
"generated_at": "2026-07-10T00:00:00Z",
"window_days": 30,
@@ -12,6 +12,7 @@
"x": "ok",
"youtube": "rate-limited"
},
+ "freshness_verdicts": [],
"clusters": [
{
"title": "Agents move into daily coding workflows",
@@ -40,6 +41,7 @@
],
"results": [
{
+ "candidate_id": "candidate-reddit",
"title": "Agents move into daily coding workflows",
"source": "reddit",
"url": "https://www.reddit.com/r/programming/comments/agent-workflows",
@@ -53,6 +55,7 @@
"cluster": 0
},
{
+ "candidate_id": "candidate-x",
"title": "Teams compare coding-agent review loops",
"source": "x",
"url": "https://x.com/example/status/123",
@@ -66,6 +69,7 @@
"cluster": 1
},
{
+ "candidate_id": "candidate-digg",
"title": "Agents climb the Digg AI leaderboard",
"source": "digg",
"url": "https://di.gg/ai/agent-leaderboard",
diff --git a/tests/test_agent_export.py b/tests/test_agent_export.py
index 4de1f1fb..acd38c38 100644
--- a/tests/test_agent_export.py
+++ b/tests/test_agent_export.py
@@ -162,7 +162,7 @@ def _report() -> schema.Report:
)
-def test_agent_export_matches_v1_golden_contract():
+def test_agent_export_matches_v1_2_golden_contract():
expected = json.loads(GOLDEN.read_text(encoding="utf-8"))
assert schema.to_agent_export(_report()) == expected
diff --git a/tests/test_cli_v3.py b/tests/test_cli_v3.py
index b153b6c7..037de7c0 100644
--- a/tests/test_cli_v3.py
+++ b/tests/test_cli_v3.py
@@ -62,7 +62,7 @@ class CliV3Tests(unittest.TestCase):
)
self.assertEqual(0, result.returncode, result.stderr)
payload = json.loads(result.stdout)
- self.assertEqual("1.0", payload["schema_version"])
+ self.assertEqual("1.2", payload["schema_version"])
self.assertEqual("test topic", payload["query"])
self.assertIn("results", payload)
self.assertIn("clusters", payload)
diff --git a/tests/test_freshness.py b/tests/test_freshness.py
new file mode 100644
index 00000000..480a86e6
--- /dev/null
+++ b/tests/test_freshness.py
@@ -0,0 +1,1130 @@
+import json
+
+import last30days as cli
+from lib import freshness, github, health, hosted, http, planner, polymarket, render, schema, stocktwits
+
+
+def _report(*items: schema.SourceItem) -> schema.Report:
+ candidates = []
+ for index, item in enumerate(items, start=1):
+ candidates.append(
+ schema.Candidate(
+ candidate_id=f"candidate-{index}",
+ item_id=item.item_id,
+ source=item.source,
+ title=item.title,
+ url=item.url,
+ snippet=item.snippet,
+ subquery_labels=["primary"],
+ native_ranks={f"primary:{item.source}": index},
+ local_relevance=0.9,
+ freshness=90,
+ engagement=10,
+ source_quality=0.8,
+ rrf_score=0.02,
+ final_score=90,
+ source_items=[item],
+ )
+ )
+ return schema.Report(
+ topic="freshness fixture",
+ range_from="2026-06-10",
+ range_to="2026-07-10",
+ generated_at="2026-07-10T12:00:00Z",
+ provider_runtime=schema.ProviderRuntime(
+ reasoning_provider="local",
+ planner_model="fixture",
+ rerank_model="fixture",
+ ),
+ query_plan=schema.QueryPlan(
+ intent="research",
+ freshness_mode="strict_recent",
+ cluster_mode="story",
+ raw_topic="freshness fixture",
+ subqueries=[
+ schema.SubQuery(
+ label="primary",
+ search_query="freshness fixture",
+ ranking_query="freshness fixture",
+ sources=[item.source for item in items] or ["reddit"],
+ )
+ ],
+ source_weights={item.source: 1.0 for item in items},
+ ),
+ clusters=[],
+ ranked_candidates=candidates,
+ items_by_source={
+ source: [item for item in items if item.source == source]
+ for source in {item.source for item in items}
+ },
+ errors_by_source={},
+ source_status={
+ source: schema.SourceOutcome(source=source, state=health.OK, items_returned=1)
+ for source in {item.source for item in items}
+ },
+ )
+
+
+def _item(source: str, *, title: str, snippet: str = "", **kwargs) -> schema.SourceItem:
+ return schema.SourceItem(
+ item_id=kwargs.pop("item_id", f"{source}-1"),
+ source=source,
+ title=title,
+ body=kwargs.pop("body", snippet),
+ url=kwargs.pop("url", f"https://example.com/{source}/1"),
+ published_at=kwargs.pop("published_at", "2026-07-09T12:00:00Z"),
+ snippet=snippet,
+ **kwargs,
+ )
+
+
+def test_extract_claims_is_conservative_and_structurally_grounded():
+ prose = _item(
+ "reddit",
+ title="10 ways teams discussed a launch",
+ snippet="The post has 2,000 votes and mentions 2026-08-01 in passing.",
+ )
+ market = _item(
+ "polymarket",
+ title="Will the bill pass?",
+ metadata={
+ "event_id": "123",
+ "outcome_prices": [["Yes", 0.42], ["No", 0.58]],
+ "end_date": "2026-11-03",
+ },
+ )
+
+ claims = freshness.extract_claims(_report(prose, market))
+
+ assert [claim.datum_kind for claim in claims] == [
+ "polymarket_probability",
+ "polymarket_probability",
+ "polymarket_end_date",
+ ]
+ assert all(claim.source_item_id == market.item_id for claim in claims)
+
+
+def test_verify_report_assigns_current_and_stale_for_each_point_source():
+ market = _item(
+ "polymarket",
+ title="Will the bill pass?",
+ metadata={"outcome_prices": [["Yes", 0.42]], "end_date": "2026-11-03"},
+ )
+ github = _item(
+ "github",
+ title="owner/repo (1K stars)",
+ url="https://github.com/owner/repo",
+ container="owner/repo",
+ engagement={"stars": 1000},
+ )
+ stocktwits = _item(
+ "stocktwits",
+ title="$ACME traders debate earnings",
+ container="ACME",
+ metadata={
+ "symbol": "ACME",
+ "sentiment_aggregate": {"pct_bullish": 60},
+ },
+ )
+ report = _report(market, github, stocktwits)
+
+ verdicts = freshness.verify_report(
+ report,
+ checked_at="2026-07-10T13:00:00Z",
+ refetchers={
+ "polymarket": lambda _item, key: {
+ "value": 0.47 if key == "Yes" else "2026-11-03",
+ "values": {"Yes": 0.47, "end_date": "2026-11-03"},
+ "url": "https://polymarket.com/event/bill",
+ "timestamp": "2026-07-10T12:59:00Z",
+ },
+ "github": lambda _item, _key: {"value": 1000, "url": _item.url},
+ "stocktwits": lambda _item, _key: {"value": 55, "url": _item.url},
+ },
+ )
+
+ by_kind = {claim.datum_kind: claim for claim in freshness.extract_claims(report)}
+ by_id = {verdict.claim_id: verdict for verdict in verdicts}
+ assert by_id[by_kind["polymarket_probability"].claim_id].verdict == "stale"
+ assert by_id[by_kind["polymarket_end_date"].claim_id].verdict == "current"
+ assert by_id[by_kind["github_stars"].claim_id].verdict == "current"
+ stock_verdict = by_id[by_kind["stocktwits_bullish_pct"].claim_id]
+ assert stock_verdict.verdict == "stale"
+ assert stock_verdict.original_value == 60
+ assert stock_verdict.current_value == 55
+ assert report.freshness_verdicts == verdicts
+
+
+def test_duplicate_polymarket_labels_keep_distinct_refetch_identity():
+ market = _item(
+ "polymarket",
+ title="What price will Bitcoin hit?",
+ metadata={"outcome_prices": [["Bitcoin", 0.86], ["Bitcoin", 0.75]]},
+ )
+ report = _report(market)
+
+ claims = freshness.extract_claims(report)
+ verdicts = freshness.verify_report(
+ report,
+ refetchers={
+ "polymarket": lambda _item, key: {
+ "value": [0.86, 0.75][int(key.rsplit("\x1f", 1)[1])],
+ "values": {"Bitcoin\x1f0": 0.86, "Bitcoin\x1f1": 0.75},
+ "url": _item.url,
+ }
+ },
+ )
+
+ assert len({claim.datum_key for claim in claims}) == 2
+ assert [verdict.verdict for verdict in verdicts] == ["current", "current"]
+
+
+def test_source_refetch_helpers_use_shared_http_wrapper(monkeypatch):
+ github_item = _item(
+ "github",
+ title="owner/repo",
+ url="https://github.com/owner/repo",
+ container="owner/repo",
+ )
+ monkeypatch.setattr(github.env, "read_secret_env", lambda _key: None)
+ monkeypatch.setattr(
+ github.http,
+ "request",
+ lambda *_args, **_kwargs: {
+ "stargazers_count": 123,
+ "html_url": github_item.url,
+ "updated_at": "2026-07-10T12:00:00Z",
+ },
+ )
+ assert github.refetch_datum(github_item, "stars")["value"] == 123
+
+ market_item = _item(
+ "polymarket",
+ title="Market",
+ url="https://polymarket.com/event/market-slug",
+ metadata={"event_id": "42"},
+ )
+ monkeypatch.setattr(
+ polymarket.http,
+ "request",
+ lambda *_args, **_kwargs: {"id": "42", "updatedAt": "2026-07-10T12:00:00Z"},
+ )
+ monkeypatch.setattr(
+ polymarket,
+ "parse_polymarket_response",
+ lambda _payload, **_kwargs: [{"outcome_prices": [["Yes", 0.51]], "end_date": "2026-12-01"}],
+ )
+ assert polymarket.refetch_datum(market_item, "Yes")["value"] == 0.51
+
+ stock_item = _item(
+ "stocktwits",
+ title="$ACME",
+ metadata={"symbol": "ACME"},
+ )
+ monkeypatch.setattr(
+ http,
+ "request",
+ lambda *_args, **_kwargs: {
+ "messages": [
+ {
+ "created_at": "2026-07-10T12:00:00Z",
+ "entities": {"sentiment": {"basic": "Bullish"}},
+ }
+ ]
+ },
+ )
+ assert stocktwits.refetch_datum(stock_item, "pct_bullish")["value"] == 100
+
+
+def test_source_item_lookup_is_scoped_by_source_when_ids_collide():
+ github_item = _item(
+ "github",
+ item_id="42",
+ title="owner/repo",
+ url="https://github.com/owner/repo",
+ container="owner/repo",
+ engagement={"stars": 10},
+ )
+ market_item = _item(
+ "polymarket",
+ item_id="42",
+ title="Will it pass?",
+ metadata={"outcome_prices": [["Yes", 0.5]]},
+ )
+ report = _report(github_item, market_item)
+
+ verdicts = freshness.verify_report(
+ report,
+ refetchers={
+ "github": lambda item, _key: {"value": item.engagement["stars"], "url": item.url},
+ "polymarket": lambda item, _key: {
+ "value": item.metadata["outcome_prices"][0][1],
+ "url": item.url,
+ },
+ },
+ )
+
+ assert [verdict.verdict for verdict in verdicts] == ["current", "current"]
+
+
+def test_degraded_source_is_unsupported_not_stale():
+ github = _item(
+ "github",
+ title="owner/repo (1K stars)",
+ url="https://github.com/owner/repo",
+ container="owner/repo",
+ engagement={"stars": 1000},
+ )
+ report = _report(github)
+ report.source_status["github"] = schema.SourceOutcome(
+ source="github", state=schema.UNREACHABLE,
+ )
+ called = False
+
+ def refetcher(_item, _key):
+ nonlocal called
+ called = True
+ return 999
+
+ verdict = freshness.verify_report(report, refetchers={"github": refetcher})[0]
+
+ assert verdict.verdict == "unsupported"
+ assert "unreachable" in (verdict.detail or "")
+ assert called is False
+
+
+def test_newer_in_report_status_disagreement_is_contradicted():
+ original = _item(
+ "reddit",
+ title="Widget API is open",
+ published_at="2026-07-08T10:00:00Z",
+ )
+ report = _report(original)
+ contradiction = _item(
+ "grounding",
+ item_id="web-2",
+ title="Widget API is closed",
+ published_at="2026-07-09T10:00:00Z",
+ url="https://status.example.com/widget",
+ )
+ report.items_by_source["grounding"] = [contradiction]
+
+ verdict = freshness.verify_report(report)[0]
+
+ assert verdict.verdict == "contradicted"
+ assert verdict.current_value == "closed"
+ assert verdict.evidence_url == contradiction.url
+ assert verdict.evidence_timestamp == contradiction.published_at
+
+
+def test_status_assertion_without_positive_rederivation_is_unsupported():
+ report = _report(_item("reddit", title="Widget API is open"))
+
+ verdict = freshness.verify_report(report)[0]
+
+ assert verdict.verdict == "unsupported"
+ assert "re-derived" in (verdict.detail or "")
+
+
+def test_status_contradiction_requires_subject_bound_to_opposite_status():
+ original = _item(
+ "reddit",
+ title="Widget API is open",
+ published_at="2026-07-08T10:00:00Z",
+ )
+ report = _report(original)
+ report.items_by_source["grounding"] = [
+ _item(
+ "grounding",
+ item_id="web-2",
+ title="Widget API remains open while legacy access is closed",
+ published_at="2026-07-09T10:00:00Z",
+ )
+ ]
+
+ verdict = freshness.verify_report(report)[0]
+
+ assert verdict.verdict == "unsupported"
+
+
+def test_verify_report_caches_one_point_refetch_per_source_key():
+ first = _item(
+ "stocktwits",
+ item_id="stock-1",
+ title="$ACME first post",
+ metadata={"symbol": "ACME", "sentiment_aggregate": {"pct_bullish": 60}},
+ )
+ second = _item(
+ "stocktwits",
+ item_id="stock-2",
+ title="$ACME second post",
+ metadata={"symbol": "ACME", "sentiment_aggregate": {"pct_bullish": 60}},
+ )
+ calls = []
+
+ verdicts = freshness.verify_report(
+ _report(first, second),
+ refetchers={
+ "stocktwits": lambda item, key: calls.append((item, key)) or {
+ "value": 60,
+ "url": item.url,
+ }
+ },
+ )
+
+ assert [verdict.verdict for verdict in verdicts] == ["current", "current"]
+ assert len(calls) == 1
+
+
+def test_stocktwits_refetch_cache_separates_depth_and_date_populations():
+ default = _item(
+ "stocktwits",
+ item_id="stock-default",
+ title="$ACME default population",
+ metadata={
+ "symbol": "ACME",
+ "sentiment_aggregate": {"pct_bullish": 60},
+ "freshness_window": {
+ "depth": "default",
+ "from_date": "2026-07-01",
+ "to_date": "2026-07-10",
+ },
+ },
+ )
+ deep = _item(
+ "stocktwits",
+ item_id="stock-deep",
+ title="$ACME deep population",
+ metadata={
+ "symbol": "ACME",
+ "sentiment_aggregate": {"pct_bullish": 75},
+ "freshness_window": {
+ "depth": "deep",
+ "from_date": "2026-06-10",
+ "to_date": "2026-07-10",
+ },
+ },
+ )
+ calls = []
+
+ verdicts = freshness.verify_report(
+ _report(default, deep),
+ refetchers={
+ "stocktwits": lambda item, _key: calls.append(item.item_id) or {
+ "value": item.metadata["sentiment_aggregate"]["pct_bullish"],
+ "url": item.url,
+ }
+ },
+ )
+
+ assert [verdict.verdict for verdict in verdicts] == ["current", "current"]
+ assert calls == ["stock-default", "stock-deep"]
+
+
+def test_stocktwits_refetch_reuses_retrieval_depth_and_date_window(monkeypatch):
+ item = _item(
+ "stocktwits",
+ title="$ACME",
+ metadata={
+ "symbol": "ACME",
+ "freshness_window": {
+ "depth": "deep",
+ "from_date": "2026-07-01",
+ "to_date": "2026-07-10",
+ },
+ },
+ )
+ calls = []
+
+ def fake_request(_method, _url, **kwargs):
+ calls.append(kwargs.get("params"))
+ if len(calls) == 1:
+ return {
+ "messages": [
+ {"id": 3, "created_at": "2026-07-10T12:00:00Z", "entities": {"sentiment": {"basic": "Bullish"}}},
+ {"id": 2, "created_at": "2026-06-30T12:00:00Z", "entities": {"sentiment": {"basic": "Bearish"}}},
+ ],
+ "cursor": {"more": True, "max": 2},
+ }
+ return {
+ "messages": [
+ {"id": 1, "created_at": "2026-07-09T12:00:00Z", "entities": {"sentiment": {"basic": "Bullish"}}},
+ ],
+ "cursor": {"more": False},
+ }
+
+ monkeypatch.setattr(http, "request", fake_request)
+
+ refreshed = stocktwits.refetch_datum(item, "pct_bullish")
+
+ assert refreshed["value"] == 100
+ assert calls == [None, {"max": 2}]
+
+
+def test_unverified_drill_clears_inherited_freshness_verdicts(tmp_path, monkeypatch):
+ cached = _report(_item("reddit", title="Widget API is open"))
+ freshness.verify_report(cached)
+ merged = _report(_item("reddit", title="Widget API is open"))
+ merged.freshness_verdicts = list(cached.freshness_verdicts)
+ drill_report = _report(_item("reddit", title="Widget API is closed"))
+ monkeypatch.setattr(cli, "_load_last_report_cache", lambda *_args, **_kwargs: (cached, None, tmp_path / "last-report.json"))
+ monkeypatch.setattr(planner, "resolve_drill_clusters", lambda *_args, **_kwargs: [])
+ monkeypatch.setattr(planner, "build_drill_plan", lambda *_args, **_kwargs: cached.query_plan)
+ monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: {})
+ monkeypatch.setattr(cli.pipeline, "run", lambda **_kwargs: drill_report)
+ monkeypatch.setattr(cli.pipeline, "merge_drill_report", lambda *_args, **_kwargs: merged)
+ monkeypatch.setattr(cli, "_show_runtime_ui", lambda *_args, **_kwargs: None)
+ monkeypatch.setattr(cli, "_write_last_run", lambda *_args, **_kwargs: True)
+ monkeypatch.setattr(cli, "_render_save_and_print", lambda *_args, **_kwargs: 0)
+ args = cli.build_parser().parse_args(["--drill", "cluster 1", "--mock"])
+
+ assert cli._run_drill(args, {}) == 0
+ assert merged.freshness_verdicts == []
+
+
+def test_polymarket_refetch_uses_complete_outcomes_and_one_event_snapshot(monkeypatch):
+ item = _item(
+ "polymarket",
+ title="Who will win?",
+ url="https://polymarket.com/event/winner",
+ metadata={
+ "event_id": "42",
+ "outcome_prices": [["Delta", 0.05]],
+ "end_date": "2026-12-01",
+ },
+ )
+ event = {
+ "id": "42",
+ "slug": "winner",
+ "title": "Who will win?",
+ "updatedAt": "2026-07-10T12:00:00Z",
+ "markets": [{
+ "active": True,
+ "closed": False,
+ "question": "Who will win?",
+ "liquidity": "100",
+ "outcomes": '["Alpha", "Beta", "Gamma", "Delta"]',
+ "outcomePrices": '["0.4", "0.3", "0.25", "0.05"]',
+ "endDate": "2026-12-01T00:00:00Z",
+ }],
+ }
+ calls = []
+ monkeypatch.setattr(
+ polymarket.http,
+ "request",
+ lambda *_args, **_kwargs: calls.append(1) or event,
+ )
+
+ verdicts = freshness.verify_report(_report(item))
+
+ assert [verdict.verdict for verdict in verdicts] == ["current", "current"]
+ assert len(calls) == 1
+
+
+def test_polymarket_refetch_marks_resolved_market_movement_stale(monkeypatch):
+ item = _item(
+ "polymarket",
+ title="Will the bill pass?",
+ url="https://polymarket.com/event/bill",
+ metadata={
+ "event_id": "42",
+ "outcome_prices": [["Yes", 0.42]],
+ },
+ )
+ monkeypatch.setattr(
+ polymarket.http,
+ "request",
+ lambda *_args, **_kwargs: {
+ "id": "42",
+ "slug": "bill",
+ "title": "Will the bill pass?",
+ "active": False,
+ "closed": True,
+ "markets": [{
+ "active": False,
+ "closed": True,
+ "question": "Will the bill pass?",
+ "liquidity": "0",
+ "outcomes": '["Yes", "No"]',
+ "outcomePrices": '["1", "0"]',
+ }],
+ },
+ )
+
+ verdict = freshness.verify_report(_report(item))[0]
+
+ assert verdict.verdict == "stale"
+ assert verdict.current_value == 1.0
+
+
+def test_github_refetch_reuses_resolved_gh_cli_token(monkeypatch):
+ item = _item(
+ "github",
+ title="owner/private",
+ url="https://github.com/owner/private",
+ container="owner/private",
+ )
+ seen_headers = []
+ monkeypatch.setattr(github, "_resolve_token", lambda: "gh-cli-token")
+ monkeypatch.setattr(
+ github.http,
+ "request",
+ lambda *_args, **kwargs: seen_headers.append(kwargs["headers"]) or {
+ "stargazers_count": 7,
+ "html_url": item.url,
+ },
+ )
+
+ github.refetch_datum(item, "stars")
+
+ assert seen_headers == [{
+ "Accept": "application/vnd.github+json",
+ "Authorization": "Bearer gh-cli-token",
+ }]
+
+
+def test_early_return_paths_do_not_ignore_freshness_verification(tmp_path, monkeypatch, capsys):
+ monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-key")
+ monkeypatch.setenv("LAST30DAYS_API_BASE", "https://api.example.test")
+ monkeypatch.setattr(cli.env, "get_config", lambda **_kwargs: {})
+ parser = cli.build_parser()
+ hosted_args = parser.parse_args(["topic", "--verify-freshness"])
+
+ assert cli._main(parser, hosted_args, []) == 2
+ assert "not supported by the hosted backend" in capsys.readouterr().err
+
+ monkeypatch.delenv("LAST30DAYS_API_KEY")
+ monkeypatch.delenv("LAST30DAYS_API_BASE")
+ monkeypatch.setenv("LAST30DAYS_SKIP_PREFLIGHT", "1")
+ synthesis = tmp_path / "synthesis.md"
+ synthesis.write_text("# Synthesis", encoding="utf-8")
+ report = _report(_item("reddit", title="Widget API is open"))
+ calls = []
+ monkeypatch.setattr(cli.pipeline, "diagnose", lambda *_args, **_kwargs: {})
+ monkeypatch.setattr(cli, "_load_last_report_cache", lambda *_args, **_kwargs: (report, None, tmp_path / "last-report.json"))
+ monkeypatch.setattr(cli, "_verify_report_set", lambda *_args, **_kwargs: calls.append("verified"))
+ monkeypatch.setattr(cli, "_render_save_and_print", lambda *_args, **_kwargs: calls.append("rendered") or 0)
+ cached_args = parser.parse_args([
+ "topic", "--emit=html", f"--synthesis-file={synthesis}", "--verify-freshness",
+ ])
+
+ assert cli._main(parser, cached_args, []) == 0
+ assert calls == ["verified", "rendered"]
+
+
+def test_hosted_configured_freshness_skips_unless_cli_explicitly_enables(monkeypatch, capsys):
+ monkeypatch.setenv("LAST30DAYS_API_KEY", "dummy-hosted-key")
+ monkeypatch.setenv("LAST30DAYS_API_BASE", "https://api.example.test")
+ monkeypatch.setattr(
+ cli.env,
+ "get_config",
+ lambda **_kwargs: {"LAST30DAYS_VERIFY_FRESHNESS": "on"},
+ )
+ calls = []
+ monkeypatch.setattr(
+ hosted,
+ "run_hosted",
+ lambda topic, depth, **_kwargs: calls.append((topic, depth)) or 0,
+ )
+ parser = cli.build_parser()
+
+ assert cli._main(parser, parser.parse_args(["topic"]), []) == 0
+ assert calls == [("topic", "default")]
+ assert capsys.readouterr().err == (
+ "hosted backend does not support freshness verification; skipping\n"
+ )
+ no_verify_args = parser.parse_args(["topic", "--no-verify-freshness"])
+ assert cli._freshness_enabled(
+ no_verify_args,
+ {"LAST30DAYS_VERIFY_FRESHNESS": "on"},
+ ) is False
+
+
+def test_agent_export_includes_typed_claim_metadata():
+ item = _item("reddit", title="Widget API is open")
+ report = _report(item)
+ freshness.verify_report(report, checked_at="2026-07-10T13:00:00Z")
+
+ exported = schema.to_agent_export(report)
+
+ assert exported["schema_version"] == "1.2"
+ assert exported["freshness_verdicts"][0]["verdict"] == "unsupported"
+ assert exported["freshness_verdicts"][0]["source_item_id"] == item.item_id
+
+
+def test_render_surfaces_inline_flag_and_freshness_footer_table():
+ item = _item(
+ "github",
+ title="owner/repo (1K stars)",
+ url="https://github.com/owner/repo",
+ container="owner/repo",
+ engagement={"stars": 1000},
+ )
+ report = _report(item)
+ report.clusters = [
+ schema.Cluster(
+ cluster_id="cluster-1",
+ title="Repository traction",
+ candidate_ids=["candidate-1"],
+ representative_ids=["candidate-1"],
+ sources=["github"],
+ score=90,
+ )
+ ]
+ report.ranked_candidates[0].cluster_id = "cluster-1"
+ freshness.verify_report(
+ report,
+ checked_at="2026-07-10T13:00:00Z",
+ refetchers={"github": lambda _item, _key: {"value": 1010, "url": _item.url}},
+ )
+
+ rendered = render.render_compact(report)
+
+ assert "[freshness:stale]" in rendered
+ assert "## Freshness Verification" in rendered
+ assert "(moved: 1,000 -> 1,010)" in rendered
+ assert "## Freshness Verification" in render.render_for_html(report)
+ assert "## Freshness Verification" in render.render_brief(report)
+
+
+def test_post_hoc_path_loads_updates_and_rewrites_cache(tmp_path, monkeypatch, capsys):
+ item = _item("reddit", title="Widget API is open")
+ report = _report(item)
+ monkeypatch.setattr(cli.env, "CONFIG_DIR", tmp_path)
+ assert cli._write_last_run(report.topic, report)
+ before = json.loads((tmp_path / "last-report.json").read_text(encoding="utf-8"))
+ args = cli.build_parser().parse_args(["--verify-freshness", "--mock", "--emit=json"])
+
+ rc = cli._run_cached_freshness(args, {})
+
+ assert rc == 0
+ payload = json.loads((tmp_path / "last-report.json").read_text(encoding="utf-8"))
+ cached_verdicts = payload["reports"][0]["report"]["freshness_verdicts"]
+ assert cached_verdicts[0]["verdict"] == "unsupported"
+ assert payload["timestamp"] == before["timestamp"]
+ assert "Updated freshness verdicts" in capsys.readouterr().err
+
+
+def test_opt_in_gating_accepts_flag_or_truthy_config():
+ parser = cli.build_parser()
+ default_args = parser.parse_args(["topic"])
+ flag_args = parser.parse_args(["topic", "--verify-freshness"])
+
+ assert cli._freshness_enabled(default_args, {}) is False
+ assert cli._freshness_enabled(default_args, {"LAST30DAYS_VERIFY_FRESHNESS": "on"}) is True
+ assert cli._freshness_enabled(flag_args, {}) is True
+
+
+def test_mixed_event_prefers_active_markets(monkeypatch):
+ from types import SimpleNamespace
+ from lib import polymarket
+
+ event = {
+ "id": "ev1",
+ "title": "Mixed event",
+ "active": True,
+ "markets": [
+ {"id": "m-closed", "active": False, "closed": True,
+ "question": "Old market", "volume": "900000",
+ "outcomePrices": '["0.99","0.01"]', "outcomes": '["Yes","No"]'},
+ {"id": "m-active", "active": True, "closed": False,
+ "question": "Live market", "volume": "1000",
+ "outcomePrices": '["0.60","0.40"]', "outcomes": '["Yes","No"]',
+ "liquidity": "5000"},
+ ],
+ }
+ captured = {}
+ real_parse = polymarket.parse_polymarket_response
+
+ def spy(payload, **kwargs):
+ captured.update(kwargs)
+ return real_parse(payload, **kwargs)
+
+ monkeypatch.setattr(polymarket, "parse_polymarket_response", spy)
+ monkeypatch.setattr(polymarket.http, "request", lambda *a, **k: [event])
+ item = SimpleNamespace(metadata={"event_id": "ev1"}, url="")
+ try:
+ polymarket.refetch_datum(item, "probability")
+ except Exception:
+ pass
+ assert captured.get("include_closed") is False
+
+ # Fully resolved event falls back to closed markets.
+ captured.clear()
+ resolved = dict(event)
+ resolved["markets"] = [dict(event["markets"][0])]
+ monkeypatch.setattr(polymarket.http, "request", lambda *a, **k: [resolved])
+ try:
+ polymarket.refetch_datum(item, "probability")
+ except Exception:
+ pass
+ assert captured.get("include_closed") is True
+
+
+def test_slug_refetch_requires_identity_match(monkeypatch):
+ from types import SimpleNamespace
+ import pytest
+ from lib import polymarket
+
+ wrong = {"id": "222", "slug": "different-market", "title": "Other",
+ "markets": [{"id": "m1", "active": True, "closed": False,
+ "question": "q", "volume": "10",
+ "outcomePrices": '["0.5","0.5"]', "outcomes": '["Yes","No"]',
+ "liquidity": "10"}]}
+ monkeypatch.setattr(polymarket.http, "request", lambda *a, **k: [wrong])
+ item = SimpleNamespace(
+ metadata={}, item_id="777",
+ url="https://polymarket.com/event/fed-rate-cut-2026",
+ )
+ with pytest.raises(KeyError):
+ polymarket.refetch_datum(item, "probability")
+
+ right = dict(wrong)
+ right["slug"] = "fed-rate-cut-2026"
+ right["id"] = "777"
+ monkeypatch.setattr(polymarket.http, "request", lambda *a, **k: [wrong, right])
+ values = polymarket.refetch_datum(item, "Yes")
+ assert values is not None
+
+
+def _stale_fixture_report() -> schema.Report:
+ market = _item(
+ "polymarket",
+ title="Will the bill pass?",
+ metadata={"outcome_prices": [["Yes", 0.42]]},
+ )
+ gh = _item(
+ "github",
+ title="owner/repo (1K stars)",
+ url="https://github.com/owner/repo",
+ container="owner/repo",
+ engagement={"stars": 1000},
+ )
+ stock = _item(
+ "stocktwits",
+ title="$ACME traders debate earnings",
+ container="ACME",
+ metadata={"symbol": "ACME", "sentiment_aggregate": {"pct_bullish": 60}},
+ )
+ return _report(market, gh, stock)
+
+
+def test_stale_detail_carries_original_and_current_values():
+ report = _stale_fixture_report()
+ verdicts = freshness.verify_report(
+ report,
+ checked_at="2026-07-10T13:00:00Z",
+ refetchers={
+ "polymarket": lambda _item, _key: {"value": 0.47, "url": _item.url},
+ "github": lambda _item, _key: {"value": 1200, "url": _item.url},
+ "stocktwits": lambda _item, _key: {"value": 55, "url": _item.url},
+ },
+ )
+
+ details = {verdict.source: verdict.detail for verdict in verdicts}
+ assert details["polymarket"] == "moved: 42% -> 47%"
+ assert details["github"] == "moved: 1,000 -> 1,200"
+ assert details["stocktwits"] == "moved: 60% -> 55%"
+
+
+def test_current_verdicts_keep_detail_none():
+ report = _stale_fixture_report()
+ verdicts = freshness.verify_report(
+ report,
+ checked_at="2026-07-10T13:00:00Z",
+ refetchers={
+ "polymarket": lambda _item, _key: {"value": 0.42, "url": _item.url},
+ "github": lambda _item, _key: {"value": 1000, "url": _item.url},
+ "stocktwits": lambda _item, _key: {"value": 60, "url": _item.url},
+ },
+ )
+
+ assert all(verdict.verdict == "current" for verdict in verdicts)
+ assert all(verdict.detail is None for verdict in verdicts)
+
+
+def test_agent_export_carries_enriched_stale_detail():
+ report = _stale_fixture_report()
+ freshness.verify_report(
+ report,
+ checked_at="2026-07-10T13:00:00Z",
+ refetchers={
+ "polymarket": lambda _item, _key: {"value": 0.47, "url": _item.url},
+ "github": lambda _item, _key: {"value": 1200, "url": _item.url},
+ "stocktwits": lambda _item, _key: {"value": 55, "url": _item.url},
+ },
+ )
+
+ exported = schema.to_agent_export(report)
+ stale = [v for v in exported["freshness_verdicts"] if v["verdict"] == "stale"]
+ assert stale and all(v["detail"].startswith("moved: ") for v in stale)
+
+
+def test_zero_claim_verification_notes_outcome_on_stderr(capsys):
+ prose_only = _report(_item("reddit", title="10 ways teams discussed a launch"))
+
+ cli._verify_report_set(prose_only, None, allow_network=False)
+
+ err = capsys.readouterr().err
+ assert "no re-checkable claims" in err
+ assert prose_only.freshness_verdicts == []
+
+
+def test_zero_claim_note_prints_once_across_entity_reports(capsys):
+ first = _report(_item("reddit", title="Thread one", item_id="reddit-a"))
+ second = _report(_item("reddit", title="Thread two", item_id="reddit-b"))
+
+ cli._verify_report_set(first, [("one", first), ("two", second)], allow_network=False)
+
+ err = capsys.readouterr().err
+ assert err.count("no re-checkable claims") == 1
+
+
+def test_zero_claim_note_absent_when_any_report_has_verdicts(capsys):
+ market = _report(
+ _item("polymarket", title="Will it?", metadata={"outcome_prices": [["Yes", 0.42]]})
+ )
+
+ cli._verify_report_set(market, None, allow_network=False)
+
+ err = capsys.readouterr().err
+ assert "no re-checkable claims" not in err
+ assert market.freshness_verdicts # unsupported verdicts still count as outcomes
+
+
+def _candidate_star_report(*, repos: dict[str, int], item_source: str = "reddit") -> schema.Report:
+ """A report whose only star facts live in candidate enrichment metadata."""
+ primary = _item(item_source, title="Agent tooling thread")
+ report = _report(primary)
+ report.ranked_candidates[0].metadata["github_stars"] = dict(repos)
+ return report
+
+
+def test_candidate_star_claims_dispatch_despite_non_github_primary_item():
+ """Regression: star facts attached during post-rerank enrichment carried
+ no claims because extraction read only item-level engagement, so a
+ GitHub-flavored run produced zero verdicts."""
+ report = _candidate_star_report(repos={"a/b": 100})
+
+ calls: list[tuple[object, str]] = []
+
+ def fake_refetch(item, key):
+ calls.append((item, key))
+ return {"value": 100, "url": f"https://github.com/{key}"}
+
+ verdicts = freshness.verify_report(
+ report,
+ checked_at="2026-07-11T13:00:00Z",
+ refetchers={"github": fake_refetch},
+ )
+
+ assert [verdict.verdict for verdict in verdicts] == ["current"]
+ assert calls == [(None, "a/b")]
+ assert verdicts[0].source == "github"
+ assert verdicts[0].source_url == "https://github.com/a/b"
+
+
+def test_candidate_star_claim_moved_value_is_stale_with_detail():
+ report = _candidate_star_report(repos={"a/b": 100})
+
+ verdicts = freshness.verify_report(
+ report,
+ checked_at="2026-07-11T13:00:00Z",
+ refetchers={"github": lambda _item, key: {"value": 250, "url": f"https://github.com/{key}"}},
+ )
+
+ assert [verdict.verdict for verdict in verdicts] == ["stale"]
+ assert verdicts[0].detail == "moved: 100 -> 250"
+ assert verdicts[0].original_value == 100
+ assert verdicts[0].current_value == 250
+
+
+def test_repo_claimed_at_item_level_is_not_claimed_again_from_metadata():
+ gh_item = _item(
+ "github",
+ title="a/b (100 stars)",
+ url="https://github.com/a/b",
+ container="a/b",
+ engagement={"stars": 100},
+ )
+ report = _report(gh_item)
+ report.ranked_candidates[0].metadata["github_stars"] = {"a/b": 100}
+
+ claims = [
+ claim for claim in freshness.extract_claims(report)
+ if claim.datum_kind == "github_stars"
+ ]
+
+ assert len(claims) == 1
+ assert claims[0].datum_key == "stars"
+
+
+def test_multiple_candidates_citing_same_repo_share_one_refetch():
+ first = _item("reddit", title="Thread one", item_id="reddit-a")
+ second = _item("reddit", title="Thread two", item_id="reddit-b")
+ report = _report(first, second)
+ for candidate in report.ranked_candidates:
+ candidate.metadata["github_stars"] = {"a/b": 100}
+
+ calls: list[str] = []
+
+ def fake_refetch(_item, key):
+ calls.append(key)
+ return {"value": 100, "url": f"https://github.com/{key}"}
+
+ verdicts = freshness.verify_report(
+ report,
+ checked_at="2026-07-11T13:00:00Z",
+ refetchers={"github": fake_refetch},
+ )
+
+ assert [verdict.verdict for verdict in verdicts] == ["current", "current"]
+ assert calls == ["a/b"]
+
+
+def test_candidate_star_claims_bypass_github_source_outcome_gate():
+ report = _candidate_star_report(repos={"a/b": 100})
+ report.source_status["github"] = schema.SourceOutcome(
+ source="github", state="timeout", items_returned=0,
+ )
+
+ verdicts = freshness.verify_report(
+ report,
+ checked_at="2026-07-11T13:00:00Z",
+ refetchers={"github": lambda _item, key: {"value": 100, "url": f"https://github.com/{key}"}},
+ )
+
+ assert [verdict.verdict for verdict in verdicts] == ["current"]
+
+
+def test_candidates_without_star_metadata_emit_no_claims():
+ report = _report(_item("reddit", title="Agent tooling thread"))
+
+ assert freshness.extract_claims(report) == []
+
+
+def test_refetch_datum_accepts_repo_slug_datum_key(monkeypatch):
+ seen_urls: list[str] = []
+ monkeypatch.setattr(github, "_resolve_token", lambda: "")
+ monkeypatch.setattr(
+ github.http,
+ "request",
+ lambda _method, url, **_kwargs: seen_urls.append(url) or {
+ "stargazers_count": 42,
+ "html_url": "https://github.com/a/b",
+ },
+ )
+
+ refreshed = github.refetch_datum(None, "a/b")
+
+ assert seen_urls == ["https://api.github.com/repos/a/b"]
+ assert refreshed["value"] == 42
+
+
+def test_unsupported_verdicts_carry_no_fabricated_evidence():
+ report = _report(_item("reddit", title="Widget API is open"))
+
+ verdicts = freshness.verify_report(report, checked_at="2026-07-11T13:00:00Z")
+
+ assert [verdict.verdict for verdict in verdicts] == ["unsupported"]
+ assert verdicts[0].evidence_url == ""
+ assert verdicts[0].evidence_timestamp is None
+ assert verdicts[0].source_url # provenance stays on the source fields
+
+
+def test_rendered_table_shows_unsupported_reason_from_detail():
+ report = _report(_item("reddit", title="Widget API is open"))
+ freshness.verify_report(report, checked_at="2026-07-11T13:00:00Z")
+
+ rendered = render.render_compact(report)
+
+ assert "(Status could not be positively re-derived from a current source)" in rendered
+
+
+def test_agent_export_results_expose_candidate_id_join_key():
+ report = _candidate_star_report(repos={"a/b": 100})
+ freshness.verify_report(
+ report,
+ checked_at="2026-07-11T13:00:00Z",
+ refetchers={"github": lambda _item, key: {"value": 100, "url": f"https://github.com/{key}"}},
+ )
+
+ exported = schema.to_agent_export(report)
+
+ result_ids = {result["candidate_id"] for result in exported["results"]}
+ verdict_ids = {verdict["candidate_id"] for verdict in exported["freshness_verdicts"]}
+ assert verdict_ids and verdict_ids <= result_ids
+
+
+def test_other_candidates_item_level_claim_does_not_suppress_enriched_claim():
+ gh_item = _item(
+ "github",
+ title="a/b (100 stars)",
+ url="https://github.com/a/b",
+ container="a/b",
+ engagement={"stars": 100},
+ )
+ reddit_item = _item("reddit", title="Thread about a/b", item_id="reddit-a")
+ report = _report(gh_item, reddit_item)
+ report.ranked_candidates[1].metadata["github_stars"] = {"a/b": 100}
+
+ calls: list[str] = []
+
+ def fake_refetch(_item, key):
+ calls.append(key)
+ return {"value": 100, "url": "https://github.com/a/b"}
+
+ verdicts = freshness.verify_report(
+ report,
+ checked_at="2026-07-11T13:00:00Z",
+ refetchers={"github": fake_refetch},
+ )
+
+ # Both candidates get their own verdict, sharing one repo snapshot.
+ assert [verdict.verdict for verdict in verdicts] == ["current", "current"]
+ assert {verdict.candidate_id for verdict in verdicts} == {"candidate-1", "candidate-2"}
+ assert calls == ["stars"]
+
+
+def test_slug_refetch_rejects_same_slug_different_event_id(monkeypatch):
+ from types import SimpleNamespace
+ import pytest
+ from lib import polymarket
+
+ recreated = {"id": "999", "slug": "fed-rate-cut-2026", "title": "Recreated",
+ "markets": [{"id": "m1", "active": True, "closed": False,
+ "question": "q", "volume": "10",
+ "outcomePrices": '["0.5","0.5"]', "outcomes": '["Yes","No"]',
+ "liquidity": "10"}]}
+ monkeypatch.setattr(polymarket.http, "request", lambda *a, **k: [recreated])
+ cached = SimpleNamespace(
+ metadata={}, item_id="123",
+ url="https://polymarket.com/event/fed-rate-cut-2026",
+ )
+ with pytest.raises(KeyError):
+ polymarket.refetch_datum(cached, "Yes")
+
+ original = dict(recreated)
+ original["id"] = "123"
+ monkeypatch.setattr(polymarket.http, "request", lambda *a, **k: [recreated, original])
+ assert polymarket.refetch_datum(cached, "Yes") is not None
+
+
+def test_slug_refetch_fails_closed_without_any_event_identity(monkeypatch):
+ """A synthetic PM<N> parse id carries no identity, so slug equality alone
+ must not verify a claim; the refetch fails closed to unsupported."""
+ from types import SimpleNamespace
+ import pytest
+ from lib import polymarket
+
+ calls: list[object] = []
+ monkeypatch.setattr(
+ polymarket.http, "request", lambda *a, **k: calls.append(a) or []
+ )
+ cached = SimpleNamespace(
+ metadata={}, item_id="PM3",
+ url="https://polymarket.com/event/fed-rate-cut-2026",
+ )
+ with pytest.raises(ValueError):
+ polymarket.refetch_datum(cached, "Yes")
+ assert calls == [] # fails closed before any network request
diff --git a/tests/test_render_comparison_multi.py b/tests/test_render_comparison_multi.py
index b5b6aca2..26fe1478 100644
--- a/tests/test_render_comparison_multi.py
+++ b/tests/test_render_comparison_multi.py
@@ -274,7 +274,7 @@ class EmitComparisonOutputTests(unittest.TestCase):
self.assertEqual(payload["entities"], ["OpenAI", "Anthropic"])
self.assertEqual(len(payload["reports"]), 2)
self.assertEqual(payload["reports"][0]["entity"], "OpenAI")
- self.assertEqual(payload["schema_version"], "1.0")
+ self.assertEqual(payload["schema_version"], "1.2")
self.assertIn("query", payload["reports"][0]["report"])
def test_compact_and_md_both_route_to_multi(self):